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.
C cdebiandesktop-environmentebpffirewalllandlocklinuxlinux-distributionopen-sourceprivacyquickjsraspberry-pi-5reactsecuritywaylandwayland-compositor
Checkpoint: translatable error codes and English default, Displays polish, mail apps polish, English pass 2, engine work in progress
Federico Pereira43881e649cc4
diff --git a/.gitignore b/.gitignoreindex 0d616c8..f0085b9 100644--- a/.gitignore+++ b/.gitignore@@ -14,3 +14,4 @@ assets/app-host.bundle.js.vscode/.idea/assets/sysapps/+assets/locales/*.tgzdiff --git a/apps/about/index.jsx b/apps/about/index.jsxindex b96f0f9..6a177d8 100644--- a/apps/about/index.jsx+++ b/apps/about/index.jsx@@ -34,7 +34,7 @@ export default function About() {<InfoRow k={tr('about.os')} v={info.os} /><InfoRow k={tr('about.kernel')} v={`${info.kernel} (${info.arch})`} /><InfoRow k={tr('about.host')} v={tr('about.hostValue', { host: info.hostname, user: info.user })} />- <InfoRow k={tr('about.cpu')} v={tr('about.cpuValue', { cpu: cpu.slice(0, 34), count: info.cores })} />+ <InfoRow k={tr('about.cpu')} v={tr('about.cpuValue', { cpu: cpu.slice(0, 34) || tr('about.cpuUnknown'), count: info.cores })} /><InfoRow k={tr('about.memory')} v={tr('shell.cc.memDetail', { used: formatBytes((info.memTotalKB - info.memAvailableKB) * 1024), total: formatBytes(info.memTotalKB * 1024) })} /><InfoRow k={tr('about.uptime')} v={formatDuration(info.uptime)} /><View style={{ height: 1, backgroundColor: t.separator, marginVertical: 8, marginHorizontal: 24 }} />diff --git a/apps/about/manifest.json b/apps/about/manifest.jsonindex 8eaf3f5..1fc9829 100644--- a/apps/about/manifest.json+++ b/apps/about/manifest.json@@ -1,7 +1,7 @@{"id": "about",- "name": "Acerca de LordOS",- "description": "Información del sistema y del servidor gráfico",+ "name": "About LordOS",+ "description": "System and graphics server information","size": [440,530diff --git a/apps/backup/index.jsx b/apps/backup/index.jsxindex ee05c89..ec99b08 100644--- a/apps/backup/index.jsx+++ b/apps/backup/index.jsx@@ -4,7 +4,7 @@// schedule and exclusions, shows progress, and lets you browse backups by date and restore a// file, a folder or everything.import {- View, Text, ScrollView, Segmented, Toggle, Button, TextInput, useTheme, useBackup, backup, fs, wm, t as tr, tOptional,+ View, Text, ScrollView, Segmented, Toggle, Button, TextInput, useTheme, useBackup, backup, fs, wm, t as tr, errorText,formatBytes, formatDate, formatTime, formatNumber, direction,Toolbar, ToolbarButton, ToolbarSpacer, MenuButton, SidebarItem, SectionTitle, EmptyState, GroupBox, FormRow, Hairline, spacing, typeScale,} from '@lordos/sdk';@@ -37,8 +37,8 @@ const when = (sec) => {const same = d.toDateString() === now.toDateString();return same ? tr('backup.todayAt', { time: formatTime(d) }) : `${formatDate(d, 'short')} ${formatTime(d)}`;};-// error codes from C (backup.c) → translated text; anything else is shown as is-const errText = (e) => (e ? tOptional(`backup.err.${e}`) || e : '');+// code lines from C (backup.c, errcode.h) → translated text; anything else is shown as is+const errText = (e) => (e ? errorText(e) : '');const pct = (a, b) => (b > 0 ? Math.min(1, a / b) : 0);const join = (a, b) => (a ? `${a}/${b}` : b);@@ -137,7 +137,7 @@ function Header({ st }) {<Label size={typeScale.title} weight={600}>{tr('backup.title')}</Label><Label dim size={typeScale.callout}>{line}</Label>{next ? <Label dim size={typeScale.callout}>{next}</Label> : null}- {st && st.last && st.last.ok === 0 && st.last.error && !running ? <Label size={typeScale.callout} style={{ color: '#e5534b' }}>{tr('backup.lastError', { error: st.last.error })}</Label> : null}+ {st && st.last && st.last.ok === 0 && st.last.error && !running ? <Label size={typeScale.callout} style={{ color: '#e5534b' }}>{tr('backup.lastError', { error: errText(st.last.error) })}</Label> : null}{err ? <Label size={typeScale.callout} style={{ color: '#e5534b' }}>{err}</Label> : null}</View>{running ? (diff --git a/apps/calculator/manifest.json b/apps/calculator/manifest.jsonindex 28e2071..47fee21 100644--- a/apps/calculator/manifest.json+++ b/apps/calculator/manifest.json@@ -1,7 +1,7 @@{"id": "calculator",- "name": "Calculadora",- "description": "Calculadora con teclado",+ "name": "Calculator",+ "description": "Calculator with keyboard input","size": [300,430diff --git a/apps/calendar/index.jsx b/apps/calendar/index.jsxindex 0d90b4f..6a33a09 100644--- a/apps/calendar/index.jsx+++ b/apps/calendar/index.jsx@@ -3,7 +3,7 @@// promise and usePim() changes whenever something changes, so views re-query on it.import {View, Text, useTheme, useLocale, useAppWindow, useKeyboard, useWindowState, usePim, calendars, calendarEvents,- Button, Segmented, ScrollView, Hairline, Toolbar, ToolbarButton, ToolbarSpacer, EmptyState, formatDate, formatTime, weekdayName, direction, t,+ Button, Segmented, ScrollView, Hairline, Toolbar, ToolbarButton, ToolbarGroup, ToolbarSpacer, EmptyState, formatDate, formatTime, weekdayName, direction, textDirection, t,} from '@lordos/sdk';import { useEffect, useMemo, useRef, useState } from 'react';import {@@ -91,6 +91,13 @@ export default function CalendarApp() {const [view, setView] = useWindowState('view', 'week');const [cursorMs, setCursor] = useWindowState('cursor', () => sod(new Date()).getTime());const [sidebar, setSidebar] = useWindowState('sidebar', true);+ // narrow windows hide the sidebar unless it is asked for, as Calendar does+ const [narrowSidebar, setNarrowSidebar] = useWindowState('narrowSidebar', false);+ const rootRef = useRef(null);+ const rootW = useWidth(rootRef, 960);+ const narrow = rootW < 760;+ const showSidebar = narrow ? narrowSidebar : sidebar;+ const toggleSidebar = () => (narrow ? setNarrowSidebar(!narrowSidebar) : setSidebar(!sidebar));const [sheet, setSheet] = useState(null); // { ev, isNew } | { cal } | { newCal: true }const now = useNow(30000);const cursor = new Date(cursorMs);@@ -155,27 +162,33 @@ export default function CalendarApp() {const rtl = direction() === 'rtl';return (- <View style={{ flex: 1, flexDirection: 'row', backgroundColor: th.windowBg }}>- {sidebar && (+ <View ref={rootRef} style={{ flex: 1, flexDirection: 'row', backgroundColor: th.windowBg }}>+ {showSidebar && (<Sidebar cals={eventCals} cursor={cursor} days={days} onPick={(d) => setCursor(sod(d).getTime())}onNew={() => setSheet({ newCal: true })} onEdit={(c) => setSheet({ cal: c })} />)}<View style={{ flex: 1 }}>- <Toolbar>- <ToolbarButton icon="▤" title={t('calendar.toggleSidebar')} onClick={() => setSidebar(!sidebar)} active={sidebar} />- <Button small label={t('calendar.today')} onClick={today} />- <View style={{ flexDirection: 'row' }}>- <ToolbarButton icon={rtl ? '›' : '‹'} iconSize={20} small title={t('calendar.previous')} onClick={() => go(-1)} />- <ToolbarButton icon={rtl ? '‹' : '›'} iconSize={20} small title={t('calendar.next')} onClick={() => go(1)} />- </View>- <Text style={{ fontSize: 17, fontWeight: 700, color: th.text, whiteSpace: 'nowrap', overflow: 'hidden', flexShrink: 1 }}>{title}</Text>+ {/* toolbar: sidebar and new event at the start, the view switch centered */}+ <Toolbar separator={false}>+ <ToolbarButton icon="▤" title={t('calendar.toggleSidebar')} onClick={toggleSidebar} active={showSidebar} />+ <ToolbarButton icon="+" iconSize={20} title={t('calendar.newEvent')} disabled={unavailable} onClick={() => newEvent(cursor)} /><ToolbarSpacer /><Segmented small appearance="neutral" value={view} onChange={setView}options={[['day', t('calendar.view.day')], ['week', t('calendar.view.week')], ['month', t('calendar.view.month')]]} />- <ToolbarButton icon="+" iconSize={20} title={t('calendar.newEvent')} disabled={unavailable} onClick={() => newEvent(cursor)} />+ <ToolbarSpacer />+ <View style={{ width: 64 }} /></Toolbar>+ {/* the period title, with previous / today / next at the trailing edge */}+ <View style={{ height: narrow ? 42 : 50, flexDirection: 'row', alignItems: 'center', gap: 12, paddingHorizontal: 16 }}>+ <Text style={{ flex: 1, fontSize: narrow ? 17 : 22, fontWeight: 700, color: th.text, whiteSpace: 'nowrap', overflow: 'hidden' }}>{title}</Text>+ <ToolbarGroup>+ <ToolbarButton icon={rtl ? '›' : '‹'} iconSize={18} small title={t('calendar.previous')} onClick={() => go(-1)} />+ <ToolbarButton label={t('calendar.today')} small onClick={today} />+ <ToolbarButton icon={rtl ? '‹' : '›'} iconSize={18} small title={t('calendar.next')} onClick={() => go(1)} />+ </ToolbarGroup>+ </View>{unavailable ? (- <EmptyState icon="📅" title={t('calendar.unavailable')} hint={t('calendar.unavailableHint')} />+ <EmptyState icon="▦" title={t('calendar.unavailable')} hint={t('calendar.unavailableHint')} />) : view === 'month' ? (<MonthGrid cursor={cursor} days={days} cals={cals} now={now} onOpen={(ev) => setSheet({ ev })}onSlot={(d) => newEvent(d, 9 * 60)} onDay={(d) => { setCursor(sod(d).getTime()); setView('day'); }} />@@ -209,20 +222,23 @@ function Sidebar({ cals, cursor, days, onPick, onNew, onEdit }) {<View style={{ width: 216, backgroundColor: th.sidebarBg }}><Hairline edge="end" /><ScrollView style={{ flex: 1 }}>- <View style={{ padding: 10, gap: 2 }}>+ <View style={{ paddingHorizontal: 10, paddingTop: 12, paddingBottom: 10, gap: 2 }}>{groups.map((g) => (- <View key={g.key} style={{ gap: 2, marginBottom: 8 }}>- <Text style={{ fontSize: 11, fontWeight: 600, color: th.textDim, marginHorizontal: 6, marginBottom: 2 }}>{g.name}</Text>+ <View key={g.key} style={{ gap: 2, marginBottom: 14 }}>+ <Text style={{ fontSize: 11, fontWeight: 600, color: th.textDim, marginHorizontal: 8, marginBottom: 2, whiteSpace: 'nowrap', overflow: 'hidden' }}>{g.name}</Text>{g.list.map((c) => <CalRow key={c.id} cal={c} onEdit={onEdit} />)}</View>))}{!cals.length ? <Text style={{ fontSize: 12, color: th.textDim, margin: 6 }}>{t('calendar.noCalendars')}</Text> : null}</View></ScrollView>- <View style={{ padding: 10, gap: 8, alignItems: 'center' }}>+ <View style={{ paddingHorizontal: 10, paddingTop: 12, gap: 6, alignItems: 'center' }}><Hairline edge="top" /><MiniMonth key={`${cursor.getFullYear()}-${cursor.getMonth()}`} value={cursor} onPick={onPick} marks={marks} cell={26} />- <Button small plain icon="+" label={t('calendar.newCalendar')} onClick={onNew} style={{ alignSelf: 'stretch' }} />+ </View>+ <View style={{ height: 40, paddingHorizontal: 10, justifyContent: 'center' }}>+ <Hairline edge="top" />+ <Button small plain icon="⊕" label={t('calendar.newCalendar')} onClick={onNew} style={{ alignSelf: 'flex-start' }} /></View></View>);@@ -236,7 +252,7 @@ function CalRow({ cal, onEdit }) {const toggle = () => calendars.update(cal.id, { hidden: !cal.hidden }).catch(() => {});return (<View ref={ref} onClick={toggle} onContextMenu={() => setMenu(true)} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}- style={{ height: 26, paddingHorizontal: 6, borderRadius: 6, flexDirection: 'row', alignItems: 'center', gap: 8, backgroundColor: hover ? th.hover : 'transparent' }}>+ style={{ height: 28, paddingHorizontal: 8, borderRadius: 6, flexDirection: 'row', alignItems: 'center', gap: 8, backgroundColor: hover ? th.hover : 'transparent' }}><ColorCheck on={!cal.hidden} color={cal.color || '#007aff'} /><Text style={{ flex: 1, fontSize: 13, color: th.text, whiteSpace: 'nowrap', overflow: 'hidden' }}>{cal.name}</Text>{menu && (@@ -271,34 +287,36 @@ function TimeGrid({ dates, days, cals, now, onOpen, onSlot, onDay }) {const colW = useWidth(colRef, 120);const rtl = direction() === 'rtl';const nowD = new Date(now);- useEffect(() => { const id = setTimeout(() => scroll.current?.scrollTo(8 * HOUR - 6), 60); return () => clearTimeout(id); }, []);+ useEffect(() => { const id = setTimeout(() => scroll.current?.scrollTo(8 * HOUR - 16), 60); return () => clearTimeout(id); }, []);const sep = (key) => <View key={key} style={{ position: 'absolute', top: 0, bottom: 0, [rtl ? 'right' : 'left']: 0, width: 1, backgroundColor: th.separator }} />;const allDay = dates.map((d) => (days.get(ymd(d)) || []).filter((e) => e.allDay));const maxAll = Math.max(1, ...allDay.map((l) => l.length));const single = dates.length === 1;+ const stacked = !single && colW < 80; // narrow columns: weekday above the day numberreturn (<View style={{ flex: 1 }}>{/* day headers */}- <View style={{ flexDirection: 'row', height: single ? 30 : 40 }}>+ <View style={{ flexDirection: 'row', height: single ? 32 : stacked ? 46 : 36 }}><Hairline edge="bottom" /><View style={{ width: GUTTER }} />{dates.map((d) => {const today = sameDay(d, nowD);return (- <View key={ymd(d)} onClick={() => !single && onDay(d)} style={{ flex: 1, flexDirection: 'row', alignItems: 'center', justifyContent: 'center', gap: 5 }}>- <Text style={{ fontSize: 12, color: today ? RED : th.textDim }}>{weekdayName(d.getDay())}</Text>+ <View key={ymd(d)} onClick={() => !single && onDay(d)}+ style={{ flex: 1, flexDirection: stacked ? 'column' : 'row', alignItems: 'center', justifyContent: 'center', gap: stacked ? 1 : 5, overflow: 'hidden' }}>+ <Text style={{ fontSize: stacked ? 10 : 12, fontWeight: stacked ? 600 : 400, color: today ? RED : th.textDim, whiteSpace: 'nowrap' }}>{weekdayName(d.getDay())}</Text><View style={{ minWidth: 24, height: 24, paddingHorizontal: 4, borderRadius: 12, alignItems: 'center', justifyContent: 'center', backgroundColor: today ? RED : 'transparent' }}>- <Text style={{ fontSize: 15, fontWeight: today ? 700 : 500, color: today ? '#fff' : th.text }}>{String(d.getDate())}</Text>+ <Text style={{ fontSize: 15, fontWeight: today ? 600 : 500, color: today ? '#fff' : th.text }}>{String(d.getDate())}</Text></View></View>);})}</View>{/* all-day row */}- <View style={{ flexDirection: 'row', minHeight: 24, maxHeight: 24 + 20 * Math.min(maxAll, 4) }}>+ <View style={{ flexDirection: 'row', minHeight: 30, maxHeight: 30 + 20 * Math.min(maxAll, 4) }}><Hairline edge="bottom" />- <View style={{ width: GUTTER, justifyContent: 'center' }}>- <Text style={{ fontSize: 10, color: th.textDim, textAlign: 'end', marginHorizontal: 6 }}>{t('calendar.allDay')}</Text>+ <View style={{ width: GUTTER, justifyContent: 'center', paddingVertical: 3 }}>+ <Text style={{ fontSize: 10, lineHeight: 12, color: th.textDim, textAlign: 'end', marginHorizontal: 8 }}>{t('calendar.allDay')}</Text></View>{dates.map((d, i) => (<View key={ymd(d)} onClick={() => onSlot(d, null)} style={{ flex: 1, padding: 2, gap: 2, overflow: 'hidden' }}>@@ -313,7 +331,7 @@ function TimeGrid({ dates, days, cals, now, onOpen, onSlot, onDay }) {<View style={{ flexDirection: 'row', height: 24 * HOUR + 8 }}><View style={{ width: GUTTER }}>{Array.from({ length: 23 }, (_, i) => i + 1).map((h) => (- <Text key={h} style={{ position: 'absolute', top: h * HOUR - 7, left: 0, right: 0, paddingHorizontal: 6, fontSize: 10, color: th.textDim, textAlign: 'end' }}>+ <Text key={h} style={{ position: 'absolute', top: h * HOUR - 7, left: 0, right: 0, paddingHorizontal: 8, fontSize: 10, color: th.textDim, textAlign: 'end', whiteSpace: 'nowrap' }}>{formatTime(new Date(2000, 0, 3, h, 0))}</Text>))}@@ -357,15 +375,17 @@ function EventBlock({ seg, left, width, color, onOpen }) {const h = Math.max(18, ((seg.bottom - seg.top) * HOUR) / 60 - 2);const rtl = direction() === 'rtl';const dark = th.mode === 'dark';+ const oneLine = h < 34 || width < 72; // no broken words in narrow columnsreturn (<View onClick={(e) => { e.stopPropagation(); onOpen(ev); }}- style={{ position: 'absolute', top: (seg.top * HOUR) / 60 + 1, left, width: Math.max(8, width), height: h, borderRadius: 5, overflow: 'hidden',- backgroundColor: tint(color, dark ? '55' : '33'), paddingVertical: 2, paddingHorizontal: 6 }}>+ style={{ position: 'absolute', top: (seg.top * HOUR) / 60 + 1, left, width: Math.max(8, width), height: h, borderRadius: 4, overflow: 'hidden',+ backgroundColor: tint(color, dark ? '4d' : '2e'), paddingVertical: 2, [rtl ? 'paddingRight' : 'paddingLeft']: 7, [rtl ? 'paddingLeft' : 'paddingRight']: 4 }}><View style={{ position: 'absolute', top: 0, bottom: 0, [rtl ? 'right' : 'left']: 0, width: 3, backgroundColor: color }} />- <Text style={{ fontSize: 11, fontWeight: 600, color: th.text, whiteSpace: h < 34 ? 'nowrap' : undefined, overflow: 'hidden' }}>+ {/* the event's own text keeps its direction, so a clipped title loses its end, not its start */}+ <Text style={{ fontSize: 11, fontWeight: 600, color: th.text, whiteSpace: oneLine ? 'nowrap' : undefined, overflow: 'hidden', direction: textDirection(ev.title || '') }}>{ev.title || t('calendar.untitled')}</Text>- {h >= 34 ? <Text style={{ fontSize: 10, color: th.textDim, whiteSpace: 'nowrap', overflow: 'hidden' }}>{ev.loc ? `${formatTime(new Date(ev.start))} · ${ev.loc}` : formatTime(new Date(ev.start))}</Text> : null}+ {h >= 34 ? <Text style={{ fontSize: 10, color: th.textDim, whiteSpace: 'nowrap', overflow: 'hidden', direction: textDirection(ev.loc || ev.title || '') }}>{ev.loc ? `${formatTime(new Date(ev.start))} · ${ev.loc}` : formatTime(new Date(ev.start))}</Text> : null}</View>);}@@ -373,7 +393,7 @@ function EventBlock({ seg, left, width, color, onOpen }) {function AllDayChip({ ev, color, onOpen }) {return (<View onClick={(e) => { e.stopPropagation(); onOpen(ev); }} style={{ height: 18, borderRadius: 4, paddingHorizontal: 6, justifyContent: 'center', backgroundColor: color }}>- <Text style={{ fontSize: 11, fontWeight: 600, color: '#fff', whiteSpace: 'nowrap', overflow: 'hidden' }}>{ev.title || t('calendar.untitled')}</Text>+ <Text style={{ fontSize: 11, fontWeight: 600, color: '#fff', whiteSpace: 'nowrap', overflow: 'hidden', direction: textDirection(ev.title || '') }}>{ev.title || t('calendar.untitled')}</Text></View>);}@@ -442,7 +462,7 @@ function MonthChip({ ev, color, onOpen }) {return (<View onClick={(e) => { e.stopPropagation(); onOpen(ev); }} style={{ height: 16, flexDirection: 'row', alignItems: 'center', gap: 4, paddingHorizontal: 3 }}><View style={{ width: 7, height: 7, borderRadius: 4, backgroundColor: color }} />- <Text style={{ flex: 1, fontSize: 11, color: th.text, whiteSpace: 'nowrap', overflow: 'hidden' }}>{ev.title || t('calendar.untitled')}</Text>+ <Text style={{ flex: 1, fontSize: 11, color: th.text, whiteSpace: 'nowrap', overflow: 'hidden', direction: textDirection(ev.title || '') }}>{ev.title || t('calendar.untitled')}</Text><Text style={{ fontSize: 10, color: th.textDim, whiteSpace: 'nowrap' }}>{formatTime(new Date(ev.start))}</Text></View>);diff --git a/apps/calendar/ui.jsx b/apps/calendar/ui.jsxindex bb79c41..ec0b39f 100644--- a/apps/calendar/ui.jsx+++ b/apps/calendar/ui.jsx@@ -127,13 +127,13 @@ export function Sheet({ title, onClose, children, footer, width = 440 }) {<View style={{ width, maxWidth: '94%', maxHeight: '94%', borderRadius: 12, backgroundColor: th.windowBg, border: `1px solid ${th.separator}`,boxShadow: '0 18px 50px rgba(0,0,0,0.45)', overflow: 'hidden' }}>{title ? (- <View style={{ paddingHorizontal: 16, paddingTop: 14, paddingBottom: 6 }}>- <Text style={{ fontSize: 15, fontWeight: 700, color: th.text }}>{title}</Text>+ <View style={{ paddingHorizontal: 20, paddingTop: 18, paddingBottom: 4 }}>+ <Text style={{ fontSize: 15, fontWeight: 600, color: th.text }}>{title}</Text></View>) : null}- <View style={{ paddingHorizontal: 16, paddingVertical: 10, gap: 10, flexShrink: 1 }}>{children}</View>+ <View style={{ paddingHorizontal: 20, paddingVertical: 12, gap: 10, flexShrink: 1 }}>{children}</View>{footer ? (- <View style={{ flexDirection: 'row', alignItems: 'center', gap: 8, paddingHorizontal: 16, paddingVertical: 12 }}>+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 8, paddingHorizontal: 20, paddingVertical: 14 }}><Hairline edge="top" />{footer}</View>@@ -244,7 +244,7 @@ export function MiniMonth({ value, onPick, marks, month: ctlMonth, onMonth, cell<View key={c} onClick={() => onPick(d)} style={{ width: cell, height: cell, alignItems: 'center', justifyContent: 'center' }}><View style={{ width: cell - 4, height: cell - 4, borderRadius: (cell - 4) / 2, alignItems: 'center', justifyContent: 'center',backgroundColor: sel ? (isToday ? RED : th.accent) : 'transparent' }}>- <Text style={{ fontSize: 11, fontWeight: isToday || sel ? 700 : 400,+ <Text style={{ fontSize: 11, fontWeight: isToday || sel ? 600 : 400,color: sel ? '#fff' : isToday ? RED : inMonth ? th.text : th.textDim }}>{String(d.getDate())}</Text></View>{marks && marks.has(ymd(d)) && !sel ? <View style={{ position: 'absolute', bottom: 1, width: 3, height: 3, borderRadius: 2, backgroundColor: th.textDim }} /> : null}@@ -256,7 +256,7 @@ export function MiniMonth({ value, onPick, marks, month: ctlMonth, onMonth, cellreturn (<View style={{ width: cell * 7, gap: 2 }}><View style={{ flexDirection: 'row', alignItems: 'center', height: 24 }}>- <Text style={{ flex: 1, fontSize: 12, fontWeight: 700, color: th.text, marginHorizontal: 4 }}>{monthYear(month)}</Text>+ <Text style={{ flex: 1, fontSize: 12, fontWeight: 600, color: th.text, marginHorizontal: 4, whiteSpace: 'nowrap', overflow: 'hidden' }}>{monthYear(month)}</Text><NavArrow glyph={rtl ? '›' : '‹'} onClick={() => setMonth(addMonths(month, -1))} /><NavArrow glyph="●" small onClick={() => { setMonth(new Date(today.getFullYear(), today.getMonth(), 1)); }} /><NavArrow glyph={rtl ? '‹' : '›'} onClick={() => setMonth(addMonths(month, 1))} />diff --git a/apps/camera/index.jsx b/apps/camera/index.jsxindex e956f7c..131ba0f 100644--- a/apps/camera/index.jsx+++ b/apps/camera/index.jsx@@ -6,7 +6,7 @@// light theme.import {View, Text, Image, MediaView, Toggle, useTheme, useKeyboard, wm,- t as tr, media, usePlayer, useThumb, userDirs, fs, mediaFormatTime, useSettings,+ t as tr, errorText, media, usePlayer, useThumb, userDirs, fs, mediaFormatTime, useSettings,} from '@lordos/sdk';import { useEffect, useRef, useState } from 'react';@@ -154,7 +154,7 @@ export default function Camera() {<MediaView media={id} style={{ position: 'absolute', left: 0, top: 0, right: 0, bottom: 0 }} />{(!cams.length || denied || p.error) && (!cams.length ? <NoCamera title={tr('camera.none')} hint={tr('camera.noneHint')} />- : <NoCamera title={denied ? tr('camera.deniedTitle') : tr('camera.errorTitle')} hint={denied ? tr('camera.denied') : tr('camera.error', { error: p.error })} />+ : <NoCamera title={denied ? tr('camera.deniedTitle') : tr('camera.errorTitle')} hint={denied ? tr('camera.denied') : tr('camera.error', { error: errorText(p.error) })} />)}{flash && <View style={{ position: 'absolute', left: 0, top: 0, right: 0, bottom: 0, backgroundColor: 'rgba(255,255,255,0.85)' }} />}{recStart > 0 && (diff --git a/apps/camera/manifest.json b/apps/camera/manifest.jsonindex ea12bd3..3bf2c7f 100644--- a/apps/camera/manifest.json+++ b/apps/camera/manifest.json@@ -1,7 +1,7 @@{"id": "camera",- "name": "Cámara",- "description": "Vista previa de la webcam, fotos y videos, con espejo y elección de cámara",+ "name": "Camera",+ "description": "Webcam preview, photos and videos, with mirroring and camera choice","size": [820, 560],"minSize": [480, 360],"dock": true,diff --git a/apps/characters/manifest.json b/apps/characters/manifest.jsonindex 1130a16..4f62083 100644--- a/apps/characters/manifest.json+++ b/apps/characters/manifest.json@@ -1,7 +1,7 @@{"id": "characters",- "name": "Emojis y símbolos",- "description": "Emojis por categoría con búsqueda y tonos de piel, y símbolos de Unicode por bloque (selector rápido con ❖.)",+ "name": "Emoji & Symbols",+ "description": "Emoji by category with search and skin tones, and Unicode symbols by block (quick picker with ❖.)","size": [860, 560],"minSize": [600, 380],"dock": false,diff --git a/apps/clock/manifest.json b/apps/clock/manifest.jsonindex 3b62249..4b24c2c 100644--- a/apps/clock/manifest.json+++ b/apps/clock/manifest.json@@ -1,7 +1,7 @@{"id": "clock",- "name": "Reloj",- "description": "Reloj mundial, alarmas, temporizador y cronómetro",+ "name": "Clock",+ "description": "World clock, alarms, timer and stopwatch","size": [560,520diff --git a/apps/contacts/card.jsx b/apps/contacts/card.jsxindex 276aaf1..e50512b 100644--- a/apps/contacts/card.jsx+++ b/apps/contacts/card.jsx@@ -3,7 +3,7 @@import {View, Text, useTheme, Button, TextInput, ScrollView, Hairline, ContactPhoto, contacts, contactName, wm, getApp, formatDate, FilePicker, t,} from '@lordos/sdk';-import { useRef, useState } from 'react';+import { useEffect, useRef, useState } from 'react';import { RED, Popover, MenuList, Choice, TextArea, DateField, ymd, parseYmd, monthName } from './ui.jsx';const TYPES = {@@ -58,30 +58,35 @@ export function Card({ contact: c, groups, onEdit }) {contacts.save(g.book, { ...g, members }, {}).catch(() => {});};const mine = groups.filter((g) => (g.members || []).includes(c.uid));+ const box = useRef(null);+ const w = useWidth(box);+ const narrow = w < 400; // a narrow card stacks the photo above the name, centered+ const lw = w < 300 ? 0 : narrow ? 70 : 96; // 0: the label goes above its value+ const head = [+ <ContactPhoto key="p" contact={c} size={narrow ? 72 : 88} />,+ <View key="n" style={narrow ? { alignSelf: 'stretch', alignItems: 'center', gap: 3 } : { flex: 1, gap: 3 }}>+ <Text style={{ fontSize: narrow ? 20 : 24, fontWeight: 600, color: th.text, textAlign: narrow ? 'center' : 'start' }}>{name}</Text>+ {sub && (showOrg || c.title) ? <Text style={{ fontSize: 13, color: th.textDim, textAlign: narrow ? 'center' : 'start' }}>{sub}</Text> : null}+ {c.nick ? <Text style={{ fontSize: 12, color: th.textDim }}>{`“${c.nick}”`}</Text> : null}+ {mine.length ? <Text style={{ fontSize: 11, color: th.textDim }}>{mine.map((g) => contactName(g)).join(', ')}</Text> : null}+ </View>,+ ];return (- <View style={{ flex: 1 }}>+ <View ref={box} style={{ flex: 1 }}><ScrollView style={{ flex: 1 }}>- <View style={{ padding: 24, gap: 18 }}>- <View style={{ flexDirection: 'row', alignItems: 'center', gap: 18 }}>- <ContactPhoto contact={c} size={96} />- <View style={{ flex: 1, gap: 3 }}>- <Text style={{ fontSize: 24, fontWeight: 700, color: th.text }}>{name}</Text>- {sub && (showOrg || c.title) ? <Text style={{ fontSize: 13, color: th.textDim }}>{sub}</Text> : null}- {c.nick ? <Text style={{ fontSize: 12, color: th.textDim }}>{`“${c.nick}”`}</Text> : null}- {mine.length ? <Text style={{ fontSize: 11, color: th.textDim }}>{mine.map((g) => contactName(g)).join(', ')}</Text> : null}- </View>- </View>- <View style={{ gap: 2 }}>- {(c.phones || []).map((p, i) => <Row key={`p${i}`} label={typeLabel('phones', p.type)} value={p.value} />)}- {(c.emails || []).map((p, i) => <Row key={`e${i}`} label={typeLabel('emails', p.type)} value={p.value} link onClick={() => openMail(contactName(c), p.value)} />)}- {(c.urls || []).map((p, i) => <Row key={`u${i}`} label={typeLabel('urls', p.type)} value={p.value} />)}- {(c.addrs || []).map((a, i) => <Row key={`a${i}`} label={typeLabel('addrs', a.type)} value={addrLines(a).join('\n')} />)}- {c.bday ? <Row label={t('contacts.birthday')} value={bdayText(c.bday)} /> : null}- {c.notes ? <Row label={t('contacts.notes')} value={c.notes} /> : null}+ <View style={{ paddingHorizontal: narrow ? 16 : 28, paddingTop: 24, paddingBottom: 24, gap: 20 }}>+ <View style={narrow ? { alignItems: 'center', gap: 12 } : { flexDirection: 'row', alignItems: 'center', gap: 20 }}>{head}</View>+ <View style={{ gap: 0 }}>+ {(c.phones || []).map((p, i) => <Row key={`p${i}`} lw={lw} label={typeLabel('phones', p.type)} value={p.value} />)}+ {(c.emails || []).map((p, i) => <Row key={`e${i}`} lw={lw} label={typeLabel('emails', p.type)} value={p.value} link onClick={() => openMail(contactName(c), p.value)} />)}+ {(c.urls || []).map((p, i) => <Row key={`u${i}`} lw={lw} label={typeLabel('urls', p.type)} value={p.value} />)}+ {(c.addrs || []).map((a, i) => <Row key={`a${i}`} lw={lw} label={typeLabel('addrs', a.type)} value={addrLines(a).join('\n')} />)}+ {c.bday ? <Row lw={lw} label={t('contacts.birthday')} value={bdayText(c.bday)} /> : null}+ {c.notes ? <Row lw={lw} label={t('contacts.notes')} value={c.notes} /> : null}</View></View></ScrollView>- <View style={{ height: 44, flexDirection: 'row', alignItems: 'center', gap: 8, paddingHorizontal: 14 }}>+ <View style={{ height: 40, flexDirection: 'row', alignItems: 'center', gap: 8, paddingHorizontal: 12 }}><Hairline edge="top" /><View ref={groupRef}><Button small label={t('contacts.groups')} disabled={!groups.length} onClick={() => setGroupMenu(true)} />@@ -99,11 +104,29 @@ export function Card({ contact: c, groups, onEdit }) {);}-function Row({ label, value, link, onClick }) {+// the width of a box after layout (re-measured on every render)+function useWidth(ref, initial = 600) {+ const [w, setW] = useState(initial);+ useEffect(() => {+ const id = setTimeout(() => { if (ref.current) { const nw = lord.getLayout(ref.current.id)[2]; if (nw && Math.abs(nw - w) > 0.5) setW(nw); } }, 20);+ return () => clearTimeout(id);+ });+ return w;+}++function Row({ label, value, link, onClick, lw = 96 }) {const th = useTheme();+ if (!lw) {+ return (+ <View style={{ paddingVertical: 5, gap: 1 }}>+ <Text style={{ fontSize: 11, color: th.textDim }}>{label}</Text>+ <Text onClick={onClick} style={{ fontSize: 13, color: link ? th.accent : th.text, lineHeight: 18 }}>{value}</Text>+ </View>+ );+ }return (- <View style={{ flexDirection: 'row', gap: 12, paddingVertical: 6 }}>- <Text style={{ width: 96, fontSize: 12, color: th.textDim, textAlign: 'end', paddingTop: 1 }}>{label}</Text>+ <View style={{ flexDirection: 'row', gap: 12, paddingVertical: 5 }}>+ <Text style={{ width: lw, fontSize: 12, color: th.textDim, textAlign: 'end', paddingTop: 1, whiteSpace: 'nowrap', overflow: 'hidden' }}>{label}</Text><Text onClick={onClick} style={{ flex: 1, fontSize: 13, color: link ? th.accent : th.text, lineHeight: 18 }}>{value}</Text></View>);@@ -189,7 +212,7 @@ export function Editor({ contact, groups, onCancel, onSave, onDelete }) {</View></View></ScrollView>- <View style={{ height: 44, flexDirection: 'row', alignItems: 'center', gap: 8, paddingHorizontal: 14 }}>+ <View style={{ height: 40, flexDirection: 'row', alignItems: 'center', gap: 8, paddingHorizontal: 12 }}><Hairline edge="top" />{onDelete ? <Button small destructive label={t('contacts.deleteContact')} onClick={onDelete} /> : null}<Text style={{ flex: 1, fontSize: 12, color: RED, textAlign: 'center' }}>{error}</Text>diff --git a/apps/contacts/index.jsx b/apps/contacts/index.jsxindex 65eaf74..92e3ad6 100644--- a/apps/contacts/index.jsx+++ b/apps/contacts/index.jsx@@ -30,7 +30,7 @@ export function Icon({ size: s }) {);}-const ROW = 34, HEAD = 22;+const ROW = 30, HEAD = 24;const sortKey = (c) => {const n = c.n || {};@@ -129,7 +129,7 @@ export default function ContactsApp() {onRenameGroup={(g) => setSheet({ group: g })} onDeleteGroup={(g) => { contacts.remove(g.book, g.uid).catch(() => {}); if (src === `group:${keyOf(g)}`) setSrc('all'); }} /><View style={{ width: 270 }}><Hairline edge="end" />- <View style={{ padding: 10, flexDirection: 'row', gap: 6, alignItems: 'center' }}>+ <View style={{ paddingHorizontal: 12, paddingTop: 12, paddingBottom: 8, flexDirection: 'row', gap: 6, alignItems: 'center' }}><SearchField value={query} onChange={setQuery} placeholder={t('contacts.search')} style={{ flex: 1 }} /></View>{unavailable ? null : list.length ? (@@ -137,23 +137,23 @@ export default function ContactsApp() {) : (<EmptyState title={query ? t('contacts.noResults') : t('contacts.noContacts')} />)}- <View style={{ height: 34, flexDirection: 'row', alignItems: 'center', paddingHorizontal: 8 }}>+ <View style={{ height: 40, flexDirection: 'row', alignItems: 'center', paddingHorizontal: 10 }}><Hairline edge="top" /><ToolbarButton icon="+" iconSize={18} small title={t('contacts.newContact')} onClick={startNew} disabled={unavailable} />- <Text style={{ flex: 1, fontSize: 11, color: th.textDim, textAlign: 'center' }}>{t('contacts.count', { count: list.length, n: formatNumber(list.length, 0) })}</Text>+ <Text style={{ flex: 1, fontSize: 11, color: th.textDim, textAlign: 'center', whiteSpace: 'nowrap' }}>{t('contacts.count', { count: list.length, n: formatNumber(list.length, 0) })}</Text><View style={{ width: 22 }} /></View></View><View style={{ flex: 1 }}>{unavailable ? (- <EmptyState icon="👤" title={t('contacts.unavailable')} hint={t('contacts.unavailableHint')} />+ <EmptyState icon={<PersonGlyph size={44} color={th.textDim} />} title={t('contacts.unavailable')} hint={t('contacts.unavailableHint')} />) : draft ? (<Editor key={draft._new ? 'new' : keyOf(draft)} contact={draft} groups={groups} onCancel={() => setDraft(null)} onSave={saveDraft}onDelete={draft._new ? null : () => setSheet({ confirm: draft })} />) : selected ? (<Card contact={selected} groups={groups.filter((g) => g.book === selected.book)} onEdit={() => setDraft(JSON.parse(JSON.stringify(selected)))} />) : (- <EmptyState icon="👤" title={t('contacts.noSelection')} />+ <EmptyState icon={<PersonGlyph size={44} color={th.textDim} />} title={t('contacts.noSelection')} />)}</View>{sheet && (sheet.newGroup || sheet.group) ? (@@ -195,14 +195,14 @@ export default function ContactsApp() {function Sources({ books, groups, src, counts, onSrc, onNewGroup, onImport, onRenameGroup, onDeleteGroup }) {const th = useTheme();return (- <View style={{ width: 200, backgroundColor: th.sidebarBg }}>+ <View style={{ width: 212, backgroundColor: th.sidebarBg }}><Hairline edge="end" />- <View style={{ flex: 1, padding: 10, gap: 2 }}>- <SrcRow icon="👥" label={t('contacts.allContacts')} count={counts.length} selected={src === 'all'} onClick={() => onSrc('all')} />+ <View style={{ flex: 1, paddingHorizontal: 10, paddingTop: 12, gap: 2 }}>+ <SrcRow icon={<PersonGlyph size={14} />} label={t('contacts.allContacts')} count={counts.length} selected={src === 'all'} onClick={() => onSrc('all')} />{books.map((b) => (- <View key={b.id} style={{ gap: 2, marginTop: 10 }}>- <Text style={{ fontSize: 11, fontWeight: 600, color: th.textDim, marginHorizontal: 6, marginBottom: 2 }}>{b.acct ? b.acctName || b.acct : t('contacts.onThisComputer')}</Text>- <SrcRow icon="📒" label={b.name} count={counts.filter((c) => c.book === b.id).length} selected={src === `book:${b.id}`} onClick={() => onSrc(`book:${b.id}`)} />+ <View key={b.id} style={{ gap: 2, marginTop: 16 }}>+ <Text style={{ fontSize: 11, fontWeight: 600, color: th.textDim, marginHorizontal: 8, marginBottom: 2, whiteSpace: 'nowrap', overflow: 'hidden' }}>{b.acct ? b.acctName || b.acct : t('contacts.onThisComputer')}</Text>+ <SrcRow icon="▤" label={b.name} count={counts.filter((c) => c.book === b.id).length} selected={src === `book:${b.id}`} onClick={() => onSrc(`book:${b.id}`)} />{groups.filter((g) => g.book === b.id).map((g) => (<SrcRow key={g.uid} indent icon="▢" label={contactName(g) || t('contacts.untitledGroup')} count={(g.members || []).length}selected={src === `group:${keyOf(g)}`} onClick={() => onSrc(`group:${keyOf(g)}`)}@@ -211,9 +211,9 @@ function Sources({ books, groups, src, counts, onSrc, onNewGroup, onImport, onRe</View>))}</View>- <View style={{ flexDirection: 'row', padding: 8, gap: 4 }}>+ <View style={{ height: 40, flexDirection: 'row', alignItems: 'center', paddingHorizontal: 6, gap: 2 }}><Hairline edge="top" />- <Button small plain icon="+" label={t('contacts.newGroup')} onClick={onNewGroup} />+ <Button small plain icon="⊕" label={t('contacts.newGroup')} onClick={onNewGroup} /><View style={{ flex: 1 }} /><Button small plain label={t('contacts.import')} onClick={onImport} /></View>@@ -228,9 +228,12 @@ function SrcRow({ icon, label, count, selected, onClick, indent, menu }) {const [hover, setHover] = useState(false);return (<View ref={ref} onClick={onClick} onContextMenu={menu ? () => setOpen(true) : undefined} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}- style={{ height: 26, paddingHorizontal: indent ? 22 : 6, borderRadius: 6, flexDirection: 'row', alignItems: 'center', gap: 7,+ style={{ height: 28, paddingHorizontal: indent ? 24 : 8, borderRadius: 6, flexDirection: 'row', alignItems: 'center', gap: 8,backgroundColor: selected ? th.accent : hover ? th.hover : 'transparent' }}>- <Text style={{ fontSize: 12, color: selected ? '#fff' : th.textDim }}>{icon}</Text>+ <View style={{ width: 16, alignItems: 'center' }}>+ {typeof icon === 'string' ? <Text style={{ fontSize: 13, color: selected ? '#fff' : th.accent }}>{icon}</Text>+ : <PersonGlyph size={14} color={selected ? '#fff' : th.accent} />}+ </View><Text style={{ flex: 1, fontSize: 13, color: selected ? '#fff' : th.text, whiteSpace: 'nowrap', overflow: 'hidden' }}>{label}</Text><Text style={{ fontSize: 11, color: selected ? 'rgba(255,255,255,0.8)' : th.textDim }}>{String(count)}</Text>{open && menu ? (@@ -287,9 +290,9 @@ function ContactList({ list, cur, onPick }) {return (<View ref={box} onWheel={(e) => setOff((o) => Math.max(0, Math.min(max, Math.min(o, max) + e.deltaY)))} style={{ flex: 1, overflow: 'hidden' }}>{shown.map((r) => (r.head != null ? (- <View key={`h${r.head}`} style={{ position: 'absolute', left: 0, right: 0, top: r.top - y, height: HEAD, justifyContent: 'center', paddingHorizontal: 14 }}>- <Text style={{ fontSize: 12, fontWeight: 700, color: th.textDim }}>{r.head}</Text>- <Hairline edge="bottom" inset={12} />+ <View key={`h${r.head}`} style={{ position: 'absolute', left: 0, right: 0, top: r.top - y, height: HEAD, justifyContent: 'flex-end', paddingBottom: 3, paddingHorizontal: 16 }}>+ <Text style={{ fontSize: 11, fontWeight: 600, color: th.textDim }}>{r.head}</Text>+ <Hairline edge="bottom" inset={14} /></View>) : (<ContactRow key={keyOf(r.c)} c={r.c} top={r.top - y} selected={keyOf(r.c) === cur} onPick={onPick} />@@ -310,15 +313,15 @@ function ContactRow({ c, top, selected, onPick }) {const family = [n.family, n.suffix].filter(Boolean).join(' ');const fg = selected ? '#fff' : th.text;return (- <View onClick={() => onPick(c)} style={{ position: 'absolute', left: 6, right: 6, top, height: ROW, borderRadius: 6, paddingHorizontal: 10,+ <View onClick={() => onPick(c)} style={{ position: 'absolute', left: 8, right: 8, top: top + 1, height: ROW - 2, borderRadius: 6, paddingHorizontal: 8,flexDirection: 'row', alignItems: 'center', gap: 4, backgroundColor: selected ? th.accent : 'transparent' }}>{given || family ? (<>{given ? <Text style={{ fontSize: 13, color: fg, whiteSpace: 'nowrap' }}>{given}</Text> : null}- {family ? <Text style={{ fontSize: 13, fontWeight: 700, color: fg, whiteSpace: 'nowrap', overflow: 'hidden', flexShrink: 1 }}>{family}</Text> : null}+ {family ? <Text style={{ fontSize: 13, fontWeight: 600, color: fg, whiteSpace: 'nowrap', overflow: 'hidden', flexShrink: 1 }}>{family}</Text> : null}</>) : (- <Text style={{ fontSize: 13, fontWeight: 700, color: fg, whiteSpace: 'nowrap', overflow: 'hidden', flexShrink: 1 }}>{contactName(c) || t('contacts.noName')}</Text>+ <Text style={{ fontSize: 13, fontWeight: 600, color: fg, whiteSpace: 'nowrap', overflow: 'hidden', flexShrink: 1 }}>{contactName(c) || t('contacts.noName')}</Text>)}</View>);@@ -339,3 +342,16 @@ function GroupSheet({ group, onClose, onSave }) {</Sheet>);}++// A person silhouette drawn with two shapes (the 👤 emoji is in color and does not follow the theme).+export function PersonGlyph({ size = 14, color }) {+ const th = useTheme();+ const c = color || th.accent;+ return (+ <View style={{ width: size, height: size, alignItems: 'center' }}>+ <View style={{ width: size * 0.44, height: size * 0.44, borderRadius: size * 0.22, backgroundColor: c }} />+ <View style={{ marginTop: size * 0.06, width: size * 0.86, height: size * 0.42, borderTopLeftRadius: size * 0.43, borderTopRightRadius: size * 0.43,+ borderBottomLeftRadius: size * 0.08, borderBottomRightRadius: size * 0.08, backgroundColor: c }} />+ </View>+ );+}diff --git a/apps/contacts/ui.jsx b/apps/contacts/ui.jsxindex bb79c41..ec0b39f 100644--- a/apps/contacts/ui.jsx+++ b/apps/contacts/ui.jsx@@ -127,13 +127,13 @@ export function Sheet({ title, onClose, children, footer, width = 440 }) {<View style={{ width, maxWidth: '94%', maxHeight: '94%', borderRadius: 12, backgroundColor: th.windowBg, border: `1px solid ${th.separator}`,boxShadow: '0 18px 50px rgba(0,0,0,0.45)', overflow: 'hidden' }}>{title ? (- <View style={{ paddingHorizontal: 16, paddingTop: 14, paddingBottom: 6 }}>- <Text style={{ fontSize: 15, fontWeight: 700, color: th.text }}>{title}</Text>+ <View style={{ paddingHorizontal: 20, paddingTop: 18, paddingBottom: 4 }}>+ <Text style={{ fontSize: 15, fontWeight: 600, color: th.text }}>{title}</Text></View>) : null}- <View style={{ paddingHorizontal: 16, paddingVertical: 10, gap: 10, flexShrink: 1 }}>{children}</View>+ <View style={{ paddingHorizontal: 20, paddingVertical: 12, gap: 10, flexShrink: 1 }}>{children}</View>{footer ? (- <View style={{ flexDirection: 'row', alignItems: 'center', gap: 8, paddingHorizontal: 16, paddingVertical: 12 }}>+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 8, paddingHorizontal: 20, paddingVertical: 14 }}><Hairline edge="top" />{footer}</View>@@ -244,7 +244,7 @@ export function MiniMonth({ value, onPick, marks, month: ctlMonth, onMonth, cell<View key={c} onClick={() => onPick(d)} style={{ width: cell, height: cell, alignItems: 'center', justifyContent: 'center' }}><View style={{ width: cell - 4, height: cell - 4, borderRadius: (cell - 4) / 2, alignItems: 'center', justifyContent: 'center',backgroundColor: sel ? (isToday ? RED : th.accent) : 'transparent' }}>- <Text style={{ fontSize: 11, fontWeight: isToday || sel ? 700 : 400,+ <Text style={{ fontSize: 11, fontWeight: isToday || sel ? 600 : 400,color: sel ? '#fff' : isToday ? RED : inMonth ? th.text : th.textDim }}>{String(d.getDate())}</Text></View>{marks && marks.has(ymd(d)) && !sel ? <View style={{ position: 'absolute', bottom: 1, width: 3, height: 3, borderRadius: 2, backgroundColor: th.textDim }} /> : null}@@ -256,7 +256,7 @@ export function MiniMonth({ value, onPick, marks, month: ctlMonth, onMonth, cellreturn (<View style={{ width: cell * 7, gap: 2 }}><View style={{ flexDirection: 'row', alignItems: 'center', height: 24 }}>- <Text style={{ flex: 1, fontSize: 12, fontWeight: 700, color: th.text, marginHorizontal: 4 }}>{monthYear(month)}</Text>+ <Text style={{ flex: 1, fontSize: 12, fontWeight: 600, color: th.text, marginHorizontal: 4, whiteSpace: 'nowrap', overflow: 'hidden' }}>{monthYear(month)}</Text><NavArrow glyph={rtl ? '›' : '‹'} onClick={() => setMonth(addMonths(month, -1))} /><NavArrow glyph="●" small onClick={() => { setMonth(new Date(today.getFullYear(), today.getMonth(), 1)); }} /><NavArrow glyph={rtl ? '‹' : '›'} onClick={() => setMonth(addMonths(month, 1))} />diff --git a/apps/editor/manifest.json b/apps/editor/manifest.jsonindex 58c80f1..e830723 100644--- a/apps/editor/manifest.json+++ b/apps/editor/manifest.json@@ -1,7 +1,7 @@{"id": "editor",- "name": "Editor de texto",- "description": "Editor de código al estilo de TextMate: proyecto, pestañas, varios cursores, buscar y reemplazar, resaltado de sintaxis",+ "name": "Text Editor",+ "description": "TextMate-style code editor: project, tabs, multiple cursors, find and replace, syntax highlighting","size": [900, 600],"minSize": [520, 340],"dock": true,diff --git a/apps/files/archive.js b/apps/files/archive.jsindex 0af78cb..cb8970e 100644--- a/apps/files/archive.js+++ b/apps/files/archive.js@@ -1,20 +1,19 @@-// archive.js — los comprimidos en Archivos: mirarlos por dentro como una carpeta, abrir o ver un-// archivo de adentro (se extrae solo ese a la caché), «Extraer aquí» y «Comprimir». El trabajo lo-// hace el ayudante encerrado lord-doc (libarchive), que nunca escribe fuera de la carpeta de-// destino (ver docs/DOCUMENTS.md).-// lugar: { type: 'archive', path: '/…/fotos.zip', inner: 'carpeta/sub' }+// archive.js — archives in Files: browse them like a folder, open or view a file inside+// (only that one is extracted, to the cache), "Extract Here" and "Compress". The work is done by+// the confined helper lord-doc (libarchive), which never writes outside the destination folder+// (see docs/DOCUMENTS.md).+// location: { type: 'archive', path: '/…/photos.zip', inner: 'folder/sub' }import { archive, createStore, fs } from '@lordos/sdk';import { bump, freeName } from './ops.js';-const lists = new Map(); // ruta → { mtime, state: 'loading' | 'ok' | 'error', dirs, info, error }+const lists = new Map(); // path → { mtime, state: 'loading' | 'ok' | 'error', dirs, info, error }export const archiveVersion = createStore(0);-const ERRS = ['invalid', 'disk-full', 'too-big', 'too-many', 'corrupt', 'write'];export const isArchiveFile = (e) => !e.dir && !e.app && !e.trash && archive.isArchive(e.name);function load(path) {let st;- try { st = fs.stat(path); } catch (e) { return { state: 'error', error: e.message }; }+ try { st = fs.stat(path); } catch (e) { return { state: 'error', error: e.code, message: e.message }; }const cur = lists.get(path);if (cur && cur.mtime === st.mtime) return cur;const entry = { mtime: st.mtime, state: 'loading' };@@ -26,46 +25,47 @@ function load(path) {archiveVersion.set((v) => v + 1);}).catch((e) => {entry.state = 'error';- entry.error = e.code || e.message;+ entry.error = e.code;+ entry.message = e.message; // already translated (sdk/doc.js)archiveVersion.set((v) => v + 1);});return entry;}-// Entradas del lugar (sincrónico: mientras carga devuelve [] y después avisa con archiveVersion).+// Entries of the location (synchronous: returns [] while loading and then notifies through archiveVersion).export function archiveEntries(loc) {const a = load(loc.path);- if (a.state === 'error') throw new Error(a.error === 'invalid' ? 'archive-invalid' : a.error);+ if (a.state === 'error') throw new Error(a.error === 'invalid' ? 'archive-invalid' : a.message);if (a.state !== 'ok') return [];const list = a.dirs.get(loc.inner || '') || [];return list.map((x) => ({ name: x.name, path: `archive:${loc.path}::${x.path}`, dir: x.dir, size: x.size, mtime: x.mtime, arc: { file: loc.path, inner: x.path }, enc: x.enc }));}export const archiveState = (path) => lists.get(path) || null;-// carpeta de la caché para lo extraído de este comprimido (una por ruta y fecha)+// cache folder for what is extracted from this archive (one per path and date)function cacheDir(file) {let h = 2166136261;const key = `${file}|${lists.get(file)?.mtime || 0}`;for (let i = 0; i < key.length; i++) { h ^= key.charCodeAt(i); h = Math.imul(h, 16777619) >>> 0; }- for (const p of ['.cache', '.cache/lordos', '.cache/lordos/archives']) { try { fs.mkdir(p); } catch (e) { /* ya está */ } }+ for (const p of ['.cache', '.cache/lordos', '.cache/lordos/archives']) { try { fs.mkdir(p); } catch (e) { /* already there */ } }const dir = `${fs.home()}/.cache/lordos/archives/${h.toString(16)}`;- try { fs.mkdir(dir); } catch (e) { /* ya está */ }+ try { fs.mkdir(dir); } catch (e) { /* already there */ }return dir;}-// Extrae una entrada a la caché y devuelve su ruta real (para abrirla o verla).+// Extracts an entry to the cache and returns its real path (to open or view it).const extracted = new Map();export async function extractEntry(e) {const dir = cacheDir(e.arc.file);const real = `${dir}/${e.arc.inner}`;if (extracted.get(real)) return real;- try { fs.stat(real); extracted.set(real, true); return real; } catch (err) { /* hay que extraerla */ }+ try { fs.stat(real); extracted.set(real, true); return real; } catch (err) { /* it has to be extracted */ }await archive.extract(e.arc.file, dir, { only: [e.arc.inner], existing: true });extracted.set(real, true);return real;}-// «Extraer aquí»: carpeta nueva con el nombre del comprimido, al lado.+// "Extract Here": a new folder named after the archive, next to it.export function extractHere(e, report, t) {const dir = fs.parent(e.path);const name = freeName(dir, archive.stem(e.name));@@ -78,11 +78,11 @@ export function extractHere(e, report, t) {return { dir: `${dir}/${name}`, ...r };}).catch((err) => {bump();- report(t('docs.extractError', { name: e.name, error: ERRS.includes(err.code) ? t(`docs.err.${err.code}`) : err.code || err.message }));+ report(t('docs.extractError', { name: e.name, error: err.message }));});}-// «Comprimir»: un .zip al lado (el nombre del elemento, o «Archivo.zip» si son varios).+// "Compress": a .zip next to it (the item's name, or "Archive.zip" for several).export function compress(paths, dir, report, t) {if (!paths.length) return Promise.resolve(null);const base = paths.length === 1 ? fs.basename(paths[0]) : t('docs.archiveName');@@ -91,5 +91,5 @@ export function compress(paths, dir, report, t) {return archive.create(paths, `${dir}/${name}`, {onProgress: (p) => report(t('docs.compressProgress', { name, files: p.files })),}).then((r) => { bump(); report(t('docs.compressed', { name, count: r.files })); return name; })- .catch((err) => { bump(); report(t('docs.compressError', { name, error: err.code || err.message })); });+ .catch((err) => { bump(); report(t('docs.compressError', { name, error: err.message })); });}diff --git a/apps/files/glyphs.jsx b/apps/files/glyphs.jsxindex 505ad15..7f8dd31 100644--- a/apps/files/glyphs.jsx+++ b/apps/files/glyphs.jsx@@ -1,5 +1,5 @@-// glyphs.jsx — íconos de Archivos: carpeta, documento por tipo (con la extensión) y miniatura-// de las imágenes. Dibujados con nodos (sin imágenes), salvo las miniaturas.+// glyphs.jsx — Files icons: folder, document by kind (with the extension) and image+// thumbnails. Drawn with nodes (no images), except the thumbnails.import { View, Text, Image, useThumb } from '@lordos/sdk';import { kindOf, extOf, isImage, KIND_COLOR } from './kinds.js';@@ -34,7 +34,7 @@ export function DocGlyph({ size: s, kind, ext, dark }) {);}-// Ícono de una entrada: carpeta, miniatura (imágenes) o documento.+// Icon of an entry: folder, thumbnail (images) or document.export function EntryIcon({ e, size, dark, thumb = true }) {if (e.Icon) return <e.Icon size={size} />;const kind = kindOf(e);@@ -46,7 +46,7 @@ export function EntryIcon({ e, size, dark, thumb = true }) {</View>);}- // medios (M9): miniaturas de videos, carátulas y formatos que no lee stb (WebP, HEIC, AVIF), por lord-media+ // media (M9): video thumbnails, covers and formats stb cannot read (WebP, HEIC, AVIF), through lord-mediaif (thumb && size >= 32 && (kind === 'video' || kind === 'audio' || (kind === 'image' && !isImage(e) && !/\.svg$/i.test(e.name)))) {return <MediaThumb e={e} size={size} kind={kind} dark={dark} />;}diff --git a/apps/files/index.jsx b/apps/files/index.jsxindex a81602b..fa4cd44 100644--- a/apps/files/index.jsx+++ b/apps/files/index.jsx@@ -1,7 +1,7 @@-// Archivos — explorador al estilo Finder: pestañas, cuatro vistas (íconos, lista, columnas y-// galería), barra lateral con Favoritos, Ubicaciones y Etiquetas, Papelera de freedesktop,-// Vista rápida, Ver información, copiar/cortar/pegar, arrastrar y soltar, y búsqueda.-// Las operaciones de disco van por lord.fs (server/src/fsops.c); ver docs/FILES.md.+// Files — a Finder-style browser: tabs, four views (icons, list, columns and gallery), a sidebar+// with Favorites, Locations and Tags, the freedesktop Trash, Quick Look, Get Info,+// copy/cut/paste, drag and drop, and search.+// Disk operations go through lord.fs (server/src/fsops.c); see docs/FILES.md.import {View, Text, useTheme, useAppWindow, useKeyboard, useStore, useLauncherApps, addListener, wm, fs, clipboard, archive, warmDocs,formatBytes, t as tr, ScrollView, Toolbar, ToolbarButton, ToolbarGroup, SearchField, Hairline, direction, spacing, typeScale,@@ -34,7 +34,7 @@ const VIEW_GLYPH = { icons: '▦', list: '≡', columns: '◫', gallery: '▣' }const SIDEBAR_W = 200;let tabSeq = 1;const newTab = (loc, from) => ({ id: tabSeq++, loc, back: [], fwd: [], view: from?.view || 'icons', sort: from?.sort || { by: 'name', desc: false }, group: from?.group || 'none', chain: [] });-// Estado de cada ventana: sobrevive a que la interfaz se vuelva a montar (cambio de idioma).+// State of each window: it survives the interface being remounted (a language change).const winStates = new Map();const homeLoc = () => ({ type: 'dir', path: fs.home() });@@ -110,7 +110,7 @@ function ScopeChip({ label, on, onClick, t }) {);}-// ---- la ventana ----+// ---- the window ----export default function Files() {const t = useTheme();@@ -145,7 +145,7 @@ export default function Files() {const [drag, setDrag] = useState(null); // { paths, x, y, alt }const [dropTarget, setDropTarget] = useState(null);const [volumes, setVolumes] = useState(() => fs.volumes());- useEffect(() => { setTimeout(warmDocs, 800); }, []); // Vista rápida de PDF sin esperar al ayudante+ useEffect(() => { setTimeout(warmDocs, 800); }, []); // PDF Quick Look without waiting for the helperconst [msg, setMsg] = useState(null);const root = useRef(null);const press = useRef(null);@@ -157,7 +157,7 @@ export default function Files() {const [entries, error] = useMemo(() => {try { return [loadEntries(loc, { hidden, launcherApps }), null]; } catch (e) { return [[], e.message]; }}, [loc.type, loc.path, loc.color, loc.query, loc.root, loc.inner, hidden, version, tags, launcherApps, arcVer]);- // Recientes y la Papelera van por fecha (lo más nuevo arriba), como en el Finder, salvo que se elija otro orden+ // Recents and the Trash go by date (newest first), as in the Finder, unless another order is chosenconst sortBy = (loc.type === 'recent' || loc.type === 'trash') && !tab.sortChosen ? { by: 'date', desc: true } : tab.sort;const sorted = useMemo(() => sortEntries(entries, sortBy), [entries, sortBy.by, sortBy.desc]);const groups = useMemo(() => groupEntries(sorted, tab.group, tr), [sorted, tab.group]);@@ -178,7 +178,7 @@ export default function Files() {if (curDir && curDir !== '/' && curDir !== fs.home()) navigate({ type: 'dir', path: fs.parent(curDir) || '/' });};- // otras apps abren una carpeta: wm.open('files', { args: { path } })+ // other apps open a folder: wm.open('files', { args: { path } })useEffect(() => { const l = argLoc(args); if (l && args?.nonce && saved) navigate(l); if (args?.nonce && saved && argView(args)) patchTab({ view: argView(args) }); }, [args?.nonce]);useEffect(() => { const id = setInterval(() => setVolumes(fs.volumes()), 4000); return () => clearInterval(id); }, []);useEffect(() => { const id = setTimeout(() => setDebounced(query.trim()), 280); return () => clearTimeout(id); }, [query]);@@ -192,8 +192,8 @@ export default function Files() {const local = (ev) => (root.current ? ev.local(root.current) : { x: ev.x, y: ev.y });const bounds = () => { const l = root.current ? lord.getLayout(root.current.id) : [0, 0, 800, 600]; return { w: l[2], h: l[3] }; };- // ---- acciones ----- const report = (e) => { console.log(`archivos: ${e?.message || e}`); setMsg(String(e?.message || e)); };+ // ---- actions ----+ const report = (e) => { console.log(`files: ${e?.message || e}`); setMsg(String(e?.message || e)); };const newFolder = (withPaths) => {if (!curDir) return;const name = freeName(curDir, tr('files.newFolder'));@@ -215,8 +215,8 @@ export default function Files() {const to = `${fs.parent(r.path)}/${name}`;try { fs.rename(r.path, to); moveTags(r.path, to); bump(); setSelected(new Set([to])); } catch (e) { report(e); }};- // las acciones reciben las rutas a usar (el menú contextual las fija al abrirse: la selección- // de ese momento, o el elemento del clic derecho si no estaba seleccionado)+ // actions receive the paths to use (the context menu fixes them when it opens: the selection+ // at that moment, or the right-clicked item if it was not selected)const askDelete = (paths = selPaths) => setConfirm({ text: tr('files.confirm.delete', { count: paths.length }), detail: tr('files.confirm.cantUndo'), ok: tr('files.menu.deleteNow'),run: () => { for (const p of paths) { try { fs.removeFromTrash(p); } catch (err) { report(err); } } bump(); } });const askEmpty = () => setConfirm({ text: tr('files.confirm.empty'), detail: tr('files.confirm.cantUndo'), ok: tr('files.menu.emptyTrash'),@@ -232,7 +232,7 @@ export default function Files() {const duplicate = (paths = selPaths) => { if (curDir && paths.length) transfer(paths, curDir, false); };const doPaste = () => { if (curDir) paste(curDir); };const ctx = { navigate, linuxApps: launcherApps, t: tr, quickLook: (e) => { setSelected(new Set([e.path])); setQuick(true); },- openArc: (e) => { setMsg(tr('docs.opening', { name: e.name })); extractEntry(e).then((real) => openEntry({ name: e.name, path: real, size: e.size, mtime: e.mtime }, ctx)).catch((err) => setMsg(tr('docs.extractError', { name: e.name, error: err.code || err.message }))); } };+ openArc: (e) => { setMsg(tr('docs.opening', { name: e.name })); extractEntry(e).then((real) => openEntry({ name: e.name, path: real, size: e.size, mtime: e.mtime }, ctx)).catch((err) => setMsg(tr('docs.extractError', { name: e.name, error: err.message }))); } };const arcReport = (m) => setMsg(m);const open = (e) => { if (e.trash) { setSelected(new Set([e.path])); setQuick(true); return; } openEntry(e, ctx); };const openSel = (list = sel) => { for (const e of list.slice(0, 8)) open(e); };@@ -245,7 +245,7 @@ export default function Files() {const setView = (view) => patchTab({ view });const setSort = (by) => patchTab((x) => ({ sortChosen: true, sort: { by, desc: x.sort.by === by ? !x.sort.desc : by === 'date' || by === 'size' } }));- // ---- selección ----+ // ---- selection ----const onItemDown = (e, ev) => {if (renaming && renaming.path !== e.path) commitRename();if (ev.button === 2) return;@@ -259,7 +259,7 @@ export default function Files() {if (!e.app && loc.type !== 'trash') press.current = { paths: next.has(e.path) ? [...next] : [e.path], x: ev.x, y: ev.y };};- // ---- arrastrar y soltar (⌥ copia; si no, mueve) ----+ // ---- drag and drop (⌥ copies; otherwise it moves) ----const dropOf = (inst) => { for (let n = inst; n; n = n.parent) { if (n.props?.dropPath) return n.props.dropPath; if (n.props?.dropTrash) return 'trash:'; } return null; };useEffect(() => {const mv = addListener('pointermove', (e) => {@@ -284,7 +284,7 @@ export default function Files() {return () => { mv(); up(); };}, []);- // ---- menús contextuales ----+ // ---- context menus ----const tagSwatches = (paths) => ({ swatches: Object.entries(TAG_COLORS).map(([color, hex]) => ({ color, hex, on: paths.every((p) => (tags[p] || []).includes(color)), onClick: () => toggleTag(paths, color) })) });function itemMenu(e) {const paths = selected.has(e.path) ? selPaths : [e.path];@@ -295,11 +295,11 @@ export default function Files() {}if (e.app) return [{ label: tr('files.menu.open'), onClick: () => open(e) }];if (e.arc) {- // adentro de un comprimido: abrir, ver y extraer (no se puede modificar)+ // inside an archive: open, view and extract (it cannot be modified)return [{ label: tr('files.menu.open'), onClick: () => open(e) }, { label: tr('files.menu.quickLook'), hint: '␣', onClick: () => setQuick(true) }, '-',{ label: tr('docs.extractSelected', { count: list.length }), onClick: () => { const dir = fs.parent(e.arc.file); const name = freeName(dir, archive.stem(fs.basename(e.arc.file)));setMsg(tr('docs.extracting', { name: fs.basename(e.arc.file) }));- archive.extract(e.arc.file, `${dir}/${name}`, { only: list.map((x) => x.arc.inner) }).then((r) => { bump(); setMsg(tr('docs.extracted', { name, count: r.files })); }).catch((err) => setMsg(tr('docs.extractError', { name, error: err.code || err.message }))); } }];+ archive.extract(e.arc.file, `${dir}/${name}`, { only: list.map((x) => x.arc.inner) }).then((r) => { bump(); setMsg(tr('docs.extracted', { name, count: r.files })); }).catch((err) => setMsg(tr('docs.extractError', { name, error: err.message }))); } }];}const openers = openersFor(e, launcherApps, tr);return [@@ -309,7 +309,7 @@ export default function Files() {'-',{ label: tr('files.menu.trash'), hint: '❖⌫', onClick: () => toTrash(paths) },'-',- // comprimir y extraer (M9, lord-doc)+ // compress and extract (M9, lord-doc)...(curDir && list.length === 1 && isArchiveFile(e) ? [{ label: tr('docs.extractHere'), onClick: () => extractHere(e, arcReport, tr) }] : []),...(curDir ? [{ label: list.length === 1 ? tr('docs.compressOne', { name: e.name }) : tr('docs.compressMany', { count: list.length }), onClick: () => compress(paths, curDir, arcReport, tr) }] : []),'-',@@ -348,7 +348,7 @@ export default function Files() {};const onBgContext = (ev) => { setSelected(new Set()); const p = local(ev); setMenu({ x: p.x, y: p.y, items: bgMenu() }); };- // ---- teclado ----+ // ---- keyboard ----const cols = () => { const w = root.current ? lord.getLayout(root.current.id)[2] - SIDEBAR_W : 600; return Math.max(1, Math.floor((w - 24 + 8) / 108)); };const moveSel = (d, ev) => {if (!flat.length) return;@@ -398,7 +398,7 @@ export default function Files() {if (e.key === 'ArrowUp') { moveSel(-grid, e); return; }if (e.key === 'Home') { if (flat[0]) setSelected(new Set([flat[0].path])); return; }if (e.key === 'End') { if (flat.length) setSelected(new Set([flat[flat.length - 1].path])); return; }- // escribir el comienzo de un nombre lo selecciona+ // typing the start of a name selects itif (e.char && !mod && e.char.trim()) {const now = Date.now();const txt = (now - typed.current.at < 900 ? typed.current.text : '') + e.char.toLowerCase();@@ -408,7 +408,7 @@ export default function Files() {}});- // ---- menús de la app (barra de menú del tema) ----+ // ---- app menus (the theme's menu bar) ----useEffect(() => {wm.setMenus(wid, [{ label: tr('files.menu.file'), items: [@@ -445,7 +445,7 @@ export default function Files() {]);}, [tab.view, tab.back.length, tab.fwd.length, tab.loc, hidden, sel.length, clip, curDir, active, tabs.length]);- // ---- vista ----+ // ---- view ----const cut = new Set(clip?.mode === 'cut' ? clip.paths : []);const viewCtx = {selected, cut, renaming, dropTarget, hidden, expanded, showFolder: loc.type === 'search' || loc.type === 'recent' || loc.type === 'tag',@@ -456,7 +456,7 @@ export default function Files() {isDir: (p) => { const e = byPath.get(p); if (e) return e.dir; try { return lord.fs.stat(p).dir; } catch (err) { return false; } },entryAt: (p) => byPath.get(p) || (() => { try { const s = lord.fs.stat(p); return { name: s.name, path: s.path, dir: s.dir, size: s.size, mtime: s.mtime }; } catch (err) { return null; } })(),};- // columnas solo en carpetas; en los demás lugares, la lista+ // columns only in folders; elsewhere, the listconst view = tab.view === 'columns' && loc.type !== 'dir' ? 'list' : tab.view;const entriesOf = (dir) => { try { return lord.fs.list(dir).filter((x) => hidden || !x.name.startsWith('.')).map((x) => ({ ...x, path: `${dir}/${x.name}` })); } catch (e) { return []; } };const freeSpace = useMemo(() => { try { return curDir ? fs.free(curDir) : null; } catch (e) { return null; } }, [curDir, version]);@@ -632,7 +632,7 @@ export default function Files() {</View></View>- {/* lo que se arrastra */}+ {/* what is being dragged */}{dragLocal && (<View style={{ position: 'absolute', left: dragLocal.x - 20, top: dragLocal.y - 20, pointerEvents: 'none', opacity: 0.85 }}>{dragEntry?.dir ? <FolderGlyph size={40} /> : <DocGlyph size={40} kind="other" ext="" dark={t.mode === 'dark'} />}diff --git a/apps/files/kinds.js b/apps/files/kinds.jsindex 2b52a1b..287874b 100644--- a/apps/files/kinds.js+++ b/apps/files/kinds.js@@ -1,4 +1,4 @@-// kinds.js — tipo de cada archivo (por la extensión), su tipo MIME y si se puede previsualizar.+// kinds.js — each file's kind (by extension), its MIME type and whether it can be previewed.const EXT = {image: ['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'ico', 'svg', 'tif', 'tiff', 'heic', 'avif'],@@ -16,7 +16,7 @@ const EXT = {const BY_EXT = new Map();for (const [kind, list] of Object.entries(EXT)) for (const e of list) BY_EXT.set(e, kind);-// Nombres sin extensión que son texto (Makefile, README…).+// Extensionless names that are text (Makefile, README…).const TEXT_NAMES = /^(makefile|dockerfile|readme|license|copying|authors|changelog|todo|news|install|\.bashrc|\.profile|\.zshrc|\.gitignore|\.editorconfig)$/i;export function extOf(name) {@@ -31,7 +31,7 @@ export function kindOf(e) {return BY_EXT.get(ext) || (TEXT_NAMES.test(e.name) ? 'text' : 'other');}-// Para «Abrir con» de las apps Linux (su MimeType en el .desktop).+// For "Open With" of Linux apps (their MimeType in the .desktop file).const MIME = {png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp', svg: 'image/svg+xml', bmp: 'image/bmp',txt: 'text/plain', md: 'text/markdown', log: 'text/plain', csv: 'text/csv', html: 'text/html', htm: 'text/html', css: 'text/css',@@ -49,7 +49,7 @@ export function mimeOf(e) {return k === 'text' || k === 'code' ? 'text/plain' : 'application/octet-stream';}-// ¿La app Linux (mimeTypes "a/b;c/*;…") abre este tipo?+// Does the Linux app (mimeTypes "a/b;c/*;…") open this type?export function appOpens(mimeTypes, mime) {if (!mimeTypes) return false;const [top] = mime.split('/');@@ -58,9 +58,9 @@ export function appOpens(mimeTypes, mime) {}export const isTextual = (e) => ['text', 'code'].includes(kindOf(e));-export const isImage = (e) => kindOf(e) === 'image' && !/\.(svg|heic|avif|tiff?|webp)$/i.test(e.name); // las que dibuja stb_image (las demás: miniatura de lord-media)+export const isImage = (e) => kindOf(e) === 'image' && !/\.(svg|heic|avif|tiff?|webp)$/i.test(e.name); // the ones stb_image draws (the rest: lord-media thumbnail)-// Color de la banda de cada tipo en el ícono de documento.+// Band color of each kind in the document icon.export const KIND_COLOR = {text: '#8e8e93', code: '#5e5ce6', pdf: '#ff3b30', archive: '#a2845e', audio: '#ff2d55', video: '#af52de',lpk: '#7d5bf0', deb: '#d70751', doc: '#0a84ff', image: '#30b0c7', other: '#8e8e93',diff --git a/apps/files/locations.js b/apps/files/locations.jsindex 2d2b483..466ce6a 100644--- a/apps/files/locations.js+++ b/apps/files/locations.js@@ -1,4 +1,4 @@-// locations.js — qué muestra cada lugar de la barra lateral y cómo se ordena y agrupa.+// locations.js — what each sidebar place shows and how it is sorted and grouped.// { type: 'dir', path } | { type: 'recent' } | { type: 'apps' } | { type: 'trash' }// | { type: 'tag', color } | { type: 'search', root, query }import { fs } from '@lordos/sdk';@@ -10,7 +10,7 @@ export const sameLoc = (a, b) => a && b && a.type === b.type && a.path === b.patconst norm = (dir) => (e) => ({ ...e, path: `${dir === '/' ? '' : dir}/${e.name}` });-// Entradas de un lugar (sin ordenar). hidden: mostrar los que empiezan con punto.+// Entries of a place (unsorted). hidden: show the ones that start with a dot.export function loadEntries(loc, { hidden, launcherApps }) {switch (loc.type) {case 'dir': return lord.fs.list(loc.path).filter((e) => hidden || !e.name.startsWith('.')).map(norm(loc.path));@@ -22,7 +22,7 @@ export function loadEntries(loc, { hidden, launcherApps }) {const out = [];for (const [p, colors] of Object.entries(all)) {if (!colors.includes(loc.color)) continue;- try { const s = fs.stat(p); out.push({ name: s.name, path: s.path, dir: s.dir, size: s.size, mtime: s.mtime }); } catch (e) { /* ya no existe */ }+ try { const s = fs.stat(p); out.push({ name: s.name, path: s.path, dir: s.dir, size: s.size, mtime: s.mtime }); } catch (e) { /* no longer exists */ }}return out;}@@ -38,7 +38,7 @@ export function sortEntries(list, sort) {const dir = sort.desc ? -1 : 1;const key = sort.by;const cmp = (a, b) => {- if (a.dir !== b.dir && key !== 'kind') return a.dir ? -1 : 1; // carpetas primero+ if (a.dir !== b.dir && key !== 'kind') return a.dir ? -1 : 1; // folders firstlet r = 0;if (key === 'date') r = (a.mtime || 0) - (b.mtime || 0);else if (key === 'size') r = (a.dir ? -1 : a.size) - (b.dir ? -1 : b.size);@@ -49,7 +49,7 @@ export function sortEntries(list, sort) {return [...list].sort(cmp);}-// Grupos: [{ key, label, items }] (un solo grupo sin título si group = 'none').+// Groups: [{ key, label, items }] (a single untitled group if group = 'none').export function groupEntries(list, group, t) {if (group === 'none') return [{ key: 'all', label: '', items: list }];const buckets = new Map();@@ -68,20 +68,20 @@ export function groupEntries(list, group, t) {}const order = { date: ['today', 'week', 'month', 'year', 'older'], size: ['folders', 'small', 'medium', 'large', 'huge'] }[group];const label = (k) => t(`files.group.${group}.${k}`);- // por tipo: las carpetas primero y después por el nombre del tipo+ // by kind: folders first, then by kind nameconst keys = order ? order.filter((k) => buckets.has(k)): [...buckets.keys()].sort((a, b) => (a === 'folder' ? -1 : b === 'folder' ? 1 : collator(label(a), label(b))));return keys.map((k) => ({ key: k, label: label(k), items: buckets.get(k) }));}-// Carpetas del usuario (xdg-user-dirs ya trae los nombres traducidos por el sistema).+// User folders (xdg-user-dirs already provides the names translated by the system).const XDG = [['DESKTOP', 'desktop', ['Escritorio', 'Desktop', 'Área de Trabalho']], ['DOCUMENTS', 'documents', ['Documentos', 'Documents']],['DOWNLOAD', 'downloads', ['Descargas', 'Downloads', 'Transferências']], ['PICTURES', 'pictures', ['Imágenes', 'Pictures', 'Imagens']],['MUSIC', 'music', ['Música', 'Music']], ['VIDEOS', 'videos', ['Videos', 'Videos', 'Vídeos']]];export function userDirs() {const home = fs.home();let conf = '';- try { conf = fs.read('.config/user-dirs.dirs'); } catch (e) { /* sin xdg-user-dirs */ }+ try { conf = fs.read('.config/user-dirs.dirs'); } catch (e) { /* no xdg-user-dirs */ }let existing;try { existing = new Set(lord.fs.list(home).filter((e) => e.dir).map((e) => e.name)); } catch (e) { existing = new Set(); }const out = [];diff --git a/apps/files/manifest.json b/apps/files/manifest.jsonindex e2a6bb8..372ce8b 100644--- a/apps/files/manifest.json+++ b/apps/files/manifest.json@@ -1,7 +1,7 @@{"id": "files",- "name": "Archivos",- "description": "Explorador de archivos al estilo Finder: pestañas, vistas, Papelera y Vista rápida",+ "name": "Files",+ "description": "Finder-style file browser: tabs, views, Trash and Quick Look","size": [960,600diff --git a/apps/files/ops.js b/apps/files/ops.jsindex 7f9388c..30ece82 100644--- a/apps/files/ops.js+++ b/apps/files/ops.js@@ -1,18 +1,18 @@-// ops.js — lo que comparten las ventanas de Archivos: portapapeles de archivos, tareas de-// copia en curso, etiquetas de colores y abrir archivos con la app que corresponde.-import { createStore, fs, wm, launchApp, archive, defaultOpenerId, nativeOf } from '@lordos/sdk';+// ops.js — what the Files windows share: the file clipboard, copy jobs in progress, color tags+// and opening files with the right app.+import { createStore, fs, wm, launchApp, archive, defaultOpenerId, nativeOf, errorText } from '@lordos/sdk';import { kindOf, mimeOf, appOpens, isTextual, isImage } from './kinds.js';-// Cambia cada vez que algo cambió en disco (copia terminada, papelera…): las vistas se recargan.+// Changes every time something changed on disk (a copy finished, the trash…): the views reload.export const fsVersion = createStore(0);export const bump = () => fsVersion.set((v) => v + 1);-// ---- portapapeles de archivos (aparte del de texto) ----+// ---- file clipboard (separate from the text one) ----export const fileClipboard = createStore(null); // { mode: 'copy' | 'cut', paths: [] }export const copyFiles = (paths) => fileClipboard.set({ mode: 'copy', paths });export const cutFiles = (paths) => fileClipboard.set({ mode: 'cut', paths });-// Nombre libre en una carpeta: "foto.png" → "foto 2.png", "foto 3.png"…+// Free name in a folder: "photo.png" → "photo 2.png", "photo 3.png"…export function freeName(dir, name, existing) {const taken = existing || new Set(lord.fs.list(dir).map((e) => e.name));if (!taken.has(name)) return name;@@ -25,7 +25,7 @@ export function freeName(dir, name, existing) {return `${stem} ${Date.now()}${ext}`;}-// ---- tareas de copia / movimiento (hilos del servidor) ----+// ---- copy / move jobs (server threads) ----export const jobState = createStore([]); // [{ id, src, dst, move, done, bytes, total, … }]let polling = null;function poll() {@@ -33,7 +33,7 @@ function poll() {const done = list.filter((j) => j.done);for (const j of done) {fs.forgetJob(j.id);- if (j.failed) jobErrors.set((e) => [...e, `${fs.basename(j.src)}: ${j.error}`].slice(-5));+ if (j.failed) jobErrors.set((e) => [...e, `${fs.basename(j.src)}: ${errorText(j.error)}`].slice(-5));}if (done.length) bump();const running = list.filter((j) => !j.done);@@ -43,13 +43,13 @@ function poll() {export const jobErrors = createStore([]);function watchJobs() { if (!polling) polling = setInterval(poll, 250); poll(); }-// Copiar o mover varias rutas a una carpeta. Copiar en el mismo lugar = duplicar con nombre libre.+// Copy or move several paths to a folder. Copying to the same place = duplicate with a free name.export function transfer(paths, destDir, move) {const existing = new Set(lord.fs.list(destDir).map((e) => e.name));const errors = [];for (const p of paths) {const name = fs.basename(p);- if (move && fs.parent(p) === destDir) continue; // ya está ahí+ if (move && fs.parent(p) === destDir) continue; // already thereif (move && (destDir === p || destDir.startsWith(`${p}/`))) { errors.push(name); continue; }const target = freeName(destDir, name, existing);existing.add(target);@@ -70,7 +70,7 @@ export function paste(destDir) {if (c.mode === 'cut') fileClipboard.set(null);}-// ---- etiquetas (~/.local/share/lordos/tags.json: ruta → [colores]) ----+// ---- tags (~/.local/share/lordos/tags.json: path → [colors]) ----const TAGS_FILE = '.local/share/lordos/tags.json';export const tagStore = createStore((() => {try { return JSON.parse(fs.read(TAGS_FILE)); } catch (e) { return {}; }@@ -85,29 +85,29 @@ export function toggleTag(paths, color) {if (cur.size) all[p] = [...cur]; else delete all[p];}tagStore.set(all);- try { fs.mkdir('.local/share/lordos'); fs.write(TAGS_FILE, JSON.stringify(all, null, 1)); } catch (e) { /* sin disco */ }+ try { fs.mkdir('.local/share/lordos'); fs.write(TAGS_FILE, JSON.stringify(all, null, 1)); } catch (e) { /* no disk */ }}-// Mover o renombrar conserva las etiquetas.+// Moving or renaming keeps the tags.export function moveTags(from, to) {const all = tagStore.get();if (!all[from]) return;const next = { ...all, [to]: all[from] };delete next[from];tagStore.set(next);- try { fs.write(TAGS_FILE, JSON.stringify(next, null, 1)); } catch (e) { /* sin disco */ }+ try { fs.write(TAGS_FILE, JSON.stringify(next, null, 1)); } catch (e) { /* no disk */ }}-// ---- abrir ----+// ---- open -----// Apps que abren una entrada: [{ id, label, run }] (la primera es la de siempre).+// Apps that open an entry: [{ id, label, run }] (the first one is the default).export function openersFor(e, linuxApps, t) {const out = [];const k = kindOf(e);if (k === 'lpk' || k === 'deb') out.push({ id: 'store', label: t('apps.store'), run: () => wm.open('store', { args: { install: e.path } }) });- // documentos (M9): PDF en el Visor de PDF y fuentes en Tipografías+ // documents (M9): PDFs in the PDF Viewer and fonts in Fontsif (k === 'pdf') out.push({ id: 'pdf', label: t('apps.pdf'), run: () => wm.open('pdf', { new: true, args: { path: e.path } }) });if (/\.(ttf|otf|ttc|otc)$/i.test(e.name)) out.push({ id: 'fonts', label: t('apps.fonts'), run: () => wm.open('fonts', { args: { path: e.path } }) });- // medios (M9): imágenes en Fotos; audio y video en el Reproductor (son los de siempre)+ // media (M9): images in Photos; audio and video in the Player (the defaults)if (k === 'image') out.push({ id: 'photos', label: t('apps.photos'), run: () => wm.open('photos', { new: true, args: { path: e.path } }) });if (k === 'audio' || k === 'video') out.push({ id: 'player', label: t('apps.player'), run: () => wm.open('player', { args: { path: e.path } }) });if (isTextual(e) || k === 'other') out.push({ id: 'editor', label: t('apps.editor'), run: () => wm.open('editor', { args: { path: e.path } }) });@@ -129,12 +129,12 @@ export function openersFor(e, linuxApps, t) {export function openEntry(e, ctx) {if (e.app) { launchApp(e.id); return; }- // comprimidos (M9): se miran por dentro como una carpeta; lo de adentro se extrae a la caché al abrirlo+ // archives (M9): browsed like a folder; what is inside is extracted to the cache when openedif (e.arc) { if (e.dir) ctx.navigate({ type: 'archive', path: e.arc.file, inner: e.arc.inner }); else ctx.openArc(e); return; }if (e.dir) { ctx.navigate({ type: 'dir', path: e.path }); return; }if (!e.trash && archive.isArchive(e.name)) { ctx.navigate({ type: 'archive', path: e.path, inner: '' }); return; }const list = openersFor(e, ctx.linuxApps, ctx.t);- if (isImage(e) && !list.some((o) => o.id !== 'editor')) { ctx.quickLook(e); return; } // sin visor: Vista rápida+ if (isImage(e) && !list.some((o) => o.id !== 'editor')) { ctx.quickLook(e); return; } // no viewer: Quick Lookif (list.length) list[0].run();else ctx.quickLook(e);}diff --git a/apps/files/panels.jsx b/apps/files/panels.jsxindex 02d1aa2..9ca4d93 100644--- a/apps/files/panels.jsx+++ b/apps/files/panels.jsx@@ -1,5 +1,5 @@-// panels.jsx — menú contextual (con submenús), Vista rápida, Ver información y confirmar.-// Todos se dibujan adentro de la ventana, con coordenadas relativas a ella.+// panels.jsx — context menu (with submenus), Quick Look, Get Info and confirm.+// All are drawn inside the window, with coordinates relative to it.import { View, Text, Button, ToolbarButton, Hairline, useTheme, formatBytes, formatDate, formatTime, addListener, direction, typeScale, spacing, t as tr } from '@lordos/sdk';import { useEffect, useRef, useState } from 'react';import { Preview, kindLabel } from './views.jsx';@@ -50,7 +50,7 @@ function MenuBox({ items, x, y, width, onClose, onSub, boxRef, bounds }) {);}-// Menú contextual: items [{ label, onClick, hint, checked, disabled, danger, submenu } | '-' | { header } | { swatches }]+// Context menu: items [{ label, onClick, hint, checked, disabled, danger, submenu } | '-' | { header } | { swatches }]export function ContextMenu({ x, y, items, onClose, bounds }) {const ref = useRef(null), subRef = useRef(null);const [sub, setSub] = useState(null);@@ -103,7 +103,7 @@ function Row({ k, v, t }) {);}-// Ver información (❖I): ficha del archivo; el tamaño de las carpetas se calcula acotado.+// Get Info (❖I): the file's card; folder sizes are computed with a bound.export function InfoPanel({ e, onClose, openers }) {const t = useTheme();const [st, setSt] = useState(null);@@ -113,7 +113,7 @@ export function InfoPanel({ e, onClose, openers }) {if (!e || e.app) return undefined;try { setSt(lord.fs.stat(e.path)); } catch (err) { setSt({ error: err.message }); }if (!e.dir) return undefined;- const id = setTimeout(() => { try { setDu(lord.fs.du(e.path, 900)); } catch (err) { /* sin permiso */ } }, 30);+ const id = setTimeout(() => { try { setDu(lord.fs.du(e.path, 900)); } catch (err) { /* no permission */ } }, 30);return () => clearTimeout(id);}, [e?.path]);if (!e) return null;diff --git a/apps/files/quicklook.jsx b/apps/files/quicklook.jsxindex 273cb22..e2b6a08 100644--- a/apps/files/quicklook.jsx+++ b/apps/files/quicklook.jsx@@ -1,7 +1,7 @@-// quicklook.jsx — contenido de la Vista rápida (Espacio): imagen, primera página de un PDF,-// texto o código, muestra de una fuente, lo que hay adentro de un comprimido y, si el agente de-// medios lo ofrece (media.poster), un cuadro del video o la tapa de un audio. Lo que viene de-// afuera (PDF, fuentes, comprimidos) lo abre el ayudante encerrado lord-doc.+// quicklook.jsx — Quick Look contents (Space): an image, the first page of a PDF, text or code,+// a font sample, what is inside an archive and, if the media agent offers it (media.poster), a+// video frame or an audio cover. What comes from outside (PDFs, fonts, archives) is opened by the+// confined helper lord-doc.import * as sdk from '@lordos/sdk';import { View, Text, Image, useTheme, formatBytes, DocImage, releaseImage, pdfThumb, fontSample, archive, warmDocs, t as tr } from '@lordos/sdk';import { useEffect, useRef, useState } from 'react';@@ -12,8 +12,8 @@ import { extractEntry } from './archive.js';const isFont = (e) => /^(ttf|otf|ttc|otc)$/.test(extOf(e.name));-// medición: desde que se abre la Vista rápida hasta tener el contenido (docs/DOCUMENTS.md,-// «Rendimiento»). La marca de inicio se toma al dibujar por primera vez, no en un efecto.+// measurement: from opening Quick Look until the content is there (docs/DOCUMENTS.md,+// "Performance"). The start mark is taken on the first draw, not in an effect.function useTiming(e, ready) {const t0 = useRef(null);const path = useRef(null);@@ -21,12 +21,12 @@ function useTiming(e, ready) {const done = useRef(null);if (ready && done.current !== e?.path) {done.current = e?.path;- console.log(`vista-rapida: ${kindOf(e)} ${e.name} en ${Date.now() - t0.current} ms`);+ console.log(`quick-look: ${kindOf(e)} ${e.name} in ${Date.now() - t0.current} ms`);}}-// pedido asincrónico que devuelve una imagen de lord-doc (se libera al cambiar). Se manda al-// dibujar, no en un efecto: así el ayudante trabaja mientras se pinta el panel.+// asynchronous request that returns an image from lord-doc (released on change). It is sent while+// drawing, not in an effect: so the helper works while the panel is painted.function useDocImage(key, make) {const [, force] = useState(0);const cur = useRef(null);@@ -51,7 +51,7 @@ function Footer({ e, th, extra }) {}function PdfLook({ e, path, th }) {- // se pide enseguida (sin esperar a medir el panel) y se muestra ajustada al lugar que haya+ // requested right away (without waiting to measure the panel) and shown fitted to the space there isconst [img, err] = useDocImage(path, () => pdfThumb(path, { width: 400, height: 480 }));useTiming(e, !!img || !!err);return (@@ -101,7 +101,7 @@ function ArchiveLook({ e, th }) {);}-// cuadro de un video o tapa de un audio: solo si el SDK trae media.poster (agente de medios)+// a video frame or an audio cover: only if the SDK has media.poster (media agent)function MediaLook({ e, th }) {const poster = sdk.media && typeof sdk.media.poster === 'function' ? sdk.media.poster : null;const [px, setPx] = useState(null);@@ -135,11 +135,11 @@ export function QuickContent({ e }) {const th = useTheme();const [real, setReal] = useState(null);const [err, setErr] = useState(null);- // un archivo de adentro de un comprimido: se extrae solo ese, a la caché+ // a file inside an archive: only that one is extracted, to the cacheuseEffect(() => {setReal(null); setErr(null);if (!e?.arc || e.dir) return;- extractEntry(e).then(setReal).catch((x) => setErr(x.code || x.message));+ extractEntry(e).then(setReal).catch((x) => setErr(x.message));}, [e?.path]);if (!e) return null;if (e.arc && !e.dir) {diff --git a/apps/files/views.jsx b/apps/files/views.jsxindex 9914c99..4bc6408 100644--- a/apps/files/views.jsx+++ b/apps/files/views.jsx@@ -1,5 +1,5 @@-// views.jsx — las cuatro vistas de Archivos: íconos (tarjetas), lista (con carpetas que se-// despliegan), columnas (Miller, con vista previa) y galería.+// views.jsx — the four Files views: icons (cards), list (with expandable folders),+// columns (Miller, with a preview) and gallery.import { View, Text, Image, TextInput, ScrollView, EmptyState, useTheme, direction, formatBytes, formatDate, formatTime, typeScale, t as tr } from '@lordos/sdk';import { useEffect, useState } from 'react';import { EntryIcon, TagDots } from './glyphs.jsx';@@ -8,11 +8,11 @@ import { tagsOf } from './ops.js';import { sortEntries } from './locations.js';const when = (ms) => { if (!ms) return '—'; const d = new Date(ms); return `${formatDate(d, 'numeric')} ${formatTime(d)}`; };-// carpeta de un resultado de búsqueda o de Recientes (el último tramo de la ruta)+// folder of a search or Recents result (the last segment of the path)const where = (p) => { const parts = String(p).split('/'); return parts[parts.length - 2] || '/'; };export const kindLabel = (e) => (e.app ? tr('files.kind.app') : tr(`files.kind.${kindOf(e)}`));-// Nombre, o el campo para renombrar en el lugar.+// Name, or the field for renaming in place.function Name({ e, ctx, center, color, lines = 1 }) {if (ctx.renaming?.path === e.path) {return (@@ -24,7 +24,7 @@ function Name({ e, ctx, center, color, lines = 1 }) {}return (<Text style={{ fontSize: center ? 12 : 13, color, textAlign: center ? 'center' : 'start', whiteSpace: lines === 1 ? 'nowrap' : 'normal',- overflow: 'hidden', maxHeight: lines * 16, lineHeight: 16 }}>{e.name}</Text>+ overflow: 'hidden', maxHeight: lines * 16, lineHeight: 16, textOverflow: 'ellipsis', numberOfLines: lines }}>{e.name}</Text>);}@@ -50,7 +50,7 @@ function GroupTitle({ g, t }) {);}-// ---- íconos ----+// ---- icons ----export function IconView({ groups, ctx }) {const t = useTheme();@@ -85,17 +85,17 @@ export function IconView({ groups, ctx }) {);}-// ---- lista ----+// ---- list ----const COLS = [['name', 'flex'], ['date', 150], ['size', 80], ['kind', 120]];function Header({ sort, onSort, t, showFolder }) {return (- <View style={{ flexDirection: 'row', height: 26, alignItems: 'center', paddingHorizontal: 18 }}>+ <View style={{ flexDirection: 'row', height: 27, alignItems: 'center', paddingHorizontal: 18, borderBottomWidth: 1, borderBottomColor: t.separator }}>{COLS.map(([k, w], i) => (<View key={k} onClick={() => onSort(k)} style={{ ...(w === 'flex' ? { flex: 1 } : { width: w }), height: 26, flexDirection: 'row', alignItems: 'center', gap: 4,justifyContent: k === 'size' ? 'flex-end' : 'flex-start', paddingHorizontal: w === 'flex' ? 20 : 8 }}>- {i > 0 && <View style={{ position: 'absolute', top: 6, bottom: 6, [direction() === 'rtl' ? 'right' : 'left']: 0, width: 1, backgroundColor: t.separator }} />}+ {i > 0 && <View style={{ position: 'absolute', top: 6, bottom: 6, insetInlineStart: 0, width: 1, backgroundColor: t.separator }} />}<Text style={{ fontSize: typeScale.caption, fontWeight: sort.by === k ? 600 : 500, color: sort.by === k ? t.text : t.textDim, whiteSpace: 'nowrap' }}>{tr(`files.col.${k === 'kind' && showFolder ? 'where' : k}`)}</Text>{sort.by === k && <Text style={{ fontSize: 8, color: t.textDim }}>{sort.desc ? '▼' : '▲'}</Text>}</View>@@ -124,12 +124,12 @@ function ListRows({ items, depth, ctx, t, sort, alt }) {</View><Text style={{ width: 150, paddingHorizontal: 8, fontSize: typeScale.callout, color: sel ? '#fff' : t.textDim, whiteSpace: 'nowrap', overflow: 'hidden' }}>{e.trash ? (e.deleted || '').replace('T', ' ') : when(e.mtime)}</Text><Text style={{ width: 80, paddingHorizontal: 8, fontSize: typeScale.callout, color: sel ? '#fff' : t.textDim, textAlign: 'end', whiteSpace: 'nowrap' }}>{e.dir && !e.trash ? '—' : e.app ? '' : formatBytes(e.size)}</Text>- <Text style={{ width: 120, paddingHorizontal: 8, fontSize: typeScale.callout, color: sel ? '#fff' : t.textDim, whiteSpace: 'nowrap', overflow: 'hidden' }}>{ctx.showFolder ? where(e.path) : kindLabel(e)}</Text>+ <Text style={{ width: 120, paddingHorizontal: 8, fontSize: typeScale.callout, color: sel ? '#fff' : t.textDim, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{ctx.showFolder ? where(e.path) : kindLabel(e)}</Text></View>,);if (open) {let kids = [];- try { kids = sortEntries(lord.fs.list(e.path).filter((x) => ctx.hidden || !x.name.startsWith('.')).map((x) => ({ ...x, path: `${e.path}/${x.name}` })), sort); } catch (err) { /* sin permiso */ }+ try { kids = sortEntries(lord.fs.list(e.path).filter((x) => ctx.hidden || !x.name.startsWith('.')).map((x) => ({ ...x, path: `${e.path}/${x.name}` })), sort); } catch (err) { /* no permission */ }rows.push(...ListRows({ items: kids, depth: depth + 1, ctx, t, sort, alt }));}}@@ -142,7 +142,6 @@ export function ListView({ groups, ctx, sort, onSort }) {return (<View style={{ flex: 1 }}><Header sort={sort} onSort={onSort} t={t} showFolder={ctx.showFolder} />- <View style={{ height: 1, backgroundColor: t.separator }} /><ScrollView style={{ flex: 1 }}><View style={{ paddingHorizontal: 8, paddingTop: 4, paddingBottom: 32 }}>{groups.map((g) => (@@ -158,7 +157,7 @@ export function ListView({ groups, ctx, sort, onSort }) {);}-// ---- vista previa (columnas, galería, Vista rápida) ----+// ---- preview (columns, gallery, Quick Look) ----export function Preview({ e, big = false }) {const t = useTheme();@@ -183,14 +182,14 @@ export function Preview({ e, big = false }) {);}-// ---- columnas (Miller) ----+// ---- columns (Miller) ----export function ColumnView({ root, chain, setChain, entriesOf, ctx, sort }) {const t = useTheme();const dirs = [root, ...chain.filter((p) => ctx.isDir(p))];const last = chain[chain.length - 1];const file = last && !ctx.isDir(last) ? ctx.entryAt(last) : null;- // las que entran: las últimas 3 carpetas+ // the ones that fit: the last 3 foldersconst shown = dirs.slice(-3);const offset = dirs.length - shown.length;return (@@ -229,7 +228,7 @@ export function ColumnView({ root, chain, setChain, entriesOf, ctx, sort }) {);}-// ---- galería ----+// ---- gallery ----export function GalleryView({ entries, ctx }) {const t = useTheme();@@ -239,8 +238,7 @@ export function GalleryView({ entries, ctx }) {return (<View style={{ flex: 1 }}><View style={{ flex: 1, padding: 8 }}>{cur ? <Preview e={cur} big /> : <EmptyState title={ctx.emptyText} />}</View>- <View style={{ height: 1, backgroundColor: t.separator }} />- <View style={{ height: 96, flexDirection: 'row', gap: 8, paddingHorizontal: 12, alignItems: 'center', justifyContent: 'center', direction: 'ltr', overflow: 'hidden' }}>+ <View style={{ height: 97, borderTopWidth: 1, borderTopColor: t.separator, flexDirection: 'row', gap: 8, paddingHorizontal: 12, alignItems: 'center', justifyContent: 'center', direction: 'ltr', overflow: 'hidden' }}>{entries.slice(from, from + 9).map((e) => {const sel = e === cur;return (diff --git a/apps/fonts/manifest.json b/apps/fonts/manifest.jsonindex 78d0edb..91b1b8e 100644--- a/apps/fonts/manifest.json+++ b/apps/fonts/manifest.json@@ -1,7 +1,7 @@{"id": "fonts",- "name": "Tipografías",- "description": "Visor y administrador de fuentes: muestras, tabla de caracteres, instalar y quitar fuentes del usuario",+ "name": "Fonts",+ "description": "Font viewer and manager: samples, character map, install and remove user fonts","size": [960, 620],"minSize": [640, 420],"dock": false,diff --git a/apps/help/manifest.json b/apps/help/manifest.jsonindex adf3110..1897321 100644--- a/apps/help/manifest.json+++ b/apps/help/manifest.json@@ -1,7 +1,7 @@{"id": "help",- "name": "Ayuda",- "description": "Ayuda y consejos de LordOS",+ "name": "Help",+ "description": "LordOS help and tips","size": [860,600diff --git a/apps/installer/index.jsx b/apps/installer/index.jsxindex 70e4648..dcbe65d 100644--- a/apps/installer/index.jsx+++ b/apps/installer/index.jsx@@ -4,7 +4,7 @@// (validates everything again on the root side) and install-reboot. See docs/ISO.md.import {View, Text, Button, TextInput, ScrollView, Toggle, Segmented, SearchField, Hairline, GroupBox, FormRow, useTheme, useLocale, useStore, createStore,- admin, keyboard, languages, setLanguage, formatBytes, locale, wm, useAppWindow, typeScale,+ admin, keyboard, languages, setLanguage, formatBytes, locale, wm, useAppWindow, typeScale, statusText,} from '@lordos/sdk';import { useEffect, useState } from 'react';@@ -330,7 +330,7 @@ function Install() {)}{s.error && <Text style={{ fontSize: 12, color: '#ff453a', textAlign: 'center', maxWidth: 480 }}>{s.error}</Text>}<View style={{ width: 520, gap: 2 }}>- {s.log.slice(-4).map((l, i) => <Text key={i} style={{ fontSize: 11, color: t.textDim, whiteSpace: 'nowrap', overflow: 'hidden' }}>{l}</Text>)}+ {s.log.slice(-4).map((l, i) => <Text key={i} style={{ fontSize: 11, color: t.textDim, whiteSpace: 'nowrap', overflow: 'hidden' }}>{statusText(l)}</Text>)}</View>{s.done && <Text style={{ fontSize: 12, color: t.text, maxWidth: 480, textAlign: 'center' }}>{tr('installer.done.usb')}</Text>}</View>diff --git a/apps/installer/manifest.json b/apps/installer/manifest.jsonindex a8df8d8..7b05f82 100644--- a/apps/installer/manifest.json+++ b/apps/installer/manifest.json@@ -1,7 +1,7 @@{"id": "installer",- "name": "Instalar LordOS",- "description": "Instala LordOS en el disco desde el sistema en vivo",+ "name": "Install LordOS",+ "description": "Installs LordOS to the disk from the live system","size": [760, 560],"minSize": [640, 480],"dock": false,diff --git a/apps/logs/index.jsx b/apps/logs/index.jsxindex 33ec19c..d846ea0 100644--- a/apps/logs/index.jsx+++ b/apps/logs/index.jsx@@ -52,7 +52,8 @@ export function parseLordLog(text, file) {const m = lines[i];if (!m) continue;const low = m.toLowerCase();- const p = /\b(error|err|falla|fallo|failed|abort|crash|segfault)\b/.test(low) ? 3 : /\b(aviso|warning|warn|sin |no se pudo)\b/.test(low) ? 4 : 6;+ // the Spanish words match lines written by older LordOS builds, which logged in Spanish+ const p = /\b(error|err|fail|failed|falla|fallo|abort|crash|segfault)\b/.test(low) ? 3 : /\b(warning|warn|could not|cannot|aviso|sin |no se pudo)\b/.test(low) ? 4 : 6;const src = /^([a-z][\w.-]{1,30})(\[\d+\])?:/i.exec(m);out.push({ t: 0, line: i + 1, p, id: src ? src[1] : file.replace(/\.log$/, ''), u: '', pid: -1, uid: -1, k: 0, b: '', m });}diff --git a/apps/mail/Setup.jsx b/apps/mail/Setup.jsxindex 7788646..e9ced37 100644--- a/apps/mail/Setup.jsx+++ b/apps/mail/Setup.jsx@@ -113,7 +113,7 @@ export function AccountSetup({ onClose, kind: kind0 = 'mail' }) {<Segmented options={[['mail', t('mail.setup.kindMail')], ['dav', t('mail.setup.kindDav')]]} value={kind} onChange={setKind} /><Field label={t('mail.setup.name')}><TextInput value={name} onChange={setName} placeholder={kind === 'dav' ? t('mail.setup.davNamePh') : t('mail.setup.namePh')} autoFocus /></Field>{kind === 'mail' ? (- <Field label={t('mail.setup.email')}><TextInput value={email} onChange={setEmail} placeholder="[email protected]" onSubmit={next} /></Field>+ <Field label={t('mail.setup.email')}><TextInput value={email} onChange={setEmail} placeholder={t('mail.setup.emailPh')} onSubmit={next} /></Field>) : (<><Field label={t('mail.setup.url')}><TextInput value={dav.url} onChange={(url) => setDav({ ...dav, url })} placeholder="https://cloud.example.com/remote.php/dav" /></Field>diff --git a/apps/mail/index.jsx b/apps/mail/index.jsxindex 24c70fe..780f41b 100644--- a/apps/mail/index.jsx+++ b/apps/mail/index.jsx@@ -4,17 +4,18 @@// an offline search index, and HTML turned into our own views without running anything.import {View, Text, useTheme, useStore, useAppWindow, useKeyboard, Button, TextInput, ScrollView, t, wm, fs, monthName, formatDate, formatTime,+ Toolbar, ToolbarButton, ToolbarSpacer, ToolbarDivider, SearchField, Hairline, direction, textDirection,mailRequest, onMailEvent, mailStatus, mailConfig, mailAccounts, mailAvailable, addListener, clipboard,} from '@lordos/sdk';import { useEffect, useRef, useState } from 'react';import { HtmlView, TextView } from './HtmlView.jsx';import { Compose } from './Compose.jsx';import { AccountSetup, AccountsPanel, CertDialog, PasswordPrompt, Sheet } from './Setup.jsx';-import { CATEGORY_COLORS, categoryName, listDate, fullDate, folderIcon, folderName, addrShort, formatSize, openPath, revealPath } from './util.js';+import { CATEGORY_COLORS, categoryName, listDate, fullDate, folderName, addrShort, formatSize, openPath, revealPath } from './util.js';import { quote } from './md.js';import { safeName } from './util.js';-const ROW = 76;+const ROW = 86; // sender, subject and two lines of preview, with room to breathe// ---- icon: an envelope on a blue tile (our own drawing) ----@@ -33,6 +34,76 @@ export function Icon({ size: s }) {);}+// ---- monochrome glyphs (the folder emoji are in color and ignore the theme) ----++// Shapes drawn with views: an inbox tray, an archive box, a trash can and a folder.+export function Glyph({ kind, size = 16, color }) {+ const th = useTheme();+ const c = color || th.accent;+ const s = size, line = 1.5;+ if (kind === 'tray') {+ return (+ <View style={{ width: s, height: s, justifyContent: 'center', alignItems: 'center' }}>+ <View style={{ width: s * 0.86, height: s * 0.62, borderRadius: s * 0.14, border: `${line}px solid ${c}` }}>+ <View style={{ position: 'absolute', left: 0, right: 0, top: s * 0.22, height: line, backgroundColor: c }} />+ </View>+ </View>+ );+ }+ if (kind === 'archive') {+ return (+ <View style={{ width: s, height: s, justifyContent: 'center', alignItems: 'center', gap: 1 }}>+ <View style={{ width: s * 0.9, height: s * 0.2, borderRadius: 1.5, backgroundColor: c }} />+ <View style={{ width: s * 0.76, height: s * 0.48, borderBottomLeftRadius: s * 0.1, borderBottomRightRadius: s * 0.1, border: `${line}px solid ${c}`, alignItems: 'center' }}>+ <View style={{ marginTop: s * 0.1, width: s * 0.28, height: line, backgroundColor: c }} />+ </View>+ </View>+ );+ }+ if (kind === 'trash') {+ return (+ <View style={{ width: s, height: s, justifyContent: 'center', alignItems: 'center', gap: 1 }}>+ <View style={{ width: s * 0.3, height: s * 0.1, borderTopLeftRadius: 1.5, borderTopRightRadius: 1.5, backgroundColor: c }} />+ <View style={{ width: s * 0.8, height: line, backgroundColor: c }} />+ <View style={{ width: s * 0.6, height: s * 0.54, borderBottomLeftRadius: s * 0.1, borderBottomRightRadius: s * 0.1, border: `${line}px solid ${c}` }} />+ </View>+ );+ }+ if (kind === 'folder') {+ return (+ <View style={{ width: s, height: s, justifyContent: 'center', alignItems: 'center' }}>+ <View style={{ width: s * 0.86, height: s * 0.66 }}>+ <View style={{ width: s * 0.36, height: s * 0.16, borderTopLeftRadius: s * 0.08, borderTopRightRadius: s * 0.08, backgroundColor: c }} />+ <View style={{ flex: 1, borderRadius: s * 0.1, borderTopLeftRadius: 0, border: `${line}px solid ${c}` }} />+ </View>+ </View>+ );+ }+ if (kind === 'calendar') {+ return (+ <View style={{ width: s, height: s, justifyContent: 'center', alignItems: 'center' }}>+ <View style={{ width: s * 0.8, height: s * 0.74, borderRadius: s * 0.14, border: `${line}px solid ${c}`, overflow: 'hidden' }}>+ <View style={{ height: s * 0.18, backgroundColor: c }} />+ </View>+ </View>+ );+ }+ return null;+}++// The icon of a folder: a drawn shape or a monochrome glyph.+const FOLDER_GLYPHS = { inbox: 'tray', archive: 'archive', trash: 'trash' };+const FOLDER_CHARS = { drafts: '✎', sent: '➤', junk: '⚠', all: '≡', flagged: '⚑' };+function FolderIcon({ f, color }) {+ const th = useTheme();+ const c = color || th.accent;+ const g = FOLDER_GLYPHS[f.special];+ if (g) return <Glyph kind={g} size={16} color={c} />;+ const ch = FOLDER_CHARS[f.special];+ if (ch) return <Text style={{ fontSize: f.special === 'sent' ? 12 : 13, color: c, textAlign: 'center' }}>{ch}</Text>;+ return <Glyph kind="folder" size={16} color={c} />;+}+// ---- the list ----function useSize(ref, every = 250) {@@ -52,27 +123,29 @@ function Row({ it, selected, onClick, onRightClick, cfg }) {const th = useTheme();if (!it) return <View style={{ height: ROW }} />;const unread = it.unreadN !== undefined ? it.unreadN > 0 : !it.seen;- const fg = selected ? '#fff' : th.text, dim = selected ? '#ffffffcc' : th.textDim;+ const fg = selected ? '#fff' : th.text, dim = selected ? 'rgba(255,255,255,0.8)' : th.textDim;return (- <View onClick={onClick} onContextMenu={onRightClick} style={{ height: ROW, flexDirection: 'row', paddingHorizontal: 10, paddingVertical: 8, gap: 8,- backgroundColor: selected ? th.accent : 'transparent' }}>- <View style={{ width: 8, alignItems: 'center', paddingTop: 5 }}>- {unread ? <View style={{ width: 8, height: 8, borderRadius: 4, backgroundColor: selected ? '#fff' : th.accent }} /> : null}- </View>- <View style={{ flex: 1, gap: 2, overflow: 'hidden' }}>- <View style={{ flexDirection: 'row', alignItems: 'center', gap: 6 }}>- <Text style={{ flex: 1, fontSize: 13, fontWeight: unread ? 700 : 500, color: fg, whiteSpace: 'nowrap', overflow: 'hidden' }}>{it.from || it.email || t('mail.unknownSender')}</Text>- {it.n > 1 ? <View style={{ paddingHorizontal: 5, borderRadius: 7, backgroundColor: selected ? '#ffffff33' : th.control }}><Text style={{ fontSize: 10, color: fg }}>{String(it.n)}</Text></View> : null}- {it.att ? <Text style={{ fontSize: 11, color: dim }}>📎</Text> : null}- {(it.anyFlag || it.flagged) ? <Text style={{ fontSize: 11, color: selected ? '#fff' : '#ff9f0a' }}>⚑</Text> : null}- <Text style={{ fontSize: 11, color: dim }}>{listDate(it.date)}</Text>+ <View onClick={onClick} onContextMenu={onRightClick} style={{ height: ROW, paddingHorizontal: 6, paddingVertical: 2 }}>+ <View style={{ flex: 1, flexDirection: 'row', paddingHorizontal: 8, paddingVertical: 8, gap: 6, borderRadius: 7,+ backgroundColor: selected ? th.accent : 'transparent' }}>+ <View style={{ width: 10, alignItems: 'center', paddingTop: 5 }}>+ {unread ? <View style={{ width: 8, height: 8, borderRadius: 4, backgroundColor: selected ? '#fff' : th.accent }} /> : null}</View>- <View style={{ flexDirection: 'row', alignItems: 'center', gap: 4 }}>- {(it.labels || []).map((l) => <View key={l} style={{ width: 8, height: 8, borderRadius: 4, backgroundColor: CATEGORY_COLORS[l - 1] }} />)}- {it.answered ? <Text style={{ fontSize: 11, color: dim }}>↩</Text> : null}- <Text style={{ flex: 1, fontSize: 12, fontWeight: unread ? 600 : 400, color: fg, whiteSpace: 'nowrap', overflow: 'hidden' }}>{it.subject || t('mail.noSubject')}</Text>+ <View style={{ flex: 1, gap: 1, overflow: 'hidden' }}>+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 6, height: 18 }}>+ <Text style={{ flex: 1, fontSize: 13, fontWeight: unread ? 600 : 500, color: fg, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{it.from || it.email || t('mail.unknownSender')}</Text>+ {it.n > 1 ? <View style={{ minWidth: 18, height: 15, paddingHorizontal: 5, borderRadius: 8, alignItems: 'center', justifyContent: 'center', backgroundColor: selected ? 'rgba(255,255,255,0.22)' : th.control }}><Text style={{ fontSize: 10, fontWeight: 600, color: fg }}>{String(it.n)}</Text></View> : null}+ {it.att ? <Text style={{ fontSize: 12, color: dim }}>⧉</Text> : null}+ {(it.anyFlag || it.flagged) ? <Text style={{ fontSize: 11, color: selected ? '#fff' : '#ff9f0a' }}>⚑</Text> : null}+ <Text style={{ fontSize: 11, color: dim, whiteSpace: 'nowrap' }}>{listDate(it.date)}</Text>+ </View>+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 4, height: 17 }}>+ {(it.labels || []).map((l) => <View key={l} style={{ width: 8, height: 8, borderRadius: 4, backgroundColor: CATEGORY_COLORS[l - 1], border: selected ? '1px solid #fff' : 'none' }} />)}+ {it.answered ? <Text style={{ fontSize: 11, color: dim }}>↩</Text> : null}+ <Text style={{ flex: 1, fontSize: 12, fontWeight: unread ? 600 : 400, color: fg, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{it.subject || t('mail.noSubject')}</Text>+ </View>+ <Text style={{ fontSize: 12, color: dim, overflow: 'hidden', height: 32, lineHeight: 16, numberOfLines: 2 }}>{it.preview}</Text></View>- <Text style={{ fontSize: 12, color: dim, overflow: 'hidden', height: 30, lineHeight: 15 }}>{it.preview}</Text></View>{cfg ? null : null}</View>@@ -127,7 +200,7 @@ function MessageList({ src, rev, selected, onSelect, onMenu, cfg }) {rows.push(<View key={key} style={{ position: 'absolute', left: 0, right: 0, top: i * ROW - yy }}><Row it={it} cfg={cfg} selected={!!it && selected === key} onClick={() => it && onSelect(it, i)} onRightClick={(e) => it && onMenu(it, e)} />- <View style={{ height: 1, marginLeft: 26, backgroundColor: th.separator, marginTop: -1 }} />+ <View style={{ position: 'absolute', bottom: 0, height: 1, [direction() === 'rtl' ? 'right' : 'left']: 30, [direction() === 'rtl' ? 'left' : 'right']: 14, backgroundColor: th.separator }} /></View>,);}@@ -155,7 +228,7 @@ function MessageList({ src, rev, selected, onSelect, onMenu, cfg }) {<Text style={{ fontSize: 13, color: th.textDim, textAlign: 'center' }}>{src.kind === 'search' ? t('mail.search.none') : t('mail.empty')}</Text></View>) : null}- {bar > 0 && <View onMouseDown={(e) => { drag.current = { py: e.y, y0: yy }; }} style={{ position: 'absolute', right: 2, width: 6, borderRadius: 3, height: bar,+ {bar > 0 && <View onMouseDown={(e) => { drag.current = { py: e.y, y0: yy }; }} style={{ position: 'absolute', [direction() === 'rtl' ? 'left' : 'right']: 2, width: 6, borderRadius: 3, height: bar,top: (h - bar) * (yy / (max || 1)), backgroundColor: th.mode === 'dark' ? 'rgba(255,255,255,0.3)' : 'rgba(0,0,0,0.28)' }} />}</View>);@@ -198,9 +271,9 @@ function Invite({ msg }) {<Text style={{ fontSize: 20, fontWeight: 700, color: '#222' }}>{String(new Date(ev.start).getDate())}</Text></View><View style={{ flex: 1, gap: 2 }}>- <Text style={{ fontSize: 14, fontWeight: 700, color: th.text }}>{ev.title || t('mail.invite.untitled')}</Text>+ <Text style={{ fontSize: 14, fontWeight: 600, color: th.text }}>{ev.title || t('mail.invite.untitled')}</Text><Text style={{ fontSize: 12, color: th.textDim }}>{when}</Text>- {ev.loc ? <Text style={{ fontSize: 12, color: th.textDim }}>{`📍 ${ev.loc}`}</Text> : null}+ {ev.loc ? <Text style={{ fontSize: 12, color: th.textDim }}>{ev.loc}</Text> : null}{ev.org ? <Text style={{ fontSize: 12, color: th.textDim }}>{t('mail.invite.organizer', { name: ev.org.name || ev.org.email })}</Text> : null}</View></View>@@ -246,10 +319,11 @@ function Attachments({ msg }) {return (<View style={{ flexDirection: 'row', flexWrap: 'wrap', gap: 8 }}>{atts.map((a) => (- <View key={a.idx} style={{ flexDirection: 'row', alignItems: 'center', gap: 8, padding: 8, borderRadius: 8, backgroundColor: th.control, maxWidth: 300 }}>- <Text style={{ fontSize: 20 }}>{/pdf/.test(a.type) ? '📕' : /^image/.test(a.type) ? '🖼️' : /calendar|ics/.test(a.type + a.name) ? '📅' : '📄'}</Text>- <View style={{ flex: 1 }}>- <Text onClick={() => open(a)} style={{ fontSize: 12, color: th.text, whiteSpace: 'nowrap', overflow: 'hidden' }}>{safeName(a.name)}</Text>+ <View key={a.idx} style={{ flexDirection: 'row', alignItems: 'center', gap: 8, paddingVertical: 6, paddingHorizontal: 8, borderRadius: 8, backgroundColor: th.control,+ border: `1px solid ${th.separator}`, maxWidth: 360, flexShrink: 1, minWidth: 0 }}>+ <DocGlyph name={a.name} type={a.type} />+ <View style={{ flex: 1, minWidth: 40 }}>+ <Text onClick={() => open(a)} style={{ fontSize: 12, fontWeight: 500, color: th.text, whiteSpace: 'nowrap', overflow: 'hidden' }}>{safeName(a.name)}</Text><Text style={{ fontSize: 11, color: th.textDim }}>{busy === a.idx ? t('mail.working') : formatSize(a.size)}</Text></View><Button small plain label={t('mail.att.open')} onClick={() => open(a)} />@@ -260,6 +334,19 @@ function Attachments({ msg }) {);}+// A document page with its extension on a colored band (instead of the color emoji).+function DocGlyph({ name, type }) {+ const ext = (/\.([a-z0-9]{1,4})$/i.exec(name || '') || [])[1] || '';+ const color = /pdf/.test(type) ? '#e5483f' : /^image/.test(type) ? '#30a46c' : /calendar|ics/.test(`${type}${name}`) ? '#f2463d' : /zip|compress/.test(type) ? '#8e8e93' : '#2f7cf6';+ return (+ <View style={{ width: 24, height: 30, borderRadius: 3, backgroundColor: '#ffffff', border: '1px solid rgba(0,0,0,0.15)', justifyContent: 'flex-end', overflow: 'hidden' }}>+ <View style={{ height: 11, backgroundColor: color, alignItems: 'center', justifyContent: 'center' }}>+ <Text style={{ fontSize: 7, fontWeight: 700, color: '#fff' }}>{ext.toUpperCase()}</Text>+ </View>+ </View>+ );+}+function MessageView({ msg, width, onLink, cfg, onTrustSender, collapsed, onExpand }) {const th = useTheme();const [remote, setRemote] = useState(false);@@ -276,27 +363,31 @@ function MessageView({ msg, width, onLink, cfg, onTrustSender, collapsed, onExpaconst warns = (msg.html?.links || []).filter((l) => l.w);if (collapsed) {return (- <View onClick={onExpand} style={{ padding: 10, borderRadius: 8, backgroundColor: th.control, flexDirection: 'row', gap: 8 }}>- <Text style={{ fontSize: 13, fontWeight: 600, color: th.text }}>{from.name || from.email}</Text>- <Text style={{ flex: 1, fontSize: 12, color: th.textDim, whiteSpace: 'nowrap', overflow: 'hidden' }}>{(msg.text || '').slice(0, 140).replace(/\s+/g, ' ')}</Text>+ <View onClick={onExpand} style={{ paddingVertical: 9, paddingHorizontal: 12, borderRadius: 8, backgroundColor: th.control, flexDirection: 'row', alignItems: 'center', gap: 10 }}>+ <Text style={{ fontSize: 13, fontWeight: 600, color: th.text, whiteSpace: 'nowrap' }}>{from.name || from.email}</Text>+ <Text style={{ flex: 1, fontSize: 12, color: th.textDim, whiteSpace: 'nowrap', overflow: 'hidden', direction: textDirection(msg.text || '') }}>{(msg.text || '').slice(0, 140).replace(/\s+/g, ' ')}</Text><Text style={{ fontSize: 11, color: th.textDim }}>{listDate(msg.date)}</Text></View>);}return (- <View style={{ gap: 10 }}>- <View style={{ flexDirection: 'row', gap: 10, alignItems: 'flex-start' }}>- <View style={{ width: 40, height: 40, borderRadius: 20, backgroundColor: th.accent, alignItems: 'center', justifyContent: 'center' }}>- <Text style={{ fontSize: 16, fontWeight: 700, color: '#fff' }}>{([...(from.name || from.email || '?')][0] || '?').toUpperCase()}</Text>+ <View style={{ gap: 12 }}>+ <View style={{ flexDirection: 'row', gap: 12, alignItems: 'flex-start' }}>+ <View style={{ width: 40, height: 40, borderRadius: 20, background: 'linear-gradient(180deg, #a5a5ad, #85858d)', alignItems: 'center', justifyContent: 'center' }}>+ <Text style={{ fontSize: 16, fontWeight: 600, color: '#fff' }}>{([...(from.name || from.email || '?')][0] || '?').toUpperCase()}</Text></View>- <View style={{ flex: 1, gap: 2 }}>- <Text style={{ fontSize: 14, fontWeight: 700, color: th.text }}>{from.name || from.email}</Text>- {from.name ? <Text style={{ fontSize: 11, color: th.textDim }}>{from.email}</Text> : null}+ <View style={{ flex: 1, gap: 2, overflow: 'hidden' }}>+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 10 }}>+ <Text style={{ flex: 1, fontSize: 14, fontWeight: 600, color: th.text, whiteSpace: 'nowrap', overflow: 'hidden' }}>{from.name || from.email}</Text>+ {width > 420 ? <Text style={{ fontSize: 11, color: th.textDim, whiteSpace: 'nowrap' }}>{fullDate(msg.date)}</Text> : null}+ </View>+ {from.name ? <Text style={{ fontSize: 12, color: th.textDim, whiteSpace: 'nowrap', overflow: 'hidden' }}>{from.email}</Text> : null}<Text style={{ fontSize: 12, color: th.textDim }}>{`${t('mail.to')}: ${(msg.to || []).map(addrShort).join(', ')}`}</Text>{msg.cc?.length ? <Text style={{ fontSize: 12, color: th.textDim }}>{`${t('mail.cc')}: ${msg.cc.map(addrShort).join(', ')}`}</Text> : null}+ {width > 420 ? null : <Text style={{ fontSize: 11, color: th.textDim }}>{fullDate(msg.date)}</Text>}</View>- <Text style={{ fontSize: 11, color: th.textDim }}>{fullDate(msg.date)}</Text></View>+ <View style={{ height: 1, backgroundColor: th.separator }} />{nRemote > 0 && !showRemote && (<Banner color={th.control}><Text style={{ fontSize: 12, color: th.text, flex: 1 }}>{t('mail.images.blocked', { count: nRemote })}{nTrackers ? ` ${t('mail.images.trackers', { count: nTrackers })}` : ''}</Text>@@ -364,6 +455,10 @@ function MailMain() {const [cfg, setCfg] = useState(mailConfig.get());const readingRef = useRef(null);const { w: readW } = useSize(readingRef, 400);+ const rootRef = useRef(null);+ const { w: rootW } = useSize(rootRef, 400);+ const compact = rootW > 100 && rootW < 1000; // narrower panes in small windows+ const sideW = compact ? 200 : 220, listW = compact ? 290 : 330;const accounts = cfg.accounts.filter((a) => a.kind === 'mail');useEffect(() => { setLoadErr(''); }, [JSON.stringify(src)]);@@ -519,26 +614,27 @@ function MailMain() {// ---- sidebar ----const sidebar = (- <View style={{ width: 220, backgroundColor: th.sidebarBg }}>+ <View style={{ width: sideW, backgroundColor: th.sidebarBg }}>+ <Hairline edge="end" /><ScrollView style={{ flex: 1 }}>- <View style={{ padding: 8, gap: 1 }}>- <Text style={{ fontSize: 11, fontWeight: 600, color: th.textDim, margin: 6 }}>{t('mail.favorites')}</Text>- <SideRow icon="📥" label={t('mail.unifiedInbox')} count={st.unread} selected={src.kind === 'unified' && !src.filter} onClick={() => { setSrc({ kind: 'unified' }); setQ(''); }} />- <SideRow icon="🔵" label={t('mail.unread')} selected={src.kind === 'unified' && src.filter === 'unread'} onClick={() => setSrc({ kind: 'unified', filter: 'unread' })} />+ <View style={{ paddingHorizontal: 10, paddingTop: 10, paddingBottom: 10, gap: 1 }}>+ <Caption first>{t('mail.favorites')}</Caption>+ <SideRow icon={{ kind: 'tray' }} label={t('mail.unifiedInboxShort')} count={st.unread} selected={src.kind === 'unified' && !src.filter && !src.label} onClick={() => { setSrc({ kind: 'unified' }); setQ(''); }} />+ <SideRow icon="●" label={t('mail.unread')} selected={src.kind === 'unified' && src.filter === 'unread'} onClick={() => setSrc({ kind: 'unified', filter: 'unread' })} /><SideRow icon="⚑" label={t('mail.flagged')} selected={src.kind === 'unified' && src.filter === 'flagged'} onClick={() => setSrc({ kind: 'unified', filter: 'flagged' })} />{folders.map((a) => {const status = st.accounts[a.id]?.status || a.status;const bad = st.authFailed[a.id] || status === 'auth' || status === 'cert' || status === 'offline';return (- <View key={a.id} style={{ marginTop: 10, gap: 1 }}>- <View style={{ flexDirection: 'row', alignItems: 'center', margin: 6, gap: 6 }}>+ <View key={a.id} style={{ gap: 1 }}>+ <View style={{ flexDirection: 'row', alignItems: 'center', marginHorizontal: 8, marginTop: 16, marginBottom: 4, gap: 6 }}><Text style={{ flex: 1, fontSize: 11, fontWeight: 600, color: th.textDim, whiteSpace: 'nowrap', overflow: 'hidden' }}>{a.name}</Text>{status === 'sync' || status === 'connecting' ? <Text style={{ fontSize: 10, color: th.textDim }}>⟳</Text> : null}{bad ? <Text onClick={() => setSheet(st.authFailed[a.id] || status === 'auth' ? { password: a.id } : st.certs.find((c) => c.acct === a.id) ? { cert: st.certs.find((c) => c.acct === a.id) } : 'accounts')}style={{ fontSize: 11, color: '#ff9f0a' }}>⚠</Text> : null}</View>{a.folders.filter((f) => !f.noselect).map((f) => (- <SideRow key={f.name} icon={folderIcon(f)} label={folderName(f)} count={f.special === 'drafts' ? f.total : f.special === 'sent' || f.special === 'trash' ? 0 : f.unread}+ <SideRow key={f.name} icon={{ folder: f }} label={folderName(f)} count={f.special === 'drafts' ? f.total : f.special === 'sent' || f.special === 'trash' ? 0 : f.unread}indent={f.delim && f.name.split(f.delim).length > 1 && f.special === '' ? 1 : 0}selected={src.kind === 'folder' && src.acct === a.id && src.folder === f.name} onClick={() => { setSrc({ kind: 'folder', acct: a.id, folder: f.name }); setQ(''); }} />))}@@ -549,54 +645,52 @@ function MailMain() {const s2 = st.accounts[a.id]?.status;const bad = st.authFailed[a.id] || s2 === 'auth' || s2 === 'cert' || s2 === 'offline';return (- <View key={a.id} style={{ flexDirection: 'row', alignItems: 'center', gap: 6, margin: 6, marginTop: 10 }}>- <Text style={{ fontSize: 12 }}>📅</Text>+ <View key={a.id} style={{ flexDirection: 'row', alignItems: 'center', gap: 6, marginHorizontal: 8, marginTop: 16, marginBottom: 4 }}>+ <Glyph kind="calendar" size={12} color={th.textDim} /><Text style={{ flex: 1, fontSize: 11, fontWeight: 600, color: th.textDim, whiteSpace: 'nowrap', overflow: 'hidden' }}>{a.name}</Text>{s2 === 'sync' ? <Text style={{ fontSize: 10, color: th.textDim }}>⟳</Text> : null}{bad ? <Text onClick={() => setSheet(st.certs.find((c) => c.acct === a.id) ? { cert: st.certs.find((c) => c.acct === a.id) } : { password: a.id })} style={{ fontSize: 11, color: '#ff9f0a' }}>⚠</Text> : null}</View>);})}- <Text style={{ fontSize: 11, fontWeight: 600, color: th.textDim, margin: 6, marginTop: 12 }}>{t('mail.categories')}</Text>+ <Caption>{t('mail.categories')}</Caption>{CATEGORY_COLORS.map((c, i) => (<SideRow key={c} icon={<View style={{ width: 10, height: 10, borderRadius: 5, backgroundColor: c }} />} label={categoryName(i + 1, cfg)}selected={src.kind === 'unified' && src.label === i + 1} onClick={() => setSrc({ kind: 'unified', label: i + 1 })} />))}</View></ScrollView>- <View style={{ flexDirection: 'row', gap: 6, padding: 8 }}>- <Button small label={`+ ${t('mail.addAccount')}`} onClick={() => setSheet('setup')} />- <Button small plain label="⚙" onClick={() => setSheet('accounts')} />+ <View style={{ height: 40, flexDirection: 'row', alignItems: 'center', gap: 4, paddingHorizontal: 8 }}>+ <Hairline edge="top" />+ <Hairline edge="end" />+ <Button small plain icon="⊕" label={t('mail.addAccount')} onClick={() => setSheet('setup')} />+ <View style={{ flex: 1 }} />+ <ToolbarButton small icon="⚙" title={t('mail.menu.accounts')} onClick={() => setSheet('accounts')} /></View></View>);- const TB = ({ icon, label, onClick, disabled, primary }) => (- <View onClick={disabled ? undefined : onClick} style={{ alignItems: 'center', justifyContent: 'center', paddingHorizontal: 8, height: 40, borderRadius: 7, minWidth: 54,- backgroundColor: primary ? th.accent : 'transparent', opacity: disabled ? 0.4 : 1 }}>- <Text style={{ fontSize: 15, color: primary ? '#fff' : th.text }}>{icon}</Text>- <Text style={{ fontSize: 10, color: primary ? '#fff' : th.textDim, whiteSpace: 'nowrap' }}>{label}</Text>- </View>- );+ // toolbar: icon-only items with tooltips, as in Mail; the ones that need a message are dimmed+ const glyphColor = () => th.text; // ToolbarButton dims disabled items itselfconst toolbar = (- <View style={{ flexDirection: 'row', alignItems: 'center', gap: 2, paddingHorizontal: 8, height: 50 }}>- <TB primary icon="✎" label={t('mail.new')} onClick={() => compose()} />- <View style={{ width: 10 }} />- <TB icon="↩" label={t('mail.reply')} disabled={!msg} onClick={act.reply} />- <TB icon="⇇" label={t('mail.replyAll')} disabled={!msg} onClick={act.replyAll} />- <TB icon="↪" label={t('mail.forward')} disabled={!msg} onClick={act.forward} />- <View style={{ width: 10 }} />- <TB icon="🗄" label={t('mail.archive')} disabled={!sel} onClick={act.archive} />- <TB icon="🗑" label={t('mail.delete')} disabled={!sel} onClick={act.remove} />- <TB icon="⚑" label={t('mail.flag')} disabled={!sel} onClick={act.flag} />- <TB icon="●" label={t('mail.category')} disabled={!sel} onClick={() => setSheet({ menu: 'labels' })} />- <View style={{ flex: 1 }} />- </View>+ <Toolbar>+ <ToolbarButton icon="✎" title={t('mail.new')} onClick={() => compose()} />+ <ToolbarDivider />+ <ToolbarButton icon="↩" title={t('mail.reply')} disabled={!msg} onClick={act.reply} />+ <ToolbarButton icon="⇇" title={t('mail.replyAll')} disabled={!msg} onClick={act.replyAll} />+ <ToolbarButton icon="↪" title={t('mail.forward')} disabled={!msg} onClick={act.forward} />+ <ToolbarDivider />+ <ToolbarButton icon={<Glyph kind="archive" size={16} color={glyphColor(sel)} />} title={t('mail.archive')} disabled={!sel} onClick={act.archive} />+ <ToolbarButton icon={<Glyph kind="trash" size={16} color={glyphColor(sel)} />} title={t('mail.delete')} disabled={!sel} onClick={act.remove} />+ <ToolbarButton icon="⚑" title={t('mail.flag')} disabled={!sel} onClick={act.flag} />+ <ToolbarButton icon={<CategoryDots />} title={t('mail.category')} disabled={!sel} onClick={() => setSheet({ menu: 'labels' })} />+ <ToolbarSpacer />+ </Toolbar>);const search = (- <View style={{ paddingHorizontal: 10, paddingBottom: 8 }}>- <TextInput value={q} onChange={(v) => { setQ(v); if (v.trim().length >= 2) setSrc({ kind: 'search', q: v.trim() }); else if (!v.trim() && src.kind === 'search') setSrc({ kind: 'unified' }); }}- placeholder={`⌕ ${t('mail.search.placeholder')}`} onCancel={() => { setQ(''); setSrc({ kind: 'unified' }); }} />+ <View style={{ paddingHorizontal: 12, paddingBottom: 10 }}>+ <SearchField value={q} onChange={(v) => { setQ(v); if (v.trim().length >= 2) setSrc({ kind: 'search', q: v.trim() }); else if (!v.trim() && src.kind === 'search') setSrc({ kind: 'unified' }); }}+ placeholder={t('mail.search.placeholder')} onCancel={() => { setQ(''); setSrc({ kind: 'unified' }); }} /></View>);@@ -606,16 +700,15 @@ function MailMain() {const noAccounts = !accounts.length;return (- <View style={{ flex: 1, flexDirection: 'row', backgroundColor: th.windowBg }}>+ <View ref={rootRef} style={{ flex: 1, flexDirection: 'row', backgroundColor: th.windowBg }}>{sidebar}- <View style={{ width: 1, backgroundColor: th.separator }} /><View style={{ flex: 1 }}>{toolbar}- <View style={{ height: 1, backgroundColor: th.separator }} /><View style={{ flex: 1, flexDirection: 'row' }}>- <View style={{ width: 330 }}>- <View style={{ flexDirection: 'row', alignItems: 'center', paddingHorizontal: 12, height: 34 }}>- <Text style={{ flex: 1, fontSize: 15, fontWeight: 700, color: th.text, whiteSpace: 'nowrap', overflow: 'hidden' }}>{listTitle}</Text>+ <View style={{ width: listW }}>+ <Hairline edge="end" />+ <View style={{ flexDirection: 'row', alignItems: 'center', paddingHorizontal: 14, paddingTop: 10, height: 40 }}>+ <Text style={{ flex: 1, fontSize: 15, fontWeight: 600, color: th.text, whiteSpace: 'nowrap', overflow: 'hidden' }}>{listTitle}</Text></View>{search}<View style={{ height: 1, backgroundColor: th.separator }} />@@ -627,12 +720,11 @@ function MailMain() {</View>) : <MessageList src={src} rev={listRev} selected={selKey} onSelect={openItem} onMenu={() => setSheet({ menu: 'labels' })} cfg={cfg} />}</View>- <View style={{ width: 1, backgroundColor: th.separator }} /><View ref={readingRef} style={{ flex: 1 }}>{msg ? (<ScrollView key={`${msg.acct}|${msg.folder}|${msg.uid}`} style={{ flex: 1 }}>- <View style={{ padding: 18, gap: 12 }}>- <Text style={{ fontSize: 19, fontWeight: 700, color: th.text }}>{msg.subject || t('mail.noSubject')}</Text>+ <View style={{ paddingHorizontal: 20, paddingTop: 16, paddingBottom: 24, gap: 12 }}>+ <Text style={{ fontSize: 20, fontWeight: 600, color: th.text, lineHeight: 26, direction: textDirection(msg.subject || '') }}>{msg.subject || t('mail.noSubject')}</Text>{(sel?.labels || []).length ? (<View style={{ flexDirection: 'row', gap: 6 }}>{sel.labels.map((l) => <View key={l} style={{ paddingHorizontal: 8, height: 18, borderRadius: 9, justifyContent: 'center', backgroundColor: `${CATEGORY_COLORS[l - 1]}44` }}><Text style={{ fontSize: 11, color: th.text }}>{categoryName(l, cfg)}</Text></View>)}@@ -640,15 +732,15 @@ function MailMain() {) : null}{thread.length > 1 ? thread.filter((x) => !(x.folder === msg.folder && x.uid === msg.uid)).map((x) => (<ThreadItem key={`${x.folder}|${x.uid}`} it={x} expanded={expanded[`${x.folder}|${x.uid}`]} onToggle={() => setExpanded((e) => ({ ...e, [`${x.folder}|${x.uid}`]: !e[`${x.folder}|${x.uid}`] }))}- width={readW - 36} onLink={onLink} cfg={cfg} onTrustSender={trustSender} />+ width={readW - 40} onLink={onLink} cfg={cfg} onTrustSender={trustSender} />)) : null}- <MessageView msg={msg} width={readW - 36} onLink={onLink} cfg={cfg} onTrustSender={trustSender} />+ <MessageView msg={msg} width={readW - 40} onLink={onLink} cfg={cfg} onTrustSender={trustSender} /></View></ScrollView>) : (- <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>- <Text style={{ fontSize: 40, opacity: 0.3 }}>✉</Text>- <Text style={{ fontSize: 13, color: th.textDim }}>{loadErr || t('mail.noSelection')}</Text>+ <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', gap: 8, padding: 24 }}>+ <Text style={{ fontSize: 40, color: th.textDim, opacity: 0.6 }}>✉</Text>+ <Text style={{ fontSize: 13, color: th.textDim, textAlign: 'center' }}>{loadErr || t('mail.noSelection')}</Text></View>)}</View>@@ -677,14 +769,43 @@ function MailMain() {);}+function Caption({ children, first }) {+ const th = useTheme();+ return <Text style={{ fontSize: 11, fontWeight: 600, color: th.textDim, marginHorizontal: 8, marginTop: first ? 4 : 16, marginBottom: 4 }}>{children}</Text>;+}++// Three small dots in the category colors: the toolbar item for categories.+function CategoryDots() {+ return (+ <View style={{ width: 16, height: 16, alignItems: 'center', justifyContent: 'center', gap: 1 }}>+ <View style={{ width: 6, height: 6, borderRadius: 3, backgroundColor: CATEGORY_COLORS[0] }} />+ <View style={{ flexDirection: 'row', gap: 1 }}>+ <View style={{ width: 6, height: 6, borderRadius: 3, backgroundColor: CATEGORY_COLORS[3] }} />+ <View style={{ width: 6, height: 6, borderRadius: 3, backgroundColor: CATEGORY_COLORS[4] }} />+ </View>+ </View>+ );+}++// Source-list row. icon: a glyph (drawn in the accent color), { kind } for a drawn shape,+// { folder } for a mail folder, or an element.function SideRow({ icon, label, count, selected, onClick, indent = 0 }) {const th = useTheme();+ const [hover, setHover] = useState(false);+ const c = selected ? '#fff' : th.accent;+ let ic;+ if (typeof icon === 'string') ic = <Text style={{ fontSize: icon === '●' ? 10 : 13, color: c, textAlign: 'center' }}>{icon}</Text>;+ else if (icon && icon.kind) ic = <Glyph kind={icon.kind} size={16} color={c} />;+ else if (icon && icon.folder) ic = <FolderIcon f={icon.folder} color={c} />;+ else ic = icon;+ const rtl = direction() === 'rtl';return (- <View onClick={onClick} style={{ flexDirection: 'row', alignItems: 'center', gap: 8, height: 26, paddingLeft: 8 + indent * 14, paddingRight: 8, borderRadius: 6,- backgroundColor: selected ? th.accent : 'transparent' }}>- {typeof icon === 'string' ? <Text style={{ fontSize: 13, width: 18, textAlign: 'center' }}>{icon}</Text> : <View style={{ width: 18, alignItems: 'center' }}>{icon}</View>}+ <View onClick={onClick} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}+ style={{ flexDirection: 'row', alignItems: 'center', gap: 8, height: 28, [rtl ? 'paddingRight' : 'paddingLeft']: 8 + indent * 14, [rtl ? 'paddingLeft' : 'paddingRight']: 8, borderRadius: 6,+ backgroundColor: selected ? th.accent : hover ? th.hover : 'transparent' }}>+ <View style={{ width: 18, alignItems: 'center', justifyContent: 'center' }}>{ic}</View><Text style={{ flex: 1, fontSize: 13, color: selected ? '#fff' : th.text, whiteSpace: 'nowrap', overflow: 'hidden' }}>{label}</Text>- {count ? <Text style={{ fontSize: 11, fontWeight: 600, color: selected ? '#fff' : th.textDim }}>{String(count)}</Text> : null}+ {count ? <Text style={{ fontSize: 11, fontWeight: 500, color: selected ? 'rgba(255,255,255,0.85)' : th.textDim }}>{String(count)}</Text> : null}</View>);}@@ -695,9 +816,9 @@ function ThreadItem({ it, expanded, onToggle, width, onLink, cfg, onTrustSenderuseEffect(() => { if (expanded && !m) mailRequest('open', { acct: it.acct, folder: it.folder, uid: it.uid }).then(setM).catch(() => {}); }, [expanded]);if (expanded && m) return <View style={{ gap: 6 }}><Text onClick={onToggle} style={{ fontSize: 11, color: th.accent }}>{t('mail.thread.collapse')}</Text><MessageView msg={m} width={width} onLink={onLink} cfg={cfg} onTrustSender={onTrustSender} /></View>;return (- <View onClick={onToggle} style={{ padding: 10, borderRadius: 8, backgroundColor: th.control, flexDirection: 'row', gap: 8 }}>- <Text style={{ fontSize: 13, fontWeight: 600, color: th.text }}>{it.from || it.email}</Text>- <Text style={{ flex: 1, fontSize: 12, color: th.textDim, whiteSpace: 'nowrap', overflow: 'hidden' }}>{it.preview}</Text>+ <View onClick={onToggle} style={{ paddingVertical: 9, paddingHorizontal: 12, borderRadius: 8, backgroundColor: th.control, flexDirection: 'row', alignItems: 'center', gap: 10 }}>+ <Text style={{ fontSize: 13, fontWeight: 600, color: th.text, whiteSpace: 'nowrap' }}>{it.from || it.email}</Text>+ <Text style={{ flex: 1, fontSize: 12, color: th.textDim, whiteSpace: 'nowrap', overflow: 'hidden', direction: textDirection(it.preview || '') }}>{it.preview}</Text><Text style={{ fontSize: 11, color: th.textDim }}>{listDate(it.date)}</Text></View>);diff --git a/apps/monitor/Firewall.jsx b/apps/monitor/Firewall.jsxindex abee584..ef275ce 100644--- a/apps/monitor/Firewall.jsx+++ b/apps/monitor/Firewall.jsx@@ -6,7 +6,7 @@// no incoming connections, and the non-network ones: camera, microphone…).// The rules are saved by lord-server (lord.fw); this screen writes no files. Drawn like the// Settings sections: 13/600 headers, inset GroupBoxes with hairlines, footers.-import { View, Text, Button, Segmented, ScrollView, GroupBox, useTheme, useLocale, useStore, useLauncherApps, firewall, firewallState, spacing, typeScale } from '@lordos/sdk';+import { View, Text, Button, Segmented, ScrollView, GroupBox, useTheme, useLocale, useStore, useLauncherApps, firewall, firewallState, spacing, typeScale, errorText } from '@lordos/sdk';import { useState } from 'react';// Firewall id of a launcher app: the built-in ones run inside LordOS.@@ -88,7 +88,7 @@ export function FirewallPrivacy() {const trusted = st.trusted || [];const restricted = st.restricted || {};const inLists = new Set([...trusted, ...Object.keys(restricted)]);- const statusText = !status.daemon ? tr('firewall.status.noDaemon') : !status.bpf ? tr('firewall.status.noBpf', { error: status.error || '' }) :+ const statusText = !status.daemon ? tr('firewall.status.noDaemon') : !status.bpf ? tr('firewall.status.noBpf', { error: errorText(status.error || '') }) :tr('firewall.status.on', { dns: tr(`firewall.dns.${status.dns || 'none'}`) });const setFlag = (id, flag, on) => {const cur = restricted[id] || [];diff --git a/apps/monitor/countries.js b/apps/monitor/countries.jsindex ad9119d..61dfc1e 100644--- a/apps/monitor/countries.js+++ b/apps/monitor/countries.js@@ -1,3 +1,3 @@-// countries.js — generado por tools/gen-monitor-data.py (Natural Earth 1:50m, dominio público).-// [longitud, latitud] del lugar de la etiqueta de cada país.+// countries.js — generated by tools/gen-monitor-data.py (Natural Earth 1:50m, public domain).+// [longitude, latitude] of the label position of each country.export const COUNTRY_LL = {"AD":[1.54,42.55],"AE":[54.55,23.47],"AF":[66.5,34.16],"AG":[-61.79,17.35],"AI":[-63.03,18.24],"AL":[20.11,40.65],"AM":[44.8,40.46],"AO":[17.98,-12.18],"AQ":[35.89,-79.84],"AR":[-64.17,-33.5],"AS":[-170.75,-14.33],"AT":[14.13,47.52],"AU":[134.05,-24.13],"AW":[-69.97,12.52],"AX":[19.87,60.16],"AZ":[47.21,40.4],"BA":[18.07,44.09],"BB":[-59.57,13.16],"BD":[89.68,24.21],"BE":[4.8,50.79],"BF":[-1.36,12.67],"BG":[25.16,42.51],"BH":[50.55,26.06],"BI":[29.92,-3.33],"BJ":[2.35,10.32],"BL":[-62.83,17.9],"BM":[-64.76,32.3],"BN":[114.55,4.45],"BO":[-64.59,-16.67],"BR":[-49.56,-12.1],"BS":[-77.15,26.4],"BT":[90.04,27.54],"BW":[24.18,-22.1],"BY":[28.42,53.82],"BZ":[-88.71,17.2],"CA":[-101.91,60.32],"CD":[23.46,-1.86],"CF":[20.91,6.99],"CG":[15.9,0.14],"CH":[7.46,46.72],"CI":[-5.57,7.49],"CK":[-159.79,-21.22],"CL":[-72.32,-38.15],"CM":[12.47,4.59],"CN":[106.34,32.5],"CO":[-73.17,3.37],"CR":[-84.08,10.07],"CU":[-77.98,21.33],"CV":[-23.64,15.07],"CW":[-68.92,12.15],"CY":[33.08,34.91],"CZ":[15.38,49.88],"DE":[9.68,50.96],"DJ":[42.5,11.98],"DK":[9.02,55.97],"DM":[-61.34,15.46],"DO":[-70.65,19.1],"DZ":[2.81,27.4],"EC":[-78.19,-1.26],"EE":[25.87,58.72],"EG":[29.45,26.19],"EH":[-12.63,23.97],"ER":[38.29,15.79],"ES":[-3.46,40.09],"ET":[39.09,8.03],"FI":[27.28,63.25],"FJ":[177.98,-17.83],"FK":[-58.74,-51.61],"FM":[158.23,6.89],"FO":[-7.06,62.19],"FR":[2.55,46.7],"GA":[11.84,-0.44],"GB":[-2.12,54.4],"GD":[-61.68,12.11],"GE":[43.74,41.87],"GG":[-2.56,49.46],"GH":[-1.04,7.72],"GL":[-39.34,74.32],"GM":[-15.0,13.64],"GN":[-10.02,10.62],"GQ":[8.99,2.33],"GR":[21.73,39.49],"GS":[-31.06,-55.68],"GT":[-90.5,14.98],"GU":[144.7,13.35],"GW":[-14.52,12.16],"GY":[-58.94,5.12],"HK":[114.1,22.45],"HM":[73.51,-53.1],"HN":[-86.89,14.79],"HR":[16.37,45.81],"HT":[-72.22,19.26],"HU":[19.45,47.09],"ID":[101.89,-0.95],"IE":[-7.8,53.08],"IL":[34.85,30.91],"IM":[-4.53,54.22],"IN":[79.36,22.69],"IO":[71.35,-6.19],"IQ":[43.26,33.09],"IR":[54.93,32.17],"IS":[-18.67,64.78],"IT":[11.08,44.73],"JE":[-2.09,49.22],"JM":[-77.32,18.14],"JO":[36.38,30.81],"JP":[138.44,36.14],"KE":[37.91,0.55],"KG":[74.53,41.67],"KH":[104.5,12.65],"KI":[-157.38,1.82],"KM":[43.32,-11.73],"KN":[-62.76,17.34],"KP":[126.44,39.89],"KR":[128.13,36.38],"KW":[47.31,29.41],"KY":[-81.24,19.32],"KZ":[68.69,49.05],"LA":[102.53,19.43],"LB":[35.99,34.13],"LC":[-60.98,13.89],"LI":[9.56,47.11],"LK":[80.7,7.58],"LR":[-9.46,6.45],"LS":[28.25,-29.48],"LT":[24.09,55.1],"LU":[6.08,49.73],"LV":[25.46,57.07],"LY":[18.01,26.64],"MA":[-7.19,31.65],"MC":[7.4,43.74],"MD":[28.49,47.43],"ME":[19.14,42.8],"MF":[-63.05,18.08],"MG":[46.7,-18.63],"MH":[171.19,7.08],"MK":[21.56,41.56],"ML":[-2.04,18.69],"MM":[95.8,21.57],"MN":[104.15,46.0],"MO":[113.56,22.13],"MP":[145.73,15.19],"MR":[-9.74,19.59],"MS":[-62.19,16.74],"MT":[14.43,35.89],"MU":[57.57,-20.3],"MV":[73.51,4.17],"MW":[33.61,-13.39],"MX":[-102.29,23.92],"MY":[113.84,2.53],"MZ":[37.84,-13.94],"NA":[17.11,-20.58],"NC":[165.08,-21.06],"NE":[9.5,17.45],"NF":[167.95,-29.03],"NG":[7.5,9.44],"NI":[-85.07,12.67],"NL":[5.61,52.42],"NO":[9.68,61.36],"NP":[83.64,28.3],"NR":[166.93,-0.52],"NU":[-169.86,-19.05],"NZ":[172.79,-39.76],"OM":[57.34,22.12],"PA":[-80.35,8.72],"PE":[-72.9,-12.98],"PF":[-149.46,-17.63],"PG":[143.91,-5.7],"PH":[122.47,11.2],"PK":[68.55,29.33],"PL":[19.49,51.99],"PM":[-56.33,47.04],"PN":[-128.32,-24.36],"PR":[-66.48,18.23],"PS":[35.29,32.05],"PT":[-8.27,39.61],"PW":[134.58,7.52],"PY":[-60.15,-21.67],"QA":[51.14,25.24],"RO":[24.97,45.73],"RS":[20.79,44.19],"RU":[44.69,58.25],"RW":[30.1,-1.9],"SA":[44.7,23.81],"SB":[159.17,-8.03],"SC":[55.48,-4.68],"SD":[29.26,16.33],"SE":[19.02,65.86],"SG":[103.82,1.37],"SH":[-5.71,-15.95],"SI":[14.92,46.06],"SK":[19.05,48.73],"SL":[-11.76,8.62],"SM":[12.44,43.93],"SN":[-14.78,15.14],"SO":[45.19,3.57],"SR":[-55.91,4.14],"SS":[30.39,7.23],"ST":[7.02,0.97],"SV":[-88.89,13.69],"SX":[-63.07,18.04],"SY":[38.28,35.01],"SZ":[31.47,-26.53],"TC":[-71.75,21.82],"TD":[18.65,15.14],"TF":[69.12,-49.3],"TG":[1.06,8.81],"TH":[101.07,15.46],"TJ":[72.59,38.2],"TL":[125.85,-8.8],"TM":[58.68,39.86],"TN":[9.01,33.69],"TO":[-175.16,-21.21],"TR":[34.51,39.35],"TT":[-60.92,11.0],"TV":[179.21,-8.51],"TW":[120.87,23.65],"TZ":[34.96,-6.05],"UA":[32.14,49.72],"UG":[32.95,1.97],"US":[-97.48,39.54],"UY":[-55.97,-32.96],"UZ":[64.01,41.69],"VA":[12.45,41.9],"VC":[-61.34,13.09],"VE":[-64.6,7.18],"VG":[-64.64,18.43],"VI":[-64.78,17.75],"VN":[105.39,21.72],"VU":[166.91,-15.37],"WF":[-178.14,-14.29],"WS":[-172.44,-13.64],"XK":[20.86,42.59],"YE":[45.87,15.33],"ZA":[23.67,-29.71],"ZM":[26.4,-14.66],"ZW":[29.93,-18.91]};diff --git a/apps/monitor/manifest.json b/apps/monitor/manifest.jsonindex 6f7621c..679e443 100644--- a/apps/monitor/manifest.json+++ b/apps/monitor/manifest.json@@ -1,7 +1,7 @@{"id": "monitor","name": "Monitor",- "description": "CPU, memoria, red, discos, procesos y conexiones de cada app",+ "description": "CPU, memory, network, disks, processes and each app's connections","size": [1180,700diff --git a/apps/notes/manifest.json b/apps/notes/manifest.jsonindex dee8913..8840e7a 100644--- a/apps/notes/manifest.json+++ b/apps/notes/manifest.json@@ -1,7 +1,7 @@{"id": "notes",- "name": "Notas",- "description": "Notas y post-its en el escritorio, con markdown, imágenes y adjuntos",+ "name": "Notes",+ "description": "Notes and sticky notes on the desktop, with markdown, images and attachments","size": [860, 560],"minSize": [560, 360],"dock": true,diff --git a/apps/pdf/index.jsx b/apps/pdf/index.jsxindex 3f2fbcf..0dfa063 100644--- a/apps/pdf/index.jsx+++ b/apps/pdf/index.jsx@@ -387,7 +387,7 @@ export default function PdfViewer() {cache.current.invalidate(a.page);thumbs.current.invalidate(a.page);setAnnotated((x) => [...x, a.page]);- }).catch((e) => setMsg(tr('pdf.annotError', { error: e.code || e.message })));+ }).catch((e) => setMsg(tr('pdf.annotError', { error: e.message })));};const finishInk = () => {if (ink && ink.strokes.some((s) => s.length >= 2)) addAnnot({ page: ink.page, type: 'ink', strokes: ink.strokes, color, width: 2.2 });@@ -425,7 +425,7 @@ export default function PdfViewer() {let name = tr('pdf.copyName', { name: base });for (let i = 2; i < 200; i++) { try { fs.stat(`${dir}/${name}.pdf`); name = `${tr('pdf.copyName', { name: base })} ${i}`; } catch (e) { break; } }const out = `${dir}/${name}.pdf`;- doc.save(out).then(() => setMsg(tr('pdf.saved', { name: `${name}.pdf` }))).catch((e) => setMsg(tr('pdf.saveError', { error: e.code || e.message })));+ doc.save(out).then(() => setMsg(tr('pdf.saved', { name: `${name}.pdf` }))).catch((e) => setMsg(tr('pdf.saveError', { error: e.message })));};const doPrint = () => { if (doc) print.open({ title: fs.basename(path), doc }); };const copySel = () => { if (selection?.text) { clipboard.set(selection.text); setMsg(tr('pdf.copied')); } };diff --git a/apps/pdf/manifest.json b/apps/pdf/manifest.jsonindex bcdbebc..4e61b94 100644--- a/apps/pdf/manifest.json+++ b/apps/pdf/manifest.json@@ -1,7 +1,7 @@{"id": "pdf",- "name": "Visor de PDF",- "description": "Visor de PDF al estilo de Vista Previa: miniaturas, índice, búsqueda, anotaciones, formularios e impresión",+ "name": "PDF Viewer",+ "description": "Preview-style PDF viewer: thumbnails, outline, search, annotations, forms and printing","size": [980, 680],"minSize": [560, 380],"dock": false,diff --git a/apps/photos/index.jsx b/apps/photos/index.jsxindex bf98030..29e84af 100644--- a/apps/photos/index.jsx+++ b/apps/photos/index.jsx@@ -6,7 +6,7 @@// (crop, rotation, brightness and contrast) are saved as a copy: the original is left untouched.import {View, Text, Image, MediaView, ScrollView, SidebarItem, SectionTitle, Button, Slider, useTheme, useAppWindow, useKeyboard, useWindowState, wm,- t as tr, media, useThumb, userDirs, fs, addListener, direction, print, ThemeProvider, ToolbarButton, ToolbarGroup, EmptyState, useStore, windows,+ t as tr, errorText, media, useThumb, userDirs, fs, addListener, direction, print, ThemeProvider, ToolbarButton, ToolbarGroup, EmptyState, useStore, windows,} from '@lordos/sdk';import { useEffect, useRef, useState } from 'react';@@ -245,7 +245,7 @@ function Viewer({ list, index, setIndex, onClose, winId, mode }) {<MediaView media={id} style={{ position: 'absolute', left: 0, top: 0, right: 0, bottom: 0 }} />{error && <View style={{ position: 'absolute', left: 0, right: 0, top: '45%', alignItems: 'center', gap: 4 }}><Text style={{ fontSize: 13, color: '#ffb0b0' }}>{tr('photos.cantOpen')}</Text>- <Text style={{ fontSize: 11, color: '#999' }}>{error}</Text>+ <Text style={{ fontSize: 11, color: '#999' }}>{errorText(error)}</Text></View>}{edit?.crop && edit.crop.w > 2 && (() => {const c = edit.crop, dim = 'rgba(0,0,0,0.5)';diff --git a/apps/photos/manifest.json b/apps/photos/manifest.jsonindex 9c55c9c..bba7e6d 100644--- a/apps/photos/manifest.json+++ b/apps/photos/manifest.json@@ -1,7 +1,7 @@{"id": "photos",- "name": "Fotos",- "description": "Visor y biblioteca de imágenes: zoom, giro, presentación y edición básica guardada como copia",+ "name": "Photos",+ "description": "Image viewer and library: zoom, rotate, slideshow and basic editing saved as a copy","size": [980, 640],"minSize": [520, 360],"dock": true,diff --git a/apps/player/index.jsx b/apps/player/index.jsxindex 4c5aaa9..81b819c 100644--- a/apps/player/index.jsx+++ b/apps/player/index.jsx@@ -6,7 +6,7 @@// and the media keys (nowPlaying).import {View, Text, Image, MediaView, ScrollView, SidebarItem, SectionTitle, Hairline, EmptyState, ToolbarButton, useTheme, useAppWindow, useKeyboard,- useStore, useWindowState, wm, typeScale, t as tr, media, usePlayer, nowPlaying, mediaFormatTime, useThumb, fs, addListener, direction,+ useStore, useWindowState, wm, typeScale, t as tr, errorText, media, usePlayer, nowPlaying, mediaFormatTime, useThumb, fs, addListener, direction,} from '@lordos/sdk';import { useEffect, useMemo, useRef, useState } from 'react';import { library, scan, albumsOf, artistsOf, parseSrt, AUDIO, VIDEO } from './library.js';@@ -367,7 +367,7 @@ export default function Player() {<View style={{ flex: 1, backgroundColor: '#000' }} onMouseMove={poke} onMouseDown={() => setMenu(null)}><MediaView media={id} style={{ position: 'absolute', left: 0, top: 0, right: 0, bottom: 0 }} />{p.error && <View style={{ position: 'absolute', left: 0, right: 0, top: '45%', alignItems: 'center' }}>- <Text style={{ fontSize: 13, color: '#ff9f9f' }}>{p.error === 'crash' ? tr('player.crashed') : tr('player.error', { error: p.error })}</Text>+ <Text style={{ fontSize: 13, color: '#ff9f9f' }}>{p.error === 'crash' ? tr('player.crashed') : tr('player.error', { error: errorText(p.error) })}</Text></View>}{cue ? (<View style={{ position: 'absolute', left: 24, right: 24, bottom: controls && !small ? 96 : 28, alignItems: 'center' }}>@@ -408,7 +408,7 @@ export default function Player() {const contentW = width - 200;const showArtist = contentW >= 380, showAlbum = contentW >= 560;const narrow = width < 720;- const col = (flex, extra) => ({ flex, minWidth: 0, fontSize: 12, color: th.textDim, whiteSpace: 'nowrap', overflow: 'hidden', ...extra });+ const col = (flex, extra) => ({ flex, minWidth: 0, fontSize: 12, color: th.textDim, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', ...extra });const header = (<View style={{ height: 26, flexDirection: 'row', alignItems: 'center', gap: 12, paddingHorizontal: 10 }}><Hairline edge="bottom" />@@ -458,8 +458,8 @@ export default function Player() {{list.map((a) => (<View key={a.key} onClick={() => { setView('albums'); setSel(a.key); }} style={{ width: 150, gap: 2 }}><Cover path={a.tracks[0].path} size={150} radius={8} />- <Text style={{ fontSize: 13, fontWeight: 500, color: th.text, whiteSpace: 'nowrap', overflow: 'hidden', marginTop: 6 }}>{a.album || tr('player.unknownAlbum')}</Text>- <Text style={{ fontSize: typeScale.callout, color: th.textDim, whiteSpace: 'nowrap', overflow: 'hidden' }}>{a.artist || tr('player.unknownArtist')}</Text>+ <Text style={{ fontSize: 13, fontWeight: 500, color: th.text, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', marginTop: 6 }}>{a.album || tr('player.unknownAlbum')}</Text>+ <Text style={{ fontSize: typeScale.callout, color: th.textDim, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{a.artist || tr('player.unknownArtist')}</Text></View>))}</View>@@ -527,8 +527,8 @@ export default function Player() {<View onClick={() => isVideo(current) && setShowVideo(true)}><Cover path={current} size={48} /></View>{!narrow && (<View style={{ flex: 1, minWidth: 0, gap: 2, overflow: 'hidden' }}>- <Text style={{ fontSize: 13, fontWeight: 600, color: th.text, whiteSpace: 'nowrap' }}>{meta?.title || p.info?.tags?.title || baseName(current)}</Text>- <Text style={{ fontSize: typeScale.callout, color: th.textDim, whiteSpace: 'nowrap' }}>{meta?.artist || p.info?.tags?.artist || ''}</Text>+ <Text style={{ fontSize: 13, fontWeight: 600, color: th.text, whiteSpace: 'nowrap', textOverflow: 'ellipsis' }}>{meta?.title || p.info?.tags?.title || baseName(current)}</Text>+ <Text style={{ fontSize: typeScale.callout, color: th.textDim, whiteSpace: 'nowrap', textOverflow: 'ellipsis' }}>{meta?.artist || p.info?.tags?.artist || ''}</Text></View>)}</View>diff --git a/apps/player/library.js b/apps/player/library.jsindex bb157d0..7a6f6d1 100644--- a/apps/player/library.js+++ b/apps/player/library.js@@ -1,8 +1,8 @@-// library.js — biblioteca de música y videos del Reproductor.+// library.js — the Player's music and video library.//-// Recorre ~/Música y ~/Videos (acotado), lee las etiquetas con media.probe (lord-media, en-// segundo plano) y guarda lo leído en ~/.cache/lordos/music.json (por ruta, tamaño y fecha), así-// la próxima vez no se vuelve a leer nada que no cambió.+// Walks ~/Music and ~/Videos (bounded), reads the tags with media.probe (lord-media, in the+// background) and stores what it read in ~/.cache/lordos/music.json (by path, size and date), so+// next time nothing that did not change is read again.import { fs, media, userDirs, createStore } from '@lordos/sdk';export const AUDIO = /\.(mp3|ogg|oga|opus|flac|wav|m4a|aac|wma|aif|aiff|ape|mka)$/i;@@ -23,7 +23,7 @@ function walk(dir, re, out, depth = 0) {const baseName = (p) => String(p).split('/').pop().replace(/\.[^.]+$/, '');-// Pista desde el resultado de probe (o el nombre del archivo si no hay etiquetas).+// Track from the probe result (or the file name if there are no tags).export function trackFrom(f, info) {const tags = (info && info.tags) || {};const n = parseInt(String(tags.track || '').split('/')[0], 10);@@ -50,7 +50,7 @@ export async function scan() {walk(dirs.music, AUDIO, files);walk(dirs.videos, VIDEO, vids);let cache = {};- try { cache = JSON.parse(fs.read(CACHE)); } catch (e) { /* primera vez */ }+ try { cache = JSON.parse(fs.read(CACHE)); } catch (e) { /* first time */ }const key = (f) => `${f.size}:${Math.round(f.mtime || 0)}`;const tracks = [];const todo = [];@@ -73,13 +73,13 @@ export async function scan() {}library.set({ scanning: false });if (todo.length || Object.keys(cache).length !== Object.keys(next).length) {- try { fs.mkdir('.cache/lordos'); } catch (e) { /* ya está */ }- try { fs.write(CACHE, JSON.stringify(next)); } catch (e) { /* sin disco */ }+ try { fs.mkdir('.cache/lordos'); } catch (e) { /* already there */ }+ try { fs.write(CACHE, JSON.stringify(next)); } catch (e) { /* no disk */ }}running = false;}-// Agrupar: artistas → álbumes → pistas.+// Grouping: artists → albums → tracks.export function albumsOf(tracks) {const map = new Map();for (const t of tracks) {@@ -102,7 +102,7 @@ export function artistsOf(tracks) {return [...map.entries()].map(([name, list]) => ({ name, tracks: list })).sort((a, b) => a.name.localeCompare(b.name));}-// Subtítulos .srt: [{ start, end, text }] en ms.+// .srt subtitles: [{ start, end, text }] in ms.export function parseSrt(text) {const out = [];const ms = (s) => { const m = /(\d+):(\d+):(\d+)[,.](\d+)/.exec(s); return m ? ((+m[1] * 60 + +m[2]) * 60 + +m[3]) * 1000 + +m[4].padEnd(3, '0').slice(0, 3) : 0; };diff --git a/apps/player/manifest.json b/apps/player/manifest.jsonindex 5dee54f..053d17c 100644--- a/apps/player/manifest.json+++ b/apps/player/manifest.json@@ -1,7 +1,7 @@{"id": "player",- "name": "Reproductor",- "description": "Videos y música: biblioteca por artista y álbum, cola, subtítulos, pantalla completa e imagen en imagen",+ "name": "Player",+ "description": "Videos and music: library by artist and album, queue, subtitles, full screen and picture in picture","size": [960, 600],"minSize": [480, 320],"dock": true,diff --git a/apps/recorder/manifest.json b/apps/recorder/manifest.jsonindex f3a31e7..e398acb 100644--- a/apps/recorder/manifest.json+++ b/apps/recorder/manifest.json@@ -1,7 +1,7 @@{"id": "recorder",- "name": "Grabadora",- "description": "Notas de voz: grabar, forma de onda, renombrar, recortar y exportar a Opus, MP3 o WAV",+ "name": "Voice Recorder",+ "description": "Voice memos: record, waveform, rename, trim and export to Opus, MP3 or WAV","size": [800, 480],"minSize": [640, 400],"dock": true,diff --git a/apps/reminders/index.jsx b/apps/reminders/index.jsxindex c2bd35e..5bdddff 100644--- a/apps/reminders/index.jsx+++ b/apps/reminders/index.jsx@@ -128,19 +128,19 @@ function Sidebar({ sel, onSel, lists, counts, now, onAdd, onEdit }) {<View style={{ width: 236, backgroundColor: th.sidebarBg }}><Hairline edge="end" /><ScrollView style={{ flex: 1 }}>- <View style={{ padding: 10, gap: 4 }}>+ <View style={{ paddingHorizontal: 10, paddingTop: 12, paddingBottom: 10, gap: 2 }}><View style={{ flexDirection: 'row', flexWrap: 'wrap', gap: 8 }}>{tiles.map((k) => (<Tile key={k} label={t(`reminders.smart.${k}`)} color={SMART[k]} glyph={glyph[k]} count={k === 'completed' ? null : counts[k]}selected={sel === k} onClick={() => onSel(k)} />))}</View>- <Text style={{ fontSize: 11, fontWeight: 600, color: th.textDim, marginHorizontal: 6, marginTop: 14, marginBottom: 2 }}>{t('reminders.myLists')}</Text>+ <Text style={{ fontSize: 11, fontWeight: 600, color: th.textDim, marginHorizontal: 8, marginTop: 18, marginBottom: 4 }}>{t('reminders.myLists')}</Text>{lists.map((l) => <ListRow key={l.id} list={l} count={counts.lists[l.id] || 0} selected={sel === `list:${l.id}`} onClick={() => onSel(`list:${l.id}`)} onEdit={onEdit} />)}- {!lists.length ? <Text style={{ fontSize: 12, color: th.textDim, marginHorizontal: 6 }}>{t('reminders.noLists')}</Text> : null}+ {!lists.length ? <Text style={{ fontSize: 12, color: th.textDim, marginHorizontal: 8 }}>{t('reminders.noLists')}</Text> : null}</View></ScrollView>- <View style={{ padding: 8 }}>+ <View style={{ height: 40, paddingHorizontal: 10, justifyContent: 'center' }}><Hairline edge="top" /><Button small plain icon="⊕" label={t('reminders.addList')} onClick={onAdd} style={{ alignSelf: 'flex-start' }} /></View>@@ -152,14 +152,15 @@ function Tile({ label, color, glyph, count, selected, onClick }) {const th = useTheme();const dark = th.mode === 'dark';return (- <View onClick={onClick} style={{ width: 103, height: 62, borderRadius: 10, padding: 8, justifyContent: 'space-between',- backgroundColor: selected ? color : dark ? 'rgba(255,255,255,0.08)' : '#ffffff', boxShadow: dark || selected ? 'none' : '0 1px 2px rgba(0,0,0,0.12)' }}>+ <View onClick={onClick} style={{ width: 104, height: 64, borderRadius: 10, paddingHorizontal: 9, paddingTop: 8, paddingBottom: 7, justifyContent: 'space-between',+ backgroundColor: selected ? color : dark ? 'rgba(255,255,255,0.07)' : '#ffffff',+ border: `1px solid ${selected ? 'transparent' : dark ? 'rgba(255,255,255,0.06)' : 'rgba(0,0,0,0.06)'}`, boxShadow: dark || selected ? 'none' : '0 1px 1px rgba(0,0,0,0.06)' }}><View style={{ flexDirection: 'row', alignItems: 'center' }}>- <View style={{ width: 24, height: 24, borderRadius: 12, alignItems: 'center', justifyContent: 'center', backgroundColor: selected ? '#ffffff' : color }}>- <Text style={{ fontSize: 12, fontWeight: 700, color: selected ? color : '#ffffff' }}>{glyph}</Text>+ <View style={{ width: 26, height: 26, borderRadius: 13, alignItems: 'center', justifyContent: 'center', backgroundColor: selected ? '#ffffff' : color }}>+ <Text style={{ fontSize: 12, fontWeight: 600, color: selected ? color : '#ffffff' }}>{glyph}</Text></View><View style={{ flex: 1 }} />- {count != null ? <Text style={{ fontSize: 19, fontWeight: 700, color: selected ? '#fff' : th.text }}>{String(count)}</Text> : null}+ {count != null ? <Text style={{ fontSize: 20, fontWeight: 700, color: selected ? '#fff' : th.text }}>{String(count)}</Text> : null}</View><Text style={{ fontSize: 12, fontWeight: 600, color: selected ? '#fff' : th.textDim, whiteSpace: 'nowrap', overflow: 'hidden' }}>{label}</Text></View>@@ -173,13 +174,13 @@ function ListRow({ list, count, selected, onClick, onEdit }) {const [hover, setHover] = useState(false);return (<View ref={ref} onClick={onClick} onContextMenu={() => setMenu(true)} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}- style={{ height: 32, paddingHorizontal: 6, borderRadius: 7, flexDirection: 'row', alignItems: 'center', gap: 8,+ style={{ height: 32, paddingHorizontal: 8, borderRadius: 6, flexDirection: 'row', alignItems: 'center', gap: 8,backgroundColor: selected ? (th.mode === 'dark' ? 'rgba(255,255,255,0.14)' : 'rgba(0,0,0,0.09)') : hover ? th.hover : 'transparent' }}>- <View style={{ width: 24, height: 24, borderRadius: 12, alignItems: 'center', justifyContent: 'center', backgroundColor: list.color || '#007aff' }}>- <Text style={{ fontSize: 12, color: '#fff' }}>☰</Text>+ <View style={{ width: 22, height: 22, borderRadius: 11, alignItems: 'center', justifyContent: 'center', backgroundColor: list.color || '#007aff' }}>+ <Text style={{ fontSize: 11, color: '#fff' }}>☰</Text></View><Text style={{ flex: 1, fontSize: 13, color: th.text, whiteSpace: 'nowrap', overflow: 'hidden' }}>{list.name}</Text>- <Text style={{ fontSize: 13, color: th.textDim }}>{String(count)}</Text>+ <Text style={{ fontSize: 12, color: th.textDim }}>{String(count)}</Text>{menu && (<Popover anchor={ref} width={200} onClose={() => setMenu(false)}><MenuList onDone={() => setMenu(false)} items={[@@ -235,24 +236,24 @@ function ListView({ sel, title, color, items, lists, now, showDone, newRowRef, lconst canAdd = sel !== 'completed';return (<View style={{ flex: 1 }}>- <View style={{ flexDirection: 'row', alignItems: 'flex-end', paddingHorizontal: 22, paddingBottom: 6 }}>- <Text style={{ flex: 1, fontSize: 28, fontWeight: 700, color, whiteSpace: 'nowrap', overflow: 'hidden' }}>{title}</Text>- <Text style={{ fontSize: 28, fontWeight: 600, color }}>{sel === 'completed' ? String(shown.length) : String(openCount)}</Text>+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 12, paddingHorizontal: 20, paddingBottom: 10 }}>+ <Text style={{ flex: 1, fontSize: 26, fontWeight: 700, color, whiteSpace: 'nowrap', overflow: 'hidden' }}>{title}</Text>+ <Text style={{ fontSize: 26, fontWeight: 600, color }}>{sel === 'completed' ? String(shown.length) : String(openCount)}</Text></View><ScrollView style={{ flex: 1 }}>- <View style={{ paddingHorizontal: 14, paddingBottom: 20 }}>+ <View style={{ paddingHorizontal: 12, paddingBottom: 20 }}>{sections.map((s) => (- <View key={s.key} style={{ marginBottom: s.title ? 12 : 0 }}>- {s.title ? <Text style={{ fontSize: 15, fontWeight: 700, color: s.color || th.text, marginHorizontal: 8, marginTop: 8, marginBottom: 4 }}>{s.title}</Text> : null}+ <View key={s.key} style={{ marginBottom: s.title ? 14 : 0 }}>+ {s.title ? <Text style={{ fontSize: 15, fontWeight: 600, color: s.color || th.text, marginHorizontal: 8, marginTop: 6, marginBottom: 2 }}>{s.title}</Text> : null}{s.rows.map(({ it, depth }) => (<ReminderRow key={`${it.list}/${it.uid}`} item={it} depth={depth} lists={lists} now={now} color={listOf(it.list)?.color || it.color || '#007aff'}listName={smart && sel !== 'all' ? listOf(it.list)?.name : ''} />))}</View>))}- {!shown.length && !loading && !canAdd ? <Text style={{ fontSize: 13, color: th.textDim, margin: 10 }}>{t('reminders.nothingCompleted')}</Text> : null}+ {!shown.length && !loading && !canAdd ? <Text style={{ fontSize: 13, color: th.textDim, marginHorizontal: 8, marginVertical: 10 }}>{t('reminders.nothingCompleted')}</Text> : null}{!shown.length && !loading && canAdd && sel !== 'all' && !sel.startsWith('list:') ? (- <Text style={{ fontSize: 13, color: th.textDim, marginHorizontal: 10, marginVertical: 6 }}>{t('reminders.empty')}</Text>+ <Text style={{ fontSize: 13, color: th.textDim, marginHorizontal: 8, marginVertical: 8 }}>{t('reminders.empty')}</Text>) : null}{canAdd ? <NewRow sel={sel} target={target} color={target?.color || color} registerFocus={newRowRef} /> : null}</View>@@ -261,11 +262,11 @@ function ListView({ sel, title, color, items, lists, now, showDone, newRowRef, l);}-function Circle({ done, color, onClick, size = 20 }) {+function Circle({ done, color, onClick, size = 18 }) {return (<View onClick={onClick} style={{ width: size, height: size, borderRadius: size / 2, alignItems: 'center', justifyContent: 'center',border: `1.5px solid ${done ? color : '#a1a1a6'}` }}>- {done ? <View style={{ width: size - 6, height: size - 6, borderRadius: (size - 6) / 2, backgroundColor: color }} /> : null}+ {done ? <View style={{ width: size - 5, height: size - 5, borderRadius: (size - 5) / 2, backgroundColor: color }} /> : null}</View>);}@@ -299,17 +300,18 @@ function ReminderRow({ item, depth, color, lists, now, listName }) {const marks = prioMarks(item.prio);const due = dueText(item);const sub = [due, listName].filter(Boolean);+ const rtl = direction() === 'rtl';return (<View ref={row} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}- style={{ flexDirection: 'row', alignItems: 'flex-start', gap: 10, paddingVertical: 7, paddingHorizontal: 8, marginHorizontal: depth ? 28 : 0 }}>+ style={{ flexDirection: 'row', alignItems: 'flex-start', gap: 10, paddingVertical: 8, paddingHorizontal: 8, marginHorizontal: depth ? 28 : 0 }}><View style={{ paddingTop: 1 }}><Circle done={done} color={color} onClick={toggle} /></View><View style={{ flex: 1, gap: 2 }}>{editing != null ? (<TextInput value={editing} onChange={setEditing} autoFocus onSubmit={commit} onCancel={() => setEditing(null)} style={{ height: 24 }} />) : (<View onClick={() => setEditing(item.title || '')} style={{ flexDirection: 'row', gap: 4, minHeight: 20, alignItems: 'center' }}>- {marks ? <Text style={{ fontSize: 14, fontWeight: 700, color }}>{marks}</Text> : null}- <Text style={{ flex: 1, fontSize: 14, color: done ? th.textDim : th.text }}>{item.title || t('reminders.untitled')}</Text>+ {marks ? <Text style={{ fontSize: 13, fontWeight: 700, color }}>{marks}</Text> : null}+ <Text style={{ flex: 1, fontSize: 13, color: done ? th.textDim : th.text }}>{item.title || t('reminders.untitled')}</Text></View>)}{item.notes ? <Text style={{ fontSize: 12, color: th.textDim, whiteSpace: 'nowrap', overflow: 'hidden' }}>{item.notes.split('\n')[0]}</Text> : null}@@ -320,12 +322,13 @@ function ReminderRow({ item, depth, color, lists, now, listName }) {</View>) : null}</View>- {item.flag ? <Text style={{ fontSize: 14, color: ORANGE, paddingTop: 1 }}>⚑</Text> : null}+ {item.flag ? <Text style={{ fontSize: 13, color: ORANGE, paddingTop: 1 }}>⚑</Text> : null}<View ref={info} onClick={() => setInspect(true)} style={{ width: 20, height: 20, borderRadius: 10, alignItems: 'center', justifyContent: 'center',border: `1.2px solid ${hover || inspect ? th.accent : 'transparent'}` }}><Text style={{ fontSize: 11, fontWeight: 700, color: hover || inspect ? th.accent : 'transparent' }}>i</Text></View>- <Hairline edge="bottom" inset={0} />+ {/* the separator starts under the text, as in Reminders */}+ <View style={{ position: 'absolute', bottom: 0, height: 1, [rtl ? 'right' : 'left']: 36, [rtl ? 'left' : 'right']: 0, backgroundColor: th.separator, pointerEvents: 'none' }} />{inspect ? <Inspector item={item} lists={lists} anchor={info} onClose={() => setInspect(false)} /> : null}</View>);@@ -408,16 +411,16 @@ function NewRow({ sel, target, color, registerFocus }) {} catch (e) { setError(t('reminders.saveFailed')); }};return (- <View style={{ flexDirection: 'row', alignItems: 'center', gap: 10, paddingVertical: 7, paddingHorizontal: 8 }}>- <View onClick={() => setActive(true)} style={{ width: 20, height: 20, borderRadius: 10, alignItems: 'center', justifyContent: 'center', backgroundColor: active ? 'transparent' : color }}>- {active ? <View style={{ width: 20, height: 20, borderRadius: 10, border: '1.5px solid #a1a1a6' }} /> : <Text style={{ fontSize: 14, fontWeight: 700, color: '#fff' }}>+</Text>}+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 10, minHeight: 36, paddingVertical: 6, paddingHorizontal: 8 }}>+ <View onClick={() => setActive(true)} style={{ width: 18, height: 18, borderRadius: 9, alignItems: 'center', justifyContent: 'center', backgroundColor: active ? 'transparent' : color }}>+ {active ? <View style={{ width: 18, height: 18, borderRadius: 9, border: '1.5px solid #a1a1a6' }} /> : <Text style={{ fontSize: 13, fontWeight: 600, color: '#fff' }}>+</Text>}</View>{active ? (<View style={{ flex: 1 }}><TextInput value={text} onChange={setText} autoFocus placeholder={t('reminders.newReminder')} onSubmit={add} onCancel={() => { setText(''); setActive(false); }} style={{ height: 26 }} /></View>) : (- <Text onClick={() => setActive(true)} style={{ flex: 1, fontSize: 14, color: th.textDim }}>{t('reminders.newReminder')}</Text>+ <Text onClick={() => setActive(true)} style={{ flex: 1, fontSize: 13, color: th.textDim }}>{t('reminders.newReminder')}</Text>)}{error ? <Text style={{ fontSize: 12, color: RED }}>{error}</Text> : null}</View>diff --git a/apps/reminders/ui.jsx b/apps/reminders/ui.jsxindex bb79c41..ec0b39f 100644--- a/apps/reminders/ui.jsx+++ b/apps/reminders/ui.jsx@@ -127,13 +127,13 @@ export function Sheet({ title, onClose, children, footer, width = 440 }) {<View style={{ width, maxWidth: '94%', maxHeight: '94%', borderRadius: 12, backgroundColor: th.windowBg, border: `1px solid ${th.separator}`,boxShadow: '0 18px 50px rgba(0,0,0,0.45)', overflow: 'hidden' }}>{title ? (- <View style={{ paddingHorizontal: 16, paddingTop: 14, paddingBottom: 6 }}>- <Text style={{ fontSize: 15, fontWeight: 700, color: th.text }}>{title}</Text>+ <View style={{ paddingHorizontal: 20, paddingTop: 18, paddingBottom: 4 }}>+ <Text style={{ fontSize: 15, fontWeight: 600, color: th.text }}>{title}</Text></View>) : null}- <View style={{ paddingHorizontal: 16, paddingVertical: 10, gap: 10, flexShrink: 1 }}>{children}</View>+ <View style={{ paddingHorizontal: 20, paddingVertical: 12, gap: 10, flexShrink: 1 }}>{children}</View>{footer ? (- <View style={{ flexDirection: 'row', alignItems: 'center', gap: 8, paddingHorizontal: 16, paddingVertical: 12 }}>+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 8, paddingHorizontal: 20, paddingVertical: 14 }}><Hairline edge="top" />{footer}</View>@@ -244,7 +244,7 @@ export function MiniMonth({ value, onPick, marks, month: ctlMonth, onMonth, cell<View key={c} onClick={() => onPick(d)} style={{ width: cell, height: cell, alignItems: 'center', justifyContent: 'center' }}><View style={{ width: cell - 4, height: cell - 4, borderRadius: (cell - 4) / 2, alignItems: 'center', justifyContent: 'center',backgroundColor: sel ? (isToday ? RED : th.accent) : 'transparent' }}>- <Text style={{ fontSize: 11, fontWeight: isToday || sel ? 700 : 400,+ <Text style={{ fontSize: 11, fontWeight: isToday || sel ? 600 : 400,color: sel ? '#fff' : isToday ? RED : inMonth ? th.text : th.textDim }}>{String(d.getDate())}</Text></View>{marks && marks.has(ymd(d)) && !sel ? <View style={{ position: 'absolute', bottom: 1, width: 3, height: 3, borderRadius: 2, backgroundColor: th.textDim }} /> : null}@@ -256,7 +256,7 @@ export function MiniMonth({ value, onPick, marks, month: ctlMonth, onMonth, cellreturn (<View style={{ width: cell * 7, gap: 2 }}><View style={{ flexDirection: 'row', alignItems: 'center', height: 24 }}>- <Text style={{ flex: 1, fontSize: 12, fontWeight: 700, color: th.text, marginHorizontal: 4 }}>{monthYear(month)}</Text>+ <Text style={{ flex: 1, fontSize: 12, fontWeight: 600, color: th.text, marginHorizontal: 4, whiteSpace: 'nowrap', overflow: 'hidden' }}>{monthYear(month)}</Text><NavArrow glyph={rtl ? '›' : '‹'} onClick={() => setMonth(addMonths(month, -1))} /><NavArrow glyph="●" small onClick={() => { setMonth(new Date(today.getFullYear(), today.getMonth(), 1)); }} /><NavArrow glyph={rtl ? '‹' : '›'} onClick={() => setMonth(addMonths(month, 1))} />diff --git a/apps/scanner/index.jsx b/apps/scanner/index.jsxindex 887dbd1..4b8ed91 100644--- a/apps/scanner/index.jsx+++ b/apps/scanner/index.jsx@@ -60,7 +60,7 @@ export default function Scanner() {if (c.res.length) setRes(c.res.includes(300) ? 300 : c.res.includes(150) ? 150 : c.res[0]);if (c.colors.length && !c.colors.includes('RGB24')) setColor(c.colors[0]);if (!c.platen && c.adf) setSource('Feeder');- }).catch((e) => setError(tr('scanner.unreachable', { error: e.code || e.message })));+ }).catch((e) => setError(tr('scanner.unreachable', { error: e.message })));}, [scanner]);useEffect(() => () => { if (preview) releaseImage(preview.image); }, [preview]);@@ -80,7 +80,7 @@ export default function Scanner() {const img = await decodeImage(r.file, { maxw: 520, maxh: 560 });setPreview(img);setArea(null);- } catch (e) { setError(tr('scanner.failed', { error: e.code || e.message })); }+ } catch (e) { setError(tr('scanner.failed', { error: e.message })); }setBusy(null);};@@ -101,7 +101,7 @@ export default function Scanner() {else await convertImage(r.file, out, { format: format === 'jpeg' ? 'jpeg' : format, native: true, dpi: res });setMsg(tr('scanner.saved', { name }));lastSaved.current = out;- } catch (e) { setError(tr('scanner.failed', { error: e.code || e.message })); }+ } catch (e) { setError(tr('scanner.failed', { error: e.message })); }setBusy(null);};const lastSaved = useRef(null);diff --git a/apps/scanner/manifest.json b/apps/scanner/manifest.jsonindex fc839ec..28cdd3c 100644--- a/apps/scanner/manifest.json+++ b/apps/scanner/manifest.json@@ -1,7 +1,7 @@{"id": "scanner",- "name": "Escáner",- "description": "Escáneres de la red sin controlador (eSCL): vista previa, área, resolución y guardar como PDF, PNG o JPEG",+ "name": "Scanner",+ "description": "Driverless network scanners (eSCL): preview, area, resolution and save as PDF, PNG or JPEG","size": [860, 620],"minSize": [640, 460],"dock": false,diff --git a/apps/screenshots/manifest.json b/apps/screenshots/manifest.jsonindex 3abb3d1..9bfa0c4 100644--- a/apps/screenshots/manifest.json+++ b/apps/screenshots/manifest.json@@ -1,7 +1,7 @@{"id": "screenshots",- "name": "Capturas",- "description": "Capturas de pantalla (pantalla, ventana o área) con anotaciones, y grabación de la pantalla",+ "name": "Screenshots",+ "description": "Screenshots (screen, window or area) with annotations, and screen recording","size": [440, 420],"minSize": [380, 360],"dock": false,diff --git a/apps/settings/Displays.jsx b/apps/settings/Displays.jsxindex 1b08feb..92b6555 100644--- a/apps/settings/Displays.jsx+++ b/apps/settings/Displays.jsx@@ -2,25 +2,47 @@// rotation, scale (100–200 %, sharp), the main display, brightness and Night Shift (docs/SETTINGS.md,// "Displays", and docs/DISPLAYS.md). Changes apply live with the system's 15-second "Keep these// display settings?" countdown (sdk/hardware.jsx) and are saved per display (EDID identity).+// Layout after macOS System Settings → Displays: the arrangement on top, then the selected display's+// settings in inset boxes, with the scale as "Larger text … More space" tiles.import {- View, Text, useTheme, useLocale, useSettings, Slider, Toggle, Segmented, Button, admin, useDisplays, applyDisplay, DisplayGlyph, addListener,- arrangeDisplay, setDisplayMirror, setMainDisplay, setCaptureAllDisplays,+ 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,} from '@lordos/sdk';import { useEffect, useRef, useState } from 'react';-import { GroupBox, SettingRow, PopUp, Note, Stack, TimeField } from './ui.jsx';+import { Section, SettingRow, PopUp, Note, Stack, TimeField } from './ui.jsx';const hz = (mhz) => {const v = mhz / 1000;return Math.abs(v - Math.round(v)) < 0.005 ? String(Math.round(v)) : v.toFixed(2);};+const SCALES = [200, 175, 150, 125, 100]; // tiles: larger text first, more space last++// The width of a box after layout (the page column narrows with the window).+function useWidth(ref, fallback) {+ const [w, setW] = useState(fallback);+ useEffect(() => {+ const measure = () => {+ const n = ref.current;+ if (!n) return;+ const x = Math.round(lord.getLayout(n.id)[2]);+ if (x > 0) setW((old) => (Math.abs(x - old) > 1 ? x : old));+ };+ measure();+ const id = setTimeout(measure, 60); // the first layout may not be done yet+ return () => clearTimeout(id);+ });+ return w;+}// The arrangement (docs/DISPLAYS.md): every active display at its place in the desktop, proportional to-// its logical size. 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, tr }) {+// 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 }) {const act = outs.filter((o) => o.active && o.w);- const W = 520, H = 170;+ const box = useRef(null);+ const W = useWidth(box, 520), H = 180;const [drag, setDrag] = useState(null); // { id, x, y } in logical px while draggingconst st = useRef(null);useEffect(() => {@@ -41,29 +63,35 @@ function Arrangement({ outs, sel, onSelect, mirror, t, tr }) {});return () => { offMove(); offUp(); };}, []);- if (!act.length) return null;+ const dark = t.mode === 'dark';+ const frame = { height: H, borderRadius: 10, direction: 'ltr', overflow: 'hidden',+ backgroundColor: dark ? 'rgba(0,0,0,0.22)' : 'rgba(0,0,0,0.045)', border: `1px solid ${t.separator}` };+ if (!act.length) return <View ref={box} style={frame} />;// mirror: the displays are drawn one behind the other; extend: at their placeconst 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 - 40) / Math.max(1, x1 - x0), (H - 30) / Math.max(1, y1 - y0));+ 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;return (- <View style={{ height: H, borderRadius: 10, direction: 'ltr', overflow: 'hidden',- backgroundColor: t.mode === 'dark' ? 'rgba(0,0,0,0.22)' : 'rgba(0,0,0,0.05)', border: `1px solid ${t.separator}` }}>+ <View ref={box} style={frame}>{boxes.map(({ o, x, y }) => {const on = o.id === sel;+ const w = Math.max(28, o.w * k - 3), h = Math.max(18, o.h * k - 3);return (<View key={o.id}- onMouseDown={(e) => { onSelect(o.id); if (!mirror && act.length > 1) st.current = { id: o.id, px: e.x, py: e.y, ox: o.x, oy: o.y, k, moved: false }; }}- style={{ position: 'absolute', left: offX + (x - x0) * k, top: offY + (y - y0) * k, width: Math.max(24, o.w * k - 2), height: Math.max(16, o.h * k - 2),- borderRadius: 5, alignItems: 'center', justifyContent: 'center', cursor: !mirror && act.length > 1 ? 'grab' : 'pointer',- background: on ? 'linear-gradient(135deg, #3b6fd8, #8f4fd1)' : 'linear-gradient(135deg, #5b5f6a, #3a3d45)',- border: on ? `2px solid ${t.accent}` : `1px solid ${t.separator}`, boxShadow: '0 4px 14px rgba(0,0,0,0.3)' }}>- {o.main ? <View style={{ position: 'absolute', left: 3, right: 3, top: 3, height: 4, borderRadius: 2, backgroundColor: 'rgba(255,255,255,0.8)' }} /> : null}- <Text style={{ fontSize: 11, fontWeight: 700, color: '#fff', textAlign: 'center' }}>{o.name}</Text>- <Text style={{ fontSize: 10, color: 'rgba(255,255,255,0.8)', textAlign: 'center' }}>{`${o.mode.w}×${o.mode.h} · ${o.scale} %`}</Text>+ 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 }; }}+ 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'}` }}>+ <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)' }}>+ {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>+ {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>);})}@@ -71,12 +99,73 @@ function Arrangement({ outs, sel, onSelect, mirror, t, tr }) {);}+// One scale as a picture of the screen with a window: the larger the scale, the bigger the window+// (macOS "Larger text … More space"). A 2 px accent ring marks the current one.+function ScaleTile({ n, on, rec, label, onPick, t, tr }) {+ const [hover, setHover] = useState(false);+ const ww = Math.round(20 + (n - 100) * 0.26), wh = Math.round(ww * 0.64);+ return (+ <View onClick={onPick} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}+ style={{ flex: 1, minWidth: 0, alignItems: 'center', gap: 5 }}>+ <View style={{ width: 70, height: 48, padding: 2, borderRadius: 8, border: `2px solid ${on ? t.accent : 'transparent'}` }}>+ <View style={{ flex: 1, borderRadius: 4, overflow: 'hidden', alignItems: 'center', justifyContent: 'center', direction: 'ltr',+ background: 'linear-gradient(160deg, #3d7be0, #7b46cf)', opacity: hover && !on ? 0.85 : 1 }}>+ <View style={{ position: 'absolute', left: 0, right: 0, top: 0, height: Math.max(2, Math.round(n / 50)), backgroundColor: 'rgba(255,255,255,0.8)' }} />+ <View style={{ width: ww, height: wh, marginTop: 3, borderRadius: 2, backgroundColor: 'rgba(246,246,249,0.95)',+ boxShadow: '0 1px 3px rgba(0,0,0,0.3)' }}>+ <View style={{ height: Math.max(2, Math.round(wh / 6)), backgroundColor: 'rgba(0,0,0,0.12)', borderRadius: 2 }} />+ </View>+ </View>+ </View>+ <Text style={{ fontSize: typeScale.caption, color: on ? t.text : t.textDim, fontWeight: on ? 600 : 400, textAlign: 'center', whiteSpace: 'nowrap' }}>{label}</Text>+ <Text style={{ fontSize: 10, color: rec ? t.textDim : 'transparent', textAlign: 'center', whiteSpace: 'nowrap', marginTop: -4 }}>{tr('prefs.display.recommended')}</Text>+ </View>+ );+}++function ScaleTiles({ value, rec, onPick, t, tr }) {+ return (+ <View style={{ paddingTop: spacing.m, paddingBottom: spacing.s, gap: spacing.xs }}>+ <View style={{ flexDirection: 'row', alignItems: 'flex-start', gap: spacing.xs }}>+ {SCALES.map((n) => (+ <ScaleTile key={n} n={n} on={n === value} rec={n === rec} label={tr('prefs.display.scaleN', { n })} onPick={() => n !== value && onPick(n)} t={t} tr={tr} />+ ))}+ </View>+ <View style={{ flexDirection: 'row', paddingHorizontal: spacing.xs }}>+ <Text style={{ flex: 1, fontSize: typeScale.caption, color: t.textDim, textAlign: 'start' }}>{tr('prefs.display.largerText')}</Text>+ <Text style={{ flex: 1, fontSize: typeScale.caption, color: t.textDim, textAlign: 'end' }}>{tr('prefs.display.moreSpace')}</Text>+ </View>+ </View>+ );+}++// The selected display: its picture, name and size line (first row of its box).+function DisplayHeader({ cur, sizeLine, several, 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>+ {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>+ </View>+ ) : null}+ </View>+ <Text style={{ fontSize: typeScale.caption, color: t.textDim, textAlign: 'start', whiteSpace: 'nowrap', overflow: 'hidden' }}>{sizeLine}</Text>+ </View>+ </View>+ );+}+function Brightness({ list }) {+ const t = useTheme();const { t: tr } = useLocale();const [vals, setVals] = useState({});const timer = useRef(0);const [err, setErr] = useState('');- if (!list.length) return <SettingRow label={tr('prefs.display.brightness')} hint={tr('prefs.display.noBacklight')} disabled />;+ if (!list.length) return [<SettingRow key="none" label={tr('prefs.display.brightness')} hint={tr('prefs.display.noBacklight')} disabled />];return list.map((b) => {const v = vals[b.name] ?? b.value;const set = (x) => {@@ -87,10 +176,10 @@ function Brightness({ list }) {};return (<SettingRow key={b.name} label={tr('prefs.display.brightness')} hint={err || (list.length > 1 ? b.name : '')}>- <View style={{ flexDirection: 'row', alignItems: 'center', gap: 8, direction: 'ltr' }}>- <Text style={{ fontSize: 12, color: '#8e8e93' }}>☼</Text>- <Slider value={v} min={0} max={b.max} width={200} onChange={set} />- <Text style={{ fontSize: 15, color: '#8e8e93' }}>☀</Text>+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: spacing.s, direction: 'ltr' }}>+ <Text style={{ fontSize: 12, color: t.textDim }}>☼</Text>+ <Slider value={v} min={0} max={b.max} width={180} onChange={set} />+ <Text style={{ fontSize: 15, color: t.textDim }}>☀</Text></View></SettingRow>);@@ -113,35 +202,35 @@ function NightShift() {? (sun ? tr('prefs.night.sunHint', { set: fmt(sun.sunset), rise: fmt(sun.sunrise) }) : tr('prefs.night.noSun')): p.schedule === 'custom' ? tr('prefs.night.customHint') : tr('prefs.night.offHint');return (- <GroupBox title={tr('prefs.night.title')} footer={tr('prefs.night.footer')}>+ <Section title={tr('prefs.night.title')} footer={tr('prefs.night.footer')}><SettingRow label={tr('prefs.night.schedule')} hint={scheduleHint}><PopUp value={p.schedule} onChange={(schedule) => patch({ schedule, manual: null })}options={[['off', tr('prefs.night.off')], ['sun', tr('prefs.night.sun')], ['custom', tr('prefs.night.custom')]]} /></SettingRow>{p.schedule === 'custom' && (<SettingRow label={tr('prefs.night.from')}>- <View style={{ flexDirection: 'row', alignItems: 'center', gap: 8 }}>+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: spacing.s }}><TimeField value={p.from} onChange={(from) => patch({ from })} format={fmt} />- <Text style={{ fontSize: 12, color: t.textDim }}>{tr('prefs.night.to')}</Text>+ <Text style={{ fontSize: typeScale.callout, color: t.textDim }}>{tr('prefs.night.to')}</Text><TimeField value={p.to} onChange={(to) => patch({ to })} format={fmt} /></View></SettingRow>)}<SettingRow label={tr('prefs.night.now')}hint={p.manual && Date.now() < p.manual.until ? tr(p.manual.on ? 'prefs.night.manualOn' : 'prefs.night.manualOff', { time: formatTime(new Date(p.manual.until)) }) : ''}>- <Toggle on={active} onChange={(on) => setNightManual(on)} />+ <Toggle small on={active} onChange={(on) => setNightManual(on)} /></SettingRow><SettingRow label={tr('prefs.night.temp')}>- <View style={{ flexDirection: 'row', alignItems: 'center', gap: 8, direction: 'ltr' }}>- <Text style={{ fontSize: 11, color: t.textDim }}>{tr('prefs.night.lessWarm')}</Text>+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: spacing.s, direction: 'ltr' }}>+ <Text style={{ fontSize: typeScale.caption, color: t.textDim }}>{tr('prefs.night.lessWarm')}</Text>{/* the slider goes from less warm (left) to more warm (right) */}- <Slider value={6500 - (preview ?? p.temp)} min={6500 - 6000} max={6500 - 1900} width={170}+ <Slider value={6500 - (preview ?? p.temp)} min={6500 - 6000} max={6500 - 1900} width={150}onChange={(v) => { const k = Math.round(6500 - v); setPreview(k); previewNight(k); clearTimeout(tm.current);tm.current = setTimeout(() => { setPreview(null); patch({ temp: k }); }, 400); }} />- <Text style={{ fontSize: 11, color: t.textDim }}>{tr('prefs.night.moreWarm')}</Text>+ <Text style={{ fontSize: typeScale.caption, color: t.textDim }}>{tr('prefs.night.moreWarm')}</Text></View></SettingRow>- </GroupBox>+ </Section>);}@@ -152,6 +241,7 @@ export function DisplaysSettings() {const [s, set] = useSettings();const [msg, setMsg] = useState('');const [selId, setSel] = useState(null);+ const [list, setList] = useState(false); // the scale as a list instead of tilesif (!d) return <Note>{tr('prefs.display.unavailable')}</Note>;const outs = d.outputs || [];const act = outs.filter((o) => o.active);@@ -170,63 +260,83 @@ export function DisplaysSettings() {const go = (o, x) => { if (!applyDisplay(o, x)) setMsg(tr('prefs.display.failed')); else setMsg(''); };const native = (r) => r.w === cur.preferred.w && r.h === cur.preferred.h;const scale = cur.scale || 100, rot = cur.rotation || 0, rec = cur.recommended || 100;+ const setScale = (sc) => go(cur, { w: mode.w, h: mode.h, refresh: mode.refresh, rotation: rot, scale: sc });const looks = scale !== 100 && cur.w ? tr('prefs.display.looksLike', { w: cur.w, h: cur.h }) : '';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;return (<Stack>- <Arrangement outs={outs} sel={cur.id} onSelect={setSel} mirror={d.mirror} t={t} tr={tr} />- {act.length > 1 && !d.mirror ? <Text style={{ fontSize: 11, color: t.textDim, textAlign: 'start', marginTop: -12 }}>{tr('prefs.display.arrangeHint')}</Text> : null}- <View style={{ flexDirection: 'row', alignItems: 'center', gap: 12, marginTop: -6 }}>- <DisplayGlyph size={34} color={t.accent} />- <View style={{ flex: 1 }}>- <Text style={{ fontSize: 14, fontWeight: 700, color: t.text, textAlign: 'start' }}>{cur.name}{cur.main && several ? ` · ${tr('prefs.display.mainLabel')}` : ''}</Text>- <Text style={{ fontSize: 11, color: t.textDim, textAlign: 'start' }}>{sizeLine}</Text>- </View>- {several && !cur.main && cur.active ? <Button small label={tr('prefs.display.makeMain')} onClick={() => setMainDisplay(cur.id)} /> : null}- </View>- <GroupBox>- <SettingRow label={tr('prefs.display.scale')} hint={tr('prefs.display.scaleHint')}>- <PopUp value={scale} onChange={(sc) => go(cur, { w: mode.w, h: mode.h, refresh: mode.refresh, rotation: rot, scale: sc })} options={scales} />- </SettingRow>+ <ArrangementBlock outs={outs} sel={cur.id} onSelect={setSel} mirror={d.mirror} t={t}+ hint={act.length > 1 && !d.mirror ? tr('prefs.display.arrangeHint') : ''} />++ <Section>+ <DisplayHeader cur={cur} sizeLine={sizeLine} several={several} 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); }} />+ </SettingRow>+ ) : null}+ <Brightness list={d.backlight || []} />+ </Section>++ <Section title={tr('prefs.display.scale')} footer={tr('prefs.display.scaleHint')}+ accessory={(+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: spacing.s }}>+ <Text style={{ fontSize: typeScale.callout, color: t.textDim }}>{tr('prefs.display.showList')}</Text>+ <Toggle small on={list} onChange={setList} />+ </View>+ )}>+ {list ? (+ <SettingRow label={tr('prefs.display.scale')} hint={looks}>+ <PopUp width={210} value={scale} onChange={setScale} options={scales} />+ </SettingRow>+ ) : <ScaleTiles value={scale} rec={rec} onPick={setScale} t={t} tr={tr} />}<SettingRow label={tr('prefs.display.resolution')}>- <PopUp width={230} value={`${curRes?.w}x${curRes?.h}`} onChange={(v) => { const [w, h] = v.split('x').map(Number); go(cur, { w, h, refresh: 0, rotation: rot, scale }); }}+ <PopUp width={210} value={`${curRes?.w}x${curRes?.h}`} onChange={(v) => { const [w, h] = v.split('x').map(Number); go(cur, { w, h, refresh: 0, rotation: rot, scale }); }}options={res.map((r) => [`${r.w}x${r.h}`, native(r) ? tr('prefs.display.native', { w: r.w, h: r.h }) : `${r.w} × ${r.h}`])} /></SettingRow><SettingRow label={tr('prefs.display.refresh')}>- <PopUp value={mode.refresh} onChange={(refresh) => go(cur, { w: mode.w, h: mode.h, refresh, rotation: rot, scale })}+ <PopUp width={210} value={mode.refresh} onChange={(refresh) => go(cur, { w: mode.w, h: mode.h, refresh, rotation: rot, scale })}options={(curRes?.rates || []).map((r) => [r, tr('prefs.display.hz', { hz: hz(r) })])} disabled={(curRes?.rates || []).length < 2} /></SettingRow><SettingRow label={tr('prefs.display.rotation')} hint={rot ? tr('prefs.display.rotationHint') : ''}>- <PopUp value={rot} onChange={(rotation) => go(cur, { w: mode.w, h: mode.h, refresh: mode.refresh, rotation, scale })}+ <PopUp width={210} value={rot} onChange={(rotation) => go(cur, { w: mode.w, h: mode.h, refresh: mode.refresh, rotation, scale })}options={[[0, tr('prefs.display.rotStandard')], [1, '90°'], [2, '180°'], [3, '270°']]} /></SettingRow>- </GroupBox>- {msg ? <Note tone="warn">{msg}</Note> : null}+ </Section>+ {msg ? <Note tone="warn" style={{ marginTop: -12 }}>{msg}</Note> : null}+{several ? (- <GroupBox title={tr('prefs.display.multiple')} footer={tr('prefs.display.multipleHint')}>- <SettingRow label={tr('prefs.display.useAs')} disabled={act.length < 2 && !d.mirror}>- <Segmented small value={d.mirror ? 'mirror' : 'extend'} onChange={(v) => setDisplayMirror(v === 'mirror')}- options={[['extend', tr('prefs.display.extend')], ['mirror', tr('prefs.display.mirror')]]} />+ <Section title={tr('prefs.display.multiple')} footer={tr('prefs.display.multipleHint')}>+ <SettingRow label={tr('prefs.display.mirrorDisplays')} disabled={act.length < 2 && !d.mirror}>+ <Toggle small on={!!d.mirror} onChange={(on) => setDisplayMirror(on)} /></SettingRow><SettingRow label={tr('prefs.display.menuBarAll')} disabled={d.mirror}>- <Toggle on={!!s.menuBarAllDisplays} onChange={(on) => set({ menuBarAllDisplays: on })} />+ <Toggle small on={!!s.menuBarAllDisplays} onChange={(on) => set({ menuBarAllDisplays: on })} /></SettingRow><SettingRow label={tr('prefs.display.capture')} hint={tr('prefs.display.captureHint')}>- <Segmented small value={d.captureAll ? 'all' : 'main'} onChange={(v) => setCaptureAllDisplays(v === 'all')}+ <PopUp width={170} value={d.captureAll ? 'all' : 'main'} onChange={(v) => setCaptureAllDisplays(v === 'all')}options={[['main', tr('prefs.display.captureMain')], ['all', tr('prefs.display.captureAll')]]} /></SettingRow>{outs.filter((o) => !o.active).map((o) => (<SettingRow key={o.id} label={o.name} hint={tr('prefs.display.noCrtc', { connector: o.connector })} disabled />))}- </GroupBox>+ </Section>) : null}- <GroupBox>- <Brightness list={d.backlight || []} />- </GroupBox>+<NightShift />- {d.softTint ? <Note>{tr('prefs.night.software')}</Note> : null}+ {d.softTint ? <Note style={{ marginTop: -12 }}>{tr('prefs.night.software')}</Note> : null}</Stack>);}++// The arrangement with its hint under it (like a section footer).+function ArrangementBlock({ hint, ...p }) {+ return (+ <View style={{ gap: 6 }}>+ <Arrangement {...p} />+ {hint ? <Note>{hint}</Note> : null}+ </View>+ );+}diff --git a/apps/settings/General.jsx b/apps/settings/General.jsxindex 81460d4..3a5eea6 100644--- a/apps/settings/General.jsx+++ b/apps/settings/General.jsx@@ -31,7 +31,7 @@ export function General() {</View><Card title={tr('settings.general.machine')} rows={[[tr('settings.general.name'), info.hostname],- [tr('about.cpu'), tr('about.cpuValue', { cpu: cpu.slice(0, 40), count: info.cores })],+ [tr('about.cpu'), tr('about.cpuValue', { cpu: cpu.slice(0, 40) || tr('about.cpuUnknown'), count: info.cores })],[tr('about.memory'), tr('shell.cc.memDetail', { used: formatBytes((info.memTotalKB - info.memAvailableKB) * 1024), total: formatBytes(info.memTotalKB * 1024) })],info.diskTotal ? [tr('settings.general.storage'), tr('settings.general.storageValue', { free: formatBytes(info.diskFree), total: formatBytes(info.diskTotal) })] : null,[tr('about.display'), `${screen.width} × ${screen.height}`],diff --git a/apps/settings/Network.jsx b/apps/settings/Network.jsxindex 991b528..182539f 100644--- a/apps/settings/Network.jsx+++ b/apps/settings/Network.jsx@@ -2,7 +2,7 @@// (lord.net, netlink) and makes changes through the administration helper (net-* actions). See docs/NETWORK.md.import {View, Text, useTheme, useLocale, Button, Toggle, Segmented, TextInput,- admin, fs, formatBytes, keyring, AutofillButton, spacing, typeScale,+ admin, fs, formatBytes, keyring, AutofillButton, spacing, typeScale, errorText, statusText,} from '@lordos/sdk';import { useEffect, useState } from 'react';import { Stack, Section, SettingRow, ValueRow, FieldRow, Badge, Note, Message, Actions, StatusDot, tint } from './ui.jsx';@@ -26,7 +26,9 @@ function useNet(intervalMs = 2000) {return has() ? { ifs: lord.net.interfaces(), routes: lord.net.routes(), dns: lord.net.dns() } : { ifs: [], routes: [], dns: { servers: [] } };}-// Notices from the network processes (DHCP, Wi-Fi, VPN) to show status.+// Notices from the network processes (DHCP, Wi-Fi, VPN) to show status. The tokens are English and+// stable ("net vpn <name> connected"); an "error" carries a code line (server/src/errcode.h) or a+// program's own output, both shown with errorText().const events = [];const eventSubs = new Set();admin.onEvent((text) => {@@ -37,8 +39,9 @@ admin.onEvent((text) => {});function useNetEvent(fn) { useEffect(() => { eventSubs.add(fn); return () => eventSubs.delete(fn); }, []); }+// The OK reply is a status code line (t('status.<code>')) unless the caller has its own text.const run = (setMsg, action, arg, okText) => admin.run(action, arg, undefined, { quiet: true }).then(- (r) => { setMsg({ ok: true, text: okText || r }); return r; },+ (r) => { setMsg({ ok: true, text: okText || statusText(r) }); return r; },(e) => { setMsg({ ok: false, text: e.message }); return null; });const TYPES = ['ethernet', 'wifi', 'wireguard', 'tun', 'bridge', 'veth', 'vlan', 'bond', 'dummy'];@@ -345,7 +348,10 @@ function VpnPage({ net }) {if (m[2] === 'connected') setMsg({ ok: true, text: tr('network.vpn.connectedMsg', { name: m[1] }) });else if (m[2] === 'need-auth') setAuth({ name: m[1], user: '', pass: '' });else if (m[2] === 'auth-failed') setMsg({ ok: false, text: tr('network.vpn.authFailed', { name: m[1] }) });- else if (m[2] === 'error' || m[2] === 'log') setMsg({ ok: false, text: `${m[1]}: ${m[3] || tr('network.vpn.error')}` });+ else if (m[2] === 'error' || m[2] === 'log') {+ const why = m[3] ? errorText(m[3]) : tr('network.vpn.error');+ setMsg({ ok: false, text: m[1] === '-' ? why : `${m[1]}: ${why}` });+ }refresh();setTick((x) => x + 1);});diff --git a/apps/settings/index.jsx b/apps/settings/index.jsxindex 53d75b9..f6b6eca 100644--- a/apps/settings/index.jsx+++ b/apps/settings/index.jsx@@ -4,7 +4,7 @@// from ./ui.jsx (docs/DESIGN.md, "Settings").import {View, Text, Image, useTheme, useSettings, themes, session, keyboard, admin, languages, setLanguage, useLocale,- reloadCatalogs, fs, useStore, SidebarItem, Toggle, Button, TextInput, ScrollView, SearchField, Hairline, useSystemInfo, useAppWindow, useTrackpads,+ reloadCatalogs, tOptional, statusText, fs, useStore, SidebarItem, Toggle, Button, TextInput, ScrollView, SearchField, Hairline, useSystemInfo, useAppWindow, useTrackpads,spacing, typeScale,} from '@lordos/sdk';import { useEffect, useState } from 'react';@@ -124,6 +124,9 @@ function Appearance() {);}+// A theme names its wallpapers with a locale key (nameKey) and an English fallback (name).+const wallpaperName = (w) => (w.nameKey && tOptional(w.nameKey)) || w.name;+function Wallpapers() {const t = useTheme();const { t: tr } = useLocale();@@ -138,7 +141,7 @@ function Wallpapers() {<View style={{ width: 128, height: 80, borderRadius: 8, overflow: 'hidden', border: `1px solid ${t.separator}` }}><Image src={cur.src} style={{ width: '100%', height: '100%', objectFit: 'cover' }} /></View>- <Text style={{ flex: 1, minWidth: 0, fontSize: typeScale.headline, fontWeight: 600, color: t.text, textAlign: 'start' }}>{cur.name}</Text>+ <Text style={{ flex: 1, minWidth: 0, fontSize: typeScale.headline, fontWeight: 600, color: t.text, textAlign: 'start' }}>{wallpaperName(cur)}</Text></View></Section><Section title={tr('settings.section.wallpaper')}>@@ -150,7 +153,7 @@ function Wallpapers() {<Image src={w.src} style={{ width: '100%', height: '100%', objectFit: 'cover' }} /></View></View>- <Text style={{ fontSize: typeScale.caption, color: cur.id === w.id ? t.text : t.textDim, fontWeight: cur.id === w.id ? 600 : 400 }}>{w.name}</Text>+ <Text style={{ fontSize: typeScale.caption, color: cur.id === w.id ? t.text : t.textDim, fontWeight: cur.id === w.id ? 600 : 400 }}>{wallpaperName(w)}</Text></View>))}</View>@@ -171,7 +174,7 @@ function AdminLog() {<Section><View style={{ paddingVertical: spacing.m, gap: 3 }}><Text style={{ fontSize: typeScale.callout, fontWeight: 600, color: t.text, textAlign: 'start' }}>{tr('settings.admin.running', { action: tr(`settings.admin.${busy.action}`), arg: busy.arg })}</Text>- {busy.log.slice(-6).map((l, i) => <Text key={i} style={{ fontSize: typeScale.caption, color: t.textDim, whiteSpace: 'nowrap', overflow: 'hidden', direction: 'ltr', textAlign: 'start' }}>{l}</Text>)}+ {busy.log.slice(-6).map((l, i) => <Text key={i} style={{ fontSize: typeScale.caption, color: t.textDim, whiteSpace: 'nowrap', overflow: 'hidden', direction: 'ltr', textAlign: 'start' }}>{statusText(l)}</Text>)}</View></Section>);diff --git a/apps/settings/manifest.json b/apps/settings/manifest.jsonindex c2f2ade..8db8b4a 100644--- a/apps/settings/manifest.json+++ b/apps/settings/manifest.json@@ -1,7 +1,7 @@{"id": "settings",- "name": "Ajustes",- "description": "General, apariencia, red, sonido, idioma, teclado, actualizaciones y temas",+ "name": "Settings",+ "description": "General, appearance, network, sound, language, keyboard, updates and themes","size": [880,600diff --git a/apps/store/debian.js b/apps/store/debian.jsindex 174fd13..e757e17 100644--- a/apps/store/debian.js+++ b/apps/store/debian.js@@ -1,11 +1,11 @@// debian.js — the Debian part of the Store. It reads our own index (lord.pkg, no root;// server/src/pkg) and makes changes through the administration helper (pkg-update, pkg-install,// pkg-remove, pkg-upgrade, pkg-install-file). Before changing anything it shows the plan: what is-// installed, upgraded or removed, and how much is downloaded and used. See docs/PAQUETES.md.+// installed, upgraded or removed, and how much is downloaded and used. See docs/PACKAGES.md.import { createElement as h, useEffect, useState } from 'react';import {View, Text, Image, Button, EmptyState, GroupBox, useTheme, useStore, createStore, admin, formatBytes, formatDate,- refreshApps, launchApp, useLauncherApps, LetterIcon, typeScale, spacing, direction, t, locale,+ refreshApps, launchApp, useLauncherApps, LetterIcon, typeScale, spacing, direction, t, locale, errorText, statusText,} from '@lordos/sdk';const available = () => typeof lord.pkg !== 'undefined';@@ -19,17 +19,18 @@ admin.onEvent((text) => {if (text === 'pkg index' || text === 'pkg changed') { bump(); if (text === 'pkg changed') refreshApps(); }});-// Runs a package action showing its progress ("progress <phase> <done> <total>").+// Runs a package action showing its progress ("progress <phase> <done> <total>"). The other LOG+// lines and the final OK are status code lines (server/src/pkg/pkg.c), shown with statusText().function runJob(action, arg, title) {state.set((s) => ({ ...s, job: { title, phase: '', done: 0, total: 0, log: [] }, msg: null }));const onLog = (line) => {const m = /^progress (\w+) (\d+) (\d+)$/.exec(line);state.set((s) => ({ ...s, job: s.job && (m? { ...s.job, phase: m[1], done: Number(m[2]), total: Number(m[3]) }- : /^plan /.test(line) ? s.job : { ...s.job, log: [...s.job.log, line].slice(-4) }) }));+ : /^plan /.test(line) ? s.job : { ...s.job, log: [...s.job.log, statusText(line)].slice(-4) }) }));};return admin.run(action, arg, onLog).then(- (ok) => { state.set((s) => ({ ...s, job: null, msg: { ok: true, text: ok } })); bump(); refreshApps(); return true; },+ (ok) => { state.set((s) => ({ ...s, job: null, msg: { ok: true, text: statusText(ok) } })); bump(); refreshApps(); return true; },(e) => { state.set((s) => ({ ...s, job: null, msg: { ok: false, text: e.message } })); bump(); return false; },);}@@ -79,7 +80,7 @@ function Progress() {// Summary of a plan: what happens and how much space it takes.function PlanView({ plan }) {const th = useTheme();- if (!plan.ok) return h(Text, { style: { fontSize: 12, color: '#ff453a' } }, plan.error || t('store.plan.impossible'));+ if (!plan.ok) return h(Text, { style: { fontSize: 12, color: '#ff453a' } }, (plan.error && errorText(plan.error)) || t('store.plan.impossible'));const by = (a) => plan.items.filter((i) => i.action === a);const line = (label, list) => (list.length ? h(Text, { style: { fontSize: 12, color: th.text, lineHeight: 1.4 } },`${label}: ${list.slice(0, 14).map((i) => i.name).join(', ')}${list.length > 14 ? ` ${t('store.plan.more', { count: list.length - 14 })}` : ''}`) : null);diff --git a/apps/store/index.jsx b/apps/store/index.jsxindex b806b86..94ca1d7 100644--- a/apps/store/index.jsx+++ b/apps/store/index.jsx@@ -7,7 +7,20 @@ import {import { useEffect, useMemo, useState } from 'react';import { debian, useDebian } from './debian.js';-// Trust level of a package from its signature (see docs/FIRMA.md).+// The user's Downloads folder relative to home ("Downloads/"), from xdg-user-dirs; without it, the+// first of the usual names that exists, or the home folder itself.+function downloadsDir() {+ let conf = '';+ try { conf = fs.read('.config/user-dirs.dirs'); } catch (e) { /* no xdg-user-dirs */ }+ const m = /^XDG_DOWNLOAD_DIR="\$HOME\/([^"]+)"/m.exec(conf);+ if (m) return `${m[1]}/`;+ for (const d of ['Downloads', 'Descargas', 'Transferências']) {+ try { fs.list(d); return `${d}/`; } catch (e) { /* not there */ }+ }+ return '';+}++// Trust level of a package from its signature (see docs/SIGNING.md).const TRUST = {lordos: { color: '#30d158', glyph: '◆' },verified: { color: '#0a84ff', glyph: '✓' },@@ -215,7 +228,7 @@ function LordOSPage({ query }) {);}-// Trust, "Modified by you", Restore original and Share my version (docs/FIRMA.md).+// Trust, "Modified by you", Restore original and Share my version (docs/SIGNING.md).function PkgManage({ pkg, onMsg }) {const t = useTheme();const { t: tr } = useLocale();@@ -231,8 +244,8 @@ function PkgManage({ pkg, onMsg }) {try {const key = lord.sign.userKey();const base = `${pkg.id}@${st.version} by ${st.signer || tr('store.trust.unknownAuthor')}`;- const manifest = { ...pkgManifest(pkg), id: pkg.id, version: `${st.version}+mia`, basedOn: base };- const out = lord.sign.share(pkg.id, JSON.stringify(manifest, null, 2), `Descargas/${pkg.id}-mia.lpk`);+ const manifest = { ...pkgManifest(pkg), id: pkg.id, version: `${st.version}+mine`, basedOn: base };+ const out = lord.sign.share(pkg.id, JSON.stringify(manifest, null, 2), `${downloadsDir()}${pkg.id}-mine.lpk`);onMsg({ ok: true, text: tr('store.share.done', { path: out.replace(fs.home(), '~'), key: key.public.slice(0, 16) }) });} catch (e) { onMsg({ ok: false, text: e.message }); }};diff --git a/apps/store/manifest.json b/apps/store/manifest.jsonindex fc3c22a..35fe667 100644--- a/apps/store/manifest.json+++ b/apps/store/manifest.json@@ -1,7 +1,7 @@{"id": "store",- "name": "Tienda",- "description": "Apps de LordOS y de Debian: buscar, instalar, actualizar y quitar",+ "name": "Store",+ "description": "LordOS and Debian apps: search, install, update and remove","size": [880,580diff --git a/apps/terminal/manifest.json b/apps/terminal/manifest.jsonindex 3215ede..f87dd07 100644--- a/apps/terminal/manifest.json+++ b/apps/terminal/manifest.json@@ -1,7 +1,7 @@{"id": "terminal","name": "Terminal",- "description": "Terminal nativa estilo iTerm2: pestañas, paneles, perfiles, búsqueda, imágenes",+ "description": "iTerm2-style native terminal: tabs, panes, profiles, search, images","size": [860,540diff --git a/assets/locales/en/about.json b/assets/locales/en/about.jsonindex aeb80f1..f073241 100644--- a/assets/locales/en/about.json+++ b/assets/locales/en/about.json@@ -1,5 +1,6 @@{"cpu": "Processor",+ "cpuUnknown": "Unknown","cpuValue": {"one": "{cpu} · {count} core","other": "{cpu} · {count} cores"diff --git a/assets/locales/en/backup.json b/assets/locales/en/backup.jsonindex 3eb1177..65fb4ef 100644--- a/assets/locales/en/backup.json+++ b/assets/locales/en/backup.json@@ -108,12 +108,5 @@"encLock": "Lock","encWorking": "Checking the passphrase…","notify.lockedTitle": "Backups are encrypted",- "notify.lockedBody": "Enter the passphrase so scheduled backups can continue.",- "err.wrong-passphrase": "Wrong passphrase",- "err.not-encrypted": "This destination is not encrypted",- "err.plain-backups-exist": "There are unencrypted backups on this destination: choose another one",- "err.setup-failed": "Couldn't turn on encryption",- "err.no-destination": "Choose a destination first",- "err.locked": "Backups are encrypted: unlock them first",- "err.interrupted": "It was interrupted"-}\ No newline at end of file+ "notify.lockedBody": "Enter the passphrase so scheduled backups can continue."+}diff --git a/assets/locales/en/docs.json b/assets/locales/en/docs.jsonindex 3bfc18b..7ba4769 100644--- a/assets/locales/en/docs.json+++ b/assets/locales/en/docs.json@@ -48,5 +48,26 @@"err.too-big": "it is too large","err.too-many": "it has too many files","err.corrupt": "it is damaged",- "err.write": "could not write"+ "err.write": "could not write",+ "err.unavailable": "the document helper is not available",+ "err.cancelled": "cancelled",+ "err.crash": "the document helper stopped unexpectedly",+ "err.timeout": "it took too long",+ "err.protocol": "the document helper sent an invalid reply",+ "err.spawn": "could not start the document helper",+ "err.closed": "the document was closed",+ "err.bad-request": "invalid request",+ "err.bad-field": "invalid form field",+ "err.bad-page": "invalid page",+ "err.busy": "the document helper is busy",+ "err.memory": "out of memory",+ "err.no-fonts": "no fonts available",+ "err.not-open": "the document is not open",+ "err.nothing": "there is nothing to save",+ "err.read-only": "the document is read-only",+ "err.save": "could not save",+ "err.unknown-op": "unknown operation",+ "err.image": "invalid image",+ "err.blob": "invalid data",+ "err.password": "the document is protected by a password"}diff --git a/assets/locales/en/errors.json b/assets/locales/en/errors.jsonnew file mode 100644index 0000000..6b8a433--- /dev/null+++ b/assets/locales/en/errors.json@@ -0,0 +1,519 @@+{+ "admin.actionFailed": "The action finished with an error",+ "admin.forkFailed": "Could not start the action",+ "admin.invalidArgument": "Invalid argument",+ "admin.noReply": "The action finished without a reply",+ "admin.notAdmin": "{user} is not an administrator",+ "admin.tooMany": "Too many actions in progress; try again in a moment",+ "admin.unavailable": "The administration helper is not available",+ "admin.unknownAction": "Unknown administration action",+ "backup.alreadyRunning": "A backup is already running",+ "backup.badConfig": "Invalid backup settings",+ "backup.badDest": "Invalid destination",+ "backup.badExclusion": "Invalid exclusion",+ "backup.badId": "Invalid backup",+ "backup.badPassphrase": "Invalid passphrase",+ "backup.badPath": "Invalid path",+ "backup.badSchedule": "Invalid schedule",+ "backup.badSuffix": "Invalid suffix",+ "backup.busy": "Another backup task is running",+ "backup.configTooLarge": "The backup settings are too large",+ "backup.createFailed": "Could not create {path}: {errno}",+ "backup.destMissing": "The destination does not exist",+ "backup.destNotAllowed": "That destination is not allowed",+ "backup.destOutside": "The destination must be in your home folder or on one of your disks",+ "backup.destUnwritable": "Cannot write to the destination",+ "backup.interrupted": "It was interrupted",+ "backup.locked": "Backups are encrypted: unlock them first",+ "backup.noDestination": "Choose a destination first",+ "backup.noSpace": "No space left on the destination",+ "backup.noSuchBackup": "That backup does not exist",+ "backup.notEncrypted": "This destination is not encrypted",+ "backup.notRunning": "Backups are not running",+ "backup.passphraseShort": "The passphrase must have at least 8 characters",+ "backup.plainBackupsExist": "There are unencrypted backups on this destination: choose another one",+ "backup.readFailed": "Could not read the backup",+ "backup.saveFailed": "Could not save the backup settings",+ "backup.setupFailed": "Couldn't turn on encryption",+ "backup.snapshotFailed": "Could not finish the backup: {errno}",+ "backup.sourceUnreadable": "Cannot read the source folder",+ "backup.tooManyExclusions": "Too many exclusions",+ "backup.verifyFailed": "A backup file failed verification (tampered with or wrong key)",+ "backup.wrongPassphrase": "Wrong passphrase",+ "camera.busy": "The camera is busy",+ "camera.failed": "The camera stopped working",+ "camera.invalid": "Invalid camera",+ "camera.noVideo": "The camera does not capture video",+ "camera.notACamera": "The device is not a camera",+ "camera.openFailed": "Could not open the camera",+ "camera.photoFailed": "Could not take the photo",+ "camera.startFailed": "Could not turn on the camera",+ "camera.unsupportedFormat": "Unsupported camera format",+ "disk.alreadyMounted": "{name} is already mounted",+ "disk.badDevice": "Invalid device",+ "disk.badLabel": "Invalid label",+ "disk.badLabelFor": "Invalid label for {fs}",+ "disk.busy": "{name} is in use (mounted or open in another program)",+ "disk.busyFiles": "{name} is in use (there are open files in {path})",+ "disk.busyWait": "{name} is in use: wait until it finishes what it is doing",+ "disk.cancelled": "Cancelled",+ "disk.cancelledPartial": "Cancelled: the disk was left half written",+ "disk.cannotMountFs": "Don't know how to mount “{fs}”",+ "disk.cannotRenameFs": "Don't know how to rename “{fs}”",+ "disk.imageOnTarget": "The image is on the same disk that would be erased",+ "disk.imageOpenFailed": "Could not open the image (it must be a file in your home folder or on your disks)",+ "disk.imageReadFailed": "Could not read the image",+ "disk.imageTooLarge": "The image ({size} bytes) does not fit on {name} ({capacity} bytes)",+ "disk.internalNeedsAdmin": "Internal disks are managed by an administrator",+ "disk.isPartition": "{name} is a partition: the whole disk is needed",+ "disk.missingTool": "{program} is missing",+ "disk.mountFailed": "Could not mount {name}: {errno}",+ "disk.mountedElsewhere": "{name} is mounted on {path}: unmount it manually",+ "disk.noDevice": "Device {name} does not exist",+ "disk.noNewPartition": "The new partition {name} did not appear",+ "disk.noSmart": "This disk does not report SMART ({name})",+ "disk.notBlock": "{name} is not a block device",+ "disk.notMounted": "{name} is not mounted",+ "disk.notPartition": "{name} is not a partition",+ "disk.nothingRunning": "Nothing is running on {name}",+ "disk.openFailed": "Could not open {name}: {errno}",+ "disk.otherUser": "Another user started it",+ "disk.smartNoReply": "The disk did not answer SMART (it may not have it, or be behind a USB adapter that blocks it)",+ "disk.systemDisk": "{name} is the system disk: it is not touched",+ "disk.tableFailed": "Could not write the partition table",+ "disk.tooLargeForMbr": "Disks larger than 2 TiB are not supported yet (GPT is needed)",+ "disk.tooSmall": "The disk is too small",+ "disk.unknownFs": "{name} has no known file system",+ "disk.unknownFsName": "Unknown file system: {fs}",+ "disk.unmountFailed": "Could not unmount {name}: {errno}",+ "disk.unmountFirst": "Unmount it first",+ "disk.verifyMismatch": "Verification failed: what was written to the disk is not the same as the image",+ "disk.verifyReadFailed": "Could not read {name} back to verify it",+ "disk.writeFailed": "Could not write to {name}",+ "doc.badBlob": "Invalid document data",+ "doc.itemCount": "Between 1 and {max} items",+ "doc.noHelper": "The document helper (lord-doc) is not available",+ "errno.E2BIG": "Argument list too long",+ "errno.EACCES": "Permission denied",+ "errno.EAGAIN": "Resource temporarily unavailable",+ "errno.EBUSY": "Device or resource busy",+ "errno.ECONNREFUSED": "Connection refused",+ "errno.ECONNRESET": "Connection reset",+ "errno.EDQUOT": "Disk quota exceeded",+ "errno.EEXIST": "Already exists",+ "errno.EFBIG": "File too large",+ "errno.EHOSTUNREACH": "Host unreachable",+ "errno.EINTR": "Interrupted",+ "errno.EINVAL": "Invalid argument",+ "errno.EIO": "Input/output error",+ "errno.EISDIR": "Is a folder",+ "errno.ELOOP": "Too many levels of symbolic links",+ "errno.EMFILE": "Too many open files",+ "errno.ENAMETOOLONG": "Name too long",+ "errno.ENETUNREACH": "Network unreachable",+ "errno.ENODEV": "No such device",+ "errno.ENOENT": "No such file or folder",+ "errno.ENOMEM": "Out of memory",+ "errno.ENOSPC": "No space left on the device",+ "errno.ENOTDIR": "Not a folder",+ "errno.ENOTEMPTY": "Folder not empty",+ "errno.ENXIO": "No such device or address",+ "errno.EOPNOTSUPP": "Operation not supported",+ "errno.EPERM": "Operation not permitted",+ "errno.EPIPE": "Broken pipe",+ "errno.EROFS": "Read-only file system",+ "errno.ETIMEDOUT": "Timed out",+ "errno.ETXTBSY": "File in use",+ "errno.EXDEV": "Cannot move between disks",+ "fs.alreadyInTrash": "It is already in the Trash",+ "fs.copyIntoItself": "A folder cannot be copied into itself",+ "fs.copyStartFailed": "Could not start the copy",+ "fs.exists": "Something with that name already exists",+ "fs.moveRemoveFailed": "Copied, but the original could not be removed: {errno}",+ "fs.noTrash": "There is no Trash for that location",+ "fs.notFile": "It is not a file",+ "fs.notInTrash": "It is not in the Trash",+ "fs.notRegular": "It is not a regular file (is it a link?)",+ "fs.openFailed": "Could not open the file: {errno}",+ "fs.outsideHome": "That location is outside your home folder or is not valid",+ "fs.protected": "That folder is protected",+ "fs.tooLarge": "The file is too large (max. {max})",+ "fs.tooManyCopies": "Too many copies in progress; try again when one finishes",+ "fs.trashBadOrigin": "The original location is not valid",+ "fs.trashEntryFailed": "Could not create the Trash entry",+ "fs.trashOriginGone": "The original folder no longer exists",+ "fs.trashOtherDisk": "It is on a different disk than its Trash",+ "fs.trashRestoreExists": "There is already a file with that name in the original location",+ "fw.bpfConfig": "could not configure BPF: {errno}",+ "fw.bpfMaps": "could not create the BPF maps: {errno}",+ "fw.bpfMissing": "the {program} program is missing",+ "fw.bpfNotBuilt": "built without the BPF programs",+ "fw.bpfRejected": "the kernel did not accept {program}: {errno}",+ "fw.bpfRing": "could not map the event buffer: {errno}",+ "fw.invalidApp": "Invalid app",+ "fw.invalidDestination": "Invalid destination",+ "fw.invalidMode": "Invalid firewall mode",+ "fw.invalidRestrictions": "Invalid restrictions",+ "fw.invalidRule": "Invalid rule ({field})",+ "hw.badProfile": "Invalid power mode",+ "hw.badTime": "Invalid date and time",+ "hw.brightnessFailed": "Could not set the brightness: {errno}",+ "hw.logindFailed": "The power settings could not be applied (code {code})",+ "hw.noBacklight": "No such backlight",+ "hw.noCpufreq": "This computer has no CPU frequency scaling",+ "hw.noRfkill": "Wireless devices cannot be unblocked on this computer",+ "hw.ntpFailed": "Could not change automatic time (code {code})",+ "hw.outOfRange": "Value out of range (0 to {max})",+ "hw.profileRefused": "The processor did not accept the power mode",+ "hw.rfkillFailed": "Could not unblock: {errno}",+ "hw.setTimeFailed": "Could not set the time (code {code}): turn off automatic time first",+ "hw.suspendFailed": "Could not suspend (code {code})",+ "install.badFullName": "The full name has invalid characters",+ "install.badHostname": "Invalid computer name (lowercase letters, numbers and -)",+ "install.badKbLayout": "Invalid keyboard layout",+ "install.badKbVariant": "Invalid keyboard variant",+ "install.badLanguage": "Invalid language",+ "install.badPlan": "Invalid installation data",+ "install.badRegion": "Unsupported region",+ "install.badSwap": "Invalid swap size (0 to 16384 MB)",+ "install.badTimezone": "Invalid time zone",+ "install.badUser": "Invalid user name (lowercase letters, numbers, - and _)",+ "install.copyFailed": "Could not copy the system",+ "install.diskBusy": "Disk /dev/{disk} is in use (mounted or used as swap)",+ "install.diskNotListed": "The disk is not in the list of installable disks",+ "install.diskTooSmall": "The disk is too small (at least 8 GB)",+ "install.formatEfiFailed": "Could not format the EFI partition",+ "install.formatRootFailed": "Could not format the system partition",+ "install.grubBiosFailed": "Could not install the boot loader (BIOS)",+ "install.grubConfigFailed": "Could not generate the boot loader configuration",+ "install.grubEfiFailed": "Could not install the boot loader (UEFI)",+ "install.hashFailed": "Could not encrypt the password",+ "install.initramfsFailed": "Could not generate the initramfs",+ "install.liveOnly": "The installer only works from the live system",+ "install.mountEfiFailed": "Could not mount the EFI partition",+ "install.mountFailed": "Could not mount {path}: {errno}",+ "install.noPartitions": "The new partitions did not appear",+ "install.noPassword": "The password is missing",+ "install.partitionFailed": "Could not partition the disk",+ "install.passwordFailed": "Could not save the password",+ "install.prepareFailed": "Could not prepare the new system",+ "install.rebootFailed": "Could not restart",+ "install.unknownKbLayout": "Unknown keyboard layout",+ "install.unknownTimezone": "Unknown time zone",+ "install.userFailed": "Could not create the user",+ "install.userMissing": "The new user was not found",+ "install.userReserved": "That user name is reserved",+ "install.userTaken": "The system already uses that user name",+ "install.uuidFailed": "Could not read the partitions' UUID",+ "install.wipeFailed": "Could not erase the disk",+ "ipsec.certNeedsKey": "Certificate authentication needs a certificate and a key (PEM)",+ "ipsec.charonExited": "strongSwan (charon) stopped",+ "ipsec.charonFailed": "Could not start strongSwan (charon)",+ "ipsec.eapNeedsUser": "EAP needs a user name and password",+ "ipsec.noCas": "There are no certificate authorities in /etc/ssl/certs",+ "ipsec.noVici": "strongSwan (charon) did not open its control socket",+ "ipsec.pskShort": "The pre-shared key needs at least 8 characters",+ "ipsec.viciFailed": "strongSwan rejected {cmd}: {detail}",+ "lang.invalidCode": "Invalid language code: {code}",+ "locale.notGenerated": "Region {name} is not installed",+ "locale.unsupported": "Unsupported region: {name}",+ "logs.badName": "Invalid log name",+ "logs.badQuery": "Invalid search",+ "logs.noSystemJournal": "There is no system journal",+ "logs.noThread": "Could not start the search",+ "logs.readFailed": "Could not read the journal",+ "logs.tooManyQueries": "Too many searches in progress",+ "lpk.badId": "The app id is not valid (a-z, 0-9 and -)",+ "lpk.badManifest": "The package's manifest.json is not valid",+ "lpk.badPath": "The package has an invalid path",+ "lpk.badSignature": "The package is damaged or badly signed: {reason}",+ "lpk.badVersion": "The app version is not valid",+ "lpk.corruptGzip": "The package is corrupt (gzip)",+ "lpk.corruptSize": "The package is corrupt (size)",+ "lpk.corruptTar": "The package is corrupt (tar)",+ "lpk.duplicateFiles": "The package has duplicate files",+ "lpk.empty": "The package is empty",+ "lpk.installFailed": "Could not install the app",+ "lpk.installHome": "Cannot install in the home folder",+ "lpk.mkdirFailed": "Cannot create the app folder",+ "lpk.noFile": "That file does not exist in the app",+ "lpk.noIcon": "The app must include its own icon (a .png from the package in \"icon\")",+ "lpk.noName": "The app has no name",+ "lpk.notInstalled": "The app is not installed",+ "lpk.notPackage": "Not a LordOS package (manifest.json or app.js is missing)",+ "lpk.readFailed": "Cannot read the file",+ "lpk.replaceFailed": "Could not replace the installed version",+ "lpk.reservedId": "The app id is reserved by LordOS",+ "lpk.specialFiles": "The package has links or special files",+ "lpk.tooLarge": "The package is too large",+ "lpk.writeFailed": "Could not write the app (is the disk full?)",+ "mail.badAccounts": "The mail accounts are not valid",+ "mail.requestTooLarge": "The request to Mail is too large",+ "mail.tooManyFiles": "At most {max} files at a time",+ "media.audioConvertFailed": "Could not convert the audio",+ "media.audioOpenFailed": "Could not open the audio",+ "media.cannotOpen": "Could not open the file (damaged or unsupported format)",+ "media.captureFailed": "Could not capture the screen",+ "media.convertFailed": "Could not convert the image",+ "media.createFailed": "Could not create the file",+ "media.denied.camera": "{app} does not have permission to use the camera",+ "media.denied.microphone": "{app} does not have permission to use the microphone",+ "media.denied.screen": "{app} does not have permission to record the screen",+ "media.encodeFailed": "Could not encode the file",+ "media.encoderOpenFailed": "Could not start the encoder",+ "media.exportFailed": "Could not export",+ "media.fileExists": "A file with that name already exists",+ "media.helperCrashed": "The media helper stopped unexpectedly",+ "media.helperNotResponding": "The media helper is not responding",+ "media.imageUnreadable": "Could not read the image",+ "media.invalidApp": "Invalid app",+ "media.invalidArguments": "Invalid arguments",+ "media.invalidCrop": "Invalid crop",+ "media.invalidImage": "Invalid image",+ "media.invalidPath": "Invalid path",+ "media.invalidPixels": "Invalid image data",+ "media.mapFailed": "Could not read the image data",+ "media.noAudio": "The file has no audio",+ "media.noDecoder": "No decoder for this format",+ "media.noEncoder": "No encoder for this format",+ "media.noHelper": "The media helper (lord-media) is not available",+ "media.noOutput": "Could not create the output file",+ "media.noRuntimeDir": "The session has no runtime folder (XDG_RUNTIME_DIR)",+ "media.noVideoEncoder": "No video encoder available",+ "media.notAFile": "Not a file",+ "media.notAnImage": "Not an image",+ "media.nothingToPlay": "There is no audio or video that can be played",+ "media.outsideHome": "Invalid path or outside the home folder",+ "media.queueFull": "Too many pending media tasks; try again in a moment",+ "media.scaleFailed": "Could not resize the image",+ "media.threadFailed": "Could not start playback",+ "media.tooMany": "Too many open media",+ "media.unknownJob": "Unknown media task",+ "media.unsupportedFormat": "Unsupported format",+ "media.writeFailed": "Could not write the file",+ "net.applyFailed": "Could not apply the configuration to {name}",+ "net.downFailed": "Could not turn off {name}: {errno}",+ "net.invalidValue": "Invalid value: {key}={value}",+ "net.missingAddress": "A static configuration needs an address",+ "net.missingMethod": "Choose a method: DHCP, static or off",+ "net.netlinkFailed": "Could not talk to the kernel (netlink)",+ "net.saveFailed": "Could not save the configuration",+ "net.stillSystem": "{name} is still managed by the system (ifupdown?)",+ "net.systemManaged": "{name} is managed by the system (systemd-networkd or ifupdown): hand it over to LordOS first",+ "net.unknownInterface": "Unknown network interface: {name}",+ "net.upFailed": "Could not turn on {name}: {errno}",+ "netd.restarted": "The system network service restarted; try again",+ "netd.unavailable": "The system network service is not available",+ "ovpn.authFile": "Line {line}: auth-user-pass takes no file (the password is asked for)",+ "ovpn.blockNotAllowed": "Line {line}: block not allowed: {block}",+ "ovpn.blockUnclosed": "</{block}> is missing",+ "ovpn.invalidArgument": "Line {line}: invalid argument",+ "ovpn.missingFile": "The file {file} is missing",+ "ovpn.mustBeInline": "Line {line}: {option} must be embedded (<{option}>)",+ "ovpn.noCa": "The certificate authority (<ca>) is missing",+ "ovpn.notClient": "Not a client configuration (client is missing)",+ "ovpn.onlyTun": "Only tun devices are supported",+ "ovpn.optionNotAllowed": "Line {line}: option not allowed: {option}",+ "perm.cameraDenied": "This app does not have permission to use the camera",+ "perm.usbDenied": "This app does not have permission to use USB devices",+ "pkg.busy": "Another package operation is in progress",+ "pkg.conflict": "{name} and {other} cannot be installed together",+ "pkg.conflictInstalled": "{name} conflicts with {other}, which is installed",+ "pkg.deb.badControl": "The .deb's control file is invalid",+ "pkg.deb.compression": "{name} is not supported (xz or gzip are used)",+ "pkg.deb.controlDamaged": "The .deb's control.tar is damaged",+ "pkg.deb.missingDeps": "{name} needs packages that are not in the sources",+ "pkg.deb.noControl": "The .deb has no control file",+ "pkg.deb.noControlTar": "The .deb has no control.tar",+ "pkg.deb.notDeb": "Not a .deb package",+ "pkg.deb.wrongArch": "{name} is for {arch} and this system is {system}",+ "pkg.dependencyUninstallable": "{name} depends on {dep}, which cannot be installed",+ "pkg.downloadFailed": "{name}: {reason}",+ "pkg.dpkgBusy": "dpkg is busy (is apt or another installer running?)",+ "pkg.dpkgFailed": "dpkg failed with code {code} (see the log)",+ "pkg.dpkgLockFailed": "Could not take the dpkg lock",+ "pkg.dpkgStatusUnreadable": "Could not read the dpkg database",+ "pkg.file.badHome": "Invalid home folder",+ "pkg.file.copyFailed": "Could not copy the file",+ "pkg.file.needDebPath": "The full path of a .deb file is needed",+ "pkg.file.openFailed": "Could not open the file (a link, permissions, or not a file?)",+ "pkg.file.outsideHome": "The file has to be in your home folder",+ "pkg.file.pathTooLong": "The path is too long",+ "pkg.file.unreadable": "Could not read the file",+ "pkg.hashMismatchIndex": "the SHA-256 does not match the signed index",+ "pkg.hashMismatchRelease": "the SHA-256 does not match the signed InRelease",+ "pkg.http.badHeaders": "invalid HTTP headers",+ "pkg.http.badResponse": "invalid HTTP response",+ "pkg.http.badUrl": "invalid address",+ "pkg.http.connectFailed": "could not connect to {host}",+ "pkg.http.connectionLost": "the connection was cut",+ "pkg.http.createFailed": "could not create {path}",+ "pkg.http.hostNotFound": "{host} was not found",+ "pkg.http.httpsRedirect": "the server redirects to https, which LordOS does not use for packages",+ "pkg.http.noResponse": "{host} did not respond",+ "pkg.http.notDownloaded": "not downloaded",+ "pkg.http.saveFailed": "could not save {path}",+ "pkg.http.status": "the server answered {status}",+ "pkg.http.tooLarge": "the file is larger than allowed",+ "pkg.http.writeFailed": "could not write (is the disk full?)",+ "pkg.index.tooLarge": "the index is too large",+ "pkg.index.tooManyPackages": "too many packages",+ "pkg.index.writeFailed": "could not write {path}: {errno}",+ "pkg.indexFailed": "Could not build the package index: {reason}",+ "pkg.installAndRemove": "{name} is marked to be installed and removed at the same time",+ "pkg.invalidName": "Invalid package name: {name}",+ "pkg.missingName": "The package name is missing",+ "pkg.neededButRemoved": "{name} is needed, but you asked to remove it",+ "pkg.noIndex": "There is no package list yet: update it first",+ "pkg.noPackagesFile": "no package list was downloaded",+ "pkg.noSources": "There are no package sources (/etc/apt/sources.list.d)",+ "pkg.noVerifiedSource": "No package source could be verified",+ "pkg.notFound": "There is no package called {name}",+ "pkg.notInstalled": "{name} is not installed",+ "pkg.pgp.badEncoding": "badly encoded signature",+ "pkg.pgp.badSignature": "invalid signature by key {key}",+ "pkg.pgp.futureSignature": "signature with a future date ({key})",+ "pkg.pgp.incomplete": "incomplete signed message",+ "pkg.pgp.keyExpired": "key {key} has expired",+ "pkg.pgp.keyNotSigning": "key {key} is not a signing key",+ "pkg.pgp.keyRevoked": "key {key} is revoked",+ "pkg.pgp.malformed": "malformed signature",+ "pkg.pgp.noSignature": "the signature is missing",+ "pkg.pgp.notClearsigned": "not a clear-signed message",+ "pkg.pgp.signatureExpired": "the signature by {key} has expired",+ "pkg.pgp.signatureIncomplete": "incomplete signature",+ "pkg.pgp.trailingData": "data after the signature",+ "pkg.pgp.unescapedDash": "line with an unescaped dash",+ "pkg.pgp.unknownKeys": {+ "one": "no signature is from a known key ({count} unknown)",+ "other": "no signature is from a known key ({count} unknown)"+ },+ "pkg.prepareFailed": "Could not prepare {path}",+ "pkg.release.expired": "the list has expired (Valid-Until)",+ "pkg.release.future": "the list has a future date (is the system clock right?)",+ "pkg.release.malformed": "malformed Release file",+ "pkg.release.noKeys": "there are no keys to verify it",+ "pkg.release.older": "the new list is older than the saved one",+ "pkg.release.saveFailed": "could not save it",+ "pkg.release.unreadable": "could not read it",+ "pkg.release.wrongSuite": "the list is for {got}, not {want}",+ "pkg.removeAlso": "These must be removed too: {names}",+ "pkg.removeEssential": "{name} is essential for the system and cannot be removed",+ "pkg.tooManyCombinations": "Too many possible combinations; ask for the packages one at a time",+ "pkg.unresolvable": "The dependencies could not be resolved",+ "pkg.virtual": "{name} is a virtual package; choose one of: {options}",+ "pkgstate.badFolder": "The app folder has links or invalid names",+ "pkgstate.badManifest": "Invalid manifest",+ "pkgstate.buildFailed": "Could not build the package",+ "pkgstate.exists": "A file with that name already exists",+ "pkgstate.invalidApp": "Invalid app",+ "pkgstate.keyFailed": "Could not create your own signing key",+ "pkgstate.manifestNotBasedOn": "The manifest has to be for the same app and include basedOn",+ "pkgstate.readFailed": "Could not read the app folder",+ "pkgstate.restoreFailed": "Could not restore the original",+ "pkgstate.shareFailed": "Could not share the app",+ "pkgstate.updateOtherKey": "The update is signed with a different key than the installed version",+ "pkgstate.updateUnsigned": "The installed version is signed and this update is not",+ "pkgstate.writeFailed": "Could not write the package",+ "print.badAddress": "Invalid printer name or address",+ "print.badDocument": "The document must be a PDF from your home folder",+ "print.badPrinter": "Invalid printer name",+ "print.badScanner": "Invalid scanner (only local network addresses)",+ "rec.noMicrophone": "No microphone available",+ "rec.startFailed": "Could not start recording (is another recording running?)",+ "remote.badPort": "Invalid port",+ "remote.configFailed": "Could not save the remote desktop settings",+ "remote.groupFailed": "Could not create the lordos-remote group",+ "remote.listenFailed": "The remote desktop could not listen on port {port}",+ "remote.needSessiond": "Remote desktop needs the LordOS session service (lord-sessiond)",+ "remote.noSuchConnection": "That connection does not exist",+ "remote.notRunning": "The remote desktop service is not running",+ "settings.tooLarge": "The settings are too large to save",+ "sig.badSignatureFile": "Invalid firma.json",+ "sig.catalog.invalid": "Invalid catalog.json",+ "sig.catalog.unknownFormat": "Catalog in an unknown format",+ "sig.catalog.unofficial": "The catalog is not signed by LordOS",+ "sig.contents.badEntry": "contenido.json has an invalid entry",+ "sig.contents.duplicate": "contenido.json lists a file twice",+ "sig.contents.invalid": "Invalid contenido.json",+ "sig.contents.missing": "The package has a signature but no contenido.json",+ "sig.contents.noFiles": "contenido.json has no file list",+ "sig.contents.otherApp": "contenido.json belongs to another app or another version",+ "sig.contents.otherKey": "contenido.json names a different key than the signature",+ "sig.contents.unknownFormat": "contenido.json is in an unknown format",+ "sig.extraFiles": "The package has files that are not in contenido.json",+ "sig.fileMissing": "A file of the package is missing: {path}",+ "sig.fileModified": "The file {path} was modified",+ "sig.mismatch": "The signature does not match the contents",+ "sig.revokedKey": "LordOS revoked the key this app was signed with",+ "sig.revokedVersion": "LordOS revoked this version of the app",+ "sig.unknownFormat": "Signature in an unknown format",+ "sys.badArgument": "Invalid request (a program error)",+ "sys.errno": "{errno}",+ "sys.outOfMemory": "Out of memory",+ "sys.programError": "{program} failed",+ "sys.programFailed": "{program} failed (exit code {code})",+ "sys.readFailed": "Could not read {path}",+ "sys.unknown": "Unknown error",+ "sys.writeFailed": "Could not write {path}",+ "term.createFailed": "Could not create the terminal",+ "tz.unknown": "Unknown time zone: {zone}",+ "users.avatarFailed": "Could not save the picture",+ "users.avatarNotAllowed": "Only an administrator can change another user's picture",+ "users.badAvatarImage": "The picture must be a PNG or JPEG from your home folder (up to 4 MB)",+ "users.badNameOrPassword": "Invalid user name or password",+ "users.deleteSelf": "You can't delete the account you are using",+ "users.exists": "“{name}” already exists",+ "users.groupFailed": "Could not change the group",+ "users.invalid": "Invalid user",+ "users.lastAdmin": "This is the only administrator",+ "users.passwordNotAllowed": "Only an administrator can change another user's password",+ "users.setPasswordFailed": "Could not set the password",+ "users.wrongPassword": "The current password is not correct",+ "vault.requestTooLarge": "The request to Passwords is too large",+ "vault.unavailable": "Passwords (lord-vault) is not available",+ "vpn.badChar": "Line {line}: invalid character in {key}",+ "vpn.createIfFailed": "Could not create {name}: {errno}",+ "vpn.credentialsOnlyOpenvpn": "Only OpenVPN asks for a user name and password",+ "vpn.expectedKeyValue": "Line {line}: expected key = value",+ "vpn.invalidCredentials": "Invalid user name or password",+ "vpn.invalidLineValue": "Line {line}: invalid {key}",+ "vpn.invalidName": "Invalid name: use letters, numbers, - and _ (up to 24)",+ "vpn.invalidValue": "Invalid {key}",+ "vpn.ipsecBusy": "Another IPsec VPN is already connected (one at a time)",+ "vpn.lost": "The VPN connection was lost",+ "vpn.missingCredentials": "A user name and password are needed",+ "vpn.missingKey": "{key} is missing or invalid",+ "vpn.missingProgram": "{type} needs the {package} package: enable it first",+ "vpn.noAddress": "The VPN server did not give an address",+ "vpn.noConfig": "The VPN configuration is missing",+ "vpn.notConnected": "The VPN was not connected",+ "vpn.pemRequired": "Line {line}: {key} must be PEM (-----BEGIN …)",+ "vpn.pemUnclosed": "{key}: -----END is missing",+ "vpn.resolveFailed": "Could not resolve {host}",+ "vpn.routesFailed": "Could not add the routes through {dev}: {errno}",+ "vpn.serverUnresolved": "Could not find the VPN server (DNS)",+ "vpn.startFailed": "Could not start the VPN",+ "vpn.tooManyLines": "The configuration has too many lines",+ "vpn.tooManyPem": "Too many PEM blocks",+ "vpn.unknown": "Unknown VPN: {name}",+ "vpn.unknownKey": "Line {line}: unknown key {key}",+ "vpn.unsupportedType": "Unsupported VPN type: {type}",+ "vpn.writeFailed": "Could not write the VPN configuration",+ "vpn.xfrmFailed": "Could not create the IPsec interface: {errno}",+ "wg.noKernel": "The kernel has no WireGuard support",+ "wg.noRandom": "No random numbers available",+ "wg.peerNoPublicKey": "A [Peer] has no PublicKey",+ "wg.setDeviceFailed": "Could not configure WireGuard: {errno}",+ "wg.tooManyPeers": "Too many [Peer] sections",+ "wifi.invalidPassword": "Invalid password (at least 8 characters)",+ "wifi.invalidSsid": "Invalid network name",+ "wifi.noAnswer": "The Wi-Fi service did not answer",+ "wifi.noSupplicant": "Wi-Fi is not running on {name}: turn the interface on first",+ "wifi.notSaved": "That network was not saved",+ "wifi.notWifi": "{name} is not a Wi-Fi interface",+ "wifi.rejected": "The Wi-Fi service did not accept the network",+ "wifi.saveFailed": "Could not save the network",+ "wifi.selectFailed": "The Wi-Fi service could not select the network",+ "wifi.startFailed": "Could not start Wi-Fi on {name}"+}diff --git a/assets/locales/en/mail.json b/assets/locales/en/mail.jsonindex 71ed005..b370c79 100644--- a/assets/locales/en/mail.json+++ b/assets/locales/en/mail.json@@ -12,6 +12,7 @@"categories": "Categories","favorites": "Favorites","unifiedInbox": "All Inboxes",+ "unifiedInboxShort": "All Inboxes","unread": "Unread","flagged": "Flagged","addAccount": "Add Account",@@ -117,6 +118,7 @@"setup.namePh": "Your name, as recipients see it","setup.davNamePh": "Nextcloud, iCloud…","setup.email": "Email",+ "setup.emailPh": "[email protected]","setup.password": "Password","setup.url": "Server URL","setup.user": "User name",diff --git a/assets/locales/en/prefs.json b/assets/locales/en/prefs.jsonindex f56e55e..d930276 100644--- a/assets/locales/en/prefs.json+++ b/assets/locales/en/prefs.json@@ -70,6 +70,7 @@"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.arrangement": "Arrangement","display.brightness": "Brightness","display.capture": "Screenshots and sharing","display.captureAll": "All displays",@@ -85,17 +86,22 @@"other": "Your display settings will go back to the previous ones in {count} seconds."},"display.keepTitle": "Keep these display settings?",+ "display.largerText": "Larger text","display.looksLike": "looks like {w} × {h}",+ "display.mainHint": "It has the menu bar and the Dock.","display.mainLabel": "main display","display.makeMain": "Use as Main Display","display.menuBarAll": "Show menu bar on all displays","display.mirror": "Mirror",+ "display.mirrorDisplays": "Mirror displays",+ "display.moreSpace": "More space","display.multiple": "Multiple displays","display.multipleHint": "Extend makes one desktop across every display: windows move between them and can span two. Mirror shows the main display on all of them.","display.native": "{w} × {h} (native)","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 Shift settings still apply when it returns.",+ "display.recommended": "Recommended","display.refresh": "Refresh rate","display.resolution": "Resolution","display.revert": "Revert",@@ -106,8 +112,10 @@"display.scaleHint": "Text, icons and images are drawn at the display's own resolution, so every scale stays sharp. Linux apps with fractional scaling render at it too.","display.scaleN": "{n} %","display.scaleRecommended": "{n} % (recommended)",+ "display.showList": "Show as list","display.unavailable": "The display information is not available.","display.useAs": "Use as",+ "display.useAsMain": "Use as main display","night.custom": "Custom","night.customHint": "Night Shift turns on and off at these times every day.","night.footer": "Night Shift shifts the colors of your display to the warmer end of the spectrum after dark.",diff --git a/assets/locales/en/print.json b/assets/locales/en/print.jsonindex 97a0716..2ceafcd 100644--- a/assets/locales/en/print.json+++ b/assets/locales/en/print.json@@ -78,7 +78,18 @@"scan": "Scan…","noScanners": "No scanners found on the network.","tlsUnsupported": "encrypted only (not yet)",- "err.forbidden": "Your user cannot manage printers: you need to be an administrator (lpadmin group).",+ "err.forbidden": "you are not allowed to manage printers","err.notFound": "CUPS did not find that printer",- "err.other": "CUPS said: {error}"+ "err.other": "CUPS said: {error}",+ "err.encode": "could not prepare the request",+ "err.no-cups": "the printing service (CUPS) is not running",+ "err.http": "the printer replied with an error ({detail})",+ "err.bad-response": "invalid reply from the printer",+ "err.bad-request": "invalid request",+ "err.bad-pages": "invalid page range",+ "err.unreachable": "could not reach it",+ "err.busy": "it is busy; try again in a moment",+ "err.timeout": "it took too long",+ "err.write": "could not write the file",+ "err.unknown": "unknown error"}diff --git a/assets/locales/en/shell.json b/assets/locales/en/shell.jsonindex 34f9b26..a38da0e 100644--- a/assets/locales/en/shell.json+++ b/assets/locales/en/shell.json@@ -118,5 +118,9 @@"spotlight.inHelp": "Help article","picker.cancel": "Cancel","picker.choose": "Choose ({n})",- "picker.empty": "No files here."+ "picker.empty": "No files here.",+ "wallpaper.aurora": "Aurora",+ "wallpaper.ocean": "Ocean",+ "wallpaper.sunset": "Sunset",+ "wallpaper.graphite": "Graphite"}diff --git a/assets/locales/en/status.json b/assets/locales/en/status.jsonnew file mode 100644index 0000000..41d117d--- /dev/null+++ b/assets/locales/en/status.json@@ -0,0 +1,119 @@+{+ "disk.cancelling": "Cancelling",+ "disk.ejected": "Ejected",+ "disk.erased": "Erased",+ "disk.rereadWarning": "Warning: the kernel did not reread the partition table ({errno})",+ "disk.unmounted": "Unmounted",+ "disk.unmountedPath": "Unmounted {path}",+ "disk.verified": "Verified (SHA-256 {sha256})",+ "hw.profileSet": "Power mode: {profile}",+ "hw.suspended": "Suspending",+ "hw.unblocked": "Unblocked",+ "install.chownWarning": "Warning: could not change the owner of a file",+ "install.done": "LordOS was installed on {dev}",+ "install.homedirsWarning": "Warning: could not create the user's folders",+ "install.installingTo": "Installing on {dev}",+ "install.rebooting": "Restarting",+ "install.stepFailed": "{program} failed (code {code})",+ "install.timezoneWarning": "Warning: could not set the time zone",+ "lang.installed": {+ "one": "{count} package installed for “{lang}”",+ "other": "{count} packages installed for “{lang}”"+ },+ "lang.noDebianPackages": "No Debian packages for “{lang}”: only the region and the LordOS texts",+ "lang.package": "Package: {name}",+ "locale.generated": "Region {name} installed",+ "locale.systemSet": "System region: {name}",+ "net.alreadyLordos": "{name} was already managed by LordOS",+ "net.configured": "{name}: {method}",+ "net.down": "{name} turned off",+ "net.managed": "{name} is now managed by LordOS",+ "net.otherSession": "The network is managed by another session",+ "net.restoreSystem": "The network is managed by the system",+ "net.restored": {+ "one": "{count} interface configured",+ "other": "{count} interfaces configured"+ },+ "net.unmanaged": "{name} is managed by the system again",+ "net.up": "{name} turned on",+ "ovpn.ignoredWindows": {+ "one": "{count} Windows-only option ignored",+ "other": "{count} Windows-only options ignored"+ },+ "pkg.componentMissing": "{component} is missing ({suite})",+ "pkg.done": "{installed} installed, {upgraded} upgraded, {removed} removed",+ "pkg.downloadingIndex": {+ "one": "Downloading {count} index file ({kb} KB)",+ "other": "Downloading {count} index files ({kb} KB)"+ },+ "pkg.downloadingPackages": {+ "one": "Downloading {count} package ({kb} KB)",+ "other": "Downloading {count} packages ({kb} KB)"+ },+ "pkg.dpkgInterrupted": "dpkg was left half-finished: running dpkg --configure -a",+ "pkg.dpkgRemoveExit": "dpkg --remove finished with code {code}",+ "pkg.fileFailed": "{url}: {reason}",+ "pkg.flatRepo": "Flat repository not supported: {uri} {suite}",+ "pkg.keyUnreadable": "Could not read the key {path}",+ "pkg.localPackage": "Local package: {name} {version} ({arch})",+ "pkg.nothingToDo": "Nothing to do: everything is already installed",+ "pkg.nothingToRemove": "There is nothing to remove",+ "pkg.source": "Source: {uri} {suite} {component}",+ "pkg.sourceFailed": "{uri} {suite}: {reason}",+ "pkg.sourceMissingFile": "{uri} {suite}: no {file}",+ "pkg.sourceSkipped": "Source skipped (only http/https): {uri}",+ "pkg.sourceVerified": "{uri} {suite}: signature verified ({label})",+ "pkg.unresolvedDep": "Unresolved dependency: {name}",+ "pkg.upToDate": {+ "one": "The list was already up to date ({count} package)",+ "other": "The list was already up to date ({count} packages)"+ },+ "pkg.updated": {+ "one": "{count} package from {sources} source(s)",+ "other": "{count} packages from {sources} source(s)"+ },+ "pkg.updatedWithProblems": {+ "one": "{count} package from {sources} source(s) ({problems} with problems: see the log)",+ "other": "{count} packages from {sources} source(s) ({problems} with problems: see the log)"+ },+ "pkg.why.auto": "No longer needed",+ "pkg.why.conflictsWith": "Conflicts with {name}",+ "pkg.why.dependencyOf": "Dependency of {name}",+ "pkg.why.lostDependency": "Depended on {dep}",+ "pkg.why.requested": "Requested",+ "pkg.why.upgrade": "Upgrade",+ "pkg.why.upgradedFor": "Upgraded for {name}",+ "remote.disconnected": "Connection closed",+ "remote.off": "Remote desktop turned off",+ "remote.on": "Remote desktop turned on",+ "remote.saved": "Settings saved",+ "remote.userAdded": "{name} can connect remotely",+ "remote.userRemoved": "{name} can no longer connect remotely",+ "tz.set": "Time zone: {zone}",+ "users.autologinOff": "Automatic login turned off",+ "users.autologinOn": "Automatic login turned on",+ "users.avatarSaved": "Picture saved",+ "users.created": "User {name} created",+ "users.deleted": "User {name} deleted",+ "users.homedirsWarning": "Warning: not all folders could be created",+ "users.noLongerAdmin": "{name} is no longer an administrator",+ "users.nowAdmin": "{name} is now an administrator",+ "users.passwordChanged": "Password changed",+ "users.unchanged": "No changes",+ "vpn.alreadyConnecting": "Already connecting",+ "vpn.alreadyInstalled": "Already installed",+ "vpn.connected": "Connected",+ "vpn.connecting": "Connecting…",+ "vpn.deleted": "VPN deleted",+ "vpn.disconnected": "Disconnected",+ "vpn.disconnecting": "Disconnecting…",+ "vpn.imported": "VPN imported",+ "vpn.saved": "Saved",+ "wg.ignoredLines": {+ "one": "{count} line ignored (PostUp, PreDown, Table…): LordOS does not run commands",+ "other": "{count} lines ignored (PostUp, PreDown, Table…): LordOS does not run commands"+ },+ "wifi.connecting": "Connecting to {ssid}…",+ "wifi.disconnected": "Disconnected",+ "wifi.forgotten": "Network forgotten"+}diff --git a/assets/locales/es/about.json b/assets/locales/es/about.jsonindex eaf5576..06de2da 100644--- a/assets/locales/es/about.json+++ b/assets/locales/es/about.json@@ -1,5 +1,6 @@{"cpu": "Procesador",+ "cpuUnknown": "Desconocido","cpuValue": {"one": "{cpu} · {count} núcleo","other": "{cpu} · {count} núcleos"diff --git a/assets/locales/es/backup.json b/assets/locales/es/backup.jsonindex 6b9afb6..838295d 100644--- a/assets/locales/es/backup.json+++ b/assets/locales/es/backup.json@@ -108,12 +108,5 @@"encLock": "Bloquear","encWorking": "Comprobando la frase…","notify.lockedTitle": "Las copias de seguridad están cifradas",- "notify.lockedBody": "Escribí la frase para que sigan las copias programadas.",- "err.wrong-passphrase": "Frase incorrecta",- "err.not-encrypted": "Este destino no está cifrado",- "err.plain-backups-exist": "Ya hay copias sin cifrar en este destino: elegí otro",- "err.setup-failed": "No se pudo activar el cifrado",- "err.no-destination": "Elegí un destino primero",- "err.locked": "Las copias están cifradas: desbloquealas primero",- "err.interrupted": "Se interrumpió"-}\ No newline at end of file+ "notify.lockedBody": "Escribí la frase para que sigan las copias programadas."+}diff --git a/assets/locales/es/docs.json b/assets/locales/es/docs.jsonindex 407f2ac..6c69de9 100644--- a/assets/locales/es/docs.json+++ b/assets/locales/es/docs.json@@ -48,5 +48,26 @@"err.too-big": "es demasiado grande","err.too-many": "tiene demasiados archivos","err.corrupt": "está dañado",- "err.write": "no se pudo escribir"+ "err.write": "no se pudo escribir",+ "err.unavailable": "el ayudante de documentos no está disponible",+ "err.cancelled": "cancelado",+ "err.crash": "el ayudante de documentos se cerró de golpe",+ "err.timeout": "tardó demasiado",+ "err.protocol": "el ayudante de documentos mandó una respuesta inválida",+ "err.spawn": "no se pudo iniciar el ayudante de documentos",+ "err.closed": "el documento se cerró",+ "err.bad-request": "pedido inválido",+ "err.bad-field": "campo de formulario inválido",+ "err.bad-page": "página inválida",+ "err.busy": "el ayudante de documentos está ocupado",+ "err.memory": "sin memoria",+ "err.no-fonts": "no hay tipografías disponibles",+ "err.not-open": "el documento no está abierto",+ "err.nothing": "no hay nada para guardar",+ "err.read-only": "el documento es de solo lectura",+ "err.save": "no se pudo guardar",+ "err.unknown-op": "operación desconocida",+ "err.image": "imagen inválida",+ "err.blob": "datos inválidos",+ "err.password": "el documento está protegido con contraseña"}diff --git a/assets/locales/es/errors.json b/assets/locales/es/errors.jsonnew file mode 100644index 0000000..b55c1a5--- /dev/null+++ b/assets/locales/es/errors.json@@ -0,0 +1,519 @@+{+ "admin.actionFailed": "La acción terminó con un error",+ "admin.forkFailed": "No se pudo iniciar la acción",+ "admin.invalidArgument": "Argumento inválido",+ "admin.noReply": "La acción terminó sin responder",+ "admin.notAdmin": "{user} no es administrador",+ "admin.tooMany": "Hay demasiadas acciones en curso; probá de nuevo en un momento",+ "admin.unavailable": "El ayudante de administración no está disponible",+ "admin.unknownAction": "Acción de administración desconocida",+ "backup.alreadyRunning": "Ya hay una copia en curso",+ "backup.badConfig": "Configuración de copias inválida",+ "backup.badDest": "Destino inválido",+ "backup.badExclusion": "Exclusión inválida",+ "backup.badId": "Copia inválida",+ "backup.badPassphrase": "Frase inválida",+ "backup.badPath": "Ruta inválida",+ "backup.badSchedule": "Programación inválida",+ "backup.badSuffix": "Sufijo inválido",+ "backup.busy": "Hay otra tarea de copias en curso",+ "backup.configTooLarge": "La configuración de copias es demasiado grande",+ "backup.createFailed": "No se pudo crear {path}: {errno}",+ "backup.destMissing": "El destino no existe",+ "backup.destNotAllowed": "Ese destino no está permitido",+ "backup.destOutside": "El destino tiene que estar en tu carpeta personal o en uno de tus discos",+ "backup.destUnwritable": "No se puede escribir en el destino",+ "backup.interrupted": "Se interrumpió",+ "backup.locked": "Las copias están cifradas: desbloquealas primero",+ "backup.noDestination": "Elegí un destino primero",+ "backup.noSpace": "No queda espacio en el destino",+ "backup.noSuchBackup": "Esa copia no existe",+ "backup.notEncrypted": "Este destino no está cifrado",+ "backup.notRunning": "Las copias no están funcionando",+ "backup.passphraseShort": "La frase tiene que tener al menos 8 caracteres",+ "backup.plainBackupsExist": "Ya hay copias sin cifrar en este destino: elegí otro",+ "backup.readFailed": "No se pudo leer la copia",+ "backup.saveFailed": "No se pudo guardar la configuración de copias",+ "backup.setupFailed": "No se pudo activar el cifrado",+ "backup.snapshotFailed": "No se pudo terminar la copia: {errno}",+ "backup.sourceUnreadable": "No se puede leer la carpeta de origen",+ "backup.tooManyExclusions": "Demasiadas exclusiones",+ "backup.verifyFailed": "Un archivo de la copia no pasó la verificación (alterado o clave equivocada)",+ "backup.wrongPassphrase": "Frase incorrecta",+ "camera.busy": "La cámara está ocupada",+ "camera.failed": "La cámara dejó de funcionar",+ "camera.invalid": "Cámara inválida",+ "camera.noVideo": "La cámara no captura video",+ "camera.notACamera": "El dispositivo no es una cámara",+ "camera.openFailed": "No se pudo abrir la cámara",+ "camera.photoFailed": "No se pudo sacar la foto",+ "camera.startFailed": "No se pudo encender la cámara",+ "camera.unsupportedFormat": "Formato de cámara no compatible",+ "disk.alreadyMounted": "{name} ya está montado",+ "disk.badDevice": "Dispositivo inválido",+ "disk.badLabel": "Etiqueta inválida",+ "disk.badLabelFor": "Etiqueta inválida para {fs}",+ "disk.busy": "{name} está en uso (montado o abierto por otro programa)",+ "disk.busyFiles": "{name} está en uso (hay archivos abiertos en {path})",+ "disk.busyWait": "{name} está en uso: esperá a que termine lo que está haciendo",+ "disk.cancelled": "Cancelado",+ "disk.cancelledPartial": "Cancelado: el disco quedó a medio escribir",+ "disk.cannotMountFs": "No se sabe montar «{fs}»",+ "disk.cannotRenameFs": "No se sabe renombrar «{fs}»",+ "disk.imageOnTarget": "La imagen está en el mismo disco que se va a borrar",+ "disk.imageOpenFailed": "No se pudo abrir la imagen (tiene que ser un archivo de tu carpeta o de tus discos)",+ "disk.imageReadFailed": "No se pudo leer la imagen",+ "disk.imageTooLarge": "La imagen ({size} bytes) no entra en {name} ({capacity} bytes)",+ "disk.internalNeedsAdmin": "Los discos internos los maneja un administrador",+ "disk.isPartition": "{name} es una partición: hace falta el disco entero",+ "disk.missingTool": "Falta {program}",+ "disk.mountFailed": "No se pudo montar {name}: {errno}",+ "disk.mountedElsewhere": "{name} está montado en {path}: desmontalo a mano",+ "disk.noDevice": "No existe el dispositivo {name}",+ "disk.noNewPartition": "No apareció la partición nueva {name}",+ "disk.noSmart": "Este disco no informa SMART ({name})",+ "disk.notBlock": "{name} no es un dispositivo de bloque",+ "disk.notMounted": "{name} no está montado",+ "disk.notPartition": "{name} no es una partición",+ "disk.nothingRunning": "No hay nada en curso en {name}",+ "disk.openFailed": "No se pudo abrir {name}: {errno}",+ "disk.otherUser": "Lo empezó otro usuario",+ "disk.smartNoReply": "El disco no respondió a SMART (puede no tenerlo, o estar detrás de un adaptador USB que no lo deja pasar)",+ "disk.systemDisk": "{name} es el disco del sistema: no se toca",+ "disk.tableFailed": "No se pudo escribir la tabla de particiones",+ "disk.tooLargeForMbr": "Discos de más de 2 TiB: todavía no (hace falta GPT)",+ "disk.tooSmall": "El disco es demasiado chico",+ "disk.unknownFs": "{name} no tiene un sistema de archivos conocido",+ "disk.unknownFsName": "Sistema de archivos desconocido: {fs}",+ "disk.unmountFailed": "No se pudo desmontar {name}: {errno}",+ "disk.unmountFirst": "Desmontalo primero",+ "disk.verifyMismatch": "La verificación falló: lo que quedó en el disco no es igual a la imagen",+ "disk.verifyReadFailed": "No se pudo releer {name} para verificar",+ "disk.writeFailed": "No se pudo escribir en {name}",+ "doc.badBlob": "Datos de documento inválidos",+ "doc.itemCount": "Entre 1 y {max} elementos",+ "doc.noHelper": "El ayudante de documentos (lord-doc) no está disponible",+ "errno.E2BIG": "Lista de argumentos demasiado larga",+ "errno.EACCES": "Permiso denegado",+ "errno.EAGAIN": "Recurso no disponible por el momento",+ "errno.EBUSY": "Dispositivo o recurso ocupado",+ "errno.ECONNREFUSED": "Conexión rechazada",+ "errno.ECONNRESET": "Conexión reiniciada",+ "errno.EDQUOT": "Cuota de disco excedida",+ "errno.EEXIST": "Ya existe",+ "errno.EFBIG": "Archivo demasiado grande",+ "errno.EHOSTUNREACH": "No se puede llegar al equipo",+ "errno.EINTR": "Interrumpido",+ "errno.EINVAL": "Argumento inválido",+ "errno.EIO": "Error de entrada/salida",+ "errno.EISDIR": "Es una carpeta",+ "errno.ELOOP": "Demasiados niveles de enlaces simbólicos",+ "errno.EMFILE": "Demasiados archivos abiertos",+ "errno.ENAMETOOLONG": "Nombre demasiado largo",+ "errno.ENETUNREACH": "Red inaccesible",+ "errno.ENODEV": "No existe el dispositivo",+ "errno.ENOENT": "No existe el archivo o la carpeta",+ "errno.ENOMEM": "Sin memoria",+ "errno.ENOSPC": "No queda espacio en el dispositivo",+ "errno.ENOTDIR": "No es una carpeta",+ "errno.ENOTEMPTY": "La carpeta no está vacía",+ "errno.ENXIO": "No existe el dispositivo o la dirección",+ "errno.EOPNOTSUPP": "Operación no admitida",+ "errno.EPERM": "Operación no permitida",+ "errno.EPIPE": "Conexión rota",+ "errno.EROFS": "Sistema de archivos de solo lectura",+ "errno.ETIMEDOUT": "Se agotó el tiempo de espera",+ "errno.ETXTBSY": "Archivo en uso",+ "errno.EXDEV": "No se puede mover entre discos",+ "fs.alreadyInTrash": "Ya está en la Papelera",+ "fs.copyIntoItself": "No se puede copiar una carpeta dentro de sí misma",+ "fs.copyStartFailed": "No se pudo empezar la copia",+ "fs.exists": "Ya existe algo con ese nombre",+ "fs.moveRemoveFailed": "Se copió, pero no se pudo quitar el original: {errno}",+ "fs.noTrash": "No hay Papelera para ese lugar",+ "fs.notFile": "No es un archivo",+ "fs.notInTrash": "No está en la Papelera",+ "fs.notRegular": "No es un archivo común (¿es un enlace?)",+ "fs.openFailed": "No se pudo abrir el archivo: {errno}",+ "fs.outsideHome": "Ese lugar está fuera de tu carpeta personal o no es válido",+ "fs.protected": "Esa carpeta está protegida",+ "fs.tooLarge": "El archivo es demasiado grande (máx. {max})",+ "fs.tooManyCopies": "Hay demasiadas copias en curso; probá de nuevo cuando termine una",+ "fs.trashBadOrigin": "El lugar original no es válido",+ "fs.trashEntryFailed": "No se pudo crear la entrada de la Papelera",+ "fs.trashOriginGone": "La carpeta original ya no existe",+ "fs.trashOtherDisk": "Está en otro disco que su Papelera",+ "fs.trashRestoreExists": "Ya hay un archivo con ese nombre en el lugar original",+ "fw.bpfConfig": "no se pudo configurar BPF: {errno}",+ "fw.bpfMaps": "no se pudieron crear los mapas BPF: {errno}",+ "fw.bpfMissing": "falta el programa {program}",+ "fw.bpfNotBuilt": "compilado sin los programas BPF",+ "fw.bpfRejected": "el kernel no aceptó {program}: {errno}",+ "fw.bpfRing": "no se pudo mapear el búfer de eventos: {errno}",+ "fw.invalidApp": "App inválida",+ "fw.invalidDestination": "Destino inválido",+ "fw.invalidMode": "Modo de firewall inválido",+ "fw.invalidRestrictions": "Restricciones inválidas",+ "fw.invalidRule": "Regla inválida ({field})",+ "hw.badProfile": "Modo de energía inválido",+ "hw.badTime": "Fecha y hora inválidas",+ "hw.brightnessFailed": "No se pudo cambiar el brillo: {errno}",+ "hw.logindFailed": "No se pudo aplicar la configuración de energía (código {code})",+ "hw.noBacklight": "No existe esa retroiluminación",+ "hw.noCpufreq": "Esta computadora no permite cambiar la frecuencia del procesador",+ "hw.noRfkill": "En esta computadora no se pueden desbloquear los dispositivos inalámbricos",+ "hw.ntpFailed": "No se pudo cambiar la hora automática (código {code})",+ "hw.outOfRange": "Valor fuera de rango (0 a {max})",+ "hw.profileRefused": "El procesador no aceptó el modo de energía",+ "hw.rfkillFailed": "No se pudo desbloquear: {errno}",+ "hw.setTimeFailed": "No se pudo cambiar la hora (código {code}): apagá primero la hora automática",+ "hw.suspendFailed": "No se pudo suspender (código {code})",+ "install.badFullName": "El nombre completo tiene caracteres inválidos",+ "install.badHostname": "El nombre del equipo es inválido (minúsculas, números y -)",+ "install.badKbLayout": "Distribución de teclado inválida",+ "install.badKbVariant": "Variante de teclado inválida",+ "install.badLanguage": "Idioma inválido",+ "install.badPlan": "Datos de instalación inválidos",+ "install.badRegion": "Región no admitida",+ "install.badSwap": "Tamaño de swap inválido (0 a 16384 MB)",+ "install.badTimezone": "Zona horaria inválida",+ "install.badUser": "El nombre de usuario es inválido (minúsculas, números, - y _)",+ "install.copyFailed": "No se pudo copiar el sistema",+ "install.diskBusy": "El disco /dev/{disk} está en uso (montado o con swap)",+ "install.diskNotListed": "El disco no está en la lista de discos instalables",+ "install.diskTooSmall": "El disco es demasiado chico (mínimo 8 GB)",+ "install.formatEfiFailed": "No se pudo formatear la partición EFI",+ "install.formatRootFailed": "No se pudo formatear la partición del sistema",+ "install.grubBiosFailed": "No se pudo instalar el gestor de arranque (BIOS)",+ "install.grubConfigFailed": "No se pudo generar la configuración del gestor de arranque",+ "install.grubEfiFailed": "No se pudo instalar el gestor de arranque (UEFI)",+ "install.hashFailed": "No se pudo cifrar la contraseña",+ "install.initramfsFailed": "No se pudo generar el initramfs",+ "install.liveOnly": "El instalador solo funciona desde el sistema en vivo",+ "install.mountEfiFailed": "No se pudo montar la partición EFI",+ "install.mountFailed": "No se pudo montar {path}: {errno}",+ "install.noPartitions": "No aparecieron las particiones nuevas",+ "install.noPassword": "Falta la contraseña",+ "install.partitionFailed": "No se pudo particionar el disco",+ "install.passwordFailed": "No se pudo guardar la contraseña",+ "install.prepareFailed": "No se pudo preparar el sistema nuevo",+ "install.rebootFailed": "No se pudo reiniciar",+ "install.unknownKbLayout": "Distribución de teclado desconocida",+ "install.unknownTimezone": "Zona horaria desconocida",+ "install.userFailed": "No se pudo crear el usuario",+ "install.userMissing": "No se encontró el usuario nuevo",+ "install.userReserved": "Ese nombre de usuario está reservado",+ "install.userTaken": "Ese nombre de usuario ya lo usa el sistema",+ "install.uuidFailed": "No se pudo leer el UUID de las particiones",+ "install.wipeFailed": "No se pudo borrar el disco",+ "ipsec.certNeedsKey": "La autenticación con certificado necesita un certificado y una clave (PEM)",+ "ipsec.charonExited": "strongSwan (charon) se detuvo",+ "ipsec.charonFailed": "No se pudo iniciar strongSwan (charon)",+ "ipsec.eapNeedsUser": "EAP necesita usuario y contraseña",+ "ipsec.noCas": "No hay autoridades de certificación en /etc/ssl/certs",+ "ipsec.noVici": "strongSwan (charon) no abrió su socket de control",+ "ipsec.pskShort": "La clave compartida necesita al menos 8 caracteres",+ "ipsec.viciFailed": "strongSwan rechazó {cmd}: {detail}",+ "lang.invalidCode": "Código de idioma inválido: {code}",+ "locale.notGenerated": "La región {name} no está instalada",+ "locale.unsupported": "Región no admitida: {name}",+ "logs.badName": "Nombre de registro inválido",+ "logs.badQuery": "Búsqueda inválida",+ "logs.noSystemJournal": "No hay journal del sistema",+ "logs.noThread": "No se pudo iniciar la búsqueda",+ "logs.readFailed": "No se pudo leer el journal",+ "logs.tooManyQueries": "Hay demasiadas búsquedas en curso",+ "lpk.badId": "El id de la app no es válido (a-z, 0-9 y -)",+ "lpk.badManifest": "El manifest.json del paquete no es válido",+ "lpk.badPath": "El paquete tiene una ruta inválida",+ "lpk.badSignature": "El paquete está dañado o mal firmado: {reason}",+ "lpk.badVersion": "La versión de la app no es válida",+ "lpk.corruptGzip": "El paquete está dañado (gzip)",+ "lpk.corruptSize": "El paquete está dañado (tamaño)",+ "lpk.corruptTar": "El paquete está dañado (tar)",+ "lpk.duplicateFiles": "El paquete tiene archivos repetidos",+ "lpk.empty": "El paquete está vacío",+ "lpk.installFailed": "No se pudo instalar la app",+ "lpk.installHome": "No se puede instalar en la carpeta personal",+ "lpk.mkdirFailed": "No se puede crear la carpeta de la app",+ "lpk.noFile": "Ese archivo no existe en la app",+ "lpk.noIcon": "La app tiene que traer su propio ícono (un .png del paquete en \"icon\")",+ "lpk.noName": "La app no tiene nombre",+ "lpk.notInstalled": "La app no está instalada",+ "lpk.notPackage": "No es un paquete de LordOS (falta manifest.json o app.js)",+ "lpk.readFailed": "No se puede leer el archivo",+ "lpk.replaceFailed": "No se pudo reemplazar la versión instalada",+ "lpk.reservedId": "El id de la app está reservado por LordOS",+ "lpk.specialFiles": "El paquete tiene enlaces o archivos especiales",+ "lpk.tooLarge": "El paquete es demasiado grande",+ "lpk.writeFailed": "No se pudo escribir la app (¿el disco está lleno?)",+ "mail.badAccounts": "Las cuentas de correo no son válidas",+ "mail.requestTooLarge": "El pedido a Mail es demasiado grande",+ "mail.tooManyFiles": "Como mucho {max} archivos a la vez",+ "media.audioConvertFailed": "No se pudo convertir el audio",+ "media.audioOpenFailed": "No se pudo abrir el audio",+ "media.cannotOpen": "No se pudo abrir el archivo (está dañado o el formato no es compatible)",+ "media.captureFailed": "No se pudo capturar la pantalla",+ "media.convertFailed": "No se pudo convertir la imagen",+ "media.createFailed": "No se pudo crear el archivo",+ "media.denied.camera": "{app} no tiene permiso para usar la cámara",+ "media.denied.microphone": "{app} no tiene permiso para usar el micrófono",+ "media.denied.screen": "{app} no tiene permiso para grabar la pantalla",+ "media.encodeFailed": "No se pudo codificar el archivo",+ "media.encoderOpenFailed": "No se pudo iniciar el codificador",+ "media.exportFailed": "No se pudo exportar",+ "media.fileExists": "Ya existe un archivo con ese nombre",+ "media.helperCrashed": "El ayudante multimedia se cerró inesperadamente",+ "media.helperNotResponding": "El ayudante multimedia no responde",+ "media.imageUnreadable": "No se pudo leer la imagen",+ "media.invalidApp": "App inválida",+ "media.invalidArguments": "Argumentos inválidos",+ "media.invalidCrop": "Recorte inválido",+ "media.invalidImage": "Imagen inválida",+ "media.invalidPath": "Ruta inválida",+ "media.invalidPixels": "Datos de imagen inválidos",+ "media.mapFailed": "No se pudieron leer los datos de la imagen",+ "media.noAudio": "El archivo no tiene audio",+ "media.noDecoder": "No hay un decodificador para este formato",+ "media.noEncoder": "No hay un codificador para este formato",+ "media.noHelper": "El ayudante multimedia (lord-media) no está disponible",+ "media.noOutput": "No se pudo crear el archivo de salida",+ "media.noRuntimeDir": "La sesión no tiene carpeta de ejecución (XDG_RUNTIME_DIR)",+ "media.noVideoEncoder": "No hay un codificador de video disponible",+ "media.notAFile": "No es un archivo",+ "media.notAnImage": "No es una imagen",+ "media.nothingToPlay": "No hay audio ni video que se pueda reproducir",+ "media.outsideHome": "Ruta inválida o fuera de la carpeta personal",+ "media.queueFull": "Hay demasiadas tareas multimedia pendientes; probá de nuevo en un momento",+ "media.scaleFailed": "No se pudo cambiar el tamaño de la imagen",+ "media.threadFailed": "No se pudo iniciar la reproducción",+ "media.tooMany": "Hay demasiados medios abiertos",+ "media.unknownJob": "Tarea multimedia desconocida",+ "media.unsupportedFormat": "Formato no compatible",+ "media.writeFailed": "No se pudo escribir el archivo",+ "net.applyFailed": "No se pudo aplicar la configuración en {name}",+ "net.downFailed": "No se pudo apagar {name}: {errno}",+ "net.invalidValue": "Valor inválido: {key}={value}",+ "net.missingAddress": "Una configuración estática necesita una dirección",+ "net.missingMethod": "Elegí un método: DHCP, estática o apagada",+ "net.netlinkFailed": "No se pudo hablar con el kernel (netlink)",+ "net.saveFailed": "No se pudo guardar la configuración",+ "net.stillSystem": "{name} la sigue administrando el sistema (¿ifupdown?)",+ "net.systemManaged": "{name} la administra el sistema (systemd-networkd o ifupdown): pasala a LordOS primero",+ "net.unknownInterface": "Interfaz de red desconocida: {name}",+ "net.upFailed": "No se pudo encender {name}: {errno}",+ "netd.restarted": "El servicio de red del sistema se reinició; probá de nuevo",+ "netd.unavailable": "El servicio de red del sistema no está disponible",+ "ovpn.authFile": "Línea {line}: auth-user-pass no lleva archivo (se pide la contraseña)",+ "ovpn.blockNotAllowed": "Línea {line}: bloque no permitido: {block}",+ "ovpn.blockUnclosed": "Falta </{block}>",+ "ovpn.invalidArgument": "Línea {line}: argumento inválido",+ "ovpn.missingFile": "Falta el archivo {file}",+ "ovpn.mustBeInline": "Línea {line}: {option} tiene que estar incrustado (<{option}>)",+ "ovpn.noCa": "Falta el certificado de la autoridad (<ca>)",+ "ovpn.notClient": "No es una configuración de cliente (falta client)",+ "ovpn.onlyTun": "Solo se admiten dispositivos tun",+ "ovpn.optionNotAllowed": "Línea {line}: opción no permitida: {option}",+ "perm.cameraDenied": "Esta app no tiene permiso para usar la cámara",+ "perm.usbDenied": "Esta app no tiene permiso para usar dispositivos USB",+ "pkg.busy": "Hay otra operación de paquetes en curso",+ "pkg.conflict": "{name} y {other} no se pueden instalar juntos",+ "pkg.conflictInstalled": "{name} choca con {other}, que está instalado",+ "pkg.deb.badControl": "El archivo control del .deb es inválido",+ "pkg.deb.compression": "{name} no está soportado (se usa xz o gzip)",+ "pkg.deb.controlDamaged": "El control.tar del .deb está dañado",+ "pkg.deb.missingDeps": "{name} necesita paquetes que no están en las fuentes",+ "pkg.deb.noControl": "El .deb no tiene archivo control",+ "pkg.deb.noControlTar": "El .deb no tiene control.tar",+ "pkg.deb.notDeb": "No es un paquete .deb",+ "pkg.deb.wrongArch": "{name} es para {arch} y este sistema es {system}",+ "pkg.dependencyUninstallable": "{name} depende de {dep}, que no se puede instalar",+ "pkg.downloadFailed": "{name}: {reason}",+ "pkg.dpkgBusy": "dpkg está ocupado (¿apt u otro instalador está corriendo?)",+ "pkg.dpkgFailed": "dpkg terminó con código {code} (ver el registro)",+ "pkg.dpkgLockFailed": "No se pudo tomar el lock de dpkg",+ "pkg.dpkgStatusUnreadable": "No se pudo leer la base de dpkg",+ "pkg.file.badHome": "Carpeta personal inválida",+ "pkg.file.copyFailed": "No se pudo copiar el archivo",+ "pkg.file.needDebPath": "Hace falta la ruta completa de un archivo .deb",+ "pkg.file.openFailed": "No se pudo abrir el archivo (¿enlace, permisos o no es un archivo?)",+ "pkg.file.outsideHome": "El archivo tiene que estar en tu carpeta personal",+ "pkg.file.pathTooLong": "La ruta es demasiado larga",+ "pkg.file.unreadable": "No se pudo leer el archivo",+ "pkg.hashMismatchIndex": "el SHA-256 no coincide con el índice firmado",+ "pkg.hashMismatchRelease": "el SHA-256 no coincide con el InRelease firmado",+ "pkg.http.badHeaders": "encabezados HTTP inválidos",+ "pkg.http.badResponse": "respuesta HTTP inválida",+ "pkg.http.badUrl": "dirección inválida",+ "pkg.http.connectFailed": "no se pudo conectar con {host}",+ "pkg.http.connectionLost": "la conexión se cortó",+ "pkg.http.createFailed": "no se pudo crear {path}",+ "pkg.http.hostNotFound": "no se encontró {host}",+ "pkg.http.httpsRedirect": "el servidor redirige a https, que LordOS no usa para paquetes",+ "pkg.http.noResponse": "{host} no respondió",+ "pkg.http.notDownloaded": "no se descargó",+ "pkg.http.saveFailed": "no se pudo guardar {path}",+ "pkg.http.status": "el servidor respondió {status}",+ "pkg.http.tooLarge": "el archivo es más grande de lo permitido",+ "pkg.http.writeFailed": "no se pudo escribir (¿el disco está lleno?)",+ "pkg.index.tooLarge": "el índice es demasiado grande",+ "pkg.index.tooManyPackages": "demasiados paquetes",+ "pkg.index.writeFailed": "no se pudo escribir {path}: {errno}",+ "pkg.indexFailed": "No se pudo armar el índice de paquetes: {reason}",+ "pkg.installAndRemove": "{name} está para instalar y para quitar a la vez",+ "pkg.invalidName": "Nombre de paquete inválido: {name}",+ "pkg.missingName": "Falta el nombre del paquete",+ "pkg.neededButRemoved": "{name} hace falta, pero pediste quitarlo",+ "pkg.noIndex": "Todavía no hay lista de paquetes: primero actualizala",+ "pkg.noPackagesFile": "no se bajó ninguna lista de paquetes",+ "pkg.noSources": "No hay fuentes de paquetes (/etc/apt/sources.list.d)",+ "pkg.noVerifiedSource": "No se pudo verificar ninguna fuente de paquetes",+ "pkg.notFound": "No hay ningún paquete llamado {name}",+ "pkg.notInstalled": "{name} no está instalado",+ "pkg.pgp.badEncoding": "firma mal codificada",+ "pkg.pgp.badSignature": "firma inválida de la clave {key}",+ "pkg.pgp.futureSignature": "firma con fecha futura ({key})",+ "pkg.pgp.incomplete": "mensaje firmado incompleto",+ "pkg.pgp.keyExpired": "la clave {key} venció",+ "pkg.pgp.keyNotSigning": "la clave {key} no es de firma",+ "pkg.pgp.keyRevoked": "la clave {key} está revocada",+ "pkg.pgp.malformed": "firma mal formada",+ "pkg.pgp.noSignature": "falta la firma",+ "pkg.pgp.notClearsigned": "no es un mensaje firmado en claro",+ "pkg.pgp.signatureExpired": "la firma de {key} venció",+ "pkg.pgp.signatureIncomplete": "firma incompleta",+ "pkg.pgp.trailingData": "datos después de la firma",+ "pkg.pgp.unescapedDash": "línea con guion sin escapar",+ "pkg.pgp.unknownKeys": {+ "one": "ninguna firma es de una clave conocida ({count} desconocida)",+ "other": "ninguna firma es de una clave conocida ({count} desconocidas)"+ },+ "pkg.prepareFailed": "No se pudo preparar {path}",+ "pkg.release.expired": "la lista venció (Valid-Until)",+ "pkg.release.future": "la lista tiene fecha futura (¿la hora del sistema está bien?)",+ "pkg.release.malformed": "archivo Release mal formado",+ "pkg.release.noKeys": "no hay claves para verificarla",+ "pkg.release.older": "la lista nueva es más vieja que la guardada",+ "pkg.release.saveFailed": "no se pudo guardar",+ "pkg.release.unreadable": "no se pudo leer",+ "pkg.release.wrongSuite": "la lista es de {got}, no de {want}",+ "pkg.removeAlso": "También hay que quitar: {names}",+ "pkg.removeEssential": "{name} es esencial para el sistema y no se puede quitar",+ "pkg.tooManyCombinations": "Demasiadas combinaciones posibles; pedí los paquetes de a uno",+ "pkg.unresolvable": "No se pudieron resolver las dependencias",+ "pkg.virtual": "{name} es un paquete virtual; elegí uno de: {options}",+ "pkgstate.badFolder": "La carpeta de la app tiene enlaces o nombres inválidos",+ "pkgstate.badManifest": "Manifest inválido",+ "pkgstate.buildFailed": "No se pudo armar el paquete",+ "pkgstate.exists": "Ya existe un archivo con ese nombre",+ "pkgstate.invalidApp": "App inválida",+ "pkgstate.keyFailed": "No se pudo crear tu clave de firma propia",+ "pkgstate.manifestNotBasedOn": "El manifest tiene que ser de la misma app y traer basedOn",+ "pkgstate.readFailed": "No se pudo leer la carpeta de la app",+ "pkgstate.restoreFailed": "No se pudo restaurar el original",+ "pkgstate.shareFailed": "No se pudo compartir la app",+ "pkgstate.updateOtherKey": "La actualización está firmada con otra clave que la versión instalada",+ "pkgstate.updateUnsigned": "La versión instalada está firmada y esta actualización no",+ "pkgstate.writeFailed": "No se pudo escribir el paquete",+ "print.badAddress": "Nombre o dirección de impresora inválidos",+ "print.badDocument": "El documento tiene que ser un PDF de tu carpeta personal",+ "print.badPrinter": "Nombre de impresora inválido",+ "print.badScanner": "Escáner inválido (solo direcciones de la red local)",+ "rec.noMicrophone": "No hay micrófono disponible",+ "rec.startFailed": "No se pudo empezar a grabar (¿hay otra grabación en curso?)",+ "remote.badPort": "Puerto inválido",+ "remote.configFailed": "No se pudo guardar la configuración del escritorio remoto",+ "remote.groupFailed": "No se pudo crear el grupo lordos-remote",+ "remote.listenFailed": "El escritorio remoto no pudo escuchar en el puerto {port}",+ "remote.needSessiond": "El escritorio remoto necesita el servicio de sesiones de LordOS (lord-sessiond)",+ "remote.noSuchConnection": "Esa conexión no existe",+ "remote.notRunning": "El servicio de escritorio remoto no está prendido",+ "settings.tooLarge": "Los ajustes son demasiado grandes para guardarlos",+ "sig.badSignatureFile": "firma.json inválido",+ "sig.catalog.invalid": "catalog.json inválido",+ "sig.catalog.unknownFormat": "Catálogo de un formato desconocido",+ "sig.catalog.unofficial": "El catálogo no está firmado por LordOS",+ "sig.contents.badEntry": "contenido.json tiene una entrada inválida",+ "sig.contents.duplicate": "contenido.json repite un archivo",+ "sig.contents.invalid": "contenido.json inválido",+ "sig.contents.missing": "El paquete tiene firma pero no contenido.json",+ "sig.contents.noFiles": "contenido.json no tiene la lista de archivos",+ "sig.contents.otherApp": "contenido.json es de otra app o de otra versión",+ "sig.contents.otherKey": "contenido.json nombra otra clave que la de la firma",+ "sig.contents.unknownFormat": "contenido.json es de un formato desconocido",+ "sig.extraFiles": "El paquete trae archivos que no están en contenido.json",+ "sig.fileMissing": "Falta un archivo del paquete: {path}",+ "sig.fileModified": "El archivo {path} fue modificado",+ "sig.mismatch": "La firma no corresponde al contenido",+ "sig.revokedKey": "LordOS revocó la clave con la que se firmó esta app",+ "sig.revokedVersion": "LordOS revocó esta versión de la app",+ "sig.unknownFormat": "Firma de un formato desconocido",+ "sys.badArgument": "Pedido inválido (un error del programa)",+ "sys.errno": "{errno}",+ "sys.outOfMemory": "Sin memoria",+ "sys.programError": "{program} falló",+ "sys.programFailed": "{program} falló (código {code})",+ "sys.readFailed": "No se pudo leer {path}",+ "sys.unknown": "Error desconocido",+ "sys.writeFailed": "No se pudo escribir {path}",+ "term.createFailed": "No se pudo crear la terminal",+ "tz.unknown": "Zona horaria desconocida: {zone}",+ "users.avatarFailed": "No se pudo guardar la imagen",+ "users.avatarNotAllowed": "Solo un administrador cambia la imagen de otro usuario",+ "users.badAvatarImage": "La imagen tiene que ser PNG o JPEG de tu carpeta personal (hasta 4 MB)",+ "users.badNameOrPassword": "Nombre o contraseña inválidos",+ "users.deleteSelf": "No se puede borrar la cuenta con la que estás",+ "users.exists": "Ya existe «{name}»",+ "users.groupFailed": "No se pudo cambiar el grupo",+ "users.invalid": "Usuario inválido",+ "users.lastAdmin": "Es el único administrador",+ "users.passwordNotAllowed": "Solo un administrador cambia la contraseña de otro usuario",+ "users.setPasswordFailed": "No se pudo cambiar la contraseña",+ "users.wrongPassword": "La contraseña actual no es correcta",+ "vault.requestTooLarge": "El pedido a Contraseñas es demasiado grande",+ "vault.unavailable": "Contraseñas (lord-vault) no está disponible",+ "vpn.badChar": "Línea {line}: carácter inválido en {key}",+ "vpn.createIfFailed": "No se pudo crear {name}: {errno}",+ "vpn.credentialsOnlyOpenvpn": "Solo OpenVPN pide usuario y contraseña",+ "vpn.expectedKeyValue": "Línea {line}: se esperaba clave = valor",+ "vpn.invalidCredentials": "Usuario o contraseña inválidos",+ "vpn.invalidLineValue": "Línea {line}: {key} inválido",+ "vpn.invalidName": "Nombre inválido: usá letras, números, - y _ (hasta 24)",+ "vpn.invalidValue": "{key} inválido",+ "vpn.ipsecBusy": "Ya hay otra VPN IPsec conectada (una a la vez)",+ "vpn.lost": "Se perdió la conexión de la VPN",+ "vpn.missingCredentials": "Faltan el usuario y la contraseña",+ "vpn.missingKey": "Falta {key} o es inválido",+ "vpn.missingProgram": "{type} necesita el paquete {package}: activalo primero",+ "vpn.noAddress": "El servidor de la VPN no dio una dirección",+ "vpn.noConfig": "Falta la configuración de la VPN",+ "vpn.notConnected": "La VPN no estaba conectada",+ "vpn.pemRequired": "Línea {line}: {key} tiene que ser PEM (-----BEGIN …)",+ "vpn.pemUnclosed": "{key}: falta -----END",+ "vpn.resolveFailed": "No se pudo resolver {host}",+ "vpn.routesFailed": "No se pudieron agregar las rutas por {dev}: {errno}",+ "vpn.serverUnresolved": "No se encontró el servidor de la VPN (DNS)",+ "vpn.startFailed": "No se pudo iniciar la VPN",+ "vpn.tooManyLines": "La configuración tiene demasiadas líneas",+ "vpn.tooManyPem": "Demasiados bloques PEM",+ "vpn.unknown": "VPN desconocida: {name}",+ "vpn.unknownKey": "Línea {line}: clave desconocida {key}",+ "vpn.unsupportedType": "Tipo de VPN no admitido: {type}",+ "vpn.writeFailed": "No se pudo escribir la configuración de la VPN",+ "vpn.xfrmFailed": "No se pudo crear la interfaz IPsec: {errno}",+ "wg.noKernel": "El kernel no tiene WireGuard",+ "wg.noRandom": "No hay números aleatorios disponibles",+ "wg.peerNoPublicKey": "Un [Peer] no tiene PublicKey",+ "wg.setDeviceFailed": "No se pudo configurar WireGuard: {errno}",+ "wg.tooManyPeers": "Demasiadas secciones [Peer]",+ "wifi.invalidPassword": "Contraseña inválida (al menos 8 caracteres)",+ "wifi.invalidSsid": "Nombre de red inválido",+ "wifi.noAnswer": "El servicio de Wi-Fi no respondió",+ "wifi.noSupplicant": "El Wi-Fi no está funcionando en {name}: encendé la interfaz primero",+ "wifi.notSaved": "Esa red no estaba guardada",+ "wifi.notWifi": "{name} no es una interfaz Wi-Fi",+ "wifi.rejected": "El servicio de Wi-Fi no aceptó la red",+ "wifi.saveFailed": "No se pudo guardar la red",+ "wifi.selectFailed": "El servicio de Wi-Fi no pudo elegir la red",+ "wifi.startFailed": "No se pudo iniciar el Wi-Fi en {name}"+}diff --git a/assets/locales/es/mail.json b/assets/locales/es/mail.jsonindex 9067e9e..b725b5c 100644--- a/assets/locales/es/mail.json+++ b/assets/locales/es/mail.json@@ -12,6 +12,7 @@"categories": "Categorías","favorites": "Favoritos","unifiedInbox": "Todas las bandejas de entrada",+ "unifiedInboxShort": "Entrada","unread": "No leídos","flagged": "Marcados","addAccount": "Agregar cuenta",@@ -117,6 +118,7 @@"setup.namePh": "Tu nombre, como lo ven los destinatarios","setup.davNamePh": "Nextcloud, iCloud…","setup.email": "Correo",+ "setup.emailPh": "[email protected]","setup.password": "Contraseña","setup.url": "URL del servidor","setup.user": "Usuario",diff --git a/assets/locales/es/prefs.json b/assets/locales/es/prefs.jsonindex 894e3e3..1c6c922 100644--- a/assets/locales/es/prefs.json+++ b/assets/locales/es/prefs.json@@ -70,6 +70,7 @@"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.arrangement": "Disposición","display.brightness": "Brillo","display.capture": "Capturas y compartir","display.captureAll": "Todas las pantallas",@@ -85,17 +86,22 @@"other": "La pantalla vuelve a la configuración anterior en {count} segundos."},"display.keepTitle": "¿Mantener esta configuración de pantalla?",+ "display.largerText": "Texto más grande","display.looksLike": "se ve como {w} × {h}",+ "display.mainHint": "Tiene la barra de menú y el Dock.","display.mainLabel": "pantalla principal","display.makeMain": "Usar como principal","display.menuBarAll": "Mostrar la barra de menú en todas las pantallas","display.mirror": "Duplicar",+ "display.mirrorDisplays": "Duplicar pantallas",+ "display.moreSpace": "Más espacio","display.multiple": "Varias pantallas","display.multipleHint": "Extender arma un solo escritorio sobre todas las pantallas: las ventanas pasan de una a otra y pueden ocupar dos. Duplicar muestra la pantalla principal en todas.","display.native": "{w} × {h} (nativa)","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. Night Shift se aplica cuando vuelva.",+ "display.recommended": "Recomendado","display.refresh": "Frecuencia de actualización","display.resolution": "Resolución","display.revert": "Volver",@@ -106,8 +112,10 @@"display.scaleHint": "Los textos, íconos e imágenes se dibujan a la resolución de la pantalla, así que todas las escalas se ven nítidas. Las apps de Linux con escala fraccional también se dibujan así.","display.scaleN": "{n} %","display.scaleRecommended": "{n} % (recomendado)",+ "display.showList": "Mostrar como lista","display.unavailable": "No hay información de las pantallas.","display.useAs": "Usar como",+ "display.useAsMain": "Usar como pantalla principal","night.custom": "Personalizado","night.customHint": "Night Shift se activa y desactiva a estas horas todos los días.","night.footer": "Night Shift pasa los colores de la pantalla hacia los tonos más cálidos cuando oscurece.",diff --git a/assets/locales/es/print.json b/assets/locales/es/print.jsonindex 73bac67..70756d7 100644--- a/assets/locales/es/print.json+++ b/assets/locales/es/print.json@@ -78,7 +78,18 @@"scan": "Escanear…","noScanners": "No se encontraron escáneres en la red.","tlsUnsupported": "solo cifrado (todavía no)",- "err.forbidden": "Tu usuario no puede administrar impresoras: hace falta ser administrador (grupo lpadmin).",+ "err.forbidden": "no tenés permiso para administrar impresoras","err.notFound": "CUPS no encontró esa impresora",- "err.other": "CUPS respondió: {error}"+ "err.other": "CUPS respondió: {error}",+ "err.encode": "no se pudo armar el pedido",+ "err.no-cups": "el servicio de impresión (CUPS) no está funcionando",+ "err.http": "la impresora respondió con un error ({detail})",+ "err.bad-response": "respuesta inválida de la impresora",+ "err.bad-request": "pedido inválido",+ "err.bad-pages": "rango de páginas inválido",+ "err.unreachable": "no se pudo llegar",+ "err.busy": "está ocupado; probá de nuevo en un momento",+ "err.timeout": "tardó demasiado",+ "err.write": "no se pudo escribir el archivo",+ "err.unknown": "error desconocido"}diff --git a/assets/locales/es/shell.json b/assets/locales/es/shell.jsonindex b57f75b..f909618 100644--- a/assets/locales/es/shell.json+++ b/assets/locales/es/shell.json@@ -118,5 +118,9 @@"spotlight.inHelp": "Artículo de ayuda","picker.cancel": "Cancelar","picker.choose": "Elegir ({n})",- "picker.empty": "No hay archivos acá."+ "picker.empty": "No hay archivos acá.",+ "wallpaper.aurora": "Aurora",+ "wallpaper.ocean": "Océano",+ "wallpaper.sunset": "Atardecer",+ "wallpaper.graphite": "Grafito"}diff --git a/assets/locales/es/status.json b/assets/locales/es/status.jsonnew file mode 100644index 0000000..41c0f8c--- /dev/null+++ b/assets/locales/es/status.json@@ -0,0 +1,119 @@+{+ "disk.cancelling": "Cancelando",+ "disk.ejected": "Expulsado",+ "disk.erased": "Borrado",+ "disk.rereadWarning": "Aviso: el kernel no releyó la tabla de particiones ({errno})",+ "disk.unmounted": "Desmontado",+ "disk.unmountedPath": "Desmontado {path}",+ "disk.verified": "Verificado (SHA-256 {sha256})",+ "hw.profileSet": "Modo de energía: {profile}",+ "hw.suspended": "Suspendiendo",+ "hw.unblocked": "Desbloqueado",+ "install.chownWarning": "Aviso: no se pudo cambiar el dueño de un archivo",+ "install.done": "LordOS quedó instalado en {dev}",+ "install.homedirsWarning": "Aviso: no se pudieron crear las carpetas del usuario",+ "install.installingTo": "Instalando en {dev}",+ "install.rebooting": "Reiniciando",+ "install.stepFailed": "{program} falló (código {code})",+ "install.timezoneWarning": "Aviso: no se pudo poner la zona horaria",+ "lang.installed": {+ "one": "{count} paquete instalado para «{lang}»",+ "other": "{count} paquetes instalados para «{lang}»"+ },+ "lang.noDebianPackages": "No hay paquetes de Debian para «{lang}»: solo la región y los textos de LordOS",+ "lang.package": "Paquete: {name}",+ "locale.generated": "Región {name} instalada",+ "locale.systemSet": "Región del sistema: {name}",+ "net.alreadyLordos": "{name} ya la administraba LordOS",+ "net.configured": "{name}: {method}",+ "net.down": "{name} apagada",+ "net.managed": "{name} ahora la administra LordOS",+ "net.otherSession": "La red la administra otra sesión",+ "net.restoreSystem": "La red la administra el sistema",+ "net.restored": {+ "one": "{count} interfaz configurada",+ "other": "{count} interfaces configuradas"+ },+ "net.unmanaged": "{name} vuelve a administrarla el sistema",+ "net.up": "{name} encendida",+ "ovpn.ignoredWindows": {+ "one": "Se ignoró {count} opción que solo vale en Windows",+ "other": "Se ignoraron {count} opciones que solo valen en Windows"+ },+ "pkg.componentMissing": "Falta {component} ({suite})",+ "pkg.done": "{installed} instalado(s), {upgraded} actualizado(s), {removed} quitado(s)",+ "pkg.downloadingIndex": {+ "one": "Bajando {count} archivo de índice ({kb} KB)",+ "other": "Bajando {count} archivos de índice ({kb} KB)"+ },+ "pkg.downloadingPackages": {+ "one": "Bajando {count} paquete ({kb} KB)",+ "other": "Bajando {count} paquetes ({kb} KB)"+ },+ "pkg.dpkgInterrupted": "dpkg quedó a medio terminar: corriendo dpkg --configure -a",+ "pkg.dpkgRemoveExit": "dpkg --remove terminó con código {code}",+ "pkg.fileFailed": "{url}: {reason}",+ "pkg.flatRepo": "Repositorio plano no soportado: {uri} {suite}",+ "pkg.keyUnreadable": "No se pudo leer la clave {path}",+ "pkg.localPackage": "Paquete local: {name} {version} ({arch})",+ "pkg.nothingToDo": "Nada para hacer: ya está todo instalado",+ "pkg.nothingToRemove": "No hay nada para quitar",+ "pkg.source": "Fuente: {uri} {suite} {component}",+ "pkg.sourceFailed": "{uri} {suite}: {reason}",+ "pkg.sourceMissingFile": "{uri} {suite}: no hay {file}",+ "pkg.sourceSkipped": "Fuente salteada (solo http/https): {uri}",+ "pkg.sourceVerified": "{uri} {suite}: firma verificada ({label})",+ "pkg.unresolvedDep": "Dependencia sin resolver: {name}",+ "pkg.upToDate": {+ "one": "La lista ya estaba al día ({count} paquete)",+ "other": "La lista ya estaba al día ({count} paquetes)"+ },+ "pkg.updated": {+ "one": "{count} paquete de {sources} fuente(s)",+ "other": "{count} paquetes de {sources} fuente(s)"+ },+ "pkg.updatedWithProblems": {+ "one": "{count} paquete de {sources} fuente(s) ({problems} con problemas: ver el registro)",+ "other": "{count} paquetes de {sources} fuente(s) ({problems} con problemas: ver el registro)"+ },+ "pkg.why.auto": "Ya no hace falta",+ "pkg.why.conflictsWith": "Choca con {name}",+ "pkg.why.dependencyOf": "Dependencia de {name}",+ "pkg.why.lostDependency": "Dependía de {dep}",+ "pkg.why.requested": "Pedido",+ "pkg.why.upgrade": "Actualización",+ "pkg.why.upgradedFor": "Se actualiza para {name}",+ "remote.disconnected": "Conexión cortada",+ "remote.off": "Escritorio remoto apagado",+ "remote.on": "Escritorio remoto prendido",+ "remote.saved": "Configuración guardada",+ "remote.userAdded": "{name} puede conectarse de forma remota",+ "remote.userRemoved": "{name} ya no puede conectarse de forma remota",+ "tz.set": "Zona horaria: {zone}",+ "users.autologinOff": "Inicio automático apagado",+ "users.autologinOn": "Inicio automático prendido",+ "users.avatarSaved": "Imagen guardada",+ "users.created": "Usuario {name} creado",+ "users.deleted": "Usuario {name} borrado",+ "users.homedirsWarning": "Aviso: no se pudieron crear todas las carpetas",+ "users.noLongerAdmin": "{name} ya no es administrador",+ "users.nowAdmin": "{name} ahora es administrador",+ "users.passwordChanged": "Contraseña cambiada",+ "users.unchanged": "Sin cambios",+ "vpn.alreadyConnecting": "Ya se estaba conectando",+ "vpn.alreadyInstalled": "Ya estaba instalado",+ "vpn.connected": "Conectada",+ "vpn.connecting": "Conectando…",+ "vpn.deleted": "VPN borrada",+ "vpn.disconnected": "Desconectada",+ "vpn.disconnecting": "Desconectando…",+ "vpn.imported": "VPN importada",+ "vpn.saved": "Guardado",+ "wg.ignoredLines": {+ "one": "Se ignoró {count} línea (PostUp, PreDown, Table…): LordOS no ejecuta comandos",+ "other": "Se ignoraron {count} líneas (PostUp, PreDown, Table…): LordOS no ejecuta comandos"+ },+ "wifi.connecting": "Conectando a {ssid}…",+ "wifi.disconnected": "Desconectado",+ "wifi.forgotten": "Red olvidada"+}diff --git a/assets/locales/pt/about.json b/assets/locales/pt/about.jsonindex f7c2afe..c341144 100644--- a/assets/locales/pt/about.json+++ b/assets/locales/pt/about.json@@ -1,5 +1,6 @@{"cpu": "Processador",+ "cpuUnknown": "Desconhecido","cpuValue": {"one": "{cpu} · {count} núcleo","other": "{cpu} · {count} núcleos"diff --git a/assets/locales/pt/backup.json b/assets/locales/pt/backup.jsonindex ee75cd6..cca5cb9 100644--- a/assets/locales/pt/backup.json+++ b/assets/locales/pt/backup.json@@ -108,12 +108,5 @@"encLock": "Bloquear","encWorking": "Verificando a frase…","notify.lockedTitle": "As cópias de segurança estão criptografadas",- "notify.lockedBody": "Digite a frase para que as cópias programadas continuem.",- "err.wrong-passphrase": "Frase incorreta",- "err.not-encrypted": "Este destino não está criptografado",- "err.plain-backups-exist": "Já existem cópias sem criptografia neste destino: escolha outro",- "err.setup-failed": "Não foi possível ativar a criptografia",- "err.no-destination": "Escolha um destino primeiro",- "err.locked": "As cópias estão criptografadas: desbloqueie-as primeiro",- "err.interrupted": "Foi interrompida"-}\ No newline at end of file+ "notify.lockedBody": "Digite a frase para que as cópias programadas continuem."+}diff --git a/assets/locales/pt/docs.json b/assets/locales/pt/docs.jsonindex 8d5f9b1..f8fb955 100644--- a/assets/locales/pt/docs.json+++ b/assets/locales/pt/docs.json@@ -48,5 +48,26 @@"err.too-big": "é grande demais","err.too-many": "tem arquivos demais","err.corrupt": "está danificado",- "err.write": "não foi possível gravar"+ "err.write": "não foi possível gravar",+ "err.unavailable": "o assistente de documentos não está disponível",+ "err.cancelled": "cancelado",+ "err.crash": "o assistente de documentos parou de repente",+ "err.timeout": "demorou demais",+ "err.protocol": "o assistente de documentos enviou uma resposta inválida",+ "err.spawn": "não foi possível iniciar o assistente de documentos",+ "err.closed": "o documento foi fechado",+ "err.bad-request": "pedido inválido",+ "err.bad-field": "campo de formulário inválido",+ "err.bad-page": "página inválida",+ "err.busy": "o assistente de documentos está ocupado",+ "err.memory": "sem memória",+ "err.no-fonts": "não há fontes disponíveis",+ "err.not-open": "o documento não está aberto",+ "err.nothing": "não há nada para salvar",+ "err.read-only": "o documento é somente leitura",+ "err.save": "não foi possível salvar",+ "err.unknown-op": "operação desconhecida",+ "err.image": "imagem inválida",+ "err.blob": "dados inválidos",+ "err.password": "o documento é protegido por senha"}diff --git a/assets/locales/pt/errors.json b/assets/locales/pt/errors.jsonnew file mode 100644index 0000000..d505f73--- /dev/null+++ b/assets/locales/pt/errors.json@@ -0,0 +1,519 @@+{+ "admin.actionFailed": "A ação terminou com um erro",+ "admin.forkFailed": "Não foi possível iniciar a ação",+ "admin.invalidArgument": "Argumento inválido",+ "admin.noReply": "A ação terminou sem responder",+ "admin.notAdmin": "{user} não é administrador",+ "admin.tooMany": "Há ações demais em andamento; tente novamente em instantes",+ "admin.unavailable": "O assistente de administração não está disponível",+ "admin.unknownAction": "Ação de administração desconhecida",+ "backup.alreadyRunning": "Já há um backup em andamento",+ "backup.badConfig": "Configuração de backup inválida",+ "backup.badDest": "Destino inválido",+ "backup.badExclusion": "Exclusão inválida",+ "backup.badId": "Backup inválido",+ "backup.badPassphrase": "Frase inválida",+ "backup.badPath": "Caminho inválido",+ "backup.badSchedule": "Agendamento inválido",+ "backup.badSuffix": "Sufixo inválido",+ "backup.busy": "Outra tarefa de backup está em andamento",+ "backup.configTooLarge": "A configuração de backup é grande demais",+ "backup.createFailed": "Não foi possível criar {path}: {errno}",+ "backup.destMissing": "O destino não existe",+ "backup.destNotAllowed": "Esse destino não é permitido",+ "backup.destOutside": "O destino precisa estar na sua pasta pessoal ou em um dos seus discos",+ "backup.destUnwritable": "Não é possível gravar no destino",+ "backup.interrupted": "Foi interrompida",+ "backup.locked": "As cópias estão criptografadas: desbloqueie-as primeiro",+ "backup.noDestination": "Escolha um destino primeiro",+ "backup.noSpace": "Não há espaço no destino",+ "backup.noSuchBackup": "Esse backup não existe",+ "backup.notEncrypted": "Este destino não está criptografado",+ "backup.notRunning": "Os backups não estão em execução",+ "backup.passphraseShort": "A frase precisa ter pelo menos 8 caracteres",+ "backup.plainBackupsExist": "Já existem cópias sem criptografia neste destino: escolha outro",+ "backup.readFailed": "Não foi possível ler o backup",+ "backup.saveFailed": "Não foi possível salvar a configuração de backup",+ "backup.setupFailed": "Não foi possível ativar a criptografia",+ "backup.snapshotFailed": "Não foi possível concluir o backup: {errno}",+ "backup.sourceUnreadable": "Não é possível ler a pasta de origem",+ "backup.tooManyExclusions": "Exclusões demais",+ "backup.verifyFailed": "Um arquivo do backup falhou na verificação (adulterado ou chave errada)",+ "backup.wrongPassphrase": "Frase incorreta",+ "camera.busy": "A câmera está ocupada",+ "camera.failed": "A câmera parou de funcionar",+ "camera.invalid": "Câmera inválida",+ "camera.noVideo": "A câmera não captura vídeo",+ "camera.notACamera": "O dispositivo não é uma câmera",+ "camera.openFailed": "Não foi possível abrir a câmera",+ "camera.photoFailed": "Não foi possível tirar a foto",+ "camera.startFailed": "Não foi possível ligar a câmera",+ "camera.unsupportedFormat": "Formato de câmera não suportado",+ "disk.alreadyMounted": "{name} já está montado",+ "disk.badDevice": "Dispositivo inválido",+ "disk.badLabel": "Rótulo inválido",+ "disk.badLabelFor": "Rótulo inválido para {fs}",+ "disk.busy": "{name} está em uso (montado ou aberto por outro programa)",+ "disk.busyFiles": "{name} está em uso (há arquivos abertos em {path})",+ "disk.busyWait": "{name} está em uso: espere terminar o que está fazendo",+ "disk.cancelled": "Cancelado",+ "disk.cancelledPartial": "Cancelado: o disco ficou gravado pela metade",+ "disk.cannotMountFs": "Não é possível montar “{fs}”",+ "disk.cannotRenameFs": "Não é possível renomear “{fs}”",+ "disk.imageOnTarget": "A imagem está no mesmo disco que seria apagado",+ "disk.imageOpenFailed": "Não foi possível abrir a imagem (precisa ser um arquivo da sua pasta ou dos seus discos)",+ "disk.imageReadFailed": "Não foi possível ler a imagem",+ "disk.imageTooLarge": "A imagem ({size} bytes) não cabe em {name} ({capacity} bytes)",+ "disk.internalNeedsAdmin": "Discos internos são gerenciados por um administrador",+ "disk.isPartition": "{name} é uma partição: é preciso o disco inteiro",+ "disk.missingTool": "Falta {program}",+ "disk.mountFailed": "Não foi possível montar {name}: {errno}",+ "disk.mountedElsewhere": "{name} está montado em {path}: desmonte-o manualmente",+ "disk.noDevice": "O dispositivo {name} não existe",+ "disk.noNewPartition": "A nova partição {name} não apareceu",+ "disk.noSmart": "Este disco não informa SMART ({name})",+ "disk.notBlock": "{name} não é um dispositivo de bloco",+ "disk.notMounted": "{name} não está montado",+ "disk.notPartition": "{name} não é uma partição",+ "disk.nothingRunning": "Nada em andamento em {name}",+ "disk.openFailed": "Não foi possível abrir {name}: {errno}",+ "disk.otherUser": "Outro usuário iniciou",+ "disk.smartNoReply": "O disco não respondeu ao SMART (pode não ter, ou estar atrás de um adaptador USB que o bloqueia)",+ "disk.systemDisk": "{name} é o disco do sistema: não é alterado",+ "disk.tableFailed": "Não foi possível gravar a tabela de partições",+ "disk.tooLargeForMbr": "Discos maiores que 2 TiB ainda não são suportados (é preciso GPT)",+ "disk.tooSmall": "O disco é pequeno demais",+ "disk.unknownFs": "{name} não tem um sistema de arquivos conhecido",+ "disk.unknownFsName": "Sistema de arquivos desconhecido: {fs}",+ "disk.unmountFailed": "Não foi possível desmontar {name}: {errno}",+ "disk.unmountFirst": "Desmonte-o primeiro",+ "disk.verifyMismatch": "A verificação falhou: o que ficou no disco não é igual à imagem",+ "disk.verifyReadFailed": "Não foi possível reler {name} para verificar",+ "disk.writeFailed": "Não foi possível gravar em {name}",+ "doc.badBlob": "Dados de documento inválidos",+ "doc.itemCount": "Entre 1 e {max} itens",+ "doc.noHelper": "O assistente de documentos (lord-doc) não está disponível",+ "errno.E2BIG": "Lista de argumentos longa demais",+ "errno.EACCES": "Permissão negada",+ "errno.EAGAIN": "Recurso temporariamente indisponível",+ "errno.EBUSY": "Dispositivo ou recurso ocupado",+ "errno.ECONNREFUSED": "Conexão recusada",+ "errno.ECONNRESET": "Conexão reiniciada",+ "errno.EDQUOT": "Cota de disco excedida",+ "errno.EEXIST": "Já existe",+ "errno.EFBIG": "Arquivo grande demais",+ "errno.EHOSTUNREACH": "Host inacessível",+ "errno.EINTR": "Interrompido",+ "errno.EINVAL": "Argumento inválido",+ "errno.EIO": "Erro de entrada/saída",+ "errno.EISDIR": "É uma pasta",+ "errno.ELOOP": "Níveis demais de links simbólicos",+ "errno.EMFILE": "Arquivos abertos demais",+ "errno.ENAMETOOLONG": "Nome longo demais",+ "errno.ENETUNREACH": "Rede inacessível",+ "errno.ENODEV": "Dispositivo inexistente",+ "errno.ENOENT": "Arquivo ou pasta inexistente",+ "errno.ENOMEM": "Sem memória",+ "errno.ENOSPC": "Sem espaço no dispositivo",+ "errno.ENOTDIR": "Não é uma pasta",+ "errno.ENOTEMPTY": "A pasta não está vazia",+ "errno.ENXIO": "Dispositivo ou endereço inexistente",+ "errno.EOPNOTSUPP": "Operação não suportada",+ "errno.EPERM": "Operação não permitida",+ "errno.EPIPE": "Conexão interrompida",+ "errno.EROFS": "Sistema de arquivos somente leitura",+ "errno.ETIMEDOUT": "Tempo esgotado",+ "errno.ETXTBSY": "Arquivo em uso",+ "errno.EXDEV": "Não é possível mover entre discos",+ "fs.alreadyInTrash": "Já está na Lixeira",+ "fs.copyIntoItself": "Não é possível copiar uma pasta para dentro dela mesma",+ "fs.copyStartFailed": "Não foi possível iniciar a cópia",+ "fs.exists": "Já existe algo com esse nome",+ "fs.moveRemoveFailed": "Copiado, mas não foi possível remover o original: {errno}",+ "fs.noTrash": "Não há Lixeira para esse local",+ "fs.notFile": "Não é um arquivo",+ "fs.notInTrash": "Não está na Lixeira",+ "fs.notRegular": "Não é um arquivo comum (é um link?)",+ "fs.openFailed": "Não foi possível abrir o arquivo: {errno}",+ "fs.outsideHome": "Esse local está fora da sua pasta pessoal ou não é válido",+ "fs.protected": "Essa pasta é protegida",+ "fs.tooLarge": "O arquivo é grande demais (máx. {max})",+ "fs.tooManyCopies": "Há cópias demais em andamento; tente de novo quando uma terminar",+ "fs.trashBadOrigin": "O local original não é válido",+ "fs.trashEntryFailed": "Não foi possível criar a entrada da Lixeira",+ "fs.trashOriginGone": "A pasta original não existe mais",+ "fs.trashOtherDisk": "Está em outro disco que a sua Lixeira",+ "fs.trashRestoreExists": "Já existe um arquivo com esse nome no local original",+ "fw.bpfConfig": "não foi possível configurar o BPF: {errno}",+ "fw.bpfMaps": "não foi possível criar os mapas BPF: {errno}",+ "fw.bpfMissing": "falta o programa {program}",+ "fw.bpfNotBuilt": "compilado sem os programas BPF",+ "fw.bpfRejected": "o kernel não aceitou {program}: {errno}",+ "fw.bpfRing": "não foi possível mapear o buffer de eventos: {errno}",+ "fw.invalidApp": "App inválido",+ "fw.invalidDestination": "Destino inválido",+ "fw.invalidMode": "Modo de firewall inválido",+ "fw.invalidRestrictions": "Restrições inválidas",+ "fw.invalidRule": "Regra inválida ({field})",+ "hw.badProfile": "Modo de energia inválido",+ "hw.badTime": "Data e hora inválidas",+ "hw.brightnessFailed": "Não foi possível alterar o brilho: {errno}",+ "hw.logindFailed": "Não foi possível aplicar a configuração de energia (código {code})",+ "hw.noBacklight": "Essa luz de fundo não existe",+ "hw.noCpufreq": "Este computador não permite alterar a frequência do processador",+ "hw.noRfkill": "Neste computador não é possível desbloquear os dispositivos sem fio",+ "hw.ntpFailed": "Não foi possível alterar a hora automática (código {code})",+ "hw.outOfRange": "Valor fora do intervalo (0 a {max})",+ "hw.profileRefused": "O processador não aceitou o modo de energia",+ "hw.rfkillFailed": "Não foi possível desbloquear: {errno}",+ "hw.setTimeFailed": "Não foi possível alterar a hora (código {code}): desative primeiro a hora automática",+ "hw.suspendFailed": "Não foi possível suspender (código {code})",+ "install.badFullName": "O nome completo tem caracteres inválidos",+ "install.badHostname": "Nome do computador inválido (minúsculas, números e -)",+ "install.badKbLayout": "Layout de teclado inválido",+ "install.badKbVariant": "Variante de teclado inválida",+ "install.badLanguage": "Idioma inválido",+ "install.badPlan": "Dados de instalação inválidos",+ "install.badRegion": "Região não suportada",+ "install.badSwap": "Tamanho de swap inválido (0 a 16384 MB)",+ "install.badTimezone": "Fuso horário inválido",+ "install.badUser": "Nome de usuário inválido (minúsculas, números, - e _)",+ "install.copyFailed": "Não foi possível copiar o sistema",+ "install.diskBusy": "O disco /dev/{disk} está em uso (montado ou com swap)",+ "install.diskNotListed": "O disco não está na lista de discos instaláveis",+ "install.diskTooSmall": "O disco é pequeno demais (mínimo 8 GB)",+ "install.formatEfiFailed": "Não foi possível formatar a partição EFI",+ "install.formatRootFailed": "Não foi possível formatar a partição do sistema",+ "install.grubBiosFailed": "Não foi possível instalar o carregador de inicialização (BIOS)",+ "install.grubConfigFailed": "Não foi possível gerar a configuração do carregador de inicialização",+ "install.grubEfiFailed": "Não foi possível instalar o carregador de inicialização (UEFI)",+ "install.hashFailed": "Não foi possível criptografar a senha",+ "install.initramfsFailed": "Não foi possível gerar o initramfs",+ "install.liveOnly": "O instalador só funciona a partir do sistema ao vivo",+ "install.mountEfiFailed": "Não foi possível montar a partição EFI",+ "install.mountFailed": "Não foi possível montar {path}: {errno}",+ "install.noPartitions": "As novas partições não apareceram",+ "install.noPassword": "Falta a senha",+ "install.partitionFailed": "Não foi possível particionar o disco",+ "install.passwordFailed": "Não foi possível salvar a senha",+ "install.prepareFailed": "Não foi possível preparar o novo sistema",+ "install.rebootFailed": "Não foi possível reiniciar",+ "install.unknownKbLayout": "Layout de teclado desconhecido",+ "install.unknownTimezone": "Fuso horário desconhecido",+ "install.userFailed": "Não foi possível criar o usuário",+ "install.userMissing": "O novo usuário não foi encontrado",+ "install.userReserved": "Esse nome de usuário é reservado",+ "install.userTaken": "O sistema já usa esse nome de usuário",+ "install.uuidFailed": "Não foi possível ler o UUID das partições",+ "install.wipeFailed": "Não foi possível apagar o disco",+ "ipsec.certNeedsKey": "A autenticação por certificado precisa de um certificado e uma chave (PEM)",+ "ipsec.charonExited": "O strongSwan (charon) parou",+ "ipsec.charonFailed": "Não foi possível iniciar o strongSwan (charon)",+ "ipsec.eapNeedsUser": "EAP precisa de usuário e senha",+ "ipsec.noCas": "Não há autoridades certificadoras em /etc/ssl/certs",+ "ipsec.noVici": "O strongSwan (charon) não abriu o socket de controle",+ "ipsec.pskShort": "A chave compartilhada precisa de pelo menos 8 caracteres",+ "ipsec.viciFailed": "O strongSwan rejeitou {cmd}: {detail}",+ "lang.invalidCode": "Código de idioma inválido: {code}",+ "locale.notGenerated": "A região {name} não está instalada",+ "locale.unsupported": "Região não suportada: {name}",+ "logs.badName": "Nome de registro inválido",+ "logs.badQuery": "Pesquisa inválida",+ "logs.noSystemJournal": "Não há journal do sistema",+ "logs.noThread": "Não foi possível iniciar a pesquisa",+ "logs.readFailed": "Não foi possível ler o journal",+ "logs.tooManyQueries": "Pesquisas demais em andamento",+ "lpk.badId": "O id do app não é válido (a-z, 0-9 e -)",+ "lpk.badManifest": "O manifest.json do pacote não é válido",+ "lpk.badPath": "O pacote tem um caminho inválido",+ "lpk.badSignature": "O pacote está danificado ou mal assinado: {reason}",+ "lpk.badVersion": "A versão do app não é válida",+ "lpk.corruptGzip": "O pacote está corrompido (gzip)",+ "lpk.corruptSize": "O pacote está corrompido (tamanho)",+ "lpk.corruptTar": "O pacote está corrompido (tar)",+ "lpk.duplicateFiles": "O pacote tem arquivos repetidos",+ "lpk.empty": "O pacote está vazio",+ "lpk.installFailed": "Não foi possível instalar o app",+ "lpk.installHome": "Não é possível instalar na pasta pessoal",+ "lpk.mkdirFailed": "Não é possível criar a pasta do app",+ "lpk.noFile": "Esse arquivo não existe no app",+ "lpk.noIcon": "O app precisa trazer o próprio ícone (um .png do pacote em \"icon\")",+ "lpk.noName": "O app não tem nome",+ "lpk.notInstalled": "O app não está instalado",+ "lpk.notPackage": "Não é um pacote do LordOS (falta manifest.json ou app.js)",+ "lpk.readFailed": "Não é possível ler o arquivo",+ "lpk.replaceFailed": "Não foi possível substituir a versão instalada",+ "lpk.reservedId": "O id do app é reservado pelo LordOS",+ "lpk.specialFiles": "O pacote tem links ou arquivos especiais",+ "lpk.tooLarge": "O pacote é grande demais",+ "lpk.writeFailed": "Não foi possível gravar o app (o disco está cheio?)",+ "mail.badAccounts": "As contas de e-mail não são válidas",+ "mail.requestTooLarge": "O pedido ao Mail é grande demais",+ "mail.tooManyFiles": "No máximo {max} arquivos por vez",+ "media.audioConvertFailed": "Não foi possível converter o áudio",+ "media.audioOpenFailed": "Não foi possível abrir o áudio",+ "media.cannotOpen": "Não foi possível abrir o arquivo (danificado ou formato não suportado)",+ "media.captureFailed": "Não foi possível capturar a tela",+ "media.convertFailed": "Não foi possível converter a imagem",+ "media.createFailed": "Não foi possível criar o arquivo",+ "media.denied.camera": "{app} não tem permissão para usar a câmera",+ "media.denied.microphone": "{app} não tem permissão para usar o microfone",+ "media.denied.screen": "{app} não tem permissão para gravar a tela",+ "media.encodeFailed": "Não foi possível codificar o arquivo",+ "media.encoderOpenFailed": "Não foi possível iniciar o codificador",+ "media.exportFailed": "Não foi possível exportar",+ "media.fileExists": "Já existe um arquivo com esse nome",+ "media.helperCrashed": "O assistente de mídia parou inesperadamente",+ "media.helperNotResponding": "O assistente de mídia não responde",+ "media.imageUnreadable": "Não foi possível ler a imagem",+ "media.invalidApp": "App inválido",+ "media.invalidArguments": "Argumentos inválidos",+ "media.invalidCrop": "Recorte inválido",+ "media.invalidImage": "Imagem inválida",+ "media.invalidPath": "Caminho inválido",+ "media.invalidPixels": "Dados de imagem inválidos",+ "media.mapFailed": "Não foi possível ler os dados da imagem",+ "media.noAudio": "O arquivo não tem áudio",+ "media.noDecoder": "Nenhum decodificador para este formato",+ "media.noEncoder": "Nenhum codificador para este formato",+ "media.noHelper": "O assistente de mídia (lord-media) não está disponível",+ "media.noOutput": "Não foi possível criar o arquivo de saída",+ "media.noRuntimeDir": "A sessão não tem pasta de execução (XDG_RUNTIME_DIR)",+ "media.noVideoEncoder": "Nenhum codificador de vídeo disponível",+ "media.notAFile": "Não é um arquivo",+ "media.notAnImage": "Não é uma imagem",+ "media.nothingToPlay": "Não há áudio nem vídeo que possa ser reproduzido",+ "media.outsideHome": "Caminho inválido ou fora da pasta pessoal",+ "media.queueFull": "Há tarefas de mídia pendentes demais; tente novamente em instantes",+ "media.scaleFailed": "Não foi possível redimensionar a imagem",+ "media.threadFailed": "Não foi possível iniciar a reprodução",+ "media.tooMany": "Há mídias abertas demais",+ "media.unknownJob": "Tarefa de mídia desconhecida",+ "media.unsupportedFormat": "Formato não suportado",+ "media.writeFailed": "Não foi possível gravar o arquivo",+ "net.applyFailed": "Não foi possível aplicar a configuração em {name}",+ "net.downFailed": "Não foi possível desligar {name}: {errno}",+ "net.invalidValue": "Valor inválido: {key}={value}",+ "net.missingAddress": "Uma configuração estática precisa de um endereço",+ "net.missingMethod": "Escolha um método: DHCP, estático ou desligado",+ "net.netlinkFailed": "Não foi possível falar com o kernel (netlink)",+ "net.saveFailed": "Não foi possível salvar a configuração",+ "net.stillSystem": "{name} continua administrada pelo sistema (ifupdown?)",+ "net.systemManaged": "{name} é administrada pelo sistema (systemd-networkd ou ifupdown): passe-a para o LordOS primeiro",+ "net.unknownInterface": "Interface de rede desconhecida: {name}",+ "net.upFailed": "Não foi possível ligar {name}: {errno}",+ "netd.restarted": "O serviço de rede do sistema reiniciou; tente novamente",+ "netd.unavailable": "O serviço de rede do sistema não está disponível",+ "ovpn.authFile": "Linha {line}: auth-user-pass não leva arquivo (a senha é pedida)",+ "ovpn.blockNotAllowed": "Linha {line}: bloco não permitido: {block}",+ "ovpn.blockUnclosed": "Falta </{block}>",+ "ovpn.invalidArgument": "Linha {line}: argumento inválido",+ "ovpn.missingFile": "Falta o arquivo {file}",+ "ovpn.mustBeInline": "Linha {line}: {option} precisa estar incorporado (<{option}>)",+ "ovpn.noCa": "Falta o certificado da autoridade (<ca>)",+ "ovpn.notClient": "Não é uma configuração de cliente (falta client)",+ "ovpn.onlyTun": "Só dispositivos tun são suportados",+ "ovpn.optionNotAllowed": "Linha {line}: opção não permitida: {option}",+ "perm.cameraDenied": "Este app não tem permissão para usar a câmera",+ "perm.usbDenied": "Este app não tem permissão para usar dispositivos USB",+ "pkg.busy": "Outra operação de pacotes está em andamento",+ "pkg.conflict": "{name} e {other} não podem ser instalados juntos",+ "pkg.conflictInstalled": "{name} conflita com {other}, que está instalado",+ "pkg.deb.badControl": "O arquivo control do .deb é inválido",+ "pkg.deb.compression": "{name} não é suportado (usa-se xz ou gzip)",+ "pkg.deb.controlDamaged": "O control.tar do .deb está danificado",+ "pkg.deb.missingDeps": "{name} precisa de pacotes que não estão nas fontes",+ "pkg.deb.noControl": "O .deb não tem arquivo control",+ "pkg.deb.noControlTar": "O .deb não tem control.tar",+ "pkg.deb.notDeb": "Não é um pacote .deb",+ "pkg.deb.wrongArch": "{name} é para {arch} e este sistema é {system}",+ "pkg.dependencyUninstallable": "{name} depende de {dep}, que não pode ser instalado",+ "pkg.downloadFailed": "{name}: {reason}",+ "pkg.dpkgBusy": "O dpkg está ocupado (o apt ou outro instalador está rodando?)",+ "pkg.dpkgFailed": "O dpkg terminou com código {code} (veja o registro)",+ "pkg.dpkgLockFailed": "Não foi possível obter o bloqueio do dpkg",+ "pkg.dpkgStatusUnreadable": "Não foi possível ler a base do dpkg",+ "pkg.file.badHome": "Pasta pessoal inválida",+ "pkg.file.copyFailed": "Não foi possível copiar o arquivo",+ "pkg.file.needDebPath": "É preciso o caminho completo de um arquivo .deb",+ "pkg.file.openFailed": "Não foi possível abrir o arquivo (link, permissões ou não é um arquivo?)",+ "pkg.file.outsideHome": "O arquivo tem que estar na sua pasta pessoal",+ "pkg.file.pathTooLong": "O caminho é longo demais",+ "pkg.file.unreadable": "Não foi possível ler o arquivo",+ "pkg.hashMismatchIndex": "o SHA-256 não confere com o índice assinado",+ "pkg.hashMismatchRelease": "o SHA-256 não confere com o InRelease assinado",+ "pkg.http.badHeaders": "cabeçalhos HTTP inválidos",+ "pkg.http.badResponse": "resposta HTTP inválida",+ "pkg.http.badUrl": "endereço inválido",+ "pkg.http.connectFailed": "não foi possível conectar a {host}",+ "pkg.http.connectionLost": "a conexão caiu",+ "pkg.http.createFailed": "não foi possível criar {path}",+ "pkg.http.hostNotFound": "{host} não foi encontrado",+ "pkg.http.httpsRedirect": "o servidor redireciona para https, que o LordOS não usa para pacotes",+ "pkg.http.noResponse": "{host} não respondeu",+ "pkg.http.notDownloaded": "não foi baixado",+ "pkg.http.saveFailed": "não foi possível salvar {path}",+ "pkg.http.status": "o servidor respondeu {status}",+ "pkg.http.tooLarge": "o arquivo é maior do que o permitido",+ "pkg.http.writeFailed": "não foi possível gravar (o disco está cheio?)",+ "pkg.index.tooLarge": "o índice é grande demais",+ "pkg.index.tooManyPackages": "pacotes demais",+ "pkg.index.writeFailed": "não foi possível gravar {path}: {errno}",+ "pkg.indexFailed": "Não foi possível montar o índice de pacotes: {reason}",+ "pkg.installAndRemove": "{name} está marcado para instalar e remover ao mesmo tempo",+ "pkg.invalidName": "Nome de pacote inválido: {name}",+ "pkg.missingName": "Falta o nome do pacote",+ "pkg.neededButRemoved": "{name} é necessário, mas você pediu para removê-lo",+ "pkg.noIndex": "Ainda não há lista de pacotes: atualize-a primeiro",+ "pkg.noPackagesFile": "nenhuma lista de pacotes foi baixada",+ "pkg.noSources": "Não há fontes de pacotes (/etc/apt/sources.list.d)",+ "pkg.noVerifiedSource": "Nenhuma fonte de pacotes pôde ser verificada",+ "pkg.notFound": "Não há nenhum pacote chamado {name}",+ "pkg.notInstalled": "{name} não está instalado",+ "pkg.pgp.badEncoding": "assinatura mal codificada",+ "pkg.pgp.badSignature": "assinatura inválida da chave {key}",+ "pkg.pgp.futureSignature": "assinatura com data futura ({key})",+ "pkg.pgp.incomplete": "mensagem assinada incompleta",+ "pkg.pgp.keyExpired": "a chave {key} expirou",+ "pkg.pgp.keyNotSigning": "a chave {key} não é de assinatura",+ "pkg.pgp.keyRevoked": "a chave {key} está revogada",+ "pkg.pgp.malformed": "assinatura malformada",+ "pkg.pgp.noSignature": "falta a assinatura",+ "pkg.pgp.notClearsigned": "não é uma mensagem assinada em texto claro",+ "pkg.pgp.signatureExpired": "a assinatura de {key} expirou",+ "pkg.pgp.signatureIncomplete": "assinatura incompleta",+ "pkg.pgp.trailingData": "dados depois da assinatura",+ "pkg.pgp.unescapedDash": "linha com hífen sem escape",+ "pkg.pgp.unknownKeys": {+ "one": "nenhuma assinatura é de uma chave conhecida ({count} desconhecida)",+ "other": "nenhuma assinatura é de uma chave conhecida ({count} desconhecidas)"+ },+ "pkg.prepareFailed": "Não foi possível preparar {path}",+ "pkg.release.expired": "a lista expirou (Valid-Until)",+ "pkg.release.future": "a lista tem data futura (o relógio do sistema está certo?)",+ "pkg.release.malformed": "arquivo Release malformado",+ "pkg.release.noKeys": "não há chaves para verificá-la",+ "pkg.release.older": "a lista nova é mais antiga que a salva",+ "pkg.release.saveFailed": "não foi possível salvá-la",+ "pkg.release.unreadable": "não foi possível lê-la",+ "pkg.release.wrongSuite": "a lista é de {got}, não de {want}",+ "pkg.removeAlso": "Também é preciso remover: {names}",+ "pkg.removeEssential": "{name} é essencial para o sistema e não pode ser removido",+ "pkg.tooManyCombinations": "Combinações possíveis demais; peça os pacotes um de cada vez",+ "pkg.unresolvable": "Não foi possível resolver as dependências",+ "pkg.virtual": "{name} é um pacote virtual; escolha um de: {options}",+ "pkgstate.badFolder": "A pasta do app tem links ou nomes inválidos",+ "pkgstate.badManifest": "Manifest inválido",+ "pkgstate.buildFailed": "Não foi possível montar o pacote",+ "pkgstate.exists": "Já existe um arquivo com esse nome",+ "pkgstate.invalidApp": "App inválido",+ "pkgstate.keyFailed": "Não foi possível criar sua própria chave de assinatura",+ "pkgstate.manifestNotBasedOn": "O manifest tem que ser do mesmo app e trazer basedOn",+ "pkgstate.readFailed": "Não foi possível ler a pasta do app",+ "pkgstate.restoreFailed": "Não foi possível restaurar o original",+ "pkgstate.shareFailed": "Não foi possível compartilhar o app",+ "pkgstate.updateOtherKey": "A atualização está assinada com uma chave diferente da versão instalada",+ "pkgstate.updateUnsigned": "A versão instalada é assinada e esta atualização não",+ "pkgstate.writeFailed": "Não foi possível gravar o pacote",+ "print.badAddress": "Nome ou endereço de impressora inválido",+ "print.badDocument": "O documento precisa ser um PDF da sua pasta pessoal",+ "print.badPrinter": "Nome de impressora inválido",+ "print.badScanner": "Scanner inválido (só endereços da rede local)",+ "rec.noMicrophone": "Nenhum microfone disponível",+ "rec.startFailed": "Não foi possível começar a gravar (há outra gravação em andamento?)",+ "remote.badPort": "Porta inválida",+ "remote.configFailed": "Não foi possível salvar a configuração da área de trabalho remota",+ "remote.groupFailed": "Não foi possível criar o grupo lordos-remote",+ "remote.listenFailed": "A área de trabalho remota não pôde escutar na porta {port}",+ "remote.needSessiond": "A área de trabalho remota precisa do serviço de sessões do LordOS (lord-sessiond)",+ "remote.noSuchConnection": "Essa conexão não existe",+ "remote.notRunning": "O serviço de área de trabalho remota não está em execução",+ "settings.tooLarge": "As configurações são grandes demais para salvar",+ "sig.badSignatureFile": "firma.json inválido",+ "sig.catalog.invalid": "catalog.json inválido",+ "sig.catalog.unknownFormat": "Catálogo em um formato desconhecido",+ "sig.catalog.unofficial": "O catálogo não está assinado pelo LordOS",+ "sig.contents.badEntry": "contenido.json tem uma entrada inválida",+ "sig.contents.duplicate": "contenido.json repete um arquivo",+ "sig.contents.invalid": "contenido.json inválido",+ "sig.contents.missing": "O pacote tem assinatura mas não contenido.json",+ "sig.contents.noFiles": "contenido.json não tem a lista de arquivos",+ "sig.contents.otherApp": "contenido.json é de outro app ou de outra versão",+ "sig.contents.otherKey": "contenido.json cita outra chave que não a da assinatura",+ "sig.contents.unknownFormat": "contenido.json está em um formato desconhecido",+ "sig.extraFiles": "O pacote traz arquivos que não estão em contenido.json",+ "sig.fileMissing": "Falta um arquivo do pacote: {path}",+ "sig.fileModified": "O arquivo {path} foi modificado",+ "sig.mismatch": "A assinatura não corresponde ao conteúdo",+ "sig.revokedKey": "O LordOS revogou a chave com que este app foi assinado",+ "sig.revokedVersion": "O LordOS revogou esta versão do app",+ "sig.unknownFormat": "Assinatura em um formato desconhecido",+ "sys.badArgument": "Pedido inválido (um erro do programa)",+ "sys.errno": "{errno}",+ "sys.outOfMemory": "Sem memória",+ "sys.programError": "{program} falhou",+ "sys.programFailed": "{program} falhou (código {code})",+ "sys.readFailed": "Não foi possível ler {path}",+ "sys.unknown": "Erro desconhecido",+ "sys.writeFailed": "Não foi possível gravar {path}",+ "term.createFailed": "Não foi possível criar o terminal",+ "tz.unknown": "Fuso horário desconhecido: {zone}",+ "users.avatarFailed": "Não foi possível salvar a imagem",+ "users.avatarNotAllowed": "Só um administrador pode alterar a imagem de outro usuário",+ "users.badAvatarImage": "A imagem precisa ser PNG ou JPEG da sua pasta pessoal (até 4 MB)",+ "users.badNameOrPassword": "Nome ou senha inválidos",+ "users.deleteSelf": "Não é possível excluir a conta que você está usando",+ "users.exists": "“{name}” já existe",+ "users.groupFailed": "Não foi possível alterar o grupo",+ "users.invalid": "Usuário inválido",+ "users.lastAdmin": "É o único administrador",+ "users.passwordNotAllowed": "Só um administrador pode alterar a senha de outro usuário",+ "users.setPasswordFailed": "Não foi possível definir a senha",+ "users.wrongPassword": "A senha atual não está correta",+ "vault.requestTooLarge": "O pedido ao Senhas é grande demais",+ "vault.unavailable": "Senhas (lord-vault) não está disponível",+ "vpn.badChar": "Linha {line}: caractere inválido em {key}",+ "vpn.createIfFailed": "Não foi possível criar {name}: {errno}",+ "vpn.credentialsOnlyOpenvpn": "Só o OpenVPN pede usuário e senha",+ "vpn.expectedKeyValue": "Linha {line}: esperava-se chave = valor",+ "vpn.invalidCredentials": "Usuário ou senha inválidos",+ "vpn.invalidLineValue": "Linha {line}: {key} inválido",+ "vpn.invalidName": "Nome inválido: use letras, números, - e _ (até 24)",+ "vpn.invalidValue": "{key} inválido",+ "vpn.ipsecBusy": "Já há outra VPN IPsec conectada (uma de cada vez)",+ "vpn.lost": "A conexão da VPN foi perdida",+ "vpn.missingCredentials": "Faltam o usuário e a senha",+ "vpn.missingKey": "{key} está faltando ou é inválido",+ "vpn.missingProgram": "{type} precisa do pacote {package}: ative-o primeiro",+ "vpn.noAddress": "O servidor da VPN não forneceu um endereço",+ "vpn.noConfig": "A configuração da VPN está faltando",+ "vpn.notConnected": "A VPN não estava conectada",+ "vpn.pemRequired": "Linha {line}: {key} precisa ser PEM (-----BEGIN …)",+ "vpn.pemUnclosed": "{key}: falta -----END",+ "vpn.resolveFailed": "Não foi possível resolver {host}",+ "vpn.routesFailed": "Não foi possível adicionar as rotas por {dev}: {errno}",+ "vpn.serverUnresolved": "Não foi possível encontrar o servidor da VPN (DNS)",+ "vpn.startFailed": "Não foi possível iniciar a VPN",+ "vpn.tooManyLines": "A configuração tem linhas demais",+ "vpn.tooManyPem": "Blocos PEM demais",+ "vpn.unknown": "VPN desconhecida: {name}",+ "vpn.unknownKey": "Linha {line}: chave desconhecida {key}",+ "vpn.unsupportedType": "Tipo de VPN não suportado: {type}",+ "vpn.writeFailed": "Não foi possível gravar a configuração da VPN",+ "vpn.xfrmFailed": "Não foi possível criar a interface IPsec: {errno}",+ "wg.noKernel": "O kernel não tem suporte a WireGuard",+ "wg.noRandom": "Não há números aleatórios disponíveis",+ "wg.peerNoPublicKey": "Um [Peer] não tem PublicKey",+ "wg.setDeviceFailed": "Não foi possível configurar o WireGuard: {errno}",+ "wg.tooManyPeers": "Seções [Peer] demais",+ "wifi.invalidPassword": "Senha inválida (pelo menos 8 caracteres)",+ "wifi.invalidSsid": "Nome de rede inválido",+ "wifi.noAnswer": "O serviço de Wi-Fi não respondeu",+ "wifi.noSupplicant": "O Wi-Fi não está funcionando em {name}: ligue a interface primeiro",+ "wifi.notSaved": "Essa rede não estava salva",+ "wifi.notWifi": "{name} não é uma interface Wi-Fi",+ "wifi.rejected": "O serviço de Wi-Fi não aceitou a rede",+ "wifi.saveFailed": "Não foi possível salvar a rede",+ "wifi.selectFailed": "O serviço de Wi-Fi não conseguiu escolher a rede",+ "wifi.startFailed": "Não foi possível iniciar o Wi-Fi em {name}"+}diff --git a/assets/locales/pt/mail.json b/assets/locales/pt/mail.jsonindex 2b048d0..b8a970e 100644--- a/assets/locales/pt/mail.json+++ b/assets/locales/pt/mail.json@@ -12,6 +12,7 @@"categories": "Categorias","favorites": "Favoritos","unifiedInbox": "Todas as caixas de entrada",+ "unifiedInboxShort": "Entrada","unread": "Não lidos","flagged": "Sinalizados","addAccount": "Adicionar conta",@@ -117,6 +118,7 @@"setup.namePh": "Seu nome, como os destinatários veem","setup.davNamePh": "Nextcloud, iCloud…","setup.email": "E-mail",+ "setup.emailPh": "[email protected]","setup.password": "Senha","setup.url": "URL do servidor","setup.user": "Usuário",diff --git a/assets/locales/pt/prefs.json b/assets/locales/pt/prefs.jsonindex acdbe32..5911062 100644--- a/assets/locales/pt/prefs.json+++ b/assets/locales/pt/prefs.json@@ -70,6 +70,7 @@"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.arrangement": "Disposição","display.brightness": "Brilho","display.capture": "Capturas e compartilhamento","display.captureAll": "Todas as telas",@@ -85,17 +86,22 @@"other": "A tela volta à configuração anterior em {count} segundos."},"display.keepTitle": "Manter esta configuração de tela?",+ "display.largerText": "Texto maior","display.looksLike": "parece {w} × {h}",+ "display.mainHint": "Tem a barra de menus e o Dock.","display.mainLabel": "tela principal","display.makeMain": "Usar como principal","display.menuBarAll": "Mostrar a barra de menus em todas as telas","display.mirror": "Espelhar",+ "display.mirrorDisplays": "Espelhar telas",+ "display.moreSpace": "Mais espaço","display.multiple": "Várias telas","display.multipleHint": "Estender cria uma única área de trabalho em todas as telas: as janelas passam de uma para outra e podem ocupar duas. Espelhar mostra a tela principal em todas.","display.native": "{w} × {h} (nativa)","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. O Night Shift vale quando ela voltar.",+ "display.recommended": "Recomendado","display.refresh": "Taxa de atualização","display.resolution": "Resolução","display.revert": "Reverter",@@ -106,8 +112,10 @@"display.scaleHint": "Textos, ícones e imagens são desenhados na resolução da tela, então toda escala fica nítida. Apps Linux com escala fracionária também são desenhados assim.","display.scaleN": "{n} %","display.scaleRecommended": "{n} % (recomendado)",+ "display.showList": "Mostrar como lista","display.unavailable": "Não há informação das telas.","display.useAs": "Usar como",+ "display.useAsMain": "Usar como tela principal","night.custom": "Personalizado","night.customHint": "O Night Shift liga e desliga nestes horários todos os dias.","night.footer": "O Night Shift muda as cores da tela para tons mais quentes quando escurece.",diff --git a/assets/locales/pt/print.json b/assets/locales/pt/print.jsonindex 49100ba..f6aa943 100644--- a/assets/locales/pt/print.json+++ b/assets/locales/pt/print.json@@ -78,7 +78,18 @@"scan": "Digitalizar…","noScanners": "Nenhum scanner encontrado na rede.","tlsUnsupported": "somente cifrado (ainda não)",- "err.forbidden": "Seu usuário não pode administrar impressoras: é preciso ser administrador (grupo lpadmin).",+ "err.forbidden": "você não tem permissão para administrar impressoras","err.notFound": "O CUPS não encontrou essa impressora",- "err.other": "O CUPS respondeu: {error}"+ "err.other": "O CUPS respondeu: {error}",+ "err.encode": "não foi possível montar o pedido",+ "err.no-cups": "o serviço de impressão (CUPS) não está funcionando",+ "err.http": "a impressora respondeu com um erro ({detail})",+ "err.bad-response": "resposta inválida da impressora",+ "err.bad-request": "pedido inválido",+ "err.bad-pages": "intervalo de páginas inválido",+ "err.unreachable": "não foi possível alcançá-lo",+ "err.busy": "está ocupado; tente de novo em instantes",+ "err.timeout": "demorou demais",+ "err.write": "não foi possível gravar o arquivo",+ "err.unknown": "erro desconhecido"}diff --git a/assets/locales/pt/shell.json b/assets/locales/pt/shell.jsonindex e039970..9929b8a 100644--- a/assets/locales/pt/shell.json+++ b/assets/locales/pt/shell.json@@ -118,5 +118,9 @@"spotlight.inHelp": "Artigo de ajuda","picker.cancel": "Cancelar","picker.choose": "Escolher ({n})",- "picker.empty": "Não há arquivos aqui."+ "picker.empty": "Não há arquivos aqui.",+ "wallpaper.aurora": "Aurora",+ "wallpaper.ocean": "Oceano",+ "wallpaper.sunset": "Pôr do sol",+ "wallpaper.graphite": "Grafite"}diff --git a/assets/locales/pt/status.json b/assets/locales/pt/status.jsonnew file mode 100644index 0000000..e6b9ac0--- /dev/null+++ b/assets/locales/pt/status.json@@ -0,0 +1,119 @@+{+ "disk.cancelling": "Cancelando",+ "disk.ejected": "Ejetado",+ "disk.erased": "Apagado",+ "disk.rereadWarning": "Aviso: o kernel não releu a tabela de partições ({errno})",+ "disk.unmounted": "Desmontado",+ "disk.unmountedPath": "Desmontado {path}",+ "disk.verified": "Verificado (SHA-256 {sha256})",+ "hw.profileSet": "Modo de energia: {profile}",+ "hw.suspended": "Suspendendo",+ "hw.unblocked": "Desbloqueado",+ "install.chownWarning": "Aviso: não foi possível alterar o dono de um arquivo",+ "install.done": "O LordOS foi instalado em {dev}",+ "install.homedirsWarning": "Aviso: não foi possível criar as pastas do usuário",+ "install.installingTo": "Instalando em {dev}",+ "install.rebooting": "Reiniciando",+ "install.stepFailed": "{program} falhou (código {code})",+ "install.timezoneWarning": "Aviso: não foi possível definir o fuso horário",+ "lang.installed": {+ "one": "{count} pacote instalado para “{lang}”",+ "other": "{count} pacotes instalados para “{lang}”"+ },+ "lang.noDebianPackages": "Não há pacotes Debian para “{lang}”: só a região e os textos do LordOS",+ "lang.package": "Pacote: {name}",+ "locale.generated": "Região {name} instalada",+ "locale.systemSet": "Região do sistema: {name}",+ "net.alreadyLordos": "{name} já era administrada pelo LordOS",+ "net.configured": "{name}: {method}",+ "net.down": "{name} desligada",+ "net.managed": "{name} agora é administrada pelo LordOS",+ "net.otherSession": "A rede é administrada por outra sessão",+ "net.restoreSystem": "A rede é administrada pelo sistema",+ "net.restored": {+ "one": "{count} interface configurada",+ "other": "{count} interfaces configuradas"+ },+ "net.unmanaged": "{name} volta a ser administrada pelo sistema",+ "net.up": "{name} ligada",+ "ovpn.ignoredWindows": {+ "one": "{count} opção exclusiva do Windows ignorada",+ "other": "{count} opções exclusivas do Windows ignoradas"+ },+ "pkg.componentMissing": "Falta {component} ({suite})",+ "pkg.done": "{installed} instalado(s), {upgraded} atualizado(s), {removed} removido(s)",+ "pkg.downloadingIndex": {+ "one": "Baixando {count} arquivo de índice ({kb} KB)",+ "other": "Baixando {count} arquivos de índice ({kb} KB)"+ },+ "pkg.downloadingPackages": {+ "one": "Baixando {count} pacote ({kb} KB)",+ "other": "Baixando {count} pacotes ({kb} KB)"+ },+ "pkg.dpkgInterrupted": "O dpkg ficou pela metade: rodando dpkg --configure -a",+ "pkg.dpkgRemoveExit": "dpkg --remove terminou com código {code}",+ "pkg.fileFailed": "{url}: {reason}",+ "pkg.flatRepo": "Repositório plano não suportado: {uri} {suite}",+ "pkg.keyUnreadable": "Não foi possível ler a chave {path}",+ "pkg.localPackage": "Pacote local: {name} {version} ({arch})",+ "pkg.nothingToDo": "Nada a fazer: já está tudo instalado",+ "pkg.nothingToRemove": "Não há nada para remover",+ "pkg.source": "Fonte: {uri} {suite} {component}",+ "pkg.sourceFailed": "{uri} {suite}: {reason}",+ "pkg.sourceMissingFile": "{uri} {suite}: não há {file}",+ "pkg.sourceSkipped": "Fonte ignorada (só http/https): {uri}",+ "pkg.sourceVerified": "{uri} {suite}: assinatura verificada ({label})",+ "pkg.unresolvedDep": "Dependência não resolvida: {name}",+ "pkg.upToDate": {+ "one": "A lista já estava em dia ({count} pacote)",+ "other": "A lista já estava em dia ({count} pacotes)"+ },+ "pkg.updated": {+ "one": "{count} pacote de {sources} fonte(s)",+ "other": "{count} pacotes de {sources} fonte(s)"+ },+ "pkg.updatedWithProblems": {+ "one": "{count} pacote de {sources} fonte(s) ({problems} com problemas: veja o registro)",+ "other": "{count} pacotes de {sources} fonte(s) ({problems} com problemas: veja o registro)"+ },+ "pkg.why.auto": "Não é mais necessário",+ "pkg.why.conflictsWith": "Conflita com {name}",+ "pkg.why.dependencyOf": "Dependência de {name}",+ "pkg.why.lostDependency": "Dependia de {dep}",+ "pkg.why.requested": "Pedido",+ "pkg.why.upgrade": "Atualização",+ "pkg.why.upgradedFor": "Atualizado para {name}",+ "remote.disconnected": "Conexão encerrada",+ "remote.off": "Área de trabalho remota desativada",+ "remote.on": "Área de trabalho remota ativada",+ "remote.saved": "Configuração salva",+ "remote.userAdded": "{name} pode se conectar remotamente",+ "remote.userRemoved": "{name} não pode mais se conectar remotamente",+ "tz.set": "Fuso horário: {zone}",+ "users.autologinOff": "Login automático desativado",+ "users.autologinOn": "Login automático ativado",+ "users.avatarSaved": "Imagem salva",+ "users.created": "Usuário {name} criado",+ "users.deleted": "Usuário {name} excluído",+ "users.homedirsWarning": "Aviso: não foi possível criar todas as pastas",+ "users.noLongerAdmin": "{name} não é mais administrador",+ "users.nowAdmin": "{name} agora é administrador",+ "users.passwordChanged": "Senha alterada",+ "users.unchanged": "Sem alterações",+ "vpn.alreadyConnecting": "Já estava conectando",+ "vpn.alreadyInstalled": "Já estava instalado",+ "vpn.connected": "Conectada",+ "vpn.connecting": "Conectando…",+ "vpn.deleted": "VPN apagada",+ "vpn.disconnected": "Desconectada",+ "vpn.disconnecting": "Desconectando…",+ "vpn.imported": "VPN importada",+ "vpn.saved": "Salvo",+ "wg.ignoredLines": {+ "one": "{count} linha ignorada (PostUp, PreDown, Table…): o LordOS não executa comandos",+ "other": "{count} linhas ignoradas (PostUp, PreDown, Table…): o LordOS não executa comandos"+ },+ "wifi.connecting": "Conectando a {ssid}…",+ "wifi.disconnected": "Desconectado",+ "wifi.forgotten": "Rede esquecida"+}diff --git a/docs/DESIGN.md b/docs/DESIGN.mdindex 981801b..e51f14c 100644--- a/docs/DESIGN.md+++ b/docs/DESIGN.md@@ -11,7 +11,7 @@ The first pass (Calculator, Text Editor, Notes, Photos, PDF Viewer and Fonts) anwith the system emoji picker, About and the Installer) are documented with before/afterscreenshots in [`docs/polish/`](polish/), as is the third (Settings page by page, Files, TerminalPreferences and the Store's remaining pages), and the fourth (the system apps: Disks, Backups, Logs,-Clock and Help).+Clock and Help), as is the fifth (Mail, Calendar, Contacts and Reminders).## Spacing: an 8 px grid@@ -113,6 +113,16 @@ the Recorder draw their empty-state icons. `↻ ⤮ ♪ ◫ ▣ ☺ ≡` rendertoolbar button at the trailing edge, never a button floating at the bottom.- **Reader (Help):** a centered reading column up to 680 px; the article keeps its own direction(`textDirection(body)`), so an English article in an Arabic interface still reads left to right.+- **Mail / Calendar / Contacts / Reminders:** source lists use monochrome glyphs in the accent+ color; where the glyph would be a color emoji (tray, archive, trash, folder, person) it is drawn+ with views (`Glyph` in `apps/mail`, `PersonGlyph` in `apps/contacts`). Mail keeps three panes with+ an icon-only toolbar over the list and the message; list rows are 86 px (sender, subject, two lines+ of preview) with a rounded selection, and under 1000 px the panes shrink to 200 / 290 px.+ Calendar centers the Day/Week/Month switch, puts the period title (22/700) over the grid with+ ‹ Today › at its trailing edge, and hides the sidebar below 760 px unless asked for. Bottom bars+ of adjacent columns share one height (40 px) so their hairlines line up. Text that belongs to the+ user (event titles, previews) keeps its own direction (`textDirection`) in an RTL UI.+ `ToolbarButton`'s `icon` may also be an element (a drawn glyph).- **Settings (System Settings):** a 220 px sidebar (search field, the user card, groups of`SidebarItem` rows 12 px apart with 20 px colored badges: a soft vertical gradient and a whiteglyph, or a drawn shape where the glyph is a color emoji), a 48 px title bar over the page with adiff --git a/docs/DISPLAYS.md b/docs/DISPLAYS.mdindex 654069b..d5f91f5 100644--- a/docs/DISPLAYS.md+++ b/docs/DISPLAYS.md@@ -147,7 +147,7 @@ Settings → Displays → "Screenshots and sharing": **main display** (default)## Measurements (VM 118, CPU path, 4 vCPU)Window drag (the About window, 6 s circles at 125 events/s with a uinput tablet; lord-server's-`arrastre:` line). "Work" is lord-server's time per rendered frame (JS of the pointer + layout ++`drag:` line). "Work" is lord-server's time per rendered frame (JS of the pointer + layout +paint + present).| Setup | Work per frame | Paint | Present | Frames/s |diff --git a/docs/DOCUMENTS.md b/docs/DOCUMENTS.mdindex e27eaf5..a6b9391 100644--- a/docs/DOCUMENTS.md+++ b/docs/DOCUMENTS.md@@ -295,7 +295,7 @@ lord-server (no Poppler or libarchive)The measurements show up in the session log:- `js: pdf: … first page in N ms (N pages)`;-- `js: vista-rapida: …` (Quick Look; this Files log line is still in Spanish);+- `js: quick-look: <kind> <name> in N ms` (Quick Look, from Files);- with the file `~/.cache/lordos/doc-trace` (or `LORD_DOC_TRACE=1`), `lord-doc: request N: queue Xms, helper Y ms` for each request.@@ -305,7 +305,7 @@ The measurements show up in the session log:make -C server test # includes build/arcpath-test, build/ipp-test and build/doc-testserver/build/arcpath-test # 37/37: names and link targetssh tests/doc_evil.sh # 31/31 (in server/): malicious archives, formats, confinement and annotated copy-server/build/doc-test server/build/lord-doc pdf archivo.pdf 900 # open, draw and measure+server/build/doc-test server/build/lord-doc pdf file.pdf 900 # open, draw and measure```## Pendingdiff --git a/docs/FILES.md b/docs/FILES.mdindex 1ea8989..4663842 100644--- a/docs/FILES.md+++ b/docs/FILES.md@@ -13,7 +13,7 @@ drop, color tags and search. Disk operations belong to the server (`server/src/f| Icons with real image thumbnails | List: columns, alternating rows and folders that expand in place (names in several scripts) ||  |  || Columns (Miller) with the text preview | Gallery: large preview and the strip below |-|  |  |+|  |  || Quick Look (Space), 5 of 7; the arrows go to the next one | Get Info (❖I): size, location, dates, permissions and «Open with» ||  |  || Context menu of a file, with tags | «Open with»: the Text Editor or a Linux app that declares the type (FeatherPad) |diff --git a/docs/GPU.md b/docs/GPU.mdindex c1e2180..1c9dd37 100644--- a/docs/GPU.md+++ b/docs/GPU.md@@ -35,7 +35,7 @@ and its buffers and the apps' dmabufs become framebuffers with `DRM_IOCTL_MODE_Atakes over.Diagnostics: `LORD_GPU_DEBUG=1` shows the dmabuf formats, failing imports and the frames sent by-direct scanout. The log says `gpu: composición por GPU (renderer…)` (GPU composition) or why not.+direct scanout. The log says `gpu: GPU composition (renderer…)` or why not.## How it composites@@ -127,9 +127,9 @@ compositing is the GPU's work, and the CPU only uploads what changed in the UI.To test it on the AMD PC (live ISO):1. Boot.2. In the LordOS Terminal, `grep gpu /tmp/lord.log` (or whatever log the ISO uses): it must say- `composición por GPU (AMD Radeon …)` (GPU composition) and `cursor por hardware` (hardware cursor).+ `GPU composition (AMD Radeon …)` and `cursor by hardware (cursor plane)`.3. `vkcube`, `glmark2-es2-wayland`, a game (SuperTuxKart, 0 A.D.).-4. With `LORD_GPU_DEBUG=1`, in fullscreen `scanout directo: N cuadros` (direct scanout: N frames) must appear.+4. With `LORD_GPU_DEBUG=1`, in fullscreen `direct scanout: N frames` must appear.## Test clientdiff --git a/docs/ISO.md b/docs/ISO.mdindex eeeb9b2..29e4bc7 100644--- a/docs/ISO.md+++ b/docs/ISO.md@@ -35,10 +35,12 @@ motherboard. It works with **UEFI** and with **BIOS/Legacy**. **Secure Boot** ha| Entry | What for ||---|---|-| LordOS (en vivo) | normal, in Spanish |-| LordOS (modo seguro: sin GPU) | passes `lordos.gpu=0` → `LORD_GPU=0`: lord-server doesn't use the GPU path and composites on the CPU |-| LordOS (English) | the interface in English the first time |-| LordOS (copiar a la RAM) | `toram`: copies the system to memory (~1 GB free is needed) and the USB stick can be removed |+| LordOS (live) | normal, in English (the default language) |+| LordOS (safe mode: no GPU) | passes `lordos.gpu=0` → `LORD_GPU=0`: lord-server doesn't use the GPU path and composites on the CPU |+| LordOS (Español) / LordOS (Português) | `lordos.lang=es` / `lordos.lang=pt`: the interface in Spanish or Portuguese the first time |+| LordOS (copy to RAM) | `toram`: copies the system to memory (~1 GB free is needed) and the USB stick can be removed |++The GRUB menu itself is in English (GRUB's default).In the live session:- **User:** `lordos`, no password, with passwordless `sudo`.diff --git a/docs/LANGUAGES.md b/docs/LANGUAGES.mdindex df277ae..a044bb3 100644--- a/docs/LANGUAGES.md+++ b/docs/LANGUAGES.md@@ -48,13 +48,46 @@ formatNumber(1234.5, 2) // "1.234,50" (es_AR) / "1,234.50" (en_US)`few`/`many`/`two`/`zero` depending on the language). Variables: `{name}`.- If a key is missing in the chosen language, English is used; if it's missing there too, the key itself.- App names come from `apps.json` (`appName(app)`); if there is no translation, from- `manifest.json`.+ `manifest.json` (whose `name` and `description` are English).+- **English is the default language** and the fallback: a new user, the greeter, the live system+ (unless GRUB's Español/Português entry passes `lordos.lang`) and the installer start in English.+ A language saved in `settings.json` is always kept.- Changing the language remounts the whole interface. Windows, tabs and sessions live in storesand are kept. That's why lists containing text can't be module-level constants: they are builtin a function or at render time.- QuickJS has no `Intl`: the plural rules (`sdk/i18n.js`) and the formats (`format.json`) are ourown.+### Error and status messages++The server never sends prose to the interface. Every error that can reach the UI (an `ERR` line of+the privileged helper, a `lord.*` exception, an error field of an event) is a **code line**+(`server/src/errcode.h`):++```+pkg.removeEssential name=dpkg+sys.writeFailed path=/etc/locale.gen+fs.readFailed path=/home/ana/a%20b.txt errno=ENOENT+```++`code` is `module.camelCase`; parameter values are percent-encoded (space, `%`, `=`, `"`, control+characters). The UI shows `t('errors.<code>', params)` (`assets/locales/<lang>/errors.json`);+statuses (`OK`/`LOG` lines) use `status.json`. Two parameters are special: `errno=ENOENT` becomes+the translated description (`errors.errno.ENOENT`) and `reason=<code line>` is a nested code.++- C: `admin_err("pkg.x", "name", n, NULL)` / `admin_ok(…)` / `admin_log(…)` in the helper,+ `lerr_set(err, sizeof err, "pkg.x", "name", n, NULL)` for error buffers, and+ `js_throw_code(c, "fs.x", "path", p, NULL)` / `js_throw_line(c, err)` (`server/src/ui/js_err.h`)+ for exceptions. Numbers with `lerr_int(n)`, errno with `lerr_errno(errno)`.+- JS (`sdk/errors.js`): `admin.run()` rejects with an `Error` whose message is already translated+ and that has `.code` and `.params`; `lord.*` exceptions too (the SDK registers+ `globalThis.__lordErrorText`). For other channels, `errorText(lineOrError)` and+ `statusText(line)`. Code that needs to react to an error compares `e.code`, never the text.+- Logs and the journal stay English prose, for developers.+- Tests match codes (`lerr_has(err, "pkg.removeAlso")`), not text.+- `node tools/i18n-check.mjs` fails if a code used in C has no English string, or if an `ERR`+ line or a JS exception is written as prose.+### FormatsEach language's `format.json` has month and day names, date patterns (`short`, `long`,diff --git a/docs/PASSWORDS.md b/docs/PASSWORDS.mdindex 6b9dea3..665e94e 100644--- a/docs/PASSWORDS.md+++ b/docs/PASSWORDS.md@@ -1,6 +1,6 @@# Passwords and the system keyring (M9)-**Contraseñas** ("Passwords" in English, "Senhas" in Portuguese) is the LordOS password manager.+**Passwords** ("Contraseñas" in Spanish, "Senhas" in Portuguese) is the LordOS password manager.The same machinery is also the **system keyring**: native apps keep their secrets there through`lord.keyring` / the SDK `keyring`, and Linux apps (Chromium, Firefox, `secret-tool`, anythingusing libsecret) through our own implementation of the freedesktop **Secret Service** D-Bus API.diff --git a/docs/RASPBERRY.md b/docs/RASPBERRY.mdindex 3100a4a..005b55a 100644--- a/docs/RASPBERRY.md+++ b/docs/RASPBERRY.md@@ -231,7 +231,7 @@ The order of `card0` and `card1` depends on which driver loads first.2. the same card's render node;3. if the display card has none, the first render node there is (v3d).- The log says `gpu: composición por GPU (V3D 7.1…, render /dev/dri/renderD128, pantalla vc4)`.+ The log says `gpu: GPU composition (V3D 7.1…, render /dev/dri/renderD128, display vc4)`.### Modifiers@@ -242,7 +242,7 @@ The order of `card0` and `card1` depends on which driver loads first.`DRM_CLIENT_CAP_UNIVERSAL_PLANES`) and records the 32-bit RGB format/modifier pairs. The log says:```- kms: placa vc4, XRGB8888 en el plano primario con modificadores: 0x0 …+ kms: card vc4, XRGB8888 on the primary plane with modifiers: 0x0 …```- **Direct scanout** of a fullscreen app (`gpu_can_scanout`) now requires the plane to accept thebuffer's modifier (`kms_scanout_ok`). A v3d UIF buffer isn't sent to the display (before, ADDFB2 was@@ -259,9 +259,9 @@ The order of `card0` and `card1` depends on which driver loads first.1. `grep -E 'kms:|gpu:' ~/.cache/lordos/session.log` (or the session log). It has to show:- the chosen card, with the `vc4` driver;- the plane's modifiers (with `0x0`, linear, present);- - `composición por GPU (V3D 7.1…)`;+ - `GPU composition (V3D 7.1…)`;- `render /dev/dri/renderD128`;- - `cursor por hardware`.+ - `cursor by hardware (cursor plane)`.2. `journalctl -u lordos` shows `lord-sessiond: display: /dev/dri/card1` (or whichever).3. `LORD_GPU_DEBUG=1`:- the list of dmabuf formats EGL announces (it has to include UIF `0x0700000000000006` anddiff --git a/docs/WINDOWS.md b/docs/WINDOWS.mdindex 54bb3f4..5f616de 100644--- a/docs/WINDOWS.md+++ b/docs/WINDOWS.md@@ -144,12 +144,12 @@ Continuous 6 s drag in circles with a virtual tablet (uinput, 125 events/s). lorline per drag to `~/.cache/lordos/session.log`:```-arrastre: 464 cuadros en 6011 ms = 77.2 FPS (464 movimientos); por cuadro: trabajo 12.80 ms (máx 36.83;-JS 0.20, layout 0.56, pintado 11.43, presentar 0.61), intervalo máx 36.9 ms; capa: 1023 pintadas, 467 copiadas (CPU)+drag: 464 frames in 6011 ms = 77.2 FPS (464 moves); per frame: work 12.80 ms (max 36.83;+JS 0.20, layout 0.56, paint 11.43, present 0.61), max gap 36.9 ms; layer: 1023 painted, 467 copied (CPU)```-"trabajo" (work) is what lord-server spends per frame: the pointer and timer JS, layout, painting-("pintado") and presentation ("presentar").+"work" is what lord-server spends per frame: the pointer and timer JS, layout, painting+("paint") and presentation ("present").| Path | Window | Before | After ||---|---|---|---|diff --git a/docs/polish/calendar-after-dark.png b/docs/polish/calendar-after-dark.pngnew file mode 100644index 0000000..8b2b0c2Binary files /dev/null and b/docs/polish/calendar-after-dark.png differdiff --git a/docs/polish/calendar-after-light.png b/docs/polish/calendar-after-light.pngnew file mode 100644index 0000000..baa3719Binary files /dev/null and b/docs/polish/calendar-after-light.png differdiff --git a/docs/polish/calendar-after-rtl.png b/docs/polish/calendar-after-rtl.pngnew file mode 100644index 0000000..d75880dBinary files /dev/null and b/docs/polish/calendar-after-rtl.png differdiff --git a/docs/polish/calendar-after-small.png b/docs/polish/calendar-after-small.pngnew file mode 100644index 0000000..7777e5cBinary files /dev/null and b/docs/polish/calendar-after-small.png differdiff --git a/docs/polish/calendar-before-dark.png b/docs/polish/calendar-before-dark.pngnew file mode 100644index 0000000..43369b7Binary files /dev/null and b/docs/polish/calendar-before-dark.png differdiff --git a/docs/polish/calendar-before-light.png b/docs/polish/calendar-before-light.pngnew file mode 100644index 0000000..8b92103Binary files /dev/null and b/docs/polish/calendar-before-light.png differdiff --git a/docs/polish/calendar-before-rtl.png b/docs/polish/calendar-before-rtl.pngnew file mode 100644index 0000000..499a1f6Binary files /dev/null and b/docs/polish/calendar-before-rtl.png differdiff --git a/docs/polish/calendar-before-small.png b/docs/polish/calendar-before-small.pngnew file mode 100644index 0000000..3eae6f6Binary files /dev/null and b/docs/polish/calendar-before-small.png differdiff --git a/docs/polish/calendar-comparison.png b/docs/polish/calendar-comparison.pngnew file mode 100644index 0000000..774df78Binary files /dev/null and b/docs/polish/calendar-comparison.png differdiff --git a/docs/polish/contacts-after-dark.png b/docs/polish/contacts-after-dark.pngnew file mode 100644index 0000000..388552cBinary files /dev/null and b/docs/polish/contacts-after-dark.png differdiff --git a/docs/polish/contacts-after-light.png b/docs/polish/contacts-after-light.pngnew file mode 100644index 0000000..90ae5d6Binary files /dev/null and b/docs/polish/contacts-after-light.png differdiff --git a/docs/polish/contacts-after-rtl.png b/docs/polish/contacts-after-rtl.pngnew file mode 100644index 0000000..99af396Binary files /dev/null and b/docs/polish/contacts-after-rtl.png differdiff --git a/docs/polish/contacts-after-small.png b/docs/polish/contacts-after-small.pngnew file mode 100644index 0000000..68d6af1Binary files /dev/null and b/docs/polish/contacts-after-small.png differdiff --git a/docs/polish/contacts-before-dark.png b/docs/polish/contacts-before-dark.pngnew file mode 100644index 0000000..0daabb5Binary files /dev/null and b/docs/polish/contacts-before-dark.png differdiff --git a/docs/polish/contacts-before-light.png b/docs/polish/contacts-before-light.pngnew file mode 100644index 0000000..7059883Binary files /dev/null and b/docs/polish/contacts-before-light.png differdiff --git a/docs/polish/contacts-before-rtl.png b/docs/polish/contacts-before-rtl.pngnew file mode 100644index 0000000..6d87f67Binary files /dev/null and b/docs/polish/contacts-before-rtl.png differdiff --git a/docs/polish/contacts-before-small.png b/docs/polish/contacts-before-small.pngnew file mode 100644index 0000000..56b7b1dBinary files /dev/null and b/docs/polish/contacts-before-small.png differdiff --git a/docs/polish/contacts-comparison.png b/docs/polish/contacts-comparison.pngnew file mode 100644index 0000000..ed04fb9Binary files /dev/null and b/docs/polish/contacts-comparison.png differdiff --git a/docs/polish/mail-after-dark.png b/docs/polish/mail-after-dark.pngnew file mode 100644index 0000000..2fd40cdBinary files /dev/null and b/docs/polish/mail-after-dark.png differdiff --git a/docs/polish/mail-after-light.png b/docs/polish/mail-after-light.pngnew file mode 100644index 0000000..f04d3a0Binary files /dev/null and b/docs/polish/mail-after-light.png differdiff --git a/docs/polish/mail-after-rtl.png b/docs/polish/mail-after-rtl.pngnew file mode 100644index 0000000..ed78283Binary files /dev/null and b/docs/polish/mail-after-rtl.png differdiff --git a/docs/polish/mail-after-small.png b/docs/polish/mail-after-small.pngnew file mode 100644index 0000000..5fd9a22Binary files /dev/null and b/docs/polish/mail-after-small.png differdiff --git a/docs/polish/mail-before-dark.png b/docs/polish/mail-before-dark.pngnew file mode 100644index 0000000..331ec05Binary files /dev/null and b/docs/polish/mail-before-dark.png differdiff --git a/docs/polish/mail-before-light.png b/docs/polish/mail-before-light.pngnew file mode 100644index 0000000..7cae306Binary files /dev/null and b/docs/polish/mail-before-light.png differdiff --git a/docs/polish/mail-before-rtl.png b/docs/polish/mail-before-rtl.pngnew file mode 100644index 0000000..713aa8cBinary files /dev/null and b/docs/polish/mail-before-rtl.png differdiff --git a/docs/polish/mail-before-small.png b/docs/polish/mail-before-small.pngnew file mode 100644index 0000000..d9b858eBinary files /dev/null and b/docs/polish/mail-before-small.png differdiff --git a/docs/polish/mail-comparison.png b/docs/polish/mail-comparison.pngnew file mode 100644index 0000000..2804837Binary files /dev/null and b/docs/polish/mail-comparison.png differdiff --git a/docs/polish/reminders-after-dark.png b/docs/polish/reminders-after-dark.pngnew file mode 100644index 0000000..d6500efBinary files /dev/null and b/docs/polish/reminders-after-dark.png differdiff --git a/docs/polish/reminders-after-light.png b/docs/polish/reminders-after-light.pngnew file mode 100644index 0000000..8901fa7Binary files /dev/null and b/docs/polish/reminders-after-light.png differdiff --git a/docs/polish/reminders-after-rtl.png b/docs/polish/reminders-after-rtl.pngnew file mode 100644index 0000000..445fe90Binary files /dev/null and b/docs/polish/reminders-after-rtl.png differdiff --git a/docs/polish/reminders-after-small.png b/docs/polish/reminders-after-small.pngnew file mode 100644index 0000000..b348838Binary files /dev/null and b/docs/polish/reminders-after-small.png differdiff --git a/docs/polish/reminders-before-dark.png b/docs/polish/reminders-before-dark.pngnew file mode 100644index 0000000..77d2afcBinary files /dev/null and b/docs/polish/reminders-before-dark.png differdiff --git a/docs/polish/reminders-before-light.png b/docs/polish/reminders-before-light.pngnew file mode 100644index 0000000..759dbaaBinary files /dev/null and b/docs/polish/reminders-before-light.png differdiff --git a/docs/polish/reminders-before-rtl.png b/docs/polish/reminders-before-rtl.pngnew file mode 100644index 0000000..3c12e1dBinary files /dev/null and b/docs/polish/reminders-before-rtl.png differdiff --git a/docs/polish/reminders-before-small.png b/docs/polish/reminders-before-small.pngnew file mode 100644index 0000000..476b427Binary files /dev/null and b/docs/polish/reminders-before-small.png differdiff --git a/docs/polish/reminders-comparison.png b/docs/polish/reminders-comparison.pngnew file mode 100644index 0000000..4fdd73dBinary files /dev/null and b/docs/polish/reminders-comparison.png differdiff --git a/docs/polish/settings-displays-after-confirm.png b/docs/polish/settings-displays-after-confirm.pngnew file mode 100644index 0000000..df17a3cBinary files /dev/null and b/docs/polish/settings-displays-after-confirm.png differdiff --git a/docs/polish/settings-displays-after-dark.png b/docs/polish/settings-displays-after-dark.pngnew file mode 100644index 0000000..3c1694bBinary files /dev/null and b/docs/polish/settings-displays-after-dark.png differdiff --git a/docs/polish/settings-displays-after-light.png b/docs/polish/settings-displays-after-light.pngnew file mode 100644index 0000000..107d571Binary files /dev/null and b/docs/polish/settings-displays-after-light.png differdiff --git a/docs/polish/settings-displays-after-rtl.png b/docs/polish/settings-displays-after-rtl.pngnew file mode 100644index 0000000..6d3af95Binary files /dev/null and b/docs/polish/settings-displays-after-rtl.png differdiff --git a/docs/polish/settings-displays-after-small.png b/docs/polish/settings-displays-after-small.pngnew file mode 100644index 0000000..206989aBinary files /dev/null and b/docs/polish/settings-displays-after-small.png differdiff --git a/docs/polish/settings-displays-after-two.png b/docs/polish/settings-displays-after-two.pngnew file mode 100644index 0000000..06598e3Binary files /dev/null and b/docs/polish/settings-displays-after-two.png differdiff --git a/docs/polish/settings-displays-before-confirm.png b/docs/polish/settings-displays-before-confirm.pngnew file mode 100644index 0000000..7f32f27Binary files /dev/null and b/docs/polish/settings-displays-before-confirm.png differdiff --git a/docs/polish/settings-displays-before-dark.png b/docs/polish/settings-displays-before-dark.pngnew file mode 100644index 0000000..559d926Binary files /dev/null and b/docs/polish/settings-displays-before-dark.png differdiff --git a/docs/polish/settings-displays-before-light.png b/docs/polish/settings-displays-before-light.pngnew file mode 100644index 0000000..bfdd822Binary files /dev/null and b/docs/polish/settings-displays-before-light.png differdiff --git a/docs/polish/settings-displays-before-rtl.png b/docs/polish/settings-displays-before-rtl.pngnew file mode 100644index 0000000..d847315Binary files /dev/null and b/docs/polish/settings-displays-before-rtl.png differdiff --git a/docs/polish/settings-displays-before-small.png b/docs/polish/settings-displays-before-small.pngnew file mode 100644index 0000000..1fa8590Binary files /dev/null and b/docs/polish/settings-displays-before-small.png differdiff --git a/docs/polish/settings-displays-comparison.png b/docs/polish/settings-displays-comparison.pngnew file mode 100644index 0000000..8dd8b0cBinary files /dev/null and b/docs/polish/settings-displays-comparison.png differdiff --git a/runtime/style.js b/runtime/style.jsindex b4a497a..8c9e7ed 100644--- a/runtime/style.js+++ b/runtime/style.js@@ -74,12 +74,53 @@ function gradient(v) {return [angle, stop(parts[0]), stop(parts[parts.length - 1])];}-const COLOR_KEYS = new Set(['backgroundColor', 'borderColor', 'color', 'shadowColor']);+const SIDES = ['Left', 'Top', 'Right', 'Bottom', 'Start', 'End'];+const COLOR_KEYS = new Set(['backgroundColor', 'borderColor', 'color', 'shadowColor', ...SIDES.map((s) => `border${s}Color`)]);const DIM_KEYS = new Set(['width', 'height', 'minWidth', 'minHeight', 'maxWidth', 'maxHeight',- 'left', 'top', 'right', 'bottom', 'flexBasis']);+ 'left', 'top', 'right', 'bottom', 'flexBasis', 'start', 'end']);+// CSS logical names → the engine's (React Native) names+const ALIASES = {+ marginInlineStart: 'marginStart', marginInlineEnd: 'marginEnd',+ paddingInlineStart: 'paddingStart', paddingInlineEnd: 'paddingEnd',+ insetInlineStart: 'start', insetInlineEnd: 'end',+ borderInlineStartWidth: 'borderStartWidth', borderInlineEndWidth: 'borderEndWidth',+ borderInlineStartColor: 'borderStartColor', borderInlineEndColor: 'borderEndColor',+ borderStartStartRadius: 'borderTopStartRadius', borderStartEndRadius: 'borderTopEndRadius',+ borderEndStartRadius: 'borderBottomStartRadius', borderEndEndRadius: 'borderBottomEndRadius',+ lineClamp: 'numberOfLines', WebkitLineClamp: 'numberOfLines',+};++// "1px solid #ccc" → [width, color]; "none" → [0, transparent]+function borderParts(v) {+ if (typeof v === 'number') return [v, null];+ if (v === 'none' || v === 0) return [0, 0];+ const p = tokens(v);+ const w = p.find((t) => /^-?[\d.]/.test(t));+ const c = p.find((t) => !/^-?[\d.]/.test(t) && !/^(solid|dashed|dotted|double|none)$/.test(t));+ return [w !== undefined ? num(w) : 1, c !== undefined ? color(c) : null];+}++function angle(v) {+ if (typeof v === 'number') return v;+ const s = String(v).trim(), n = parseFloat(s) || 0;+ if (s.endsWith('rad')) return n * 180 / Math.PI;+ if (s.endsWith('turn')) return n * 360;+ return n; // deg (default)+}++const ORIGIN_WORDS = { left: '0%', top: '0%', center: '50%', right: '100%', bottom: '100%' };+function origin(v, out) {+ const p = Array.isArray(v) ? v : tokens(String(v));+ let x = p[0] ?? '50%', y = p[1] ?? '50%';+ if (p.length === 1 && (x === 'top' || x === 'bottom')) { y = x; x = '50%'; }+ if (x === 'top' || x === 'bottom' || y === 'left' || y === 'right') [x, y] = [y, x];+ out.transformOriginX = dim(ORIGIN_WORDS[x] ?? x);+ out.transformOriginY = dim(ORIGIN_WORDS[y] ?? y);+}const WEIGHTS = { normal: 400, medium: 500, semibold: 600, bold: 700 };function expand(k, v, out) {+ if (k in ALIASES) k = ALIASES[k];switch (k) {case 'margin': case 'padding': {const [t, r, b, l] = box(v);@@ -101,8 +142,38 @@ function expand(k, v, out) {out.top = t; out.right = r; out.bottom = b; out.left = l;return;}- case 'flex':- out.flexGrow = num(v); out.flexShrink = 1; out.flexBasis = 0;+ case 'marginInline': case 'paddingInline': {+ const base = k.replace('Inline', ''), p = tokens(String(v)).map(num);+ out[base + 'Start'] = p[0] || 0; out[base + 'End'] = p.length > 1 ? p[1] : p[0] || 0;+ return;+ }+ case 'insetInline': {+ const p = tokens(String(v)).map(dim);+ out.start = p[0]; out.end = p.length > 1 ? p[1] : p[0];+ return;+ }+ case 'flex': {+ // React Native: flex > 0 grows and shrinks from a zero basis; flex: 0 is sized by its+ // width/height and inflexible; flex < 0 only shrinks (down to minWidth/minHeight)+ const f = num(v);+ if (f > 0) { out.flexGrow = f; out.flexShrink = 1; out.flexBasis = 0; }+ else if (f === 0) { out.flexGrow = 0; out.flexShrink = 0; out.flexBasis = 'auto'; }+ else { out.flexGrow = 0; out.flexShrink = -f; out.flexBasis = 'auto'; }+ return;+ }+ case 'borderTop': case 'borderRight': case 'borderBottom': case 'borderLeft':+ case 'borderStart': case 'borderEnd': case 'borderInlineStart': case 'borderInlineEnd': {+ const side = k.replace('Inline', '');+ const [w, c] = borderParts(v);+ out[side + 'Width'] = w;+ if (c !== null) out[side + 'Color'] = c;+ return;+ }+ case 'textOverflow':+ out.textOverflow = v === 'ellipsis' ? 'ellipsis' : 'clip';+ return;+ case 'transformOrigin':+ origin(v, out);return;case 'border': {const p = tokens(v);@@ -130,14 +201,31 @@ function expand(k, v, out) {return;}case 'transform': {+ // translate moves the box (and what layout reports); scale and rotate only paint (as in CSS)const list = Array.isArray(v) ? v : [];for (const t of list) {if ('translateX' in t) out.translateX = num(t.translateX);if ('translateY' in t) out.translateY = num(t.translateY);+ if ('scale' in t) out.scaleX = out.scaleY = num(t.scale);+ if ('scaleX' in t) out.scaleX = num(t.scaleX);+ if ('scaleY' in t) out.scaleY = num(t.scaleY);+ if ('rotate' in t) out.rotate = angle(t.rotate);+ if ('rotateZ' in t) out.rotate = angle(t.rotateZ);}- if (typeof v === 'string') {- const m = v.match(/translate\(\s*([-\d.]+)px?\s*,\s*([-\d.]+)/);- if (m) { out.translateX = +m[1]; out.translateY = +m[2]; }+ if (typeof v === 'string' && v !== 'none') {+ for (const m of v.matchAll(/(\w+)\(([^)]*)\)/g)) {+ const a = m[2].split(/[\s,]+/).filter(Boolean);+ switch (m[1]) {+ case 'translate': out.translateX = num(a[0]); out.translateY = num(a[1] ?? 0); break;+ case 'translateX': out.translateX = num(a[0]); break;+ case 'translateY': out.translateY = num(a[0]); break;+ case 'scale': out.scaleX = num(a[0]); out.scaleY = num(a[1] ?? a[0]); break;+ case 'scaleX': out.scaleX = num(a[0]); break;+ case 'scaleY': out.scaleY = num(a[0]); break;+ case 'rotate': case 'rotateZ': out.rotate = angle(a[0]); break;+ default: break;+ }+ }}return;}diff --git a/sdk/admin.js b/sdk/admin.jsindex 6572db4..d2b4a44 100644--- a/sdk/admin.js+++ b/sdk/admin.js@@ -5,7 +5,12 @@//// await admin.run('locale-gen', 'pt_BR.UTF-8', (line) => showProgress(line))// const off = admin.onEvent((text) => ...) // unsolicited notices: "net link eth0 up"...+//+// An ERR reply is a code line (server/src/errcode.h): the promise rejects with an Error whose+// message is already translated (t('errors.<code>')) and that carries .code and .params. OK and+// LOG texts arrive as sent; show a status code line with statusText() (sdk/errors.js).import { createStore } from './store.js';+import { codeError } from './errors.js';const pending = new Map(); // id → { action, arg, onLog, resolve, reject }const eventListeners = new Set();@@ -32,7 +37,7 @@ globalThis.__lordAdmin = (id, kind, text) => {}pending.delete(id);refreshBusy();- if (kind === 'OK') p.resolve(text); else p.reject(new Error(text));+ if (kind === 'OK') p.resolve(text); else p.reject(codeError(text));};export const admin = {@@ -41,7 +46,7 @@ export const admin = {run(action, arg = '', onLog, { quiet = false } = {}) {return new Promise((resolve, reject) => {const id = lord.admin.request(action, String(arg));- if (!id) { reject(new Error('the administration helper is not available')); return; }+ if (!id) { reject(codeError('admin.unavailable')); return; }pending.set(id, { action, arg: quiet ? '' : arg, onLog, resolve, reject, quiet, log: [] }); // quiet: may carry a passwordif (!quiet) refreshBusy();});diff --git a/sdk/backup.js b/sdk/backup.jsindex 536112f..e30eb44 100644--- a/sdk/backup.js+++ b/sdk/backup.js@@ -13,6 +13,7 @@import { createStore, useStore } from './store.js';import { notify } from './notify.js';import { t } from './i18n.js';+import { errorText } from './errors.js';import { formatBytes } from './system.js';import { wm } from './windows.js';@@ -32,7 +33,7 @@ function changed(prev, st) {notify({ app: 'backup', title: t('backup.notify.doneTitle'),body: t('backup.notify.doneBody', { count: st.last.files, size: formatBytes(st.last.bytes) }), actions: open, sound: false });} else if (st.last.ok === 0) {- notify({ app: 'backup', title: t('backup.notify.failTitle'), body: st.last.error || '', actions: open });+ notify({ app: 'backup', title: t('backup.notify.failTitle'), body: errorText(st.last.error) || '', actions: open });}asked = false;}diff --git a/sdk/controls.jsx b/sdk/controls.jsxindex 7df594c..6cde689 100644--- a/sdk/controls.jsx+++ b/sdk/controls.jsx@@ -45,7 +45,8 @@ function TooltipBubble({ text, end, top }) {);}-// Toolbar item: an icon (a glyph) and/or a short label, borderless until hovered.+// Toolbar item: an icon (a glyph, or an element such as a drawn shape) and/or a short label,+// borderless until hovered.// title: tooltip text (required for icon-only buttons). active: a toggled-on state.export function ToolbarButton({ icon, label, title, onClick, active, disabled, small, iconSize, color, style }) {const t = useTheme();@@ -61,7 +62,9 @@ export function ToolbarButton({ icon, label, title, onClick, active, disabled, sstyle={[{ height: h, minWidth: h, paddingHorizontal: label ? 8 : 0, borderRadius: controlSize.radiusSmall, flexDirection: 'row', gap: 6,alignItems: 'center', justifyContent: 'center', opacity: disabled ? 0.45 : 1, zIndex: tip ? 1000 : 0,backgroundColor: active ? (t.mode === 'dark' ? 'rgba(255,255,255,0.12)' : 'rgba(0,0,0,0.08)') : hover && !disabled ? t.hover : 'transparent' }, style]}>- {icon != null ? <Text style={{ fontSize: iconSize || (small ? 13 : 15), color: fg, textAlign: 'center' }}>{icon}</Text> : null}+ {icon == null ? null : typeof icon === 'string' || typeof icon === 'number'+ ? <Text style={{ fontSize: iconSize || (small ? 13 : 15), color: fg, textAlign: 'center' }}>{icon}</Text>+ : icon /* an element: a drawn glyph */}{label ? <Text style={{ fontSize: small ? 12 : 13, fontWeight: 500, color: fg, whiteSpace: 'nowrap' }}>{label}</Text> : null}{tip && title ? <TooltipBubble text={title} end={nearEnd(winId, ref.current)} top={h + 6} /> : null}</View>diff --git a/sdk/doc.js b/sdk/doc.jsindex 282c2fe..7b07148 100644--- a/sdk/doc.js+++ b/sdk/doc.js@@ -12,6 +12,11 @@import { createElement as h, useEffect, useRef } from 'react';import { Image } from '@lordos/runtime';import { settings } from './settings.js';+import { tOptional } from './i18n.js';+import { errorText } from './errors.js';++// lord-doc reports short codes ('corrupt', 'password'…): the message is their translation (docs.err.*).+const docError = (code, extra = {}) => Object.assign(new Error(code ? tOptional(`docs.err.${code}`) ?? errorText(code) : errorText('sys.unknown')), { code, ...extra });const has = () => typeof lord !== 'undefined' && typeof lord.doc !== 'undefined';export const docAvailable = () => has() && lord.doc.available();@@ -36,7 +41,7 @@ function dispatch(e) {if (e.type === 'part') { w.onPart?.(e.data); return; }if (e.type === 'prog') { w.onProgress?.(e.data); return; }waiting.delete(k);- if (e.type === 'err') { const err = new Error(e.data?.error || 'error'); err.code = e.data?.error; err.detail = e.data?.detail; err.data = e.data; w.reject(err); return; }+ if (e.type === 'err') { w.reject(docError(e.data?.error, { detail: e.data?.detail, data: e.data })); return; }if (e.type === 'img') w.resolve({ image: e.image, w: e.w, h: e.h, data: e.data || {} });else if (e.type === 'blob') w.resolve({ blob: e.blob, size: e.size });else w.resolve(e.data || {});@@ -58,7 +63,7 @@ export function onSessionCrash(sid, fn) {// Waits for the result of a request already made ({ sid, req } or both numbers).export function waitFor(sid, req, { onPart, onProgress } = {}) {- if (req == null || req < 0) return Promise.reject(Object.assign(new Error('unavailable'), { code: 'unavailable' }));+ if (req == null || req < 0) return Promise.reject(docError('unavailable'));return new Promise((resolve, reject) => {waiting.set(`${sid}:${req}`, { resolve, reject, onPart, onProgress });if (!timer) timer = setInterval(pump, 8);@@ -69,7 +74,7 @@ export function cancelRequest(sid, req) {if (lord.doc.cancel(sid, req)) {const w = waiting.get(`${sid}:${req}`);waiting.delete(`${sid}:${req}`);- w?.reject(Object.assign(new Error('cancelled'), { code: 'cancelled' }));+ w?.reject(docError('cancelled'));}}diff --git a/sdk/emoji.jsx b/sdk/emoji.jsxindex 3dbf590..3b3ca46 100644--- a/sdk/emoji.jsx+++ b/sdk/emoji.jsx@@ -54,7 +54,7 @@ function buildIndex() {return index;}-const uiLang = () => String(locale.get().lang || 'es').split(/[-_]/)[0];+const uiLang = () => String(locale.get().lang || 'en').split(/[-_]/)[0];export const emoji = {groups,diff --git a/sdk/errors.js b/sdk/errors.jsnew file mode 100644index 0000000..90cce34--- /dev/null+++ b/sdk/errors.js@@ -0,0 +1,68 @@+// errors.js — translated error and status messages from stable codes.+//+// The server never sends prose to the UI: an error is a *code line* (server/src/errcode.h),+// "pkg.removeEssential name=dpkg"+// that is shown with t('errors.pkg.removeEssential', { name: 'dpkg' }).+//+// errorText(e) Error, code line or { code, params } → text in the user's language+// statusText(line) same for OK/LOG statuses (t('status.<code>'))+// codeError(line) new Error(errorText(line)) with .code and .params+// parseCode(line) { code, params } or null+//+// Text that is not a code line, or a code without a translation, is shown as is (the output of a+// program, an older server). Two parameters are special: `errno` (ENOENT…) becomes its+// translated description (errors.errno.ENOENT) and `reason` is a nested code line.+// Errors thrown by lord.* (server/src/ui/js_err.h) already carry a translated message, `code`+// and `params`, through globalThis.__lordErrorText.+import { tOptional } from './i18n.js';++const CODE_RE = /^([a-z][a-zA-Z0-9]*(?:\.[a-zA-Z0-9]+)+)(?= |$)/;++const decode = (v) => { try { return decodeURIComponent(v); } catch (e) { return v; } };++export function parseCode(line) {+ if (typeof line !== 'string') return null;+ const m = CODE_RE.exec(line);+ if (!m) return null;+ const params = {};+ for (const part of line.slice(m[1].length).split(' ')) {+ const eq = part.indexOf('=');+ if (eq > 0) params[part.slice(0, eq)] = decode(part.slice(eq + 1));+ }+ return { code: m[1], params };+}++function translate(ns, code, params = {}) {+ const p = { ...params };+ if (p.errno) p.errno = tOptional(`errors.errno.${p.errno}`) ?? p.errno;+ if (p.reason) p.reason = errorText(p.reason);+ return tOptional(`${ns}.${code}`, p);+}++function textOf(ns, x) {+ if (x == null) return '';+ if (typeof x === 'object') {+ if (x.code) {+ const s = translate(ns, x.code, x.params);+ if (s != null) return s;+ }+ if (x.message != null) return textOf(ns, String(x.message));+ return String(x);+ }+ const line = String(x);+ const p = parseCode(line);+ return (p && translate(ns, p.code, p.params)) ?? line;+}++export const errorText = (x) => textOf('errors', x);+export const statusText = (x) => textOf('status', x);++export function codeError(line) {+ const p = parseCode(String(line ?? ''));+ const e = new Error(errorText(line));+ if (p) { e.code = p.code; e.params = p.params; }+ return e;+}++// For lord.* exceptions (js_err.h): the message in the user's language, or null to keep the line.+globalThis.__lordErrorText = (code, params) => translate('errors', code, params || {}) ?? null;diff --git a/sdk/hardware.jsx b/sdk/hardware.jsxindex e92cd98..657cf6a 100644--- a/sdk/hardware.jsx+++ b/sdk/hardware.jsx@@ -207,20 +207,25 @@ function useSystemTokens() {separator: 'rgba(0,0,0,0.12)', control: '#e2e2e7' } : th;}+// The "Keep these display settings?" alert, drawn like a macOS alert: a 260 px panel with the icon on+// top, a 13/700 title, an 11 px body with the countdown and two equal buttons (the default one in the+// accent color).export function DisplayConfirm() {const c = useStore(displayConfirm);const th = useSystemTokens();if (!c) return null;+ const dark = th.mode !== 'light';return h(View, { style: { position: 'absolute', ...mainBox(), alignItems: 'center', justifyContent: 'center',- backgroundColor: 'rgba(0,0,0,0.25)', zIndex: 100001 } },- h(View, { style: { width: 340, borderRadius: 14, padding: 22, gap: 10, alignItems: 'center', backgroundColor: th.windowBg,- border: `1px solid ${th.separator}`, boxShadow: '0 20px 60px rgba(0,0,0,0.45)' } },- h(DisplayGlyph, { size: 48, color: th.accent }),- h(Text, { style: { fontSize: 14, fontWeight: 700, color: th.text, textAlign: 'center' } }, t('prefs.display.keepTitle')),- h(Text, { style: { fontSize: 12, color: th.textDim, textAlign: 'center', lineHeight: 1.4 } }, t('prefs.display.keepBody', { count: c.left })),- h(View, { style: { flexDirection: 'row', gap: 10, marginTop: 8, alignSelf: 'stretch' } },- h(DialogButton, { label: t('prefs.display.revert'), onClick: revertDisplay, th }),- h(DialogButton, { label: t('prefs.display.keep'), onClick: keepDisplay, primary: true, th }))));+ backgroundColor: 'rgba(0,0,0,0.12)', zIndex: 100001 } },+ h(View, { style: { width: 260, borderRadius: 12, paddingTop: 20, paddingHorizontal: 16, paddingBottom: 16, alignItems: 'center',+ backgroundColor: dark ? '#2b2b2f' : '#ececee', border: `1px solid ${dark ? 'rgba(255,255,255,0.12)' : 'rgba(0,0,0,0.1)'}`,+ boxShadow: '0 18px 50px rgba(0,0,0,0.4)' } },+ h(DisplayGlyph, { size: 56, color: th.accent }),+ h(Text, { style: { width: 228, marginTop: 10, fontSize: 13, fontWeight: 700, color: th.text, textAlign: 'center', lineHeight: 1.3 } }, t('prefs.display.keepTitle')),+ h(Text, { style: { width: 228, marginTop: 6, fontSize: 11, color: th.text, opacity: 0.8, textAlign: 'center', lineHeight: 1.4 } }, t('prefs.display.keepBody', { count: c.left })),+ h(View, { style: { flexDirection: 'row', gap: 8, marginTop: 16, alignSelf: 'stretch' } },+ h(DialogButton, { label: t('prefs.display.revert'), onClick: revertDisplay, th, dark }),+ h(DialogButton, { label: t('prefs.display.keep'), onClick: keepDisplay, primary: true, th, dark }))));}export function DisplayGlyph({ size = 40, color = '#0a84ff' }) {@@ -231,12 +236,13 @@ export function DisplayGlyph({ size = 40, color = '#0a84ff' }) {h(View, { style: { width: size * 0.42, height: Math.max(2, size / 18), borderRadius: 2, backgroundColor: color } }));}-function DialogButton({ label, onClick, primary, th }) {+function DialogButton({ label, onClick, primary, th, dark = th.mode !== 'light' }) {const [hover, setHover] = useState(false);return h(View, { onClick, onMouseEnter: () => setHover(true), onMouseLeave: () => setHover(false),- style: { flex: 1, height: 30, borderRadius: 8, alignItems: 'center', justifyContent: 'center',- backgroundColor: primary ? th.accent : th.control, opacity: hover ? 0.85 : 1 } },- h(Text, { style: { fontSize: 13, fontWeight: 600, color: primary ? '#fff' : th.text } }, label));+ style: { flex: 1, height: 28, borderRadius: 7, alignItems: 'center', justifyContent: 'center',+ backgroundColor: primary ? th.accent : dark ? 'rgba(255,255,255,0.14)' : '#ffffff',+ boxShadow: primary ? 'none' : '0 0.5px 1.5px rgba(0,0,0,0.25)', opacity: hover ? 0.88 : 1 } },+ h(Text, { style: { fontSize: 13, fontWeight: 500, color: primary ? '#fff' : th.text } }, label));}// ---- idle: screen off, lock, sleep ----diff --git a/sdk/i18n.js b/sdk/i18n.jsindex 137ded7..91cd142 100644--- a/sdk/i18n.js+++ b/sdk/i18n.js@@ -81,7 +81,8 @@ function meta(lang) {return metas.get(lang) || {};}-// Initial language: the one chosen in Settings, or the one from the user's region (LANG=pt_BR.UTF-8 → pt).+// Initial language: the one chosen in Settings, or the one from the user's region (LANG=pt_BR.UTF-8 → pt),+// or English (FALLBACK). A saved choice always wins.function initial() {const s = settings.get().language;if (s) return s;@@ -90,7 +91,7 @@ function initial() {const lang = (l.user.LANG || l.system.LANG || '').split(/[_.@]/)[0];if (lang && lang !== 'C' && lord.locale.catalog(lang, 'shell')) return lang;} catch (e) { /* no region */ }- return 'es';+ return FALLBACK;}export const locale = createStore({ lang: initial(), region: settings.get().region || '' });@@ -148,8 +149,9 @@ export function tOptional(key, vars) {return v === undefined ? null : t(key, vars);}-// Name of an app (manifest.json → apps.<id> in the catalog, if it exists).-export const appName = (app) => (app ? (lookup(locale.get().lang, `apps.${app.id}`) ?? app.name) : '');+// Name of an app: apps.<id> in the catalog (the user's language, then English), else manifest.json's+// name (English).+export const appName = (app) => (app ? (lookup(locale.get().lang, `apps.${app.id}`) ?? lookup(FALLBACK, `apps.${app.id}`) ?? app.name) : '');// ---- formats (date, time, numbers) ----diff --git a/sdk/index.js b/sdk/index.jsindex 0b8f8fe..36c3b8f 100644--- a/sdk/index.js+++ b/sdk/index.js@@ -34,6 +34,7 @@ export { emoji, Grid as EmojiGrid, ToneBar as EmojiToneBar } from './emoji.jsx';import { PrintDialog } from './printdialog.jsx';import { EmojiPanel } from './emoji.jsx';export { admin } from './admin.js';+export { errorText, statusText, codeError, parseCode } from './errors.js';export { logs } from './logs.js';export { LordOSLogo } from './logo.js';export { DesktopWidgets, registerWidgetType, setWidgets, desktopWidgets } from './widgets.js';diff --git a/sdk/mail.js b/sdk/mail.jsindex 656fa48..35eec86 100644--- a/sdk/mail.js+++ b/sdk/mail.js@@ -93,7 +93,7 @@ async function passwordFor(acct) {catch (e) { return null; }}-const slug = (s) => String(s).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 24) || 'cuenta';+const slug = (s) => String(s).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 24) || 'account';export const mailAccounts = {list: () => mailConfig.get().accounts,diff --git a/sdk/media.js b/sdk/media.jsindex 653b472..f9f582b 100644--- a/sdk/media.js+++ b/sdk/media.js@@ -8,6 +8,9 @@// const p = usePlayer(id); // { info, pos, duration, playing, state, subs, stats }// media.control(id, 'seek', 30000)//+// Errors (the `error` of a job result and of a player's state) are code lines such as+// "media.notAnImage": show them with errorText() (sdk/errors.js). 'crash' means lord-media died.+//// Camera, microphone and screen ask for permission (requestPermission, the system prompt) and the// server checks it again. While in use, the menu bar indicators light up.import { createElement as h, useEffect, useState } from 'react';@@ -39,7 +42,7 @@ function job(fn) {return new Promise((resolve) => {let id = 0;try { id = fn(); } catch (e) { resolve({ ok: false, error: e?.message || String(e) }); return; }- if (!id) { resolve({ ok: false, error: 'sin lord-media' }); return; }+ if (!id) { resolve({ ok: false, error: 'media.noHelper' }); return; }pending.set(id, resolve);});}diff --git a/sdk/print.js b/sdk/print.jsindex 2e0b80e..752a507 100644--- a/sdk/print.js+++ b/sdk/print.js@@ -15,6 +15,11 @@// scanCaps(scanner), scan(scanner, settings) → { file, format, bytes }// submit(printer, blob | pdfPath, options) → { job }import { createStore } from './store.js';+import { tOptional } from './i18n.js';+import { errorText } from './errors.js';++// lord.print reports short codes ('no-cups', 'unreachable'…): the message is their translation (print.err.*).+const printError = (code, detail) => Object.assign(new Error(code ? tOptional(`print.err.${code}`, { detail: detail || '' }) ?? errorText(code) : errorText('sys.unknown')), { code, detail });const has = () => typeof lord !== 'undefined' && typeof lord.print !== 'undefined';const waiting = new Map();@@ -28,13 +33,13 @@ function pump() {if (!w) continue;waiting.delete(e.id);if (e.ok) w.resolve(e.data);- else { const err = new Error(e.data?.error || 'error'); err.code = e.data?.error; err.detail = e.data?.detail; w.reject(err); }+ else w.reject(printError(e.data?.error, e.data?.detail));}if (!waiting.size && timer) { clearInterval(timer); timer = null; }}function wait(id) {- if (!(id > 0)) return Promise.reject(Object.assign(new Error('busy'), { code: 'busy' }));+ if (!(id > 0)) return Promise.reject(printError('busy'));return new Promise((resolve, reject) => {waiting.set(id, { resolve, reject });if (!timer) timer = setInterval(pump, 50);diff --git a/sdk/printdialog.jsx b/sdk/printdialog.jsxindex d23be48..e9e277a 100644--- a/sdk/printdialog.jsx+++ b/sdk/printdialog.jsx@@ -155,7 +155,7 @@ function Dialog({ req }) {finish({ job: r.job, printer: dest });} catch (e) {setBusy(false);- setError(e.code === 'bad-pages' ? t('print.badPages') : t('print.failed', { error: e.detail || e.code || e.message }));+ setError(e.code === 'bad-pages' ? t('print.badPages') : t('print.failed', { error: e.message }));}}diff --git a/sdk/theme.js b/sdk/theme.jsindex bcf3e4d..6a67473 100644--- a/sdk/theme.js+++ b/sdk/theme.js@@ -16,7 +16,7 @@ export const DEFAULT_TOKENS = {control: '#3a3a40',inputBg: '#2c2c31',radius: 8,- wallpapers: [],+ wallpapers: [], // [{ id, nameKey (locale key), name (English fallback), src }]};const ThemeContext = createContext(DEFAULT_TOKENS);diff --git a/sdk/vault.js b/sdk/vault.jsindex 2bac53f..8848510 100644--- a/sdk/vault.js+++ b/sdk/vault.js@@ -1,14 +1,14 @@-// vault.js — Contraseñas y el llavero del sistema: habla con lord.vault (el ayudante encerrado-// lord-vault, ver docs/CONTRASENAS.md). Todo es asincrónico: los pedidos devuelven promesas y un-// temporizador lee las respuestas (lord.vault.poll); el escritorio nunca espera.+// vault.js — Passwords and the system keyring: talks to lord.vault (the confined helper+// lord-vault, see docs/PASSWORDS.md). Everything is asynchronous: requests return promises and a+// timer reads the replies (lord.vault.poll); the desktop never waits.//-// vaultAvailable() ¿está lord-vault?-// vaultRequest(op, args, { files }) → promesa con la respuesta ({ ok, … }) o error con .code-// onVaultEvent(fn) eventos: locked, unlocked, changed, touch, ss-prompt, keyring-mismatch, crash+// vaultAvailable() is lord-vault there?+// vaultRequest(op, args, { files }) → promise with the reply ({ ok, … }) or an error with .code+// onVaultEvent(fn) events: locked, unlocked, changed, touch, ss-prompt, keyring-mismatch, crash// keyring.set(app, { service, account, secret, label }) / get(app, { service, account }) / remove / list-// el llavero de la sesión, por app: una app ve solo lo suyo (salvo que el usuario lo comparta)-// autofill(app, { url | service }) → [{ id, title, username }] de Contraseñas (si está abierta)-// <KeyringPrompt /> aviso del sistema para abrir el llavero (lo monta startShell)+// the session keyring, per app: an app only sees its own items (unless the user shares them)+// autofill(app, { url | service }) → [{ id, title, username }] from Passwords (if it is unlocked)+// <KeyringPrompt /> system prompt to unlock the keyring (mounted by startShell)// <AutofillButton app service|url|ssid onFill /> "fill from Passwords" next to a login fieldimport { createElement as h, useEffect, useState } from 'react';import { View, Text, mainBox } from '@lordos/runtime';@@ -49,7 +49,7 @@ function pump() {if (!waiting.size && fast) { clearInterval(fast); fast = null; }}-// Los eventos (bloqueo automático, avisos de Secret Service) llegan aunque nadie espere nada.+// Events (auto-lock, Secret Service notices) arrive even when nobody is waiting for anything.function startSlow() { if (!slow && has()) slow = setInterval(pump, 600); }export function vaultRequest(op, args = {}, { files, fds } = {}) {@@ -57,7 +57,8 @@ export function vaultRequest(op, args = {}, { files, fds } = {}) {let id;// files: paths opened by lord-server (shell); fds: files picked in the system dialog (app process)try { id = lord.vault.request(JSON.stringify({ op, ...args }), files || fds ? { files, fds } : undefined); }- catch (e) { return Promise.reject(Object.assign(new Error(e.message), { code: 'file' })); }+ // lord.vault.request throws translated errors with a code (server/src/ui/js_err.h)+ catch (e) { return Promise.reject(Object.assign(new Error(e.message), { code: e.code === 'vault.unavailable' ? 'unavailable' : 'file' })); }startSlow();return new Promise((resolve, reject) => {waiting.set(id, { resolve, reject });@@ -71,7 +72,7 @@ export function onVaultEvent(fn) {return () => listeners.delete(fn);}-// ---- llavero de la sesión, por app ----+// ---- the session keyring, per app ----export const keyring = {set: (app, { service, account = '', secret, label = '' }) => vaultRequest('kr-set', { owner: app, service, account, secret: String(secret ?? ''), label }),@@ -81,11 +82,11 @@ export const keyring = {},remove: (app, { service, account = '' }) => vaultRequest('kr-del', { owner: app, service, account }),list: async (app) => (await vaultRequest('kr-list', { owner: app })).items || [],- // el usuario aceptó que `app` use un ítem de otra app (lo pregunta el sistema, no la app)+ // the user agreed that `app` may use another app's item (the system asks, not the app)share: (id, app, allow = true) => vaultRequest('kr-share', { admin: true, id, app, allow }),};-// ---- autocompletar en los campos de inicio de sesión de las apps nativas ----+// ---- autofill in the login fields of native apps ----const hostOf = (u) => String(u || '').replace(/^[a-z]+:\/\//i, '').split(/[/:?#]/)[0].toLowerCase().replace(/^www\./, '');@@ -101,14 +102,14 @@ export async function autofill(app, { url, service, ssid } = {}) {return list.filter((e) => !e.trash && hit(e)).map((e) => ({ id: e.id, title: e.title, username: e.sub || '' }));}-// El usuario eligió una: usuario y contraseña (la contraseña sale de lord-vault solo ahora).+// The user picked one: username and password (the password leaves lord-vault only now).export async function autofillReveal(id) {const e = (await vaultRequest('get', { id, reveal: true })).entry;const f = (k) => e.f.find((x) => x.k === k)?.v || '';return { username: f('username') || f('email'), password: f('password') };}-// ---- aviso del sistema: abrir el llavero (Secret Service lo pidió) ----+// ---- system prompt: unlock the keyring (Secret Service asked for it) ----const prompts = createStore([]); // [{ prompt }]if (has()) {diff --git a/server/Makefile b/server/Makefileindex 4abf3a8..005a31f 100644--- a/server/Makefile+++ b/server/Makefile@@ -55,7 +55,7 @@ SEC_SRC := src/sec/json.c src/sec/sign.c src/sec/pkgstate.c src/sec/perms.c src/# App mode: lord-server --app <id> runs an .lpk app as an isolated Wayland client (src/app)APP_SRC := src/app/appclient.c src/app/appspawn.c src/ui/js_broker.c src/ui/js_brokercam.cSRC := src/main.c src/kms.c src/gpu/gpu.c src/input.c src/canvas.c src/admin.c src/install/install.c src/apps.c src/lpk.c src/fsops.c src/remote/mirror.c src/remote/remote_admin.c src/users/users_admin.c src/users/homedirs.c src/keyboard.c src/ime.c src/wl/wl.c \- src/ui/node.c src/ui/style.c src/ui/layout.c src/ui/text.c src/ui/image.c \+ src/ui/node.c src/ui/style.c src/ui/layout.c src/ui/transform.c src/ui/text.c src/ui/image.c \src/ui/paint.c src/ui/js.c src/ui/js_sys.c src/ui/js_term.c src/ui/js_wasm.c src/wasm/wasm.c src/wasm/wasm_run.c src/ui/js_sound.c src/ui/js_net.c src/sound/snd.c src/sound/pulse.c src/ui/otf.c src/ui/fonts.c \src/ui/unicode.c src/ui/bidi.c src/ui/shape.c src/ui/shape_indic.c src/ui/shape_syl.c src/ui/shape_khmer.c src/ui/shape_myanmar.c src/ui/shape_use.c src/ui/thbrk.c src/ui/textlayout.c \src/term/vt.c src/term/pty.c src/term/term.c src/term/term_paint.c src/term/hold.c \@@ -223,6 +223,16 @@ build/mmdb-test: tests/mmdb_test.c src/monitor/mmdb.c src/monitor/mmdb.h src/pkgbuild/map-bench: tests/map_bench.c src/monitor/map.c src/monitor/map.h src/monitor/mon.c src/monitor/conn.c src/monitor/mmdb.c src/pkg/xz.c build/obj/ui/stb.o$(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ tests/map_bench.c src/monitor/map.c src/monitor/mon.c src/monitor/conn.c src/monitor/mmdb.c src/pkg/xz.c build/obj/ui/stb.o -lm -lpthread# canvas.c rows: SIMD (NEON on aarch64) against C, bit for bit, and how long each one takes+# UI engine (docs/DESIGN.md "Engine notes"): ellipsis in LTR/RTL/Arabic/Thai/emoji, per-side borders,+# per-corner radii, logical edges, transforms and hit testing; `build/engine-test bench` times a 2000-row+# list and a window drag on one and two displays+ENGINE_SRC := src/ui/node.c src/ui/style.c src/ui/layout.c src/ui/transform.c src/ui/text.c src/ui/textlayout.c src/ui/image.c \+ src/ui/paint.c src/ui/otf.c src/ui/fonts.c src/ui/unicode.c src/ui/bidi.c src/ui/shape.c src/ui/shape_indic.c \+ src/ui/shape_syl.c src/ui/shape_khmer.c src/ui/shape_myanmar.c src/ui/shape_use.c src/ui/thbrk.c src/canvas.c+test: build/engine-test+build/engine-test: tests/engine_test.c $(ENGINE_SRC) build/obj/ui/stb.o $(HDR)+ $(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ tests/engine_test.c $(ENGINE_SRC) build/obj/ui/stb.o -lm+ ./$@ || { rm -f $@; exit 1; }build/canvas-test: tests/canvas_test.c src/canvas.c src/canvas.h@mkdir -p build$(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -DLORD_CANVAS_TEST -o $@ tests/canvas_test.c src/canvas.c -lmdiff --git a/server/src/admin.c b/server/src/admin.cindex 662525f..7fd8e5a 100644--- a/server/src/admin.c+++ b/server/src/admin.c@@ -348,7 +348,7 @@ static void kid_read(Kid *k) {close(k->fd);int code = wait_code(k->pid);cur_client = k->client;- if (k->id && !k->done) put_line(k->id, "ERR", code == 0 ? "finished without a reply" : "finished with an error");+ if (k->id && !k->done) put_line(k->id, "ERR", code == 0 ? "admin.noReply" : "admin.actionFailed");if (!k->id) {char msg[96];snprintf(msg, sizeof msg, "daemon %s exit %d", k->name, code);@@ -460,7 +460,7 @@ static int locale_generated(const char *name) {/* Enables the line in /etc/locale.gen (uncomments or adds it) and runs locale-gen. */static void act_locale_gen(const char *name) {- if (!supported_locale(name)) { admin_say("ERR", "unsupported region: %s", name); return; }+ if (!supported_locale(name)) { admin_err("locale.unsupported", "name", name, NULL); return; }char want[160];snprintf(want, sizeof want, "%s UTF-8", name);FILE *f = fopen("/etc/locale.gen", "r");@@ -478,29 +478,29 @@ static void act_locale_gen(const char *name) {} else fputs(line, mem);}if (f) fclose(f);- if (!mem) { admin_say("ERR", "out of memory"); return; }+ if (!mem) { admin_err("sys.outOfMemory", NULL); return; }if (!found) fprintf(mem, "%s\n", want);fclose(mem);int fd = open("/etc/locale.gen.lordos", O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644);int ok = fd >= 0 && write(fd, buf, len) == (ssize_t)len;if (fd >= 0) ok = close(fd) == 0 && ok;free(buf);- if (!ok || rename("/etc/locale.gen.lordos", "/etc/locale.gen")) { admin_say("ERR", "could not write /etc/locale.gen"); return; }+ if (!ok || rename("/etc/locale.gen.lordos", "/etc/locale.gen")) { admin_err("sys.writeFailed", "path", "/etc/locale.gen", NULL); return; }const char *const argv[] = { "/usr/sbin/locale-gen", NULL };int r = admin_run(argv);- if (r == 0) admin_say("OK", "region %s generated", name);- else admin_say("ERR", "locale-gen exited with code %d", r);+ if (r == 0) admin_ok("locale.generated", "name", name, NULL);+ else admin_err("sys.programFailed", "program", "locale-gen", "code", lerr_int(r), NULL);}static void act_system_locale(const char *name) {- if (!supported_locale(name) && strcmp(name, "C.UTF-8")) { admin_say("ERR", "unsupported region: %s", name); return; }- if (!locale_generated(name)) { admin_say("ERR", "region %s is not generated", name); return; }+ if (!supported_locale(name) && strcmp(name, "C.UTF-8")) { admin_err("locale.unsupported", "name", name, NULL); return; }+ if (!locale_generated(name)) { admin_err("locale.notGenerated", "name", name, NULL); return; }int fd = open("/etc/default/locale.lordos", O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644);- if (fd < 0) { admin_say("ERR", "could not write /etc/default/locale"); return; }+ if (fd < 0) { admin_err("sys.writeFailed", "path", "/etc/default/locale", NULL); return; }dprintf(fd, "LANG=%s\n", name);close(fd);- if (rename("/etc/default/locale.lordos", "/etc/default/locale")) { admin_say("ERR", "could not write /etc/default/locale"); return; }- admin_say("OK", "system region: %s", name);+ if (rename("/etc/default/locale.lordos", "/etc/default/locale")) { admin_err("sys.writeFailed", "path", "/etc/default/locale", NULL); return; }+ admin_ok("locale.systemSet", "name", name, NULL);}static void act_timezone(const char *zone) {@@ -510,15 +510,15 @@ static void act_timezone(const char *zone) {char path[320];struct stat st;snprintf(path, sizeof path, "/usr/share/zoneinfo/%s", zone);- if (!ok || stat(path, &st) || !S_ISREG(st.st_mode)) { admin_say("ERR", "unknown time zone: %s", zone); return; }+ if (!ok || stat(path, &st) || !S_ISREG(st.st_mode)) { admin_err("tz.unknown", "zone", zone, NULL); return; }const char *const argv[] = { "/usr/bin/timedatectl", "set-timezone", zone, NULL };- if (access(argv[0], X_OK) == 0 && admin_run(argv) == 0) { admin_say("OK", "time zone: %s", zone); return; }+ if (access(argv[0], X_OK) == 0 && admin_run(argv) == 0) { admin_ok("tz.set", "zone", zone, NULL); return; }/* without systemd: the /etc/localtime link and /etc/timezone, like dpkg-reconfigure */unlink("/etc/localtime.lordos");- if (symlink(path, "/etc/localtime.lordos") || rename("/etc/localtime.lordos", "/etc/localtime")) { admin_say("ERR", "could not change /etc/localtime"); return; }+ if (symlink(path, "/etc/localtime.lordos") || rename("/etc/localtime.lordos", "/etc/localtime")) { admin_err("sys.writeFailed", "path", "/etc/localtime", NULL); return; }FILE *f = fopen("/etc/timezone", "w");if (f) { fprintf(f, "%s\n", zone); fclose(f); }- admin_say("OK", "time zone: %s", zone);+ admin_ok("tz.set", "zone", zone, NULL);}/* Fonts for the language's script and dictionaries for the input methods (ime.c), from@@ -569,7 +569,7 @@ static void act_langpack(const char *arg) {if (n - i != 3 || arg[i + 1] < 'A' || arg[i + 1] > 'Z' || arg[i + 2] < 'A' || arg[i + 2] > 'Z') ok = 0;else { cc[0] = (char)(arg[i + 1] - 'A' + 'a'); cc[1] = (char)(arg[i + 2] - 'A' + 'a'); }}- if (!ok) { admin_say("ERR", "invalid language code: %s", arg); return; }+ if (!ok) { admin_err("lang.invalidCode", "code", arg, NULL); return; }static const char *const patterns[] = { "manpages-%s", "hunspell-%s", "aspell-%s", "hyphen-%s", "mythes-%s" };char names[24][48];int count = 0;@@ -585,14 +585,14 @@ static void act_langpack(const char *arg) {}for (size_t i = 0; i < sizeof script_fonts / sizeof *script_fonts; i++)if (!strcmp(script_fonts[i].lang, ll) && count < 20) snprintf(names[count++], sizeof names[0], "%s", script_fonts[i].pkgs);- if (!count) { admin_say("OK", "no Debian packages for «%s»: only the region and the LordOS texts", arg); return; }+ if (!count) { admin_ok("lang.noDebianPackages", "lang", arg, NULL); return; }const char *argv[28] = { "/usr/bin/apt-get", "install", "-y", "--no-install-recommends" };int a = 4;- for (int i = 0; i < count; i++) { argv[a++] = names[i]; admin_say("LOG", "package: %s", names[i]); }+ for (int i = 0; i < count; i++) { argv[a++] = names[i]; admin_log("lang.package", "name", names[i], NULL); }argv[a] = NULL;int r = admin_run(argv);- if (r == 0) admin_say("OK", "%d package(s) installed for «%s»", count, arg);- else admin_say("ERR", "apt-get exited with code %d", r);+ if (r == 0) admin_ok("lang.installed", "count", lerr_int(count), "lang", arg, NULL);+ else admin_err("sys.programFailed", "program", "apt-get", "code", lerr_int(r), NULL);}#endif /* LORD_NETD */@@ -629,7 +629,7 @@ static void run_action(size_t a, AdminReq *req, int id, const char *arg, size_tif (actions[a].flags & A_FORK) {Kid *k = kid_new();int p[2];- if (!k || pipe2(p, O_CLOEXEC)) { admin_say("ERR", "too many actions in progress"); return; }+ if (!k || pipe2(p, O_CLOEXEC)) { admin_err("admin.tooMany", NULL); return; }pid_t pid = fork();if (pid == 0) {close(p[0]);@@ -643,7 +643,7 @@ static void run_action(size_t a, AdminReq *req, int id, const char *arg, size_t_exit(0);}close(p[1]);- if (pid < 0) { close(p[0]); admin_say("ERR", "could not create the process"); }+ if (pid < 0) { close(p[0]); admin_err("admin.forkFailed", NULL); }else *k = (Kid){ .pid = pid, .fd = p[0], .id = id, .client = client };} else actions[a].fn(req, arg, len);}@@ -699,7 +699,7 @@ static int netd_connect(void) {static void netd_lost(void) {if (netd_fd >= 0) close(netd_fd);netd_fd = -1;- for (int i = 0; i < netd_npending; i++) put_line(netd_pending[i], "ERR", "the system network (lord-netd) restarted: try again");+ for (int i = 0; i < netd_npending; i++) put_line(netd_pending[i], "ERR", "netd.restarted");netd_npending = 0;}@@ -745,11 +745,11 @@ static void helper_request(int id, const char *action, char *arg, size_t len, voh->req->id = id;size_t a = find_action(action);int fw = 1;- if (a == N_ACTIONS) admin_say("ERR", "unknown action");- else if (strlen(arg) != len) admin_say("ERR", "invalid argument");- else if (!h->allowed && !(actions[a].flags & A_ANYONE)) admin_say("ERR", "user %s is not an administrator (sudo group)", h->user);+ if (a == N_ACTIONS) admin_err("admin.unknownAction", NULL);+ else if (strlen(arg) != len) admin_err("admin.invalidArgument", NULL);+ else if (!h->allowed && !(actions[a].flags & A_ANYONE)) admin_err("admin.notAdmin", "user", h->user, NULL);else if (!strncmp(action, "net-", 4) && (fw = netd_forward(id, action, arg, len)) <= 0) {- if (fw < 0) admin_say("ERR", "the system network (lord-netd) is not available");+ if (fw < 0) admin_err("netd.unavailable", NULL);} else run_action(a, h->req, id, arg, len, -1);cur_id = 0;}@@ -872,10 +872,10 @@ static void netd_request(int id, const char *action, char *arg, size_t len, voidcur_id = id;c->req.id = id;size_t a = find_action(action);- if (a == N_ACTIONS || strncmp(action, "net-", 4)) admin_say("ERR", "unknown action");- else if (strlen(arg) != len) admin_say("ERR", "invalid argument");- else if (!c->req.admin && !(actions[a].flags & A_ANYONE)) admin_say("ERR", "user %s is not an administrator (sudo group)", c->user);- else if (!strcmp(action, "net-restore")) admin_say("OK", "0 interface(s): the network belongs to the system (lord-netd)");+ if (a == N_ACTIONS || strncmp(action, "net-", 4)) admin_err("admin.unknownAction", NULL);+ else if (strlen(arg) != len) admin_err("admin.invalidArgument", NULL);+ else if (!c->req.admin && !(actions[a].flags & A_ANYONE)) admin_err("admin.notAdmin", "user", c->user, NULL);+ else if (!strcmp(action, "net-restore")) admin_ok("net.restoreSystem", NULL);else {run_action(a, &c->req, id, arg, len, cur_client);if (!strcmp(action, "net-vpn-up")) netd_vpn_note(arg, 1);diff --git a/server/src/admin.h b/server/src/admin.hindex 5c09c70..edc6c39 100644--- a/server/src/admin.h+++ b/server/src/admin.h@@ -34,9 +34,27 @@ typedef struct {/* Replies of the running action: "LOG", "OK" or "ERR" (one line; \n become spaces). */void admin_say(const char *kind, const char *fmt, ...) __attribute__((format(printf, 2, 3)));-/* Unsolicited notice (id 0, EVENT): "net link eth0 up", "vpn wg0 conectada"... */+/* Unsolicited notice (id 0, EVENT): "net link eth0 up", "vpn wg0 connected"... */void admin_event(const char *fmt, ...) __attribute__((format(printf, 1, 2)));+/* What reaches the UI is a code line, never prose (see errcode.h): the UI translates it with+ * t('errors.<code>') for ERR and t('status.<code>') for OK/LOG. Pairs (key, value) end in NULL:+ * admin_err("pkg.removeEssential", "name", n, NULL); → "<id> ERR pkg.removeEssential name=dpkg" */+#include "errcode.h"+__attribute__((sentinel))+static inline void admin_code(const char *kind, const char *code, ...)+{+ char line[2048];+ va_list ap;+ va_start(ap, code);+ lerr_vset(line, sizeof line, code, ap);+ va_end(ap);+ admin_say(kind, "%s", line);+}+#define admin_err(...) admin_code("ERR", __VA_ARGS__)+#define admin_ok(...) admin_code("OK", __VA_ARGS__)+#define admin_log(...) admin_code("LOG", __VA_ARGS__)+/* Fixed-path program with a clean environment; its output goes as LOG. Returns the exit code. */int admin_run(const char *const argv[]);/* Same, with `input` on standard input (e.g. a password for chpasswd: never in argv). */diff --git a/server/src/backup/backup.c b/server/src/backup/backup.cindex 4ea66ee..bdedf08 100644--- a/server/src/backup/backup.c+++ b/server/src/backup/backup.c@@ -12,6 +12,7 @@* The time of the last good backup is the newest snapshot on the destination: there is no other* state file. The first scheduled backup waits 5 minutes after the session starts. */#include "backup.h"+#include "../errcode.h"#include "engine.h"#include "crypt.h"#include "../fsops.h"@@ -109,9 +110,9 @@ static int valid_dest(const char *in, char *real, size_t n, char *err, size_t enchar r[PATH_MAX];struct stat st;if (!in[0]) { real[0] = 0; return 0; }- if (in[0] != '/' || !realpath(in, r) || stat(r, &st) || !S_ISDIR(st.st_mode)) { snprintf(err, en, "the destination does not exist"); return -1; }- if (!fsops_allowed(r) || fsops_protected(r)) { snprintf(err, en, "the destination must be in the home folder or on one of the user's disks"); return -1; }- if (access(r, W_OK)) { snprintf(err, en, "cannot write to the destination"); return -1; }+ if (in[0] != '/' || !realpath(in, r) || stat(r, &st) || !S_ISDIR(st.st_mode)) { lerr_set(err, en, "backup.destMissing", NULL); return -1; }+ if (!fsops_allowed(r) || fsops_protected(r)) { lerr_set(err, en, "backup.destOutside", NULL); return -1; }+ if (access(r, W_OK)) { lerr_set(err, en, "backup.destUnwritable", NULL); return -1; }snprintf(real, n, "%s", r);return 0;}@@ -122,14 +123,14 @@ static int parse_config(const char *text, size_t len, Config *c, char *err, sizememset(c, 0, sizeof *c);c->interval = 3600;c->battery_pause = 1;- if (json_parse(text, len, &d, jerr, sizeof jerr)) { snprintf(err, en, "invalid configuration: %s", jerr); return -1; }+ if (json_parse(text, len, &d, jerr, sizeof jerr)) { lerr_set(err, en, "backup.badConfig", NULL); return -1; }const JVal *o = d.root;int r = 0;- if (!o || o->type != J_OBJ) { snprintf(err, en, "invalid configuration"); r = -1; goto out; }+ if (!o || o->type != J_OBJ) { lerr_set(err, en, "backup.badConfig", NULL); r = -1; goto out; }const char *dest = json_str(o, "dest");if (dest && strict && (strlen(dest) >= PATH_MAX || valid_dest(dest, c->dest, sizeof c->dest, err, en))) { r = -1; goto out; }if (dest && !strict) {- if (dest[0] != '/' || strlen(dest) >= sizeof c->dest || !bk_rel_valid(dest + 1)) { snprintf(err, en, "invalid destination"); r = -1; goto out; }+ if (dest[0] != '/' || strlen(dest) >= sizeof c->dest || !bk_rel_valid(dest + 1)) { lerr_set(err, en, "backup.badDest", NULL); r = -1; goto out; }snprintf(c->dest, sizeof c->dest, "%s", dest);}const char *iv = json_str(o, "interval");@@ -138,14 +139,14 @@ static int parse_config(const char *text, size_t len, Config *c, char *err, sizeelse if (!strcmp(iv, "daily")) c->interval = 86400;else if (!strcmp(iv, "weekly")) c->interval = 7 * 86400;else if (!strcmp(iv, "manual")) c->interval = 0;- else { snprintf(err, en, "invalid schedule"); r = -1; goto out; }+ else { lerr_set(err, en, "backup.badSchedule", NULL); r = -1; goto out; }}c->battery_pause = json_bool(o, "pauseOnBattery", 1);const JVal *ex = json_get(o, "exclude");if (ex && ex->type == J_ARR) {for (const JVal *e = ex->kid; e; e = e->next) {- if (e->type != J_STR || !e->len || e->len > 255 || !bk_rel_valid(e->str)) { snprintf(err, en, "invalid exclusion"); r = -1; goto out; }- if (c->nexcl >= BK_MAX_EXCL - 8) { snprintf(err, en, "too many exclusions"); r = -1; goto out; }+ if (e->type != J_STR || !e->len || e->len > 255 || !bk_rel_valid(e->str)) { lerr_set(err, en, "backup.badExclusion", NULL); r = -1; goto out; }+ if (c->nexcl >= BK_MAX_EXCL - 8) { lerr_set(err, en, "backup.tooManyExclusions", NULL); r = -1; goto out; }snprintf(c->excl[c->nexcl++], sizeof c->excl[0], "%s", e->str);}}@@ -330,10 +331,10 @@ static void do_snapshot(void) {last_ok = time(NULL);} else if (r < 0) {last.ok = 0;- snprintf(last_error, sizeof last_error, "%s", run.error[0] ? run.error : "error");+ snprintf(last_error, sizeof last_error, "%s", run.error[0] ? run.error : "sys.unknown");} else {last.ok = -1; /* interrupted: resumed next time */- snprintf(last_error, sizeof last_error, "interrupted");+ snprintf(last_error, sizeof last_error, "backup.interrupted");}last.files = run.files;last.copied = run.copied;@@ -362,12 +363,12 @@ static void do_restore(void) {int replace = rjob.replace;memset(&rres, 0, sizeof rres);snprintf(rres.id, sizeof rres.id, "%s", id);- if (machine_dir(&c, machine, sizeof machine)) { rres.done = 1; snprintf(rres.error, sizeof rres.error, "no-destination"); emit(); return; }+ if (machine_dir(&c, machine, sizeof machine)) { rres.done = 1; snprintf(rres.error, sizeof rres.error, "backup.noDestination"); emit(); return; }state = S_RESTORING;cancel_flag = 0;emit();pthread_mutex_unlock(&mu);- if (dest_enc && !have_key) { state = S_IDLE; rres.done = 1; snprintf(rres.error, sizeof rres.error, "locked"); emit(); return; }+ if (dest_enc && !have_key) { state = S_IDLE; rres.done = 1; snprintf(rres.error, sizeof rres.error, "backup.locked"); emit(); return; }BkRestore o = { .cancel = &cancel_flag, .key = dest_enc ? key : NULL };int r = bk_restore(machine, id, rel, to, replace, suffix, &o);pthread_mutex_lock(&mu);@@ -379,7 +380,7 @@ static void do_restore(void) {rres.replaced = o.replaced;rres.skipped = o.skipped;rres.errors = o.errors;- snprintf(rres.error, sizeof rres.error, "%s", r > 0 ? "interrupted" : o.error);+ snprintf(rres.error, sizeof rres.error, "%s", r > 0 ? "backup.interrupted" : o.error);fprintf(stderr, "backup: restored %s/%s: %llu files, %llu kept alongside, %llu replaced, %llu errors\n", id, rel,(unsigned long long)o.files, (unsigned long long)o.kept_both, (unsigned long long)o.replaced, (unsigned long long)o.errors);emit();@@ -408,7 +409,7 @@ static void do_unlock(void) {bkc_wipe(ujob.pass, sizeof ujob.pass);ujob.pending = 0;memset(&ures, 0, sizeof ures);- if (machine_dir(&cfg, machine, sizeof machine)) { bkc_wipe(pass, sizeof pass); ures.done = 1; snprintf(ures.error, sizeof ures.error, "no-destination"); emit(); return; }+ if (machine_dir(&cfg, machine, sizeof machine)) { bkc_wipe(pass, sizeof pass); ures.done = 1; snprintf(ures.error, sizeof ures.error, "backup.noDestination"); emit(); return; }State before = state;state = S_UNLOCKING;emit();@@ -431,8 +432,8 @@ static void do_unlock(void) {ures.done = 1;ures.ok = r == 0;if (r == 0) { memcpy(key, k, sizeof key); have_key = 1; dest_enc = 1; }- else snprintf(ures.error, sizeof ures.error, "%s", r == -1 ? "wrong-passphrase" : r == -2 ? "not-encrypted" :- r == -3 ? "plain-backups-exist" : "setup-failed"); /* codes: the UI translates them */+ else snprintf(ures.error, sizeof ures.error, "%s", r == -1 ? "backup.wrongPassphrase" : r == -2 ? "backup.notEncrypted" :+ r == -3 ? "backup.plainBackupsExist" : "backup.setupFailed"); /* code lines: the UI translates them */bkc_wipe(k, sizeof k);state = before == S_UNLOCKING ? S_IDLE : before;if (state == S_LOCKED) state = S_IDLE;@@ -590,11 +591,11 @@ char *backup_config_json(void) {}int backup_configure(const char *json, char *err, size_t n) {- if (!started) { snprintf(err, n, "backups are not running"); return -1; }- if (strlen(json) > 60000) { snprintf(err, n, "configuration too large"); return -1; }+ if (!started) { lerr_set(err, n, "backup.notRunning", NULL); return -1; }+ if (strlen(json) > 60000) { lerr_set(err, n, "backup.configTooLarge", NULL); return -1; }Config c;if (parse_config(json, strlen(json), &c, err, n, 1)) return -1;- if (save_config(&c)) { snprintf(err, n, "could not save the configuration"); return -1; }+ if (save_config(&c)) { lerr_set(err, n, "backup.saveFailed", NULL); return -1; }pthread_mutex_lock(&mu);int changed_dest = strcmp(c.dest, cfg.dest) != 0;cfg = c;@@ -612,11 +613,11 @@ int backup_configure(const char *json, char *err, size_t n) {}int backup_run_now(char *err, size_t n) {- if (!started) { snprintf(err, n, "backups are not running"); return -1; }+ if (!started) { lerr_set(err, n, "backup.notRunning", NULL); return -1; }pthread_mutex_lock(&mu);int r = 0;- if (!cfg.dest[0]) { snprintf(err, n, "choose a destination first"); r = -1; }- else if (state == S_RUNNING || state == S_RESTORING) { snprintf(err, n, "a backup is already running"); r = -1; }+ if (!cfg.dest[0]) { lerr_set(err, n, "backup.noDestination", NULL); r = -1; }+ else if (state == S_RUNNING || state == S_RESTORING) { lerr_set(err, n, "backup.alreadyRunning", NULL); r = -1; }else { want_run = 1; user_pause = 0; if (state == S_NODEST) state = S_IDLE; last_try = 0; pthread_cond_broadcast(&cv); }pthread_mutex_unlock(&mu);return r;@@ -682,13 +683,13 @@ static int ent_cmp(const void *a, const void *b) {char *backup_ls_json(const char *id, const char *rel, char *err, size_t en) {char snap[PATH_MAX], dir[PATH_MAX], real[PATH_MAX];- if (!bk_rel_valid(rel)) { snprintf(err, en, "invalid path"); return NULL; }- if (backup_snapshot_path(id, snap, sizeof snap)) { snprintf(err, en, "no such backup"); return NULL; }- if (pathf(dir, sizeof dir, "%s%s%s", snap, rel[0] ? "/" : "", rel)) { snprintf(err, en, "invalid path"); return NULL; }+ if (!bk_rel_valid(rel)) { lerr_set(err, en, "backup.badPath", NULL); return NULL; }+ if (backup_snapshot_path(id, snap, sizeof snap)) { lerr_set(err, en, "backup.noSuchBackup", NULL); return NULL; }+ if (pathf(dir, sizeof dir, "%s%s%s", snap, rel[0] ? "/" : "", rel)) { lerr_set(err, en, "backup.badPath", NULL); return NULL; }size_t sl = strlen(snap);- if (!realpath(dir, real) || strncmp(real, snap, sl) || (real[sl] && real[sl] != '/')) { snprintf(err, en, "invalid path"); return NULL; }+ if (!realpath(dir, real) || strncmp(real, snap, sl) || (real[sl] && real[sl] != '/')) { lerr_set(err, en, "backup.badPath", NULL); return NULL; }DIR *d = opendir(real);- if (!d) { snprintf(err, en, "cannot read"); return NULL; }+ if (!d) { lerr_set(err, en, "backup.readFailed", NULL); return NULL; }pthread_mutex_lock(&mu);int enc = dest_enc;pthread_mutex_unlock(&mu);@@ -730,17 +731,17 @@ char *backup_ls_json(const char *id, const char *rel, char *err, size_t en) {}int backup_restore(const char *id, const char *rel, int replace, const char *suffix, const char *to, char *err, size_t n) {- if (!started) { snprintf(err, n, "backups are not running"); return -1; }- if (!bk_id_valid(id) || !bk_rel_valid(rel) || strlen(rel) >= sizeof rjob.rel) { snprintf(err, n, "invalid path"); return -1; }+ if (!started) { lerr_set(err, n, "backup.notRunning", NULL); return -1; }+ if (!bk_id_valid(id) || !bk_rel_valid(rel) || strlen(rel) >= sizeof rjob.rel) { lerr_set(err, n, "backup.badPath", NULL); return -1; }size_t sl = strlen(suffix);- if (!sl || sl >= sizeof rjob.suffix || strchr(suffix, '/')) { snprintf(err, n, "invalid suffix"); return -1; }+ if (!sl || sl >= sizeof rjob.suffix || strchr(suffix, '/')) { lerr_set(err, n, "backup.badSuffix", NULL); return -1; }char tr[PATH_MAX] = "";if (to && to[0]) {- if (!realpath(to, tr) || !fsops_allowed(tr) || fsops_protected(tr)) { snprintf(err, n, "destination not allowed"); return -1; }+ if (!realpath(to, tr) || !fsops_allowed(tr) || fsops_protected(tr)) { lerr_set(err, n, "backup.destNotAllowed", NULL); return -1; }}pthread_mutex_lock(&mu);int r = 0;- if (state == S_RUNNING || state == S_RESTORING || state == S_DELETING || rjob.pending) { snprintf(err, n, "another task is running"); r = -1; }+ if (state == S_RUNNING || state == S_RESTORING || state == S_DELETING || rjob.pending) { lerr_set(err, n, "backup.busy", NULL); r = -1; }else {snprintf(rjob.id, sizeof rjob.id, "%s", id);snprintf(rjob.rel, sizeof rjob.rel, "%s", rel);@@ -756,24 +757,24 @@ int backup_restore(const char *id, const char *rel, int replace, const char *suf}int backup_delete(const char *id, char *err, size_t n) {- if (!started) { snprintf(err, n, "backups are not running"); return -1; }- if (!bk_id_valid(id)) { snprintf(err, n, "invalid backup"); return -1; }+ if (!started) { lerr_set(err, n, "backup.notRunning", NULL); return -1; }+ if (!bk_id_valid(id)) { lerr_set(err, n, "backup.badId", NULL); return -1; }pthread_mutex_lock(&mu);int r = 0;- if (state != S_IDLE && state != S_NODEST) { snprintf(err, n, "another task is running"); r = -1; }+ if (state != S_IDLE && state != S_NODEST) { lerr_set(err, n, "backup.busy", NULL); r = -1; }else { snprintf(djob.id, sizeof djob.id, "%s", id); djob.pending = 1; pthread_cond_broadcast(&cv); }pthread_mutex_unlock(&mu);return r;}int backup_unlock(const char *pass, int create, char *err, size_t n) {- if (!started) { snprintf(err, n, "backups are not running"); return -1; }+ if (!started) { lerr_set(err, n, "backup.notRunning", NULL); return -1; }size_t len = strlen(pass);- if (len < (create ? 8u : 1u) || len >= sizeof ujob.pass) { snprintf(err, n, create ? "the passphrase must have at least 8 characters" : "invalid passphrase"); return -1; }+ if (len < (create ? 8u : 1u) || len >= sizeof ujob.pass) { lerr_set(err, n, create ? "backup.passphraseShort" : "backup.badPassphrase", NULL); return -1; }pthread_mutex_lock(&mu);int r = 0;- if (!cfg.dest[0]) { snprintf(err, n, "choose a destination first"); r = -1; }- else if (state == S_RUNNING || state == S_RESTORING || state == S_UNLOCKING || ujob.pending) { snprintf(err, n, "another task is running"); r = -1; }+ if (!cfg.dest[0]) { lerr_set(err, n, "backup.noDestination", NULL); r = -1; }+ else if (state == S_RUNNING || state == S_RESTORING || state == S_UNLOCKING || ujob.pending) { lerr_set(err, n, "backup.busy", NULL); r = -1; }else {snprintf(ujob.pass, sizeof ujob.pass, "%s", pass);ujob.create = create != 0;diff --git a/server/src/backup/engine.c b/server/src/backup/engine.cindex 3465c65..29759e8 100644--- a/server/src/backup/engine.c+++ b/server/src/backup/engine.c@@ -10,6 +10,7 @@* complete file (which is what makes resuming an interrupted run possible);* - deletion only happens inside the machine folder and with validated names. */#include "engine.h"+#include "../errcode.h"#include "../fsops.h"#include "crypt.h"@@ -380,7 +381,7 @@ static void entry(Walk *w, const char *rel, int depth) {/* out of space: delete old snapshots (never the newest) and retry once */if (bk_prune(w->r->machine, time(NULL), (uint64_t)st.st_size + (w->r->min_free ? w->r->min_free : (512u << 20))) > 0)r = copy_file(w, src, dst, &st);- if (r == -2) { w->fatal = 1; snprintf(w->r->error, sizeof w->r->error, "no space left on the destination"); return; }+ if (r == -2) { w->fatal = 1; lerr_set(w->r->error, sizeof w->r->error, "backup.noSpace", NULL); return; }}if (r == 0) w->r->copied++;else if (r < 0) w->r->errors++;@@ -447,7 +448,7 @@ int bk_snapshot(BkRun *r, time_t now) {w.r = r;struct stat hs;if (pathf(w.src, sizeof w.src, "%s", r->home) || lstat(w.src, &hs) || !S_ISDIR(hs.st_mode)) {- snprintf(r->error, sizeof r->error, "cannot read the source folder");+ lerr_set(r->error, sizeof r->error, "backup.sourceUnreadable", NULL);return -1;}w.home_dev = hs.st_dev;@@ -455,7 +456,7 @@ int bk_snapshot(BkRun *r, time_t now) {struct stat ss;if (!stat(r->skip_real, &ss)) { w.has_skip = 1; w.skip_dev = ss.st_dev; w.skip_ino = ss.st_ino; }}- if (mkdir_p(r->machine, 0700)) { snprintf(r->error, sizeof r->error, "could not create %s: %s", r->machine, strerror(errno)); return -1; }+ if (mkdir_p(r->machine, 0700)) { lerr_set(r->error, sizeof r->error, "backup.createFailed", "path", r->machine, "errno", lerr_errno(errno), NULL); return -1; }static char ids[BK_MAX_SNAPS][BK_ID_LEN];int n = bk_list(r->machine, ids, BK_MAX_SNAPS);@@ -507,7 +508,7 @@ int bk_snapshot(BkRun *r, time_t now) {if (w.stop) return 1;if (pathf(w.dst, sizeof w.dst, "%s/.inprogress-%s", r->machine, r->id) || mkdir(w.dst, 0700)) {- snprintf(r->error, sizeof r->error, "cannot write to the destination: %s", strerror(errno));+ lerr_set(r->error, sizeof r->error, "backup.destUnwritable", "errno", lerr_errno(errno), NULL);return -1;}walk(&w, "", 0);@@ -521,7 +522,7 @@ int bk_snapshot(BkRun *r, time_t now) {if (dfd >= 0) { syncfs(dfd); close(dfd); }char final[PATH_MAX];if (pathf(final, sizeof final, "%s/%s", r->machine, r->id) || rename(w.dst, final)) {- snprintf(r->error, sizeof r->error, "could not finish the snapshot: %s", strerror(errno));+ lerr_set(r->error, sizeof r->error, "backup.snapshotFailed", "errno", lerr_errno(errno), NULL);return -1;}int mfd = open(r->machine, O_RDONLY | O_DIRECTORY | O_CLOEXEC);@@ -588,7 +589,7 @@ static int restore_file(Rest *x, const char *src, const char *dst, const structint r = 0;if (x->o->key) {r = bkc_decrypt_fd(in, out, x->o->key, rest_tick, x);- if (r == -3) snprintf(x->o->error, sizeof x->o->error, "a backup file failed verification (tampered with or wrong key)");+ if (r == -3) lerr_set(x->o->error, sizeof x->o->error, "backup.verifyFailed", NULL);if (r < 0) r = -1;} else {char *buf = malloc(1 << 20);@@ -694,14 +695,14 @@ int bk_restore(const char *machine, const char *id, const char *rel, const charint replace, const char *suffix, BkRestore *out) {out->files = out->bytes = out->kept_both = out->replaced = out->skipped = out->errors = 0;out->error[0] = 0;- if (!bk_id_valid(id) || !bk_rel_valid(rel)) { snprintf(out->error, sizeof out->error, "invalid path"); return -1; }+ if (!bk_id_valid(id) || !bk_rel_valid(rel)) { lerr_set(out->error, sizeof out->error, "backup.badPath", NULL); return -1; }size_t sl = strlen(suffix);- if (!sl || sl > 64 || strchr(suffix, '/')) { snprintf(out->error, sizeof out->error, "invalid suffix"); return -1; }- for (const char *p = suffix; *p; p++) if ((unsigned char)*p < 0x20) { snprintf(out->error, sizeof out->error, "invalid suffix"); return -1; }+ if (!sl || sl > 64 || strchr(suffix, '/')) { lerr_set(out->error, sizeof out->error, "backup.badSuffix", NULL); return -1; }+ for (const char *p = suffix; *p; p++) if ((unsigned char)*p < 0x20) { lerr_set(out->error, sizeof out->error, "backup.badSuffix", NULL); return -1; }Rest x = { .o = out, .suffix = suffix, .replace = replace };char snap[PATH_MAX], src[PATH_MAX], breal[PATH_MAX], dst[PATH_MAX];if (pathf(snap, sizeof snap, "%s/%s", machine, id) || !realpath(snap, x.snapreal)) {- snprintf(out->error, sizeof out->error, "backup %s does not exist", id);+ lerr_set(out->error, sizeof out->error, "backup.noSuchBackup", "id", id, NULL);return -1;}if (pathf(src, sizeof src, "%s%s%s", x.snapreal, rel[0] ? "/" : "", rel)) return -1;@@ -710,9 +711,9 @@ int bk_restore(const char *machine, const char *id, const char *rel, const charchar parent[PATH_MAX], preal[PATH_MAX];snprintf(parent, sizeof parent, "%s", src);*strrchr(parent, '/') = 0;- if (!realpath(parent, preal) || !under(preal, x.snapreal)) { snprintf(out->error, sizeof out->error, "invalid path"); return -1; }+ if (!realpath(parent, preal) || !under(preal, x.snapreal)) { lerr_set(out->error, sizeof out->error, "backup.badPath", NULL); return -1; }}- if (!realpath(base, breal) || !fsops_allowed(breal)) { snprintf(out->error, sizeof out->error, "destination not allowed"); return -1; }+ if (!realpath(base, breal) || !fsops_allowed(breal)) { lerr_set(out->error, sizeof out->error, "backup.destNotAllowed", NULL); return -1; }if (!rel[0]) {/* everything: the snapshot's contents, inside base */DIR *d = opendir(src);@@ -737,9 +738,9 @@ int bk_restore(const char *machine, const char *id, const char *rel, const charchar p[PATH_MAX];if (pathf(p, sizeof p, "%s/%s", cur, tok)) return -1;struct stat st;- if (lstat(p, &st) && mkdir(p, 0700)) { snprintf(out->error, sizeof out->error, "could not create %.200s", p); return -1; }+ if (lstat(p, &st) && mkdir(p, 0700)) { lerr_set(out->error, sizeof out->error, "backup.createFailed", "path", p, "errno", lerr_errno(errno), NULL); return -1; }char pr[PATH_MAX];- if (!realpath(p, pr) || !fsops_allowed(pr) || fsops_protected(pr)) { snprintf(out->error, sizeof out->error, "destination not allowed"); return -1; }+ if (!realpath(p, pr) || !fsops_allowed(pr) || fsops_protected(pr)) { lerr_set(out->error, sizeof out->error, "backup.destNotAllowed", NULL); return -1; }snprintf(cur, sizeof cur, "%s", pr);tok = next;}diff --git a/server/src/canvas.c b/server/src/canvas.cindex be78d6b..1761ae8 100644--- a/server/src/canvas.c+++ b/server/src/canvas.c@@ -581,3 +581,220 @@ void canvas_blit_scaled(Canvas *c, const uint32_t *src, int stride, int sw_px, i}}}++/* ---- per-corner radii, per-side borders, affine copies ---- */++/* CSS: radii that don't fit are all scaled down by the same factor. */+static void fix_radii(const float in[4], float w, float h, float r[4]) {+ float f = 1;+ float top = in[0] + in[1], bot = in[3] + in[2], left = in[0] + in[3], right = in[1] + in[2];+ if (top > w && top > 0) f = fminf(f, w / top);+ if (bot > w && bot > 0) f = fminf(f, w / bot);+ if (left > h && left > 0) f = fminf(f, h / left);+ if (right > h && right > 0) f = fminf(f, h / right);+ for (int i = 0; i < 4; i++) r[i] = in[i] > 0 ? in[i] * f : 0;+}++static inline float rr4_sdf(float px, float py, float cx, float cy, float hw, float hh, const float r[4]) {+ float k = px < cx ? (py < cy ? r[0] : r[3]) : (py < cy ? r[1] : r[2]);+ return rr_sdf(px, py, cx, cy, hw, hh, k);+}++void canvas_rrect4(Canvas *c, float x, float y, float w, float h, const float rin[4], uint32_t argb) {+ uint32_t a = argb >> 24;+ int x0, y0, x1, y1;+ if (!a || w <= 0 || h <= 0 || !bounds(c, x, y, w, h, &x0, &y0, &x1, &y1)) return;+ float r[4];+ fix_radii(rin, w, h, r);+ float cx = x + w * 0.5f, cy = y + h * 0.5f, hw = w * 0.5f, hh = h * 0.5f;+ float top = fmaxf(r[0], r[1]), bot = fmaxf(r[2], r[3]);+ int fx0 = (int)ceilf(x), fx1 = (int)floorf(x + w);+ for (int j = y0; j < y1; j++) {+ uint32_t *row = c->px + (size_t)j * c->stride;+ if (j >= y + top && j + 1 <= y + h - bot) {+ int m0 = fx0 > x0 ? fx0 : x0, m1 = fx1 < x1 ? fx1 : x1;+ if (m1 < m0) m1 = m0;+ for (int i = x0; i < m0; i++) {+ float cov = fminf(i + 1.0f, x + w) - fmaxf((float)i, x);+ if (cov > 0) put(&row[i], argb, (uint32_t)(a * cov + 0.5f));+ }+ if (a >= 255) { uint32_t v = argb | 0xff000000u; for (int i = m0; i < m1; i++) row[i] = v; }+ else for (int i = m0; i < m1; i++) row[i] = blend(row[i], argb, a);+ for (int i = m1; i < x1; i++) {+ float cov = fminf(i + 1.0f, x + w) - fmaxf((float)i, x);+ if (cov > 0) put(&row[i], argb, (uint32_t)(a * cov + 0.5f));+ }+ } else {+ float py = j + 0.5f;+ for (int i = x0; i < x1; i++) {+ float cov = cov_of(rr4_sdf(i + 0.5f, py, cx, cy, hw, hh, r));+ if (cov > 0) put(&row[i], argb, (uint32_t)(a * cov + 0.5f));+ }+ }+ }+}++void canvas_rrect4_gradient(Canvas *c, float x, float y, float w, float h, const float rin[4],+ uint32_t from, uint32_t to, float angle_deg, float opacity) {+ int x0, y0, x1, y1;+ if (w <= 0 || h <= 0 || !bounds(c, x, y, w, h, &x0, &y0, &x1, &y1)) return;+ float r[4];+ fix_radii(rin, w, h, r);+ float cx = x + w * 0.5f, cy = y + h * 0.5f, hw = w * 0.5f, hh = h * 0.5f;+ float rad = angle_deg * 3.14159265f / 180.0f, dx = sinf(rad), dy = -cosf(rad);+ float len = fabsf(w * dx) + fabsf(h * dy);+ if (len <= 0) len = 1;+ for (int j = y0; j < y1; j++) {+ uint32_t *row = c->px + (size_t)j * c->stride;+ float py = j + 0.5f;+ for (int i = x0; i < x1; i++) {+ float px = i + 0.5f;+ float cov = cov_of(rr4_sdf(px, py, cx, cy, hw, hh, r));+ if (cov <= 0) continue;+ float t = 0.5f + ((px - cx) * dx + (py - cy) * dy) / len;+ t = t < 0 ? 0 : t > 1 ? 1 : t;+ uint32_t col = lerp_color(from, to, t);+ put(&row[i], col, (uint32_t)((col >> 24) * cov * opacity + 0.5f));+ }+ }+}++void canvas_border4(Canvas *c, float x, float y, float w, float h, const float rin[4], const float bw[4], const uint32_t col[4]) {+ int x0, y0, x1, y1;+ if (w <= 0 || h <= 0 || !bounds(c, x, y, w, h, &x0, &y0, &x1, &y1)) return;+ enum { L, T, R, B };+ float r[4];+ fix_radii(rin, w, h, r);+ if (r[0] <= 0 && r[1] <= 0 && r[2] <= 0 && r[3] <= 0) {+ /* square corners: four rectangles (the top and bottom ones span the corners) */+ float bt = fminf(bw[T], h), bb = fminf(bw[B], h - bt);+ if (bt > 0) canvas_rrect(c, x, y, w, bt, 0, col[T]);+ if (bb > 0) canvas_rrect(c, x, y + h - bb, w, bb, 0, col[B]);+ float mh = h - bt - bb;+ if (mh > 0 && bw[L] > 0) canvas_rrect(c, x, y + bt, fminf(bw[L], w), mh, 0, col[L]);+ if (mh > 0 && bw[R] > 0) canvas_rrect(c, x + w - fminf(bw[R], w), y + bt, fminf(bw[R], w), mh, 0, col[R]);+ return;+ }+ float ix = x + bw[L], iy = y + bw[T], iw = w - bw[L] - bw[R], ih = h - bw[T] - bw[B];+ float ir[4] = { fmaxf(0, r[0] - fmaxf(bw[L], bw[T])), fmaxf(0, r[1] - fmaxf(bw[R], bw[T])),+ fmaxf(0, r[2] - fmaxf(bw[R], bw[B])), fmaxf(0, r[3] - fmaxf(bw[L], bw[B])) };+ float cx = x + w * 0.5f, cy = y + h * 0.5f, hw = w * 0.5f, hh = h * 0.5f;+ float icx = ix + iw * 0.5f, icy = iy + ih * 0.5f, ihw = iw * 0.5f, ihh = ih * 0.5f;+ int hollow = iw > 0 && ih > 0;+ float etop = fmaxf(bw[T], fmaxf(r[0], r[1])) + 1, ebot = fmaxf(bw[B], fmaxf(r[2], r[3])) + 1;+ float eleft = fmaxf(bw[L], fmaxf(r[0], r[3])) + 1, eright = fmaxf(bw[R], fmaxf(r[1], r[2])) + 1;+ for (int j = y0; j < y1; j++) {+ uint32_t *row = c->px + (size_t)j * c->stride;+ float py = j + 0.5f;+ int middle = hollow && py > y + etop && py < y + h - ebot;+ for (int i = x0; i < x1; i++) {+ float px = i + 0.5f;+ if (middle && px > x + eleft && px < x + w - eright) {+ int last = (int)ceilf(x + w - eright - 0.5f) - 1;+ if (last > i) i = last;+ continue;+ }+ float cov = cov_of(rr4_sdf(px, py, cx, cy, hw, hh, r));+ if (hollow) cov -= cov_of(rr4_sdf(px, py, icx, icy, ihw, ihh, ir));+ if (cov <= 0) continue;+ /* the side whose border band the pixel is deepest in, relative to its width (corner diagonals) */+ float best = 1e30f;+ int side = T;+ float d[4] = { px - x, py - y, x + w - px, y + h - py };+ for (int s = 0; s < 4; s++) {+ if (bw[s] <= 0) continue;+ float v = d[s] / bw[s];+ if (v < best) { best = v; side = s; }+ }+ uint32_t a = col[side] >> 24;+ if (a && bw[side] > 0) put(&row[i], col[side], (uint32_t)(a * cov + 0.5f));+ }+ }+}++void canvas_corners_save4(Canvas *c, Corners *k, float x, float y, float w, float h, const float rin[4]) {+ float r[4];+ fix_radii(rin, w, h, r);+ float m = fmaxf(fmaxf(r[0], r[1]), fmaxf(r[2], r[3]));+ k->n = (int)ceilf(m) + 1;+ k->buf = NULL;+ if (m <= 0) return;+ k->buf = malloc((size_t)k->n * k->n * 4 * 4);+ if (!k->buf) return;+ int xs[4] = { (int)floorf(x), (int)ceilf(x + w) - k->n, (int)floorf(x), (int)ceilf(x + w) - k->n };+ int ys[4] = { (int)floorf(y), (int)floorf(y), (int)ceilf(y + h) - k->n, (int)ceilf(y + h) - k->n };+ for (int q = 0; q < 4; q++) {+ k->x[q] = xs[q]; k->y[q] = ys[q];+ for (int j = 0; j < k->n; j++)+ for (int i = 0; i < k->n; i++) {+ int px = xs[q] + i, py = ys[q] + j;+ uint32_t v = 0;+ if (px >= 0 && py >= 0 && px < c->w && py < c->h) v = c->px[(size_t)py * c->stride + px];+ k->buf[((size_t)q * k->n + j) * k->n + i] = v;+ }+ }+}++void canvas_corners_restore4(Canvas *c, Corners *k, float x, float y, float w, float h, const float rin[4]) {+ if (!k->buf) return;+ float r[4];+ fix_radii(rin, w, h, r);+ float cx = x + w * 0.5f, cy = y + h * 0.5f, hw = w * 0.5f, hh = h * 0.5f;+ for (int q = 0; q < 4; q++)+ for (int j = 0; j < k->n; j++)+ for (int i = 0; i < k->n; i++) {+ int px = k->x[q] + i, py = k->y[q] + j;+ if (px < c->clip.x0 || py < c->clip.y0 || px >= c->clip.x1 || py >= c->clip.y1) continue;+ float cov = cov_of(rr4_sdf(px + 0.5f, py + 0.5f, cx, cy, hw, hh, r));+ if (cov >= 1) continue;+ uint32_t *d = &c->px[(size_t)py * c->stride + px];+ *d = blend(*d, k->buf[((size_t)q * k->n + j) * k->n + i], (uint32_t)((1 - cov) * 255 + 0.5f));+ }+ free(k->buf);+ k->buf = NULL;+}++static inline uint32_t texel(const uint32_t *src, int sw, int sh, int x, int y) {+ return x < 0 || y < 0 || x >= sw || y >= sh ? 0 : src[(size_t)y * sw + x];+}++void canvas_blit_affine(Canvas *c, const uint32_t *src, int sw, int sh, const float inv[6], const float fwd[6], float opacity) {+ if (sw <= 0 || sh <= 0) return;+ /* destination bounds: the four transformed corners */+ float bx0 = 1e30f, by0 = 1e30f, bx1 = -1e30f, by1 = -1e30f;+ const float cs[4][2] = { {0, 0}, {(float)sw, 0}, {(float)sw, (float)sh}, {0, (float)sh} };+ for (int q = 0; q < 4; q++) {+ float px = fwd[0] * cs[q][0] + fwd[2] * cs[q][1] + fwd[4], py = fwd[1] * cs[q][0] + fwd[3] * cs[q][1] + fwd[5];+ bx0 = fminf(bx0, px); by0 = fminf(by0, py); bx1 = fmaxf(bx1, px); by1 = fmaxf(by1, py);+ }+ int x0, y0, x1, y1;+ if (!bounds(c, bx0 - 1, by0 - 1, bx1 - bx0 + 2, by1 - by0 + 2, &x0, &y0, &x1, &y1)) return;+ uint32_t k_op = (uint32_t)(opacity * 256 + 0.5f);+ if (!k_op) return;+ for (int j = y0; j < y1; j++) {+ uint32_t *row = c->px + (size_t)j * c->stride;+ float dy = j + 0.5f;+ /* source coordinates of the pixel center, stepped along the row */+ float u = inv[0] * (x0 + 0.5f) + inv[2] * dy + inv[4] - 0.5f;+ float v = inv[1] * (x0 + 0.5f) + inv[3] * dy + inv[5] - 0.5f;+ for (int i = x0; i < x1; i++, u += inv[0], v += inv[1]) {+ if (u <= -1 || v <= -1 || u >= sw || v >= sh) continue;+ int ix = (int)floorf(u), iy = (int)floorf(v);+ uint32_t wx = (uint32_t)((u - ix) * 256), wy = (uint32_t)((v - iy) * 256);+ uint32_t a = texel(src, sw, sh, ix, iy), b = texel(src, sw, sh, ix + 1, iy);+ uint32_t cc = texel(src, sw, sh, ix, iy + 1), d = texel(src, sw, sh, ix + 1, iy + 1), p = 0;+ if (!(a | b | cc | d)) continue;+ for (int s8 = 0; s8 < 32; s8 += 8) {+ uint32_t top = ((a >> s8 & 255) * (256 - wx) + (b >> s8 & 255) * wx) >> 8;+ uint32_t bot = ((cc >> s8 & 255) * (256 - wx) + (d >> s8 & 255) * wx) >> 8;+ p |= ((top * (256 - wy) + bot * wy) >> 8 & 255) << s8;+ }+ uint32_t sa = ((p >> 24) * k_op) >> 8;+ if (!sa) continue;+ uint32_t srb = (((p & 0xff00ff) * k_op) >> 8) & 0xff00ff, sg = (((p & 0xff00) * k_op) >> 8) & 0xff00;+ uint32_t ia = 255 - sa, dd = row[i];+ uint32_t drb = (((dd & 0xff00ff) * ia) >> 8) & 0xff00ff, dg = (((dd & 0xff00) * ia) >> 8) & 0xff00;+ row[i] = over_alpha(sa, dd >> 24) << 24 | (srb + drb) | (sg + dg);+ }+ }+}diff --git a/server/src/canvas.h b/server/src/canvas.hindex fc9d94a..1f6c173 100644--- a/server/src/canvas.h+++ b/server/src/canvas.h@@ -36,6 +36,20 @@ typedef struct { int x[4], y[4], n; uint32_t *buf; } Corners;void canvas_corners_save(Canvas *c, Corners *k, float x, float y, float w, float h, float r);void canvas_corners_restore(Canvas *c, Corners *k, float x, float y, float w, float h, float r);+/* Per-corner radii r[4] = top-left, top-right, bottom-right, bottom-left (radii that are all equal go+ * through the functions above, which are faster). */+void canvas_rrect4(Canvas *c, float x, float y, float w, float h, const float r[4], uint32_t argb);+void canvas_rrect4_gradient(Canvas *c, float x, float y, float w, float h, const float r[4],+ uint32_t from, uint32_t to, float angle_deg, float opacity);+/* Border with a width and a color per side (bw/col: left, top, right, bottom) and per-corner radii.+ * Sides meet on the diagonal of each corner, as in CSS. */+void canvas_border4(Canvas *c, float x, float y, float w, float h, const float r[4], const float bw[4], const uint32_t col[4]);+void canvas_corners_save4(Canvas *c, Corners *k, float x, float y, float w, float h, const float r[4]);+void canvas_corners_restore4(Canvas *c, Corners *k, float x, float y, float w, float h, const float r[4]);+/* Affine copy: destination pixel p takes the source at inv(p) (bilinear, transparent outside), a+ * premultiplied w × h image; inv maps canvas pixels to source pixels. */+void canvas_blit_affine(Canvas *c, const uint32_t *src, int sw, int sh, const float inv[6], const float fwd[6], float opacity);+/* 8-bit coverage mask (glyphs). */void canvas_alpha_mask(Canvas *c, int x, int y, const uint8_t *a, int w, int h, int stride, uint32_t argb);/* Premultiplied ARGB image, with rounded corners and opacity. */diff --git a/server/src/disk/disk_admin.c b/server/src/disk/disk_admin.cindex cdc00db..4c042a7 100644--- a/server/src/disk/disk_admin.c+++ b/server/src/disk/disk_admin.c@@ -89,28 +89,28 @@ static int known_kind(const char *n) {* also allowed on the system disk and for any user. */static int target(const AdminReq *r, const char *name, int want, int allow_system, Target *t) {memset(t, 0, sizeof *t);- if (!disk_valid_name(name) || !known_kind(name)) { admin_say("ERR", "dispositivo inválido"); return -1; }+ if (!disk_valid_name(name) || !known_kind(name)) { admin_err("disk.badDevice", NULL); return -1; }char p[PATH_MAX], devno[32];snprintf(p, sizeof p, "/sys/class/block/%s/dev", name);FILE *f = fopen(p, "re");unsigned ma = 0, mi = 0;int ok = f && fgets(devno, sizeof devno, f) && sscanf(devno, "%u:%u", &ma, &mi) == 2;if (f) fclose(f);- if (!ok) { admin_say("ERR", "no existe el dispositivo %s", name); return -1; }+ if (!ok) { admin_err("disk.noDevice", "name", name, NULL); return -1; }snprintf(t->name, sizeof t->name, "%s", name);t->part = disk_parent(name, t->disk, sizeof t->disk);if (!t->part) snprintf(t->disk, sizeof t->disk, "%s", name);- if (want == 1 && t->part) { admin_say("ERR", "%s es una partición: hace falta el disco entero", name); return -1; }- if (want == 2 && !t->part) { admin_say("ERR", "%s no es una partición", name); return -1; }+ if (want == 1 && t->part) { admin_err("disk.isPartition", "name", name, NULL); return -1; }+ if (want == 2 && !t->part) { admin_err("disk.notPartition", "name", name, NULL); return -1; }snprintf(t->dev, sizeof t->dev, "/dev/%s", name);struct stat st;if (lstat(t->dev, &st) || !S_ISBLK(st.st_mode) || major(st.st_rdev) != ma || minor(st.st_rdev) != mi) {- admin_say("ERR", "%s no es un dispositivo de bloque", t->dev);+ admin_err("disk.notBlock", "name", t->dev, NULL);return -1;}- if (!allow_system && disk_is_system(t->disk)) { admin_say("ERR", "%s es el disco del sistema: no se toca", t->disk); return -1; }+ if (!allow_system && disk_is_system(t->disk)) { admin_err("disk.systemDisk", "name", t->disk, NULL); return -1; }t->removable = disk_is_removable(t->disk);- if (!allow_system && !t->removable && !r->admin) { admin_say("ERR", "los discos internos los maneja un administrador (grupo sudo)"); return -1; }+ if (!allow_system && !t->removable && !r->admin) { admin_err("disk.internalNeedsAdmin", NULL); return -1; }t->size = disk_size(name);return 0;}@@ -143,7 +143,7 @@ static void job_end(const char *disk) {void disk_act_cancel(const AdminReq *r, const char *arg, size_t len) {(void)len;- if (!disk_valid_name(arg)) { admin_say("ERR", "dispositivo inválido"); return; }+ if (!disk_valid_name(arg)) { admin_err("disk.badDevice", NULL); return; }char p[96];job_path(arg, p, sizeof p);FILE *f = fopen(p, "re");@@ -151,16 +151,16 @@ void disk_act_cancel(const AdminReq *r, const char *arg, size_t len) {unsigned uid = 0;int ok = f && fscanf(f, "%d %u", &pid, &uid) == 2;if (f) fclose(f);- if (!ok || pid <= 1) { admin_say("ERR", "no hay nada en curso en %s", arg); return; }- if (uid != r->uid && !r->admin) { admin_say("ERR", "lo empezó otro usuario"); return; }+ if (!ok || pid <= 1) { admin_err("disk.nothingRunning", "name", arg, NULL); return; }+ if (uid != r->uid && !r->admin) { admin_err("disk.otherUser", NULL); return; }/* it must really be a helper child (lord-admin), not a recycled pid */char cp[64], comm[32] = "";snprintf(cp, sizeof cp, "/proc/%d/comm", pid);FILE *c = fopen(cp, "re");if (c) { if (!fgets(comm, sizeof comm, c)) comm[0] = 0; fclose(c); }- if (strncmp(comm, "lord-admin", 10)) { unlink(p); admin_say("ERR", "no hay nada en curso en %s", arg); return; }+ if (strncmp(comm, "lord-admin", 10)) { unlink(p); admin_err("disk.nothingRunning", "name", arg, NULL); return; }kill(pid, SIGTERM);- admin_say("OK", "cancelando");+ admin_ok("disk.cancelling", NULL);}/* ---- mounts ---- */@@ -174,13 +174,13 @@ static int unmount_dev(const char *name) {char mounts[4096];if (!disk_mounts(name, mounts, sizeof mounts)) return 0;for (char *m = strtok(mounts, "\n"); m; m = strtok(NULL, "\n")) {- if (!in_media(m)) { admin_say("ERR", "%s está montado en %s: desmontalo a mano", name, m); return -1; }+ if (!in_media(m)) { admin_err("disk.mountedElsewhere", "name", name, "path", m, NULL); return -1; }sync();if (umount2(m, UMOUNT_NOFOLLOW)) {- admin_say("ERR", errno == EBUSY ? "%s está en uso (hay archivos abiertos en %s)" : "no se pudo desmontar %s (%s)", name, m);+ { if (errno == EBUSY) admin_err("disk.busyFiles", "name", name, "path", m, NULL); else admin_err("disk.unmountFailed", "name", name, "errno", lerr_errno(errno), NULL); }return -1;}- admin_say("LOG", "desmontado %s", m);+ admin_log("disk.unmountedPath", "path", m, NULL);rmdir(m);}return 0;@@ -212,7 +212,7 @@ void disk_act_mount(const AdminReq *r, const char *arg, size_t len) {(void)len;Target t;if (target(r, arg, 0, 0, &t)) return;- if (disk_mounts(t.name, NULL, 0)) { admin_say("ERR", "%s ya está montado", t.name); return; }+ if (disk_mounts(t.name, NULL, 0)) { admin_err("disk.alreadyMounted", "name", t.name, NULL); return; }char fs[32], label[256], uuid[96];disk_udev_prop(t.name, "ID_FS_TYPE", fs, sizeof fs);disk_fs_label(t.name, label, sizeof label); /* sanitize_dir removes / and control characters */@@ -224,7 +224,7 @@ void disk_act_mount(const AdminReq *r, const char *arg, size_t len) {};int k = -1;for (size_t i = 0; i < sizeof kinds / sizeof *kinds; i++) if (!strcmp(fs, kinds[i].udev)) k = (int)i;- if (k < 0) { admin_say("ERR", fs[0] ? "no se sabe montar «%s»" : "%s no tiene un sistema de archivos conocido", fs[0] ? fs : t.name); return; }+ if (k < 0) { { if (fs[0]) admin_err("disk.cannotMountFs", "fs", fs, NULL); else admin_err("disk.unknownFs", "name", t.name, NULL); } return; }char base[96], dir[PATH_MAX], leaf[200];mkdir("/media", 0755);snprintf(base, sizeof base, "/media/%.64s", r->user);@@ -249,19 +249,19 @@ void disk_act_mount(const AdminReq *r, const char *arg, size_t len) {if (mount(t.dev, dir, kinds[k].kernel, flags, opts[0] ? opts : NULL)) {int e = errno;rmdir(dir);- admin_say("ERR", "no se pudo montar %s (%s)", t.name, strerror(e));+ admin_err("disk.mountFailed", "name", t.name, "errno", lerr_errno(e), NULL);return;}- admin_say("OK", "%s", dir);+ admin_say("OK", "%s", dir); /* i18n-ok */}void disk_act_unmount(const AdminReq *r, const char *arg, size_t len) {(void)len;Target t;if (target(r, arg, 0, 0, &t)) return;- if (t.part && !disk_mounts(t.name, NULL, 0)) { admin_say("ERR", "%s no está montado", t.name); return; }+ if (t.part && !disk_mounts(t.name, NULL, 0)) { admin_err("disk.notMounted", "name", t.name, NULL); return; }if (t.part ? unmount_dev(t.name) : unmount_disk(&t)) return;- admin_say("OK", "desmontado");+ admin_ok("disk.unmounted", NULL);}/* ---- SCSI / ATA ---- */@@ -312,12 +312,12 @@ void disk_act_smart(const AdminReq *r, const char *arg, size_t len) {Target t;if (target(r, arg, 1, 1, &t)) return; /* the system disk too: read only */if (strncmp(t.name, "sd", 2) && strncmp(t.name, "nvme", 4) && strncmp(t.name, "hd", 2)) {- admin_say("ERR", "este disco no informa SMART (%s)", t.name);+ admin_err("disk.noSmart", "name", t.name, NULL);return;}double t0 = now_s();int fd = open(t.dev, O_RDONLY | O_NONBLOCK | O_CLOEXEC);- if (fd < 0) { admin_say("ERR", "no se pudo abrir %s (%s)", t.dev, strerror(errno)); return; }+ if (fd < 0) { admin_err("disk.openFailed", "name", t.dev, "errno", lerr_errno(errno), NULL); return; }SmartReport rep;int ok;if (!strncmp(t.name, "nvme", 4)) {@@ -339,11 +339,11 @@ void disk_act_smart(const AdminReq *r, const char *arg, size_t len) {if (ok && !has_data) rep.nattr = 0;}close(fd);- if (!ok) { admin_say("ERR", "el disco no respondió a SMART (puede no tenerlo, o estar detrás de un adaptador USB que no lo deja pasar)"); return; }+ if (!ok) { admin_err("disk.smartNoReply", NULL); return; }char j[1024];- if (!smart_summary_json(&rep, j, sizeof j)) admin_say("LOG", "smart %s", j);- for (int i = 0; i < rep.nattr; i++) if (!smart_attr_json(&rep.attr[i], j, sizeof j)) admin_say("LOG", "attr %s", j);- admin_say("OK", "%.1f ms", (now_s() - t0) * 1000);+ if (!smart_summary_json(&rep, j, sizeof j)) admin_say("LOG", "smart %s", j); /* i18n-ok */+ for (int i = 0; i < rep.nattr; i++) if (!smart_attr_json(&rep.attr[i], j, sizeof j)) admin_say("LOG", "attr %s", j); /* i18n-ok */+ admin_say("OK", "%.1f ms", (now_s() - t0) * 1000); /* i18n-ok */}/* ---- writing to the device ---- */@@ -384,7 +384,7 @@ static int wipe_ends(int fd, uint64_t size) {static int open_excl(const Target *t, int extra) {int fd = open(t->dev, O_RDWR | O_EXCL | O_CLOEXEC | extra);- if (fd < 0) admin_say("ERR", errno == EBUSY ? "%s está en uso (montado o abierto por otro programa)" : "no se pudo abrir %s (%s)", t->name, strerror(errno));+ if (fd < 0) { if (errno == EBUSY) admin_err("disk.busy", "name", t->name, NULL); else admin_err("disk.openFailed", "name", t->name, "errno", lerr_errno(errno), NULL); }return fd;}@@ -450,9 +450,9 @@ void disk_act_format(const AdminReq *r, const char *arg, size_t len) {s = nl ? nl + 1 : NULL;if (nf == 2 && nl) { nf = -1; break; } /* too many lines */}- if (!buf || nf < 2) { admin_say("ERR", "argumento inválido"); free(buf); return; }+ if (!buf || nf < 2) { admin_err("admin.invalidArgument", NULL); free(buf); return; }char *name = f[0], fsname[16], lab[64];- if (strlen(f[1]) >= sizeof fsname || (f[2] && strlen(f[2]) >= sizeof lab)) { admin_say("ERR", "argumento inválido"); free(buf); return; }+ if (strlen(f[1]) >= sizeof fsname || (f[2] && strlen(f[2]) >= sizeof lab)) { admin_err("admin.invalidArgument", NULL); free(buf); return; }snprintf(fsname, sizeof fsname, "%s", f[1]);snprintf(lab, sizeof lab, "%s", f[2] ? f[2] : "");struct { const char *id, *prog; uint8_t type; } kinds[] = {@@ -461,9 +461,9 @@ void disk_act_format(const AdminReq *r, const char *arg, size_t len) {};int k = -1;for (int i = 0; i < 4; i++) if (!strcmp(fsname, kinds[i].id)) k = i;- if (k < 0) { admin_say("ERR", "sistema de archivos desconocido: %s", fsname); free(buf); return; }- if (access(kinds[k].prog, X_OK)) { admin_say("ERR", "falta %s", kinds[k].prog); free(buf); return; }- if (!valid_label(fsname, lab)) { admin_say("ERR", "etiqueta inválida para %s", fsname); free(buf); return; }+ if (k < 0) { admin_err("disk.unknownFsName", "fs", fsname, NULL); free(buf); return; }+ if (access(kinds[k].prog, X_OK)) { admin_err("disk.missingTool", "program", kinds[k].prog, NULL); free(buf); return; }+ if (!valid_label(fsname, lab)) { admin_err("disk.badLabelFor", "fs", fsname, NULL); free(buf); return; }Target t;if (target(r, name, 0, 0, &t)) { free(buf); return; }free(buf);@@ -473,12 +473,12 @@ void disk_act_format(const AdminReq *r, const char *arg, size_t len) {char dev[48];snprintf(dev, sizeof dev, "%s", t.dev);if (!t.part) {- admin_say("LOG", "progress phase=table");+ admin_say("LOG", "progress phase=table"); /* i18n-ok */int e = wipe_ends(fd, t.size);if (!e) e = write_mbr(fd, t.size, kinds[k].type);if (e) {close(fd);- admin_say("ERR", e == -2 ? "discos de más de 2 TiB: todavía no (hace falta GPT)" : e == -3 ? "el disco es demasiado chico" : "no se pudo escribir la tabla de particiones");+ admin_err(e == -2 ? "disk.tooLargeForMbr" : e == -3 ? "disk.tooSmall" : "disk.tableFailed", NULL);return;}fsync(fd);@@ -489,7 +489,7 @@ void disk_act_format(const AdminReq *r, const char *arg, size_t len) {ioctl(fd, LOOP_SET_STATUS64, &li);}}- if (ioctl(fd, BLKRRPART) && errno != EINVAL) admin_say("LOG", "aviso: el kernel no releyó la tabla (%s)", strerror(errno));+ if (ioctl(fd, BLKRRPART) && errno != EINVAL) admin_log("disk.rereadWarning", "errno", lerr_errno(errno), NULL);close(fd);settle();char pn[32], sp[PATH_MAX];@@ -499,15 +499,15 @@ void disk_act_format(const AdminReq *r, const char *arg, size_t len) {snprintf(dev, sizeof dev, "/dev/%s", pn);struct stat st;for (int i = 0; i < 50 && (stat(dev, &st) || !S_ISBLK(st.st_mode)); i++) usleep(100000);- if (stat(dev, &st) || !S_ISBLK(st.st_mode)) { admin_say("ERR", "no apareció la partición nueva %s", dev); return; }+ if (stat(dev, &st) || !S_ISBLK(st.st_mode)) { admin_err("disk.noNewPartition", "name", dev, NULL); return; }snprintf(t.name, sizeof t.name, "%s", pn);} else {int e = zero_range(fd, 0, t.size < MIB ? t.size : MIB); /* old signatures at the start */fsync(fd);close(fd);- if (e) { admin_say("ERR", "no se pudo escribir en %s", t.name); return; }+ if (e) { admin_err("disk.writeFailed", "name", t.name, NULL); return; }}- admin_say("LOG", "progress phase=mkfs");+ admin_say("LOG", "progress phase=mkfs"); /* i18n-ok */char owner[48];snprintf(owner, sizeof owner, "root_owner=%u:%u", (unsigned)r->uid, (unsigned)r->gid);int rc;@@ -527,39 +527,39 @@ void disk_act_format(const AdminReq *r, const char *arg, size_t len) {}uevent_change(t.name);settle();- if (rc) admin_say("ERR", "%s terminó con código %d", kinds[k].prog, rc);- else admin_say("OK", "%s", t.name);+ if (rc) admin_err("sys.programFailed", "program", kinds[k].prog, "code", lerr_int(rc), NULL);+ else admin_say("OK", "%s", t.name); /* i18n-ok */}void disk_act_label(const AdminReq *r, const char *arg, size_t len) {char *buf = strndup(arg, len), *name, *lab;- if (!buf || split2(buf, &name, &lab)) { admin_say("ERR", "argumento inválido"); free(buf); return; }+ if (!buf || split2(buf, &name, &lab)) { admin_err("admin.invalidArgument", NULL); free(buf); return; }Target t;if (target(r, name, 0, 0, &t)) { free(buf); return; }char fs[32], label[64];disk_udev_prop(t.name, "ID_FS_TYPE", fs, sizeof fs);- if (strlen(lab) >= sizeof label) { admin_say("ERR", "etiqueta inválida"); free(buf); return; }+ if (strlen(lab) >= sizeof label) { admin_err("disk.badLabel", NULL); free(buf); return; }snprintf(label, sizeof label, "%s", lab);free(buf);const char *prog = !strcmp(fs, "vfat") ? "/usr/sbin/fatlabel" : !strcmp(fs, "exfat") ? "/usr/sbin/exfatlabel": !strncmp(fs, "ext", 3) && strlen(fs) == 4 ? "/usr/sbin/e2label" : !strcmp(fs, "ntfs") ? "/usr/sbin/ntfslabel" : NULL;- if (!prog) { admin_say("ERR", "no se sabe renombrar «%s»", fs); return; }- if (access(prog, X_OK)) { admin_say("ERR", "falta %s", prog); return; }- if (!valid_label(fs, label)) { admin_say("ERR", "etiqueta inválida para %s", fs); return; }- if (strncmp(fs, "ext", 3) && disk_mounts(t.name, NULL, 0)) { admin_say("ERR", "desmontalo primero"); return; }+ if (!prog) { admin_err("disk.cannotRenameFs", "fs", fs, NULL); return; }+ if (access(prog, X_OK)) { admin_err("disk.missingTool", "program", prog, NULL); return; }+ if (!valid_label(fs, label)) { admin_err("disk.badLabelFor", "fs", fs, NULL); return; }+ if (strncmp(fs, "ext", 3) && disk_mounts(t.name, NULL, 0)) { admin_err("disk.unmountFirst", NULL); return; }const char *a[] = { prog, t.dev, label, NULL };int rc = admin_run(a);uevent_change(t.name);settle();- if (rc) admin_say("ERR", "%s terminó con código %d", prog, rc);- else admin_say("OK", "%s", label);+ if (rc) admin_err("sys.programFailed", "program", prog, "code", lerr_int(rc), NULL);+ else admin_say("OK", "%s", label); /* i18n-ok */}void disk_act_erase(const AdminReq *r, const char *arg, size_t len) {char *buf = strndup(arg, len), *name, *mode;- if (!buf || split2(buf, &name, &mode)) { admin_say("ERR", "argumento inválido"); free(buf); return; }+ if (!buf || split2(buf, &name, &mode)) { admin_err("admin.invalidArgument", NULL); free(buf); return; }int full = !strcmp(mode, "zero");- if (!full && strcmp(mode, "quick")) { admin_say("ERR", "modo inválido"); free(buf); return; }+ if (!full && strcmp(mode, "quick")) { admin_err("admin.invalidArgument", NULL); free(buf); return; }Target t;if (target(r, name, 0, 0, &t)) { free(buf); return; }free(buf);@@ -580,7 +580,7 @@ void disk_act_erase(const AdminReq *r, const char *arg, size_t len) {if (now_s() - last > 0.5 || off == t.size) {last = now_s();fdatasync(fd); /* real progress, and don't fill the page cache */- admin_say("LOG", "progress phase=erase done=%llu total=%llu", (unsigned long long)off, (unsigned long long)t.size);+ admin_say("LOG", "progress phase=erase done=%llu total=%llu", (unsigned long long)off, (unsigned long long)t.size); /* i18n-ok */}}job_end(t.disk);@@ -590,9 +590,9 @@ void disk_act_erase(const AdminReq *r, const char *arg, size_t len) {close(fd);uevent_change(t.name);settle();- if (cancelled) admin_say("ERR", "cancelado");- else if (e) admin_say("ERR", "no se pudo escribir en %s (%s)", t.name, strerror(errno));- else admin_say("OK", "borrado");+ if (cancelled) admin_err("disk.cancelled", NULL);+ else if (e) admin_err("disk.writeFailed", "name", t.name, "errno", lerr_errno(errno), NULL);+ else admin_ok("disk.erased", NULL);}/* ---- image → disk ---- */@@ -634,22 +634,22 @@ static ssize_t read_full(int fd, uint8_t *b, size_t n) {void disk_act_write_image(const AdminReq *r, const char *arg, size_t len) {char *buf = strndup(arg, len), *name, *path;- if (!buf || split2(buf, &name, &path)) { admin_say("ERR", "argumento inválido"); free(buf); return; }+ if (!buf || split2(buf, &name, &path)) { admin_err("admin.invalidArgument", NULL); free(buf); return; }Target t;if (target(r, name, 1, 0, &t)) { free(buf); return; }struct stat st;int in = open_image(r, path, &st);free(buf);- if (in < 0) { admin_say("ERR", "no se pudo abrir la imagen (tiene que ser un archivo de tu carpeta o de tus discos)"); return; }+ if (in < 0) { admin_err("disk.imageOpenFailed", NULL); return; }uint64_t total = (uint64_t)st.st_size;- if (total > t.size) { close(in); admin_say("ERR", "la imagen (%llu bytes) no entra en %s (%llu bytes)", (unsigned long long)total, t.name, (unsigned long long)t.size); return; }+ if (total > t.size) { close(in); admin_err("disk.imageTooLarge", "name", t.name, "size", lerr_int((long long)total), "capacity", lerr_int((long long)t.size), NULL); return; }{ /* the image cannot be on the same disk */char dn[32] = "", base[32] = "";char p[64], real[PATH_MAX];snprintf(p, sizeof p, "/sys/dev/block/%u:%u", major(st.st_dev), minor(st.st_dev));if (realpath(p, real) && strrchr(real, '/')) snprintf(dn, sizeof dn, "%s", strrchr(real, '/') + 1);if (dn[0] && !disk_parent(dn, base, sizeof base)) snprintf(base, sizeof base, "%s", dn);- if (base[0] && !strcmp(base, t.disk)) { close(in); admin_say("ERR", "la imagen está en el mismo disco que se va a borrar"); return; }+ if (base[0] && !strcmp(base, t.disk)) { close(in); admin_err("disk.imageOnTarget", NULL); return; }}if (unmount_disk(&t)) { close(in); return; }int out = open_excl(&t, O_DIRECT);@@ -660,7 +660,7 @@ void disk_act_write_image(const AdminReq *r, const char *arg, size_t len) {posix_fadvise(in, 0, 0, POSIX_FADV_SEQUENTIAL);const size_t CH = 4 * MIB;uint8_t *b = NULL;- if (posix_memalign((void **)&b, 4096, CH)) { close(in); close(out); job_end(t.disk); admin_say("ERR", "sin memoria"); return; }+ if (posix_memalign((void **)&b, 4096, CH)) { close(in); close(out); job_end(t.disk); admin_err("sys.outOfMemory", NULL); return; }Sha256 hs;sha256_init(&hs);uint64_t off = 0;@@ -683,7 +683,7 @@ void disk_act_write_image(const AdminReq *r, const char *arg, size_t len) {off += (uint64_t)k;if (now_s() - last > 0.5 || off == total) {last = now_s();- admin_say("LOG", "progress phase=write done=%llu total=%llu", (unsigned long long)off, (unsigned long long)total);+ admin_say("LOG", "progress phase=write done=%llu total=%llu", (unsigned long long)off, (unsigned long long)total); /* i18n-ok */}}close(in);@@ -709,7 +709,7 @@ void disk_act_write_image(const AdminReq *r, const char *arg, size_t len) {o += want_n;if (now_s() - last > 0.5 || o == total) {last = now_s();- admin_say("LOG", "progress phase=verify done=%llu total=%llu", (unsigned long long)o, (unsigned long long)total);+ admin_say("LOG", "progress phase=verify done=%llu total=%llu", (unsigned long long)o, (unsigned long long)total); /* i18n-ok */}}sha256_final(&hv, got);@@ -721,12 +721,17 @@ void disk_act_write_image(const AdminReq *r, const char *arg, size_t len) {settle();char hex[65];hex_encode(want, 32, hex);- if (cancelled) admin_say("ERR", "cancelado: el disco quedó a medio escribir");- else if (err == 1) admin_say("ERR", "no se pudo leer la imagen");- else if (err == 2) admin_say("ERR", "no se pudo escribir en %s (%s)", t.name, strerror(errno));- else if (err == 3) admin_say("ERR", "no se pudo releer %s para verificar", t.name);- else if (memcmp(want, got, 32)) admin_say("ERR", "la verificación falló: lo que quedó en el disco no es igual a la imagen");- else admin_say("OK", "verificado sha256=%s ms=%.0f mbps=%.1f", hex, tw * 1000, tw > 0 ? total / tw / 1e6 : 0);+ if (cancelled) admin_err("disk.cancelledPartial", NULL);+ else if (err == 1) admin_err("disk.imageReadFailed", NULL);+ else if (err == 2) admin_err("disk.writeFailed", "name", t.name, "errno", lerr_errno(errno), NULL);+ else if (err == 3) admin_err("disk.verifyReadFailed", "name", t.name, NULL);+ else if (memcmp(want, got, 32)) admin_err("disk.verifyMismatch", NULL);+ else {+ char ms[24], mbps[24];+ snprintf(ms, sizeof ms, "%.0f", tw * 1000);+ snprintf(mbps, sizeof mbps, "%.1f", tw > 0 ? total / tw / 1e6 : 0);+ admin_ok("disk.verified", "sha256", hex, "ms", ms, "mbps", mbps, NULL);+ }}/* ---- eject ---- */@@ -739,7 +744,7 @@ void disk_act_eject(const AdminReq *r, const char *arg, size_t len) {sync();/* nobody else holds it exclusively (an erase or a copy in progress) */int ex = open(t.dev, O_RDONLY | O_EXCL | O_NONBLOCK | O_CLOEXEC);- if (ex < 0 && errno == EBUSY) { admin_say("ERR", "%s está en uso: esperá a que termine lo que está haciendo", t.name); return; }+ if (ex < 0 && errno == EBUSY) { admin_err("disk.busyWait", "name", t.name, NULL); return; }if (ex >= 0) close(ex);int fd = open(t.dev, O_RDONLY | O_NONBLOCK | O_CLOEXEC);if (fd >= 0) {@@ -761,5 +766,5 @@ void disk_act_eject(const AdminReq *r, const char *arg, size_t len) {int d = open(p, O_WRONLY | O_CLOEXEC);if (d >= 0) { if (write(d, "1", 1) < 0) { /* keep going */ } close(d); }}- admin_say("OK", "expulsado");+ admin_ok("disk.ejected", NULL);}diff --git a/server/src/errcode.h b/server/src/errcode.hnew file mode 100644index 0000000..a2b3179--- /dev/null+++ b/server/src/errcode.h@@ -0,0 +1,149 @@+/* errcode.h — stable, translatable error and status codes (header only).+ *+ * Nothing that reaches the UI is prose: C code reports a *code line* and the UI translates it+ * with t('errors.<code>', params) (sdk/errors.js). Logs and the journal stay English prose.+ *+ * code line := code (' ' key '=' value)*+ * code := [a-z][a-zA-Z0-9]* ('.' [a-zA-Z0-9]+)+ e.g. pkg.removeEssential+ * key := [a-zA-Z][a-zA-Z0-9]*+ * value := any bytes; '%', ' ', '=', '"' and bytes < 0x20 or 0x7f are written as %XX+ *+ * char err[256];+ * lerr_set(err, sizeof err, "pkg.removeEssential", "name", n->name, NULL);+ * → "pkg.removeEssential name=dpkg"+ * lerr_set(err, sizeof err, "fs.readFailed", "path", p, "errno", lerr_errno(errno), NULL);+ *+ * Two parameter names have a meaning for the UI:+ * errno=ENOENT replaced by the translated description of that errno (errors.errno.ENOENT);+ * reason=<line> a nested code line, translated too ("could not install: <reason>").+ * The locale strings live in assets/locales/<lang>/errors.json (status.json for OK/LOG+ * statuses); tools/i18n-check.mjs checks that every code used here has an English string. */+#ifndef LORD_ERRCODE_H+#define LORD_ERRCODE_H++#include <errno.h>+#include <stdarg.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>++/* Is s[0..n) a valid code? */+static inline int lerr_valid_code(const char *s, size_t n)+{+ if (!n || s[0] < 'a' || s[0] > 'z') return 0;+ int dots = 0, seg = 0;+ for (size_t i = 0; i < n; i++) {+ char ch = s[i];+ if (ch == '.') { if (!seg) return 0; dots++; seg = 0; continue; }+ if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9'))) return 0;+ seg++;+ }+ return dots > 0 && seg > 0;+}++/* Does the line start with a code (followed by a space or the end)? */+static inline int lerr_is(const char *line)+{+ if (!line) return 0;+ size_t n = strcspn(line, " ");+ return lerr_valid_code(line, n);+}++/* Is the line's code exactly `code`? (tests and C consumers match on this, never on prose) */+static inline int lerr_has(const char *line, const char *code)+{+ if (!line || !code) return 0;+ size_t n = strlen(code);+ return !strncmp(line, code, n) && (line[n] == 0 || line[n] == ' ') && lerr_is(line);+}++static inline size_t lerr__put(char *out, size_t cap, size_t at, const char *s, int encode)+{+ static const char hex[] = "0123456789ABCDEF";+ for (; s && *s; s++) {+ unsigned char ch = (unsigned char)*s;+ int esc = encode && (ch < 0x20 || ch == 0x7f || ch == '%' || ch == ' ' || ch == '=' || ch == '"');+ size_t need = esc ? 3 : 1;+ if (at + need >= cap) return (size_t)-1;+ if (esc) { out[at++] = '%'; out[at++] = hex[ch >> 4]; out[at++] = hex[ch & 15]; }+ else out[at++] = (char)ch;+ }+ return at;+}++/* Writes "code k=v k=v" into out; the arguments after code are (key, value) pairs ending in NULL.+ * A NULL value is written as empty. A parameter that does not fit is dropped (the code always is+ * kept). Returns out. */+static inline const char *lerr_vset(char *out, size_t cap, const char *code, va_list ap)+{+ if (!out || !cap) return out;+ size_t at = lerr__put(out, cap, 0, code, 0);+ if (at == (size_t)-1) { snprintf(out, cap, "%s", code); return out; }+ for (;;) {+ const char *k = va_arg(ap, const char *);+ if (!k) break;+ const char *v = va_arg(ap, const char *);+ size_t a = lerr__put(out, cap, at, " ", 0);+ if (a != (size_t)-1) a = lerr__put(out, cap, a, k, 0);+ if (a != (size_t)-1) a = lerr__put(out, cap, a, "=", 0);+ if (a != (size_t)-1) a = lerr__put(out, cap, a, v ? v : "", 1);+ if (a != (size_t)-1) at = a;+ }+ out[at] = 0;+ return out;+}++__attribute__((sentinel))+static inline const char *lerr_set(char *out, size_t cap, const char *code, ...)+{+ va_list ap;+ va_start(ap, code);+ lerr_vset(out, cap, code, ap);+ va_end(ap);+ return out;+}++/* A number as a parameter value: lerr_set(err, n, "pkg.tooMany", "count", lerr_int(n), NULL).+ * Rotating per-thread buffers: valid for the next 7 calls. */+static inline const char *lerr_int(long long v)+{+ static _Thread_local char buf[8][24];+ static _Thread_local unsigned next;+ char *b = buf[next++ & 7];+ snprintf(b, sizeof buf[0], "%lld", v);+ return b;+}++/* errno as a parameter value ("ENOENT"); the UI shows its translated description. */+static inline const char *lerr_errno(int e)+{+#if defined(__GLIBC__) && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 32))+ const char *n = strerrorname_np(e);+ if (n) return n;+#endif+ return lerr_int(e);+}++/* Decoded value of parameter `key` of a code line into out; returns out, or NULL if it is not there. */+static inline const char *lerr_param(const char *line, const char *key, char *out, size_t cap)+{+ if (!line || !key || !out || !cap || !lerr_is(line)) return NULL;+ size_t kl = strlen(key);+ for (const char *p = strchr(line, ' '); p; p = strchr(p + 1, ' ')) {+ if (strncmp(p + 1, key, kl) || p[1 + kl] != '=') continue;+ const char *v = p + 2 + kl;+ size_t o = 0;+ for (; *v && *v != ' ' && o + 1 < cap; v++) {+ if (v[0] == '%' && v[1] && v[2]) {+ char h[3] = { v[1], v[2], 0 };+ out[o++] = (char)strtol(h, NULL, 16);+ v += 2;+ } else out[o++] = *v;+ }+ out[o] = 0;+ return out;+ }+ return NULL;+}++#endifdiff --git a/server/src/fsops.c b/server/src/fsops.cindex f001eb5..e641128 100644--- a/server/src/fsops.c+++ b/server/src/fsops.c@@ -16,6 +16,7 @@* depth, and without following links. */#include "fsops.h"+#include "errcode.h"#include <ctype.h>#include <dirent.h>@@ -79,7 +80,9 @@ int fsops_protected(const char *real) {static double now_ms(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec * 1e3 + t.tv_nsec / 1e6; }-static void seterr(char *e, size_t n, const char *m) { if (e && n) pathf(e, n, "%s", m); }+/* err buffers carry code lines (errcode.h): lord.fs throws them translated */+static void seterr(char *e, size_t n, const char *code) { if (e && n) lerr_set(e, n, code, NULL); }+static void seterrno(char *e, size_t n, int no) { if (e && n) lerr_set(e, n, "sys.errno", "errno", lerr_errno(no), NULL); }/* ---- deleting a tree (only used by cross-disk move and the trash) ---- */@@ -186,11 +189,11 @@ static void *job_main(void *arg) {walk_total(j->src, j, 0);int r = copy_tree(j->src, j->dst, j, 0);if (r) {- pathf(j->error, sizeof j->error, "%s", strerror(errno));+ seterrno(j->error, sizeof j->error, errno);rm_tree(j->dst); /* no half-done copies */j->failed = 1;} else if (j->move && rm_tree(j->src)) {- pathf(j->error, sizeof j->error, "copied, but the original could not be removed: %s", strerror(errno));+ lerr_set(j->error, sizeof j->error, "fs.moveRemoveFailed", "errno", lerr_errno(errno), NULL);j->failed = 1;}__atomic_store_n(&j->done, 1, __ATOMIC_RELEASE);@@ -199,13 +202,13 @@ static void *job_main(void *arg) {int fsjob_start(const char *src, const char *dst, int move, char *err, size_t errlen) {struct stat st;- if (lstat(src, &st)) { seterr(err, errlen, strerror(errno)); return -1; }- if (!lstat(dst, &st)) { seterr(err, errlen, "already exists"); return -1; }+ if (lstat(src, &st)) { seterrno(err, errlen, errno); return -1; }+ if (!lstat(dst, &st)) { seterr(err, errlen, "fs.exists"); return -1; }size_t n = strlen(src);- if (!strncmp(dst, src, n) && dst[n] == '/') { seterr(err, errlen, "cannot copy a folder into itself"); return -1; }+ if (!strncmp(dst, src, n) && dst[n] == '/') { seterr(err, errlen, "fs.copyIntoItself"); return -1; }FsJob *j = NULL;for (int i = 0; i < FSJOB_MAX; i++) if (!jobs[i].used) { j = &jobs[i]; break; }- if (!j) { seterr(err, errlen, "too many copies in progress"); return -1; }+ if (!j) { seterr(err, errlen, "fs.tooManyCopies"); return -1; }memset(j, 0, sizeof *j);j->used = 1;j->id = next_job++;@@ -213,12 +216,12 @@ int fsjob_start(const char *src, const char *dst, int move, char *err, size_t erpathf(j->src, sizeof j->src, "%s", src);pathf(j->dst, sizeof j->dst, "%s", dst);if (move && rename(src, dst) == 0) { j->done = 1; return j->id; } /* same disk: instant */- if (move && errno != EXDEV) { int e = errno; j->used = 0; seterr(err, errlen, strerror(e)); return -1; }+ if (move && errno != EXDEV) { int e = errno; j->used = 0; seterrno(err, errlen, e); return -1; }pthread_t t;pthread_attr_t a;pthread_attr_init(&a);pthread_attr_setdetachstate(&a, PTHREAD_CREATE_DETACHED);- if (pthread_create(&t, &a, job_main, j)) { j->used = 0; seterr(err, errlen, "could not start the copy"); pthread_attr_destroy(&a); return -1; }+ if (pthread_create(&t, &a, job_main, j)) { j->used = 0; seterr(err, errlen, "fs.copyStartFailed"); pthread_attr_destroy(&a); return -1; }pthread_attr_destroy(&a);return j->id;}@@ -301,8 +304,8 @@ static void url_decode(const char *s, char *out, size_t n) {int fstrash_put(const char *real, char *err, size_t errlen) {char dir[PATH_MAX], top[PATH_MAX];int rel;- if (trash_dir_for(real, dir, sizeof dir, top, sizeof top, &rel) || mkdirs_trash(dir)) { seterr(err, errlen, "there is no trash for that location"); return -1; }- if (!strncmp(real, dir, strlen(dir))) { seterr(err, errlen, "already in the Trash"); return -1; }+ if (trash_dir_for(real, dir, sizeof dir, top, sizeof top, &rel) || mkdirs_trash(dir)) { seterr(err, errlen, "fs.noTrash"); return -1; }+ if (!strncmp(real, dir, strlen(dir))) { seterr(err, errlen, "fs.alreadyInTrash"); return -1; }const char *base = strrchr(real, '/');base = base ? base + 1 : real;char name[NAME_MAX + 16], info[PATH_MAX + 300], dest[PATH_MAX + 300];@@ -317,7 +320,7 @@ int fstrash_put(const char *real, char *err, size_t errlen) {fd = open(info, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0600);if (fd < 0 && errno != EEXIST) break;}- if (fd < 0) { seterr(err, errlen, "could not create the Trash entry"); return -1; }+ if (fd < 0) { seterr(err, errlen, "fs.trashEntryFailed"); return -1; }char path[PATH_MAX * 3], enc[PATH_MAX * 3], when[32];pathf(path, sizeof path, "%s", rel ? real + strlen(top) + 1 : real);url_encode(path, enc, sizeof enc);@@ -330,7 +333,8 @@ int fstrash_put(const char *real, char *err, size_t errlen) {if (rename(real, dest)) {int e = errno;unlink(info);- seterr(err, errlen, e == EXDEV ? "it is on a different disk than its trash" : strerror(e));+ seterr(err, errlen, e == EXDEV ? "fs.trashOtherDisk" : "sys.errno");+ if (e != EXDEV) seterrno(err, errlen, e);return -1;}return 0;@@ -435,22 +439,22 @@ static int trash_id(const char *id, char *dir, size_t dn, char *name, size_t nn)int fstrash_restore(const char *id, char *err, size_t errlen) {char dir[PATH_MAX], name[NAME_MAX + 16], orig[PATH_MAX * 2], date[64];if (trash_id(id, dir, sizeof dir, name, sizeof name) || read_info(dir, name, orig, sizeof orig, date, sizeof date) || !orig[0]) {- seterr(err, errlen, "not in the Trash");+ seterr(err, errlen, "fs.notInTrash");return -1;}/* the original folder must still exist, inside the roots and unprotected */char parent[PATH_MAX * 2], rparent[PATH_MAX];pathf(parent, sizeof parent, "%s", orig);char *sl = strrchr(parent, '/');- if (!sl) { seterr(err, errlen, "invalid original location"); return -1; }+ if (!sl) { seterr(err, errlen, "fs.trashBadOrigin"); return -1; }*sl = 0;- if (!realpath(parent[0] ? parent : "/", rparent) || !fsops_allowed(rparent)) { seterr(err, errlen, "the original folder no longer exists"); return -1; }+ if (!realpath(parent[0] ? parent : "/", rparent) || !fsops_allowed(rparent)) { seterr(err, errlen, "fs.trashOriginGone"); return -1; }char dest[PATH_MAX * 2];pathf(dest, sizeof dest, "%s/%s", rparent, sl + 1);- if (fsops_protected(dest)) { seterr(err, errlen, "that folder is protected"); return -1; }+ if (fsops_protected(dest)) { seterr(err, errlen, "fs.protected"); return -1; }struct stat st;- if (!lstat(dest, &st)) { seterr(err, errlen, "there is already a file with that name in the original location"); return -1; }- if (rename(id, dest)) { seterr(err, errlen, strerror(errno)); return -1; }+ if (!lstat(dest, &st)) { seterr(err, errlen, "fs.trashRestoreExists"); return -1; }+ if (rename(id, dest)) { seterrno(err, errlen, errno); return -1; }char info[PATH_MAX * 2];pathf(info, sizeof info, "%s/info/%s.trashinfo", dir, name);unlink(info);@@ -459,8 +463,8 @@ int fstrash_restore(const char *id, char *err, size_t errlen) {int fstrash_remove(const char *id, char *err, size_t errlen) {char dir[PATH_MAX], name[NAME_MAX + 16];- if (trash_id(id, dir, sizeof dir, name, sizeof name)) { seterr(err, errlen, "not in the Trash"); return -1; }- if (rm_tree(id)) { seterr(err, errlen, strerror(errno)); return -1; }+ if (trash_id(id, dir, sizeof dir, name, sizeof name)) { seterr(err, errlen, "fs.notInTrash"); return -1; }+ if (rm_tree(id)) { seterrno(err, errlen, errno); return -1; }char info[PATH_MAX * 2];pathf(info, sizeof info, "%s/info/%s.trashinfo", dir, name);unlink(info);diff --git a/server/src/fw/rules.c b/server/src/fw/rules.cindex 4738cd3..280d56e 100644--- a/server/src/fw/rules.c+++ b/server/src/fw/rules.c@@ -927,7 +927,7 @@ static int load_doc(FwStore *t, const JVal *root, char *err, size_t errlen) {const char *app = jstr(k, FW_APP_MAX);char c[FW_APP_MAX];if (!app || fw_app_canon(app, c, sizeof c) || strcmp(app, c)) return jerr(err, errlen, "trusted %d: invalid app", i);- if (fw_is_trusted(t, c)) return jerr(err, errlen, "trusted %d: repetida", i);+ if (fw_is_trusted(t, c)) return jerr(err, errlen, "trusted %d: repeated", i);if (fw_set_trusted(t, c, 1)) return jerr(err, errlen, "trusted %d: doesn't fit", i);}}diff --git a/server/src/gpu/gpu.c b/server/src/gpu/gpu.cindex 3ba05c1..c319368 100644--- a/server/src/gpu/gpu.c+++ b/server/src/gpu/gpu.c@@ -1,18 +1,18 @@-/* gpu.c — composición por GPU de lord-server: GBM + EGL + GLES2 de Mesa (aprobado por el- * usuario el 2026-10-16; ver docs/GPU.md).+/* gpu.c — lord-server's GPU composition: Mesa's GBM + EGL + GLES2 (approved by the+ * user on 2026-10-16; see docs/GPU.md).*- * El modesetting sigue siendo el propio (kms.c, ioctls sin libdrm): GBM se crea sobre el mismo- * fd de la tarjeta y sus búferes pasan a framebuffers con DRM_IOCTL_MODE_ADDFB2.+ * Modesetting is still our own (kms.c, ioctls without libdrm): GBM is created on the same+ * card fd and its buffers become framebuffers with DRM_IOCTL_MODE_ADDFB2.*- * Cada cuadro: la UI de LordOS (el canvas que pinta la CPU) es una textura de pantalla completa a- * la que solo se le sube lo que cambió. Debajo se dibujan las ventanas de las apps (texturas de- * sus búferes shm o dmabuf, sin pasar por la CPU) y encima los menús de las apps; donde hay una- * ventana de app, la UI deja un hueco transparente (alfa 0). Una app a pantalla completa con un- * búfer compatible va directo al plano primario: cero copias (gpu_scanout).+ * Each frame: the LordOS UI (the canvas the CPU paints) is a fullscreen texture to which+ * only what changed is uploaded. App windows are drawn below it (textures of their shm or+ * dmabuf buffers, without going through the CPU) and app menus on top; where there is an+ * app window, the UI leaves a transparent hole (alpha 0). A fullscreen app with a compatible+ * buffer goes straight to the primary plane: zero copies (gpu_scanout).*- * Por defecto se activa solo con una GPU de verdad: con un renderer por software (llvmpipe,- * softpipe) el camino por CPU propio es más rápido. LORD_GPU=1 lo fuerza (pruebas), LORD_GPU=0- * lo apaga, LORD_GPU_DEBUG=1 cuenta qué hace. Compilado sin Mesa (sin -DLORD_GPU) son stubs. */+ * By default it only turns on with a real GPU: with a software renderer (llvmpipe,+ * softpipe) our own CPU path is faster. LORD_GPU=1 forces it (tests), LORD_GPU=0+ * turns it off, LORD_GPU_DEBUG=1 reports what it does. Built without Mesa (no -DLORD_GPU) these are stubs. */#include "gpu.h"#include "../outputs.h"@@ -58,8 +58,8 @@ int gpu_can_scanout(const GpuDmabuf *d, int w, int h) { (void)d; (void)w; (void#include <drm/virtgpu_drm.h>#include <sys/ioctl.h>-/* ¿La placa tiene aceleración 3D? Se pregunta al kernel antes de cargar Mesa, así una máquina- * sin GPU (o una VM sin virgl) no carga llvmpipe para nada. */+/* Does the card have 3D acceleration? The kernel is asked before loading Mesa, so a machine+ * without a GPU (or a VM without virgl) does not load llvmpipe for nothing. */static int drm_accelerated(int fd, char *name, size_t n) {struct drm_version v;memset(&v, 0, sizeof v);@@ -85,9 +85,9 @@ struct GpuTex {EGLImageKHR image;};-/* Qué hay en pantalla (o en camino): un BO del gbm_surface o un dmabuf de una app. */+/* What is on screen (or on its way): a BO of the gbm_surface or an app's dmabuf. */typedef struct {- int kind; /* 0 nada, 1 BO de GBM, 2 scanout directo */+ int kind; /* 0 nothing, 1 GBM BO, 2 direct scanout */struct gbm_bo *bo;uint32_t fb, handles[4];void (*done)(void *);@@ -146,9 +146,9 @@ static int has_ext(const char *list, const char *ext) {return 0;}-/* El render node que usa EGL (EGL_EXT_device_query + EGL_EXT_device_drm_render_node). En las- * placas con pantalla y GPU separadas (Raspberry Pi 4/5: vc4 + v3d; muchos ARM con kmsro) no es- * el de la tarjeta de la pantalla, y es el que las apps tienen que usar para sus búferes. */+/* The render node EGL uses (EGL_EXT_device_query + EGL_EXT_device_drm_render_node). On+ * boards with separate display and GPU (Raspberry Pi 4/5: vc4 + v3d; many ARM boards with kmsro) it is+ * not the display card's, and it is the one apps have to use for their buffers. */#ifndef EGL_DRM_RENDER_NODE_FILE_EXT# define EGL_DRM_RENDER_NODE_FILE_EXT 0x3377#endif@@ -272,7 +272,7 @@ static uint32_t fb_for_bo(struct gbm_bo *bo) {mod, &fb) &&kms_add_fb2(G.k, gbm_bo_get_width(bo), gbm_bo_get_height(bo), gbm_bo_get_format(bo), handles, pitches, offsets,DRM_FORMAT_MOD_INVALID, &fb)) {- fprintf(stderr, "gpu: ADDFB2 del BO falló (%s)\n", strerror(errno));+ fprintf(stderr, "gpu: ADDFB2 of the BO failed (%s)\n", strerror(errno));return 0;}gbm_bo_set_user_data(bo, (void *)(uintptr_t)fb, bo_fb_destroy);@@ -358,7 +358,7 @@ int gpu_add_output(Kms *k) {return -1;}-/* ---- inicio ---- */+/* ---- startup ---- */int gpu_active(void) { return G.on; }const char *gpu_renderer(void) { return G.renderer; }@@ -366,19 +366,19 @@ const char *gpu_renderer(void) { return G.renderer; }int gpu_init(Kms *k) {const char *env = getenv("LORD_GPU");G.debug = getenv("LORD_GPU_DEBUG") != NULL;- if (env && !strcmp(env, "0")) { fprintf(stderr, "gpu: apagado (LORD_GPU=0), composición por CPU\n"); return -1; }+ if (env && !strcmp(env, "0")) { fprintf(stderr, "gpu: off (LORD_GPU=0), CPU composition\n"); return -1; }G.k = k;char drv[64];if (!drm_accelerated(k->fd, drv, sizeof drv) && !(env && !strcmp(env, "1"))) {- fprintf(stderr, "gpu: la placa (%s) no tiene aceleración 3D: composición por CPU (LORD_GPU=1 lo fuerza)\n", drv);+ fprintf(stderr, "gpu: the card (%s) has no 3D acceleration: CPU composition (LORD_GPU=1 forces it)\n", drv);return -1;}G.gbm = gbm_create_device(k->fd);- if (!G.gbm) { fprintf(stderr, "gpu: sin GBM en la tarjeta, composición por CPU\n"); return -1; }+ if (!G.gbm) { fprintf(stderr, "gpu: no GBM on the card, CPU composition\n"); return -1; }PFNEGLGETPLATFORMDISPLAYEXTPROC get_display = (PFNEGLGETPLATFORMDISPLAYEXTPROC)eglGetProcAddress("eglGetPlatformDisplayEXT");G.dpy = get_display ? get_display(EGL_PLATFORM_GBM_KHR, G.gbm, NULL) : eglGetDisplay((EGLNativeDisplayType)G.gbm);EGLint maj, min;- if (G.dpy == EGL_NO_DISPLAY || !eglInitialize(G.dpy, &maj, &min)) { fprintf(stderr, "gpu: EGL no arrancó, composición por CPU\n"); goto fail; }+ if (G.dpy == EGL_NO_DISPLAY || !eglInitialize(G.dpy, &maj, &min)) { fprintf(stderr, "gpu: EGL did not start, CPU composition\n"); goto fail; }const char *exts = eglQueryString(G.dpy, EGL_EXTENSIONS);query_render_node();eglBindAPI(EGL_OPENGL_ES_API);@@ -391,23 +391,23 @@ int gpu_init(Kms *k) {EGLint vid = 0;if (eglGetConfigAttrib(G.dpy, cfgs[i], EGL_NATIVE_VISUAL_ID, &vid) && vid == GBM_FORMAT_XRGB8888) cfg = cfgs[i];}- if (!cfg) { fprintf(stderr, "gpu: sin configuración XRGB8888 de EGL, composición por CPU\n"); goto fail; }+ if (!cfg) { fprintf(stderr, "gpu: no XRGB8888 EGL config, CPU composition\n"); goto fail; }static const EGLint ctx_attr[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE };G.ctx = eglCreateContext(G.dpy, cfg, EGL_NO_CONTEXT, ctx_attr);G.cfg = cfg;- if (G.ctx == EGL_NO_CONTEXT || out_setup(&G.out[0], k)) { fprintf(stderr, "gpu: could not create the context or the surface, composing by CPU\n"); goto fail; }+ if (G.ctx == EGL_NO_CONTEXT || out_setup(&G.out[0], k)) { fprintf(stderr, "gpu: could not create the context or the surface, CPU composition\n"); goto fail; }const char *rend = (const char *)glGetString(GL_RENDERER), *gl_exts = (const char *)glGetString(GL_EXTENSIONS);snprintf(G.renderer, sizeof G.renderer, "%s", rend ? rend : "?");int software = strstr(G.renderer, "llvmpipe") || strstr(G.renderer, "softpipe") || strstr(G.renderer, "swrast");if (software && !(env && !strcmp(env, "1"))) {- fprintf(stderr, "gpu: el renderer es por software (%s): composición por CPU (LORD_GPU=1 lo fuerza)\n", G.renderer);+ fprintf(stderr, "gpu: the renderer is software (%s): CPU composition (LORD_GPU=1 forces it)\n", G.renderer);goto fail;}G.bgra = has_ext(gl_exts, "GL_EXT_texture_format_BGRA8888");G.have_external = has_ext(gl_exts, "GL_OES_EGL_image_external");- if (!has_ext(gl_exts, "GL_EXT_unpack_subimage")) dbg("sin GL_EXT_unpack_subimage: se sube el canvas entero");- if (make_prog(0, fs_2d) || (G.have_external && make_prog(1, fs_ext))) { fprintf(stderr, "gpu: shaders, composición por CPU\n"); goto fail; }+ if (!has_ext(gl_exts, "GL_EXT_unpack_subimage")) dbg("no GL_EXT_unpack_subimage: the whole canvas is uploaded");+ if (make_prog(0, fs_2d) || (G.have_external && make_prog(1, fs_ext))) { fprintf(stderr, "gpu: shaders failed, CPU composition\n"); goto fail; }if (has_ext(exts, "EGL_EXT_image_dma_buf_import")) {G.create_image = (PFNEGLCREATEIMAGEKHRPROC)eglGetProcAddress("eglCreateImageKHR");G.destroy_image = (PFNEGLDESTROYIMAGEKHRPROC)eglGetProcAddress("eglDestroyImageKHR");@@ -426,11 +426,11 @@ int gpu_init(Kms *k) {if (G.debug) {GpuFormat f[64];int nf = gpu_formats(f, 64);- for (int i = 0; i < nf; i++) dbg("formato dmabuf %08x mod %llx", f[i].fourcc, (unsigned long long)f[i].modifier);+ for (int i = 0; i < nf; i++) dbg("dmabuf format %08x mod %llx", f[i].fourcc, (unsigned long long)f[i].modifier);}- fprintf(stderr, "gpu: composición por GPU (%s, EGL %d.%d, dmabuf %s, render %s, pantalla %s)\n", G.renderer, maj, min,- G.create_image ? (G.query_modifiers ? "con modificadores" : "sí") : "no",- G.render_node[0] ? G.render_node : "el de la tarjeta", k->driver[0] ? k->driver : drv);+ fprintf(stderr, "gpu: GPU composition (%s, EGL %d.%d, dmabuf %s, render %s, display %s)\n", G.renderer, maj, min,+ G.create_image ? (G.query_modifiers ? "with modifiers" : "yes") : "no",+ G.render_node[0] ? G.render_node : "the card's", k->driver[0] ? k->driver : drv);return 0;fail:gpu_shutdown();@@ -450,7 +450,7 @@ void gpu_shutdown(void) {memset(&G, 0, sizeof G);G.debug = debug;}-/* ---- formatos y dispositivo (linux-dmabuf) ---- */+/* ---- formats and device (linux-dmabuf) ---- */static const uint32_t known[] = { DRM_FORMAT_ARGB8888, DRM_FORMAT_XRGB8888, DRM_FORMAT_ABGR8888, DRM_FORMAT_XBGR8888 };@@ -463,14 +463,14 @@ int gpu_formats(GpuFormat *out, int max) {EGLint nm = 0;if (G.query_modifiers) G.query_modifiers(G.dpy, (EGLint)known[f], 64, mods, ext, &nm);for (int i = 0; i < nm && n < max; i++) out[n++] = (GpuFormat){ known[f], mods[i] };- if (n < max) out[n++] = (GpuFormat){ known[f], DRM_FORMAT_MOD_INVALID }; /* implícito */+ if (n < max) out[n++] = (GpuFormat){ known[f], DRM_FORMAT_MOD_INVALID }; /* implicit */}return n;}-/* El render node para el feedback de linux-dmabuf: el que usa EGL; si EGL no lo dice, el de la- * misma placa que la tarjeta de la salida; y si esa placa no tiene (pantalla sin GPU, como vc4 en- * la Pi 5), el primer render node que haya, que en esas placas es la GPU (v3d, panfrost…). */+/* The render node for linux-dmabuf feedback: the one EGL uses; if EGL does not say, the one on+ * the same device as the output's card; and if that device has none (a display without a GPU, like vc4 on+ * the Pi 5), the first render node there is, which on those boards is the GPU (v3d, panfrost…). */int gpu_device(dev_t *dev) {if (!G.k) return -1;struct stat st;@@ -490,7 +490,7 @@ int gpu_device(dev_t *dev) {snprintf(sys, sizeof sys, "/sys/dev/char/%u:%u/device", major(rs.st_rdev), minor(rs.st_rdev));if (realpath(sys, real) && !strcmp(real, want)) { *dev = rs.st_rdev; closedir(d); return 0; }}- /* ninguno es de la misma placa: pantalla y GPU separadas */+ /* none is on the same device: separate display and GPU */int found = 0;dev_t other = 0;if (d) rewinddir(d);@@ -500,7 +500,7 @@ int gpu_device(dev_t *dev) {struct stat rs;snprintf(path, sizeof path, "/dev/dri/%s", e->d_name);if (stat(path, &rs) || !S_ISCHR(rs.st_mode)) continue;- if (!found || rs.st_rdev < other) other = rs.st_rdev; /* el de número más bajo */+ if (!found || rs.st_rdev < other) other = rs.st_rdev; /* the lowest-numbered one */found = 1;}if (d) closedir(d);@@ -508,7 +508,7 @@ int gpu_device(dev_t *dev) {return 0;}-/* ---- texturas ---- */+/* ---- textures ---- */static void tex_params(GLenum target) {glTexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_LINEAR);@@ -543,10 +543,10 @@ static EGLImageKHR import_image(const GpuDmabuf *d, int with_mod);GpuTex *gpu_tex_dmabuf(const GpuDmabuf *d) {if (!G.on || !G.create_image || !G.have_external || d->nplanes < 1 || d->nplanes > 4) return NULL;EGLImageKHR img = import_image(d, 1);- /* lineal sin modificador explícito: hay drivers que solo aceptan el implícito */+ /* linear without an explicit modifier: some drivers only accept the implicit one */if (img == EGL_NO_IMAGE_KHR && d->modifier == DRM_FORMAT_MOD_LINEAR) img = import_image(d, 0);if (img == EGL_NO_IMAGE_KHR) {- dbg("no se pudo importar un dmabuf %dx%d fourcc %08x mod %llx (EGL 0x%x)", d->width, d->height, d->fourcc,+ dbg("could not import a dmabuf %dx%d fourcc %08x mod %llx (EGL 0x%x)", d->width, d->height, d->fourcc,(unsigned long long)d->modifier, eglGetError());return NULL;}@@ -598,7 +598,7 @@ void gpu_tex_free(GpuTex *t) {free(t);}-/* ---- dibujo ---- */+/* ---- drawing ---- */void gpu_draw(GpuTex *t, float dx, float dy, float dw, float dh, float sx, float sy, float sw, float sh, Rect clip, float op) {if (!G.on || !G.cur || !t || dw <= 0 || dh <= 0 || op <= 0.004f) return;@@ -659,10 +659,10 @@ int gpu_frame(int out, const Canvas *scene, Rect dmg, void (*draw_layer)(int layG.frames++;return present(o, (Shown){ .kind = 1, .bo = bo, .fb = fb });}-/* ---- scanout directo ---- */+/* ---- direct scanout ---- */int gpu_can_scanout(const GpuDmabuf *d, int w, int h) {- /* y que el plano primario acepte el modificador (vc4: solo lineal; UIF de v3d no) */+ /* and that the primary plane accepts the modifier (vc4: linear only; not v3d's UIF) */return G.on && d->width == w && d->height == h && d->nplanes == 1 &&(d->fourcc == DRM_FORMAT_XRGB8888 || d->fourcc == DRM_FORMAT_ARGB8888) &&kms_scanout_ok(G.k, DRM_FORMAT_XRGB8888, d->modifier);@@ -675,20 +675,20 @@ int gpu_scanout(const GpuDmabuf *d, void (*done)(void *), void *data) {for (int i = 0; i < d->nplanes; i++)if (kms_prime_import(G.k, d->fd[i], &s.handles[i])) {for (int j = 0; j < i; j++) kms_close_handle(G.k, s.handles[j]);- dbg("scanout: PRIME import falló (%s)", strerror(errno));+ dbg("scanout: PRIME import failed (%s)", strerror(errno));return -1;}- /* ARGB en el plano primario se muestra como XRGB (la salida no tiene nada debajo) */+ /* ARGB on the primary plane is shown as XRGB (the output has nothing below it) */uint32_t fourcc = d->fourcc == DRM_FORMAT_ARGB8888 ? DRM_FORMAT_XRGB8888 : d->fourcc;if (kms_add_fb2(G.k, (uint32_t)d->width, (uint32_t)d->height, fourcc, s.handles, d->stride, d->offset, d->modifier, &s.fb)) {- dbg("scanout: ADDFB2 falló (%s)", strerror(errno));+ dbg("scanout: ADDFB2 failed (%s)", strerror(errno));s.done = NULL;s.kind = 2;release(o, &s);return -1;}G.scanouts++;- if (G.debug && (G.scanouts == 1 || G.scanouts % 300 == 0)) dbg("scanout directo: %ld cuadros (compuestos %ld)", G.scanouts, G.frames);+ if (G.debug && (G.scanouts == 1 || G.scanouts % 300 == 0)) dbg("direct scanout: %ld frames (composed %ld)", G.scanouts, G.frames);return present(o, s);}diff --git a/server/src/gpu/gpu.h b/server/src/gpu/gpu.hindex 58d719e..443b65f 100644--- a/server/src/gpu/gpu.h+++ b/server/src/gpu/gpu.h@@ -1,5 +1,5 @@-/* gpu.h — composición por GPU (GBM + EGL + GLES2 de Mesa) y scanout directo (ver gpu.c y- * docs/GPU.md). Si no hay GPU usable, gpu_init falla y lord-server sigue por CPU como siempre. */+/* gpu.h — GPU composition (Mesa's GBM + EGL + GLES2) and direct scanout (see gpu.c and+ * docs/GPU.md). If there is no usable GPU, gpu_init fails and lord-server keeps going by CPU as always. */#ifndef LORD_GPU_H#define LORD_GPU_H@@ -10,34 +10,34 @@typedef struct GpuTex GpuTex;-/* Un búfer dmabuf de una app (hasta 4 planos). */+/* An app's dmabuf buffer (up to 4 planes). */typedef struct {int width, height, nplanes;uint32_t fourcc;- uint64_t modifier; /* DRM_FORMAT_MOD_INVALID = implícito */+ uint64_t modifier; /* DRM_FORMAT_MOD_INVALID = implicit */int fd[4];uint32_t offset[4], stride[4];} GpuDmabuf;typedef struct { uint32_t fourcc; uint64_t modifier; } GpuFormat;-int gpu_init(Kms *k); /* 0 si quedó activo; LORD_GPU=0 lo apaga */+int gpu_init(Kms *k); /* 0 if it is active; LORD_GPU=0 turns it off */int gpu_active(void);void gpu_shutdown(void);const char *gpu_renderer(void); /* "llvmpipe (LLVM …)", "AMD Radeon …" */-/* Formatos/modificadores que se pueden importar (linux-dmabuf) y el dispositivo DRM. */+/* Formats/modifiers that can be imported (linux-dmabuf) and the DRM device. */int gpu_formats(GpuFormat *out, int max);int gpu_device(dev_t *dev);-/* Texturas: desde píxeles ARGB premultiplicados (shm) o desde un dmabuf (EGLImage). */+/* Textures: from premultiplied ARGB pixels (shm) or from a dmabuf (EGLImage). */GpuTex *gpu_tex_pixels(GpuTex *t, const uint32_t *px, int w, int h, int opaque);GpuTex *gpu_tex_dmabuf(const GpuDmabuf *d);void gpu_tex_free(GpuTex *t);-/* Un cuadro: se sube lo que cambió del canvas de la UI, se dibujan las capas y se hace el flip.- * draw_layer(0) = ventanas de apps (debajo de la UI), draw_layer(1) = menús de las apps y- * pantalla completa (encima). */+/* One frame: what changed in the UI canvas is uploaded, the layers are drawn and the flip is done.+ * draw_layer(0) = app windows (below the UI), draw_layer(1) = app menus and+ * fullscreen (on top). */int gpu_frame(int out, const Canvas *scene, Rect damage, void (*draw_layer)(int layer));/* Another display (docs/DISPLAYS.md): its own GBM/EGL surface on the same context; gpu_init made* output 0. Returns the output index for gpu_frame, or -1 (then that display goes by the CPU). */@@ -45,10 +45,10 @@ int gpu_add_output(Kms *k);void gpu_draw(GpuTex *t, float dx, float dy, float dw, float dh,float sx, float sy, float sw, float sh, Rect clip, float opacity);-/* Scanout directo de un dmabuf a pantalla completa (sin componer). done(data) se llama cuando- * el búfer deja de estar en pantalla. 0 si se mandó el flip. */+/* Direct scanout of a fullscreen dmabuf (without composing). done(data) is called when+ * the buffer leaves the screen. 0 if the flip was sent. */int gpu_scanout(const GpuDmabuf *d, void (*done)(void *), void *data);-/* ¿Se puede mostrar directo? (tamaño de la salida, formato y modificador del plano primario) */+/* Can it be shown directly? (output size, format and primary plane modifier) */int gpu_can_scanout(const GpuDmabuf *d, int w, int h);#endifdiff --git a/server/src/hw/hw_admin.c b/server/src/hw/hw_admin.cindex 36add73..c720f38 100644--- a/server/src/hw/hw_admin.c+++ b/server/src/hw/hw_admin.c@@ -59,22 +59,22 @@ void hw_act_brightness(const AdminReq *r, const char *arg, size_t len) {char a[128], name[72];long v;if (arg_copy(arg, len, a, sizeof a) || sscanf(a, "%71s %ld", name, &v) != 2 || !hw_backlight_name_valid(name)) {- admin_say("ERR", "invalid argument");+ admin_err("admin.invalidArgument", NULL);return;}/* the entry has to be a real backlight device under /sys/devices */char link[PATH_MAX], real[PATH_MAX];snprintf(link, sizeof link, "/sys/class/backlight/%s", name);- if (!realpath(link, real) || strncmp(real, "/sys/devices/", 13)) { admin_say("ERR", "no such backlight"); return; }+ if (!realpath(link, real) || strncmp(real, "/sys/devices/", 13)) { admin_err("hw.noBacklight", NULL); return; }char p[PATH_MAX + 32];snprintf(p, sizeof p, "%s/max_brightness", real);long max = read_long(p);- if (max <= 0 || v < 0 || v > max) { admin_say("ERR", "value out of range (0..%ld)", max); return; }+ if (max <= 0 || v < 0 || v > max) { admin_err("hw.outOfRange", "max", lerr_int(max), NULL); return; }char val[32];snprintf(val, sizeof val, "%ld\n", v);snprintf(p, sizeof p, "%s/brightness", real);- if (write_file(p, val)) admin_say("ERR", "could not set the brightness: %s", strerror(errno));- else admin_say("OK", "%ld", v);+ if (write_file(p, val)) admin_err("hw.brightnessFailed", "errno", lerr_errno(errno), NULL);+ else admin_say("OK", "%ld", v); /* i18n-ok */}/* ---- power profile ---- */@@ -88,19 +88,19 @@ void hw_act_power_profile(const AdminReq *r, const char *arg, size_t len) {(void)r;char p[24];if (arg_copy(arg, len, p, sizeof p) || (strcmp(p, "performance") && strcmp(p, "balanced") && strcmp(p, "power-saver"))) {- admin_say("ERR", "invalid profile");+ admin_err("hw.badProfile", NULL);return;}if (file_ok("/usr/bin/powerprofilesctl")) {const char *const argv[] = { "/usr/bin/powerprofilesctl", "set", p, NULL };int code = admin_run(argv);- if (code) admin_say("ERR", "powerprofilesctl failed (%d)", code);- else admin_say("OK", "%s", p);+ if (code) admin_err("sys.programFailed", "program", "powerprofilesctl", "code", lerr_int(code), NULL);+ else admin_say("OK", "%s", p); /* i18n-ok */return;}/* no daemon: the cpufreq governor of every policy (and the energy/performance preference) */DIR *d = opendir("/sys/devices/system/cpu/cpufreq");- if (!d) { admin_say("ERR", "this computer has no CPU frequency scaling"); return; }+ if (!d) { admin_err("hw.noCpufreq", NULL); return; }int done = 0, failed = 0;for (struct dirent *e; (e = readdir(d));) {if (strncmp(e->d_name, "policy", 6) || !isdigit((unsigned char)e->d_name[6])) continue;@@ -121,16 +121,16 @@ void hw_act_power_profile(const AdminReq *r, const char *arg, size_t len) {done++;}closedir(d);- if (!done) admin_say("ERR", "no CPU policy accepted the profile");- else admin_say("OK", "%s (%d policies%s)", p, done, failed ? ", some refused" : "");+ if (!done) admin_err("hw.profileRefused", NULL);+ else admin_ok("hw.profileSet", "profile", p, "count", lerr_int(done), "refused", failed ? "1" : "0", NULL);}void hw_act_suspend(const AdminReq *r, const char *arg, size_t len) {(void)r; (void)arg; (void)len;const char *const argv[] = { "/usr/bin/systemctl", "suspend", NULL };int code = admin_run(argv);- if (code) admin_say("ERR", "systemctl suspend failed (%d)", code);- else admin_say("OK", "suspend");+ if (code) admin_err("hw.suspendFailed", "code", lerr_int(code), NULL);+ else admin_ok("hw.suspended", NULL);}/* ---- power button and lid (logind) ---- */@@ -149,7 +149,7 @@ void hw_act_buttons(const AdminReq *r, const char *arg, size_t len) {char a[128], power[16], lid[16], lidac[16];if (arg_copy(arg, len, a, sizeof a) || sscanf(a, "%15s %15s %15s", power, lid, lidac) != 3 ||!hw_button_action_valid(power, 0) || !hw_button_action_valid(lid, 1) || !hw_button_action_valid(lidac, 1)) {- admin_say("ERR", "invalid argument");+ admin_err("admin.invalidArgument", NULL);return;}mkdir("/etc/systemd/logind.conf.d", 0755);@@ -161,11 +161,11 @@ void hw_act_buttons(const AdminReq *r, const char *arg, size_t len) {int fd = open(tmp, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW, 0644);int ok = fd >= 0 && write(fd, text, strlen(text)) == (ssize_t)strlen(text);if (fd >= 0) { ok = fsync(fd) == 0 && ok; close(fd); }- if (!ok || rename(tmp, dst)) { unlink(tmp); admin_say("ERR", "could not write %s", dst); return; }+ if (!ok || rename(tmp, dst)) { unlink(tmp); admin_err("sys.writeFailed", "path", dst, NULL); return; }const char *const argv[] = { "/usr/bin/systemctl", "reload", "systemd-logind", NULL };int code = admin_run(argv);- if (code) admin_say("ERR", "logind did not reload (%d)", code);- else admin_say("OK", "%s %s %s", power, lid, lidac);+ if (code) admin_err("hw.logindFailed", "code", lerr_int(code), NULL);+ else admin_say("OK", "%s %s %s", power, lid, lidac); /* i18n-ok */}/* ---- date and time ---- */@@ -173,11 +173,11 @@ void hw_act_buttons(const AdminReq *r, const char *arg, size_t len) {void hw_act_ntp(const AdminReq *r, const char *arg, size_t len) {(void)r;char a[8];- if (arg_copy(arg, len, a, sizeof a) || (strcmp(a, "on") && strcmp(a, "off"))) { admin_say("ERR", "invalid argument"); return; }+ if (arg_copy(arg, len, a, sizeof a) || (strcmp(a, "on") && strcmp(a, "off"))) { admin_err("admin.invalidArgument", NULL); return; }const char *const argv[] = { "/usr/bin/timedatectl", "set-ntp", !strcmp(a, "on") ? "true" : "false", NULL };int code = admin_run(argv);- if (code) admin_say("ERR", "timedatectl set-ntp failed (%d)", code);- else admin_say("OK", "%s", a);+ if (code) admin_err("hw.ntpFailed", "code", lerr_int(code), NULL);+ else admin_say("OK", "%s", a); /* i18n-ok */}int hw_time_valid(const char *t) {@@ -198,11 +198,11 @@ int hw_time_valid(const char *t) {void hw_act_time_set(const AdminReq *r, const char *arg, size_t len) {(void)r;char t[32];- if (arg_copy(arg, len, t, sizeof t) || !hw_time_valid(t)) { admin_say("ERR", "invalid date and time"); return; }+ if (arg_copy(arg, len, t, sizeof t) || !hw_time_valid(t)) { admin_err("hw.badTime", NULL); return; }const char *const argv[] = { "/usr/bin/timedatectl", "set-time", t, NULL };int code = admin_run(argv);- if (code) admin_say("ERR", "timedatectl set-time failed (%d): turn off automatic time first", code);- else admin_say("OK", "%s", t);+ if (code) admin_err("hw.setTimeFailed", "code", lerr_int(code), NULL);+ else admin_say("OK", "%s", t); /* i18n-ok */}/* ---- Bluetooth rfkill ---- */@@ -210,10 +210,10 @@ void hw_act_time_set(const AdminReq *r, const char *arg, size_t len) {void hw_act_bt_unblock(const AdminReq *r, const char *arg, size_t len) {(void)r; (void)arg; (void)len;int fd = open("/dev/rfkill", O_WRONLY | O_CLOEXEC);- if (fd < 0) { admin_say("ERR", "no /dev/rfkill"); return; }+ if (fd < 0) { admin_err("hw.noRfkill", NULL); return; }struct rfkill_event ev = { .type = RFKILL_TYPE_BLUETOOTH, .op = RFKILL_OP_CHANGE_ALL, .soft = 0 };ssize_t w = write(fd, &ev, RFKILL_EVENT_SIZE_V1);close(fd);- if (w != RFKILL_EVENT_SIZE_V1) admin_say("ERR", "rfkill: %s", strerror(errno));- else admin_say("OK", "unblocked");+ if (w != RFKILL_EVENT_SIZE_V1) admin_err("hw.rfkillFailed", "errno", lerr_errno(errno), NULL);+ else admin_ok("hw.unblocked", NULL);}diff --git a/server/src/install/install.c b/server/src/install/install.cindex c07d257..638802d 100644--- a/server/src/install/install.c+++ b/server/src/install/install.c@@ -211,7 +211,7 @@ static void pair(const char *line, const char *key, char *out, size_t n) {void install_act_disks(const AdminReq *r, const char *arg, size_t len) {(void)r; (void)arg; (void)len;- if (!is_live()) { admin_say("ERR", "el instalador solo funciona desde el sistema en vivo"); return; }+ if (!is_live()) { admin_err("install.liveOnly", NULL); return; }Disk disks[32];int n = list_disks(disks, 32);for (int i = 0; i < n; i++) {@@ -250,7 +250,7 @@ void install_act_disks(const AdminReq *r, const char *arg, size_t len) {admin_say("LOG", "%s", js);free(js);}- admin_say("OK", "%d", n);+ admin_say("OK", "%d", n); /* i18n-ok */}/* ---- flat JSON of install-run ---- */@@ -368,39 +368,39 @@ static int locale_supported(const char *name) {static const char *validate(Plan *pl) {Disk disks[32];int n = list_disks(disks, 32), found = 0;- for (int i = 0; i < n; i++) if (!strcmp(disks[i].name, pl->disk)) { found = 1; if (disks[i].size < MIN_DISK) return "el disco es demasiado chico (mínimo 8 GB)"; }- if (!found) return "el disco no está en la lista de discos instalables";+ for (int i = 0; i < n; i++) if (!strcmp(disks[i].name, pl->disk)) { found = 1; if (disks[i].size < MIN_DISK) return "install.diskTooSmall"; }+ if (!found) return "install.diskNotListed";static const char *const reserved[] = { "root", "daemon", "bin", "sys", "sync", "games", "man", "lp", "mail", "news", "uucp","proxy", "www-data", "backup", "list", "irc", "nobody", "systemd-network", "messagebus", "pipewire", "sudo", "admin", NULL };- if (!re_user(pl->user)) return "el nombre de usuario es inválido (minúsculas, números, - y _)";- for (int i = 0; reserved[i]; i++) if (!strcmp(pl->user, reserved[i])) return "ese nombre de usuario está reservado";+ if (!re_user(pl->user)) return "install.badUser";+ for (int i = 0; reserved[i]; i++) if (!strcmp(pl->user, reserved[i])) return "install.userReserved";struct passwd *pw = getpwnam(pl->user);- if (pw && strcmp(pl->user, "lordos")) return "ese nombre de usuario ya lo usa el sistema";- for (const unsigned char *p = (const unsigned char *)pl->fullname; *p; p++) if (*p < 0x20 || *p == ':' || *p == ',' || *p == 0x7f) return "el nombre completo tiene caracteres inválidos";- if (!pl->password[0]) return "falta la contraseña";- if (!re_host(pl->hostname)) return "el nombre del equipo es inválido (minúsculas, números y -)";- if (!re_simple(pl->lang, 10, "-", 0)) return "idioma inválido";- if (!locale_supported(pl->locale)) return "región no soportada";+ if (pw && strcmp(pl->user, "lordos")) return "install.userTaken";+ for (const unsigned char *p = (const unsigned char *)pl->fullname; *p; p++) if (*p < 0x20 || *p == ':' || *p == ',' || *p == 0x7f) return "install.badFullName";+ if (!pl->password[0]) return "install.noPassword";+ if (!re_host(pl->hostname)) return "install.badHostname";+ if (!re_simple(pl->lang, 10, "-", 0)) return "install.badLanguage";+ if (!locale_supported(pl->locale)) return "install.badRegion";char p[PATH_MAX];struct stat st;- if (!re_simple(pl->timezone, 60, "/_+-", 0) || strstr(pl->timezone, "..") || pl->timezone[0] == '/') return "zona horaria inválida";+ if (!re_simple(pl->timezone, 60, "/_+-", 0) || strstr(pl->timezone, "..") || pl->timezone[0] == '/') return "install.badTimezone";snprintf(p, sizeof p, "/usr/share/zoneinfo/%s", pl->timezone);- if (stat(p, &st) || !S_ISREG(st.st_mode)) return "zona horaria desconocida";- if (!re_simple(pl->kblayout, 20, "_", 0)) return "distribución de teclado inválida";+ if (stat(p, &st) || !S_ISREG(st.st_mode)) return "install.unknownTimezone";+ if (!re_simple(pl->kblayout, 20, "_", 0)) return "install.badKbLayout";snprintf(p, sizeof p, "/usr/share/X11/xkb/symbols/%s", pl->kblayout);- if (access(p, R_OK)) return "distribución de teclado desconocida";- if (!re_simple(pl->kbvariant, 36, "_-", 1)) return "variante de teclado inválida";- if (pl->swap < 0 || pl->swap > 16384) return "tamaño de swap inválido (0 a 16384 MB)";+ if (access(p, R_OK)) return "install.unknownKbLayout";+ if (!re_simple(pl->kbvariant, 36, "_-", 1)) return "install.badKbVariant";+ if (pl->swap < 0 || pl->swap > 16384) return "install.badSwap";return NULL;}/* ---- install-run steps ---- */-static void progress(const char *phase, int done, int total) { admin_say("LOG", "progress %s %d %d", phase, done, total); }+static void progress(const char *phase, int done, int total) { admin_say("LOG", "progress %s %d %d", phase, done, total); } /* i18n-ok */static int run(const char *const argv[]) {int r = admin_run(argv);- if (r) admin_say("LOG", "falló %s (código %d)", argv[0], r);+ if (r) admin_log("install.stepFailed", "program", argv[0], "code", lerr_int(r), NULL);return r;}@@ -478,7 +478,7 @@ static int set_shadow(const char *user, const char *hash) {struct stat st;stat(path, &st);int r = done ? write_file(path, out, st.st_mode & 07777) : -1;- if (!r) if (chown(path, st.st_uid, st.st_gid)) admin_say("LOG", "aviso: no se pudo cambiar el dueño");+ if (!r) if (chown(path, st.st_uid, st.st_gid)) admin_log("install.chownWarning", NULL);explicit_bzero(out, ol);free(out);return r;@@ -533,66 +533,66 @@ static int disk_busy(const char *disk) {return busy;}-#define FAIL(...) do { admin_say("ERR", __VA_ARGS__); umount_target(); explicit_bzero(&pl, sizeof pl); return; } while (0)+#define FAIL(...) do { admin_err(__VA_ARGS__, NULL); umount_target(); explicit_bzero(&pl, sizeof pl); return; } while (0)void install_act_run(const AdminReq *r, const char *arg, size_t len) {(void)r; (void)len;Plan pl;- if (!is_live()) { admin_say("ERR", "el instalador solo funciona desde el sistema en vivo"); return; }- if (parse_plan(arg, &pl)) { admin_say("ERR", "datos de instalación inválidos"); return; }+ if (!is_live()) { admin_err("install.liveOnly", NULL); return; }+ if (parse_plan(arg, &pl)) { admin_err("install.badPlan", NULL); return; }const char *why = validate(&pl);- if (why) { explicit_bzero(&pl, sizeof pl); admin_say("ERR", "%s", why); return; }- if (disk_busy(pl.disk)) { admin_say("ERR", "el disco /dev/%s está en uso (montado o con swap)", pl.disk); explicit_bzero(&pl, sizeof pl); return; }+ if (why) { explicit_bzero(&pl, sizeof pl); admin_err(why, NULL); return; }+ if (disk_busy(pl.disk)) { admin_err("install.diskBusy", "disk", pl.disk, NULL); explicit_bzero(&pl, sizeof pl); return; }char dev[48], bios[48], esp[48], root[48];snprintf(dev, sizeof dev, "/dev/%s", pl.disk);part_path(pl.disk, 1, bios, sizeof bios);part_path(pl.disk, 2, esp, sizeof esp);part_path(pl.disk, 3, root, sizeof root);- admin_say("LOG", "instalando en %s", dev);+ admin_log("install.installingTo", "dev", dev, NULL);/* 1. partition: GPT with BIOS boot (1 MiB), ESP (512 MiB) and root */progress("partition", 0, 4);- { const char *const a[] = { "/usr/sbin/wipefs", "-a", dev, NULL }; if (run(a)) FAIL("no se pudo borrar el disco"); }+ { const char *const a[] = { "/usr/sbin/wipefs", "-a", dev, NULL }; if (run(a)) FAIL("install.wipeFailed"); }{ const char *const a[] = { "/usr/sbin/sgdisk", "--zap-all", dev, NULL }; run(a); }{ const char *const a[] = { "/usr/sbin/sgdisk", "-n", "1:0:+1M", "-t", "1:ef02", "-c", "1:biosboot","-n", "2:0:+512M", "-t", "2:ef00", "-c", "2:EFI","-n", "3:0:0", "-t", "3:8304", "-c", "3:LordOS", dev, NULL };- if (run(a)) FAIL("no se pudo particionar el disco"); }+ if (run(a)) FAIL("install.partitionFailed"); }progress("partition", 1, 4);{ const char *const a[] = { "/usr/bin/udevadm", "settle", "--timeout=10", NULL }; run(a); }for (int i = 0; i < 50 && (access(esp, F_OK) || access(root, F_OK)); i++) usleep(200000);- if (access(esp, F_OK) || access(root, F_OK)) FAIL("no aparecieron las particiones nuevas");- { const char *const a[] = { "/usr/sbin/mkfs.vfat", "-F", "32", "-n", "EFI", esp, NULL }; if (run(a)) FAIL("no se pudo formatear la partición EFI"); }+ if (access(esp, F_OK) || access(root, F_OK)) FAIL("install.noPartitions");+ { const char *const a[] = { "/usr/sbin/mkfs.vfat", "-F", "32", "-n", "EFI", esp, NULL }; if (run(a)) FAIL("install.formatEfiFailed"); }progress("partition", 2, 4);- { const char *const a[] = { "/usr/sbin/mkfs.ext4", "-F", "-q", "-L", "LordOS", root, NULL }; if (run(a)) FAIL("no se pudo formatear la partición del sistema"); }+ { const char *const a[] = { "/usr/sbin/mkfs.ext4", "-F", "-q", "-L", "LordOS", root, NULL }; if (run(a)) FAIL("install.formatRootFailed"); }progress("partition", 3, 4);mkdir("/run/lordos-install", 0700);mkdir(TARGET, 0755);umount_target();- if (mount(root, TARGET, "ext4", 0, NULL)) FAIL("no se pudo montar %s: %s", root, strerror(errno));+ if (mount(root, TARGET, "ext4", 0, NULL)) FAIL("install.mountFailed", "path", root, "errno", lerr_errno(errno));progress("partition", 4, 4);/* 2. copy the live system */progress("copy", 0, 100);- if (copy_system()) FAIL("no se pudo copiar el sistema");+ if (copy_system()) FAIL("install.copyFailed");progress("copy", 100, 100);mkdir(TARGET "/boot/efi", 0755);- if (mount(esp, TARGET "/boot/efi", "vfat", 0, "umask=0077")) FAIL("no se pudo montar la partición EFI");- if (bind("/dev") || bind("/proc") || bind("/sys") || bind("/run")) FAIL("no se pudo preparar el sistema nuevo");+ if (mount(esp, TARGET "/boot/efi", "vfat", 0, "umask=0077")) FAIL("install.mountEfiFailed");+ if (bind("/dev") || bind("/proc") || bind("/sys") || bind("/run")) FAIL("install.prepareFailed");/* 3. configure */const int steps = 9;int step = 0;progress("configure", step, steps);char ru[80], eu[80];- if (uuid_of(root, ru, sizeof ru) || uuid_of(esp, eu, sizeof eu)) FAIL("no se pudo leer el UUID de las particiones");+ if (uuid_of(root, ru, sizeof ru) || uuid_of(esp, eu, sizeof eu)) FAIL("install.uuidFailed");char swapline[64] = "";if (pl.swap > 0) snprintf(swapline, sizeof swapline, "/swapfile none swap sw 0 0\n");if (writef(TARGET "/etc/fstab", 0644,"# /etc/fstab — generated by the LordOS installer\n""UUID=%s / ext4 errors=remount-ro 0 1\nUUID=%s /boot/efi vfat umask=0077 0 1\n%s", ru, eu, swapline))- FAIL("no se pudo escribir /etc/fstab");+ FAIL("sys.writeFailed", "path", "/etc/fstab");writef(TARGET "/etc/hostname", 0644, "%s\n", pl.hostname);writef(TARGET "/etc/hosts", 0644, "127.0.0.1\tlocalhost\n127.0.1.1\t%s\n::1\tlocalhost ip6-localhost ip6-loopback\n", pl.hostname);progress("configure", ++step, steps);@@ -607,7 +607,7 @@ void install_act_run(const AdminReq *r, const char *arg, size_t len) {/* the user, with their password hashed here (yescrypt) */{ const char *const a[] = { "/usr/sbin/useradd", "-m", "-s", "/bin/bash", "-c", pl.fullname, "-G", "sudo,audio,video,input,render,pipewire", pl.user, NULL };- if (in_target(a)) FAIL("no se pudo crear el usuario"); }+ if (in_target(a)) FAIL("install.userFailed"); }/* CUPS printer administrator (lpadmin group, docs/PRINTING.md); if CUPS didn't come in* the image, the group doesn't exist and nothing happens */{ const char *const a[] = { "/usr/sbin/usermod", "--append", "--groups", "lpadmin", pl.user, NULL }; if (in_target(a)) { /* no CUPS */ } }@@ -617,8 +617,8 @@ void install_act_run(const AdminReq *r, const char *arg, size_t len) {memset(&cd, 0, sizeof cd);const char *hash = salt ? crypt_r(pl.password, salt, &cd) : NULL;free(salt);- if (!hash || hash[0] == '*') FAIL("no se pudo cifrar la contraseña");- if (set_shadow(pl.user, hash) || set_shadow("root", "*")) { explicit_bzero(&cd, sizeof cd); FAIL("no se pudo guardar la contraseña"); }+ if (!hash || hash[0] == '*') FAIL("install.hashFailed");+ if (set_shadow(pl.user, hash) || set_shadow("root", "*")) { explicit_bzero(&cd, sizeof cd); FAIL("install.passwordFailed"); }explicit_bzero(&cd, sizeof cd);explicit_bzero(pl.password, sizeof pl.password);mkdir(TARGET "/var/lib/systemd/linger", 0755);@@ -640,26 +640,26 @@ void install_act_run(const AdminReq *r, const char *arg, size_t len) {const char *const a[] = { "/usr/sbin/locale-gen", NULL }; in_target(a); } }writef(TARGET "/etc/default/locale", 0644, "LANG=%s\n", pl.locale);{ char zp[PATH_MAX]; snprintf(zp, sizeof zp, "/usr/share/zoneinfo/%s", pl.timezone);- unlink(TARGET "/etc/localtime"); if (symlink(zp, TARGET "/etc/localtime")) admin_say("LOG", "aviso: /etc/localtime");+ unlink(TARGET "/etc/localtime"); if (symlink(zp, TARGET "/etc/localtime")) admin_log("install.timezoneWarning", NULL);writef(TARGET "/etc/timezone", 0644, "%s\n", pl.timezone); }writef(TARGET "/etc/default/keyboard", 0644, "XKBMODEL=\"pc105\"\nXKBLAYOUT=\"%s\"\nXKBVARIANT=\"%s\"\nXKBOPTIONS=\"\"\nBACKSPACE=\"guess\"\n", pl.kblayout, pl.kbvariant);progress("configure", ++step, steps);/* the user's LordOS settings: chosen language and keyboard */uid_t uid; gid_t gid;- if (target_ids(pl.user, &uid, &gid)) FAIL("no se encontró el usuario nuevo");+ if (target_ids(pl.user, &uid, &gid)) FAIL("install.userMissing");{ char p[PATH_MAX];- snprintf(p, sizeof p, TARGET "/home/%s/.config", pl.user); mkdir(p, 0755); if (chown(p, uid, gid)) admin_say("LOG", "aviso: no se pudo cambiar el dueño");- snprintf(p, sizeof p, TARGET "/home/%s/.config/lordos", pl.user); mkdir(p, 0755); if (chown(p, uid, gid)) admin_say("LOG", "aviso: no se pudo cambiar el dueño");+ snprintf(p, sizeof p, TARGET "/home/%s/.config", pl.user); mkdir(p, 0755); if (chown(p, uid, gid)) admin_log("install.chownWarning", NULL);+ snprintf(p, sizeof p, TARGET "/home/%s/.config/lordos", pl.user); mkdir(p, 0755); if (chown(p, uid, gid)) admin_log("install.chownWarning", NULL);snprintf(p, sizeof p, TARGET "/home/%s/.config/lordos/settings.json", pl.user);writef(p, 0644, "{\n \"language\": \"%s\",\n \"keyboards\": [{ \"layout\": \"%s\", \"variant\": \"%s\" }],\n \"keyboardIndex\": 0\n}\n", pl.lang, pl.kblayout, pl.kbvariant);- if (chown(p, uid, gid)) admin_say("LOG", "aviso: no se pudo cambiar el dueño");+ if (chown(p, uid, gid)) admin_log("install.chownWarning", NULL);snprintf(p, sizeof p, TARGET "/home/%s/.config/locale.conf", pl.user);- writef(p, 0644, "LANG=%s\n", pl.locale); if (chown(p, uid, gid)) admin_say("LOG", "aviso: no se pudo cambiar el dueño"); }+ writef(p, 0644, "LANG=%s\n", pl.locale); if (chown(p, uid, gid)) admin_log("install.chownWarning", NULL); }/* Escritorio, Documentos, Descargas… in the chosen language and ~/.config/user-dirs.dirs (the* same list as Settings → Users and the live system: users/homedirs.c) */{ char p[PATH_MAX]; snprintf(p, sizeof p, TARGET "/home/%s", pl.user);- if (homedirs_create(p, uid, gid, pl.locale)) admin_say("LOG", "aviso: no se pudieron crear las carpetas del usuario"); }+ if (homedirs_create(p, uid, gid, pl.locale)) admin_log("install.homedirsWarning", NULL); }progress("configure", ++step, steps);/* swap as a file */@@ -677,24 +677,24 @@ void install_act_run(const AdminReq *r, const char *arg, size_t len) {"# generated by the LordOS installer\nGRUB_DEFAULT=0\nGRUB_TIMEOUT=2\nGRUB_DISTRIBUTOR=LordOS\n""GRUB_CMDLINE_LINUX_DEFAULT=\"quiet loglevel=3\"\nGRUB_CMDLINE_LINUX=\"\"\nGRUB_DISABLE_OS_PROBER=true\n");progress("configure", ++step, steps);- { const char *const a[] = { "/usr/sbin/update-initramfs", "-u", "-k", "all", NULL }; if (in_target(a)) FAIL("no se pudo generar el initramfs"); }+ { const char *const a[] = { "/usr/sbin/update-initramfs", "-u", "-k", "all", NULL }; if (in_target(a)) FAIL("install.initramfsFailed"); }progress("configure", ++step, steps);progress("configure", steps, steps);/* 4. boot: grub for UEFI (removable path, works on any firmware) and for BIOS */progress("bootloader", 0, 3);{ const char *const a[] = { "/usr/sbin/grub-install", "--target=x86_64-efi", "--efi-directory=/boot/efi", "--removable", "--no-nvram", NULL };- if (in_target(a)) FAIL("no se pudo instalar grub (UEFI)"); }+ if (in_target(a)) FAIL("install.grubEfiFailed"); }progress("bootloader", 1, 3);{ const char *const a[] = { "/usr/sbin/grub-install", "--target=i386-pc", dev, NULL };- if (in_target(a)) FAIL("no se pudo instalar grub (BIOS)"); }+ if (in_target(a)) FAIL("install.grubBiosFailed"); }progress("bootloader", 2, 3);{ const char *const a[] = { "/usr/sbin/grub-mkconfig", "-o", "/boot/grub/grub.cfg", NULL };- if (in_target(a)) FAIL("no se pudo generar la configuración de grub"); }+ if (in_target(a)) FAIL("install.grubConfigFailed"); }progress("bootloader", 3, 3);umount_target();explicit_bzero(&pl, sizeof pl);- admin_say("OK", "LordOS quedó instalado en %s", dev);+ admin_ok("install.done", "dev", dev, NULL);}/* Reboots without waiting around: a separate process (outlives the helper, which dies with@@ -702,7 +702,7 @@ void install_act_run(const AdminReq *r, const char *arg, size_t len) {* after 20 s the system is still alive and nobody killed it, does sync + reboot(2). */void install_act_reboot(const AdminReq *r, const char *arg, size_t len) {(void)r; (void)arg; (void)len;- if (!is_live() && access("/run/live", F_OK)) { admin_say("ERR", "solo desde el sistema en vivo"); return; }+ if (!is_live() && access("/run/live", F_OK)) { admin_err("install.liveOnly", NULL); return; }sync();pid_t pid = fork();if (pid == 0) {@@ -726,7 +726,7 @@ void install_act_reboot(const AdminReq *r, const char *arg, size_t len) {reboot(RB_AUTOBOOT);_exit(0);}- if (pid < 0) { admin_say("ERR", "no se pudo reiniciar"); return; }+ if (pid < 0) { admin_err("install.rebootFailed", NULL); return; }waitpid(pid, NULL, 0);- admin_say("OK", "reiniciando");+ admin_ok("install.rebooting", NULL);}diff --git a/server/src/kms.c b/server/src/kms.cindex 271b954..db23e7a 100644--- a/server/src/kms.c+++ b/server/src/kms.c@@ -1,4 +1,4 @@-/* kms.c — modesetting con ioctls del kernel: conector, CRTC, dumb buffers, page flip. */+/* kms.c — modesetting with kernel ioctls: connector, CRTC, dumb buffers, page flip. */#include "kms.h"#include <errno.h>@@ -188,13 +188,13 @@ static int pick_output(Kms *k) {ret = 0;}kms_outputs_free(outs, n);- if (ret) fprintf(stderr, "kms: no hay monitor conectado\n");+ if (ret) fprintf(stderr, "kms: no monitor connected\n");return ret;}-/* ---- formatos del plano primario (IN_FORMATS) ---- */+/* ---- primary plane formats (IN_FORMATS) ---- */-#define PLANE_TYPE_PRIMARY 1 /* enum drm_plane_type del kernel (no está en la uapi) */+#define PLANE_TYPE_PRIMARY 1 /* the kernel's enum drm_plane_type (not in the uapi) *//* Value (and property id) of property `name` of a KMS object. 0 if found. */int kms_obj_prop(int fd, uint32_t obj, uint32_t type, const char *name, uint64_t *val, uint32_t *prop_id) {@@ -221,7 +221,7 @@ static int rgb32(uint32_t f) {return f == DRM_FORMAT_XRGB8888 || f == DRM_FORMAT_ARGB8888 || f == DRM_FORMAT_XBGR8888 || f == DRM_FORMAT_ABGR8888;}-/* Lee el blob IN_FORMATS (struct drm_format_modifier_blob) y guarda los pares de RGB de 32 bits. */+/* Reads the IN_FORMATS blob (struct drm_format_modifier_blob) and keeps the 32-bit RGB pairs. */static void parse_in_formats(Kms *k, uint32_t blob_id) {struct drm_mode_get_blob gb = { .blob_id = blob_id };if (xioctl(k->fd, DRM_IOCTL_MODE_GETPROPBLOB, &gb) || gb.length < sizeof(struct drm_format_modifier_blob) || gb.length > (1u << 20)) return;@@ -254,8 +254,8 @@ static void parse_in_formats(Kms *k, uint32_t blob_id) {free(d);}-/* Busca el plano primario del CRTC y lo que acepta. Sin IN_FORMATS (drivers viejos) queda- * scan_known = 0 y el scanout directo se prueba con ADDFB2 como antes. */+/* Finds the CRTC's primary plane and what it accepts. Without IN_FORMATS (old drivers)+ * scan_known stays 0 and direct scanout is tried with ADDFB2 as before. */static void read_scanout_formats(Kms *k) {struct drm_version v;memset(&v, 0, sizeof v);@@ -280,8 +280,8 @@ static void read_scanout_formats(Kms *k) {if (!obj_prop(k->fd, planes[i], DRM_MODE_OBJECT_PLANE, "IN_FORMATS", &blob) && blob) parse_in_formats(k, (uint32_t)blob);break;}- if (!k->scan_known) { fprintf(stderr, "kms: placa %s, el plano primario no informa modificadores\n", k->driver); return; }- fprintf(stderr, "kms: placa %s, XRGB8888 en el plano primario con modificadores:", k->driver);+ if (!k->scan_known) { fprintf(stderr, "kms: card %s, the primary plane reports no modifiers\n", k->driver); return; }+ fprintf(stderr, "kms: card %s, XRGB8888 on the primary plane with modifiers:", k->driver);for (int i = 0; i < k->nscan; i++)if (k->scan[i].fourcc == DRM_FORMAT_XRGB8888) fprintf(stderr, " 0x%llx", (unsigned long long)k->scan[i].modifier);fputc('\n', stderr);@@ -301,7 +301,7 @@ static int kms_setup(Kms *k) {k->saved.crtc_id = k->crtc_id;xioctl(k->fd, DRM_IOCTL_MODE_GETCRTC, &k->saved);if (create_buffer(k, &k->buf[0]) || create_buffer(k, &k->buf[1])) return -1;- /* el primer cuadro en negro (no lo que dejó la sesión anterior) */+ /* the first frame in black (not what the previous session left) */memset(k->buf[0].map, 0, k->buf[0].size);memset(k->buf[1].map, 0, k->buf[1].size);struct drm_mode_crtc set = {@@ -351,7 +351,7 @@ int kms_open(Kms *k, const char *path) {k->fd = open(path, O_RDWR | O_CLOEXEC);if (k->fd < 0) { perror(path); return -1; }if (xioctl(k->fd, DRM_IOCTL_SET_MASTER, NULL))- fprintf(stderr, "kms: aviso, no somos DRM master (%s)\n", strerror(errno));+ fprintf(stderr, "kms: warning, we are not DRM master (%s)\n", strerror(errno));if (kms_setup(k)) { kms_close(k); return -1; }return 0;}@@ -381,8 +381,8 @@ void kms_close(Kms *k) {r.count_connectors = 1;xioctl(k->fd, DRM_IOCTL_MODE_SETCRTC, &r);}- /* prestado (kms_attach): el próximo en mostrarse pone su cuadro; el master lo maneja- * lord-sessiond. Los dumb buffers se destruyen después de que otro tomó la pantalla. */+ /* borrowed (kms_attach): the next one to show puts up its frame; lord-sessiond handles+ * master. The dumb buffers are destroyed after another one took the screen. */if (k->shared && k->crtc_id) { /* a second display: its CRTC stops scanning out */struct drm_mode_crtc off = { .crtc_id = k->crtc_id };xioctl(k->fd, DRM_IOCTL_MODE_SETCRTC, &off);@@ -407,7 +407,7 @@ int kms_flip(Kms *k) {k->flip_pending = 1;return 0;}- /* Fallback síncrono si el driver no soporta page flip. */+ /* Synchronous fallback if the driver does not support page flip. */struct drm_mode_crtc set = {.crtc_id = k->crtc_id, .fb_id = k->buf[back].fb_id,.set_connectors_ptr = (uintptr_t)&k->conn_id, .count_connectors = 1,@@ -424,7 +424,7 @@ void kms_dispatch(Kms *k) { kms_dispatch_heads(&k, 1); }* 4.12+; without it the first head waiting for a flip takes it). */void kms_dispatch_heads(Kms **heads, int nh) {if (nh < 1 || heads[0]->fd < 0) return;- /* alineado: los eventos llevan campos de 64 bits (user_data) y se leen con un cast */+ /* aligned: events carry 64-bit fields (user_data) and are read with a cast */char buf[1024] __attribute__((aligned(8)));ssize_t n = read(heads[0]->fd, buf, sizeof buf);for (ssize_t off = 0; n > 0 && off + (ssize_t)sizeof(struct drm_event) <= n;) {@@ -453,7 +453,7 @@ void kms_dispatch_heads(Kms **heads, int nh) {}}-/* ---- framebuffers propios (GPU y scanout directo) ---- */+/* ---- our own framebuffers (GPU and direct scanout) ---- */int kms_add_fb2(Kms *k, uint32_t w, uint32_t h, uint32_t fourcc, const uint32_t handles[4],const uint32_t pitches[4], const uint32_t offsets[4], uint64_t modifier, uint32_t *fb) {@@ -500,7 +500,7 @@ int kms_flip_fb(Kms *k, uint32_t fb, void *data) {};k->custom = 1;if (xioctl(k->fd, DRM_IOCTL_MODE_PAGE_FLIP, &pf) == 0) { k->flip_pending = 1; return 0; }- /* sin page flip: modeset síncrono y se avisa enseguida */+ /* no page flip: synchronous modeset and notify right away */if (kms_set_fb(k, fb)) return -1;struct timespec t;clock_gettime(CLOCK_MONOTONIC, &t);@@ -510,7 +510,7 @@ int kms_flip_fb(Kms *k, uint32_t fb, void *data) {return 0;}-/* ---- cursor por hardware ---- */+/* ---- hardware cursor ---- */int kms_cursor_image(Kms *k, const uint32_t *argb, int w, int h, int hot_x, int hot_y) {if (!k->cursor_handle) {diff --git a/server/src/kms.h b/server/src/kms.hindex d84afd9..7acb77a 100644--- a/server/src/kms.h+++ b/server/src/kms.h@@ -1,4 +1,4 @@-/* kms.h — salida de video directa al kernel (DRM/KMS), sin libdrm. */+/* kms.h — video output straight to the kernel (DRM/KMS), without libdrm. */#ifndef LORD_KMS_H#define LORD_KMS_H@@ -19,40 +19,40 @@ typedef struct {struct drm_mode_modeinfo mode;uint32_t width, height;KmsBuffer buf[2];- int front; /* buffer que se ve en pantalla */- int flip_pending; /* esperando vblank */+ int front; /* buffer shown on screen */+ int flip_pending; /* waiting for vblank */struct drm_mode_crtc saved;- /* flips de framebuffers propios (camino GPU, scanout directo): al terminar se llama a- * on_flip con lo que se pasó a kms_flip_fb; los dumb buffers de arriba no se usan */+ /* flips of our own framebuffers (GPU path, direct scanout): when done, on_flip is called+ * with what was passed to kms_flip_fb; the dumb buffers above are not used */void (*on_flip)(void *data);int custom;- /* último flip: hora (CLOCK_MONOTONIC, ns) y número de vblank (wp_presentation) */+ /* last flip: time (CLOCK_MONOTONIC, ns) and vblank number (wp_presentation) */uint64_t flip_ns;unsigned flip_seq;- /* cursor por hardware (plano de cursor, ioctl clásico) */+ /* hardware cursor (cursor plane, legacy ioctl) */uint32_t cursor_handle, cursor_w, cursor_h;uint32_t *cursor_map;uint64_t cursor_size;int cursor_ok, cursor_visible;- int borrowed; /* el fd lo pasó lord-sessiond (master y modo previo los maneja él) */+ int borrowed; /* the fd came from lord-sessiond (it handles master and the previous mode) */int shared; /* a second display (kms_head_open): the fd belongs to the main head */- /* plano primario del CRTC: formato y modificadores que acepta (propiedad IN_FORMATS). En la- * Raspberry Pi (vc4) el RGB solo se muestra lineal: los búferes con tiling UIF de v3d no van- * directo a la pantalla. scan_known = 0: el driver no lo dice (se prueba con ADDFB2). */+ /* the CRTC's primary plane: formats and modifiers it accepts (IN_FORMATS property). On the+ * Raspberry Pi (vc4) RGB is only shown linear: buffers with v3d's UIF tiling do not go+ * straight to the screen. scan_known = 0: the driver does not say (ADDFB2 is tried). */char driver[32];int crtc_index, scan_known, nscan;struct { uint32_t fourcc; uint64_t modifier; } scan[96];} Kms;int kms_open(Kms *k, const char *path);-/* Con un fd de la placa que pasó lord-sessiond (ya master): misma preparación que kms_open. */+/* With a card fd passed by lord-sessiond (already master): same setup as kms_open. */int kms_attach(Kms *k, int fd);void kms_close(Kms *k);-/* Buffer libre para dibujar (el que no está en pantalla). */+/* Free buffer to draw on (the one not on screen). */KmsBuffer *kms_back(Kms *k);-/* Muestra el back buffer en el próximo vblank. */+/* Shows the back buffer at the next vblank. */int kms_flip(Kms *k);-/* Procesa eventos del fd DRM (fin de page flip). */+/* Handles events of the DRM fd (page flip done). */void kms_dispatch(Kms *k);/* Several displays on one card: the events go to the head whose CRTC flipped. */void kms_dispatch_heads(Kms **heads, int n);@@ -60,22 +60,22 @@ void kms_dispatch_heads(Kms **heads, int n);* kms_close turns its CRTC off and leaves the fd open. 0 if it shows. */int kms_head_open(Kms *k, int fd, uint32_t conn_id, const struct drm_mode_modeinfo *mode);-/* Framebuffer desde handles GEM del fd de KMS (BO de GBM, o un dmabuf importado). Con modifier- * != DRM_FORMAT_MOD_INVALID se usa DRM_MODE_FB_MODIFIERS. 0 bien. */+/* Framebuffer from GEM handles of the KMS fd (a GBM BO, or an imported dmabuf). With modifier+ * != DRM_FORMAT_MOD_INVALID, DRM_MODE_FB_MODIFIERS is used. 0 on success. */int kms_add_fb2(Kms *k, uint32_t w, uint32_t h, uint32_t fourcc, const uint32_t handles[4],const uint32_t pitches[4], const uint32_t offsets[4], uint64_t modifier, uint32_t *fb);void kms_rm_fb(Kms *k, uint32_t fb);-int kms_prime_import(Kms *k, int dmabuf_fd, uint32_t *handle); /* dmabuf → handle GEM */+int kms_prime_import(Kms *k, int dmabuf_fd, uint32_t *handle); /* dmabuf → GEM handle */void kms_close_handle(Kms *k, uint32_t handle);-/* Primer modeset con un framebuffer propio, y page flip a uno (data vuelve en on_flip). */+/* First modeset with our own framebuffer, and page flip to one (data comes back in on_flip). */int kms_set_fb(Kms *k, uint32_t fb);int kms_flip_fb(Kms *k, uint32_t fb, void *data);-/* ¿El plano primario muestra este formato con este modificador? 1 sí (o no se sabe), 0 no.- * DRM_FORMAT_MOD_INVALID (implícito) cuenta como lineal. */+/* Does the primary plane show this format with this modifier? 1 yes (or unknown), 0 no.+ * DRM_FORMAT_MOD_INVALID (implicit) counts as linear. */int kms_scanout_ok(const Kms *k, uint32_t fourcc, uint64_t modifier);-/* Cursor por hardware: imagen ARGB (hasta 64×64) y posición. 0 si el driver lo soporta. */+/* Hardware cursor: ARGB image (up to 64×64) and position. 0 if the driver supports it. */int kms_cursor_image(Kms *k, const uint32_t *argb, int w, int h, int hot_x, int hot_y);void kms_cursor_move(Kms *k, int x, int y);void kms_cursor_show(Kms *k, int visible);diff --git a/server/src/logs/logs_admin.c b/server/src/logs/logs_admin.cindex ac16205..d75677e 100644--- a/server/src/logs/logs_admin.c+++ b/server/src/logs/logs_admin.c@@ -20,14 +20,14 @@void logs_act_system(const AdminReq *r, const char *arg, size_t len) {(void)r; (void)len;JQuery q;- if (jq_parse(arg, &q, 5000)) { admin_say("ERR", "consulta inválida"); return; }+ if (jq_parse(arg, &q, 5000)) { admin_err("logs.badQuery", NULL); return; }char **paths;int np = jq_files(JSCOPE_SYSTEM, 0, &paths);- if (np <= 0) { admin_say("ERR", "no hay journal del sistema"); return; }+ if (np <= 0) { admin_err("logs.noSystemJournal", NULL); return; }JEntry *e = NULL;long n = jq_run(paths, np, &q, &e);jq_files_free(paths, np);- if (n < 0) { admin_say("ERR", "no se pudo leer el journal"); return; }+ if (n < 0) { admin_err("logs.readFailed", NULL); return; }char buf[LINE_MAX_JSON];long sent = 0;for (long i = 0; i < n; i++) {@@ -36,5 +36,5 @@ void logs_act_system(const AdminReq *r, const char *arg, size_t len) {if (jentry_json(&e[i], buf, sizeof buf, tries[k])) { admin_say("LOG", "%s", buf); sent++; break; }}jq_free(e, n);- admin_say("OK", "%ld", sent);+ admin_say("OK", "%ld", sent); /* i18n-ok */}diff --git a/server/src/lpk.c b/server/src/lpk.cindex fbfe98b..4ccde3f 100644--- a/server/src/lpk.c+++ b/server/src/lpk.c@@ -86,7 +86,7 @@ int lpk_open(const char *path, Lpk *out, char *err, size_t errlen) {struct stat st;if (fd < 0 || fstat(fd, &st) || !S_ISREG(st.st_mode) || st.st_size <= 0 || (unsigned long long)st.st_size > LPK_MAX_ARCHIVE) {if (fd >= 0) close(fd);- seterr(err, errlen, "cannot read the file");+ seterr(err, errlen, "lpk.readFailed");return -1;}size_t len = (size_t)st.st_size;@@ -99,18 +99,18 @@ int lpk_open(const char *path, Lpk *out, char *err, size_t errlen) {got += (size_t)r;}close(fd);- if (!buf || got != len) { free(buf); seterr(err, errlen, "cannot read the file"); return -1; }+ if (!buf || got != len) { free(buf); seterr(err, errlen, "lpk.readFailed"); return -1; }if (buf[0] == 0x1f && buf[1] == 0x8b) {size_t n = 0;unsigned char *raw = gunzip(buf, len, &n);free(buf);- if (!raw) { seterr(err, errlen, "the package is corrupt (gzip)"); return -1; }+ if (!raw) { seterr(err, errlen, "lpk.corruptGzip"); return -1; }buf = raw;len = n;}out->raw = buf;out->files = calloc(LPK_MAX_FILES, sizeof *out->files);- if (!out->files) { lpk_free(out); seterr(err, errlen, "out of memory"); return -1; }+ if (!out->files) { lpk_free(out); seterr(err, errlen, "sys.outOfMemory"); return -1; }size_t total = 0;for (size_t off = 0; off + 512 <= len;) {const char *h = (const char *)buf + off;@@ -119,7 +119,7 @@ int lpk_open(const char *path, Lpk *out, char *err, size_t errlen) {if (empty) break; /* end of the tar */unsigned long sum = octal(h + 148, 8), calc = 0;for (int i = 0; i < 512; i++) calc += (i >= 148 && i < 156) ? ' ' : (unsigned char)h[i];- if (sum != calc) { lpk_free(out); seterr(err, errlen, "the package is corrupt (tar)"); return -1; }+ if (sum != calc) { lpk_free(out); seterr(err, errlen, "lpk.corruptTar"); return -1; }unsigned long size = octal(h + 124, 12);char type = h[156];char name[260];@@ -128,23 +128,23 @@ int lpk_open(const char *path, Lpk *out, char *err, size_t errlen) {else snprintf(name, sizeof name, "%.100s", h);size_t data = off + 512;size_t next = data + ((size + 511) & ~511ul);- if (next > len || size > LPK_MAX_TOTAL) { lpk_free(out); seterr(err, errlen, "the package is corrupt (size)"); return -1; }+ if (next > len || size > LPK_MAX_TOTAL) { lpk_free(out); seterr(err, errlen, "lpk.corruptSize"); return -1; }size_t nl = strlen(name);while (nl && name[nl - 1] == '/') name[--nl] = 0;if (nl > 2 && name[0] == '.' && name[1] == '/') memmove(name, name + 2, (nl -= 2) + 1);if (type == '5' || (type == 0 && nl == 0)) { off = next; continue; } /* folders: created on their own */if (type == 'x' || type == 'g') { off = next; continue; } /* pax headers: ignored */- if (type != '0' && type != 0) { lpk_free(out); seterr(err, errlen, "the package has links or special files"); return -1; }- if (!lpk_valid_path(name)) { lpk_free(out); seterr(err, errlen, "the package has an invalid path"); return -1; }- if (out->nfiles >= LPK_MAX_FILES || (total += size) > LPK_MAX_TOTAL) { lpk_free(out); seterr(err, errlen, "the package is too large"); return -1; }- if (lpk_find(out, name)) { lpk_free(out); seterr(err, errlen, "the package has duplicate files"); return -1; }+ if (type != '0' && type != 0) { lpk_free(out); seterr(err, errlen, "lpk.specialFiles"); return -1; }+ if (!lpk_valid_path(name)) { lpk_free(out); seterr(err, errlen, "lpk.badPath"); return -1; }+ if (out->nfiles >= LPK_MAX_FILES || (total += size) > LPK_MAX_TOTAL) { lpk_free(out); seterr(err, errlen, "lpk.tooLarge"); return -1; }+ if (lpk_find(out, name)) { lpk_free(out); seterr(err, errlen, "lpk.duplicateFiles"); return -1; }LpkFile *f = &out->files[out->nfiles++];snprintf(f->path, sizeof f->path, "%s", name);f->data = buf + data;f->size = size;off = next;}- if (!out->nfiles) { lpk_free(out); seterr(err, errlen, "the package is empty"); return -1; }+ if (!out->nfiles) { lpk_free(out); seterr(err, errlen, "lpk.empty"); return -1; }return 0;}@@ -203,14 +203,14 @@ static int make_parents(const char *base, const char *rel) {int lpk_install(const Lpk *p, const char *id, char *err, size_t errlen) {const char *root = lpk_root();- if (!root || !lpk_valid_id(id)) { seterr(err, errlen, "cannot install in the home folder"); return -1; }+ if (!root || !lpk_valid_id(id)) { seterr(err, errlen, "lpk.installHome"); return -1; }char dst[PATH_MAX], tmp[PATH_MAX], old[PATH_MAX];snprintf(dst, sizeof dst, "%s/%s", root, id);snprintf(tmp, sizeof tmp, "%s/.%s.new", root, id);snprintf(old, sizeof old, "%s/.%s.old", root, id);rm_tree(tmp);rm_tree(old);- if (mkdir(tmp, 0755)) { seterr(err, errlen, "cannot create the app folder"); return -1; }+ if (mkdir(tmp, 0755)) { seterr(err, errlen, "lpk.mkdirFailed"); return -1; }for (int i = 0; i < p->nfiles; i++) {const LpkFile *f = &p->files[i];char path[PATH_MAX];@@ -224,15 +224,15 @@ int lpk_install(const Lpk *p, const char *id, char *err, size_t errlen) {if (r <= 0) break;w += (size_t)r;}- if (fd < 0 || close(fd) || w != f->size) { rm_tree(tmp); seterr(err, errlen, "could not write the app (disk full?)"); return -1; }+ if (fd < 0 || close(fd) || w != f->size) { rm_tree(tmp); seterr(err, errlen, "lpk.writeFailed"); return -1; }}struct stat st;int had = !lstat(dst, &st);- if (had && rename(dst, old)) { rm_tree(tmp); seterr(err, errlen, "could not replace the installed version"); return -1; }+ if (had && rename(dst, old)) { rm_tree(tmp); seterr(err, errlen, "lpk.replaceFailed"); return -1; }if (rename(tmp, dst)) {if (had) rename(old, dst);rm_tree(tmp);- seterr(err, errlen, "could not install the app");+ seterr(err, errlen, "lpk.installFailed");return -1;}if (had) rm_tree(old);diff --git a/server/src/mail/search.c b/server/src/mail/search.cindex ffc4943..8b6afd5 100644--- a/server/src/mail/search.c+++ b/server/src/mail/search.c@@ -31,12 +31,12 @@ static uint64_t hash(const char *s, size_t n) {/* lower case without accents (Latin letters); other bytes are kept */void search_fold(const char *in, char *out, size_t cap) {static const struct { const char *from; const char *to; } map[] = {- { "á", "a" }, { "à", "a" }, { "â", "a" }, { "ä", "a" }, { "ã", "a" }, { "å", "a" }, { "Á", "a" }, { "À", "a" }, { "Â", "a" }, { "Ä", "a" }, { "Ã", "a" },- { "é", "e" }, { "è", "e" }, { "ê", "e" }, { "ë", "e" }, { "É", "e" }, { "È", "e" }, { "Ê", "e" }, { "Ë", "e" },- { "í", "i" }, { "ì", "i" }, { "î", "i" }, { "ï", "i" }, { "Í", "i" }, { "Ì", "i" }, { "Î", "i" }, { "Ï", "i" },- { "ó", "o" }, { "ò", "o" }, { "ô", "o" }, { "ö", "o" }, { "õ", "o" }, { "Ó", "o" }, { "Ò", "o" }, { "Ô", "o" }, { "Ö", "o" }, { "Õ", "o" },- { "ú", "u" }, { "ù", "u" }, { "û", "u" }, { "ü", "u" }, { "Ú", "u" }, { "Ù", "u" }, { "Û", "u" }, { "Ü", "u" },- { "ñ", "n" }, { "Ñ", "n" }, { "ç", "c" }, { "Ç", "c" }, { "ß", "ss" }, { "ø", "o" }, { "Ø", "o" }, { "æ", "ae" }, { "œ", "oe" },+ { "á", "a" }, { "à", "a" }, { "â", "a" }, { "ä", "a" }, { "ã", "a" }, { "å", "a" }, { "Á", "a" }, { "À", "a" }, { "Â", "a" }, { "Ä", "a" }, { "Ã", "a" }, /* i18n-ok */+ { "é", "e" }, { "è", "e" }, { "ê", "e" }, { "ë", "e" }, { "É", "e" }, { "È", "e" }, { "Ê", "e" }, { "Ë", "e" }, /* i18n-ok */+ { "í", "i" }, { "ì", "i" }, { "î", "i" }, { "ï", "i" }, { "Í", "i" }, { "Ì", "i" }, { "Î", "i" }, { "Ï", "i" }, /* i18n-ok */+ { "ó", "o" }, { "ò", "o" }, { "ô", "o" }, { "ö", "o" }, { "õ", "o" }, { "Ó", "o" }, { "Ò", "o" }, { "Ô", "o" }, { "Ö", "o" }, { "Õ", "o" }, /* i18n-ok */+ { "ú", "u" }, { "ù", "u" }, { "û", "u" }, { "ü", "u" }, { "Ú", "u" }, { "Ù", "u" }, { "Û", "u" }, { "Ü", "u" }, /* i18n-ok */+ { "ñ", "n" }, { "Ñ", "n" }, { "ç", "c" }, { "Ç", "c" }, { "ß", "ss" }, { "ø", "o" }, { "Ø", "o" }, { "æ", "ae" }, { "œ", "oe" }, /* i18n-ok */};size_t o = 0;if (!cap) return;diff --git a/server/src/mail/store.c b/server/src/mail/store.cindex 1c0d5b3..636db41 100644--- a/server/src/mail/store.c+++ b/server/src/mail/store.c@@ -47,7 +47,7 @@ const char *special_of(const char *name, const char *flags) {{ "Drafts", "drafts" }, { "Borradores", "drafts" }, { "Rascunhos", "drafts" },{ "Trash", "trash" }, { "Deleted Items", "trash" }, { "Deleted Messages", "trash" }, { "Papelera", "trash" }, { "Lixeira", "trash" }, { "Bin", "trash" },{ "Junk", "junk" }, { "Spam", "junk" }, { "Junk E-mail", "junk" }, { "Correo no deseado", "junk" },- { "Archive", "archive" }, { "Archivo", "archive" }, { "Arquivo", "archive" }, { "All Mail", "all" },+ { "Archive", "archive" }, { "Archivo", "archive" }, { "Arquivo", "archive" }, { "All Mail", "all" }, /* i18n-ok: folder names servers use */};for (size_t i = 0; i < sizeof names / sizeof names[0]; i++) if (!strcasecmp(base, names[i].n)) return names[i].sp;return "";diff --git a/server/src/main.c b/server/src/main.cindex 43b0f0a..5282841 100644--- a/server/src/main.c+++ b/server/src/main.c@@ -73,9 +73,9 @@ extern int paint_profile;typedef struct { int down, button; } ButtonEvent;-/* Medición de arrastres (docs/WINDOWS.md): con un botón apretado y el puntero en movimiento se- * cuentan los cuadros y el trabajo de cada uno (JS del puntero + layout + pintado + presentar). Al- * soltar se escribe una línea "arrastre: …" en el registro de la sesión. */+/* Drag measurement (docs/WINDOWS.md): with a button held and the pointer moving, the frames+ * and the work of each one are counted (pointer JS + layout + paint + present). On+ * release a "drag: …" line is written to the session log. */typedef struct {int held, active;double t0, last, js, work_js, work, work_max, gap_max, paint, present, layout;@@ -268,20 +268,20 @@ static double now_ms(void) {return t.tv_sec * 1e3 + t.tv_nsec / 1e6;}-/* Pasa de root al usuario que invocó sudo (o --user), conservando solo- * CAP_SYS_TTY_CONFIG para poder devolver la consola a modo texto al salir. */+/* Drops from root to the user who ran sudo (or --user), keeping only+ * CAP_SYS_TTY_CONFIG so the console can be put back in text mode on exit. */static int drop_privileges(const char *user) {if (geteuid() != 0) return 0;if (!user) user = getenv("SUDO_USER");if (!user) {- fprintf(stderr, "lord-server: aviso, sigue corriendo como root (usar sudo o --user)\n");+ fprintf(stderr, "lord-server: warning, still running as root (use sudo or --user)\n");return 0;}struct passwd *pw = getpwnam(user);- if (!pw || pw->pw_uid == 0) { fprintf(stderr, "lord-server: usuario inválido '%s'\n", user); return -1; }+ if (!pw || pw->pw_uid == 0) { fprintf(stderr, "lord-server: invalid user '%s'\n", user); return -1; }if (prctl(PR_SET_KEEPCAPS, 1) || initgroups(pw->pw_name, pw->pw_gid) ||setgid(pw->pw_gid) || setuid(pw->pw_uid)) {- perror("lord-server: soltar privilegios");+ perror("lord-server: dropping privileges");return -1;}struct __user_cap_header_struct hdr = { _LINUX_CAPABILITY_VERSION_3, 0 };@@ -290,10 +290,10 @@ static int drop_privileges(const char *user) {caps[0].effective = caps[0].permitted = 1u << CAP_SYS_TTY_CONFIG;if (syscall(SYS_capset, &hdr, caps)) perror("lord-server: capset");prctl(PR_SET_KEEPCAPS, 0);- if (setuid(0) == 0) { fprintf(stderr, "lord-server: no se pudieron soltar privilegios\n"); return -1; }+ if (setuid(0) == 0) { fprintf(stderr, "lord-server: could not drop privileges\n"); return -1; }setenv("HOME", pw->pw_dir, 1);setenv("USER", pw->pw_name, 1);- fprintf(stderr, "lord-server: corriendo como %s (uid %d)\n", pw->pw_name, (int)pw->pw_uid);+ fprintf(stderr, "lord-server: running as %s (uid %d)\n", pw->pw_name, (int)pw->pw_uid);return 0;}@@ -358,9 +358,9 @@ static void dispatch_pointer(Server *s) {double span = dstat.last - dstat.t0;long lr = 0, lb = 0;paint_layer_stats(&lr, &lb);- fprintf(stderr, "arrastre: %ld cuadros en %.0f ms = %.1f FPS (%ld movimientos); por cuadro: trabajo %.2f ms "- "(máx %.2f; JS %.2f, layout %.2f, pintado %.2f, presentar %.2f), intervalo máx %.1f ms; "- "capa: %ld pintadas, %ld copiadas (%s)\n",+ fprintf(stderr, "drag: %ld frames in %.0f ms = %.1f FPS (%ld moves); per frame: work %.2f ms "+ "(max %.2f; JS %.2f, layout %.2f, paint %.2f, present %.2f), max gap %.1f ms; "+ "layer: %ld painted, %ld copied (%s)\n",dstat.frames, span, 1000.0 * dstat.frames / span, dstat.moves, dstat.work / dstat.frames, dstat.work_max,dstat.js / dstat.frames, dstat.layout / dstat.frames, (dstat.paint - dstat.layout) / dstat.frames,dstat.present / dstat.frames, dstat.gap_max, lr, lb, gpu_active() ? "GPU" : "CPU");@@ -1278,7 +1278,7 @@ static void switch_theme(const char *current) {ui_reset();term_detach_all();if (js_init(path)) {- fprintf(stderr, "lord-server: el tema falló, se vuelve a %s\n", current);+ fprintf(stderr, "lord-server: the theme failed, going back to %s\n", current);snprintf(ui.theme_failed, sizeof ui.theme_failed, "%s", path);js_shutdown();ui_reset();@@ -1301,8 +1301,8 @@ static void hw_redraw(void) { if (hw_server) full_damage(hw_server); }static const DisplayHost hw_host = { hw_kms, hw_redraw, js_hw_event, hw_heads };static void usage(const char *argv0) {- fprintf(stderr, "uso: %s [--theme bundle.js] [--fonts dir] [--shell dir] [--user nombre] [--card /dev/dri/cardN]\n"- " [--headless ANCHOxALTO [--greeter]] [--timeout s] [--debug] [--profile]\n", argv0);+ fprintf(stderr, "usage: %s [--theme bundle.js] [--fonts dir] [--shell dir] [--user name] [--card /dev/dri/cardN]\n"+ " [--headless WIDTHxHEIGHT [--greeter]] [--timeout s] [--debug] [--profile]\n", argv0);}int main(int argc, char **argv) {@@ -1384,33 +1384,33 @@ int main(int argc, char **argv) {int vt = -1;if (!s.headless) {- if (input_open(&s.input)) fprintf(stderr, "input: sin dispositivos (¿permisos?)\n");- /* La consola de texto deja de dibujar encima nuestro. */+ if (input_open(&s.input)) fprintf(stderr, "input: no devices (permissions?)\n");+ /* The text console stops drawing over us. */vt = open("/dev/tty0", O_RDWR | O_CLOEXEC);if (vt >= 0 && ioctl(vt, KDSETMODE, KD_GRAPHICS)) { close(vt); vt = -1; }}- /* Ayudante privilegiado (acciones cerradas: región, zona horaria, paquetes de idioma). La- * pantalla de ingreso no tiene: lo que necesita root lo hace lord-sessiond. */+ /* Privileged helper (a closed set of actions: region, time zone, language packs). The+ * login screen has none: what needs root is done by lord-sessiond. */const char *session_user = s.greeter ? NULL : user ? user : getenv("SUDO_USER");- if (session_user && admin_start(session_user)) fprintf(stderr, "lord-server: sin ayudante de administración\n");+ if (session_user && admin_start(session_user)) fprintf(stderr, "lord-server: no administration helper\n");/* LordOS networking: with lord-sessiond the network belongs to the system (lord-netd brings it* up at boot) and net-restore only confirms; without it (a standalone lord-server) this* session's helper brings it up (see net_act_restore and docs/NETWORK.md) */else if (session_user) admin_send("net-restore", "", 0);int ok = drop_privileges(user) == 0;if (ok && s.headless && getenv("HOME")) {- /* sin terminal: el registro de la sesión va a la carpeta personal */+ /* no terminal: the session log goes to the home folder */char log[1024];snprintf(log, sizeof log, "%s/.cache", getenv("HOME"));mkdir(log, 0700);snprintf(log, sizeof log, "%s/.cache/lordos", getenv("HOME"));mkdir(log, 0700);snprintf(log, sizeof log, "%s/.cache/lordos/%s", getenv("HOME"), s.greeter ? "greeter.log" : "session.log");- if (!freopen(log, "w", stderr)) { /* sigue sin registro */ }+ if (!freopen(log, "w", stderr)) { /* carries on without a log */ }setvbuf(stderr, NULL, _IOLBF, 0);}- /* GPU (Mesa) después de soltar root: si no hay una usable, sigue el camino por CPU */+ /* GPU (Mesa) after dropping root: if there is no usable one, the CPU path goes on *//* Settings' hardware pages: displays, uevents, Bluetooth, power profiles (src/hw) */kms_set_picker(display_pick);hw_server = &s;@@ -1420,20 +1420,20 @@ int main(int argc, char **argv) {struct stat st;if (K0(&s)->fd >= 0 && fstat(K0(&s)->fd, &st) == 0) wl_set_drm_device(st.st_rdev);}- if (ok && wl_start()) fprintf(stderr, "lord-server: sin Wayland (las apps Linux no van a poder abrirse)\n");+ if (ok && wl_start()) fprintf(stderr, "lord-server: no Wayland (Linux apps will not be able to open)\n");publish_displays(&s); /* one wl_output per display */- if (ok && net_open()) fprintf(stderr, "lord-server: sin avisos de red (rtnetlink)\n");+ if (ok && net_open()) fprintf(stderr, "lord-server: no network notifications (rtnetlink)\n");/* Backups: a thread running as the user, nice 19 and idle I/O (backup/backup.c) */if (ok && !s.greeter && getenv("HOME") && session_user) backup_start(getenv("HOME"), session_user);- if (ok && snd_start()) fprintf(stderr, "lord-server: sin PipeWire por ahora (sonido); se reintenta solo\n");- if (ok && !s.greeter) portal_start(); /* modo oscuro, acento y botones para GTK/GNOME/Qt (ui/portal.c) */- if (ok && !s.greeter) term_restore(); /* shells que siguieron vivos desde el arranque anterior */+ if (ok && snd_start()) fprintf(stderr, "lord-server: no PipeWire for now (sound); it retries on its own\n");+ if (ok && !s.greeter) portal_start(); /* dark mode, accent and buttons for GTK/GNOME/Qt (ui/portal.c) */+ if (ok && !s.greeter) term_restore(); /* shells still alive from the previous start */remote_server = &s;tp_route_init(&tp_host);static const MirrorInput mirror_in = { remote_pointer, remote_button, remote_wheel, remote_key, remote_clip, remote_clients,remote_refresh, remote_resize, remote_greeter, display_attach, display_detach,remote_scroll, remote_pinch, remote_input_add };- if (ok && mirror_start(s.W, s.H, &mirror_in)) fprintf(stderr, "lord-server: sin escritorio remoto (socket)\n");+ if (ok && mirror_start(s.W, s.H, &mirror_in)) fprintf(stderr, "lord-server: no remote desktop (socket)\n");if (ok) {char path[1024];snprintf(path, sizeof path, "%s", theme);@@ -1594,7 +1594,7 @@ int main(int argc, char **argv) {}if (s.renders)- fprintf(stderr, "lord-server: %ld frames, %ld renders de UI, layout %.2f ms, paint %.2f ms (promedio)\n",+ fprintf(stderr, "lord-server: %ld frames, %ld UI renders, layout %.2f ms, paint %.2f ms (average)\n",s.frames, s.renders, s.layout_total / s.renders, s.paint_total / s.renders);input_close(&s.input);mirror_stop();diff --git a/server/src/media/helper/lm.h b/server/src/media/helper/lm.hindex 14c5116..efbf6aa 100644--- a/server/src/media/helper/lm.h+++ b/server/src/media/helper/lm.h@@ -11,6 +11,7 @@#define LORD_MEDIA_LM_H#include "../proto.h"+#include "../../errcode.h"#include <stdint.h>#include <stdio.h>@@ -53,7 +54,8 @@ void lm_buf_printf(LmBuf *b, const char *fmt, ...) __attribute__((format(printf,void lm_buf_str(LmBuf *b, const char *s); /* JSON string with escapes */void lm_buf_free(LmBuf *b);-/* Replies to lord-server. */+/* Replies to lord-server. A failed result's payload and every error are code lines (../../errcode.h),+ * never prose: the UI translates them (errors.media.*). Details go to the log (LM_LOG). */void lm_result(uint32_t id, int status, const char *payload, int fd);void lm_error(const char *fmt, ...) __attribute__((format(printf, 1, 2)));diff --git a/server/src/media/helper/lm_cam.c b/server/src/media/helper/lm_cam.cindex 40454dc..a4a6780 100644--- a/server/src/media/helper/lm_cam.c+++ b/server/src/media/helper/lm_cam.c@@ -77,15 +77,15 @@ static void on_mic(const int16_t *pcm, int samples) {void lm_camera(const char *params, int dev, int render) {struct v4l2_capability cap;memset(&cap, 0, sizeof cap);- if (dev < 0 || xioctl(dev, VIDIOC_QUERYCAP, &cap)) { lm_error("no es una cámara"); mp_sendv(LM_SOCK, MM_STATE, 0, MS_FAILED, 0, 0, 0); return; }+ if (dev < 0 || xioctl(dev, VIDIOC_QUERYCAP, &cap)) { lm_error("camera.notACamera"); mp_sendv(LM_SOCK, MM_STATE, 0, MS_FAILED, 0, 0, 0); return; }uint32_t caps = (cap.capabilities & V4L2_CAP_DEVICE_CAPS) ? cap.device_caps : cap.capabilities;- if (!(caps & V4L2_CAP_VIDEO_CAPTURE) || !(caps & V4L2_CAP_STREAMING)) { lm_error("la cámara no captura video"); mp_sendv(LM_SOCK, MM_STATE, 0, MS_FAILED, 0, 0, 0); return; }+ if (!(caps & V4L2_CAP_VIDEO_CAPTURE) || !(caps & V4L2_CAP_STREAMING)) { lm_error("camera.noVideo"); mp_sendv(LM_SOCK, MM_STATE, 0, MS_FAILED, 0, 0, 0); return; }char accel[24];AVBufferRef *hw = lm_hw_device(lm_hw_accel(params, accel, sizeof accel), render);lm_out_init(0);struct v4l2_format fmt;if (choose_format(dev, &fmt, (int)mp_param_int(params, "width", 1280), (int)mp_param_int(params, "height", 720))) {- lm_error("formato de cámara no soportado");+ lm_error("camera.unsupportedFormat");mp_sendv(LM_SOCK, MM_STATE, 0, MS_FAILED, 0, 0, 0);return;}@@ -94,7 +94,7 @@ void lm_camera(const char *params, int dev, int render) {struct v4l2_requestbuffers rb = { .count = NBUF, .type = V4L2_BUF_TYPE_VIDEO_CAPTURE, .memory = V4L2_MEMORY_MMAP };Buf bufs[NBUF];memset(bufs, 0, sizeof bufs);- if (xioctl(dev, VIDIOC_REQBUFS, &rb) || rb.count < 2) { lm_error("la cámara está ocupada"); mp_sendv(LM_SOCK, MM_STATE, 0, MS_FAILED, 0, 0, 0); return; }+ if (xioctl(dev, VIDIOC_REQBUFS, &rb) || rb.count < 2) { lm_error("camera.busy"); mp_sendv(LM_SOCK, MM_STATE, 0, MS_FAILED, 0, 0, 0); return; }int nb = rb.count > NBUF ? NBUF : (int)rb.count;for (int i = 0; i < nb; i++) {struct v4l2_buffer b = { .index = (uint32_t)i, .type = V4L2_BUF_TYPE_VIDEO_CAPTURE, .memory = V4L2_MEMORY_MMAP };@@ -105,7 +105,7 @@ void lm_camera(const char *params, int dev, int render) {xioctl(dev, VIDIOC_QBUF, &b);}enum v4l2_buf_type type = V4L2_BUF_TYPE_VIDEO_CAPTURE;- if (xioctl(dev, VIDIOC_STREAMON, &type)) { lm_error("no se pudo encender la cámara"); mp_sendv(LM_SOCK, MM_STATE, 0, MS_FAILED, 0, 0, 0); return; }+ if (xioctl(dev, VIDIOC_STREAMON, &type)) { lm_error("camera.startFailed"); mp_sendv(LM_SOCK, MM_STATE, 0, MS_FAILED, 0, 0, 0); return; }AVCodecContext *mj = NULL;if (pixfmt == V4L2_PIX_FMT_MJPEG) {const AVCodec *c = avcodec_find_decoder(AV_CODEC_ID_MJPEG);@@ -149,7 +149,7 @@ void lm_camera(const char *params, int dev, int render) {}char j[64];snprintf(j, sizeof j, "{\"width\":%d,\"height\":%d}", last ? last->width : 0, last ? last->height : 0);- lm_result(m.id, ok ? -1 : 0, ok ? "no se pudo sacar la foto" : j, -1);+ lm_result(m.id, ok ? -1 : 0, ok ? "camera.photoFailed" : j, -1);} else if (m.type == MM_RECORD && fds[0] >= 0 && !enc) {char err[128];ring = lm_mic_ring(fds[1], &ring_len);diff --git a/server/src/media/helper/lm_enc.c b/server/src/media/helper/lm_enc.cindex 8af5d95..251250e 100644--- a/server/src/media/helper/lm_enc.c+++ b/server/src/media/helper/lm_enc.c@@ -108,9 +108,9 @@ LmEnc *lm_enc_open(int out_fd, int w, int h, int fps, AVBufferRef *hw, int audioe->last_pts = -1;e->pkt = av_packet_alloc();e->oc = lm_open_output(out_fd, "mp4");- if (!e->oc || e->w < 16 || e->h < 16) { snprintf(err, errlen, "no se pudo crear el archivo"); lm_enc_close(e); return NULL; }+ if (!e->oc || e->w < 16 || e->h < 16) { lerr_set(err, errlen, "media.createFailed", NULL); lm_enc_close(e); return NULL; }e->v = video_encoder(e, fps > 0 ? fps : 30, hw);- if (!e->v) { snprintf(err, errlen, "sin codificador de video"); lm_enc_close(e); return NULL; }+ if (!e->v) { lerr_set(err, errlen, "media.noVideoEncoder", NULL); lm_enc_close(e); return NULL; }e->vs = avformat_new_stream(e->oc, NULL);avcodec_parameters_from_context(e->vs->codecpar, e->v);e->vs->time_base = (AVRational){ 1, 1000 };@@ -134,7 +134,7 @@ LmEnc *lm_enc_open(int out_fd, int w, int h, int fps, AVBufferRef *hw, int audioswr_init(e->swr);} else LM_LOG("no AAC: the recording has no sound");}- if (avformat_write_header(e->oc, NULL) < 0) { snprintf(err, errlen, "no se pudo escribir el archivo"); lm_enc_close(e); return NULL; }+ if (avformat_write_header(e->oc, NULL) < 0) { lerr_set(err, errlen, "media.writeFailed", NULL); lm_enc_close(e); return NULL; }e->header = 1;e->yuv = av_frame_alloc();e->yuv->format = e->frames ? AV_PIX_FMT_NV12 : AV_PIX_FMT_YUV420P;diff --git a/server/src/media/helper/lm_io.c b/server/src/media/helper/lm_io.cindex be3e627..24d2f33 100644--- a/server/src/media/helper/lm_io.c+++ b/server/src/media/helper/lm_io.c@@ -68,15 +68,15 @@ static int64_t io_seek(void *op, int64_t off, int whence) {AVFormatContext *lm_open_input(int fd, char *err, size_t errlen) {struct stat st;- if (fd < 0 || fstat(fd, &st) || !S_ISREG(st.st_mode)) { snprintf(err, errlen, "no es un archivo"); return NULL; }+ if (fd < 0 || fstat(fd, &st) || !S_ISREG(st.st_mode)) { lerr_set(err, errlen, "media.notAFile", NULL); return NULL; }FdIo *f = av_mallocz(sizeof *f);unsigned char *buf = av_malloc(65536);- if (!f || !buf) { av_free(f); av_free(buf); snprintf(err, errlen, "sin memoria"); return NULL; }+ if (!f || !buf) { av_free(f); av_free(buf); lerr_set(err, errlen, "sys.outOfMemory", NULL); return NULL; }f->fd = fd;f->size = st.st_size;AVIOContext *io = avio_alloc_context(buf, 65536, 0, f, io_read, NULL, io_seek);AVFormatContext *fmt = avformat_alloc_context();- if (!io || !fmt) { snprintf(err, errlen, "sin memoria"); return NULL; }+ if (!io || !fmt) { lerr_set(err, errlen, "sys.outOfMemory", NULL); return NULL; }fmt->pb = io;fmt->flags |= AVFMT_FLAG_CUSTOM_IO;/* no network nor auxiliary files (m3u8 lists, concat, "%d" images): only this fd */@@ -84,7 +84,10 @@ AVFormatContext *lm_open_input(int fd, char *err, size_t errlen) {fmt->format_whitelist = NULL;int r = avformat_open_input(&fmt, NULL, NULL, NULL);if (r < 0) {- av_strerror(r, err, errlen);+ char why[128];+ av_strerror(r, why, sizeof why);+ LM_LOG("could not open the input: %s", why);+ lerr_set(err, errlen, "media.cannotOpen", NULL);av_free(io->buffer);avio_context_free(&io);av_free(f);diff --git a/server/src/media/helper/lm_job.c b/server/src/media/helper/lm_job.cindex e4fc4d3..db55da6 100644--- a/server/src/media/helper/lm_job.c+++ b/server/src/media/helper/lm_job.c@@ -51,7 +51,7 @@ static void job_thumb(uint32_t id, int in, int out, int size, int as_pixels) {int is_video = vi >= 0 && !(fmt->streams[vi]->disposition & AV_DISPOSITION_ATTACHED_PIC) && dur > 1000;int orient = 0;AVFrame *f = lm_decode_still(fmt, is_video ? (dur > 30000 ? dur / 10 : dur / 3) : 0, &orient, !is_video);- if (!f) { lm_close_input(&fmt); lm_result(id, -2, "sin imagen", -1); return; }+ if (!f) { lm_close_input(&fmt); lm_result(id, -2, "media.notAnImage", -1); return; }if (size < 16) size = 16;if (size > 1024) size = 1024;int sw = f->width, sh = f->height;@@ -62,7 +62,7 @@ static void job_thumb(uint32_t id, int in, int out, int size, int as_pixels) {AVFrame *o = lm_to_bgra(f, tw, th, 1);av_frame_free(&f);lm_close_input(&fmt);- if (!o) { lm_result(id, -1, "no se pudo escalar", -1); return; }+ if (!o) { lm_result(id, -1, "media.scaleFailed", -1); return; }char json[160];snprintf(json, sizeof json, "{\"width\":%d,\"height\":%d,\"orientation\":%d,\"video\":%s,\"duration\":%lld}", tw, th, orient,is_video ? "true" : "false", (long long)dur);@@ -70,14 +70,14 @@ static void job_thumb(uint32_t id, int in, int out, int size, int as_pixels) {void *map;size_t n = (size_t)tw * th * 4;int mfd = lm_memfd(n, &map, "lord-media-poster");- if (mfd < 0) { av_frame_free(&o); lm_result(id, -1, "sin memoria", -1); return; }+ if (mfd < 0) { av_frame_free(&o); lm_result(id, -1, "sys.outOfMemory", -1); return; }for (int y = 0; y < th; y++) memcpy((uint8_t *)map + (size_t)y * tw * 4, o->data[0] + (size_t)y * o->linesize[0], (size_t)tw * 4);munmap(map, n);lm_result(id, 0, json, mfd);close(mfd);} else {int r = lm_encode_image(o, "png", 0, out);- lm_result(id, r ? -1 : 0, r ? "no se pudo codificar" : json, -1);+ lm_result(id, r ? -1 : 0, r ? "media.encodeFailed" : json, -1);}av_frame_free(&o);}@@ -102,17 +102,17 @@ static void job_image(uint32_t id, int in) {av_packet_free(&pkt);}lm_close_input(&fmt);- if (!f) { lm_result(id, -2, "no es una imagen", -1); return; }+ if (!f) { lm_result(id, -2, "media.notAnImage", -1); return; }int w, h;fit_size(f->width, f->height, MP_MAX_DIM, &w, &h);AVFrame *o = lm_to_bgra(f, w, h, 1);int ow = f->width, oh = f->height;av_frame_free(&f);- if (!o) { lm_result(id, -1, "no se pudo convertir", -1); return; }+ if (!o) { lm_result(id, -1, "media.convertFailed", -1); return; }void *map;size_t n = (size_t)w * h * 4;int mfd = lm_memfd(n, &map, "lord-media-image");- if (mfd < 0) { av_frame_free(&o); lm_result(id, -1, "sin memoria", -1); return; }+ if (mfd < 0) { av_frame_free(&o); lm_result(id, -1, "sys.outOfMemory", -1); return; }int alpha = 0;for (int y = 0; y < h; y++) {const uint8_t *s = o->data[0] + (size_t)y * o->linesize[0];@@ -139,12 +139,12 @@ static void job_edit(uint32_t id, int in, int out, const char *p) {int orient = 0;AVFrame *f = lm_decode_still(fmt, 0, &orient, 0);lm_close_input(&fmt);- if (!f) { lm_result(id, -2, "no es una imagen", -1); return; }+ if (!f) { lm_result(id, -2, "media.notAnImage", -1); return; }int w, h;fit_size(f->width, f->height, MP_MAX_DIM, &w, &h);AVFrame *o = lm_to_bgra(f, w, h, 0);av_frame_free(&f);- if (!o) { lm_result(id, -1, "sin memoria", -1); return; }+ if (!o) { lm_result(id, -1, "sys.outOfMemory", -1); return; }int rot = (((int)mp_param_int(p, "rotate", 0) + orient) % 360 + 360) % 360;int bright = (int)mp_param_int(p, "brightness", 0), contrast = (int)mp_param_int(p, "contrast", 0);if (mp_param(p, "format", format, sizeof format)) snprintf(format, sizeof format, "png");@@ -152,7 +152,7 @@ static void job_edit(uint32_t id, int in, int out, const char *p) {int rw = (rot == 90 || rot == 270) ? h : w, rh = (rot == 90 || rot == 270) ? w : h;AVFrame *r = av_frame_alloc();r->format = AV_PIX_FMT_BGRA; r->width = rw; r->height = rh;- if (av_frame_get_buffer(r, 0) < 0) { av_frame_free(&o); av_frame_free(&r); lm_result(id, -1, "sin memoria", -1); return; }+ if (av_frame_get_buffer(r, 0) < 0) { av_frame_free(&o); av_frame_free(&r); lm_result(id, -1, "sys.outOfMemory", -1); return; }for (int y = 0; y < rh; y++) {uint32_t *d = (uint32_t *)(r->data[0] + (size_t)y * r->linesize[0]);for (int x = 0; x < rw; x++) {@@ -174,7 +174,7 @@ static void job_edit(uint32_t id, int in, int out, const char *p) {if (cy < 0) cy = 0;if (cx + cw > rw) cw = rw - cx;if (cy + ch > rh) ch = rh - cy;- if (cw < 1 || ch < 1) { av_frame_free(&r); lm_result(id, -1, "recorte inválido", -1); return; }+ if (cw < 1 || ch < 1) { av_frame_free(&r); lm_result(id, -1, "media.invalidCrop", -1); return; }AVFrame *c = av_frame_alloc();c->format = AV_PIX_FMT_BGRA; c->width = cw; c->height = ch;av_frame_get_buffer(c, 0);@@ -198,7 +198,7 @@ static void job_edit(uint32_t id, int in, int out, const char *p) {int e = lm_encode_image(c, format, (int)mp_param_int(p, "quality", 92), out);char json[96];snprintf(json, sizeof json, "{\"width\":%d,\"height\":%d}", cw, ch);- lm_result(id, e ? -1 : 0, e ? "no se pudo codificar" : json, -1);+ lm_result(id, e ? -1 : 0, e ? "media.encodeFailed" : json, -1);av_frame_free(&c);}@@ -206,11 +206,11 @@ static void job_edit(uint32_t id, int in, int out, const char *p) {static void job_encode(uint32_t id, int mfd, int out, int w, int h, const char *p) {struct stat st;if (w <= 0 || h <= 0 || w > MP_MAX_DIM || h > MP_MAX_DIM || fstat(mfd, &st) || st.st_size < (off_t)w * h * 4) {- lm_result(id, -1, "píxeles inválidos", -1);+ lm_result(id, -1, "media.invalidPixels", -1);return;}void *m = mmap(NULL, (size_t)w * h * 4, PROT_READ, MAP_SHARED, mfd, 0);- if (m == MAP_FAILED) { lm_result(id, -1, "no se pudo mapear", -1); return; }+ if (m == MAP_FAILED) { lm_result(id, -1, "media.mapFailed", -1); return; }AVFrame *f = av_frame_alloc();f->format = AV_PIX_FMT_BGRA; f->width = w; f->height = h;av_frame_get_buffer(f, 0);@@ -220,7 +220,7 @@ static void job_encode(uint32_t id, int mfd, int out, int w, int h, const char *if (mp_param(p, "format", format, sizeof format)) snprintf(format, sizeof format, "png");int r = lm_encode_image(f, format, (int)mp_param_int(p, "quality", 92), out);av_frame_free(&f);- lm_result(id, r ? -1 : 0, r ? "no se pudo codificar" : "{}", -1);+ lm_result(id, r ? -1 : 0, r ? "media.encodeFailed" : "{}", -1);}/* ---- audio: decode everything (or a segment) to float mono/stereo ---- */@@ -239,20 +239,20 @@ static int audio_open(AudioIn *a, int in, int rate, int channels, char *err, siza->fmt = lm_open_input(in, err, errlen);if (!a->fmt) return -1;a->ai = av_find_best_stream(a->fmt, AVMEDIA_TYPE_AUDIO, -1, -1, NULL, 0);- if (a->ai < 0) { snprintf(err, errlen, "sin audio"); return -1; }+ if (a->ai < 0) { lerr_set(err, errlen, "media.noAudio", NULL); return -1; }AVStream *st = a->fmt->streams[a->ai];const AVCodec *codec = avcodec_find_decoder(st->codecpar->codec_id);a->dec = codec ? avcodec_alloc_context3(codec) : NULL;- if (!a->dec) { snprintf(err, errlen, "sin decodificador"); return -1; }+ if (!a->dec) { lerr_set(err, errlen, "media.noDecoder", NULL); return -1; }avcodec_parameters_to_context(a->dec, st->codecpar);a->dec->pkt_timebase = st->time_base;- if (avcodec_open2(a->dec, codec, NULL) < 0) { snprintf(err, errlen, "no se pudo abrir el audio"); return -1; }+ if (avcodec_open2(a->dec, codec, NULL) < 0) { lerr_set(err, errlen, "media.audioOpenFailed", NULL); return -1; }a->rate = rate > 0 ? rate : a->dec->sample_rate;a->channels = channels;AVChannelLayout out;av_channel_layout_default(&out, channels);if (swr_alloc_set_opts2(&a->swr, &out, AV_SAMPLE_FMT_FLT, a->rate, &a->dec->ch_layout, a->dec->sample_fmt, a->dec->sample_rate, 0, NULL) < 0 ||- swr_init(a->swr) < 0) { snprintf(err, errlen, "no se pudo convertir el audio"); return -1; }+ swr_init(a->swr) < 0) { lerr_set(err, errlen, "media.audioConvertFailed", NULL); return -1; }a->pkt = av_packet_alloc();a->frame = av_frame_alloc();return 0;@@ -325,11 +325,11 @@ static void job_transcode(uint32_t id, int in, int out, const char *p) {char err[128], format[16];if (mp_param(p, "format", format, sizeof format)) snprintf(format, sizeof format, "opus");int opus = !strcmp(format, "opus"), mp3 = !strcmp(format, "mp3");- if (!opus && !mp3 && strcmp(format, "wav")) { lm_result(id, -1, "formato no soportado", -1); return; }+ if (!opus && !mp3 && strcmp(format, "wav")) { lm_result(id, -1, "media.unsupportedFormat", -1); return; }const AVCodec *codec = opus ? avcodec_find_encoder_by_name("libopus") : mp3 ? avcodec_find_encoder_by_name("libmp3lame"): avcodec_find_encoder(AV_CODEC_ID_PCM_S16LE);if (!codec && opus) codec = avcodec_find_encoder(AV_CODEC_ID_OPUS);- if (!codec) { lm_result(id, -1, "sin codificador", -1); return; }+ if (!codec) { lm_result(id, -1, "media.noEncoder", -1); return; }AudioIn a;int rate = mp3 ? 44100 : 48000; /* MP3 at 44.1 kHz; Opus and WAV like the recorder */if (audio_open(&a, in, rate, 1, err, sizeof err)) { audio_close(&a); lm_result(id, -1, err, -1); return; }@@ -346,13 +346,13 @@ static void job_transcode(uint32_t id, int in, int out, const char *p) {enc->bit_rate = opus ? 64000 * ch : mp3 ? 96000 * ch : 0;enc->time_base = (AVRational){ 1, rate };AVFormatContext *oc = lm_open_output(out, opus ? "ogg" : mp3 ? "mp3" : "wav");- if (!oc) { avcodec_free_context(&enc); audio_close(&a); lm_result(id, -1, "sin salida", -1); return; }+ if (!oc) { avcodec_free_context(&enc); audio_close(&a); lm_result(id, -1, "media.noOutput", -1); return; }if (oc->oformat->flags & AVFMT_GLOBALHEADER) enc->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;- if (avcodec_open2(enc, codec, NULL) < 0) { lm_close_output(oc, 0); avcodec_free_context(&enc); audio_close(&a); lm_result(id, -1, "no se pudo abrir el codificador", -1); return; }+ if (avcodec_open2(enc, codec, NULL) < 0) { lm_close_output(oc, 0); avcodec_free_context(&enc); audio_close(&a); lm_result(id, -1, "media.encoderOpenFailed", -1); return; }AVStream *os = avformat_new_stream(oc, NULL);avcodec_parameters_from_context(os->codecpar, enc);os->time_base = enc->time_base;- if (avformat_write_header(oc, NULL) < 0) { lm_close_output(oc, 0); avcodec_free_context(&enc); audio_close(&a); lm_result(id, -1, "no se pudo escribir", -1); return; }+ if (avformat_write_header(oc, NULL) < 0) { lm_close_output(oc, 0); avcodec_free_context(&enc); audio_close(&a); lm_result(id, -1, "media.writeFailed", -1); return; }int64_t from = mp_param_int(p, "from", 0) * rate / 1000, to = mp_param_int(p, "to", -1);to = to < 0 ? INT64_MAX : to * rate / 1000;/* interleaved float → the encoder's format, in frames of frame_size */@@ -408,7 +408,7 @@ static void job_transcode(uint32_t id, int in, int out, const char *p) {int r = lm_close_output(oc, 1);char json[96];snprintf(json, sizeof json, "{\"duration\":%lld}", (long long)(pts * 1000 / rate));- lm_result(id, (r < 0 || !okw) ? -1 : 0, (r < 0 || !okw) ? "no se pudo exportar" : json, -1);+ lm_result(id, (r < 0 || !okw) ? -1 : 0, (r < 0 || !okw) ? "media.exportFailed" : json, -1);swr_free(&cv);av_frame_free(&ef);av_packet_free(&pkt);@@ -468,7 +468,7 @@ void lm_worker(void) {case MW_TRANSCODE: job_transcode(m.id, fds[0], fds[1], payload); break;case MW_WAVEFORM: job_waveform(m.id, fds[0], (int)m.v[1]); break;case MW_SELFTEST: job_selftest(m.id); break;- default: lm_result(m.id, -1, "trabajo desconocido", -1);+ default: lm_result(m.id, -1, "media.unknownJob", -1);}LM_DBG("trabajo %u (%lld) en %.1f ms", m.id, (long long)m.v[0], lm_now_ms() - t0);closefds(fds);diff --git a/server/src/media/helper/lm_main.c b/server/src/media/helper/lm_main.cindex 812c7ab..d7c88ce 100644--- a/server/src/media/helper/lm_main.c+++ b/server/src/media/helper/lm_main.c@@ -79,7 +79,7 @@ int main(int argc, char **argv) {case MK_SCREENREC: lm_screenrec(payload, fds[0], fds[1], fds[2]); break;case MK_CAMERA: lm_camera(payload, fds[0], fds[1]); break;case MK_AUDIOREC: lm_audiorec(payload, fds[0], fds[1]); break;- default: LM_LOG("tipo desconocido %lld", (long long)m.v[0]); return 1;+ default: LM_LOG("unknown kind %lld", (long long)m.v[0]); return 1;}return 0;}diff --git a/server/src/media/helper/lm_play.c b/server/src/media/helper/lm_play.cindex e349c54..05c2b58 100644--- a/server/src/media/helper/lm_play.c+++ b/server/src/media/helper/lm_play.c@@ -534,7 +534,7 @@ void lm_player(const char *params, int fd, int pulse, int render) {close(pulse);P.fmt = lm_open_input(fd, err, sizeof err);- if (!P.fmt) { lm_error("no se pudo abrir: %s", err); return; }+ if (!P.fmt) { lm_error("%s", err); return; }P.start_ms = P.fmt->start_time != AV_NOPTS_VALUE ? P.fmt->start_time / 1000 : 0;P.dur_ms = P.fmt->duration > 0 ? P.fmt->duration / 1000 : 0;P.vi = av_find_best_stream(P.fmt, AVMEDIA_TYPE_VIDEO, -1, -1, NULL, 0);@@ -556,7 +556,7 @@ void lm_player(const char *params, int fd, int pulse, int render) {enum AVMediaType t = P.fmt->streams[i]->codecpar->codec_type;if (t == AVMEDIA_TYPE_AUDIO || t == AVMEDIA_TYPE_SUBTITLE) P.fmt->streams[i]->discard = AVDISCARD_DEFAULT;}- if (P.vi < 0 && P.ai < 0) { lm_error("no hay audio ni video que se pueda reproducir"); lm_close_input(&P.fmt); return; }+ if (P.vi < 0 && P.ai < 0) { lm_error("media.nothingToPlay"); lm_close_input(&P.fmt); return; }C.audio = P.ai >= 0 && AR != NULL;C.anchor_byte = -1;send_info(render);@@ -566,7 +566,7 @@ void lm_player(const char *params, int fd, int pulse, int render) {/* cover art: a single frame, presented right away */AVFrame *cover = P.cover ? lm_decode_still(P.fmt, 0, NULL, 1) : NULL;if (P.cover) { avcodec_free_context(&P.vdec); av_seek_frame(P.fmt, -1, 0, AVSEEK_FLAG_BACKWARD); }- if (pthread_create(&P.th, NULL, decode_thread, NULL)) { lm_error("sin hilos"); return; }+ if (pthread_create(&P.th, NULL, decode_thread, NULL)) { lm_error("media.threadFailed"); return; }static char payload[MP_PAYLOAD_MAX + 1];double last_pos = 0, last_stats = 0, last_shown_ms = lm_now_ms();diff --git a/server/src/media/helper/lm_rec.c b/server/src/media/helper/lm_rec.cindex 8857585..849182d 100644--- a/server/src/media/helper/lm_rec.c+++ b/server/src/media/helper/lm_rec.c@@ -58,7 +58,7 @@ void lm_audiorec(const char *params, int out, int pulse) {close(pulse);R.out_fd = out;if (out < 0 || !ring) {- lm_error("no hay micrófono (PipeWire)");+ lm_error("rec.noMicrophone");mp_sendv(LM_SOCK, MM_STATE, 0, MS_FAILED, 0, 0, 0);return;}diff --git a/server/src/media/media.c b/server/src/media/media.cindex 407f3a9..1d2a169 100644--- a/server/src/media/media.c+++ b/server/src/media/media.c@@ -17,6 +17,7 @@#include "../pkg/crypto.h"#include "../ui/ui.h"#include "../ui/js_sys.h"+#include "../errcode.h"#include <dirent.h>#include <errno.h>@@ -576,7 +577,7 @@ static void job_finish(Job *j, int status, int fd) {media_src_damage(s);media_event(s->id, "ready", "%s", payload);} else {- media_json_str(esc, sizeof esc, ok ? "no se pudo leer la imagen" : payload);+ media_json_str(esc, sizeof esc, ok || !lerr_is(payload) ? "media.imageUnreadable" : payload);media_event(s->id, "error", "{\"message\":%s}", esc);}}@@ -636,7 +637,7 @@ static void worker_kick(int bg) {wk->sock = media_spawn(MK_WORKER, NULL, NULL, 0, &wk->pid);if (wk->sock < 0) {/* no lord-media: all jobs fail */- while (queue[bg]) { Job *j = queue[bg]; queue[bg] = j->next; queued[bg]--; payload[0] = 0; snprintf(payload, sizeof payload, "sin lord-media"); job_finish(j, -1, -1); job_free(j); }+ while (queue[bg]) { Job *j = queue[bg]; queue[bg] = j->next; queued[bg]--; payload[0] = 0; snprintf(payload, sizeof payload, "media.noHelper"); job_finish(j, -1, -1); job_free(j); }queue_tail[bg] = NULL;return;}@@ -648,7 +649,7 @@ static void worker_kick(int bg) {int64_t v[6] = { j->kind, j->a, j->b, 0, 0, 0 };if (mp_send(wk->sock, MM_JOB, (uint32_t)j->id, v, j->params && j->purpose != JP_THUMB ? j->params : NULL,j->params && j->purpose != JP_THUMB ? strlen(j->params) : 0, j->fds, j->nfds)) {- snprintf(payload, sizeof payload, "el ayudante no responde");+ snprintf(payload, sizeof payload, "media.helperNotResponding");job_finish(j, -1, -1);job_free(j);return;@@ -697,7 +698,7 @@ static void worker_dispatch(int bg) {wk->pid = 0;if (wk->cur) {fprintf(stderr, "media: lord-media crashed during a job (%d); moving on to the next\n", wk->cur->kind);- snprintf(payload, sizeof payload, "el ayudante se cayó");+ snprintf(payload, sizeof payload, "media.helperCrashed");job_finish(wk->cur, -1, -1);job_free(wk->cur);wk->cur = NULL;diff --git a/server/src/net/actions.c b/server/src/net/actions.cindex eca826a..ea84ab1 100644--- a/server/src/net/actions.c+++ b/server/src/net/actions.c@@ -65,9 +65,9 @@ static int is_physical(const char *ifname) {}static int check_if(const char *ifname, int must_be_free) {- if (!valid_ifname(ifname) || !rt_ifindex(ifname)) { admin_say("ERR", "interfaz desconocida: %s", ifname); return -1; }+ if (!valid_ifname(ifname) || !rt_ifindex(ifname)) { admin_err("net.unknownInterface", "name", ifname, NULL); return -1; }if (must_be_free && managed_by_system(ifname)) {- admin_say("ERR", "la interfaz %s la maneja el sistema (systemd-networkd/ifupdown): pasala a LordOS primero", ifname);+ admin_err("net.systemManaged", "name", ifname, NULL);return -1;}return 0;@@ -156,7 +156,7 @@ void net_act_restore(const AdminReq *r, const char *arg, size_t len) {if (o) {pid_t p = (pid_t)atoi(o);free(o);- if (p > 1 && p != getpid() && kill(p, 0) == 0) { admin_say("OK", "0 interfaz(es): la maneja otra sesión"); return; }+ if (p > 1 && p != getpid() && kill(p, 0) == 0) { admin_ok("net.otherSession", NULL); return; }}FILE *of = fopen(NET_RUN_DIR "/net-owner", "w");if (of) { fprintf(of, "%d\n", (int)getpid()); fclose(of); }@@ -175,7 +175,7 @@ void net_act_restore(const AdminReq *r, const char *arg, size_t len) {if (is_physical(name)) { if (!apply_config(name, "method=dhcp\n")) n++; }}if (ifs) if_freenameindex(ifs);- admin_say("OK", "%d interfaz(es)", n);+ admin_ok("net.restored", "count", lerr_int(n), NULL);}void net_act_up(const AdminReq *r, const char *arg, size_t len) {@@ -187,7 +187,7 @@ void net_act_up(const AdminReq *r, const char *arg, size_t len) {char *t = load_if_conf(arg);if (!e) apply_config(arg, t ? t : (is_physical(arg) ? "method=dhcp\n" : "method=none\n"));free(t);- if (e) admin_say("ERR", "no se pudo levantar %s: %s", arg, strerror(-e)); else admin_say("OK", "%s levantada", arg);+ if (e) admin_err("net.upFailed", "name", arg, "errno", lerr_errno(-e), NULL); else admin_ok("net.up", "name", arg, NULL);}void net_act_down(const AdminReq *r, const char *arg, size_t len) {@@ -197,13 +197,13 @@ void net_act_down(const AdminReq *r, const char *arg, size_t len) {int fd = nl_open(NETLINK_ROUTE, 0);int e = fd >= 0 ? rt_link_set(fd, rt_ifindex(arg), 0) : -1;if (fd >= 0) close(fd);- if (e) admin_say("ERR", "no se pudo bajar %s: %s", arg, strerror(-e)); else admin_say("OK", "%s bajada", arg);+ if (e) admin_err("net.downFailed", "name", arg, "errno", lerr_errno(-e), NULL); else admin_ok("net.down", "name", arg, NULL);}void net_act_config(const AdminReq *r, const char *arg, size_t len) {(void)r; (void)len;char *copy = strdup(arg);- if (!copy) { admin_say("ERR", "sin memoria"); return; }+ if (!copy) { admin_err("sys.outOfMemory", NULL); return; }char *nl = strchr(copy, '\n');char *body = nl ? nl + 1 : (char *)"";if (nl) *nl = 0;@@ -230,18 +230,18 @@ void net_act_config(const AdminReq *r, const char *arg, size_t len) {else if (!strcmp(k, "gateway")) { if (*v && parse_ip(v, &fam, a)) ok = 0; else if (*v) buf_printf(&b, "gateway=%s\n", v); }else if (!strcmp(k, "dns")) { if (parse_ip(v, &fam, a)) ok = 0; else buf_printf(&b, "dns=%s\n", v); }else ok = 0;- if (!ok) admin_say("ERR", "valor inválido: %s=%s", k, v);+ if (!ok) admin_err("net.invalidValue", "key", k, "value", v, NULL);}- if (ok && !method[0]) { ok = 0; admin_say("ERR", "falta method (dhcp, static u off)"); }- if (ok && !strcmp(method, "static") && !naddr) { ok = 0; admin_say("ERR", "falta address"); }+ if (ok && !method[0]) { ok = 0; admin_err("net.missingMethod", NULL); }+ if (ok && !strcmp(method, "static") && !naddr) { ok = 0; admin_err("net.missingAddress", NULL); }if (ok) {Buf f = {0};buf_printf(&f, "method=%s\n%s", method, b.p ? b.p : "");char path[128];snprintf(path, sizeof path, NET_IF_DIR "/%s.conf", copy);- if (f.oom || write_file_atomic(path, f.p, f.len, 0644)) admin_say("ERR", "no se pudo guardar");- else if (apply_config(copy, f.p)) admin_say("ERR", "no se pudo aplicar en %s", copy);- else admin_say("OK", "%s: %s", copy, method);+ if (f.oom || write_file_atomic(path, f.p, f.len, 0644)) admin_err("net.saveFailed", NULL);+ else if (apply_config(copy, f.p)) admin_err("net.applyFailed", "name", copy, NULL);+ else admin_ok("net.configured", "name", copy, "method", method, NULL);buf_free(&f);}buf_free(&b);@@ -252,17 +252,17 @@ void net_act_config(const AdminReq *r, const char *arg, size_t len) {void net_act_manage(const AdminReq *r, const char *arg, size_t len) {(void)r; (void)len;if (check_if(arg, 0)) return;- if (!managed_by_system(arg)) { admin_say("OK", "%s ya era de LordOS", arg); return; }+ if (!managed_by_system(arg)) { admin_ok("net.alreadyLordos", "name", arg, NULL); return; }char path[160];snprintf(path, sizeof path, "/etc/systemd/network/00-lordos-%s.network", arg);char body[200];int n = snprintf(body, sizeof body, "# LordOS manages this interface (net-manage)\n[Match]\nName=%s\n\n[Link]\nUnmanaged=yes\n", arg);- if (write_file_atomic(path, body, (size_t)n, 0644)) { admin_say("ERR", "no se pudo escribir %s", path); return; }+ if (write_file_atomic(path, body, (size_t)n, 0644)) { admin_err("sys.writeFailed", "path", path, NULL); return; }char out[256];const char *argv[] = { NETWORKCTL, "reload", NULL };if (access(NETWORKCTL, X_OK) == 0) admin_run_capture(argv, out, sizeof out);for (int i = 0; i < 30 && managed_by_system(arg); i++) usleep(100000);- if (managed_by_system(arg)) { unlink(path); admin_run_capture(argv, out, sizeof out); admin_say("ERR", "%s la sigue manejando el sistema (¿ifupdown?)", arg); return; }+ if (managed_by_system(arg)) { unlink(path); admin_run_capture(argv, out, sizeof out); admin_err("net.stillSystem", "name", arg, NULL); return; }int fd = nl_open(NETLINK_ROUTE, 0);if (fd >= 0) { rt_addr_flush(fd, rt_ifindex(arg), AF_INET); close(fd); }char *t = load_if_conf(arg);@@ -273,7 +273,7 @@ void net_act_manage(const AdminReq *r, const char *arg, size_t len) {}apply_config(arg, t ? t : "method=dhcp\n");free(t);- admin_say("OK", "%s ahora la maneja LordOS", arg);+ admin_ok("net.managed", "name", arg, NULL);}void net_act_unmanage(const AdminReq *r, const char *arg, size_t len) {@@ -291,14 +291,14 @@ void net_act_unmanage(const AdminReq *r, const char *arg, size_t len) {const char *rc[] = { NETWORKCTL, "reconfigure", arg, NULL };admin_run_capture(rc, out, sizeof out);}- admin_say("OK", "%s vuelve al sistema", arg);+ admin_ok("net.unmanaged", "name", arg, NULL);}/* ---- Wi-Fi ---- */static int check_wifi(const char *ifname) {if (check_if(ifname, 1)) return -1;- if (!is_wifi(ifname)) { admin_say("ERR", "%s no es Wi-Fi", ifname); return -1; }+ if (!is_wifi(ifname)) { admin_err("wifi.notWifi", "name", ifname, NULL); return -1; }return 0;}@@ -307,16 +307,16 @@ void net_act_wifi_scan(const AdminReq *r, const char *arg, size_t len) {if (check_wifi(arg)) return;char d[40];snprintf(d, sizeof d, "wpa:%s", arg);- if (!admin_daemon_running(d)) { admin_say("ERR", "la interfaz %s no tiene wpa_supplicant (net-up)", arg); return; }+ if (!admin_daemon_running(d)) { admin_err("wifi.noSupplicant", "name", arg, NULL); return; }wifi_act_scan(arg);}void net_act_wifi_connect(const AdminReq *r, const char *arg, size_t len) {(void)r; (void)len;char *copy = strdup(arg), *l[3] = { NULL, NULL, NULL };- if (!copy) { admin_say("ERR", "sin memoria"); return; }+ if (!copy) { admin_err("sys.outOfMemory", NULL); return; }int k = split_lines(copy, l, 3);- if (k < 2) { admin_say("ERR", "formato: interfaz, SSID y contraseña en líneas"); free(copy); return; }+ if (k < 2) { admin_err("admin.invalidArgument", NULL); free(copy); return; }if (!check_wifi(l[0])) wifi_act_connect(l[0], l[1], k > 2 ? l[2] : "");memset(copy, 0, len);free(copy);@@ -353,33 +353,33 @@ static int vpn_type(const char *name, char *type, size_t n) {}static int check_vpn(const char *name, char *type, size_t n) {- if (!valid_vpn_name(name) || vpn_type(name, type, n)) { admin_say("ERR", "VPN desconocida: %s", name); return -1; }+ if (!valid_vpn_name(name) || vpn_type(name, type, n)) { admin_err("vpn.unknown", "name", name, NULL); return -1; }return 0;}void net_act_vpn_import(const AdminReq *r, const char *arg, size_t len) {(void)r;char *copy = strdup(arg), *l[3] = { NULL, NULL, NULL };- if (!copy) { admin_say("ERR", "sin memoria"); return; }+ if (!copy) { admin_err("sys.outOfMemory", NULL); return; }int k = split_lines(copy, l, 3);char err[200] = "";- if (k < 3) admin_say("ERR", "formato: tipo, nombre y configuración");- else if (!valid_vpn_name(l[1])) admin_say("ERR", "nombre inválido (letras, números, - y _; hasta 24)");+ if (k < 3) admin_err("admin.invalidArgument", NULL);+ else if (!valid_vpn_name(l[1])) admin_err("vpn.invalidName", NULL);else if (!strcmp(l[0], "wireguard")) {char pub[64];- if (wg_import(l[1], l[2], pub, err, sizeof err)) admin_say("ERR", "%s", err);- else admin_say("OK", "%s", pub); /* the public key, to give to the server */+ if (wg_import(l[1], l[2], pub, err, sizeof err)) admin_say("ERR", "%s", err); /* i18n-ok: err is a code line */+ else admin_say("OK", "%s", pub); /* i18n-ok: the public key (data), to give to the server */} else if (!strcmp(l[0], "openvpn")) {- if (access("/usr/sbin/openvpn", X_OK)) admin_say("ERR", "falta openvpn (paquete openvpn)");- else if (ovpn_import(l[1], l[2], err, sizeof err)) admin_say("ERR", "%s", err);- else admin_say("OK", "importada");- } else if (!vpn_type_known(l[0])) admin_say("ERR", "tipo de VPN no soportado: %s", l[0]);- else if (!vpn_type_available(l[0])) admin_say("ERR", "falta el programa de %s (net-vpn-enable o los paquetes %s)", l[0], vpn_type_package(l[0]));+ if (access("/usr/sbin/openvpn", X_OK)) admin_err("vpn.missingProgram", "type", "openvpn", "package", "openvpn", NULL);+ else if (ovpn_import(l[1], l[2], err, sizeof err)) admin_say("ERR", "%s", err); /* i18n-ok: err is a code line */+ else admin_ok("vpn.imported", NULL);+ } else if (!vpn_type_known(l[0])) admin_err("vpn.unsupportedType", "type", l[0], NULL);+ else if (!vpn_type_available(l[0])) admin_err("vpn.missingProgram", "type", l[0], "package", vpn_type_package(l[0]), NULL);else {int (*imp)(const char *, const char *, char *, size_t) = !strcmp(l[0], "ipsec") ? ipsec_import : !strcmp(l[0], "pptp") ? pptp_import: !strcmp(l[0], "openconnect") ? oc_import : forti_import;- if (imp(l[1], l[2], err, sizeof err)) admin_say("ERR", "%s", err);- else admin_say("OK", "importada");+ if (imp(l[1], l[2], err, sizeof err)) admin_say("ERR", "%s", err); /* i18n-ok: err is a code line */+ else admin_ok("vpn.imported", NULL);}memset(copy, 0, len);free(copy);@@ -388,13 +388,13 @@ void net_act_vpn_import(const AdminReq *r, const char *arg, size_t len) {void net_act_vpn_credentials(const AdminReq *r, const char *arg, size_t len) {(void)r;char *copy = strdup(arg), *l[3] = { NULL, NULL, NULL }, type[24];- if (!copy) { admin_say("ERR", "sin memoria"); return; }+ if (!copy) { admin_err("sys.outOfMemory", NULL); return; }int k = split_lines(copy, l, 3);- if (k < 3) admin_say("ERR", "formato: nombre, usuario y contraseña");+ if (k < 3) admin_err("admin.invalidArgument", NULL);else if (!check_vpn(l[0], type, sizeof type)) {- if (strcmp(type, "openvpn")) admin_say("ERR", "solo OpenVPN usa usuario y contraseña");- else if (ovpn_set_credentials(l[0], l[1], l[2])) admin_say("ERR", "usuario o contraseña inválidos");- else admin_say("OK", "guardado");+ if (strcmp(type, "openvpn")) admin_err("vpn.credentialsOnlyOpenvpn", NULL);+ else if (ovpn_set_credentials(l[0], l[1], l[2])) admin_err("vpn.invalidCredentials", NULL);+ else admin_ok("vpn.saved", NULL);}memset(copy, 0, len);free(copy);@@ -411,16 +411,16 @@ void net_act_vpn_up(const AdminReq *r, const char *arg, size_t len) {char type[24], err[200] = "";if (check_vpn(arg, type, sizeof type)) return;if (!strcmp(type, "wireguard")) {- if (wg_up(arg, err, sizeof err)) { admin_say("ERR", "%s", err); admin_event("net vpn %s error", arg); }- else { admin_say("OK", "conectada"); admin_event("net vpn %s connected", arg); }+ if (wg_up(arg, err, sizeof err)) { admin_say("ERR", "%s", err); admin_event("net vpn %s error %s", arg, err); } /* i18n-ok: err is a code line */+ else { admin_ok("vpn.connected", NULL); admin_event("net vpn %s connected", arg); }return;}static char name_arg[32];char d[40];snprintf(d, sizeof d, "vpn:%s", arg);snprintf(name_arg, sizeof name_arg, "%s", arg);- if (admin_daemon_running(d)) { admin_say("OK", "ya estaba conectándose"); return; }- if (!vpn_type_available(type)) { admin_say("ERR", "falta el programa de %s (net-vpn-enable)", type); return; }+ if (admin_daemon_running(d)) { admin_ok("vpn.alreadyConnecting", NULL); return; }+ if (!vpn_type_available(type)) { admin_err("vpn.missingProgram", "type", type, "package", vpn_type_package(type), NULL); return; }void (*fn)(void *) = !strcmp(type, "openvpn") ? ovpn_entry : !strcmp(type, "ipsec") ? ipsec_entry : !strcmp(type, "pptp") ? pptp_entry: !strcmp(type, "openconnect") ? oc_entry : forti_entry;if (!strcmp(type, "ipsec") && access("/run/charon.pid", F_OK) == 0) {@@ -428,10 +428,10 @@ void net_act_vpn_up(const AdminReq *r, const char *arg, size_t len) {char *t = read_file("/run/charon.pid", 32, NULL);int busy = t && atoi(t) > 1 && kill(atoi(t), 0) == 0;free(t);- if (busy) { admin_say("ERR", "ya hay otra VPN IPsec conectada (una a la vez)"); return; }+ if (busy) { admin_err("vpn.ipsecBusy", NULL); return; }}- if (admin_daemon_fork(d, fn, name_arg)) admin_say("ERR", "no se pudo iniciar");- else admin_say("OK", "conectando");+ if (admin_daemon_fork(d, fn, name_arg)) admin_err("vpn.startFailed", NULL);+ else admin_ok("vpn.connecting", NULL);}void net_act_vpn_down(const AdminReq *r, const char *arg, size_t len) {@@ -439,10 +439,10 @@ void net_act_vpn_down(const AdminReq *r, const char *arg, size_t len) {char type[24];if (check_vpn(arg, type, sizeof type)) return;if (!strcmp(type, "wireguard")) {- if (wg_down(arg)) admin_say("ERR", "no estaba conectada");- else { admin_say("OK", "desconectada"); admin_event("net vpn %s disconnected", arg); }- } else if (ovpn_down(arg)) admin_say("ERR", "no estaba conectada"); /* "vpn:<name>", any type */- else admin_say("OK", "desconectando");+ if (wg_down(arg)) admin_err("vpn.notConnected", NULL);+ else { admin_ok("vpn.disconnected", NULL); admin_event("net vpn %s disconnected", arg); }+ } else if (ovpn_down(arg)) admin_err("vpn.notConnected", NULL); /* "vpn:<name>", any type */+ else admin_ok("vpn.disconnecting", NULL);}void net_act_vpn_delete(const AdminReq *r, const char *arg, size_t len) {@@ -463,7 +463,7 @@ void net_act_vpn_delete(const AdminReq *r, const char *arg, size_t len) {snprintf(p, sizeof p, gen[i], arg);unlink(p);}- admin_say("OK", "borrada");+ admin_ok("vpn.deleted", NULL);}static void status_one(const char *name) {@@ -479,7 +479,7 @@ static void status_one(const char *name) {void net_act_vpn_status(const AdminReq *r, const char *arg, size_t len) {(void)r; (void)len;- if (*arg) { status_one(arg); admin_say("OK", "1"); return; }+ if (*arg) { status_one(arg); admin_say("OK", "1"); return; } /* i18n-ok: a count (data) */DIR *d = opendir(NET_VPN_DIR);struct dirent *e;int n = 0;@@ -493,7 +493,7 @@ void net_act_vpn_status(const AdminReq *r, const char *arg, size_t len) {n++;}if (d) closedir(d);- admin_say("OK", "%d", n);+ admin_say("OK", "%d", n); /* i18n-ok: a count (data) */}/* net-vpn-enable openconnect|fortinet: installs the (optional) program with LordOS's package@@ -501,7 +501,7 @@ void net_act_vpn_status(const AdminReq *r, const char *arg, size_t len) {void net_act_vpn_enable(const AdminReq *r, const char *arg, size_t len) {(void)len;const char *pkgs = !strcmp(arg, "openconnect") ? "openconnect" : !strcmp(arg, "fortinet") ? "openfortivpn" : NULL;- if (!pkgs) { admin_say("ERR", "net-vpn-enable: openconnect o fortinet"); return; }- if (vpn_type_available(arg)) { admin_say("OK", "ya estaba instalado"); return; }+ if (!pkgs) { admin_err("admin.invalidArgument", NULL); return; }+ if (vpn_type_available(arg)) { admin_ok("vpn.alreadyInstalled", NULL); return; }pkg_act_install(r, pkgs, strlen(pkgs));}diff --git a/server/src/net/ipsec.c b/server/src/net/ipsec.cindex d80cb96..13d26ba 100644--- a/server/src/net/ipsec.c+++ b/server/src/net/ipsec.c@@ -64,17 +64,17 @@ int ipsec_import(const char *name, const char *text, char *err, size_t errn) {if (vpn_kv_parse(text, keys, pems, &kv, err, errn)) return -1;const char *server = vpn_kv(&kv, "server"), *auth = vpn_kv(&kv, "auth");int rc = 0;- if (!server || !vpn_host_ok(server)) { snprintf(err, errn, "falta server o es inválido"); rc = -1; }- else if (!auth || (strcmp(auth, "eap") && strcmp(auth, "psk") && strcmp(auth, "cert"))) { snprintf(err, errn, "auth tiene que ser eap, psk o cert"); rc = -1; }- else if (!strcmp(auth, "eap") && (!vpn_kv(&kv, "user") || !id_ok(vpn_kv(&kv, "user")) || !vpn_kv(&kv, "password"))) { snprintf(err, errn, "eap necesita user y password"); rc = -1; }- else if (!strcmp(auth, "psk") && (!vpn_kv(&kv, "psk") || strlen(vpn_kv(&kv, "psk")) < 8)) { snprintf(err, errn, "psk necesita una clave de al menos 8 caracteres"); rc = -1; }- else if (!strcmp(auth, "cert") && (!vpn_kv_pem(&kv, "cert") || !vpn_kv_pem(&kv, "key"))) { snprintf(err, errn, "cert necesita cert y key (PEM)"); rc = -1; }- else if (vpn_kv(&kv, "remote_id") && !id_ok(vpn_kv(&kv, "remote_id"))) { snprintf(err, errn, "remote_id inválido"); rc = -1; }- else if (vpn_kv(&kv, "local_id") && !id_ok(vpn_kv(&kv, "local_id"))) { snprintf(err, errn, "local_id inválido"); rc = -1; }- else if (vpn_kv(&kv, "ike") && !proposal_ok(vpn_kv(&kv, "ike"))) { snprintf(err, errn, "ike inválido"); rc = -1; }- else if (vpn_kv(&kv, "esp") && !proposal_ok(vpn_kv(&kv, "esp"))) { snprintf(err, errn, "esp inválido"); rc = -1; }- else if (vpn_kv(&kv, "routes") && !vpn_routes_valid(vpn_kv(&kv, "routes"))) { snprintf(err, errn, "routes inválido"); rc = -1; }- if (!rc && vpn_kv_save(name, "ipsec", &kv)) { snprintf(err, errn, "no se pudo guardar"); rc = -1; }+ if (!server || !vpn_host_ok(server)) { lerr_set(err, errn, "vpn.missingKey", "key", "server", NULL); rc = -1; }+ else if (!auth || (strcmp(auth, "eap") && strcmp(auth, "psk") && strcmp(auth, "cert"))) { lerr_set(err, errn, "vpn.invalidValue", "key", "auth", NULL); rc = -1; }+ else if (!strcmp(auth, "eap") && (!vpn_kv(&kv, "user") || !id_ok(vpn_kv(&kv, "user")) || !vpn_kv(&kv, "password"))) { lerr_set(err, errn, "ipsec.eapNeedsUser", NULL); rc = -1; }+ else if (!strcmp(auth, "psk") && (!vpn_kv(&kv, "psk") || strlen(vpn_kv(&kv, "psk")) < 8)) { lerr_set(err, errn, "ipsec.pskShort", NULL); rc = -1; }+ else if (!strcmp(auth, "cert") && (!vpn_kv_pem(&kv, "cert") || !vpn_kv_pem(&kv, "key"))) { lerr_set(err, errn, "ipsec.certNeedsKey", NULL); rc = -1; }+ else if (vpn_kv(&kv, "remote_id") && !id_ok(vpn_kv(&kv, "remote_id"))) { lerr_set(err, errn, "vpn.invalidValue", "key", "remote_id", NULL); rc = -1; }+ else if (vpn_kv(&kv, "local_id") && !id_ok(vpn_kv(&kv, "local_id"))) { lerr_set(err, errn, "vpn.invalidValue", "key", "local_id", NULL); rc = -1; }+ else if (vpn_kv(&kv, "ike") && !proposal_ok(vpn_kv(&kv, "ike"))) { lerr_set(err, errn, "vpn.invalidValue", "key", "ike", NULL); rc = -1; }+ else if (vpn_kv(&kv, "esp") && !proposal_ok(vpn_kv(&kv, "esp"))) { lerr_set(err, errn, "vpn.invalidValue", "key", "esp", NULL); rc = -1; }+ else if (vpn_kv(&kv, "routes") && !vpn_routes_valid(vpn_kv(&kv, "routes"))) { lerr_set(err, errn, "vpn.invalidValue", "key", "routes", NULL); rc = -1; }+ if (!rc && vpn_kv_save(name, "ipsec", &kv)) { lerr_set(err, errn, "net.saveFailed", NULL); rc = -1; }if (!rc) {char ifn[IFNAMSIZ];vpn_ifname("ipsec", name, ifn, sizeof ifn);@@ -86,7 +86,7 @@ int ipsec_import(const char *name, const char *text, char *err, size_t errn) {buf_printf(&m, ",\"auth\":\"%s\",\"user\":", auth);buf_json_str(&m, vpn_kv(&kv, "user") ? vpn_kv(&kv, "user") : "");buf_printf(&m, ",\"fullTunnel\":%s,\"insecure\":false}\n", vpn_kv(&kv, "routes") ? "false" : "true");- if (!m.p || vpn_meta_save(name, m.p)) { snprintf(err, errn, "no se pudo guardar"); rc = -1; }+ if (!m.p || vpn_meta_save(name, m.p)) { lerr_set(err, errn, "net.saveFailed", NULL); rc = -1; }buf_free(&m);}vpn_kv_free(&kv);@@ -123,7 +123,7 @@ static int load_pem(int fd, const char *cmd, const char *type, const char *flag,ViciResult r;int rc = vici_simple(fd, cmd, &m, &r, 5000);vici_free(&m);- if (rc && err) snprintf(err, errn, "%s: %s", cmd, r.errmsg);+ if (rc && err) lerr_set(err, errn, "ipsec.viciFailed", "cmd", cmd, "detail", r.errmsg, NULL);return rc;}@@ -160,7 +160,7 @@ static int vici_load(int fd, const VpnKv *kv, uint32_t if_id, char *err, size_tconst char *rid = vpn_kv(kv, "remote_id") ? vpn_kv(kv, "remote_id") : server;const char *lid = vpn_kv(kv, "local_id"), *routes = vpn_kv(kv, "routes");ViciResult r;- if (!vpn_kv_pem(kv, "ca") && load_system_cas(fd) == 0 && strcmp(auth, "psk")) { snprintf(err, errn, "no hay autoridades en /etc/ssl/certs"); return -1; }+ if (!vpn_kv_pem(kv, "ca") && load_system_cas(fd) == 0 && strcmp(auth, "psk")) { lerr_set(err, errn, "ipsec.noCas", NULL); return -1; }if (!strcmp(auth, "cert") && load_pem(fd, "load-key", "any", NULL, vpn_kv_pem(kv, "key"), err, errn)) return -1;if (!strcmp(auth, "eap") || !strcmp(auth, "psk")) {ViciMsg m = {0};@@ -172,7 +172,7 @@ static int vici_load(int fd, const VpnKv *kv, uint32_t if_id, char *err, size_tvici_list_end(&m);int rc = vici_simple(fd, "load-shared", &m, &r, 5000);vici_free(&m);- if (rc) { snprintf(err, errn, "load-shared: %s", r.errmsg); return -1; }+ if (rc) { lerr_set(err, errn, "ipsec.viciFailed", "cmd", "load-shared", "detail", r.errmsg, NULL); return -1; }}char hex[16];snprintf(hex, sizeof hex, "0x%x", if_id);@@ -218,7 +218,7 @@ static int vici_load(int fd, const VpnKv *kv, uint32_t if_id, char *err, size_tvici_end(&m);int rc = vici_simple(fd, "load-conn", &m, &r, 5000);vici_free(&m);- if (rc) { snprintf(err, errn, "load-conn: %s", r.errmsg); return -1; }+ if (rc) { lerr_set(err, errn, "ipsec.viciFailed", "cmd", "load-conn", "detail", r.errmsg, NULL); return -1; }return 0;}@@ -254,7 +254,7 @@ static int list_sas(int fd, SaCtx *s) {void ipsec_run(const char *name) {vpn_signals();VpnKv kv;- if (vpn_kv_load(name, "ipsec", &kv)) { admin_event("net vpn %s error no-config", name); admin_event("net vpn %s disconnected", name); return; }+ if (vpn_kv_load(name, "ipsec", &kv)) { admin_event("net vpn %s error vpn.noConfig", name); admin_event("net vpn %s disconnected", name); return; }char ifn[IFNAMSIZ], sconf[200], sock[160], dnsf[160], err[300] = "";vpn_ifname("ipsec", name, ifn, sizeof ifn);snprintf(sconf, sizeof sconf, SCONF_DIR "/%s.conf", name);@@ -267,7 +267,7 @@ void ipsec_run(const char *name) {admin_event("net vpn %s connecting", name);int sfam = 0;uint8_t sip[16];- if (vpn_resolve(vpn_kv(&kv, "server"), &sfam, sip)) { admin_event("net vpn %s error no-resolve", name); admin_event("net vpn %s disconnected", name); vpn_kv_free(&kv); return; }+ if (vpn_resolve(vpn_kv(&kv, "server"), &sfam, sip)) { admin_event("net vpn %s error vpn.serverUnresolved", name); admin_event("net vpn %s disconnected", name); vpn_kv_free(&kv); return; }/* if_id: from the name, never 0 */uint32_t if_id = 0x4c000000u;for (const char *p = name; *p; p++) if_id = (if_id * 31 + (unsigned char)*p) | 0x4c000000u;@@ -276,20 +276,20 @@ void ipsec_run(const char *name) {if (fd < 0) { vpn_kv_free(&kv); return; }if (rt_ifindex(ifn)) rt_link_del(fd, rt_ifindex(ifn));int r = rt_link_new_xfrm(fd, ifn, if_id);- if (r) { close(fd); admin_event("net vpn %s error xfrm %s", name, strerror(-r)); admin_event("net vpn %s disconnected", name); vpn_kv_free(&kv); return; }+ if (r) { close(fd); admin_event("net vpn %s error vpn.xfrmFailed errno=%s", name, lerr_errno(-r)); admin_event("net vpn %s disconnected", name); vpn_kv_free(&kv); return; }rt_link_set(fd, rt_ifindex(ifn), 1);close(fd);vpn_mark(ifn, name, 1);pid_t charon = -1;int cout = -1, vfd = -1, connected = 0;- if (write_sconf(name, ifn, sconf)) { admin_event("net vpn %s error write", name); goto out; }+ if (write_sconf(name, ifn, sconf)) { admin_event("net vpn %s error vpn.writeFailed", name); goto out; }char envs[300];snprintf(envs, sizeof envs, "STRONGSWAN_CONF=%s", sconf);const char *cargv[] = { CHARON, NULL };charon = vpn_spawn(cargv, &cout, NULL, envs);- if (charon < 0) { admin_event("net vpn %s error charon", name); goto out; }+ if (charon < 0) { admin_event("net vpn %s error ipsec.charonFailed", name); goto out; }for (int i = 0; i < 100 && (vfd = vici_connect(sock)) < 0; i++) usleep(100000);- if (vfd < 0) { admin_event("net vpn %s error charon-no-vici", name); goto out; }+ if (vfd < 0) { admin_event("net vpn %s error ipsec.noVici", name); goto out; }if (vici_load(vfd, &kv, if_id, err, sizeof err)) { admin_event("net vpn %s error %.200s", name, err); goto out; }InitCtx ic = { .log = "" };ViciMsg m = {0};@@ -342,11 +342,11 @@ void ipsec_run(const char *name) {struct pollfd pf = { cout, POLLIN, 0 };if (poll(&pf, 1, 1000) > 0) {char junk[4096];- if (read(cout, junk, sizeof junk) <= 0) { admin_event("net vpn %s error charon-exit", name); break; }+ if (read(cout, junk, sizeof junk) <= 0) { admin_event("net vpn %s error ipsec.charonExited", name); break; }}if (time(NULL) >= next) {next = time(NULL) + 10;- if (list_sas(vfd, &sa) || !sa.established) { admin_event("net vpn %s error lost", name); break; }+ if (list_sas(vfd, &sa) || !sa.established) { admin_event("net vpn %s error vpn.lost", name); break; }}}{diff --git a/server/src/net/ovpn.c b/server/src/net/ovpn.cindex 4ea4d72..7fc149d 100644--- a/server/src/net/ovpn.c+++ b/server/src/net/ovpn.c@@ -69,7 +69,7 @@ static int arg_ok(const char *s) {int ovpn_import(const char *name, const char *text, char *err, size_t errn) {char *copy = strdup(text);- if (!copy) { snprintf(err, errn, "sin memoria"); return -1; }+ if (!copy) { lerr_set(err, errn, "sys.outOfMemory", NULL); return -1; }Buf out = {0};char block[24] = "", dev_type[8] = "tun", server[200] = "";int lineno = 0, rc = 0, needs_auth = 0, has_ca = 0, client = 0, ignored = 0;@@ -86,7 +86,7 @@ int ovpn_import(const char *name, const char *text, char *err, size_t errn) {while (isspace((unsigned char)*t)) t++;if (!strncmp(t, close_tag, strlen(close_tag))) { buf_printf(&out, "%s\n", close_tag); block[0] = 0; continue; }/* certificate/key contents: base64, dashes, PEM headers, hex */- for (char *p = l; *p; p++) if (!isalnum((unsigned char)*p) && !strchr("+/=- :\t.#,()", *p)) { snprintf(err, errn, "línea %d: carácter inválido en <%s>", lineno, block); rc = -1; break; }+ for (char *p = l; *p; p++) if (!isalnum((unsigned char)*p) && !strchr("+/=- :\t.#,()", *p)) { lerr_set(err, errn, "vpn.badChar", "line", lerr_int(lineno), "key", block, NULL); rc = -1; break; }if (!rc) buf_printf(&out, "%s\n", l);continue;}@@ -95,7 +95,7 @@ int ovpn_import(const char *name, const char *text, char *err, size_t errn) {if (!*t || *t == '#' || *t == ';') continue;if (*t == '<') {char tag[24];- if (sscanf(t, "<%23[a-z0-9-]>", tag) != 1 || !in_list(blocks, tag)) { snprintf(err, errn, "línea %d: bloque no permitido %s", lineno, t); rc = -1; break; }+ if (sscanf(t, "<%23[a-z0-9-]>", tag) != 1 || !in_list(blocks, tag)) { lerr_set(err, errn, "ovpn.blockNotAllowed", "line", lerr_int(lineno), "block", t, NULL); rc = -1; break; }snprintf(block, sizeof block, "%s", tag);if (!strcmp(tag, "ca")) has_ca = 1;buf_printf(&out, "<%s>\n", tag);@@ -111,29 +111,29 @@ int ovpn_import(const char *name, const char *text, char *err, size_t errn) {if (in_list(windows_only, w)) { ignored++; continue; }if (in_list(blocks, w)) {/* "ca file": it has to come embedded (lord.net.prepareOvpn does that) */- if (strncmp(args, "[inline]", 8)) { snprintf(err, errn, "línea %d: %s tiene que estar incrustado (<%s>)", lineno, w, w); rc = -1; break; }+ if (strncmp(args, "[inline]", 8)) { lerr_set(err, errn, "ovpn.mustBeInline", "line", lerr_int(lineno), "option", w, NULL); rc = -1; break; }continue;}- if (!in_list(allowed, w)) { snprintf(err, errn, "línea %d: opción no permitida: %s", lineno, w); rc = -1; break; }- if (!arg_ok(args)) { snprintf(err, errn, "línea %d: argumento inválido", lineno); rc = -1; break; }+ if (!in_list(allowed, w)) { lerr_set(err, errn, "ovpn.optionNotAllowed", "line", lerr_int(lineno), "option", w, NULL); rc = -1; break; }+ if (!arg_ok(args)) { lerr_set(err, errn, "ovpn.invalidArgument", "line", lerr_int(lineno), NULL); rc = -1; break; }if (!strcmp(w, "client") || !strcmp(w, "tls-client")) client = 1;if (!strcmp(w, "auth-user-pass")) {- if (*args) { snprintf(err, errn, "línea %d: auth-user-pass no lleva archivo (se pide la contraseña)", lineno); rc = -1; break; }+ if (*args) { lerr_set(err, errn, "ovpn.authFile", "line", lerr_int(lineno), NULL); rc = -1; break; }needs_auth = 1;}- if (!strcmp(w, "dev")) { if (!strncmp(args, "tap", 3)) { snprintf(err, errn, "solo se admite dev tun"); rc = -1; } continue; }- if (!strcmp(w, "dev-type")) { if (strcmp(args, "tun")) { snprintf(err, errn, "solo se admite dev-type tun"); rc = -1; } snprintf(dev_type, sizeof dev_type, "tun"); continue; }+ if (!strcmp(w, "dev")) { if (!strncmp(args, "tap", 3)) { lerr_set(err, errn, "ovpn.onlyTun", NULL); rc = -1; } continue; }+ if (!strcmp(w, "dev-type")) { if (strcmp(args, "tun")) { lerr_set(err, errn, "ovpn.onlyTun", NULL); rc = -1; } snprintf(dev_type, sizeof dev_type, "tun"); continue; }if (!strcmp(w, "remote") && !server[0]) snprintf(server, sizeof server, "%s", args);if (in_list(replaced, w)) continue;buf_printf(&out, "%s%s%s\n", w, *args ? " " : "", args);}free(copy);- if (!rc && block[0]) { snprintf(err, errn, "falta </%s>", block); rc = -1; }- if (!rc && !client) { snprintf(err, errn, "no es una configuración de cliente (falta client)"); rc = -1; }- if (!rc && !has_ca) { snprintf(err, errn, "falta el certificado de la autoridad (<ca>)"); rc = -1; }- if (!rc && !server[0]) { snprintf(err, errn, "falta remote"); rc = -1; }- if (rc || out.oom) { buf_free(&out); if (!rc) snprintf(err, errn, "sin memoria"); return -1; }- if (ignored) admin_say("LOG", "se ignoraron %d opciones que solo valen en Windows", ignored);+ if (!rc && block[0]) { lerr_set(err, errn, "ovpn.blockUnclosed", "block", block, NULL); rc = -1; }+ if (!rc && !client) { lerr_set(err, errn, "ovpn.notClient", NULL); rc = -1; }+ if (!rc && !has_ca) { lerr_set(err, errn, "ovpn.noCa", NULL); rc = -1; }+ if (!rc && !server[0]) { lerr_set(err, errn, "vpn.missingKey", "key", "remote", NULL); rc = -1; }+ if (rc || out.oom) { buf_free(&out); if (!rc) lerr_set(err, errn, "sys.outOfMemory", NULL); return -1; }+ if (ignored) admin_log("ovpn.ignoredWindows", "count", lerr_int(ignored), NULL);char path[160];snprintf(path, sizeof path, NET_VPN_DIR "/%s.ovpn", name);int ok = write_file_atomic(path, out.p, out.len, 0600) == 0;@@ -150,7 +150,7 @@ int ovpn_import(const char *name, const char *text, char *err, size_t errn) {snprintf(path, sizeof path, NET_VPN_DIR "/%s.json", name);ok = ok && m.p && write_file_atomic(path, m.p, m.len, 0644) == 0;buf_free(&m);- if (!ok) { snprintf(err, errn, "no se pudo guardar"); return -1; }+ if (!ok) { lerr_set(err, errn, "net.saveFailed", NULL); return -1; }return 0;}@@ -230,7 +230,7 @@ void ovpn_run(const char *name) {vpn_ifname("openvpn", name, ifn, sizeof ifn);snprintf(path, sizeof path, NET_VPN_DIR "/%s.ovpn", name);char *stored = read_file(path, 65536, NULL);- if (!stored) { admin_event("net vpn %s error no-config", name); return; }+ if (!stored) { admin_event("net vpn %s error vpn.noConfig", name); return; }mkdir(NET_RUN_DIR, 0755);mkdir(OVPN_RUN, 0700);snprintf(sock, sizeof sock, OVPN_RUN "/%s.sock", name);@@ -242,7 +242,7 @@ void ovpn_run(const char *name) {int local_full = strstr(stored, "\nredirect-gateway") != NULL || !strncmp(stored, "redirect-gateway", 16);memset(stored, 0, strlen(stored));free(stored);- if (c.oom || write_file_atomic(conf, c.p, c.len, 0600)) { buf_free(&c); admin_event("net vpn %s error write", name); return; }+ if (c.oom || write_file_atomic(conf, c.p, c.len, 0600)) { buf_free(&c); admin_event("net vpn %s error vpn.writeFailed", name); return; }memset(c.p, 0, c.len);buf_free(&c);@@ -262,7 +262,7 @@ void ovpn_run(const char *name) {_exit(127);}close(p[1]);- if (pid < 0) { close(p[0]); admin_event("net vpn %s error fork", name); return; }+ if (pid < 0) { close(p[0]); admin_event("net vpn %s error vpn.startFailed", name); return; }mkdir(NET_RUN_DIR "/vpn", 0755);char mark[128], content[64];snprintf(mark, sizeof mark, NET_RUN_DIR "/vpn/%s", ifn);diff --git a/server/src/net/state.c b/server/src/net/state.cindex cd2276c..4354785 100644--- a/server/src/net/state.c+++ b/server/src/net/state.c@@ -2,6 +2,7 @@* counters (rtnetlink dumps), DNS, who manages each interface, and change notifications. */#include "net.h"#include "netpriv.h"+#include "../errcode.h"#include <net/if.h> /* before the linux/ ones */@@ -386,7 +387,7 @@ static const char *const inline_dirs[] = { "ca", "cert", "key", "tls-auth", "tlschar *net_ovpn_inline(const char *path, char *err, size_t errn) {size_t len;char *t = read_file(path, 256 * 1024, &len);- if (!t) { snprintf(err, errn, "no se pudo leer %s", path); return NULL; }+ if (!t) { lerr_set(err, errn, "sys.readFailed", "path", path, NULL); return NULL; }char dir[512];snprintf(dir, sizeof dir, "%s", path);char *slash = strrchr(dir, '/');@@ -403,7 +404,7 @@ char *net_ovpn_inline(const char *path, char *err, size_t errn) {char p[1024];if (a1[0] == '/') snprintf(p, sizeof p, "%s", a1); else snprintf(p, sizeof p, "%s/%s", dir, a1);char *f = read_file(p, 64 * 1024, NULL);- if (!f) { snprintf(err, errn, "falta el archivo %s", a1); free(t); buf_free(&b); return NULL; }+ if (!f) { lerr_set(err, errn, "ovpn.missingFile", "file", a1, NULL); free(t); buf_free(&b); return NULL; }buf_printf(&b, "<%s>\n%s%s</%s>\n", w, f, f[0] && f[strlen(f) - 1] == '\n' ? "" : "\n", w);if (!strcmp(w, "tls-auth") && k == 3) buf_printf(&b, "key-direction %s\n", a2);free(f);@@ -414,7 +415,7 @@ char *net_ovpn_inline(const char *path, char *err, size_t errn) {l = e ? e + 1 : NULL;}free(t);- if (b.oom || !b.p) { buf_free(&b); snprintf(err, errn, "sin memoria"); return NULL; }+ if (b.oom || !b.p) { buf_free(&b); lerr_set(err, errn, "sys.outOfMemory", NULL); return NULL; }return b.p;}diff --git a/server/src/net/vici.c b/server/src/net/vici.cindex a2d5f4f..8e78514 100644--- a/server/src/net/vici.c+++ b/server/src/net/vici.c@@ -224,7 +224,7 @@ static void ok_cb(const char *path, const char *key, const char *val, void *ud)int vici_simple(int fd, const char *cmd, const ViciMsg *req, ViciResult *res, int timeout_ms) {memset(res, 0, sizeof *res);- if (vici_call(fd, cmd, req, NULL, NULL, ok_cb, res, timeout_ms)) { snprintf(res->errmsg, sizeof res->errmsg, "sin respuesta de charon"); return -1; }+ if (vici_call(fd, cmd, req, NULL, NULL, ok_cb, res, timeout_ms)) { snprintf(res->errmsg, sizeof res->errmsg, "no answer from charon"); return -1; }return res->success ? 0 : -1;}diff --git a/server/src/net/vpn.c b/server/src/net/vpn.cindex 40b3651..bae412d 100644--- a/server/src/net/vpn.c+++ b/server/src/net/vpn.c@@ -55,7 +55,7 @@ int vpn_host_ok(const char *s) {int vpn_kv_parse(const char *text, const char *const *keys, const char *const *pem_keys, VpnKv *kv, char *err, size_t errn) {memset(kv, 0, sizeof *kv);char *copy = strdup(text);- if (!copy) { snprintf(err, errn, "sin memoria"); return -1; }+ if (!copy) { lerr_set(err, errn, "sys.outOfMemory", NULL); return -1; }int lineno = 0, rc = 0;for (char *l = copy, *next; l && !rc; l = next) {next = strchr(l, '\n');@@ -67,7 +67,7 @@ int vpn_kv_parse(const char *text, const char *const *keys, const char *const *pwhile (isspace((unsigned char)*t)) t++;if (!*t || *t == '#') continue;char *eq = strchr(t, '=');- if (!eq) { snprintf(err, errn, "línea %d: se esperaba clave=valor", lineno); rc = -1; break; }+ if (!eq) { lerr_set(err, errn, "vpn.expectedKeyValue", "line", lerr_int(lineno), NULL); rc = -1; break; }*eq = 0;char *k = t, *v = eq + 1;char *ke = k + strlen(k);@@ -76,7 +76,7 @@ int vpn_kv_parse(const char *text, const char *const *keys, const char *const *pchar *ve = v + strlen(v);while (ve > v && isspace((unsigned char)ve[-1])) *--ve = 0;if (in_list(pem_keys, k)) {- if (strncmp(v, "-----BEGIN ", 11)) { snprintf(err, errn, "línea %d: %s tiene que ser PEM (-----BEGIN ...)", lineno, k); rc = -1; break; }+ if (strncmp(v, "-----BEGIN ", 11)) { lerr_set(err, errn, "vpn.pemRequired", "line", lerr_int(lineno), "key", k, NULL); rc = -1; break; }Buf b = {0};buf_printf(&b, "%s\n", v);int closed = strstr(v + 11, "-----END ") != NULL;@@ -87,20 +87,20 @@ int vpn_kv_parse(const char *text, const char *const *keys, const char *const *plineno++;size_t pn = strlen(pl);if (pn && pl[pn - 1] == '\r') pl[--pn] = 0;- for (char *c = pl; *c; c++) if (!isalnum((unsigned char)*c) && !strchr("+/=- :", *c)) { snprintf(err, errn, "línea %d: carácter inválido en %s", lineno, k); rc = -1; break; }+ for (char *c = pl; *c; c++) if (!isalnum((unsigned char)*c) && !strchr("+/=- :", *c)) { lerr_set(err, errn, "vpn.badChar", "line", lerr_int(lineno), "key", k, NULL); rc = -1; break; }if (rc) break;buf_printf(&b, "%s\n", pl);if (!strncmp(pl, "-----END ", 9)) closed = 1;}- if (!rc && !closed) { snprintf(err, errn, "%s: falta -----END", k); rc = -1; }- if (rc || kv->npem >= VPN_MAX_PEM) { buf_free(&b); if (!rc) { snprintf(err, errn, "demasiados PEM"); rc = -1; } break; }+ if (!rc && !closed) { lerr_set(err, errn, "vpn.pemUnclosed", "key", k, NULL); rc = -1; }+ if (rc || kv->npem >= VPN_MAX_PEM) { buf_free(&b); if (!rc) { lerr_set(err, errn, "vpn.tooManyPem", NULL); rc = -1; } break; }snprintf(kv->pem_key[kv->npem], sizeof kv->pem_key[0], "%s", k);kv->pem[kv->npem++] = b.p;continue;}- if (!in_list(keys, k)) { snprintf(err, errn, "línea %d: clave desconocida %s", lineno, k); rc = -1; break; }- if (!vpn_text_ok(v, 255)) { snprintf(err, errn, "línea %d: valor inválido para %s", lineno, k); rc = -1; break; }- if (kv->n >= VPN_MAX_KV) { snprintf(err, errn, "demasiadas líneas"); rc = -1; break; }+ if (!in_list(keys, k)) { lerr_set(err, errn, "vpn.unknownKey", "line", lerr_int(lineno), "key", k, NULL); rc = -1; break; }+ if (!vpn_text_ok(v, 255)) { lerr_set(err, errn, "vpn.invalidLineValue", "line", lerr_int(lineno), "key", k, NULL); rc = -1; break; }+ if (kv->n >= VPN_MAX_KV) { lerr_set(err, errn, "vpn.tooManyLines", NULL); rc = -1; break; }snprintf(kv->key[kv->n], sizeof kv->key[0], "%s", k);snprintf(kv->val[kv->n], sizeof kv->val[0], "%s", v);kv->n++;@@ -218,7 +218,7 @@ int vpn_routes_full(const char *ifn, int sfam, const uint8_t server[16]) {int r = rt_route_proto(fd, 1, AF_INET, lo, 1, NULL, idx, 0, 0, RTPROT_LORDOS);if (!r) r = rt_route_proto(fd, 1, AF_INET, hi, 1, NULL, idx, 0, 0, RTPROT_LORDOS);close(fd);- if (r) admin_event("net vpn - log rutas por %s: %s", ifn, strerror(-r));+ if (r) { char e[200]; admin_event("net vpn - error %s", lerr_set(e, sizeof e, "vpn.routesFailed", "dev", ifn, "errno", lerr_errno(-r), NULL)); }return r ? -1 : 0;}diff --git a/server/src/net/vpnproc.c b/server/src/net/vpnproc.cindex 956e42a..79b48b0 100644--- a/server/src/net/vpnproc.c+++ b/server/src/net/vpnproc.c@@ -134,11 +134,11 @@ int pptp_import(const char *name, const char *text, char *err, size_t errn) {if (vpn_kv_parse(text, pptp_keys, NULL, &kv, err, errn)) return -1;const char *server = vpn_kv(&kv, "server"), *user = vpn_kv(&kv, "user"), *pw = vpn_kv(&kv, "password"), *mppe = vpn_kv(&kv, "mppe");int rc = 0;- if (!server || !vpn_host_ok(server) || strchr(server, ':')) { snprintf(err, errn, "falta server o es inválido"); rc = -1; }- else if (!user || !*user || !pw) { snprintf(err, errn, "faltan user y password"); rc = -1; }- else if (mppe && strcmp(mppe, "required") && strcmp(mppe, "optional") && strcmp(mppe, "off")) { snprintf(err, errn, "mppe: required, optional u off"); rc = -1; }- else if (vpn_kv(&kv, "routes") && !vpn_routes_valid(vpn_kv(&kv, "routes"))) { snprintf(err, errn, "routes inválido"); rc = -1; }- if (!rc && vpn_kv_save(name, "pptp", &kv)) { snprintf(err, errn, "no se pudo guardar"); rc = -1; }+ if (!server || !vpn_host_ok(server) || strchr(server, ':')) { lerr_set(err, errn, "vpn.missingKey", "key", "server", NULL); rc = -1; }+ else if (!user || !*user || !pw) { lerr_set(err, errn, "vpn.missingCredentials", NULL); rc = -1; }+ else if (mppe && strcmp(mppe, "required") && strcmp(mppe, "optional") && strcmp(mppe, "off")) { lerr_set(err, errn, "vpn.invalidValue", "key", "mppe", NULL); rc = -1; }+ else if (vpn_kv(&kv, "routes") && !vpn_routes_valid(vpn_kv(&kv, "routes"))) { lerr_set(err, errn, "vpn.invalidValue", "key", "routes", NULL); rc = -1; }+ if (!rc && vpn_kv_save(name, "pptp", &kv)) { lerr_set(err, errn, "net.saveFailed", NULL); rc = -1; }if (!rc) meta(name, "pptp", server, user, !vpn_kv(&kv, "routes"), 1);vpn_kv_free(&kv);return rc;@@ -172,12 +172,12 @@ static void pptp_tick(Run *r) {void pptp_run(const char *name) {vpn_signals();VpnKv kv;- if (vpn_kv_load(name, "pptp", &kv)) { admin_event("net vpn %s error no-config", name); admin_event("net vpn %s disconnected", name); return; }+ if (vpn_kv_load(name, "pptp", &kv)) { admin_event("net vpn %s error vpn.noConfig", name); admin_event("net vpn %s disconnected", name); return; }Run r = { .name = name, .type = "pptp", .routes = vpn_kv(&kv, "routes") };r.full = !r.routes;vpn_ifname("pptp", name, r.ifn, sizeof r.ifn);admin_event("net vpn %s connecting", name);- if (vpn_resolve(vpn_kv(&kv, "server"), &r.sfam, r.sip) || r.sfam != AF_INET) { admin_event("net vpn %s error no-resolve", name); admin_event("net vpn %s disconnected", name); vpn_kv_free(&kv); return; }+ if (vpn_resolve(vpn_kv(&kv, "server"), &r.sfam, r.sip) || r.sfam != AF_INET) { admin_event("net vpn %s error vpn.serverUnresolved", name); admin_event("net vpn %s disconnected", name); vpn_kv_free(&kv); return; }char sip[64], qu[300], qp[600], path[200];fmt_ip(AF_INET, r.sip, sip, sizeof sip);pquote(vpn_kv(&kv, "user"), qu, sizeof qu);@@ -201,12 +201,12 @@ void pptp_run(const char *name) {if (o.p) memset(o.p, 0, o.len);buf_free(&o);vpn_kv_free(&kv);- if (!ok) { admin_event("net vpn %s error write", name); admin_event("net vpn %s disconnected", name); return; }+ if (!ok) { admin_event("net vpn %s error vpn.writeFailed", name); admin_event("net vpn %s disconnected", name); return; }vpn_mark(r.ifn, name, 1);const char *argv[] = { PPPD, "file", path, NULL };int out;pid_t pid = vpn_spawn(argv, &out, NULL, NULL);- if (pid < 0) { admin_event("net vpn %s error spawn", name); admin_event("net vpn %s disconnected", name); vpn_mark(r.ifn, name, 0); return; }+ if (pid < 0) { admin_event("net vpn %s error vpn.startFailed", name); admin_event("net vpn %s disconnected", name); vpn_mark(r.ifn, name, 0); return; }r.routes = NULL; /* kv already freed: reread */VpnKv k2;char routes[256] = "";@@ -243,11 +243,11 @@ int oc_import(const char *name, const char *text, char *err, size_t errn) {if (vpn_kv_parse(text, oc_keys, NULL, &kv, err, errn)) return -1;const char *server = vpn_kv(&kv, "server"), *proto = vpn_kv(&kv, "protocol"), *user = vpn_kv(&kv, "user");int rc = 0;- if (!server || !oc_server_ok(server)) { snprintf(err, errn, "falta server o es inválido"); rc = -1; }- else if (proto && strcmp(proto, "anyconnect") && strcmp(proto, "gp") && strcmp(proto, "pulse") && strcmp(proto, "fortinet")) { snprintf(err, errn, "protocol: anyconnect, gp, pulse o fortinet"); rc = -1; }- else if (!user || !*user || !vpn_kv(&kv, "password")) { snprintf(err, errn, "faltan user y password"); rc = -1; }- else if (vpn_kv(&kv, "servercert") && !pin_ok(vpn_kv(&kv, "servercert"))) { snprintf(err, errn, "servercert: pin-sha256:… o la huella en hex"); rc = -1; }- if (!rc && vpn_kv_save(name, "openconnect", &kv)) { snprintf(err, errn, "no se pudo guardar"); rc = -1; }+ if (!server || !oc_server_ok(server)) { lerr_set(err, errn, "vpn.missingKey", "key", "server", NULL); rc = -1; }+ else if (proto && strcmp(proto, "anyconnect") && strcmp(proto, "gp") && strcmp(proto, "pulse") && strcmp(proto, "fortinet")) { lerr_set(err, errn, "vpn.invalidValue", "key", "protocol", NULL); rc = -1; }+ else if (!user || !*user || !vpn_kv(&kv, "password")) { lerr_set(err, errn, "vpn.missingCredentials", NULL); rc = -1; }+ else if (vpn_kv(&kv, "servercert") && !pin_ok(vpn_kv(&kv, "servercert"))) { lerr_set(err, errn, "vpn.invalidValue", "key", "servercert", NULL); rc = -1; }+ if (!rc && vpn_kv_save(name, "openconnect", &kv)) { lerr_set(err, errn, "net.saveFailed", NULL); rc = -1; }if (!rc) meta(name, "openconnect", server, user, 1, 0);vpn_kv_free(&kv);return rc;@@ -293,7 +293,7 @@ static void oc_tick(Run *r) {kv_get(t, "CISCO_SPLIT_INC", 0, nsplit, sizeof nsplit);int fam;uint8_t a[16];- if (parse_ip(addr, &fam, a) || fam != AF_INET) { free(t); admin_event("net vpn %s error no-address", r->name); return; }+ if (parse_ip(addr, &fam, a) || fam != AF_INET) { free(t); admin_event("net vpn %s error vpn.noAddress", r->name); return; }int prefix = masklen[0] ? atoi(masklen) : 32;if (!masklen[0] && mask[0]) {uint8_t m[16];@@ -338,14 +338,14 @@ static void oc_tick(Run *r) {void oc_run(const char *name) {vpn_signals();VpnKv kv;- if (vpn_kv_load(name, "openconnect", &kv)) { admin_event("net vpn %s error no-config", name); admin_event("net vpn %s disconnected", name); return; }+ if (vpn_kv_load(name, "openconnect", &kv)) { admin_event("net vpn %s error vpn.noConfig", name); admin_event("net vpn %s disconnected", name); return; }Run r = { .name = name, .type = "openconnect" };vpn_ifname("openconnect", name, r.ifn, sizeof r.ifn);admin_event("net vpn %s connecting", name);mkdir(NET_DIR, 0755);mkdir(NET_RUN_DIR, 0755);mkdir(OC_RUN, 0700);- if (write_file_atomic(OC_SCRIPT, oc_script, sizeof oc_script - 1, 0755)) { admin_event("net vpn %s error script", name); admin_event("net vpn %s disconnected", name); vpn_kv_free(&kv); return; }+ if (write_file_atomic(OC_SCRIPT, oc_script, sizeof oc_script - 1, 0755)) { admin_event("net vpn %s error vpn.writeFailed", name); admin_event("net vpn %s disconnected", name); vpn_kv_free(&kv); return; }char proto[40], user[300], group[300] = "", cert[300] = "", iface[40];snprintf(proto, sizeof proto, "--protocol=%s", vpn_kv(&kv, "protocol") ? vpn_kv(&kv, "protocol") : "anyconnect");snprintf(user, sizeof user, "--user=%s", vpn_kv(&kv, "user"));@@ -368,7 +368,7 @@ void oc_run(const char *name) {close(in);}vpn_kv_free(&kv);- if (pid < 0) { admin_event("net vpn %s error spawn", name); admin_event("net vpn %s disconnected", name); vpn_mark(r.ifn, name, 0); return; }+ if (pid < 0) { admin_event("net vpn %s error vpn.startFailed", name); admin_event("net vpn %s disconnected", name); vpn_mark(r.ifn, name, 0); return; }supervise(&r, pid, out, oc_line, oc_tick);close(out);char path[160];@@ -388,17 +388,17 @@ int forti_import(const char *name, const char *text, char *err, size_t errn) {if (vpn_kv_parse(text, forti_keys, NULL, &kv, err, errn)) return -1;const char *host = vpn_kv(&kv, "host"), *port = vpn_kv(&kv, "port"), *user = vpn_kv(&kv, "user"), *tc = vpn_kv(&kv, "trusted-cert");int rc = 0;- if (!host || !vpn_host_ok(host) || strchr(host, ':')) { snprintf(err, errn, "falta host o es inválido"); rc = -1; }- else if (port && (atoi(port) < 1 || atoi(port) > 65535 || strspn(port, "0123456789") != strlen(port))) { snprintf(err, errn, "port inválido"); rc = -1; }- else if (!user || !*user || !vpn_kv(&kv, "password")) { snprintf(err, errn, "faltan user y password"); rc = -1; }+ if (!host || !vpn_host_ok(host) || strchr(host, ':')) { lerr_set(err, errn, "vpn.missingKey", "key", "host", NULL); rc = -1; }+ else if (port && (atoi(port) < 1 || atoi(port) > 65535 || strspn(port, "0123456789") != strlen(port))) { lerr_set(err, errn, "vpn.invalidValue", "key", "port", NULL); rc = -1; }+ else if (!user || !*user || !vpn_kv(&kv, "password")) { lerr_set(err, errn, "vpn.missingCredentials", NULL); rc = -1; }else if (tc) {char copy[256];snprintf(copy, sizeof copy, "%s", tc);for (char *t = strtok(copy, ", "); t && !rc; t = strtok(NULL, ", "))- if (strlen(t) != 64 || strspn(t, "0123456789abcdefABCDEF") != 64) { snprintf(err, errn, "trusted-cert: huella sha256 en hex (64)"); rc = -1; }+ if (strlen(t) != 64 || strspn(t, "0123456789abcdefABCDEF") != 64) { lerr_set(err, errn, "vpn.invalidValue", "key", "trusted-cert", NULL); rc = -1; }}- if (!rc && vpn_kv(&kv, "routes") && !vpn_routes_valid(vpn_kv(&kv, "routes"))) { snprintf(err, errn, "routes inválido"); rc = -1; }- if (!rc && vpn_kv_save(name, "fortinet", &kv)) { snprintf(err, errn, "no se pudo guardar"); rc = -1; }+ if (!rc && vpn_kv(&kv, "routes") && !vpn_routes_valid(vpn_kv(&kv, "routes"))) { lerr_set(err, errn, "vpn.invalidValue", "key", "routes", NULL); rc = -1; }+ if (!rc && vpn_kv_save(name, "fortinet", &kv)) { lerr_set(err, errn, "net.saveFailed", NULL); rc = -1; }if (!rc) meta(name, "fortinet", host, user, 1, 0);vpn_kv_free(&kv);return rc;@@ -430,11 +430,11 @@ static void forti_line(const char *l, void *ud) {void forti_run(const char *name) {vpn_signals();VpnKv kv;- if (vpn_kv_load(name, "fortinet", &kv)) { admin_event("net vpn %s error no-config", name); admin_event("net vpn %s disconnected", name); return; }+ if (vpn_kv_load(name, "fortinet", &kv)) { admin_event("net vpn %s error vpn.noConfig", name); admin_event("net vpn %s disconnected", name); return; }Run r = { .name = name, .type = "fortinet" };vpn_ifname("fortinet", name, r.ifn, sizeof r.ifn);admin_event("net vpn %s connecting", name);- if (vpn_resolve(vpn_kv(&kv, "host"), &r.sfam, r.sip)) { admin_event("net vpn %s error no-resolve", name); admin_event("net vpn %s disconnected", name); vpn_kv_free(&kv); return; }+ if (vpn_resolve(vpn_kv(&kv, "host"), &r.sfam, r.sip)) { admin_event("net vpn %s error vpn.serverUnresolved", name); admin_event("net vpn %s disconnected", name); vpn_kv_free(&kv); return; }static char routes[256];routes[0] = 0;if (vpn_kv(&kv, "routes")) snprintf(routes, sizeof routes, "%s", vpn_kv(&kv, "routes"));@@ -459,14 +459,14 @@ void forti_run(const char *name) {int ok = !c.oom && write_file_atomic(path, c.p, c.len, 0600) == 0;if (c.p) memset(c.p, 0, c.len);buf_free(&c);- if (!ok) { admin_event("net vpn %s error write", name); admin_event("net vpn %s disconnected", name); return; }+ if (!ok) { admin_event("net vpn %s error vpn.writeFailed", name); admin_event("net vpn %s disconnected", name); return; }char ifarg[48];snprintf(ifarg, sizeof ifarg, "--pppd-ifname=%s", r.ifn);const char *argv[] = { OPENFORTIVPN, "-c", path, ifarg, "--pppd-no-peerdns", NULL };vpn_mark(r.ifn, name, 1);int out;pid_t pid = vpn_spawn(argv, &out, NULL, NULL);- if (pid < 0) { admin_event("net vpn %s error spawn", name); admin_event("net vpn %s disconnected", name); vpn_mark(r.ifn, name, 0); return; }+ if (pid < 0) { admin_event("net vpn %s error vpn.startFailed", name); admin_event("net vpn %s disconnected", name); vpn_mark(r.ifn, name, 0); return; }supervise(&r, pid, out, forti_line, NULL);close(out);down(&r);diff --git a/server/src/net/wg.c b/server/src/net/wg.cindex 54102d1..c3a12b9 100644--- a/server/src/net/wg.c+++ b/server/src/net/wg.c@@ -93,7 +93,7 @@ static int key32(const char *b64, uint8_t out[32]) {static int wg_parse(const char *text, WgConf *c, char *err, size_t errn) {memset(c, 0, sizeof *c);char *copy = strdup(text);- if (!copy) { snprintf(err, errn, "sin memoria"); return -1; }+ if (!copy) { lerr_set(err, errn, "sys.outOfMemory", NULL); return -1; }int section = 0, lineno = 0, rc = 0;for (char *l = copy, *next; l && !rc; l = next) {next = strchr(l, '\n');@@ -105,12 +105,12 @@ static int wg_parse(const char *text, WgConf *c, char *err, size_t errn) {if (!*l) continue;if (!strcasecmp(l, "[Interface]")) { section = 1; continue; }if (!strcasecmp(l, "[Peer]")) {- if (c->npeer >= MAX_PEERS) { snprintf(err, errn, "demasiados [Peer]"); rc = -1; break; }+ if (c->npeer >= MAX_PEERS) { lerr_set(err, errn, "wg.tooManyPeers", NULL); rc = -1; break; }section = 2; c->npeer++;continue;}char *eq = strchr(l, '=');- if (!eq || !section) { snprintf(err, errn, "línea %d: se esperaba clave = valor", lineno); rc = -1; break; }+ if (!eq || !section) { lerr_set(err, errn, "vpn.expectedKeyValue", "line", lerr_int(lineno), NULL); rc = -1; break; }*eq = 0;char *k = trim(l), *v = trim(eq + 1);Peer *p = section == 2 ? &c->peer[c->npeer - 1] : NULL;@@ -118,12 +118,12 @@ static int wg_parse(const char *text, WgConf *c, char *err, size_t errn) {!strcasecmp(k, "SaveConfig") || !strcasecmp(k, "Table")) { c->ignored++; continue; }if (section == 1 && !strcasecmp(k, "PrivateKey")) {if (!strcmp(v, "generate")) c->generate = 1;- else if (key32(v, c->priv)) { snprintf(err, errn, "línea %d: PrivateKey inválida", lineno); rc = -1; }+ else if (key32(v, c->priv)) { lerr_set(err, errn, "vpn.invalidLineValue", "line", lerr_int(lineno), "key", "PrivateKey", NULL); rc = -1; }else c->has_priv = 1;} else if (section == 1 && !strcasecmp(k, "Address")) {for (char *t = strtok(v, ","); t && !rc; t = strtok(NULL, ",")) {t = trim(t);- if (c->naddr >= 8 || parse_cidr(t, &c->addr[c->naddr], 0)) { snprintf(err, errn, "línea %d: Address inválida (%s)", lineno, t); rc = -1; }+ if (c->naddr >= 8 || parse_cidr(t, &c->addr[c->naddr], 0)) { lerr_set(err, errn, "vpn.invalidLineValue", "line", lerr_int(lineno), "key", "Address", "value", t, NULL); rc = -1; }else c->naddr++;}} else if (section == 1 && !strcasecmp(k, "DNS")) {@@ -133,42 +133,42 @@ static int wg_parse(const char *text, WgConf *c, char *err, size_t errn) {uint8_t a[16];if (!parse_ip(t, &fam, a)) { if (c->ndns < 8) snprintf(c->dns[c->ndns++], 64, "%s", t); }else if (valid_domain(t)) { if (c->nsearch < 8) snprintf(c->search[c->nsearch++], 64, "%s", t); }- else { snprintf(err, errn, "línea %d: DNS inválido (%s)", lineno, t); rc = -1; }+ else { lerr_set(err, errn, "vpn.invalidLineValue", "line", lerr_int(lineno), "key", "DNS", "value", t, NULL); rc = -1; }}} else if (section == 1 && !strcasecmp(k, "MTU")) {c->mtu = atoi(v);- if (c->mtu < 576 || c->mtu > 9000) { snprintf(err, errn, "línea %d: MTU inválido", lineno); rc = -1; }+ if (c->mtu < 576 || c->mtu > 9000) { lerr_set(err, errn, "vpn.invalidLineValue", "line", lerr_int(lineno), "key", "MTU", NULL); rc = -1; }} else if (section == 1 && !strcasecmp(k, "ListenPort")) {c->listen = atoi(v);- if (c->listen < 1 || c->listen > 65535) { snprintf(err, errn, "línea %d: ListenPort inválido", lineno); rc = -1; }+ if (c->listen < 1 || c->listen > 65535) { lerr_set(err, errn, "vpn.invalidLineValue", "line", lerr_int(lineno), "key", "ListenPort", NULL); rc = -1; }} else if (section == 1 && !strcasecmp(k, "FwMark")) {c->ignored++;} else if (p && !strcasecmp(k, "PublicKey")) {- if (key32(v, p->pub)) { snprintf(err, errn, "línea %d: PublicKey inválida", lineno); rc = -1; }+ if (key32(v, p->pub)) { lerr_set(err, errn, "vpn.invalidLineValue", "line", lerr_int(lineno), "key", "PublicKey", NULL); rc = -1; }} else if (p && !strcasecmp(k, "PresharedKey")) {- if (key32(v, p->psk)) { snprintf(err, errn, "línea %d: PresharedKey inválida", lineno); rc = -1; }+ if (key32(v, p->psk)) { lerr_set(err, errn, "vpn.invalidLineValue", "line", lerr_int(lineno), "key", "PresharedKey", NULL); rc = -1; }else p->has_psk = 1;} else if (p && !strcasecmp(k, "Endpoint")) {- if (!valid_endpoint(v)) { snprintf(err, errn, "línea %d: Endpoint inválido", lineno); rc = -1; }+ if (!valid_endpoint(v)) { lerr_set(err, errn, "vpn.invalidLineValue", "line", lerr_int(lineno), "key", "Endpoint", NULL); rc = -1; }else snprintf(p->endpoint, sizeof p->endpoint, "%s", v);} else if (p && !strcasecmp(k, "AllowedIPs")) {for (char *t = strtok(v, ","); t && !rc; t = strtok(NULL, ",")) {t = trim(t);if (!*t) continue;- if (p->nallowed >= MAX_IPS || parse_cidr(t, &p->allowed[p->nallowed], 0)) { snprintf(err, errn, "línea %d: AllowedIPs inválido (%s)", lineno, t); rc = -1; }+ if (p->nallowed >= MAX_IPS || parse_cidr(t, &p->allowed[p->nallowed], 0)) { lerr_set(err, errn, "vpn.invalidLineValue", "line", lerr_int(lineno), "key", "AllowedIPs", "value", t, NULL); rc = -1; }else p->nallowed++;}} else if (p && !strcasecmp(k, "PersistentKeepalive")) {p->keepalive = !strcasecmp(v, "off") ? 0 : atoi(v);- if (p->keepalive < 0 || p->keepalive > 65535) { snprintf(err, errn, "línea %d: PersistentKeepalive inválido", lineno); rc = -1; }- } else { snprintf(err, errn, "línea %d: clave desconocida %s", lineno, k); rc = -1; }+ if (p->keepalive < 0 || p->keepalive > 65535) { lerr_set(err, errn, "vpn.invalidLineValue", "line", lerr_int(lineno), "key", "PersistentKeepalive", NULL); rc = -1; }+ } else { lerr_set(err, errn, "vpn.unknownKey", "line", lerr_int(lineno), "key", k, NULL); rc = -1; }}free(copy);- if (!rc && !c->has_priv && !c->generate) { snprintf(err, errn, "falta PrivateKey"); rc = -1; }- if (!rc && !c->npeer) { snprintf(err, errn, "falta [Peer]"); rc = -1; }+ if (!rc && !c->has_priv && !c->generate) { lerr_set(err, errn, "vpn.missingKey", "key", "PrivateKey", NULL); rc = -1; }+ if (!rc && !c->npeer) { lerr_set(err, errn, "vpn.missingKey", "key", "[Peer]", NULL); rc = -1; }for (int i = 0; !rc && i < c->npeer; i++) {uint8_t zero[32] = {0};- if (!memcmp(c->peer[i].pub, zero, 32)) { snprintf(err, errn, "un [Peer] no tiene PublicKey"); rc = -1; }+ if (!memcmp(c->peer[i].pub, zero, 32)) { lerr_set(err, errn, "wg.peerNoPublicKey", NULL); rc = -1; }}return rc;}@@ -211,11 +211,11 @@ void vpn_ifname(const char *type, const char *name, char *out, size_t n) {int wg_import(const char *name, const char *text, char *pub_out, char *err, size_t errn) {WgConf c;if (wg_parse(text, &c, err, errn)) return -1;- if (c.generate) { if (random_bytes(c.priv, 32)) { snprintf(err, errn, "sin números aleatorios"); return -1; } x25519_clamp(c.priv); }+ if (c.generate) { if (random_bytes(c.priv, 32)) { lerr_set(err, errn, "wg.noRandom", NULL); return -1; } x25519_clamp(c.priv); }uint8_t pub[32];x25519_public(pub, c.priv);b64_encode(pub, 32, pub_out, 64);- if (c.ignored) admin_say("LOG", "se ignoraron %d líneas (PostUp, PreDown, Table...): LordOS no ejecuta comandos", c.ignored);+ if (c.ignored) admin_log("wg.ignoredLines", "count", lerr_int(c.ignored), NULL);Buf b = {0};wg_emit(&c, &b);char path[160];@@ -241,7 +241,7 @@ int wg_import(const char *name, const char *text, char *pub_out, char *err, sizesnprintf(path, sizeof path, NET_VPN_DIR "/%s.json", name);ok = ok && m.p && write_file_atomic(path, m.p, m.len, 0644) == 0;buf_free(&m);- if (!ok) { snprintf(err, errn, "no se pudo guardar"); return -1; }+ if (!ok) { lerr_set(err, errn, "net.saveFailed", NULL); return -1; }return 0;}@@ -285,9 +285,9 @@ static int resolve_endpoint(const char *ep, struct sockaddr_storage *ss, socklenstatic int wg_set_device(const char *ifn, const WgConf *c, uint32_t fwmark, char *err, size_t errn) {int fd = nl_open(NETLINK_GENERIC, 0);- if (fd < 0) { snprintf(err, errn, "netlink"); return -1; }+ if (fd < 0) { lerr_set(err, errn, "net.netlinkFailed", NULL); return -1; }int fam = genl_family(fd, WG_GENL_NAME);- if (fam < 0) { close(fd); snprintf(err, errn, "el kernel no tiene WireGuard"); return -1; }+ if (fam < 0) { close(fd); lerr_set(err, errn, "wg.noKernel", NULL); return -1; }NlMsg m;nlm_init(&m, (uint16_t)fam, 0);struct genlmsghdr g = { .cmd = WG_CMD_SET_DEVICE, .version = WG_GENL_VERSION };@@ -307,7 +307,7 @@ static int wg_set_device(const char *ifn, const WgConf *c, uint32_t fwmark, charif (p->endpoint[0]) {struct sockaddr_storage ss;socklen_t sl;- if (resolve_endpoint(p->endpoint, &ss, &sl)) { nlm_free(&m); close(fd); snprintf(err, errn, "no se pudo resolver %s", p->endpoint); return -1; }+ if (resolve_endpoint(p->endpoint, &ss, &sl)) { nlm_free(&m); close(fd); lerr_set(err, errn, "vpn.resolveFailed", "host", p->endpoint, NULL); return -1; }nlm_attr(&m, WGPEER_A_ENDPOINT, &ss, sl);}nlm_attr_u16(&m, WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL, (uint16_t)p->keepalive);@@ -325,7 +325,7 @@ static int wg_set_device(const char *ifn, const WgConf *c, uint32_t fwmark, charnlm_nest_end(&m, peers);int r = nl_talk(fd, &m);close(fd);- if (r) snprintf(err, errn, "WG_CMD_SET_DEVICE: %s", strerror(-r));+ if (r) lerr_set(err, errn, "wg.setDeviceFailed", "errno", lerr_errno(-r), NULL);return r ? -1 : 0;}@@ -338,7 +338,7 @@ static int load_conf(const char *name, WgConf *c, char *err, size_t errn) {char path[160];snprintf(path, sizeof path, NET_VPN_DIR "/%s.conf", name);char *t = read_file(path, 65536, NULL);- if (!t) { snprintf(err, errn, "no existe la VPN %s", name); return -1; }+ if (!t) { lerr_set(err, errn, "vpn.unknown", "name", name, NULL); return -1; }int r = wg_parse(t, c, err, errn);memset(t, 0, strlen(t));free(t);@@ -356,11 +356,11 @@ int wg_up(const char *name, char *err, size_t errn) {char ifn[IFNAMSIZ];vpn_ifname("wireguard", name, ifn, sizeof ifn);int fd = nl_open(NETLINK_ROUTE, 0);- if (fd < 0) { snprintf(err, errn, "netlink"); return -1; }+ if (fd < 0) { lerr_set(err, errn, "net.netlinkFailed", NULL); return -1; }int idx = rt_ifindex(ifn);if (idx) { rt_link_del(fd, idx); idx = 0; }int r = rt_link_new(fd, ifn, "wireguard");- if (r) { close(fd); snprintf(err, errn, "no se pudo crear %s: %s", ifn, strerror(-r)); return -1; }+ if (r) { close(fd); lerr_set(err, errn, "vpn.createIfFailed", "name", ifn, "errno", lerr_errno(-r), NULL); return -1; }idx = rt_ifindex(ifn);int full4 = 0, full6 = 0;for (int i = 0; i < c.npeer; i++)diff --git a/server/src/net/wifi.c b/server/src/net/wifi.cindex ab757e7..fe498d5 100644--- a/server/src/net/wifi.c+++ b/server/src/net/wifi.c@@ -245,7 +245,7 @@ static void unescape_ssid(const char *in, char *out, size_t n) {void wifi_act_scan(const char *ifname) {char me[108];int fd = ctrl_open(ifname, me, sizeof me);- if (fd < 0) { admin_say("ERR", "la interfaz %s no tiene wpa_supplicant", ifname); return; }+ if (fd < 0) { admin_err("wifi.noSupplicant", "name", ifname, NULL); return; }char r[256];int got = 0;if (send(fd, "ATTACH", 6, 0) == 6 && ctrl_recv(fd, r, sizeof r, 3000) > 0 && send(fd, "SCAN", 4, 0) == 4) {@@ -267,8 +267,8 @@ void wifi_act_scan(const char *ifname) {unlink(me);(void)got; /* if the notice didn't arrive, whatever results there are get used */char *res = malloc(65536);- if (!res) { admin_say("ERR", "sin memoria"); return; }- if (wifi_ctrl(ifname, "SCAN_RESULTS", res, 65536) <= 0) { free(res); admin_say("ERR", "wpa_supplicant no respondió"); return; }+ if (!res) { admin_err("sys.outOfMemory", NULL); return; }+ if (wifi_ctrl(ifname, "SCAN_RESULTS", res, 65536) <= 0) { free(res); admin_err("wifi.noAnswer", NULL); return; }/* bssid / frequency / signal / flags / ssid; one entry per SSID (the one with the best signal) */struct { char ssid[40], bssid[20], sec[16]; int freq, signal; } nets[96];int n = 0;@@ -311,12 +311,12 @@ void wifi_act_scan(const char *ifname) {if (b.p) admin_say("LOG", "%s", b.p);buf_free(&b);}- admin_say("OK", "%d", n);+ admin_say("OK", "%d", n); /* i18n-ok: a count (data) */}void wifi_act_connect(const char *ifname, const char *ssid, const char *pass) {- if (!valid_ssid(ssid)) { admin_say("ERR", "SSID inválido"); return; }- if (!valid_pass(pass) || (pass[0] && strlen(pass) < 8)) { admin_say("ERR", "contraseña inválida"); return; }+ if (!valid_ssid(ssid)) { admin_err("wifi.invalidSsid", NULL); return; }+ if (!valid_pass(pass) || (pass[0] && strlen(pass) < 8)) { admin_err("wifi.invalidPassword", NULL); return; }char sh[72], path[160];hex((const uint8_t *)ssid, strlen(ssid), sh);/* it's saved: public part (ssid, security) and secret part (password) */@@ -332,27 +332,27 @@ void wifi_act_connect(const char *ifname, const char *ssid, const char *pass) {snprintf(path, sizeof path, NET_WIFI_DIR "/%s.key", sh);ok = ok && write_file_atomic(path, sec, (size_t)sl, 0600) == 0;memset(sec, 0, sizeof sec);- if (!ok) { admin_say("ERR", "no se pudo guardar la red"); return; }+ if (!ok) { admin_err("wifi.saveFailed", NULL); return; }char wname[40];snprintf(wname, sizeof wname, "wpa:%s", ifname);int fresh = !admin_daemon_running(wname);- if (wifi_start(ifname)) { admin_say("ERR", "no se pudo iniciar wpa_supplicant en %s", ifname); return; }+ if (wifi_start(ifname)) { admin_err("wifi.startFailed", "name", ifname, NULL); return; }int id = fresh ? find_network(ifname, sh) : load_network(ifname, ssid, pass);- if (id < 0) { admin_say("ERR", "wpa_supplicant no aceptó la red"); return; }+ if (id < 0) { admin_err("wifi.rejected", NULL); return; }char cmd[48];snprintf(cmd, sizeof cmd, "SELECT_NETWORK %d", id);- if (ctrl_ok(ifname, cmd)) { admin_say("ERR", "wpa_supplicant no pudo elegir la red"); return; }+ if (ctrl_ok(ifname, cmd)) { admin_err("wifi.selectFailed", NULL); return; }ctrl_ok(ifname, "ENABLE_NETWORK all"); /* the other saved ones stay available */- admin_say("OK", "conectando a %s", ssid);+ admin_ok("wifi.connecting", "ssid", ssid, NULL);}void wifi_act_disconnect(const char *ifname) {- if (ctrl_ok(ifname, "DISCONNECT")) { admin_say("ERR", "la interfaz %s no tiene wpa_supplicant", ifname); return; }- admin_say("OK", "desconectado");+ if (ctrl_ok(ifname, "DISCONNECT")) { admin_err("wifi.noSupplicant", "name", ifname, NULL); return; }+ admin_ok("wifi.disconnected", NULL);}void wifi_act_forget(const char *ssid) {- if (!valid_ssid(ssid)) { admin_say("ERR", "SSID inválido"); return; }+ if (!valid_ssid(ssid)) { admin_err("wifi.invalidSsid", NULL); return; }char sh[72], path[160];hex((const uint8_t *)ssid, strlen(ssid), sh);snprintf(path, sizeof path, NET_WIFI_DIR "/%s.key", sh);@@ -369,5 +369,5 @@ void wifi_act_forget(const char *ssid) {if (id >= 0) { char cmd[48]; snprintf(cmd, sizeof cmd, "REMOVE_NETWORK %d", id); ctrl_ok(e->d_name, cmd); }}if (d) closedir(d);- if (had) admin_say("OK", "red olvidada"); else admin_say("ERR", "no estaba guardada");+ if (had) admin_ok("wifi.forgotten", NULL); else admin_err("wifi.notSaved", NULL);}diff --git a/server/src/netperm/netperm.c b/server/src/netperm/netperm.cindex d7dc2d5..f54fe89 100644--- a/server/src/netperm/netperm.c+++ b/server/src/netperm/netperm.c@@ -19,6 +19,7 @@#include "netperm/npdns.h"#include "netperm/npproto.h"#include "fw/fwmap.h"+#include "errcode.h"#include "sec/json.h"#include <arpa/inet.h>@@ -96,7 +97,7 @@ typedef struct {static struct {int bpf_ok;- char bpf_err[200];+ char bpf_err[200]; /* a code line (errcode.h): the firewall page shows it translated */int m_cfg, m_apps, m_union, m_lpm4, m_lpm6, m_seen, m_counts, m_events;int links[16], nlinks;int progs[16], nprogs;@@ -652,7 +653,7 @@ static void on_dns(void *u, const uint8_t *pkt, size_t len) {static int bpf_setup(void) {#ifndef NP_HAVE_BPF- snprintf(G.bpf_err, sizeof G.bpf_err, "built without the BPF programs (BPF=0: clang missing)");+ lerr_set(G.bpf_err, sizeof G.bpf_err, "fw.bpfNotBuilt", NULL);return -1;#elseG.m_cfg = bpfs_map_create(BPF_MAP_TYPE_ARRAY, 4, sizeof(NpCfg), 1, 0, "np_cfg");@@ -664,11 +665,11 @@ static int bpf_setup(void) {G.m_counts = bpfs_map_create(BPF_MAP_TYPE_HASH, 8, sizeof(NpCount), NP_MAX_APPS, 0, "np_counts");G.m_events = bpfs_map_create(BPF_MAP_TYPE_RINGBUF, 0, 0, NP_RINGBUF, 0, "np_events");if (G.m_cfg < 0 || G.m_apps < 0 || G.m_union < 0 || G.m_lpm4 < 0 || G.m_lpm6 < 0 || G.m_seen < 0 || G.m_counts < 0 || G.m_events < 0) {- snprintf(G.bpf_err, sizeof G.bpf_err, "could not create the BPF maps: %s", strerror(errno));+ lerr_set(G.bpf_err, sizeof G.bpf_err, "fw.bpfMaps", "errno", lerr_errno(errno), NULL);return -1;}if (bpfs_ring_open(&G.ring, G.m_events, NP_RINGBUF)) {- snprintf(G.bpf_err, sizeof G.bpf_err, "could not map the ring buffer: %s", strerror(errno));+ lerr_set(G.bpf_err, sizeof G.bpf_err, "fw.bpfRing", "errno", lerr_errno(errno), NULL);return -1;}static const struct { const char *sec; uint32_t type, attach; } want[] = {@@ -685,13 +686,13 @@ static int bpf_setup(void) {for (size_t w = 0; w < sizeof want / sizeof want[0]; w++) {const NpProgDesc *d = NULL;for (int i = 0; i < NP_NPROGS; i++) if (!strcmp(np_progs[i].section, want[w].sec)) d = &np_progs[i];- if (!d) { snprintf(G.bpf_err, sizeof G.bpf_err, "program %s is missing", want[w].sec); return -1; }+ if (!d) { lerr_set(G.bpf_err, sizeof G.bpf_err, "fw.bpfMissing", "program", want[w].sec, NULL); return -1; }int fd = bpfs_prog_load(want[w].type, want[w].attach, d, map_fd, log, sizeof log);if (fd < 0) {int e = errno;size_t ll = strlen(log);fprintf(stderr, "%s\n", ll > 3000 ? log + ll - 3000 : log);- snprintf(G.bpf_err, sizeof G.bpf_err, "the kernel did not accept %s: %s", want[w].sec, strerror(e));+ lerr_set(G.bpf_err, sizeof G.bpf_err, "fw.bpfRejected", "program", want[w].sec, "errno", lerr_errno(e), NULL);return -1;}G.attach[np] = want[w].attach;@@ -700,7 +701,7 @@ static int bpf_setup(void) {G.nprogs = np;NpCfg cfg = { SCOPE_LEVEL, 1, USER_LEVEL };uint32_t zero = 0;- if (bpfs_map_update(G.m_cfg, &zero, &cfg, BPF_ANY)) { snprintf(G.bpf_err, sizeof G.bpf_err, "np_cfg: %s", strerror(errno)); return -1; }+ if (bpfs_map_update(G.m_cfg, &zero, &cfg, BPF_ANY)) { lerr_set(G.bpf_err, sizeof G.bpf_err, "fw.bpfConfig", "errno", lerr_errno(errno), NULL); return -1; }logf_("%d programas BPF cargados", np);return 0;#endifdiff --git a/server/src/pkg/http.c b/server/src/pkg/http.cindex 5b97e85..a2c2a59 100644--- a/server/src/pkg/http.c+++ b/server/src/pkg/http.c@@ -6,6 +6,7 @@* [type 1 byte][item 4][length 4][data] type H = "status date length", D = data, E = end* (E with text = error). */#include "http.h"+#include "../errcode.h"#include "crypto.h"#include <ctype.h>@@ -95,7 +96,7 @@ static int conn_open(Conn *c, const char *host, const char *port, char *err, sizmemset(&hints, 0, sizeof hints);hints.ai_socktype = SOCK_STREAM;int r = getaddrinfo(host, port, &hints, &res);- if (r) { snprintf(err, errlen, "no se encontró %.100s (%.60s)", host, gai_strerror(r)); return -1; }+ if (r) { lerr_set(err, errlen, "pkg.http.hostNotFound", "host", host, NULL); return -1; }for (struct addrinfo *a = res; a; a = a->ai_next) {int fd = socket(a->ai_family, a->ai_socktype | SOCK_CLOEXEC | SOCK_NONBLOCK, a->ai_protocol);if (fd < 0) continue;@@ -108,7 +109,7 @@ static int conn_open(Conn *c, const char *host, const char *port, char *err, sizbreak;}freeaddrinfo(res);- if (c->fd < 0) { snprintf(err, errlen, "no se pudo conectar con %.120s", host); return -1; }+ if (c->fd < 0) { lerr_set(err, errlen, "pkg.http.connectFailed", "host", host, NULL); return -1; }snprintf(c->host, sizeof c->host, "%s", host);snprintf(c->port, sizeof c->port, "%s", port);return 0;@@ -195,7 +196,7 @@ static void get_one(Conn *c, const FetchItem *it, uint32_t idx) {char host[256], port[8];const char *path;if (parse_url(url, host, sizeof host, port, sizeof port, &path)) {- snprintf(err, sizeof err, strncmp(url, "https://", 8) ? "dirección inválida" : "el servidor redirige a https, que LordOS no usa para paquetes");+ lerr_set(err, sizeof err, strncmp(url, "https://", 8) ? "pkg.http.badUrl" : "pkg.http.httpsRedirect", NULL);break;}int retry = c->fd >= 0; /* a reused connection may have been closed */@@ -213,16 +214,16 @@ static void get_one(Conn *c, const FetchItem *it, uint32_t idx) {if (rl >= (int)sizeof req || conn_write(c, req, (size_t)rl) || conn_line(c, line, sizeof line)) {conn_close(c);if (retry) { retry = 0; goto again; }- snprintf(err, sizeof err, "%.150s no respondió", host);+ lerr_set(err, sizeof err, "pkg.http.noResponse", "host", host, NULL);break;}int status = 0, minor = 1;- if (sscanf(line, "HTTP/1.%d %d", &minor, &status) != 2) { conn_close(c); snprintf(err, sizeof err, "respuesta HTTP inválida"); break; }+ if (sscanf(line, "HTTP/1.%d %d", &minor, &status) != 2) { conn_close(c); lerr_set(err, sizeof err, "pkg.http.badResponse", NULL); break; }int64_t clen = -1, lastmod = 0;int chunked = 0, close_after = minor == 0;char location[1024] = "";for (;;) {- if (conn_line(c, line, sizeof line)) { conn_close(c); snprintf(err, sizeof err, "encabezados HTTP inválidos"); goto out; }+ if (conn_line(c, line, sizeof line)) { conn_close(c); lerr_set(err, sizeof err, "pkg.http.badHeaders", NULL); goto out; }if (!line[0]) break;char *v = strchr(line, ':');if (!v) continue;@@ -266,7 +267,7 @@ static void get_one(Conn *c, const FetchItem *it, uint32_t idx) {size_t n = c->len - c->pos;if ((chunked || clen >= 0) && (int64_t)n > remaining) n = (size_t)remaining;if (deliver) {- if (got + n > it->max) { snprintf(err, sizeof err, "archivo más grande de lo permitido"); conn_close(c); goto out; }+ if (got + n > it->max) { lerr_set(err, sizeof err, "pkg.http.tooLarge", NULL); conn_close(c); goto out; }if (send_msg(c->out, 'D', idx, c->buf + c->pos, (uint32_t)n)) _exit(1);}got += n;@@ -285,11 +286,11 @@ static void get_one(Conn *c, const FetchItem *it, uint32_t idx) {char h[48];snprintf(h, sizeof h, "304 0 0");send_msg(c->out, 'H', idx, h, (uint32_t)strlen(h));- } else if (!deliver) snprintf(err, sizeof err, "el servidor respondió %d", status);+ } else if (!deliver) lerr_set(err, sizeof err, "pkg.http.status", "status", lerr_int(status), NULL);break;broken:conn_close(c);- snprintf(err, sizeof err, "la conexión se cortó");+ lerr_set(err, sizeof err, "pkg.http.connectionLost", NULL);break;}out:@@ -332,7 +333,7 @@ int fetch_batch(FetchItem *items, int n, FetchProgress cb, void *ud) {items[i].status = 0;items[i].size = 0;items[i].last_modified = 0;- snprintf(items[i].err, sizeof items[i].err, "no se descargó");+ lerr_set(items[i].err, sizeof items[i].err, "pkg.http.notDownloaded", NULL);}pid_t pid = fork();if (pid < 0) { close(p[0]); close(p[1]); return 0; }@@ -379,15 +380,15 @@ int fetch_batch(FetchItem *items, int n, FetchProgress cb, void *ud) {fd = open(tmp, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC | O_NOFOLLOW, 0644);cur = (int)item;sha256_init(&sh);- if (fd < 0) { snprintf(it->err, sizeof it->err, "no se pudo crear %.150s", tmp); it->status = 0; }+ if (fd < 0) { lerr_set(it->err, sizeof it->err, "pkg.http.createFailed", "path", tmp, NULL); it->status = 0; }}} else if (h[0] == 'D') {if ((int)item != cur || fd < 0) continue;- if (it->size + len > it->max) { close(fd); fd = -1; unlink(tmp); it->status = 0; snprintf(it->err, sizeof it->err, "archivo más grande de lo permitido"); continue; }+ if (it->size + len > it->max) { close(fd); fd = -1; unlink(tmp); it->status = 0; lerr_set(it->err, sizeof it->err, "pkg.http.tooLarge", NULL); continue; }for (uint32_t o = 0; o < len;) {ssize_t w = write(fd, buf + o, len - o);if (w < 0 && errno == EINTR) continue;- if (w <= 0) { close(fd); fd = -1; unlink(tmp); it->status = 0; snprintf(it->err, sizeof it->err, "no se pudo escribir (¿disco lleno?)"); break; }+ if (w <= 0) { close(fd); fd = -1; unlink(tmp); it->status = 0; lerr_set(it->err, sizeof it->err, "pkg.http.writeFailed", NULL); break; }o += (uint32_t)w;}sha256_update(&sh, buf, len);@@ -410,7 +411,7 @@ int fetch_batch(FetchItem *items, int n, FetchProgress cb, void *ud) {fd = -1;if (good) {sha256_final(&sh, it->sha256);- if (rename(tmp, it->dest)) { unlink(tmp); it->status = 0; snprintf(it->err, sizeof it->err, "no se pudo guardar %.150s", it->dest); }+ if (rename(tmp, it->dest)) { unlink(tmp); it->status = 0; lerr_set(it->err, sizeof it->err, "pkg.http.saveFailed", "path", it->dest, NULL); }} else unlink(tmp);}if (it->status == 200 || it->status == 304) ok++;diff --git a/server/src/pkg/idx.c b/server/src/pkg/idx.cindex e130423..b5431f8 100644--- a/server/src/pkg/idx.c+++ b/server/src/pkg/idx.c@@ -1,5 +1,6 @@/* idx.c — building and reading the package index (see idx.h). */#include "idx.h"+#include "../errcode.h"#include "deb.h"#include "crypto.h"@@ -712,15 +713,15 @@ static int pad4(int fd, size_t *off) {}int idxb_write(IdxBuilder *b, const char *dir, const char *arch, char *err, size_t errlen) {- if (b->npk >= UINT32_MAX / 2) { snprintf(err, errlen, "demasiados paquetes"); return -1; }+ if (b->npk >= UINT32_MAX / 2) { lerr_set(err, errlen, "pkg.index.tooManyPackages", NULL); return -1; }uint32_t *perm = malloc((b->npk ? b->npk : 1) * sizeof *perm), *inv = malloc((b->npk ? b->npk : 1) * sizeof *inv);- if (!perm || !inv) { free(perm); free(inv); snprintf(err, errlen, "sin memoria"); return -1; }+ if (!perm || !inv) { free(perm); free(inv); lerr_set(err, errlen, "sys.outOfMemory", NULL); return -1; }for (size_t i = 0; i < b->npk; i++) perm[i] = (uint32_t)i;sort_b = b;qsort(perm, b->npk, sizeof *perm, pkg_order);for (size_t i = 0; i < b->npk; i++) inv[perm[i]] = (uint32_t)i;IdxPkg *sorted = malloc((b->npk ? b->npk : 1) * sizeof *sorted);- if (!sorted) { free(perm); free(inv); snprintf(err, errlen, "sin memoria"); return -1; }+ if (!sorted) { free(perm); free(inv); lerr_set(err, errlen, "sys.outOfMemory", NULL); return -1; }for (size_t i = 0; i < b->npk; i++) sorted[i] = b->pk[perm[i]];/* provides */@@ -775,7 +776,7 @@ int idxb_write(IdxBuilder *b, const char *dir, const char *arch, char *err, sizeh.off_str = (uint32_t)off; h.len_str = (uint32_t)b->slen; off += b->slen;off = (off + 3) & ~(size_t)3;h.off_desc = (uint32_t)off; h.len_desc = (uint32_t)b->dlen; off += b->dlen;- if (off > UINT32_MAX) { free(perm); free(inv); free(sorted); free(prov); snprintf(err, errlen, "índice demasiado grande"); return -1; }+ if (off > UINT32_MAX) { free(perm); free(inv); free(sorted); free(prov); lerr_set(err, errlen, "pkg.index.tooLarge", NULL); return -1; }char tmp[512], path[512];snprintf(tmp, sizeof tmp, "%s/index.bin.new", dir);@@ -801,6 +802,6 @@ int idxb_write(IdxBuilder *b, const char *dir, const char *arch, char *err, sizeif (ok) ok = fsync(fd) == 0;if (fd >= 0 && close(fd)) ok = 0;free(perm); free(inv); free(sorted); free(prov);- if (!ok || rename(tmp, path)) { unlink(tmp); snprintf(err, errlen, "no se pudo escribir %s: %s", path, strerror(errno)); return -1; }+ if (!ok || rename(tmp, path)) { unlink(tmp); lerr_set(err, errlen, "pkg.index.writeFailed", "path", path, "errno", lerr_errno(errno), NULL); return -1; }return 0;}diff --git a/server/src/pkg/pgp.c b/server/src/pkg/pgp.cindex a1f4d6f..db816ba 100644--- a/server/src/pkg/pgp.c+++ b/server/src/pkg/pgp.c@@ -7,6 +7,7 @@* signature over the canonical text, the key has to exist, be able to sign, not be revoked or* expired, and the signature can't be expired or come from the future. */#include "pgp.h"+#include "../errcode.h"#include "crypto.h"#include <stdio.h>@@ -409,14 +410,14 @@ int pgp_verify_clearsigned(const PgpKeyring *kr, const char *msg, size_t len, inerr[0] = 0;const char *end = msg + len, *p = msg;if (len < sizeof head || memcmp(msg, head, sizeof head - 1) || (msg[sizeof head - 1] != '\n' && msg[sizeof head - 1] != '\r')) {- snprintf(err, errlen, "no es un mensaje firmado en claro");+ lerr_set(err, errlen, "pkg.pgp.notClearsigned", NULL);return -1;}p = memchr(msg, '\n', len) + 1;/* Hash: headers up to the empty line */for (;;) {const char *nl = memchr(p, '\n', (size_t)(end - p));- if (!nl) { snprintf(err, errlen, "mensaje firmado incompleto"); return -1; }+ if (!nl) { lerr_set(err, errlen, "pkg.pgp.incomplete", NULL); return -1; }size_t l = (size_t)(nl - p);if (l && p[l - 1] == '\r') l--;p = nl + 1;@@ -424,7 +425,7 @@ int pgp_verify_clearsigned(const PgpKeyring *kr, const char *msg, size_t len, in}/* text: up to the signature's armor */char *text = malloc((size_t)(end - p) + 2), *canon = malloc((size_t)(end - p) * 2 + 2);- if (!text || !canon) { free(text); free(canon); snprintf(err, errlen, "sin memoria"); return -1; }+ if (!text || !canon) { free(text); free(canon); lerr_set(err, errlen, "sys.outOfMemory", NULL); return -1; }size_t tl = 0, cl = 0;const char *sig = NULL;int first = 1;@@ -435,7 +436,7 @@ int pgp_verify_clearsigned(const PgpKeyring *kr, const char *msg, size_t len, inif (l >= sizeof sighead - 1 && !memcmp(p, sighead, sizeof sighead - 1)) { sig = p; break; }const char *s = p;if (l >= 2 && s[0] == '-' && s[1] == ' ') { s += 2; l -= 2; }- else if (l && s[0] == '-') { free(text); free(canon); snprintf(err, errlen, "línea con guion sin escapar"); return -1; }+ else if (l && s[0] == '-') { free(text); free(canon); lerr_set(err, errlen, "pkg.pgp.unescapedDash", NULL); return -1; }while (l && (s[l - 1] == ' ' || s[l - 1] == '\t' || s[l - 1] == '\r')) l--;if (!first) { canon[cl++] = '\r'; canon[cl++] = '\n'; }first = 0;@@ -445,17 +446,17 @@ int pgp_verify_clearsigned(const PgpKeyring *kr, const char *msg, size_t len, inif (!nl) break;p = nl + 1;}- if (!sig) { free(text); free(canon); snprintf(err, errlen, "falta la firma"); return -1; }+ if (!sig) { free(text); free(canon); lerr_set(err, errlen, "pkg.pgp.noSignature", NULL); return -1; }/* signature armor; after END there can only be whitespace */const char *endmark = NULL;for (const char *q = sig; q + 27 <= end; q++)if (!memcmp(q, "-----END PGP SIGNATURE-----", 27)) { endmark = q + 27; break; }- if (!endmark) { free(text); free(canon); snprintf(err, errlen, "firma incompleta"); return -1; }+ if (!endmark) { free(text); free(canon); lerr_set(err, errlen, "pkg.pgp.signatureIncomplete", NULL); return -1; }for (const char *q = endmark; q < end; q++)- if (*q != '\n' && *q != '\r' && *q != ' ' && *q != '\t') { free(text); free(canon); snprintf(err, errlen, "datos después de la firma"); return -1; }+ if (*q != '\n' && *q != '\r' && *q != ' ' && *q != '\t') { free(text); free(canon); lerr_set(err, errlen, "pkg.pgp.trailingData", NULL); return -1; }uint8_t *raw;long rawlen = dearmor(sig, (size_t)(endmark - sig), &raw);- if (rawlen < 0) { free(text); free(canon); snprintf(err, errlen, "firma mal codificada"); return -1; }+ if (rawlen < 0) { free(text); free(canon); lerr_set(err, errlen, "pkg.pgp.badEncoding", NULL); return -1; }int good = 0, bad = 0, unknown = 0;size_t pos = 0;@@ -472,11 +473,11 @@ int pgp_verify_clearsigned(const PgpKeyring *kr, const char *msg, size_t len, inif (!k) { unknown++; continue; }char fpr[41];hex_fpr(k->fpr, fpr);- if (k->revoked) { snprintf(why, sizeof why, "la clave %s está revocada", fpr); continue; }- if (k->expires && k->expires <= now) { snprintf(why, sizeof why, "la clave %s venció", fpr); continue; }- if (!k->can_sign) { snprintf(why, sizeof why, "la clave %s no es de firma", fpr); continue; }- if (s.created > now + 86400) { snprintf(why, sizeof why, "firma con fecha futura (%s)", fpr); continue; }- if (s.sig_expires && s.created + s.sig_expires <= now) { snprintf(why, sizeof why, "la firma de %s venció", fpr); continue; }+ if (k->revoked) { lerr_set(why, sizeof why, "pkg.pgp.keyRevoked", "key", fpr, NULL); continue; }+ if (k->expires && k->expires <= now) { lerr_set(why, sizeof why, "pkg.pgp.keyExpired", "key", fpr, NULL); continue; }+ if (!k->can_sign) { lerr_set(why, sizeof why, "pkg.pgp.keyNotSigning", "key", fpr, NULL); continue; }+ if (s.created > now + 86400) { lerr_set(why, sizeof why, "pkg.pgp.futureSignature", "key", fpr, NULL); continue; }+ if (s.sig_expires && s.created + s.sig_expires <= now) { lerr_set(why, sizeof why, "pkg.pgp.signatureExpired", "key", fpr, NULL); continue; }if (s.created < k->created) { bad++; continue; }/* hash: text (canonical if it's a text signature) + signature header + v4 trailer */uint8_t dig[64], trailer[6] = { 4, 0xff, (uint8_t)(s.headlen >> 24), (uint8_t)(s.headlen >> 16), (uint8_t)(s.headlen >> 8), (uint8_t)s.headlen };@@ -499,19 +500,19 @@ int pgp_verify_clearsigned(const PgpKeyring *kr, const char *msg, size_t len, in}if (dig[0] != s.left16[0] || dig[1] != s.left16[1] || !verify_sig(k, &s, dig)) {bad++;- snprintf(why, sizeof why, "firma inválida de la clave %s", fpr);+ lerr_set(why, sizeof why, "pkg.pgp.badSignature", "key", fpr, NULL);continue;}good++;}free(raw);free(canon);- if (r < 0) { free(text); snprintf(err, errlen, "firma mal formada"); return -1; }+ if (r < 0) { free(text); lerr_set(err, errlen, "pkg.pgp.malformed", NULL); return -1; }if (bad) { free(text); snprintf(err, errlen, "%s", why); return -1; }if (!good) {free(text);if (why[0]) snprintf(err, errlen, "%s", why);- else snprintf(err, errlen, "ninguna firma es de una clave conocida (%d desconocidas)", unknown);+ else lerr_set(err, errlen, "pkg.pgp.unknownKeys", "count", lerr_int(unknown), NULL);return 0;}*body = text;diff --git a/server/src/pkg/pkg.c b/server/src/pkg/pkg.cindex 5d6d9af..c007e89 100644--- a/server/src/pkg/pkg.c+++ b/server/src/pkg/pkg.c@@ -89,7 +89,7 @@ static int lock_pkg(void) {}static void progress(const char *phase, uint64_t done, uint64_t total) {- admin_say("LOG", "progress %s %llu %llu", phase, (unsigned long long)done, (unsigned long long)total);+ admin_say("LOG", "progress %s %llu %llu", phase, (unsigned long long)done, (unsigned long long)total); /* i18n-ok: protocol line parsed by apps/store */}static void fetch_progress(uint64_t done, uint64_t total, void *ud) { progress((const char *)ud, done, total); }@@ -150,8 +150,8 @@ static void add_source(Source *src, int *ns, const char *uri, const char *suite,Source *s = &src[*ns];memset(s, 0, sizeof *s);mirror_uri(uri, s->uri, sizeof s->uri);- if (!s->uri[0]) { admin_say("LOG", "fuente salteada (solo http/https): %s", uri); return; }- if (strchr(suite, '/') || !suite[0]) { admin_say("LOG", "repositorio plano no soportado: %s %s", uri, suite); return; }+ if (!s->uri[0]) { admin_log("pkg.sourceSkipped", "uri", uri, NULL); return; }+ if (strchr(suite, '/') || !suite[0]) { admin_log("pkg.flatRepo", "uri", uri, "suite", suite, NULL); return; }snprintf(s->suite, sizeof s->suite, "%s", suite);for (int i = 0; i < nc && i < 16; i++) snprintf(s->comps[s->ncomp++], sizeof s->comps[0], "%s", comps[i]);if (sblen) {@@ -271,7 +271,7 @@ static int load_keyring(const Source *s, PgpKeyring *kr) {memset(kr, 0, sizeof *kr);if (s->inline_key) return pgp_keyring_add_mem(kr, s->inline_key, strlen(s->inline_key));if (s->nkeys) {- for (int i = 0; i < s->nkeys; i++) if (pgp_keyring_add_file(kr, s->keys[i])) admin_say("LOG", "no se pudo leer la clave %s", s->keys[i]);+ for (int i = 0; i < s->nkeys; i++) if (pgp_keyring_add_file(kr, s->keys[i])) admin_log("pkg.keyUnreadable", "path", s->keys[i], NULL);return kr->n ? 0 : -1;}/* no Signed-By: apt's trusted keys */@@ -466,18 +466,18 @@ static void gc_lists(Wanted *w, int nw, Source *src, int ns) {void pkg_act_update(const AdminReq *r, const char *arg, size_t len) {(void)r; (void)arg; (void)len;int lk = lock_pkg();- if (lk == -2) { admin_say("ERR", "otra operación de paquetes está en curso"); return; }- if (lk < 0 || mkdirs(LISTS, 0755) || mkdirs(LISTS "/partial", 0755) || mkdirs(ICONS, 0755)) { admin_say("ERR", "no se pudo preparar %s", PKG_DIR); return; }+ if (lk == -2) { admin_err("pkg.busy", NULL); return; }+ if (lk < 0 || mkdirs(LISTS, 0755) || mkdirs(LISTS "/partial", 0755) || mkdirs(ICONS, 0755)) { admin_err("pkg.prepareFailed", "path", PKG_DIR, NULL); return; }const char *arch = pkg_native_arch();Source *src = calloc(MAX_SOURCES, sizeof *src);- if (!src) { admin_say("ERR", "sin memoria"); return; }+ if (!src) { admin_err("sys.outOfMemory", NULL); return; }int ns = load_sources(src, arch);- if (!ns) { admin_say("ERR", "no hay fuentes de paquetes (/etc/apt/sources.list.d)"); free(src); return; }+ if (!ns) { admin_err("pkg.noSources", NULL); free(src); return; }/* 1. InRelease of each source */FetchItem *rel = calloc((size_t)ns, sizeof *rel);char (*final)[PATH_MAX] = calloc((size_t)ns, PATH_MAX);- if (!rel || !final) { admin_say("ERR", "sin memoria"); return; }+ if (!rel || !final) { admin_err("sys.outOfMemory", NULL); return; }for (int i = 0; i < ns; i++) {char name[700], san[700];snprintf(name, sizeof name, "%s_%s", src[i].uri, src[i].suite);@@ -488,7 +488,7 @@ void pkg_act_update(const AdminReq *r, const char *arg, size_t len) {rel[i].max = 64u << 20;struct stat st;if (!stat(final[i], &st)) rel[i].ims = (int64_t)st.st_mtime;- admin_say("LOG", "fuente: %s %s %s", src[i].uri, src[i].suite, src[i].comps[0]);+ admin_log("pkg.source", "uri", src[i].uri, "suite", src[i].suite, "component", src[i].comps[0], NULL);}progress("lists", 0, (uint64_t)ns);fetch_batch(rel, ns, NULL, NULL);@@ -500,24 +500,24 @@ void pkg_act_update(const AdminReq *r, const char *arg, size_t len) {int64_t now = (int64_t)time(NULL);for (int i = 0; R && good && i < ns; i++) {const char *path = rel[i].status == 200 ? rel[i].dest : rel[i].status == 304 ? final[i] : NULL;- if (!path) { admin_say("LOG", "%s %s: %s", src[i].uri, src[i].suite, rel[i].err); failures++; continue; }+ if (!path) { admin_log("pkg.sourceFailed", "uri", src[i].uri, "suite", src[i].suite, "reason", rel[i].err, NULL); failures++; continue; }size_t blen;uint8_t *b = read_file(path, &blen, 64u << 20);PgpKeyring kr;char *body = NULL, err[256];size_t bodylen = 0;int ok = b && !load_keyring(&src[i], &kr);- if (!ok) snprintf(err, sizeof err, b ? "no hay claves para verificar" : "no se pudo leer");+ if (!ok) lerr_set(err, sizeof err, b ? "pkg.release.noKeys" : "pkg.release.unreadable", NULL);else {int g = pgp_verify_clearsigned(&kr, (char *)b, blen, now, &body, &bodylen, err, sizeof err);pgp_keyring_free(&kr);ok = g > 0;}free(b);- if (ok && parse_release(body, bodylen, &R[i])) { ok = 0; snprintf(err, sizeof err, "Release mal formado"); }- if (ok && R[i].valid_until && R[i].valid_until < now) { ok = 0; snprintf(err, sizeof err, "la lista venció (Valid-Until)"); }- if (ok && R[i].date > now + 86400) { ok = 0; snprintf(err, sizeof err, "la lista tiene fecha futura (¿hora del sistema?)"); }- if (ok && strcmp(R[i].suite, src[i].suite) && strcmp(R[i].codename, src[i].suite)) { ok = 0; snprintf(err, sizeof err, "la lista es de %s, no de %s", R[i].codename, src[i].suite); }+ if (ok && parse_release(body, bodylen, &R[i])) { ok = 0; lerr_set(err, sizeof err, "pkg.release.malformed", NULL); }+ if (ok && R[i].valid_until && R[i].valid_until < now) { ok = 0; lerr_set(err, sizeof err, "pkg.release.expired", NULL); }+ if (ok && R[i].date > now + 86400) { ok = 0; lerr_set(err, sizeof err, "pkg.release.future", NULL); }+ if (ok && strcmp(R[i].suite, src[i].suite) && strcmp(R[i].codename, src[i].suite)) { ok = 0; lerr_set(err, sizeof err, "pkg.release.wrongSuite", "got", R[i].codename, "want", src[i].suite, NULL); }free(body);if (ok && rel[i].status == 200) {/* don't accept a list older than the one we already had (replay attack) */@@ -525,20 +525,20 @@ void pkg_act_update(const AdminReq *r, const char *arg, size_t len) {uint8_t *old = read_file(final[i], &ol, 64u << 20);if (old) {const char *d = strstr((char *)old, "\nDate: ");- if (d && http_parse_date(d + 7) > R[i].date) { ok = 0; snprintf(err, sizeof err, "la lista nueva es más vieja que la guardada"); }+ if (d && http_parse_date(d + 7) > R[i].date) { ok = 0; lerr_set(err, sizeof err, "pkg.release.older", NULL); }free(old);}if (ok) {- if (rename(rel[i].dest, final[i])) { ok = 0; snprintf(err, sizeof err, "no se pudo guardar"); }+ if (rename(rel[i].dest, final[i])) { ok = 0; lerr_set(err, sizeof err, "pkg.release.saveFailed", NULL); }else if (rel[i].last_modified) {struct timespec ts[2] = { { (time_t)rel[i].last_modified, 0 }, { (time_t)rel[i].last_modified, 0 } };utimensat(AT_FDCWD, final[i], ts, 0);}}}- if (!ok) { admin_say("LOG", "%s %s: %s", src[i].uri, src[i].suite, err); unlink(rel[i].dest); failures++; continue; }+ if (!ok) { admin_log("pkg.sourceFailed", "uri", src[i].uri, "suite", src[i].suite, "reason", err, NULL); unlink(rel[i].dest); failures++; continue; }good[i] = 1;- admin_say("LOG", "%s %s: firma verificada (%s)", src[i].uri, src[i].suite, R[i].label[0] ? R[i].label : R[i].origin);+ admin_log("pkg.sourceVerified", "uri", src[i].uri, "suite", src[i].suite, "label", R[i].label[0] ? R[i].label : R[i].origin, NULL);/* which files to download */for (int c = 0; c < src[i].ncomp; c++) {char base[200];@@ -550,7 +550,7 @@ void pkg_act_update(const AdminReq *r, const char *arg, size_t len) {else snprintf(base, sizeof base, "%s/dep11/icons-64x64.tar", src[i].comps[c]);const RelFile *f = rel_pick(&R[i], base, &ext);if (k == 2 && f && !strcmp(ext, "")) f = NULL; /* the uncompressed YAML is huge */- if (!f) { if (k == 0) admin_say("LOG", "%s %s: no hay %s", src[i].uri, src[i].suite, base); continue; }+ if (!f) { if (k == 0) admin_log("pkg.sourceMissingFile", "uri", src[i].uri, "suite", src[i].suite, "file", base, NULL); continue; }Wanted *nwp = realloc(w, sizeof *w * (size_t)(nw + 2));if (!nwp) continue;w = nwp;@@ -593,12 +593,12 @@ void pkg_act_update(const AdminReq *r, const char *arg, size_t len) {free(R); free(good); free(w); free(src); free(final);utimensat(AT_FDCWD, PKG_DIR "/index.bin", NULL, 0); /* "last update": now */close(lk);- admin_say("OK", "la lista ya estaba al día (%u paquetes)", n);+ admin_ok("pkg.upToDate", "count", lerr_int(n), NULL);return;}int ngood = 0;for (int i = 0; good && i < ns; i++) ngood += good[i];- if (!ngood) { admin_say("ERR", "no se pudo verificar ninguna fuente"); return; }+ if (!ngood) { admin_err("pkg.noVerifiedSource", NULL); return; }/* 2. missing indexes (by their SHA-256: what's already there isn't downloaded again) */FetchItem *fi = calloc((size_t)(nw ? nw : 1), sizeof *fi);@@ -636,13 +636,13 @@ void pkg_act_update(const AdminReq *r, const char *arg, size_t len) {uint8_t (*expect)[32] = calloc((size_t)(nf ? nf : 1), 32);for (int k = 0; expect && k < nf; k++) memcpy(expect[k], fi[k].sha256, 32);if (nf) {- admin_say("LOG", "bajando %d archivos de índice (%llu KB)", nf, (unsigned long long)(total / 1024));+ admin_log("pkg.downloadingIndex", "count", lerr_int(nf), "kb", lerr_int((long long)(total / 1024)), NULL);fetch_batch(fi, nf, fetch_progress, "download");}for (int k = 0; fi && expect && k < nf; k++) {if (fi[k].status != 200 || fi[k].size != fi[k].expect || memcmp(fi[k].sha256, expect[k], 32)) {- if (fi[k].status == 200) snprintf(fi[k].err, sizeof fi[k].err, "el SHA-256 no coincide con el InRelease firmado");- admin_say("LOG", "%s: %s", fi[k].url, fi[k].err);+ if (fi[k].status == 200) lerr_set(fi[k].err, sizeof fi[k].err, "pkg.hashMismatchRelease", NULL);+ admin_log("pkg.fileFailed", "url", fi[k].url, "reason", fi[k].err, NULL);unlink(fi[k].dest);}}@@ -652,7 +652,7 @@ void pkg_act_update(const AdminReq *r, const char *arg, size_t len) {/* 3. index: Packages, Translation, DEP-11, icons */IdxBuilder *b = idxb_new();int *srcid = calloc((size_t)ns, sizeof *srcid);- if (!b || !srcid) { admin_say("ERR", "sin memoria"); return; }+ if (!b || !srcid) { admin_err("sys.outOfMemory", NULL); return; }for (int i = 0; i < ns; i++) srcid[i] = -1;int pk_files = 0, pk_missing = 0;for (int pass = 0; pass < 4; pass++)@@ -677,7 +677,7 @@ void pkg_act_update(const AdminReq *r, const char *arg, size_t len) {size_t dl;uint8_t *d = load_index_file(x->path, x->ext, &dl);if (!d) {- if (pass == 0) { pk_missing++; admin_say("LOG", "falta %s (%s)", x->comp, src[x->src].suite); }+ if (pass == 0) { pk_missing++; admin_log("pkg.componentMissing", "component", x->comp, "suite", src[x->src].suite, NULL); }continue;}if (pass == 0) { idxb_packages(b, srcid[x->src], (char *)d, dl, arch); pk_files++; }@@ -695,10 +695,10 @@ void pkg_act_update(const AdminReq *r, const char *arg, size_t len) {for (int i = 0; i < ns; i++) { free(R[i].files); free(src[i].inline_key); }free(R); free(good); free(w); free(src); free(final); free(srcid);close(lk);- if (!wrote) { admin_say("ERR", "no se pudo armar el índice: %s", pk_files ? err : "no se bajó ningún Packages"); return; }+ if (!wrote) { admin_err("pkg.indexFailed", "reason", pk_files ? err : "pkg.noPackagesFile", NULL); return; }admin_event("pkg index");- if (failures || pk_missing) admin_say("OK", "%u paquetes de %d fuentes (%d con problemas: ver el registro)", count, ngood, failures + pk_missing);- else admin_say("OK", "%u paquetes de %d fuentes", count, ngood);+ if (failures || pk_missing) admin_ok("pkg.updatedWithProblems", "count", lerr_int(count), "sources", lerr_int(ngood), "problems", lerr_int(failures + pk_missing), NULL);+ else admin_ok("pkg.updated", "count", lerr_int(count), "sources", lerr_int(ngood), NULL);}/* ---- dpkg ---- */@@ -758,7 +758,7 @@ static void dpkg_pending(void) {while (d && (e = readdir(d))) if (e->d_name[0] != '.') pending = 1;if (d) closedir(d);if (!pending) return;- admin_say("LOG", "dpkg quedó a medio terminar: dpkg --configure -a");+ admin_log("pkg.dpkgInterrupted", NULL);const char *const argv[] = { "/usr/bin/dpkg", "--force-confdef", "--force-confold", "--configure", "-a", NULL };run_dpkg(argv, NULL);}@@ -803,7 +803,7 @@ static int parse_names(const char *arg, size_t len, char names[][129], int max,else if (!strcmp(tok, "--purge")) *flags |= 8;else if (!strcmp(tok, "--keep-orphans")) *flags |= 16;else if (deb_valid_name(tok, strlen(tok)) && *nn < max) snprintf(names[(*nn)++], 129, "%s", tok);- else { admin_say("ERR", "nombre de paquete inválido: %.60s", tok); return -1; }+ else { { char nm[64]; snprintf(nm, sizeof nm, "%.60s", tok); admin_err("pkg.invalidName", "name", nm, NULL); } return -1; }}return 0;}@@ -812,9 +812,9 @@ static void say_plan(const Plan *p, const Idx *x) {for (int i = 0; i < p->n; i++) {const PlanItem *it = &p->items[i];const char *a = it->action == PA_INSTALL ? "install" : it->action == PA_UPGRADE ? "upgrade" : "remove";- admin_say("LOG", "plan %s %s %s %u", a, it->name, it->version ? it->version : "", it->rec >= 0 ? x->pkg[it->rec].size : 0);+ admin_say("LOG", "plan %s %s %s %u", a, it->name, it->version ? it->version : "", it->rec >= 0 ? x->pkg[it->rec].size : 0); /* i18n-ok: protocol line parsed by apps/store */}- for (int i = 0; i < p->nheld; i++) admin_say("LOG", "plan held %s", p->held[i]);+ for (int i = 0; i < p->nheld; i++) admin_say("LOG", "plan held %s", p->held[i]); /* i18n-ok: protocol line parsed by apps/store */}static void deb_cache_name(const Idx *x, long rec, char *out, size_t n) {@@ -851,14 +851,14 @@ static int file_sha_ok(const char *path, const uint8_t *sha, uint64_t size) {static int apply_plan(const Idx *x, const Plan *p, int purge, const char *extra_deb) {int ninst = 0, nrem = 0;for (int i = 0; i < p->n; i++) { if (p->items[i].rec >= 0) ninst++; else if (p->items[i].action == PA_REMOVE) nrem++; }- if (!ninst && !nrem && !extra_deb) { admin_say("OK", "nada para hacer: ya está todo instalado"); return 0; }- if (mkdirs(PKG_CACHE, 0755)) { admin_say("ERR", "no se pudo crear %s", PKG_CACHE); return -1; }+ if (!ninst && !nrem && !extra_deb) { admin_ok("pkg.nothingToDo", NULL); return 0; }+ if (mkdirs(PKG_CACHE, 0755)) { admin_err("pkg.prepareFailed", "path", PKG_CACHE, NULL); return -1; }/* download */char (*files)[PATH_MAX] = calloc((size_t)(p->n ? p->n : 1), PATH_MAX);FetchItem *fi = calloc((size_t)(ninst ? ninst : 1), sizeof *fi);int *fitem = calloc((size_t)(ninst ? ninst : 1), sizeof *fitem);- if (!files || !fi || !fitem) { admin_say("ERR", "sin memoria"); return -1; }+ if (!files || !fi || !fitem) { admin_err("sys.outOfMemory", NULL); return -1; }int nf = 0;uint64_t total = 0;for (int i = 0; i < p->n; i++) {@@ -876,13 +876,13 @@ static int apply_plan(const Idx *x, const Plan *p, int purge, const char *extra_total += k->size;}if (nf) {- admin_say("LOG", "bajando %d paquetes (%llu KB)", nf, (unsigned long long)(total / 1024));+ admin_log("pkg.downloadingPackages", "count", lerr_int(nf), "kb", lerr_int((long long)(total / 1024)), NULL);progress("download", 0, total);fetch_batch(fi, nf, fetch_progress, "download");for (int k = 0; k < nf; k++) {const IdxPkg *pk = &x->pkg[p->items[fitem[k]].rec];if (fi[k].status != 200 || fi[k].size != pk->size || memcmp(fi[k].sha256, pk->sha256, 32)) {- admin_say("ERR", "%s: %s", idx_s(x, pk->name), fi[k].status == 200 ? "el SHA-256 no coincide con el índice firmado" : fi[k].err);+ admin_err("pkg.downloadFailed", "name", idx_s(x, pk->name), "reason", fi[k].status == 200 ? "pkg.hashMismatchIndex" : fi[k].err, NULL);unlink(fi[k].dest);free(files); free(fi); free(fitem);return -1;@@ -893,7 +893,7 @@ static int apply_plan(const Idx *x, const Plan *p, int purge, const char *extra_free(fitem);int lk = lock_dpkg();- if (lk < 0) { admin_say("ERR", lk == -2 ? "dpkg está ocupado (¿apt u otro instalador corriendo?)" : "no se pudo tomar el lock de dpkg"); free(files); return -1; }+ if (lk < 0) { admin_err(lk == -2 ? "pkg.dpkgBusy" : "pkg.dpkgLockFailed", NULL); free(files); return -1; }dpkg_pending();DpkgProgress pr = { 0, 0, 0, ninst + (extra_deb ? 1 : 0) };int rc = 0;@@ -907,7 +907,7 @@ static int apply_plan(const Idx *x, const Plan *p, int purge, const char *extra_DpkgProgress rp = { 0, 0, 0, nrem };rc = run_dpkg(argv, &rp);free(argv);- if (rc) admin_say("LOG", "dpkg --remove terminó con código %d", rc);+ if (rc) admin_log("pkg.dpkgRemoveExit", "code", lerr_int(rc), NULL);}if (!rc && (ninst || extra_deb)) {int *order = calloc((size_t)(p->n ? p->n : 1), sizeof *order), *group = calloc((size_t)(p->n ? p->n : 1), sizeof *group);@@ -937,7 +937,7 @@ static int apply_plan(const Idx *x, const Plan *p, int purge, const char *extra_}close(lk);if (rc) {- admin_say("ERR", "dpkg terminó con código %d (ver el registro)", rc);+ admin_err("pkg.dpkgFailed", "code", lerr_int(rc), NULL);free(files);return -1;}@@ -952,14 +952,14 @@ static int apply_plan(const Idx *x, const Plan *p, int purge, const char *extra_}admin_event("pkg changed");if (extra_deb) ni++;- admin_say("OK", "%d instalado(s), %d actualizado(s), %d quitado(s)", ni, nu, nr);+ admin_ok("pkg.done", "installed", lerr_int(ni), "upgraded", lerr_int(nu), "removed", lerr_int(nr), NULL);return 0;}static int open_db(Idx *x, Status *st, int need_index) {memset(st, 0, sizeof *st);- if (idx_open(x, PKG_DIR) && need_index) { admin_say("ERR", "no hay lista de paquetes: primero hay que actualizarla"); return -1; }- if (status_load(st, DPKG_STATUS, pkg_native_arch())) { admin_say("ERR", "no se pudo leer la base de dpkg"); idx_close(x); return -1; }+ if (idx_open(x, PKG_DIR) && need_index) { admin_err("pkg.noIndex", NULL); return -1; }+ if (status_load(st, DPKG_STATUS, pkg_native_arch())) { admin_err("pkg.dpkgStatusUnreadable", NULL); idx_close(x); return -1; }return 0;}@@ -986,8 +986,8 @@ static void auto_free(AutoList *a) { free(a->buf); free(a->v); }static void run_plan_action(const char *const *ins, int ni, const char *const *rem, int nr, const PlanOpts *o, int purge) {int lk = lock_pkg();- if (lk == -2) { admin_say("ERR", "otra operación de paquetes está en curso"); return; }- if (lk < 0) { admin_say("ERR", "no se pudo preparar %s", PKG_DIR); return; }+ if (lk == -2) { admin_err("pkg.busy", NULL); return; }+ if (lk < 0) { admin_err("pkg.prepareFailed", "path", PKG_DIR, NULL); return; }Idx x;Status st;if (open_db(&x, &st, ni > 0 || o->upgrade_all)) { close(lk); return; }@@ -1000,10 +1000,10 @@ static void run_plan_action(const char *const *ins, int ni, const char *const *rplan_make(&x, &st, ins, ni, rem, nr, &po, &p);auto_free(&al);say_plan(&p, &x);- if (!p.ok) admin_say("ERR", "%s", p.err);- else if (!p.n && o->orphans && !ni && !nr) admin_say("OK", "no hay nada para quitar");+ if (!p.ok) admin_say("ERR", "%s", p.err); /* i18n-ok: already a code line */+ else if (!p.n && o->orphans && !ni && !nr) admin_ok("pkg.nothingToRemove", NULL);else {- admin_say("LOG", "plan total %llu %lld", (unsigned long long)p.download, (long long)p.isize_delta);+ admin_say("LOG", "plan total %llu %lld", (unsigned long long)p.download, (long long)p.isize_delta); /* i18n-ok: protocol line parsed by apps/store */apply_plan(&x, &p, purge, NULL);}plan_free(&p);@@ -1017,7 +1017,7 @@ void pkg_act_install(const AdminReq *r, const char *arg, size_t len) {char names[64][129];int n, flags;if (parse_names(arg, len, names, 64, &n, &flags)) return;- if (!n) { admin_say("ERR", "falta el nombre del paquete"); return; }+ if (!n) { admin_err("pkg.missingName", NULL); return; }const char *ins[64];for (int i = 0; i < n; i++) ins[i] = names[i];PlanOpts o = { .recommends = flags & 1, .allow_remove = (flags & 2) != 0 };@@ -1029,7 +1029,7 @@ void pkg_act_remove(const AdminReq *r, const char *arg, size_t len) {char names[64][129];int n, flags;if (parse_names(arg, len, names, 64, &n, &flags)) return;- if (!n) { admin_say("ERR", "falta el nombre del paquete"); return; }+ if (!n) { admin_err("pkg.missingName", NULL); return; }const char *rem[64];for (int i = 0; i < n; i++) rem[i] = names[i];PlanOpts o = { .cascade = (flags & 4) != 0, .allow_remove = (flags & 6) != 0, .orphans = !(flags & 16) };@@ -1039,7 +1039,7 @@ void pkg_act_remove(const AdminReq *r, const char *arg, size_t len) {/* Removes what was installed as a dependency that nobody uses anymore (apt autoremove). */void pkg_act_autoremove(const AdminReq *r, const char *arg, size_t len) {(void)r;- if (len) { admin_say("ERR", "pkg-autoremove no lleva argumentos"); (void)arg; return; }+ if (len) { admin_err("admin.invalidArgument", NULL); (void)arg; return; }PlanOpts o = { .orphans = 1 };run_plan_action(NULL, 0, NULL, 0, &o, 0);}@@ -1096,19 +1096,19 @@ static int read_control(const uint8_t *deb, size_t len, DebControl *dc, char *erconst uint8_t *m;size_t ml;char name[32];- if (ar_member(deb, len, "debian-binary", &m, &ml, name, sizeof name) || ml < 3 || m[0] != '2') { snprintf(err, errlen, "no es un paquete .deb"); return -1; }- if (ar_member(deb, len, "control.tar", &m, &ml, name, sizeof name)) { snprintf(err, errlen, "el .deb no tiene control.tar"); return -1; }+ if (ar_member(deb, len, "debian-binary", &m, &ml, name, sizeof name) || ml < 3 || m[0] != '2') { lerr_set(err, errlen, "pkg.deb.notDeb", NULL); return -1; }+ if (ar_member(deb, len, "control.tar", &m, &ml, name, sizeof name)) { lerr_set(err, errlen, "pkg.deb.noControlTar", NULL); return -1; }uint8_t *tar = NULL;size_t tl = 0;if (!strcmp(name, "control.tar.xz")) { if (xz_decode(m, ml, &tar, &tl, 64u << 20)) tar = NULL; }else if (!strcmp(name, "control.tar.gz")) { if (gz_decode(m, ml, &tar, &tl, 64u << 20)) tar = NULL; }else if (!strcmp(name, "control.tar")) { tar = malloc(ml); if (tar) { memcpy(tar, m, ml); tl = ml; } }- else { snprintf(err, errlen, "%s no está soportado (se usa xz o gzip)", name); return -1; }- if (!tar) { snprintf(err, errlen, "control.tar dañado"); return -1; }+ else { lerr_set(err, errlen, "pkg.deb.compression", "name", name, NULL); return -1; }+ if (!tar) { lerr_set(err, errlen, "pkg.deb.controlDamaged", NULL); return -1; }CtlCtx c = { NULL, 0 };tar_walk(tar, tl, control_entry, &c);free(tar);- if (!c.control) { snprintf(err, errlen, "el .deb no tiene control"); return -1; }+ if (!c.control) { lerr_set(err, errlen, "pkg.deb.noControl", NULL); return -1; }D822 it = { c.control, c.control + c.len };D822Field f;while (d822_next_field(&it, &f)) {@@ -1123,7 +1123,7 @@ static int read_control(const uint8_t *deb, size_t len, DebControl *dc, char *erif (dst && !*dst && (*dst = malloc(f.vlen + 1))) { memcpy(*dst, f.value, f.vlen); (*dst)[f.vlen] = 0; }}free(c.control);- if (!deb_valid_name(dc->name, strlen(dc->name)) || !deb_valid_version(dc->version, strlen(dc->version))) { snprintf(err, errlen, "control inválido"); return -1; }+ if (!deb_valid_name(dc->name, strlen(dc->name)) || !deb_valid_version(dc->version, strlen(dc->version))) { lerr_set(err, errlen, "pkg.deb.badControl", NULL); return -1; }return 0;}@@ -1133,10 +1133,10 @@ static void control_free(DebControl *dc) { free(dc->depends); free(dc->predepend* new root-owned file. That way there's no race: what gets verified and installed is the copy. */static int copy_user_file(const AdminReq *r, const char *path, const char *dest, char *err, size_t errlen) {char home[PATH_MAX];- if (!realpath(r->home, home)) { snprintf(err, errlen, "carpeta personal inválida"); return -1; }+ if (!realpath(r->home, home)) { lerr_set(err, errlen, "pkg.file.badHome", NULL); return -1; }size_t hl = strlen(home);if (strncmp(path, home, hl) || path[hl] != '/' || strstr(path, "/../") || strstr(path, "/./") || strlen(path) > 1000) {- snprintf(err, errlen, "el archivo tiene que estar en la carpeta personal");+ lerr_set(err, errlen, "pkg.file.outsideHome", NULL);return -1;}setfsgid(r->gid);@@ -1160,12 +1160,12 @@ static int copy_user_file(const AdminReq *r, const char *path, const char *dest,struct stat st;if (fd < 0 || fstat(fd, &st) || !S_ISREG(st.st_mode) || st.st_size > (off_t)(2048u << 20)) {if (fd >= 0) close(fd);- snprintf(err, errlen, "no se pudo abrir el archivo (¿enlace, permisos o no es un archivo?)");+ lerr_set(err, errlen, "pkg.file.openFailed", NULL);return -1;}unlink(dest);int out = open(dest, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC | O_NOFOLLOW, 0644);- if (out < 0) { close(fd); snprintf(err, errlen, "no se pudo copiar"); return -1; }+ if (out < 0) { close(fd); lerr_set(err, errlen, "pkg.file.copyFailed", NULL); return -1; }uint8_t buf[65536];ssize_t n;int ok = 1;@@ -1175,44 +1175,44 @@ static int copy_user_file(const AdminReq *r, const char *path, const char *dest,}close(fd);if (close(out)) ok = 0;- if (!ok) { unlink(dest); snprintf(err, errlen, "no se pudo copiar"); return -1; }+ if (!ok) { unlink(dest); lerr_set(err, errlen, "pkg.file.copyFailed", NULL); return -1; }return 0;}void pkg_act_install_file(const AdminReq *r, const char *arg, size_t len) {char buf[1100];- if (len >= sizeof buf) { admin_say("ERR", "ruta demasiado larga"); return; }+ if (len >= sizeof buf) { admin_err("pkg.file.pathTooLong", NULL); return; }memcpy(buf, arg, len);buf[len] = 0;int allow_remove = 0;char *flag = strstr(buf, " --allow-remove");if (flag && !flag[15]) { *flag = 0; allow_remove = 1; }size_t pl = strlen(buf);- if (buf[0] != '/' || pl < 5 || strcmp(buf + pl - 4, ".deb") || strchr(buf, '\n')) { admin_say("ERR", "hace falta la ruta completa de un archivo .deb"); return; }+ if (buf[0] != '/' || pl < 5 || strcmp(buf + pl - 4, ".deb") || strchr(buf, '\n')) { admin_err("pkg.file.needDebPath", NULL); return; }int lk = lock_pkg();- if (lk == -2) { admin_say("ERR", "otra operación de paquetes está en curso"); return; }- if (lk < 0 || mkdirs(PKG_CACHE, 0755)) { admin_say("ERR", "no se pudo preparar %s", PKG_CACHE); return; }+ if (lk == -2) { admin_err("pkg.busy", NULL); return; }+ if (lk < 0 || mkdirs(PKG_CACHE, 0755)) { admin_err("pkg.prepareFailed", "path", PKG_CACHE, NULL); return; }char dest[PATH_MAX], err[256];snprintf(dest, sizeof dest, PKG_CACHE "/local-%d.deb", (int)getpid());- if (copy_user_file(r, buf, dest, err, sizeof err)) { admin_say("ERR", "%s", err); close(lk); return; }+ if (copy_user_file(r, buf, dest, err, sizeof err)) { admin_say("ERR", "%s", err); close(lk); return; } /* i18n-ok: already a code line */size_t dl;uint8_t *deb = read_file(dest, &dl, 2048u << 20);DebControl dc;if (!deb || read_control(deb, dl, &dc, err, sizeof err)) {free(deb);unlink(dest);- admin_say("ERR", "%s", deb ? err : "no se pudo leer");+ admin_say("ERR", "%s", deb ? err : "pkg.file.unreadable"); /* i18n-ok: already a code line */close(lk);return;}free(deb);const char *arch = pkg_native_arch();if (strcmp(dc.arch, arch) && strcmp(dc.arch, "all")) {- admin_say("ERR", "%s es para %s y este sistema es %s", dc.name, dc.arch, arch);+ admin_err("pkg.deb.wrongArch", "name", dc.name, "arch", dc.arch, "system", arch, NULL);control_free(&dc); unlink(dest); close(lk);return;}- admin_say("LOG", "paquete local: %s %s (%s)", dc.name, dc.version, dc.arch);+ admin_log("pkg.localPackage", "name", dc.name, "version", dc.version, "arch", dc.arch, NULL);Idx x;Status st;if (open_db(&x, &st, 0)) { control_free(&dc); unlink(dest); close(lk); return; }@@ -1251,18 +1251,18 @@ void pkg_act_install_file(const AdminReq *r, const char *arg, size_t len) {ok = 1;}}- if (!ok) { missing++; admin_say("LOG", "dependencia sin resolver: %.*s", (int)a[0].nlen, a[0].name); }+ if (!ok) { missing++; { char dn[130]; snprintf(dn, sizeof dn, "%.*s", (int)a[0].nlen, a[0].name); admin_log("pkg.unresolvedDep", "name", dn, NULL); } }}}if (missing) {- admin_say("ERR", "%s necesita paquetes que no están en las fuentes", dc.name);+ admin_err("pkg.deb.missingDeps", "name", dc.name, NULL);} else {PlanOpts o = { .allow_remove = allow_remove };Plan p;plan_make(&x, &st, ins, ni, NULL, 0, &o, &p);say_plan(&p, &x);- admin_say("LOG", "plan install %s %s %llu", dc.name, dc.version, (unsigned long long)dl);- if (!p.ok) admin_say("ERR", "%s", p.err);+ admin_say("LOG", "plan install %s %s %llu", dc.name, dc.version, (unsigned long long)dl); /* i18n-ok: protocol line parsed by apps/store */+ if (!p.ok) admin_say("ERR", "%s", p.err); /* i18n-ok: already a code line */else apply_plan(&x, &p, 0, dest);plan_free(&p);}diff --git a/server/src/pkg/resolve.c b/server/src/pkg/resolve.cindex 7c8d7db..93564ed 100644--- a/server/src/pkg/resolve.c+++ b/server/src/pkg/resolve.c@@ -11,6 +11,7 @@* that changed and whatever depends on it is reviewed until nothing else changes. */#include "resolve.h"#include "deb.h"+#include "../errcode.h"#include <stdio.h>#include <stdlib.h>@@ -331,7 +332,7 @@ static int removable(const Node *n) {static int apply_remove(S *s, int ni, const char *why) {Node *n = nd(s, ni);- if (!removable(n)) { snprintf(s->err, sizeof s->err, "%s es esencial para el sistema y no se puede quitar", n->name); return 0; }+ if (!removable(n)) { lerr_set(s->err, sizeof s->err, "pkg.removeEssential", "name", n->name, NULL); return 0; }if (mark(s, ni)) return 0;n->target = T_NONE;n->touched = 1;@@ -389,23 +390,23 @@ static int fix_clash(S *s, int ni, int ti) {char why[200];if (t->target == T_KEEP) {if (t->cand >= 0 && ver_cmp(idx_s(s->x, s->x->pkg[t->cand].version), t->inst->version) > 0 && !clash(s, ti, t->cand, ni)) {- snprintf(why, sizeof why, "se actualiza para %s", n->name);+ lerr_set(why, sizeof why, "pkg.why.upgradedFor", "name", n->name, NULL);return apply_install(s, ti, t->cand, why);}if (s->may_remove && removable(t) && !t->requested) {- snprintf(why, sizeof why, "choca con %s", n->name);+ lerr_set(why, sizeof why, "pkg.why.conflictsWith", "name", n->name, NULL);return apply_remove(s, ti, why);}- snprintf(s->err, sizeof s->err, "%s choca con %s, que está instalado", n->name, t->name);+ lerr_set(s->err, sizeof s->err, "pkg.conflictInstalled", "name", n->name, "other", t->name, NULL);return 0;}- snprintf(s->err, sizeof s->err, "%s y %s no se pueden instalar juntos", n->name, t->name);+ lerr_set(s->err, sizeof s->err, "pkg.conflict", "name", n->name, "other", t->name, NULL);return 0;}static int apply_install(S *s, int ni, long rec, const char *why) {Node *n = nd(s, ni);- if (n->remove_req) { snprintf(s->err, sizeof s->err, "%s hace falta, pero se pidió quitarlo", n->name); return 0; }+ if (n->remove_req) { lerr_set(s->err, sizeof s->err, "pkg.neededButRemoved", "name", n->name, NULL); return 0; }if (mark(s, ni)) return 0;n->target = rec;n->touched = 1;@@ -503,7 +504,9 @@ static int group_len(const char *g, const char *ge) {}static void describe_missing(S *s, const Node *owner, const char *g, const char *ge) {- snprintf(s->err, sizeof s->err, "%s depende de %.*s, que no se puede instalar", owner->name, group_len(g, ge), g);+ char dep[128];+ snprintf(dep, sizeof dep, "%.*s", group_len(g, ge), g);+ lerr_set(s->err, sizeof s->err, "pkg.dependencyUninstallable", "name", owner->name, "dep", dep, NULL);}static int solve(S *s, int qpos) {@@ -523,11 +526,11 @@ static int solve(S *s, int qpos) {opt[no++] = (Opt){ it.node, owner->cand };no += gather(s, alts, na, opt + no, MAX_ALTS);char why[200];- snprintf(why, sizeof why, "dependencia de %s", owner->name);+ lerr_set(why, sizeof why, "pkg.why.dependencyOf", "name", owner->name, NULL);/* if nothing works and it's something installed, it's removed too (with confirmation) */int can_drop = owner->target == T_KEEP && s->may_remove && !owner->requested && removable(owner);char w2[200];- snprintf(w2, sizeof w2, "dependía de %.*s", group_len(it.g, it.ge), it.g);+ { char dep[128]; snprintf(dep, sizeof dep, "%.*s", group_len(it.g, it.ge), it.g); lerr_set(w2, sizeof w2, "pkg.why.lostDependency", "dep", dep, NULL); }if (!no) {if (it.optional) continue;if (can_drop) { if (!apply_remove(s, it.node, w2)) return 0; continue; }@@ -538,7 +541,7 @@ static int solve(S *s, int qpos) {* way out, the option is tried with the rest of the queue and if it fails the owner is removed. */if (no == 1 && !can_drop) {int lm = s->nlog, qm = s->nq;- if (!apply_install(s, opt[0].node, opt[0].rec, opt[0].node == it.node ? "actualización" : why)) {+ if (!apply_install(s, opt[0].node, opt[0].rec, opt[0].node == it.node ? "pkg.why.upgrade" : why)) {undo_to(s, lm);s->nq = qm;if (it.optional) continue;@@ -547,9 +550,9 @@ static int solve(S *s, int qpos) {continue;}for (int k = 0; k < no; k++) {- if (--s->budget <= 0) { snprintf(s->err, sizeof s->err, "demasiadas combinaciones posibles; pedí los paquetes de a uno"); return 0; }+ if (--s->budget <= 0) { lerr_set(s->err, sizeof s->err, "pkg.tooManyCombinations", NULL); return 0; }int lm = s->nlog, qm = s->nq;- if (apply_install(s, opt[k].node, opt[k].rec, opt[k].node == it.node ? "actualización" : why) && solve(s, qpos)) return 1;+ if (apply_install(s, opt[k].node, opt[k].rec, opt[k].node == it.node ? "pkg.why.upgrade" : why) && solve(s, qpos)) return 1;undo_to(s, lm);s->nq = qm;}@@ -669,17 +672,17 @@ int plan_make(const Idx *x, const Status *st, const char *const *install, int nis.budget = BUDGET;s.may_remove = 1; /* the extra removals are computed and then confirmed */int ok = !build_tables(&s);- if (!ok) snprintf(s.err, sizeof s.err, "sin memoria");- if (!x->map && (ni || o->upgrade_all)) { ok = 0; snprintf(s.err, sizeof s.err, "no hay índice de paquetes: falta actualizar la lista"); }+ if (!ok) lerr_set(s.err, sizeof s.err, "sys.outOfMemory", NULL);+ if (!x->map && (ni || o->upgrade_all)) { ok = 0; lerr_set(s.err, sizeof s.err, "pkg.noIndex", NULL); }for (int i = 0; ok && i < nr; i++) {int k = node_get(&s, remove[i], strlen(remove[i]));if (k < 0) { ok = 0; break; }Node *n = nd(&s, k);- if (!n->inst) { ok = 0; snprintf(s.err, sizeof s.err, "%s no está instalado", remove[i]); break; }+ if (!n->inst) { ok = 0; lerr_set(s.err, sizeof s.err, "pkg.notInstalled", "name", remove[i], NULL); break; }n->remove_req = 1;n->requested = 1;- ok = apply_remove(&s, k, "pedido");+ ok = apply_remove(&s, k, "pkg.why.requested");}for (int i = 0; ok && i < ni; i++) {int k = node_get(&s, install[i], strlen(install[i]));@@ -692,14 +695,16 @@ int plan_make(const Idx *x, const Status *st, const char *const *install, int niint no = gather(&s, &r, 1, opt, MAX_ALTS);if (no == 1) { k = opt[0].node; n = nd(&s, k); }else if (no > 1) {- int l = snprintf(s.err, sizeof s.err, "%s es virtual; hay que elegir uno:", install[i]);- for (int j = 0; j < no && l < (int)sizeof s.err - 40; j++) l += snprintf(s.err + l, sizeof s.err - (size_t)l, " %s", nd(&s, opt[j].node)->name);+ char names[300] = "";+ for (int j = 0; j < no && strlen(names) < sizeof names - 70; j++)+ snprintf(names + strlen(names), sizeof names - strlen(names), "%s%s", j ? ", " : "", nd(&s, opt[j].node)->name);+ lerr_set(s.err, sizeof s.err, "pkg.virtual", "name", install[i], "options", names, NULL);ok = 0;break;- } else { ok = 0; snprintf(s.err, sizeof s.err, "no hay ningún paquete llamado %s", install[i]); break; }+ } else { ok = 0; lerr_set(s.err, sizeof s.err, "pkg.notFound", "name", install[i], NULL); break; }}n->requested = 1;- if (n->remove_req) { ok = 0; snprintf(s.err, sizeof s.err, "%s está para instalar y para quitar a la vez", n->name); break; }+ if (n->remove_req) { ok = 0; lerr_set(s.err, sizeof s.err, "pkg.installAndRemove", "name", n->name, NULL); break; }if (n->cand < 0 || (n->inst && !ver_cmp(idx_s(x, x->pkg[n->cand].version), n->inst->version))) continue; /* already there */ok = apply_install(&s, k, n->cand, NULL);}@@ -715,7 +720,7 @@ int plan_make(const Idx *x, const Status *st, const char *const *install, int niif (n->target != T_KEEP || n->cand < 0 || ver_cmp(idx_s(x, x->pkg[n->cand].version), p->version) <= 0) continue;int lm = s.nlog, qm = s.nq;s.budget = BUDGET;- if (apply_install(&s, k, n->cand, "actualización") && solve(&s, qm)) continue;+ if (apply_install(&s, k, n->cand, "pkg.why.upgrade") && solve(&s, qm)) continue;undo_to(&s, lm);s.nq = qm;if (out->nheld < 32) snprintf(out->held[out->nheld++], sizeof out->held[0], "%s", p->name);@@ -735,7 +740,7 @@ int plan_make(const Idx *x, const Status *st, const char *const *install, int niif (changed) count++;}out->items = calloc((size_t)(count ? count : 1), sizeof *out->items);- if (!out->items) { ok = 0; snprintf(s.err, sizeof s.err, "sin memoria"); }+ if (!out->items) { ok = 0; lerr_set(s.err, sizeof s.err, "sys.outOfMemory", NULL); }int extra_removals = 0;char extra[300] = "";for (int i = 0; out->items && i < s.nn; i++) {@@ -764,16 +769,16 @@ int plan_make(const Idx *x, const Status *st, const char *const *install, int niit.name = n->name;it.requested = n->requested;it.orphan = n->orphan;- snprintf(it.reason, sizeof it.reason, "%s", n->requested ? "pedido" : n->orphan ? "auto" : n->reason);+ snprintf(it.reason, sizeof it.reason, "%s", n->requested ? "pkg.why.requested" : n->orphan ? "pkg.why.auto" : n->reason);out->items[out->n++] = it;}if (out->items) qsort(out->items, (size_t)out->n, sizeof *out->items, item_cmp);if (ok && extra_removals && !o->allow_remove && !o->cascade) {ok = 0;- snprintf(s.err, sizeof s.err, "también hay que quitar: %s", extra);+ lerr_set(s.err, sizeof s.err, "pkg.removeAlso", "names", extra, NULL);}out->ok = ok;- snprintf(out->err, sizeof out->err, "%s", ok ? "" : s.err[0] ? s.err : "no se pudo resolver");+ snprintf(out->err, sizeof out->err, "%s", ok ? "" : s.err[0] ? s.err : "pkg.unresolvable");for (int i = 0; i < s.nblocks; i++) free(s.blocks[i]);free(s.blocks); free(s.ht); free(s.log); free(s.q); free(s.prov); free(s.rdep); free(s.conf);return ok ? 0 : -1;diff --git a/server/src/remote/client.html b/server/src/remote/client.htmlindex 24f45e2..a237364 100644--- a/server/src/remote/client.html+++ b/server/src/remote/client.html@@ -1,10 +1,10 @@<!doctype html>-<html lang="es" translate="no">+<html lang="en" translate="no"><head><meta charset="utf-8"><meta name="google" content="notranslate"><meta name="viewport" content="width=device-width, initial-scale=1">-<title>LordOS · Escritorio remoto</title>+<title>LordOS · Remote desktop</title><style>* { box-sizing: border-box; }html, body { margin: 0; height: 100%; background: #0b0a14; overflow: hidden; font: 13px system-ui, -apple-system, "Segoe UI", sans-serif; color: #eee; }@@ -33,11 +33,11 @@<script>'use strict';const L = {- es: { full: 'Pantalla completa', out: 'Desconectar', bye: 'La sesión terminó o se cortó la conexión.', again: 'Reconectar', conn: 'Conectando…' },en: { full: 'Full screen', out: 'Disconnect', bye: 'The session ended or the connection was lost.', again: 'Reconnect', conn: 'Connecting…' },+ es: { full: 'Pantalla completa', out: 'Desconectar', bye: 'La sesión terminó o se cortó la conexión.', again: 'Reconectar', conn: 'Conectando…' },pt: { full: 'Tela cheia', out: 'Desconectar', bye: 'A sessão terminou ou a conexão caiu.', again: 'Reconectar', conn: 'Conectando…' },};-const T = L[(navigator.language || 'es').slice(0, 2)] || L.en;+const T = L[(navigator.language || 'en').slice(0, 2)] || L.en;const $ = (id) => document.getElementById(id);const cv = $('c'), ctx = cv.getContext('2d', { alpha: false });$('fs').title = T.full; $('out').title = T.out; $('again').textContent = T.again;diff --git a/server/src/remote/conn.c b/server/src/remote/conn.cindex d532e60..f221b39 100644--- a/server/src/remote/conn.c+++ b/server/src/remote/conn.c@@ -790,7 +790,7 @@ void rd_serve(SSL_CTX *ctx, int fd, const char *ip) {}sd_log("connected to %s's session", name);bridge(&me);- sd_log("desconectado");+ sd_log("disconnected");return;}respond(404, "Not Found", "text/plain", NULL, "no", 2);diff --git a/server/src/remote/login.html b/server/src/remote/login.htmlindex bc3504e..e261238 100644--- a/server/src/remote/login.html+++ b/server/src/remote/login.html@@ -1,10 +1,10 @@<!doctype html>-<html lang="es" translate="no">+<html lang="en" translate="no"><head><meta charset="utf-8"><meta name="google" content="notranslate"><meta name="viewport" content="width=device-width, initial-scale=1">-<title>LordOS · Escritorio remoto</title>+<title>LordOS · Remote desktop</title><style>/* Same look as the monitor's login screen (themes/greeter). No list ofusers: from the network we don't reveal who has an account on the machine. */@@ -58,18 +58,18 @@<div class="br"><button type="button" class="pill" data-l="es">ES</button><button type="button" class="pill" data-l="en">EN</button><button type="button" class="pill" data-l="pt">PT</button></div><script>const L = {- es: { user: 'Usuario', pass: 'Contraseña', e1: 'Usuario o contraseña incorrectos.', e2: 'Demasiados intentos. Esperá un rato y probá de nuevo.',- e3: 'La sesión se bloqueó. Volvé a ingresar.',- foot: 'Escritorio remoto de LordOS · conexión cifrada. Si el navegador avisa del certificado, compará su huella con la de Ajustes → Compartir.',- days: ['domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado'],- months: ['enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre'],- date: (w, d, m) => `${w}, ${d} de ${m}`, h12: false },en: { user: 'Username', pass: 'Password', e1: 'Wrong username or password.', e2: 'Too many attempts. Wait a while and try again.',e3: 'The session was locked. Sign in again.',foot: 'LordOS remote desktop · encrypted connection. If your browser warns about the certificate, compare its fingerprint with Settings → Sharing.',days: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],date: (w, d, m) => `${w}, ${m} ${d}`, h12: true },+ es: { user: 'Usuario', pass: 'Contraseña', e1: 'Usuario o contraseña incorrectos.', e2: 'Demasiados intentos. Esperá un rato y probá de nuevo.',+ e3: 'La sesión se bloqueó. Volvé a ingresar.',+ foot: 'Escritorio remoto de LordOS · conexión cifrada. Si el navegador avisa del certificado, compará su huella con la de Ajustes → Compartir.',+ days: ['domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado'],+ months: ['enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre'],+ date: (w, d, m) => `${w}, ${d} de ${m}`, h12: false },pt: { user: 'Usuário', pass: 'Senha', e1: 'Usuário ou senha incorretos.', e2: 'Muitas tentativas. Espere um pouco e tente de novo.',e3: 'A sessão foi bloqueada. Entre de novo.',foot: 'Área de trabalho remota do LordOS · conexão criptografada. Se o navegador avisar do certificado, compare a impressão digital com Ajustes → Compartilhar.',@@ -78,7 +78,7 @@date: (w, d, m) => `${w}, ${d} de ${m}`, h12: false },};const $ = (id) => document.getElementById(id);- let lang = (() => { try { return localStorage.getItem('lordos-lang'); } catch (e) { return null; } })() || (navigator.language || 'es').slice(0, 2);+ let lang = (() => { try { return localStorage.getItem('lordos-lang'); } catch (e) { return null; } })() || (navigator.language || 'en').slice(0, 2);if (!L[lang]) lang = 'en';const PAL = [['#5b9cff', '#2f6fe0'], ['#f0915a', '#d0602b'], ['#4cc37a', '#269653'], ['#e0609d', '#b83574'], ['#a77bf3', '#7a4fd6'], ['#4cc4d3', '#2391a3'], ['#f2c14e', '#d0961d']];const hash = (s) => { let h = 0; for (const c of s) h = (h * 31 + c.codePointAt(0)) >>> 0; return h; };diff --git a/server/src/remote/remote_admin.c b/server/src/remote/remote_admin.cindex 922e72d..ec45565 100644--- a/server/src/remote/remote_admin.c+++ b/server/src/remote/remote_admin.c@@ -79,22 +79,22 @@ static pid_t sessiond_pid(void) {static void set_enabled(int on) {pid_t pid = sessiond_pid();- if (pid < 0) { admin_say("ERR", "el escritorio remoto necesita lord-sessiond (lordos.service)"); return; }+ if (pid < 0) { admin_err("remote.needSessiond", NULL); return; }Conf c;conf_read(&c);c.enabled = on;- if (conf_write(&c)) { admin_say("ERR", "no se pudo escribir %s/config", CONF_DIR); return; }+ if (conf_write(&c)) { admin_err("sys.writeFailed", "path", CONF_DIR "/config", NULL); return; }kill(pid, SIGHUP);- if (!on) { admin_say("OK", "escritorio remoto apagado"); return; }+ if (!on) { admin_ok("remote.off", NULL); return; }/* waits for it to listen (status.json says running) */for (int i = 0; i < 40; i++) {char st[512] = "";int fd = open("/run/lordos/status.json", O_RDONLY | O_NOFOLLOW | O_CLOEXEC);if (fd >= 0) { ssize_t n = read(fd, st, sizeof st - 1); if (n > 0) st[n] = 0; close(fd); }- if (strstr(st, "\"running\":true")) { admin_say("OK", "escritorio remoto prendido"); return; }+ if (strstr(st, "\"running\":true")) { admin_ok("remote.on", NULL); return; }usleep(100000);}- admin_say("ERR", "lord-sessiond no pudo escuchar en el puerto %d (journalctl -u lordos)", c.port);+ admin_err("remote.listenFailed", "port", lerr_int(c.port), NULL);}void remote_act_enable(const AdminReq *r, const char *arg, size_t len) {@@ -117,48 +117,48 @@ void remote_act_config(const AdminReq *r, const char *arg, size_t len) {int v;char s[16];if (sscanf(line, "port=%d", &v) == 1) {- if (v < 1024 || v > 65535) { admin_say("ERR", "puerto inválido"); return; }+ if (v < 1024 || v > 65535) { admin_err("remote.badPort", NULL); return; }c.port = v;} else if (sscanf(line, "allow=%15s", s) == 1) {- if (strcmp(s, "all") && strcmp(s, "group")) { admin_say("ERR", "allow inválido"); return; }+ if (strcmp(s, "all") && strcmp(s, "group")) { admin_err("admin.invalidArgument", NULL); return; }c.group_only = !strcmp(s, "group");- } else { admin_say("ERR", "opción desconocida"); return; }+ } else { admin_err("admin.invalidArgument", NULL); return; }}if (c.group_only && !getgrnam("lordos-remote")) {const char *const g[] = { "/usr/sbin/groupadd", "--system", "lordos-remote", NULL };- if (admin_run(g)) { admin_say("ERR", "no se pudo crear el grupo lordos-remote"); return; }+ if (admin_run(g)) { admin_err("remote.groupFailed", NULL); return; }}- if (conf_write(&c)) { admin_say("ERR", "no se pudo escribir la configuración"); return; }+ if (conf_write(&c)) { admin_err("remote.configFailed", NULL); return; }pid_t pid = sessiond_pid();if (pid > 0) kill(pid, SIGHUP);- admin_say("OK", "configuración guardada");+ admin_ok("remote.saved", NULL);}void remote_act_member(const AdminReq *r, const char *arg, size_t len) {(void)r; (void)len;char user[40] = "";int on = -1;- if (sscanf(arg, "%39[a-z0-9_-]\n%d", user, &on) != 2 || (on != 0 && on != 1)) { admin_say("ERR", "argumento inválido"); return; }+ if (sscanf(arg, "%39[a-z0-9_-]\n%d", user, &on) != 2 || (on != 0 && on != 1)) { admin_err("admin.invalidArgument", NULL); return; }struct passwd *pw = getpwnam(user);- if (!pw || pw->pw_uid < 1000 || pw->pw_uid >= 60000) { admin_say("ERR", "usuario inválido"); return; }+ if (!pw || pw->pw_uid < 1000 || pw->pw_uid >= 60000) { admin_err("users.invalid", NULL); return; }if (!getgrnam("lordos-remote")) {const char *const g[] = { "/usr/sbin/groupadd", "--system", "lordos-remote", NULL };- if (admin_run(g)) { admin_say("ERR", "no se pudo crear el grupo lordos-remote"); return; }+ if (admin_run(g)) { admin_err("remote.groupFailed", NULL); return; }}const char *const a[] = { "/usr/bin/gpasswd", on ? "-a" : "-d", user, "lordos-remote", NULL };- if (admin_run(a)) admin_say("ERR", "gpasswd falló"); else admin_say("OK", "%s", on ? "agregado" : "quitado");+ if (admin_run(a)) admin_err("sys.programError", "program", "gpasswd", NULL); else admin_ok(on ? "remote.userAdded" : "remote.userRemoved", "name", user, NULL);}void remote_act_kick(const AdminReq *r, const char *arg, size_t len) {(void)r; (void)len;char *end;long pid = strtol(arg, &end, 10);- if (pid <= 1 || *end) { admin_say("ERR", "pid inválido"); return; }+ if (pid <= 1 || *end) { admin_err("admin.invalidArgument", NULL); return; }/* only a connection that lord-sessiond (root) recorded in its list */char status[16384] = "", want[40];int fd = open("/run/lordos/status.json", O_RDONLY | O_NOFOLLOW | O_CLOEXEC);struct stat st;- if (fd < 0 || fstat(fd, &st) || st.st_uid != 0) { if (fd >= 0) close(fd); admin_say("ERR", "el servicio no está prendido"); return; }+ if (fd < 0 || fstat(fd, &st) || st.st_uid != 0) { if (fd >= 0) close(fd); admin_err("remote.notRunning", NULL); return; }ssize_t n = read(fd, status, sizeof status - 1);close(fd);if (n > 0) status[n] = 0;@@ -168,7 +168,7 @@ void remote_act_kick(const AdminReq *r, const char *arg, size_t len) {ssize_t l = readlink(link, exe, sizeof exe - 1);if (l > 0) exe[l] = 0;const char *base = l > 0 ? strrchr(exe, '/') : NULL;- if (!strstr(status, want) || !base || strcmp(base + 1, "lord-sessiond")) { admin_say("ERR", "esa conexión no existe"); return; }+ if (!strstr(status, want) || !base || strcmp(base + 1, "lord-sessiond")) { admin_err("remote.noSuchConnection", NULL); return; }kill((pid_t)pid, SIGTERM);- admin_say("OK", "conexión cortada");+ admin_ok("remote.disconnected", NULL);}diff --git a/server/src/remote/sess.c b/server/src/remote/sess.cindex ce5d0bf..30459e4 100644--- a/server/src/remote/sess.c+++ b/server/src/remote/sess.c@@ -301,7 +301,7 @@ int sd_session_get(const struct passwd *pw, int w, int h) {}if (stat(rt, &st) || st.st_uid != pw->pw_uid) sd_log("no %s", rt);else {- char lang[64] = "LANG=es_ES.UTF-8", p[600];+ char lang[64] = "LANG=en_US.UTF-8", p[600];read_lang("/etc/default/locale", lang, sizeof lang);snprintf(p, sizeof p, "%s/.config/locale.conf", pw->pw_dir);read_lang(p, lang, sizeof lang);@@ -330,7 +330,7 @@ int sd_greeter_get(int w, int h) {sd_log("could not prepare %s", SD_GREETER_RUN);return -1;}- char lang[64] = "LANG=es_ES.UTF-8";+ char lang[64] = "LANG=en_US.UTF-8";read_lang("/etc/default/locale", lang, sizeof lang);spawn(pw, SD_GREETER_RUN, lang, w, h, 1);fd = wait_socket(sock, 0, 1);diff --git a/server/src/sec/brokercam.c b/server/src/sec/brokercam.cindex 911fe57..7ced3f5 100644--- a/server/src/sec/brokercam.c+++ b/server/src/sec/brokercam.c@@ -159,7 +159,7 @@ static int on_helper_msg(void *src, const MediaMsg *m, const char *payload, intreturn 1;}case MM_ERROR:- cam_event(c, "event %d error {\"message\":\"camera\"}", c->sid);+ cam_event(c, "event %d error {\"message\":\"camera.failed\"}", c->sid);return 1;default:return 1; /* nothing else of a camera reaches the session */diff --git a/server/src/sec/json.c b/server/src/sec/json.cindex 38ca39c..8acf853 100644--- a/server/src/sec/json.c+++ b/server/src/sec/json.c@@ -150,7 +150,7 @@ static JVal *container(P *p, int obj) {if (!v) { fail(p, "out of memory"); return NULL; }memset(v, 0, sizeof *v);v->type = obj ? J_OBJ : J_ARR;- if (++p->depth > MAX_DEPTH) { fail(p, "demasiados niveles"); return NULL; }+ if (++p->depth > MAX_DEPTH) { fail(p, "nested too deeply"); return NULL; }p->s++;ws(p);JVal **tail = &v->kid;diff --git a/server/src/sec/pkgstate.c b/server/src/sec/pkgstate.cindex 97999f8..616ae2d 100644--- a/server/src/sec/pkgstate.c+++ b/server/src/sec/pkgstate.c@@ -166,7 +166,7 @@ int pkg_status(const char *id, PkgStatus *st) {st->installed = 1;if (pkg_original_path(id, orig, sizeof orig) || stat(orig, &os)) return 0; /* installed before M8 */st->has_original = 1;- if (list_dir(dir)) { seterr(st->error, sizeof st->error, "no se pudo leer la carpeta de la app"); return 0; }+ if (list_dir(dir)) { seterr(st->error, sizeof st->error, "pkgstate.readFailed"); return 0; }/* cheap fingerprint: sizes and dates of everything, plus the original */unsigned long long fp = 1469598103934665603ULL;for (int i = 0; i < walk_n; i++) {@@ -222,14 +222,14 @@ int pkg_check_update(const char *id, const LpkSigInfo *next, char *err, size_t nint bad = sig_verify_package(&pk, id, ver, &old, e2, sizeof e2);lpk_free(&pk);if (bad || !old.has_signature) return 0; /* the installed one has no valid signature: no key to require */- if (!next->has_signature) { seterr(err, n, "la versión instalada está firmada y esta actualización no"); return -1; }- if (strcmp(old.key, next->key)) { seterr(err, n, "la actualización está firmada con otra clave que la versión instalada"); return -1; }+ if (!next->has_signature) { seterr(err, n, "pkgstate.updateUnsigned"); return -1; }+ if (strcmp(old.key, next->key)) { seterr(err, n, "pkgstate.updateOtherKey"); return -1; }return 0;}int pkg_restore(const char *id, char *err, size_t n) {char orig[PATH_MAX];- if (pkg_original_path(id, orig, sizeof orig)) { seterr(err, n, "app inválida"); return -1; }+ if (pkg_original_path(id, orig, sizeof orig)) { seterr(err, n, "pkgstate.invalidApp"); return -1; }Lpk pk;if (lpk_open(orig, &pk, err, n)) return -1;char ver[40];@@ -277,7 +277,7 @@ int pkg_user_key(uint8_t seed[32], char pubhex[65], char name[128]) {struct passwd *pw = getpwuid(getuid());char full[128] = "";if (pw && pw->pw_gecos && pw->pw_gecos[0]) { snprintf(full, sizeof full, "%s", pw->pw_gecos); char *c = strchr(full, ','); if (c) *c = 0; }- if (!full[0]) snprintf(full, sizeof full, "%s", pw ? pw->pw_name : "usuario");+ if (!full[0]) snprintf(full, sizeof full, "%s", pw ? pw->pw_name : "user");snprintf(name, 128, "%s", full);char sh[65], qn[300], out[600];hex_encode(seed, 32, sh);@@ -288,7 +288,7 @@ int pkg_user_key(uint8_t seed[32], char pubhex[65], char name[128]) {int r = fd >= 0 && n > 0 && !write_all(fd, out, (size_t)n) ? 0 : -1;if (fd >= 0) close(fd);explicit_bzero(out, sizeof out);- if (!r) fprintf(stderr, "firma: clave propia creada (%s)\n", pubhex);+ if (!r) fprintf(stderr, "sign: own key created (%s)\n", pubhex);return r;}@@ -344,21 +344,21 @@ static void tar_add(Buf *o, const char *name, const void *data, size_t size) {int pkg_share(const char *id, const char *manifest, size_t mlen, const char *out_path, char *err, size_t n) {const char *root = lpk_root();- if (!root || !lpk_valid_id(id)) { seterr(err, n, "app inválida"); return -1; }+ if (!root || !lpk_valid_id(id)) { seterr(err, n, "pkgstate.invalidApp"); return -1; }JDoc md;- if (json_parse(manifest, mlen, &md, NULL, 0)) { seterr(err, n, "manifest inválido"); return -1; }+ if (json_parse(manifest, mlen, &md, NULL, 0)) { seterr(err, n, "pkgstate.badManifest"); return -1; }const char *mid = json_str(md.root, "id"), *ver = json_str(md.root, "version"), *based = json_str(md.root, "basedOn");int bad = !mid || strcmp(mid, id) || !ver || !based;char version[40];snprintf(version, sizeof version, "%s", ver ? ver : "");json_free(&md);- if (bad) { seterr(err, n, "el manifest tiene que ser de la misma app y traer basedOn"); return -1; }+ if (bad) { seterr(err, n, "pkgstate.manifestNotBasedOn"); return -1; }uint8_t seed[32];char pub[65], name[128];- if (pkg_user_key(seed, pub, name)) { seterr(err, n, "no se pudo crear la clave propia"); return -1; }+ if (pkg_user_key(seed, pub, name)) { seterr(err, n, "pkgstate.keyFailed"); return -1; }char dir[PATH_MAX];snprintf(dir, sizeof dir, "%s/%s", root, id);- if (list_dir(dir) || walk_bad) { explicit_bzero(seed, 32); seterr(err, n, "la carpeta de la app tiene enlaces o nombres inválidos"); return -1; }+ if (list_dir(dir) || walk_bad) { explicit_bzero(seed, 32); seterr(err, n, "pkgstate.badFolder"); return -1; }Buf tar = { 0 }, contents = { 0 };char line[600], q[300];json_quote(q, sizeof q, name);@@ -398,8 +398,8 @@ int pkg_share(const char *id, const char *manifest, size_t mlen, const char *output(&tar, end, sizeof end);int fd = tar.fail ? -1 : open(out_path, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC | O_NOFOLLOW, 0644);if (fd >= 0 && !write_all(fd, tar.b, tar.len) && !close(fd)) r = 0;- else { if (fd >= 0) { close(fd); unlink(out_path); } seterr(err, n, errno == EEXIST ? "ya existe un archivo con ese nombre" : "no se pudo escribir el paquete"); }- } else seterr(err, n, "no se pudo armar el paquete");+ else { if (fd >= 0) { close(fd); unlink(out_path); } seterr(err, n, errno == EEXIST ? "pkgstate.exists" : "pkgstate.writeFailed"); }+ } else seterr(err, n, "pkgstate.buildFailed");explicit_bzero(seed, sizeof seed);free(tar.b);free(contents.b);diff --git a/server/src/sec/sandbox.c b/server/src/sec/sandbox.cindex f9c492f..07615ac 100644--- a/server/src/sec/sandbox.c+++ b/server/src/sec/sandbox.c@@ -312,7 +312,7 @@ static int apply_seccomp_extra(int net, const int *extra, int ioctl_classes, intif (!SB_AUDIT_ARCH) { fprintf(stderr, "sandbox: seccomp not supported on this architecture\n"); return -1; }static struct sock_filter filt[1024];int n = build_filter(filt, (int)(sizeof filt / sizeof filt[0]), net, extra, ioctl_classes, helper, (unsigned)getpid());- if (n > (int)(sizeof filt / sizeof filt[0])) { fprintf(stderr, "sandbox: filtro seccomp demasiado grande (%d)\n", n); return -1; }+ if (n > (int)(sizeof filt / sizeof filt[0])) { fprintf(stderr, "sandbox: seccomp filter too large (%d)\n", n); return -1; }struct sock_fprog prog = { .len = (unsigned short)n, .filter = filt };if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)) return -1;long r = syscall(SYS_seccomp, SECCOMP_SET_MODE_FILTER, SECCOMP_FILTER_FLAG_TSYNC, &prog);diff --git a/server/src/sec/sign.c b/server/src/sec/sign.cindex 1b72fc7..f8e8209 100644--- a/server/src/sec/sign.c+++ b/server/src/sec/sign.c@@ -6,6 +6,7 @@#include "sign.h"#include "json.h"#include "keys.h"+#include "../errcode.h"#include "../pkg/crypto.h"#include <errno.h>@@ -48,13 +49,13 @@ int sig_official(const char *keyhex) {int sig_verify_detached(const char *sig_json, size_t siglen, const void *data, size_t len, char key[65], char *err, size_t errlen) {JDoc d;char why[96];- if (json_parse(sig_json, siglen, &d, why, sizeof why)) { seterr(err, errlen, "firma.json inválido"); return -1; }+ if (json_parse(sig_json, siglen, &d, why, sizeof why)) { seterr(err, errlen, "sig.badSignatureFile"); return -1; }const char *alg = json_str(d.root, "alg"), *k = json_str(d.root, "key"), *s = json_str(d.root, "sig");int r = -1;uint8_t pub[32], sig[64];- if (json_num(d.root, "format", 0) != 1 || !alg || strcmp(alg, "ed25519")) seterr(err, errlen, "firma de un formato desconocido");- else if (!is_hex(k, 64) || !is_hex(s, 128) || hex_decode(k, pub, 32) || hex_decode(s, sig, 64)) seterr(err, errlen, "firma.json inválido");- else if (!ed25519_verify(pub, sig, data, len)) seterr(err, errlen, "la firma no corresponde al contenido");+ if (json_num(d.root, "format", 0) != 1 || !alg || strcmp(alg, "ed25519")) seterr(err, errlen, "sig.unknownFormat");+ else if (!is_hex(k, 64) || !is_hex(s, 128) || hex_decode(k, pub, 32) || hex_decode(s, sig, 64)) seterr(err, errlen, "sig.badSignatureFile");+ else if (!ed25519_verify(pub, sig, data, len)) seterr(err, errlen, "sig.mismatch");else { snprintf(key, 65, "%s", k); r = 0; }json_free(&d);return r;@@ -76,32 +77,32 @@ int sig_make_detached(const uint8_t seed[32], const void *data, size_t len, charstatic int check_contents(const Lpk *pk, const JVal *root, const char *id, const char *version, char *err, size_t errlen) {const char *cid = json_str(root, "id"), *cver = json_str(root, "version");const JVal *files = json_get(root, "files");- if (json_num(root, "format", 0) != 1) { seterr(err, errlen, "contenido.json de un formato desconocido"); return -1; }- if (!cid || strcmp(cid, id) || !cver || strcmp(cver, version)) { seterr(err, errlen, "contenido.json es de otra app o de otra versión"); return -1; }- if (!files || files->type != J_ARR) { seterr(err, errlen, "contenido.json no tiene la lista de archivos"); return -1; }+ if (json_num(root, "format", 0) != 1) { seterr(err, errlen, "sig.contents.unknownFormat"); return -1; }+ if (!cid || strcmp(cid, id) || !cver || strcmp(cver, version)) { seterr(err, errlen, "sig.contents.otherApp"); return -1; }+ if (!files || files->type != J_ARR) { seterr(err, errlen, "sig.contents.noFiles"); return -1; }int listed = 0;for (const JVal *f = files->kid; f; f = f->next) {const char *path = json_str(f, "path"), *sha = json_str(f, "sha256");double size = json_num(f, "size", -1);if (!path || !lpk_valid_path(path) || !strcmp(path, SIG_CONTENTS) || !strcmp(path, SIG_SIGNATURE) || !is_hex(sha, 64) || size < 0) {- seterr(err, errlen, "contenido.json tiene una entrada inválida");+ seterr(err, errlen, "sig.contents.badEntry");return -1;}for (const JVal *g = files->kid; g != f; g = g->next)- if (!strcmp(json_str(g, "path"), path)) { seterr(err, errlen, "contenido.json repite un archivo"); return -1; }+ if (!strcmp(json_str(g, "path"), path)) { seterr(err, errlen, "sig.contents.duplicate"); return -1; }const LpkFile *lf = lpk_find(pk, path);- if (!lf) { if (err && errlen) snprintf(err, errlen, "falta un archivo del paquete: %s", path); return -1; }+ if (!lf) { if (err && errlen) lerr_set(err, errlen, "sig.fileMissing", "path", path, NULL); return -1; }uint8_t h[32];char hx[65];sha256(lf->data, lf->size, h);hex_encode(h, 32, hx);- if ((double)lf->size != size || strcmp(hx, sha)) { if (err && errlen) snprintf(err, errlen, "el archivo %s fue modificado", path); return -1; }+ if ((double)lf->size != size || strcmp(hx, sha)) { if (err && errlen) lerr_set(err, errlen, "sig.fileModified", "path", path, NULL); return -1; }listed++;}int real = 0;for (int i = 0; i < pk->nfiles; i++)if (strcmp(pk->files[i].path, SIG_CONTENTS) && strcmp(pk->files[i].path, SIG_SIGNATURE)) real++;- if (real != listed) { seterr(err, errlen, "el paquete trae archivos que no están en contenido.json"); return -1; }+ if (real != listed) { seterr(err, errlen, "sig.extraFiles"); return -1; }return 0;}@@ -111,7 +112,7 @@ int sig_verify_package(const Lpk *pk, const char *id, const char *version, LpkSiout->has_contents = c != NULL;out->has_signature = s != NULL;if (!c) {- if (s) { seterr(err, errlen, "el paquete tiene firma pero no contenido.json"); return -1; }+ if (s) { seterr(err, errlen, "sig.contents.missing"); return -1; }out->trust = LPK_UNSIGNED;if (catalog_revoked("", id, version, "", out->revoked_why, sizeof out->revoked_why)) out->revoked = 1;return 0;@@ -122,7 +123,7 @@ int sig_verify_package(const Lpk *pk, const char *id, const char *version, LpkSiJDoc d;char why[96];if (json_parse((const char *)c->data, c->size, &d, why, sizeof why)) {- if (err && errlen) snprintf(err, errlen, "contenido.json inválido: %s", why);+ if (err && errlen) lerr_set(err, errlen, "sig.contents.invalid", NULL);return -1;}int r = check_contents(pk, d.root, id, version, err, errlen);@@ -130,7 +131,7 @@ int sig_verify_package(const Lpk *pk, const char *id, const char *version, LpkSiconst char *sname = json_str(signer, "name"), *skey = json_str(signer, "key");if (!r && s) {r = sig_verify_detached((const char *)s->data, s->size, c->data, c->size, out->key, err, errlen);- if (!r && (!skey || strcmp(skey, out->key))) { seterr(err, errlen, "contenido.json nombra otra clave que la de la firma"); r = -1; }+ if (!r && (!skey || strcmp(skey, out->key))) { seterr(err, errlen, "sig.contents.otherKey"); r = -1; }}if (!r) {if (!s) out->trust = LPK_UNSIGNED;@@ -162,12 +163,12 @@ int catalog_parse(const char *json, size_t len, const char *sig, size_t siglen,memset(out, 0, sizeof *out);char key[65];if (sig_verify_detached(sig, siglen, json, len, key, err, errlen)) return -1;- if (!sig_official(key)) { seterr(err, errlen, "el catálogo no está firmado por LordOS"); return -1; }+ if (!sig_official(key)) { seterr(err, errlen, "sig.catalog.unofficial"); return -1; }JDoc d;char why[96];- if (json_parse(json, len, &d, why, sizeof why)) { if (err && errlen) snprintf(err, errlen, "catalog.json inválido: %s", why); return -1; }+ if (json_parse(json, len, &d, why, sizeof why)) { if (err && errlen) lerr_set(err, errlen, "sig.catalog.invalid", NULL); return -1; }const JVal *r = d.root;- if (json_num(r, "format", 0) != 1) { json_free(&d); seterr(err, errlen, "catálogo de un formato desconocido"); return -1; }+ if (json_num(r, "format", 0) != 1) { json_free(&d); seterr(err, errlen, "sig.catalog.unknownFormat"); return -1; }out->serial = json_num(r, "serial", 0);cpy(out->date, sizeof out->date, json_str(r, "date"));const JVal *a = json_get(r, "authors"), *rv = json_get(r, "revoked"), *p = json_get(r, "packages");@@ -178,7 +179,7 @@ int catalog_parse(const char *json, size_t len, const char *sig, size_t siglen,out->revoked_keys = calloc(nk + 1, sizeof *out->revoked_keys);out->revoked = calloc(nr + 1, sizeof *out->revoked);out->packages = calloc(np + 1, sizeof *out->packages);- if (!out->authors || !out->revoked_keys || !out->revoked || !out->packages) { json_free(&d); catalog_free(out); seterr(err, errlen, "sin memoria"); return -1; }+ if (!out->authors || !out->revoked_keys || !out->revoked || !out->packages) { json_free(&d); catalog_free(out); seterr(err, errlen, "sys.outOfMemory"); return -1; }for (const JVal *x = na ? a->kid : NULL; x; x = x->next) {const char *k = json_str(x, "key"), *n = json_str(x, "name");if (!is_hex(k, 64) || !n) continue;@@ -286,12 +287,12 @@ int catalog_revoked(const char *key, const char *id, const char *version, constconst Catalog *c = catalog_current();if (!c) return 0;for (int i = 0; key && key[0] && i < c->nrevoked_keys; i++)- if (!strcmp(c->revoked_keys[i], key)) { seterr(why, n, "LordOS revocó la clave con la que se firmó esta app"); return 1; }+ if (!strcmp(c->revoked_keys[i], key)) { seterr(why, n, "sig.revokedKey"); return 1; }for (int i = 0; i < c->nrevoked; i++) {const CatRevoked *r = &c->revoked[i];int hit = r->sha[0] ? contents_sha && !strcmp(r->sha, contents_sha): id && !strcmp(r->id, id) && (!strcmp(r->version, "*") || (version && !strcmp(r->version, version)));- if (hit) { seterr(why, n, "LordOS revocó esta versión de la app"); return 1; }+ if (hit) { seterr(why, n, "sig.revokedVersion"); return 1; }}return 0;}diff --git a/server/src/sound/snd.c b/server/src/sound/snd.cindex 3de0b31..3de63fc 100644--- a/server/src/sound/snd.c+++ b/server/src/sound/snd.c@@ -452,7 +452,7 @@ static void on_reply(Pending p, TsIn *t) {case R_NAME:S.connected = 1;S.dirty = 1;- fprintf(stderr, "sonido: conectado a PipeWire (protocolo %u)\n", S.version);+ fprintf(stderr, "sound: connected to PipeWire (protocol %u)\n", S.version);after_connected();break;case R_SERVER: {@@ -548,7 +548,7 @@ void snd_dispatch(void) {if (S.in_cap - S.in_len < 65536) {size_t cap = S.in_cap ? S.in_cap * 2 : 65536;while (cap - S.in_len < 65536) cap *= 2;- if (cap > PA_FRAME_MAX + 65536) { disconnect("paquete demasiado grande"); return; }+ if (cap > PA_FRAME_MAX + 65536) { disconnect("packet too large"); return; }uint8_t *b = realloc(S.in, cap);if (!b) { disconnect("out of memory"); return; }S.in = b;diff --git a/server/src/ui/grab.c b/server/src/ui/grab.cindex 96fe4d3..70111c6 100644--- a/server/src/ui/grab.c+++ b/server/src/ui/grab.c@@ -87,6 +87,7 @@ void grab_motion(float px, float py) {g.x = x; g.y = y; g.w = w; g.h = h;n->s.pos[EDGE_L] = (Dim){ x, UNIT_PX };n->s.pos[EDGE_T] = (Dim){ y, UNIT_PX };+ node_moved(n);if (sized) {n->s.width = (Dim){ w, UNIT_PX };n->s.height = (Dim){ h, UNIT_PX };diff --git a/server/src/ui/js.c b/server/src/ui/js.cindex 9fc1547..d3b843f 100644--- a/server/src/ui/js.c+++ b/server/src/ui/js.c@@ -144,6 +144,8 @@ static JSValue f_set_style(JSContext *c, JSValueConst this_val, int argc, JSValuJSValueConst v = argv[2];int err = 0;Style before = n->s;+ StyleExt ext_before;+ if (n->s.ext) memcpy(&ext_before, n->s.ext, STYLE_EXT_VALUES);if (!strcmp(key, "gradient")) {if (JS_IsArray(c, v)) {double a[3] = {180, 0, 0};@@ -171,7 +173,8 @@ static JSValue f_set_style(JSContext *c, JSValueConst this_val, int argc, JSValuif (err) fprintf(stderr, "js: unsupported style '%s'\n", key);JS_FreeCString(c, key);/* the same value (e.g. React confirms the position left by a drag in C): nothing to repaint */- if (memcmp(&before, &n->s, sizeof before)) node_invalidate(n);+ if (memcmp(&before, &n->s, sizeof before) || (n->s.ext && (!before.ext || memcmp(&ext_before, n->s.ext, STYLE_EXT_VALUES))))+ node_invalidate(n);return JS_UNDEFINED;}diff --git a/server/src/ui/js_backup.c b/server/src/ui/js_backup.cindex 9c24abd..b56c107 100644--- a/server/src/ui/js_backup.c+++ b/server/src/ui/js_backup.c@@ -14,6 +14,7 @@* the thread) and kept only in memory; result in status().unlock* Errors are thrown as exceptions carrying the reason. */#include "js_backup.h"+#include "js_err.h"#include "../backup/backup.h"#include <stdlib.h>@@ -26,7 +27,7 @@ static JSValue parsed(JSContext *c, char *j, const char *what) {return v;}-static JSValue fail(JSContext *c, const char *err) { return JS_ThrowTypeError(c, "%s", err[0] ? err : "error"); }+static JSValue fail(JSContext *c, const char *err) { return js_throw_line(c, err[0] ? err : "sys.unknown"); }static JSValue f_status(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {(void)t; (void)argc; (void)argv;@@ -40,7 +41,7 @@ static JSValue f_config(JSContext *c, JSValueConst t, int argc, JSValueConst *arstatic JSValue f_configure(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {(void)t;- if (argc < 1) return JS_ThrowTypeError(c, "missing configuration");+ if (argc < 1) return js_throw_code(c, "backup.badConfig", NULL);JSValue s = JS_JSONStringify(c, argv[0], JS_UNDEFINED, JS_UNDEFINED);const char *j = JS_IsException(s) ? NULL : JS_ToCString(c, s);JS_FreeValue(c, s);diff --git a/server/src/ui/js_brokercam.c b/server/src/ui/js_brokercam.cindex b6e58a3..8074f2c 100644--- a/server/src/ui/js_brokercam.c+++ b/server/src/ui/js_brokercam.c@@ -9,6 +9,7 @@* the app only learns the file name. */#include "js_broker.h"#include "js.h"+#include "js_err.h"#include "../sec/broker.h"#include "../media/media_int.h"@@ -157,18 +158,18 @@ static JSValue f_camera(JSContext *c, JSValueConst t, int argc, JSValueConst *archar p[96];int n = dev && a ? snprintf(p, sizeof p, "open %.40s %d %d", dev, opt_int(c, o, "width", 1280, 160, 3840), opt_int(c, o, "height", 720, 120, 2160)) : -1;if (dev) JS_FreeCString(c, dev);- if (n <= 0) return JS_ThrowTypeError(c, "invalid camera");+ if (n <= 0) return js_throw_code(c, "camera.invalid", NULL);int st = BST_ERROR;char *out = NULL;uint32_t len = 0;if (js_broker_rpc(BOP_CAMERA, p, (uint32_t)n, &st, &out, &len) || st != BST_OK || !out) {free(out);- return st == BST_DENIED ? JS_ThrowTypeError(c, "camera permission denied") : JS_ThrowRangeError(c, "could not open the camera");+ return js_throw_code(c, st == BST_DENIED ? "perm.cameraDenied" : "camera.openFailed", NULL);}int sid = atoi(out);free(out);MediaSrc *s = media_src_new(SK_CAMERA, "app");- if (!s) { cmd("close %d%s", sid, NULL, NULL); return JS_ThrowRangeError(c, "too many media"); }+ if (!s) { cmd("close %d%s", sid, NULL, NULL); return js_throw_code(c, "media.tooMany", NULL); }*a = (ACam){ .used = 1, .sid = sid, .local = s->id };return JS_NewInt32(c, s->id);}diff --git a/server/src/ui/js_doc.c b/server/src/ui/js_doc.cindex 6569fc5..5e70bd0 100644--- a/server/src/ui/js_doc.c+++ b/server/src/ui/js_doc.c@@ -19,6 +19,7 @@*/#include "js_doc.h"#include "js_sys.h"+#include "js_err.h"#include "ui.h"#include "../doc/doc.h"#include "../doc/proto.h"@@ -88,7 +89,7 @@ static int open_new(const char *path) {return open(target, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0644);}-static JSValue throw_path(JSContext *c) { return JS_ThrowRangeError(c, "path outside the home folder or invalid"); }+static JSValue throw_path(JSContext *c) { return js_throw_code(c, "fs.outsideHome", NULL); }static const char *arg_str(JSContext *c, int argc, JSValueConst *argv, int i) {return i < argc && JS_IsString(argv[i]) ? JS_ToCString(c, argv[i]) : NULL;@@ -137,32 +138,32 @@ static JSValue f_open_pdf(JSContext *c, JSValueConst t, int argc, JSValueConst *if (p) JS_FreeCString(c, p);if (bad) return throw_path(c);int fd = open_file(real);- if (fd < 0) return JS_ThrowTypeError(c, "could not open: %s", strerror(errno));+ if (fd < 0) return js_throw_code(c, "fs.openFailed", "errno", lerr_errno(errno), NULL);DocInitFd init = { fd, "file" };int sid = doc_session("pdf", &init, 1);- return sid > 0 ? JS_NewInt32(c, sid) : JS_ThrowInternalError(c, "no document helper");+ return sid > 0 ? JS_NewInt32(c, sid) : js_throw_code(c, "doc.noHelper", NULL);}static JSValue f_open_blob(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {(void)t;int fd = doc_blob_dup(arg_int(c, argc, argv, 0, 0), NULL);- if (fd < 0) return JS_ThrowRangeError(c, "invalid blob");+ if (fd < 0) return js_throw_code(c, "doc.badBlob", NULL);DocInitFd init = { fd, "file" };int sid = doc_session("pdf", &init, 1);- return sid > 0 ? JS_NewInt32(c, sid) : JS_ThrowInternalError(c, "no document helper");+ return sid > 0 ? JS_NewInt32(c, sid) : js_throw_code(c, "doc.noHelper", NULL);}static JSValue f_request(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {(void)t;int sid = arg_int(c, argc, argv, 0, 0);const char *op = arg_str(c, argc, argv, 1);- if (!op) return JS_ThrowTypeError(c, "op");+ if (!op) return js_throw_code(c, "sys.badArgument", NULL);uint32_t code = 0;int timeout = 0;for (size_t i = 0; i < sizeof pdf_ops / sizeof pdf_ops[0]; i++)if (!strcmp(op, pdf_ops[i].name)) { code = pdf_ops[i].op; timeout = pdf_ops[i].timeout; }JS_FreeCString(c, op);- if (!code) return JS_ThrowRangeError(c, "unknown op");+ if (!code) return js_throw_code(c, "sys.badArgument", NULL);size_t len;const char *json = arg_json(c, argc, argv, 2, &len);int prio = arg_int(c, argc, argv, 3, 0);@@ -179,7 +180,7 @@ static JSValue f_save_pdf(JSContext *c, JSValueConst t, int argc, JSValueConst *const char *p = arg_str(c, argc, argv, 1);int fd = open_new(p);if (p) JS_FreeCString(c, p);- if (fd < 0) return errno == EEXIST ? JS_ThrowRangeError(c, "already exists") : throw_path(c);+ if (fd < 0) return errno == EEXIST ? js_throw_code(c, "fs.exists", NULL) : throw_path(c);int id = doc_request(sid, DQ_PDF_SAVE, "{}", 2, &fd, 1, 5, 120000);return JS_NewInt32(c, id);}@@ -199,10 +200,10 @@ static JSValue f_arc_list(JSContext *c, JSValueConst t, int argc, JSValueConst *if (p) JS_FreeCString(c, p);if (bad) return throw_path(c);int fd = open_file(real);- if (fd < 0) return JS_ThrowTypeError(c, "could not open: %s", strerror(errno));+ if (fd < 0) return js_throw_code(c, "fs.openFailed", "errno", lerr_errno(errno), NULL);DocInitFd init = { fd, "file" };int sid = doc_session("arc", &init, 1);- if (sid < 0) return JS_ThrowInternalError(c, "no document helper");+ if (sid < 0) return js_throw_code(c, "doc.noHelper", NULL);return pair(c, sid, doc_request(sid, DQ_ARC_LIST, "{\"slot\":0}", 10, NULL, 0, 0, 0));}@@ -217,14 +218,14 @@ static JSValue f_arc_extract(JSContext *c, JSValueConst t, int argc, JSValueConsif (d) JS_FreeCString(c, d);if (bad) return throw_path(c);int existing = argc > 3 && JS_ToBool(c, argv[3]) > 0;- if (!existing && mkdir(target, 0755)) return errno == EEXIST ? JS_ThrowRangeError(c, "already exists") : JS_ThrowTypeError(c, "%s", strerror(errno));+ if (!existing && mkdir(target, 0755)) return errno == EEXIST ? js_throw_code(c, "fs.exists", NULL) : js_throw_code(c, "sys.errno", "errno", lerr_errno(errno), NULL);int dfd = open(target, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);- if (dfd < 0) return JS_ThrowTypeError(c, "%s", strerror(errno));+ if (dfd < 0) return js_throw_code(c, "sys.errno", "errno", lerr_errno(errno), NULL);int fd = open_file(real);- if (fd < 0) { close(dfd); return JS_ThrowTypeError(c, "could not open: %s", strerror(errno)); }+ if (fd < 0) { close(dfd); return js_throw_code(c, "fs.openFailed", "errno", lerr_errno(errno), NULL); }DocInitFd init[2] = { { fd, "file" }, { dfd, "rw" } };int sid = doc_session("arc", init, 2);- if (sid < 0) return JS_ThrowInternalError(c, "no document helper");+ if (sid < 0) return js_throw_code(c, "doc.noHelper", NULL);/* {"slot":0,"dir":1, ...what JS sent} */size_t len;const char *json = arg_json(c, argc, argv, 2, &len);@@ -242,12 +243,12 @@ static JSValue f_arc_extract(JSContext *c, JSValueConst t, int argc, JSValueConsstatic JSValue f_arc_create(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {(void)t;- if (argc < 2 || !JS_IsArray(c, argv[0])) return JS_ThrowTypeError(c, "rutas");+ if (argc < 2 || !JS_IsArray(c, argv[0])) return js_throw_code(c, "sys.badArgument", NULL);JSValue lv = JS_GetPropertyStr(c, argv[0], "length");int32_t n = 0;JS_ToInt32(c, &n, lv);JS_FreeValue(c, lv);- if (n < 1 || n > DOC_INIT_FDS - 1) return JS_ThrowRangeError(c, "between 1 and %d items", DOC_INIT_FDS - 1);+ if (n < 1 || n > DOC_INIT_FDS - 1) return js_throw_code(c, "doc.itemCount", "max", lerr_int(DOC_INIT_FDS - 1), NULL);DocInitFd *init = calloc((size_t)n + 1, sizeof *init);if (!init) return JS_ThrowOutOfMemory(c);JBuf items;@@ -282,7 +283,7 @@ static JSValue f_arc_create(JSContext *c, JSValueConst t, int argc, JSValueConstfor (int i = 0; i < k; i++) close(init[i].fd);free(init);jb_free(&items);- return !bad && eexist ? JS_ThrowRangeError(c, "already exists") : throw_path(c);+ return !bad && eexist ? js_throw_code(c, "fs.exists", NULL) : throw_path(c);}init[k].fd = ofd;init[k].role = "out";@@ -296,19 +297,19 @@ static JSValue f_arc_create(JSContext *c, JSValueConst t, int argc, JSValueConstfree(init);int req = sid > 0 && !j.oom ? doc_request(sid, DQ_ARC_CREATE, j.p, j.n, NULL, 0, 0, 0) : -1;jb_free(&j);- if (sid < 0) return JS_ThrowInternalError(c, "no document helper");+ if (sid < 0) return js_throw_code(c, "doc.noHelper", NULL);return pair(c, sid, req);}static JSValue f_util(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {(void)t;const char *op = arg_str(c, argc, argv, 0);- if (!op) return JS_ThrowTypeError(c, "op");+ if (!op) return js_throw_code(c, "sys.badArgument", NULL);int k = -1;for (size_t i = 0; i < sizeof util_ops / sizeof util_ops[0]; i++) if (!strcmp(op, util_ops[i].name)) k = (int)i;int font = !strncmp(op, "font", 4);JS_FreeCString(c, op);- if (k < 0) return JS_ThrowRangeError(c, "unknown op");+ if (k < 0) return js_throw_code(c, "sys.badArgument", NULL);int fds[2], nfds = 0;const char *p = arg_str(c, argc, argv, 2);if (p) {@@ -317,14 +318,14 @@ static JSValue f_util(JSContext *c, JSValueConst t, int argc, JSValueConst *argvJS_FreeCString(c, p);if (bad) return throw_path(c);int fd = open_file(real);- if (fd < 0) return JS_ThrowTypeError(c, "could not open: %s", strerror(errno));+ if (fd < 0) return js_throw_code(c, "fs.openFailed", "errno", lerr_errno(errno), NULL);fds[nfds++] = fd;}if (util_ops[k].out) {const char *o = arg_str(c, argc, argv, 3);int ofd = open_new(o);if (o) JS_FreeCString(c, o);- if (ofd < 0) { for (int i = 0; i < nfds; i++) close(fds[i]); return errno == EEXIST ? JS_ThrowRangeError(c, "already exists") : throw_path(c); }+ if (ofd < 0) { for (int i = 0; i < nfds; i++) close(fds[i]); return errno == EEXIST ? js_throw_code(c, "fs.exists", NULL) : throw_path(c); }fds[nfds++] = ofd;}size_t len;@@ -337,7 +338,7 @@ static JSValue f_util(JSContext *c, JSValueConst t, int argc, JSValueConst *argvint id = util_sid > 0 ? doc_request(util_sid, util_ops[k].op, json, len, fds, nfds, 0, util_ops[k].timeout) : -1;if (util_sid <= 0) for (int i = 0; i < nfds; i++) close(fds[i]);if (json) JS_FreeCString(c, json);- if (id < 0) return JS_ThrowInternalError(c, "no document helper");+ if (id < 0) return js_throw_code(c, "doc.noHelper", NULL);JSValue o = pair(c, util_sid, id);return o;}@@ -408,7 +409,7 @@ static JSValue f_blob_save(JSContext *c, JSValueConst t, int argc, JSValueConstconst char *p = arg_str(c, argc, argv, 1);int fd = open_new(p);if (p) JS_FreeCString(c, p);- if (fd < 0) return errno == EEXIST ? JS_ThrowRangeError(c, "already exists") : throw_path(c);+ if (fd < 0) return errno == EEXIST ? js_throw_code(c, "fs.exists", NULL) : throw_path(c);int r = doc_blob_copy(arg_int(c, argc, argv, 0, 0), fd);close(fd);return JS_NewBool(c, r == 0);diff --git a/server/src/ui/js_err.h b/server/src/ui/js_err.hnew file mode 100644index 0000000..7841f97--- /dev/null+++ b/server/src/ui/js_err.h@@ -0,0 +1,91 @@+/* js_err.h — throwing translatable errors to JS (header only; see ../errcode.h).+ *+ * return js_throw_code(c, "fs.outsideHome", "path", p, NULL);+ * if (lpk_open(path, &pk, err, sizeof err)) return js_throw_line(c, err); // err holds a code line+ *+ * The thrown Error has `code` ("fs.outsideHome") and `params` ({ path }) and, as its message, the+ * text in the user's language: the SDK registers globalThis.__lordErrorText(code, params)+ * (sdk/errors.js), so existing `catch (e) { show(e.message) }` code keeps working. Without the+ * SDK (tests) the message is the code line itself. A line that is not a code (prose from an older+ * path) is thrown as is. */+#ifndef LORD_JS_ERR_H+#define LORD_JS_ERR_H++#include "quickjs.h"+#include "../errcode.h"++static inline JSValue js_err_params(JSContext *c, const char *line)+{+ JSValue o = JS_NewObject(c);+ for (const char *p = strchr(line, ' '); p; p = strchr(p + 1, ' ')) {+ const char *eq = strchr(p + 1, '=');+ const char *end = strchr(p + 1, ' ');+ if (!eq || (end && eq > end)) continue;+ char key[64];+ size_t kl = (size_t)(eq - p - 1);+ if (!kl || kl >= sizeof key) continue;+ memcpy(key, p + 1, kl);+ key[kl] = 0;+ size_t vl = end ? (size_t)(end - eq - 1) : strlen(eq + 1);+ char *v = js_malloc(c, vl + 1);+ if (!v) break;+ size_t o2 = 0;+ for (size_t i = 0; i < vl; i++) {+ const char *s = eq + 1 + i;+ if (s[0] == '%' && i + 2 < vl) {+ char h[3] = { s[1], s[2], 0 };+ v[o2++] = (char)strtol(h, NULL, 16);+ i += 2;+ } else v[o2++] = *s;+ }+ v[o2] = 0;+ JS_SetPropertyStr(c, o, key, JS_NewStringLen(c, v, o2));+ js_free(c, v);+ }+ return o;+}++/* Throws the code line `line` (or prose, as is) as a translated Error. */+static inline JSValue js_throw_line(JSContext *c, const char *line)+{+ if (!line || !line[0]) line = "sys.unknown";+ JSValue e = JS_NewError(c);+ if (JS_IsException(e)) return e;+ if (!lerr_is(line)) {+ JS_SetPropertyStr(c, e, "message", JS_NewString(c, line));+ return JS_Throw(c, e);+ }+ size_t n = strcspn(line, " ");+ JSValue code = JS_NewStringLen(c, line, n);+ JSValue params = js_err_params(c, line);+ JSValue msg = JS_UNDEFINED;+ JSValue g = JS_GetGlobalObject(c);+ JSValue fn = JS_GetPropertyStr(c, g, "__lordErrorText");+ if (JS_IsFunction(c, fn)) {+ JSValue argv[2] = { code, params };+ msg = JS_Call(c, fn, JS_UNDEFINED, 2, argv);+ if (JS_IsException(msg)) { JS_FreeValue(c, JS_GetException(c)); msg = JS_UNDEFINED; }+ else if (!JS_IsString(msg)) { JS_FreeValue(c, msg); msg = JS_UNDEFINED; }+ }+ JS_FreeValue(c, fn);+ JS_FreeValue(c, g);+ if (JS_IsUndefined(msg)) msg = JS_NewString(c, line);+ JS_SetPropertyStr(c, e, "message", msg);+ JS_SetPropertyStr(c, e, "code", code);+ JS_SetPropertyStr(c, e, "params", params);+ return JS_Throw(c, e);+}++/* Throws code with (key, value) pairs ending in NULL. */+__attribute__((sentinel))+static inline JSValue js_throw_code(JSContext *c, const char *code, ...)+{+ char line[1024];+ va_list ap;+ va_start(ap, code);+ lerr_vset(line, sizeof line, code, ap);+ va_end(ap);+ return js_throw_line(c, line);+}++#endifdiff --git a/server/src/ui/js_fw.c b/server/src/ui/js_fw.cindex 39351fd..3e93dfb 100644--- a/server/src/ui/js_fw.c+++ b/server/src/ui/js_fw.c@@ -20,6 +20,7 @@* All of them validate: app ids with fw_app_canon, destinations with fw_parse_dest, ports 1–65535. */#include "js_fw.h"#include "../fw/rules.h"+#include "js_err.h"#include "../netperm/npproto.h"#include <errno.h>@@ -210,7 +211,7 @@ static JSValue f_state(JSContext *c, JSValueConst t, int argc, JSValueConst *argstatic JSValue f_app_rule(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {(void)t;char app[FW_APP_MAX];- if (argc < 1 || arg_app(c, argv[0], app)) return JS_ThrowTypeError(c, "invalid app");+ if (argc < 1 || arg_app(c, argv[0], app)) return js_throw_code(c, "fw.invalidApp", NULL);FwRule buf[256];const FwRule *r = app_rule(app, buf, 256);return r ? JS_NewString(c, r->action == FW_DENY ? "deny" : "allow") : JS_NULL;@@ -219,12 +220,12 @@ static JSValue f_app_rule(JSContext *c, JSValueConst t, int argc, JSValueConst *static JSValue f_set_app_rule(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {(void)t;char app[FW_APP_MAX];- if (argc < 2 || arg_app(c, argv[0], app)) return JS_ThrowTypeError(c, "invalid app");+ if (argc < 2 || arg_app(c, argv[0], app)) return js_throw_code(c, "fw.invalidApp", NULL);char v[8];if (JS_IsNull(argv[1])) v[0] = 0;else {const char *s = JS_IsString(argv[1]) ? JS_ToCString(c, argv[1]) : NULL;- if (!s || (strcmp(s, "allow") && strcmp(s, "deny"))) { if (s) JS_FreeCString(c, s); return JS_ThrowTypeError(c, "'allow', 'deny' or null"); }+ if (!s || (strcmp(s, "allow") && strcmp(s, "deny"))) { if (s) JS_FreeCString(c, s); return js_throw_code(c, "fw.invalidRule", "field", "action", NULL); }snprintf(v, sizeof v, "%s", s);JS_FreeCString(c, s);}@@ -251,7 +252,7 @@ static JSValue f_set_app_rule(JSContext *c, JSValueConst t, int argc, JSValueConstatic JSValue f_set_trusted(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {(void)t;char app[FW_APP_MAX];- if (argc < 2 || arg_app(c, argv[0], app)) return JS_ThrowTypeError(c, "invalid app");+ if (argc < 2 || arg_app(c, argv[0], app)) return js_throw_code(c, "fw.invalidApp", NULL);if (fw_set_trusted(store, app, JS_ToBool(c, argv[1]) > 0)) return JS_FALSE;return JS_NewBool(c, save() == 0);}@@ -259,20 +260,20 @@ static JSValue f_set_trusted(JSContext *c, JSValueConst t, int argc, JSValueConsstatic JSValue f_set_restricted(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {(void)t;char app[FW_APP_MAX];- if (argc < 2 || arg_app(c, argv[0], app)) return JS_ThrowTypeError(c, "invalid app");+ if (argc < 2 || arg_app(c, argv[0], app)) return js_throw_code(c, "fw.invalidApp", NULL);uint32_t flags = 0, len = 0;- if (!JS_IsArray(c, argv[1])) return JS_ThrowTypeError(c, "list of restrictions");+ if (!JS_IsArray(c, argv[1])) return js_throw_code(c, "fw.invalidRestrictions", NULL);JSValue lv = JS_GetPropertyStr(c, argv[1], "length");JS_ToUint32(c, &len, lv);JS_FreeValue(c, lv);- if (len > 32) return JS_ThrowRangeError(c, "too many restrictions");+ if (len > 32) return js_throw_code(c, "fw.invalidRestrictions", NULL);for (uint32_t i = 0; i < len; i++) {JSValue e = JS_GetPropertyUint32(c, argv[1], i);const char *s = JS_IsString(e) ? JS_ToCString(c, e) : NULL;uint32_t f = s ? fw_flag_from_name(s) : 0;if (s) JS_FreeCString(c, s);JS_FreeValue(c, e);- if (!f) return JS_ThrowTypeError(c, "unknown restriction");+ if (!f) return js_throw_code(c, "fw.invalidRestrictions", NULL);flags |= f;}if (fw_set_restricted(store, app, flags)) return JS_FALSE;@@ -282,12 +283,12 @@ static JSValue f_set_restricted(JSContext *c, JSValueConst t, int argc, JSValueCstatic JSValue f_set_mode(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {(void)t;char m[16];- if (argc < 1 || !JS_IsString(argv[0])) return JS_ThrowTypeError(c, "mode");+ if (argc < 1 || !JS_IsString(argv[0])) return js_throw_code(c, "fw.invalidMode", NULL);const char *s = JS_ToCString(c, argv[0]);snprintf(m, sizeof m, "%s", s ? s : "");if (s) JS_FreeCString(c, s);FwMode mode = !strcmp(m, "silent") ? FW_MODE_SILENT : !strcmp(m, "ask") ? FW_MODE_ASK : !strcmp(m, "off") ? FW_MODE_OFF : (FwMode)-1;- if ((int)mode < 0) return JS_ThrowTypeError(c, "'silent', 'ask' u 'off'");+ if ((int)mode < 0) return js_throw_code(c, "fw.invalidMode", NULL);fw_set_mode(store, mode);return JS_NewBool(c, save() == 0);}@@ -313,7 +314,7 @@ static JSValue rule_obj(JSContext *c, const FwRule *r) {static JSValue f_rules(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {(void)t;char app[FW_APP_MAX];- if (argc < 1 || arg_app(c, argv[0], app)) return JS_ThrowTypeError(c, "invalid app");+ if (argc < 1 || arg_app(c, argv[0], app)) return js_throw_code(c, "fw.invalidApp", NULL);JSValue arr = JS_NewArray(c);int n = fw_rule_list(store, app, NULL, 0);if (n <= 0) return arr;@@ -343,28 +344,28 @@ static int parse_port(const char *s, FwRule *r) {static JSValue f_add_rule(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {(void)t;- if (argc < 1 || !JS_IsObject(argv[0])) return JS_ThrowTypeError(c, "rule");+ if (argc < 1 || !JS_IsObject(argv[0])) return js_throw_code(c, "fw.invalidRule", "field", "rule", NULL);char app[FW_APP_MAX], canon[FW_APP_MAX], dir[8], dst[300], port[16], proto[8], action[8];- if (str_prop(c, argv[0], "app", app, sizeof app) || fw_app_canon(app, canon, sizeof canon)) return JS_ThrowTypeError(c, "invalid app");- if (str_prop(c, argv[0], "dst", dst, sizeof dst)) return JS_ThrowTypeError(c, "destination");+ if (str_prop(c, argv[0], "app", app, sizeof app) || fw_app_canon(app, canon, sizeof canon)) return js_throw_code(c, "fw.invalidApp", NULL);+ if (str_prop(c, argv[0], "dst", dst, sizeof dst)) return js_throw_code(c, "fw.invalidRule", "field", "dst", NULL);if (str_prop(c, argv[0], "dir", dir, sizeof dir) < 0 || str_prop(c, argv[0], "port", port, sizeof port) < 0 ||str_prop(c, argv[0], "proto", proto, sizeof proto) < 0 || str_prop(c, argv[0], "action", action, sizeof action))- return JS_ThrowTypeError(c, "rule");+ return js_throw_code(c, "fw.invalidRule", "field", "rule", NULL);FwRule r;memset(&r, 0, sizeof r);snprintf(r.app, sizeof r.app, "%s", canon);- if (fw_parse_dest(dst, &r)) return JS_ThrowTypeError(c, "invalid destination");+ if (fw_parse_dest(dst, &r)) return js_throw_code(c, "fw.invalidDestination", NULL);if (!dir[0] || !strcmp(dir, "out")) r.dir = FW_OUT;else if (!strcmp(dir, "in")) r.dir = FW_IN;- else return JS_ThrowTypeError(c, "direction");- if (parse_port(port, &r)) return JS_ThrowTypeError(c, "port");+ else return js_throw_code(c, "fw.invalidRule", "field", "dir", NULL);+ if (parse_port(port, &r)) return js_throw_code(c, "fw.invalidRule", "field", "port", NULL);if (!proto[0]) r.proto = FW_PROTO_ANY;else if (!strcmp(proto, "tcp")) r.proto = FW_PROTO_TCP;else if (!strcmp(proto, "udp")) r.proto = FW_PROTO_UDP;- else return JS_ThrowTypeError(c, "protocol");+ else return js_throw_code(c, "fw.invalidRule", "field", "proto", NULL);if (!strcmp(action, "allow")) r.action = FW_ALLOW;else if (!strcmp(action, "deny")) r.action = FW_DENY;- else return JS_ThrowTypeError(c, "action");+ else return js_throw_code(c, "fw.invalidRule", "field", "action", NULL);r.life = FW_LIFE_FOREVER;r.when = (long long)time(NULL);uint32_t id = 0;@@ -376,7 +377,7 @@ static JSValue f_add_rule(JSContext *c, JSValueConst t, int argc, JSValueConst *static JSValue f_remove_rule(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {(void)t;uint32_t id = 0;- if (argc < 1 || JS_ToUint32(c, &id, argv[0]) || !id) return JS_ThrowTypeError(c, "id");+ if (argc < 1 || JS_ToUint32(c, &id, argv[0]) || !id) return js_throw_code(c, "fw.invalidRule", "field", "id", NULL);if (fw_rule_remove(store, id)) return JS_FALSE;return JS_NewBool(c, save() == 0);}diff --git a/server/src/ui/js_logs.c b/server/src/ui/js_logs.cindex 44674b9..a82a036 100644--- a/server/src/ui/js_logs.c+++ b/server/src/ui/js_logs.c@@ -18,6 +18,7 @@* The thread and inotify go through a single epoll fd that the main loop watches (logs_fd()), so* the compositor never waits on a read and there is no polling. */#include "js_logs.h"+#include "js_err.h"#include "../logs/journal.h"#include <ctype.h>@@ -217,7 +218,7 @@ static int get_str(JSContext *c, JSValueConst o, const char *k, char *out, size_static JSValue f_query(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {(void)t;- if (argc < 1 || !JS_IsObject(argv[0])) return JS_ThrowTypeError(c, "logs.query: missing query");+ if (argc < 1 || !JS_IsObject(argv[0])) return js_throw_code(c, "logs.badQuery", NULL);JSValueConst o = argv[0];Req r = { 0 };char scope[16], tmp[160];@@ -236,16 +237,16 @@ static JSValue f_query(JSContext *c, JSValueConst t, int argc, JSValueConst *argJS_FreeValue(c, k);if (get_str(c, o, "match", tmp, 97) == 1 && tmp[0]) n += (size_t)snprintf(text + n, sizeof text - n, "match=%s\n", tmp);if (get_str(c, o, "grep", tmp, 128) == 1 && tmp[0] && !strchr(tmp, '\n')) n += (size_t)snprintf(text + n, sizeof text - n, "grep=%s\n", tmp);- if (n >= sizeof text || jq_parse(text, &r.q, 20000)) return JS_ThrowRangeError(c, "logs.query: invalid query");+ if (n >= sizeof text || jq_parse(text, &r.q, 20000)) return js_throw_code(c, "logs.badQuery", NULL);pthread_mutex_lock(&mu);- if (nq == QMAX) { pthread_mutex_unlock(&mu); return JS_ThrowRangeError(c, "logs.query: too many queries in progress"); }+ if (nq == QMAX) { pthread_mutex_unlock(&mu); return js_throw_code(c, "logs.tooManyQueries", NULL); }if (!th_started) {pthread_attr_t a;pthread_attr_init(&a);pthread_attr_setdetachstate(&a, PTHREAD_CREATE_DETACHED);th_started = pthread_create(&th, &a, worker, NULL) == 0;pthread_attr_destroy(&a);- if (!th_started) { pthread_mutex_unlock(&mu); return JS_ThrowInternalError(c, "logs.query: no thread"); }+ if (!th_started) { pthread_mutex_unlock(&mu); return js_throw_code(c, "logs.noThread", NULL); }}r.id = next_id++;if (next_id > 1 << 30) next_id = 1;@@ -320,7 +321,7 @@ static JSValue f_tail(JSContext *c, JSValueConst t, int argc, JSValueConst *argvchar p[1024];snprintf(p, sizeof p, "%s/.cache/lordos/%s", home(), name);JS_FreeCString(c, name);- if (!ok) return JS_ThrowRangeError(c, "logs.tail: invalid name");+ if (!ok) return js_throw_code(c, "logs.badName", NULL);double want = 262144;if (argc > 1) JS_ToFloat64(c, &want, argv[1]);size_t max = want < 1024 ? 1024 : want > 1048576 ? 1048576 : (size_t)want;diff --git a/server/src/ui/js_mail.c b/server/src/ui/js_mail.cindex 15ac750..9ff6aaf 100644--- a/server/src/ui/js_mail.c+++ b/server/src/ui/js_mail.c@@ -18,6 +18,7 @@*/#include "js_mail.h"#include "js_sys.h"+#include "js_err.h"#include "ui.h"#include "../mail/mailc.h"#include "../mail/proto.h"@@ -77,14 +78,14 @@ static JSValue f_request(JSContext *c, JSValueConst t, int argc, JSValueConst *a(void)t;size_t len = 0;const char *j = arg_str(c, argc, argv, 0, &len);- if (!j) return JS_ThrowTypeError(c, "request(json, [paths])");- if (len > MAIL_REQ_MAX) { JS_FreeCString(c, j); return JS_ThrowRangeError(c, "request too big"); }+ if (!j) return js_throw_code(c, "sys.badArgument", NULL);+ if (len > MAIL_REQ_MAX) { JS_FreeCString(c, j); return js_throw_code(c, "mail.requestTooLarge", NULL); }/* must be a JSON object with a short "op" */JDoc d;if (json_parse(j, len, &d, NULL, 0) || !d.root || d.root->type != J_OBJ || !json_str(d.root, "op") || strlen(json_str(d.root, "op")) > 32) {if (d.root) json_free(&d);JS_FreeCString(c, j);- return JS_ThrowTypeError(c, "request: invalid JSON");+ return js_throw_code(c, "sys.badArgument", NULL);}json_free(&d);int fds[15], nfds = 0;@@ -93,7 +94,7 @@ static JSValue f_request(JSContext *c, JSValueConst t, int argc, JSValueConst *aint32_t n = 0;JS_ToInt32(c, &n, lv);JS_FreeValue(c, lv);- if (n < 0 || n > 15) { JS_FreeCString(c, j); return JS_ThrowRangeError(c, "at most 15 files"); }+ if (n < 0 || n > 15) { JS_FreeCString(c, j); return js_throw_code(c, "mail.tooManyFiles", "max", "15", NULL); }for (int i = 0; i < n; i++) {JSValue pv = JS_GetPropertyUint32(c, argv[1], (uint32_t)i);const char *p = JS_IsString(pv) ? JS_ToCString(c, pv) : NULL;@@ -103,7 +104,7 @@ static JSValue f_request(JSContext *c, JSValueConst t, int argc, JSValueConst *aif (fd < 0) {for (int k = 0; k < nfds; k++) close(fds[k]);JS_FreeCString(c, j);- return JS_ThrowRangeError(c, "file outside the home folder or unreadable");+ return js_throw_code(c, "fs.outsideHome", NULL);}fds[nfds++] = fd;}@@ -155,7 +156,7 @@ static JSValue f_save_config(JSContext *c, JSValueConst t, int argc, JSValueCons(void)t;size_t len = 0;const char *j = arg_str(c, argc, argv, 0, &len);- if (!j) return JS_ThrowTypeError(c, "saveConfig(json)");+ if (!j) return js_throw_code(c, "sys.badArgument", NULL);JDoc d;int bad = len > MAIL_CONFIG_MAX || json_parse(j, len, &d, NULL, 0);if (!bad) {@@ -165,12 +166,12 @@ static JSValue f_save_config(JSContext *c, JSValueConst t, int argc, JSValueConsfor (const JVal *a = acc ? acc->kid : NULL; !bad && a; a = a->next) if (json_get(a, "password") || json_get(a, "secret")) bad = 1;json_free(&d);}- if (bad) { JS_FreeCString(c, j); return JS_ThrowTypeError(c, "saveConfig: invalid accounts JSON"); }+ if (bad) { JS_FreeCString(c, j); return js_throw_code(c, "mail.badAccounts", NULL); }char dir[PATH_MAX], tmp[PATH_MAX + 16];snprintf(dir, sizeof dir, "%s", mail_config_path());char *slash = strrchr(dir, '/');if (slash) *slash = 0;- if (mkdirs(dir)) { JS_FreeCString(c, j); return JS_ThrowInternalError(c, "cannot create %s", dir); }+ if (mkdirs(dir)) { JS_FreeCString(c, j); return js_throw_code(c, "sys.writeFailed", "path", dir, NULL); }snprintf(tmp, sizeof tmp, "%s.tmp", mail_config_path());int fd = open(tmp, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW, 0600);int ok = fd >= 0 && write(fd, j, len) == (ssize_t)len && fsync(fd) == 0;@@ -178,14 +179,14 @@ static JSValue f_save_config(JSContext *c, JSValueConst t, int argc, JSValueConsok = ok && rename(tmp, mail_config_path()) == 0;if (!ok) unlink(tmp);JS_FreeCString(c, j);- if (!ok) return JS_ThrowInternalError(c, "cannot write the accounts file");+ if (!ok) return js_throw_code(c, "sys.writeFailed", "path", mail_config_path(), NULL);mail_reload_config();return JS_TRUE;}static JSValue f_allow_images(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {(void)t;- if (argc < 1 || !JS_IsArray(c, argv[0])) return JS_ThrowTypeError(c, "allowImages([urls])");+ if (argc < 1 || !JS_IsArray(c, argv[0])) return js_throw_code(c, "sys.badArgument", NULL);JSValue lv = JS_GetPropertyStr(c, argv[0], "length");int32_t n = 0;JS_ToInt32(c, &n, lv);diff --git a/server/src/ui/js_media.c b/server/src/ui/js_media.cindex 6234ca7..7375011 100644--- a/server/src/ui/js_media.c+++ b/server/src/ui/js_media.c@@ -14,6 +14,7 @@#include "../media/proto.h"#include "../sec/perms.h"#include "ui.h"+#include "js_err.h"#include <ctype.h>#include <fcntl.h>@@ -97,12 +98,14 @@ static int arg_id(JSContext *c, JSValueConst v) {static int permitted(JSContext *c, const char *app, Perm p) {if (perm_get(app, p) == PERM_ALLOW) return 1;- JS_ThrowTypeError(c, "%s permission denied for %s", perm_name(p), app);+ char code[48];+ snprintf(code, sizeof code, "media.denied.%s", perm_name(p)); /* media.denied.camera, .microphone, .screen */+ js_throw_code(c, code, "app", app, NULL);return 0;}static JSValue path_error(JSContext *c, int r) {- return JS_ThrowRangeError(c, r == -2 ? "a file with that name already exists" : "invalid path or outside the home folder");+ return r == -2 ? js_throw_code(c, "media.fileExists", NULL) : js_throw_code(c, "media.outsideHome", NULL);}static const char *basename_of(const char *p) { const char *s = strrchr(p, '/'); return s ? s + 1 : p; }@@ -116,12 +119,12 @@ static JSValue f_play(JSContext *c, JSValueConst t, int argc, JSValueConst *argvconst char *app = arg_app(c, argv[0]), *path = arg_path(c, argv[1]);JSValueConst o = argc > 2 ? argv[2] : JS_UNDEFINED;JSValue ret = JS_NULL;- if (!app || !path) { ret = JS_ThrowTypeError(c, "invalid arguments"); goto out; }+ if (!app || !path) { ret = js_throw_code(c, "media.invalidArguments", NULL); goto out; }char real[PATH_MAX];int in = media_open_input(path, real, sizeof real);if (in < 0) { ret = path_error(c, -1); goto out; }MediaSrc *s = media_src_new(SK_PLAYER, app);- if (!s) { close(in); ret = JS_ThrowRangeError(c, "too many open media"); goto out; }+ if (!s) { close(in); ret = js_throw_code(c, "media.tooMany", NULL); goto out; }int ring = -1, render = -1;char appname[64];opt_str(c, o, "appName", appname, sizeof appname);@@ -136,7 +139,7 @@ static JSValue f_play(JSContext *c, JSValueConst t, int argc, JSValueConst *argvs->sock = media_spawn(MK_PLAY, params, fds, 3, &s->pid);close(in);if (render >= 0) close(render);- if (s->sock < 0) { media_src_close(s); ret = JS_ThrowRangeError(c, "could not launch lord-media"); goto out; }+ if (s->sock < 0) { media_src_close(s); ret = js_throw_code(c, "media.noHelper", NULL); goto out; }ret = JS_NewInt32(c, s->id);out:if (app) JS_FreeCString(c, app);@@ -235,7 +238,7 @@ static JSValue f_image(JSContext *c, JSValueConst t, int argc, JSValueConst *argif (in < 0) ret = path_error(c, -1);else {MediaSrc *s = media_src_new(SK_IMAGE, app);- if (!s) { close(in); ret = JS_ThrowRangeError(c, "too many open media"); }+ if (!s) { close(in); ret = js_throw_code(c, "media.tooMany", NULL); }else {s->job = media_job(0, MW_IMAGE, JP_IMAGE, &in, 1, 0, 0, NULL, NULL, NULL, s->id);ret = JS_NewInt32(c, s->id);@@ -261,14 +264,14 @@ static JSValue f_thumb(JSContext *c, JSValueConst t, int argc, JSValueConst *arg/* probe / waveform / poster: background job → "job" event with the id */static JSValue simple_job(JSContext *c, int argc, JSValueConst *argv, int kind, int purpose, int bg, int64_t def) {const char *path = argc ? arg_path(c, argv[0]) : NULL;- if (!path) return JS_ThrowTypeError(c, "invalid path");+ if (!path) return js_throw_code(c, "media.invalidPath", NULL);int in = media_open_input(path, NULL, 0);JS_FreeCString(c, path);if (in < 0) return path_error(c, -1);int32_t a = (int32_t)def;if (argc > 1 && JS_IsNumber(argv[1])) JS_ToInt32(c, &a, argv[1]);int id = media_job(bg, kind, purpose, &in, 1, a, 0, NULL, NULL, NULL, 0);- return id > 0 ? JS_NewInt32(c, id) : JS_ThrowRangeError(c, "queue full");+ return id > 0 ? JS_NewInt32(c, id) : js_throw_code(c, "media.queueFull", NULL);}static JSValue f_probe(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) { (void)t; return simple_job(c, argc, argv, MW_PROBE, JP_EVENT, 1, 0); }static JSValue f_waveform(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) { (void)t; return simple_job(c, argc, argv, MW_WAVEFORM, JP_EVENT, 0, 200); }@@ -299,7 +302,7 @@ static JSValue file_job(JSContext *c, int argc, JSValueConst *argv, int kind, coelse {int fds[2] = { in, o };int id = media_job(0, kind, JP_FILE, fds, 2, 0, 0, params, tmp, dst, 0);- ret = id > 0 ? JS_NewInt32(c, id) : JS_ThrowRangeError(c, "queue full");+ ret = id > 0 ? JS_NewInt32(c, id) : js_throw_code(c, "media.queueFull", NULL);if (id <= 0) unlink(tmp);}if (app) JS_FreeCString(c, app);@@ -344,14 +347,14 @@ static JSValue f_transcode(JSContext *c, JSValueConst t, int argc, JSValueConststatic JSValue f_screenshot(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {(void)t;const char *app = argc ? arg_app(c, argv[0]) : NULL;- if (!app) return JS_ThrowTypeError(c, "invalid app");+ if (!app) return js_throw_code(c, "media.invalidApp", NULL);JSValue ret;if (!permitted(c, app, PERM_SCREEN)) ret = JS_EXCEPTION;else {JSValueConst o = argc > 1 ? argv[1] : JS_UNDEFINED;MediaSrc *s = media_screenshot(app, opt_int(c, o, "x", 0, -65536, 65536), opt_int(c, o, "y", 0, -65536, 65536),opt_int(c, o, "width", 0, 0, 65536), opt_int(c, o, "height", 0, 0, 65536));- ret = s ? JS_NewInt32(c, s->id) : JS_ThrowRangeError(c, "could not capture");+ ret = s ? JS_NewInt32(c, s->id) : js_throw_code(c, "media.captureFailed", NULL);}JS_FreeCString(c, app);return ret;@@ -434,7 +437,7 @@ static JSValue f_save_image(JSContext *c, JSValueConst t, int argc, JSValueConst(void)t;MediaSrc *s = argc >= 2 ? media_src_get(arg_id(c, argv[0])) : NULL;const char *out = argc >= 2 ? arg_path(c, argv[1]) : NULL;- if (!s || !s->px || !out) { if (out) JS_FreeCString(c, out); return JS_ThrowTypeError(c, "invalid arguments"); }+ if (!s || !s->px || !out) { if (out) JS_FreeCString(c, out); return js_throw_code(c, "media.invalidArguments", NULL); }char tmp[PATH_MAX + 64], dst[PATH_MAX], fmt[8], params[64];opt_str(c, argc > 2 ? argv[2] : JS_UNDEFINED, "format", fmt, sizeof fmt);if (strcmp(fmt, "jpeg")) snprintf(fmt, sizeof fmt, "png");@@ -443,19 +446,19 @@ static JSValue f_save_image(JSContext *c, JSValueConst t, int argc, JSValueConstJS_FreeCString(c, out);if (o < 0) return path_error(c, o);int mfd = media_memfd_from_pixels(s->px, s->w, s->h);- if (mfd < 0) { close(o); unlink(tmp); return JS_ThrowRangeError(c, "out of memory"); }+ if (mfd < 0) { close(o); unlink(tmp); return js_throw_code(c, "sys.outOfMemory", NULL); }int fds[2] = { mfd, o };int id = media_job(0, MW_ENCODE, JP_FILE, fds, 2, s->w, s->h, params, tmp, dst, 0);- return id > 0 ? JS_NewInt32(c, id) : JS_ThrowRangeError(c, "queue full");+ return id > 0 ? JS_NewInt32(c, id) : js_throw_code(c, "media.queueFull", NULL);}/* copyImage(id) → job id: PNG to the clipboard (like an image copied in an app) */static JSValue f_copy_image(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {(void)t;MediaSrc *s = argc ? media_src_get(arg_id(c, argv[0])) : NULL;- if (!s || !s->px) return JS_ThrowTypeError(c, "invalid image");+ if (!s || !s->px) return js_throw_code(c, "media.invalidImage", NULL);const char *rt = getenv("XDG_RUNTIME_DIR");- if (!rt) return JS_ThrowRangeError(c, "no XDG_RUNTIME_DIR");+ if (!rt) return js_throw_code(c, "media.noRuntimeDir", NULL);static unsigned seq;char dir[PATH_MAX], dst[PATH_MAX + 64], tmp[PATH_MAX + 64];snprintf(dir, sizeof dir, "%s/lordos", rt);@@ -463,12 +466,12 @@ static JSValue f_copy_image(JSContext *c, JSValueConst t, int argc, JSValueConstsnprintf(dst, sizeof dst, "%s/clip-shot%d-%u.png", dir, (int)getpid(), ++seq);snprintf(tmp, sizeof tmp, "%s/.shot%d-%u.part", dir, (int)getpid(), seq);int o = open(tmp, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC | O_NOFOLLOW, 0600);- if (o < 0) return JS_ThrowRangeError(c, "could not create the file");+ if (o < 0) return js_throw_code(c, "media.createFailed", NULL);int mfd = media_memfd_from_pixels(s->px, s->w, s->h);- if (mfd < 0) { close(o); unlink(tmp); return JS_ThrowRangeError(c, "out of memory"); }+ if (mfd < 0) { close(o); unlink(tmp); return js_throw_code(c, "sys.outOfMemory", NULL); }int fds[2] = { mfd, o };int id = media_job(0, MW_ENCODE, JP_CLIP, fds, 2, s->w, s->h, "format=png\n", tmp, dst, 0);- return id > 0 ? JS_NewInt32(c, id) : JS_ThrowRangeError(c, "queue full");+ return id > 0 ? JS_NewInt32(c, id) : js_throw_code(c, "media.queueFull", NULL);}/* ---- recordings ---- */@@ -479,18 +482,18 @@ static JSValue f_screen_record(JSContext *c, JSValueConst t, int argc, JSValueCoconst char *app = argc > 0 ? arg_app(c, argv[0]) : NULL, *out = argc > 1 ? arg_path(c, argv[1]) : NULL;JSValueConst o = argc > 2 ? argv[2] : JS_UNDEFINED;JSValue ret = JS_EXCEPTION;- if (!app || !out) { ret = JS_ThrowTypeError(c, "invalid arguments"); goto out; }+ if (!app || !out) { ret = js_throw_code(c, "media.invalidArguments", NULL); goto out; }int mic = opt_int(c, o, "mic", 0, 0, 1);if (!permitted(c, app, PERM_SCREEN) || (mic && !permitted(c, app, PERM_MICROPHONE))) goto out;MediaSrc *s = media_src_new(SK_SCREENREC, app);- if (!s) { ret = JS_ThrowRangeError(c, "too many open media"); goto out; }+ if (!s) { ret = js_throw_code(c, "media.tooMany", NULL); goto out; }int fd = media_open_output(out, s->tmp, sizeof s->tmp, s->dst, sizeof s->dst);if (fd < 0) { media_src_close(s); ret = path_error(c, fd); goto out; }int ring = -1;char src[256], appname[64];opt_str(c, o, "source", src, sizeof src);opt_str(c, o, "appName", appname, sizeof appname);- if (mic) s->mic = maudio_open(1, appname[0] ? appname : app, "Grabación de pantalla", src, &ring);+ if (mic) s->mic = maudio_open(1, appname[0] ? appname : app, "Screen recording", src, &ring);int hw = opt_int(c, o, "hw", 1, 0, 1), render = hw ? media_render_fd() : -1;char params[160];int cw, chh;@@ -503,7 +506,7 @@ static JSValue f_screen_record(JSContext *c, JSValueConst t, int argc, JSValueCoif (render >= 0) close(render);if (s->sock < 0 || media_screenrec_start(s, opt_int(c, o, "fps", 30, 5, 60))) {media_src_close(s);- ret = JS_ThrowRangeError(c, "could not start recording (is a recording already running?)");+ ret = js_throw_code(c, "rec.startFailed", NULL);goto out;}ret = JS_NewInt32(c, s->id);@@ -519,22 +522,22 @@ static JSValue f_audio_record(JSContext *c, JSValueConst t, int argc, JSValueConconst char *app = argc > 0 ? arg_app(c, argv[0]) : NULL, *out = argc > 1 ? arg_path(c, argv[1]) : NULL;JSValueConst o = argc > 2 ? argv[2] : JS_UNDEFINED;JSValue ret = JS_EXCEPTION;- if (!app || !out) { ret = JS_ThrowTypeError(c, "invalid arguments"); goto out; }+ if (!app || !out) { ret = js_throw_code(c, "media.invalidArguments", NULL); goto out; }if (!permitted(c, app, PERM_MICROPHONE)) goto out;MediaSrc *s = media_src_new(SK_AUDIOREC, app);- if (!s) { ret = JS_ThrowRangeError(c, "too many open media"); goto out; }+ if (!s) { ret = js_throw_code(c, "media.tooMany", NULL); goto out; }int fd = media_open_output(out, s->tmp, sizeof s->tmp, s->dst, sizeof s->dst);if (fd < 0) { media_src_close(s); ret = path_error(c, fd); goto out; }char src[256], appname[64];opt_str(c, o, "source", src, sizeof src);opt_str(c, o, "appName", appname, sizeof appname);int ring = -1;- s->mic = maudio_open(1, appname[0] ? appname : app, "Grabación", src, &ring);- if (!s->mic) { close(fd); media_src_close(s); ret = JS_ThrowRangeError(c, "no microphone"); goto out; }+ s->mic = maudio_open(1, appname[0] ? appname : app, "Recording", src, &ring);+ if (!s->mic) { close(fd); media_src_close(s); ret = js_throw_code(c, "rec.noMicrophone", NULL); goto out; }int fds[2] = { fd, ring };s->sock = media_spawn(MK_AUDIOREC, "", fds, 2, &s->pid);close(fd);- if (s->sock < 0) { media_src_close(s); ret = JS_ThrowRangeError(c, "could not launch lord-media"); goto out; }+ if (s->sock < 0) { media_src_close(s); ret = js_throw_code(c, "media.noHelper", NULL); goto out; }ret = JS_NewInt32(c, s->id);out:if (app) JS_FreeCString(c, app);@@ -573,12 +576,12 @@ static JSValue f_camera(JSContext *c, JSValueConst t, int argc, JSValueConst *arconst char *app = argc > 0 ? arg_app(c, argv[0]) : NULL, *dev = argc > 1 ? JS_ToCString(c, argv[1]) : NULL;JSValueConst o = argc > 2 ? argv[2] : JS_UNDEFINED;JSValue ret = JS_EXCEPTION;- if (!app || !dev_ok(dev)) { ret = JS_ThrowTypeError(c, "invalid camera"); goto out; }+ if (!app || !dev_ok(dev)) { ret = js_throw_code(c, "camera.invalid", NULL); goto out; }if (!permitted(c, app, PERM_CAMERA)) goto out;int fd = open(dev, O_RDWR | O_NONBLOCK | O_CLOEXEC);- if (fd < 0) { ret = JS_ThrowRangeError(c, "could not open the camera"); goto out; }+ if (fd < 0) { ret = js_throw_code(c, "camera.openFailed", NULL); goto out; }MediaSrc *s = media_src_new(SK_CAMERA, app);- if (!s) { close(fd); ret = JS_ThrowRangeError(c, "too many open media"); goto out; }+ if (!s) { close(fd); ret = js_throw_code(c, "media.tooMany", NULL); goto out; }int render = media_render_fd();char params[96];snprintf(params, sizeof params, "width=%d\nheight=%d\nhw=%d\nhwaccel=%s\n", opt_int(c, o, "width", 1280, 160, 3840),@@ -587,7 +590,7 @@ static JSValue f_camera(JSContext *c, JSValueConst t, int argc, JSValueConst *ars->sock = media_spawn(MK_CAMERA, params, fds, 2, &s->pid);close(fd);if (render >= 0) close(render);- if (s->sock < 0) { media_src_close(s); ret = JS_ThrowRangeError(c, "could not launch lord-media"); goto out; }+ if (s->sock < 0) { media_src_close(s); ret = js_throw_code(c, "media.noHelper", NULL); goto out; }ret = JS_NewInt32(c, s->id);out:if (app) JS_FreeCString(c, app);@@ -637,7 +640,7 @@ static JSValue f_camera_record(JSContext *c, JSValueConst t, int argc, JSValueCochar appname[64];opt_str(c, o, "appName", appname, sizeof appname);maudio_close(s->mic);- s->mic = maudio_open(1, appname[0] ? appname : s->app, "Video de la cámara", "", &ring);+ s->mic = maudio_open(1, appname[0] ? appname : s->app, "Camera video", "", &ring);}int64_t v[6] = { opt_int(c, o, "mirror", 0, 0, 1), 0, 0, 0, 0, 0 };int fds[2] = { fd, ring };diff --git a/server/src/ui/js_monitor.c b/server/src/ui/js_monitor.cindex 23de849..31cbeca 100644--- a/server/src/ui/js_monitor.c+++ b/server/src/ui/js_monitor.c@@ -19,6 +19,7 @@#include "../monitor/map.h"#include "../apps.h"#include "js_sys.h"+#include "js_err.h"#include <ctype.h>#include <stdio.h>@@ -66,7 +67,7 @@ static JSValue f_info(JSContext *c, JSValueConst t, int argc, JSValueConst *argv/* the CPU model comes from the same place as About (on ARM there is no "model name") */char cpu[160];js_sys_cpu_name(cpu, sizeof cpu);- if (JS_IsObject(o) && cpu[0] && strcmp(cpu, "desconocido")) JS_SetPropertyStr(c, o, "cpuModel", JS_NewString(c, cpu));+ if (JS_IsObject(o) && cpu[0]) JS_SetPropertyStr(c, o, "cpuModel", JS_NewString(c, cpu));return o;}@@ -240,7 +241,7 @@ static int color_prop(JSContext *c, JSValueConst o, const char *k, uint32_t *out* home: { lon, lat } | null, dots: [{ lon, lat, r, sel }] }) → request number */static JSValue f_map(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {(void)t;- if (argc < 1 || !JS_IsObject(argv[0])) return JS_ThrowTypeError(c, "missing view");+ if (argc < 1 || !JS_IsObject(argv[0])) return js_throw_code(c, "sys.badArgument", NULL);JSValueConst o = argv[0];static MapReq q;memset(&q, 0, sizeof q);@@ -249,7 +250,7 @@ static JSValue f_map(JSContext *c, JSValueConst t, int argc, JSValueConst *argv)num_prop(c, o, "lon", -720, 720, &q.lon0) || num_prop(c, o, "lat", -360, 360, &q.lat0) || num_prop(c, o, "ppd", 0.1, 2000, &q.ppd) ||color_prop(c, o, "land", &q.land) || color_prop(c, o, "border", &q.border) || color_prop(c, o, "accent", &q.accent) ||color_prop(c, o, "homeColor", &q.home_color) || color_prop(c, o, "selColor", &q.sel_color))- return JS_ThrowRangeError(c, "invalid view");+ return js_throw_code(c, "sys.badArgument", NULL);q.w = (int)w;q.h = (int)h;JSValue home = JS_GetPropertyStr(c, o, "home");diff --git a/server/src/ui/js_net.c b/server/src/ui/js_net.cindex 635de86..2d83ce3 100644--- a/server/src/ui/js_net.c+++ b/server/src/ui/js_net.c@@ -5,6 +5,7 @@* changes (links, addresses, routes) arrive at __lordNet(what), with what = link | addr | route. */#include "js_net.h"#include "../net/net.h"+#include "js_err.h"#include <limits.h>#include <stdio.h>@@ -58,7 +59,7 @@ static JSValue f_config(JSContext *c, JSValueConst t, int argc, JSValueConst *ar* for admin.run('net-vpn-import', 'openvpn\n<name>\n' + text). Throws an error if something is missing. */static JSValue f_prepare_ovpn(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {(void)t;- if (argc < 1) return JS_ThrowTypeError(c, "missing path");+ if (argc < 1) return js_throw_code(c, "admin.invalidArgument", NULL);const char *p = JS_ToCString(c, argv[0]);if (!p) return JS_EXCEPTION;char real[PATH_MAX], home[PATH_MAX];@@ -67,10 +68,10 @@ static JSValue f_prepare_ovpn(JSContext *c, JSValueConst t, int argc, JSValueConsize_t hl = ok ? strlen(home) : 0;ok = ok && !strncmp(real, home, hl) && real[hl] == '/';JS_FreeCString(c, p);- if (!ok) return JS_ThrowTypeError(c, "the file must be in the home folder");+ if (!ok) return js_throw_code(c, "fs.outsideHome", NULL);char err[256] = "";char *txt = net_ovpn_inline(real, err, sizeof err);- if (!txt) return JS_ThrowTypeError(c, "%s", err);+ if (!txt) return js_throw_line(c, err);JSValue v = JS_NewString(c, txt);free(txt);return v;diff --git a/server/src/ui/js_pkg.c b/server/src/ui/js_pkg.cindex e6d0498..2f69a94 100644--- a/server/src/ui/js_pkg.c+++ b/server/src/ui/js_pkg.c@@ -358,7 +358,7 @@ static JSValue f_plan(JSContext *c, JSValueConst this_val, int argc, JSValueConsJSValue r = JS_NewObject(c);if (ni < 0 || nr < 0) {JS_SetPropertyStr(c, r, "ok", JS_FALSE);- set_s(c, r, "error", "invalid package name");+ set_s(c, r, "error", "pkg.invalidName");return r;}refresh();diff --git a/server/src/ui/js_print.c b/server/src/ui/js_print.cindex c8f3650..d3450b8 100644--- a/server/src/ui/js_print.c+++ b/server/src/ui/js_print.c@@ -13,6 +13,7 @@* scanCaps(ip, port, rs), scan(ip, port, rs, settings)*/#include "js_print.h"+#include "js_err.h"#include "../print/print.h"#include "../print/cups.h"#include "../print/escl.h"@@ -48,7 +49,7 @@ static JSValue f_discover(JSContext *c, JSValueConst t, int argc, JSValueConst *static JSValue f_cancel(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {(void)t;int32_t job = 0;- if (argc < 1 || JS_ToInt32(c, &job, argv[0]) || job <= 0) return JS_ThrowRangeError(c, "job");+ if (argc < 1 || JS_ToInt32(c, &job, argv[0]) || job <= 0) return js_throw_code(c, "sys.badArgument", NULL);JBuf b;jb_init(&b);jb_printf(&b, "{\"job\":%d}", job);@@ -59,7 +60,7 @@ static JSValue f_cancel(JSContext *c, JSValueConst t, int argc, JSValueConst *arstatic JSValue f_submit(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {(void)t;const char *printer = str_arg(c, argc, argv, 0);- if (!printer || !cups_valid_name(printer)) { if (printer) JS_FreeCString(c, printer); return JS_ThrowRangeError(c, "printer"); }+ if (!printer || !cups_valid_name(printer)) { if (printer) JS_FreeCString(c, printer); return js_throw_code(c, "print.badPrinter", NULL); }int fd = -1;size_t len = 0;if (argc > 1 && JS_IsNumber(argv[1])) {@@ -82,7 +83,7 @@ static JSValue f_submit(JSContext *c, JSValueConst t, int argc, JSValueConst *arelse if (fd >= 0) { len = (size_t)st.st_size; fcntl(fd, F_SETFL, 0); }}}- if (fd < 0) { JS_FreeCString(c, printer); return JS_ThrowRangeError(c, "document (a PDF from the home folder or a blob)"); }+ if (fd < 0) { JS_FreeCString(c, printer); return js_throw_code(c, "print.badDocument", NULL); }const char *opts = str_arg(c, argc, argv, 2);JBuf b;jb_init(&b);@@ -100,7 +101,7 @@ static JSValue f_submit(JSContext *c, JSValueConst t, int argc, JSValueConst *arstatic JSValue name_task(JSContext *c, int argc, JSValueConst *argv, const char *kind) {const char *n = str_arg(c, argc, argv, 0);- if (!n || !cups_valid_name(n)) { if (n) JS_FreeCString(c, n); return JS_ThrowRangeError(c, "name"); }+ if (!n || !cups_valid_name(n)) { if (n) JS_FreeCString(c, n); return js_throw_code(c, "print.badPrinter", NULL); }JBuf b;jb_init(&b);jb_raw(&b, "{\"name\":");@@ -130,7 +131,7 @@ static JSValue f_add(JSContext *c, JSValueConst t, int argc, JSValueConst *argv)if (u) JS_FreeCString(c, u);if (i) JS_FreeCString(c, i);if (l) JS_FreeCString(c, l);- if (!ok) { jb_free(&b); return JS_ThrowRangeError(c, "invalid name or address"); }+ if (!ok) { jb_free(&b); return js_throw_code(c, "print.badAddress", NULL); }return task(c, "add", &b, -1, 0);}@@ -155,7 +156,7 @@ static JSValue f_scan_caps(JSContext *c, JSValueConst t, int argc, JSValueConst(void)t;JBuf b;jb_init(&b);- if (scanner_args(c, argc, argv, &b)) { jb_free(&b); return JS_ThrowRangeError(c, "scanner (local network addresses only)"); }+ if (scanner_args(c, argc, argv, &b)) { jb_free(&b); return js_throw_code(c, "print.badScanner", NULL); }jb_raw(&b, "}");return task(c, "scancaps", &b, -1, 0);}@@ -164,7 +165,7 @@ static JSValue f_scan(JSContext *c, JSValueConst t, int argc, JSValueConst *argv(void)t;JBuf b;jb_init(&b);- if (scanner_args(c, argc, argv, &b)) { jb_free(&b); return JS_ThrowRangeError(c, "scanner (local network addresses only)"); }+ if (scanner_args(c, argc, argv, &b)) { jb_free(&b); return js_throw_code(c, "print.badScanner", NULL); }const char *s = str_arg(c, argc, argv, 3);JDoc d = { 0 };if (s && !json_parse(s, strlen(s), &d, NULL, 0) && d.root->type == J_OBJ) { jb_raw(&b, ",\"settings\":"); jb_raw(&b, s); }diff --git a/server/src/ui/js_sec.c b/server/src/ui/js_sec.cindex 5f80424..4f75b87 100644--- a/server/src/ui/js_sec.c+++ b/server/src/ui/js_sec.c@@ -2,6 +2,7 @@* state lives in perms.c (a file the apps cannot write). */#include "js_sec.h"#include "js_sys.h"+#include "js_err.h"#include "../sec/perms.h"#include "../sec/sign.h"#include "../sec/pkgstate.h"@@ -115,7 +116,7 @@ static JSValue f_sign_restore(JSContext *c, JSValueConst t, int argc, JSValueConchar err[160] = "";int ok = id && lpk_valid_id(id) && pkg_restore(id, err, sizeof err) == 0;if (id) JS_FreeCString(c, id);- if (!ok) return JS_ThrowInternalError(c, "%s", err[0] ? err : "could not restore");+ if (!ok) return js_throw_line(c, err[0] ? err : "pkgstate.restoreFailed");return JS_TRUE;}@@ -130,7 +131,7 @@ static JSValue f_sign_share(JSContext *c, JSValueConst t, int argc, JSValueConstchar out[1024], err[160] = "";int ok = id && manifest && rel && lpk_valid_id(id) && !js_sys_resolve_target(rel, out, sizeof out) &&pkg_share(id, manifest, mlen, out, err, sizeof err) == 0;- JSValue r = ok ? JS_NewString(c, out) : JS_ThrowInternalError(c, "%s", err[0] ? err : "could not share");+ JSValue r = ok ? JS_NewString(c, out) : js_throw_line(c, err[0] ? err : "pkgstate.shareFailed");if (id) JS_FreeCString(c, id);if (manifest) JS_FreeCString(c, manifest);if (rel) JS_FreeCString(c, rel);@@ -141,7 +142,7 @@ static JSValue f_sign_userkey(JSContext *c, JSValueConst t, int argc, JSValueCon(void)t; (void)argc; (void)argv;uint8_t seed[32];char pub[65], name[128];- if (pkg_user_key(seed, pub, name)) return JS_ThrowInternalError(c, "could not get our own key");+ if (pkg_user_key(seed, pub, name)) return js_throw_code(c, "pkgstate.keyFailed", NULL);memset(seed, 0, sizeof seed);JSValue o = JS_NewObject(c);JS_SetPropertyStr(c, o, "public", JS_NewString(c, pub));diff --git a/server/src/ui/js_sys.c b/server/src/ui/js_sys.cindex dc3df27..4795bdd 100644--- a/server/src/ui/js_sys.c+++ b/server/src/ui/js_sys.c@@ -12,6 +12,7 @@* lpk.c, nor to overwrite the settings. lord.settings only writes to ~/.config/lordos/settings.json;* lord.themes only accepts simple names. */#include "js_sys.h"+#include "js_err.h"#include "ui.h"#include "fonts.h"#include "../admin.h"@@ -118,9 +119,9 @@ static JSValue f_fs_list(JSContext *c, JSValueConst this_val, int argc, JSValueCchar dir[PATH_MAX];int bad = resolve_in_home(p, dir);JS_FreeCString(c, p);- if (bad) return JS_ThrowRangeError(c, "path outside the home folder or nonexistent");+ if (bad) return js_throw_code(c, "fs.outsideHome", NULL);DIR *d = opendir(dir);- if (!d) return JS_ThrowInternalError(c, "%s", strerror(errno));+ if (!d) return js_throw_code(c, "sys.errno", "errno", lerr_errno(errno), NULL);JSValue arr = JS_NewArray(c);uint32_t i = 0;struct dirent *e;@@ -156,13 +157,13 @@ static JSValue f_fs_read(JSContext *c, JSValueConst this_val, int argc, JSValueCchar path[PATH_MAX];int bad = resolve_in_home(p, path);JS_FreeCString(c, p);- if (bad) return JS_ThrowRangeError(c, "path outside the home folder or nonexistent");+ if (bad) return js_throw_code(c, "fs.outsideHome", NULL);struct stat st;- if (stat(path, &st) || !S_ISREG(st.st_mode)) return JS_ThrowTypeError(c, "not a file");- if (st.st_size > FS_READ_MAX) return JS_ThrowRangeError(c, "file too large (max. 8 MB)");+ if (stat(path, &st) || !S_ISREG(st.st_mode)) return js_throw_code(c, "fs.notFile", NULL);+ if (st.st_size > FS_READ_MAX) return js_throw_code(c, "fs.tooLarge", "max", "8 MB", NULL);size_t len;char *buf = read_small(path, FS_READ_MAX, &len);- if (!buf) return JS_ThrowInternalError(c, "%s", strerror(errno));+ if (!buf) return js_throw_code(c, "sys.errno", "errno", lerr_errno(errno), NULL);JSValue v = binary ? JS_NewArrayBufferCopy(c, (uint8_t *)buf, len) : JS_NewStringLen(c, buf, len);free(buf);return v;@@ -189,7 +190,7 @@ static void arm_cpu_name(const char *txt, char *out, size_t size) {if (core[0] && board && board[0]) snprintf(out, size, "%s · %s", core, board);else if (core[0]) snprintf(out, size, "%s", core);else if (board && board[0]) snprintf(out, size, "%s", board);- else snprintf(out, size, "desconocido");+ else if (size) out[0] = 0; /* unknown: the UI shows its own translated word */free(board);}@@ -298,7 +299,7 @@ static JSValue f_settings_save(JSContext *c, JSValueConst this_val, int argc, JSsize_t len;const char *txt = JS_ToCStringLen(c, &len, argv[0]);if (!txt) return JS_EXCEPTION;- if (len > SETTINGS_MAX) { JS_FreeCString(c, txt); return JS_ThrowRangeError(c, "settings too large"); }+ if (len > SETTINGS_MAX) { JS_FreeCString(c, txt); return js_throw_code(c, "settings.tooLarge", NULL); }char dir[PATH_MAX + 64], tmp[PATH_MAX + 64], path[PATH_MAX + 64];snprintf(dir, sizeof dir, "%s/.config", home);mkdir(dir, 0700);@@ -913,7 +914,7 @@ static int resolve_target(const char *path, char *out, size_t n, char *dir, sizeint js_sys_resolve_target(const char *path, char *out, size_t n) { return resolve_target(path, out, n, NULL, 0); }static JSValue fs_path_error(JSContext *c, int r) {- return r == -2 ? JS_ThrowRangeError(c, "that folder is protected") : JS_ThrowRangeError(c, "path outside the home folder or invalid");+ return js_throw_code(c, r == -2 ? "fs.protected" : "fs.outsideHome", NULL);}/* lord.fs.write(path, text | ArrayBuffer): creates or replaces the file atomically. */@@ -934,11 +935,11 @@ static JSValue f_fs_write(JSContext *c, JSValueConst this_val, int argc, JSValueif (!text) return JS_EXCEPTION;}const uint8_t *data = bin ? bin : (const uint8_t *)text;- if (len > FS_WRITE_MAX) { if (text) JS_FreeCString(c, text); return JS_ThrowRangeError(c, "file too large (max. 32 MB)"); }+ if (len > FS_WRITE_MAX) { if (text) JS_FreeCString(c, text); return js_throw_code(c, "fs.tooLarge", "max", "32 MB", NULL); }struct stat st;mode_t mode = 0644;if (!lstat(target, &st)) {- if (!S_ISREG(st.st_mode)) { if (text) JS_FreeCString(c, text); return JS_ThrowTypeError(c, "not a regular file (a link?)"); }+ if (!S_ISREG(st.st_mode)) { if (text) JS_FreeCString(c, text); return js_throw_code(c, "fs.notRegular", NULL); }mode = st.st_mode & 07777;}char tmp[PATH_MAX + 64];@@ -959,7 +960,7 @@ static JSValue f_fs_write(JSContext *c, JSValueConst this_val, int argc, JSValue}int err = errno;if (text) JS_FreeCString(c, text);- if (!ok) return JS_ThrowInternalError(c, "%s", strerror(err));+ if (!ok) return js_throw_code(c, "sys.errno", "errno", lerr_errno(err), NULL);return JS_TRUE;}@@ -972,7 +973,7 @@ static JSValue f_fs_mkdir(JSContext *c, JSValueConst this_val, int argc, JSValueint r = resolve_target(p, target, sizeof target, NULL, 0);JS_FreeCString(c, p);if (r) return fs_path_error(c, r);- if (mkdir(target, 0755) && errno != EEXIST) return JS_ThrowInternalError(c, "%s", strerror(errno));+ if (mkdir(target, 0755) && errno != EEXIST) return js_throw_code(c, "sys.errno", "errno", lerr_errno(errno), NULL);return JS_TRUE;}@@ -988,9 +989,9 @@ static JSValue f_fs_rename(JSContext *c, JSValueConst this_val, int argc, JSValuif (b) JS_FreeCString(c, b);if (r) return fs_path_error(c, r);struct stat st;- if (lstat(from, &st)) return JS_ThrowInternalError(c, "%s", strerror(errno));- if (!lstat(to, &st)) return JS_ThrowRangeError(c, "already exists");- if (rename(from, to)) return JS_ThrowInternalError(c, "%s", strerror(errno));+ if (lstat(from, &st)) return js_throw_code(c, "sys.errno", "errno", lerr_errno(errno), NULL);+ if (!lstat(to, &st)) return js_throw_code(c, "fs.exists", NULL);+ if (rename(from, to)) return js_throw_code(c, "sys.errno", "errno", lerr_errno(errno), NULL);return JS_TRUE;}@@ -1010,7 +1011,7 @@ static JSValue f_fs_copy(JSContext *c, JSValueConst this_val, int argc, JSValueCif (b) JS_FreeCString(c, b);if (r) return fs_path_error(c, r);int id = fsjob_start(from, to, move, err, sizeof err);- if (id < 0) return JS_ThrowInternalError(c, "%s", err);+ if (id < 0) return js_throw_line(c, err);return JS_NewInt32(c, id);}@@ -1064,7 +1065,7 @@ static JSValue f_fs_trash(JSContext *c, JSValueConst this_val, int argc, JSValueint r = resolve_target(p, target, sizeof target, NULL, 0);JS_FreeCString(c, p);if (r) return fs_path_error(c, r);- if (fstrash_put(target, err, sizeof err)) return JS_ThrowInternalError(c, "%s", err);+ if (fstrash_put(target, err, sizeof err)) return js_throw_line(c, err);return JS_TRUE;}@@ -1096,7 +1097,7 @@ static JSValue trash_id_op(JSContext *c, JSValueConst arg, int (*op)(const charchar err[256] = "";int r = op(id, err, sizeof err);JS_FreeCString(c, id);- if (r) return JS_ThrowInternalError(c, "%s", err);+ if (r) return js_throw_line(c, err);return JS_TRUE;}static JSValue f_fs_restore(JSContext *c, JSValueConst this_val, int argc, JSValueConst *argv) {@@ -1122,7 +1123,7 @@ static JSValue f_fs_stat(JSContext *c, JSValueConst this_val, int argc, JSValueCJS_FreeCString(c, p);if (r == -1) return fs_path_error(c, r);struct statx sx;- if (statx(AT_FDCWD, target, AT_SYMLINK_NOFOLLOW, STATX_BASIC_STATS | STATX_BTIME, &sx)) return JS_ThrowInternalError(c, "%s", strerror(errno));+ if (statx(AT_FDCWD, target, AT_SYMLINK_NOFOLLOW, STATX_BASIC_STATS | STATX_BTIME, &sx)) return js_throw_code(c, "sys.errno", "errno", lerr_errno(errno), NULL);JSValue o = JS_NewObject(c);const char *base = strrchr(target, '/');JS_SetPropertyStr(c, o, "name", JS_NewString(c, base ? base + 1 : target));@@ -1187,7 +1188,7 @@ static JSValue f_fs_free(JSContext *c, JSValueConst this_val, int argc, JSValueCJS_FreeCString(c, p);if (bad) return fs_path_error(c, -1);struct statvfs vs;- if (statvfs(path, &vs)) return JS_ThrowInternalError(c, "%s", strerror(errno));+ if (statvfs(path, &vs)) return js_throw_code(c, "sys.errno", "errno", lerr_errno(errno), NULL);JSValue o = JS_NewObject(c);JS_SetPropertyStr(c, o, "total", JS_NewFloat64(c, (double)vs.f_blocks * vs.f_frsize));JS_SetPropertyStr(c, o, "free", JS_NewFloat64(c, (double)vs.f_bavail * vs.f_frsize));@@ -1469,12 +1470,12 @@ static JSValue lpk_check(JSContext *c, JSValueConst arg, int install) {char path[PATH_MAX];int bad = resolve_in_home(p, path);JS_FreeCString(c, p);- if (bad) return JS_ThrowRangeError(c, "path outside the home folder or nonexistent");+ if (bad) return js_throw_code(c, "fs.outsideHome", NULL);Lpk pk;char err[160];- if (lpk_open(path, &pk, err, sizeof err)) return JS_ThrowTypeError(c, "%s", err);+ if (lpk_open(path, &pk, err, sizeof err)) return js_throw_line(c, err);const LpkFile *mf = lpk_find(&pk, "manifest.json");- if (!mf || !lpk_find(&pk, "app.js")) { lpk_free(&pk); return JS_ThrowTypeError(c, "not a LordOS package (manifest.json or app.js missing)"); }+ if (!mf || !lpk_find(&pk, "app.js")) { lpk_free(&pk); return js_throw_code(c, "lpk.notPackage", NULL); }char *txt = malloc(mf->size + 1);if (!txt) { lpk_free(&pk); return JS_ThrowOutOfMemory(c); }memcpy(txt, mf->data, mf->size);@@ -1485,25 +1486,25 @@ static JSValue lpk_check(JSContext *c, JSValueConst arg, int install) {JS_FreeValue(c, JS_GetException(c));JS_FreeValue(c, m);lpk_free(&pk);- return JS_ThrowTypeError(c, "invalid manifest.json");+ return js_throw_code(c, "lpk.badManifest", NULL);}char id[64], ver[48], name[128], icon[224];const char *why = NULL;- if (!str_prop(c, m, "id", id, sizeof id) || !lpk_valid_id(id)) why = "the app id is invalid (a-z, 0-9 and -)";- else if (lpk_reserved(id)) why = "the app id is reserved by LordOS";- else if (!str_prop_tr(c, m, "name", name, sizeof name, 1)) why = "the app name is missing";- else if (!str_prop(c, m, "version", ver, sizeof ver) || !valid_version(ver)) why = "the version is invalid";+ if (!str_prop(c, m, "id", id, sizeof id) || !lpk_valid_id(id)) why = "lpk.badId";+ else if (lpk_reserved(id)) why = "lpk.reservedId";+ else if (!str_prop_tr(c, m, "name", name, sizeof name, 1)) why = "lpk.noName";+ else if (!str_prop(c, m, "version", ver, sizeof ver) || !valid_version(ver)) why = "lpk.badVersion";else if (!str_prop(c, m, "icon", icon, sizeof icon) || !lpk_find(&pk, icon) || strlen(icon) < 5 || strcmp(icon + strlen(icon) - 4, ".png"))- why = "the app must ship its own icon (a .png from the package in \"icon\")";- if (why) { JS_FreeValue(c, m); lpk_free(&pk); return JS_ThrowTypeError(c, "%s", why); }+ why = "lpk.noIcon";+ if (why) { JS_FreeValue(c, m); lpk_free(&pk); return js_throw_code(c, why, NULL); }/* Signature: checks hashes and signature; rejects an altered or revoked package, and when installing* requires the update rule (same key as the installed version). See docs/SIGNING.md. */LpkSigInfo si;- if (sig_verify_package(&pk, id, ver, &si, err, sizeof err)) { JS_FreeValue(c, m); lpk_free(&pk); return JS_ThrowTypeError(c, "the package is damaged or badly signed: %s", err); }- if (si.revoked) { JS_FreeValue(c, m); lpk_free(&pk); return JS_ThrowTypeError(c, "%s", si.revoked_why); }+ if (sig_verify_package(&pk, id, ver, &si, err, sizeof err)) { JS_FreeValue(c, m); lpk_free(&pk); return js_throw_code(c, "lpk.badSignature", "reason", err, NULL); }+ if (si.revoked) { JS_FreeValue(c, m); lpk_free(&pk); return js_throw_line(c, si.revoked_why); }if (install) {- if (pkg_check_update(id, &si, err, sizeof err)) { JS_FreeValue(c, m); lpk_free(&pk); return JS_ThrowTypeError(c, "%s", err); }- if (lpk_install(&pk, id, err, sizeof err)) { JS_FreeValue(c, m); lpk_free(&pk); return JS_ThrowInternalError(c, "%s", err); }+ if (pkg_check_update(id, &si, err, sizeof err)) { JS_FreeValue(c, m); lpk_free(&pk); return js_throw_line(c, err); }+ if (lpk_install(&pk, id, err, sizeof err)) { JS_FreeValue(c, m); lpk_free(&pk); return js_throw_line(c, err); }pkg_keep_original(id, path); /* the original .lpk, for "Restore" and to detect changes */}size_t total = 0;@@ -1592,7 +1593,7 @@ static JSValue f_apps_load(JSContext *c, JSValueConst this_val, int argc, JSValuchar name[96];snprintf(name, sizeof name, "lpk:%s/app.js", id);JS_FreeCString(c, id);- if (!src) return JS_ThrowTypeError(c, "the app is not installed");+ if (!src) return js_throw_code(c, "lpk.notInstalled", NULL);JSValue r = JS_Eval(c, src, len, name, JS_EVAL_TYPE_GLOBAL);free(src);if (JS_IsException(r)) return r;@@ -1614,7 +1615,7 @@ static JSValue f_apps_file(JSContext *c, JSValueConst this_val, int argc, JSValuchar *buf = id && rel ? lpk_read(id, rel, 32 * 1024 * 1024, &len) : NULL;if (id) JS_FreeCString(c, id);if (rel) JS_FreeCString(c, rel);- if (!buf) return JS_ThrowTypeError(c, "file does not exist in the app");+ if (!buf) return js_throw_code(c, "lpk.noFile", NULL);JSValue v = JS_NewArrayBufferCopy(c, (uint8_t *)buf, len);free(buf);return v;diff --git a/server/src/ui/js_term.c b/server/src/ui/js_term.cindex 7572b07..7cb2aae 100644--- a/server/src/ui/js_term.c+++ b/server/src/ui/js_term.c@@ -7,6 +7,7 @@#include "ui.h"#include "../term/term.h"#include "js_sys.h"+#include "js_err.h"#include <fcntl.h>#include <limits.h>@@ -62,7 +63,7 @@ static JSValue f_create(JSContext *c, JSValueConst this_val, int argc, JSValueCoscrollback = (int)num(c, argv[0], "scrollback", 0);}Session *s = term_create(cwd[0] ? cwd : NULL, scrollback);- if (!s) return JS_ThrowInternalError(c, "could not create the terminal");+ if (!s) return js_throw_code(c, "term.createFailed", NULL);return JS_NewInt32(c, s->id);}@@ -710,7 +711,7 @@ static JSValue f_clip_save_image(JSContext *c, JSValueConst this_val, int argc,char dst[PATH_MAX + 300];int r = js_sys_resolve_target(p, dst, sizeof dst);JS_FreeCString(c, p);- if (r) return JS_ThrowRangeError(c, "path outside the home folder or protected");+ if (r) return js_throw_code(c, "fs.outsideHome", NULL);size_t n = 0;FILE *in = fopen(src, "rb");if (!in) return JS_FALSE;diff --git a/server/src/ui/js_vault.c b/server/src/ui/js_vault.cindex 13a39bd..6b9abba 100644--- a/server/src/ui/js_vault.c+++ b/server/src/ui/js_vault.c@@ -1,21 +1,22 @@-/* js_vault.c — lord.vault: Contraseñas y el llavero por el ayudante encerrado lord-vault (ver- * src/vault/vclient.c y docs/CONTRASENAS.md).+/* js_vault.c — lord.vault: Passwords and the keyring through the confined helper lord-vault (see+ * src/vault/vclient.c and docs/PASSWORDS.md).** lord.vault.available() → bool* lord.vault.request(json, { files }) → id; files: [{ path, mode: 'r' | 'w' }]- * 'r' = archivo existente de la carpeta personal o un disco del usuario (realpath + raíces);- * 'w' = archivo NUEVO (O_EXCL) en un destino válido de lord.fs. lord-server los abre y le- * pasa solo los fds a lord-vault, que no puede abrir rutas.- * lord.vault.poll() → texto JSON [{ id, kind: 'rep'|'evt', data }] o null- * lord.vault.pending() → pedidos sin respuesta- * lord.vault.lock(why) → cerrar la bóveda (pantalla, cambio de usuario)- * lord.vault.fidoDevices() → [{ path, name, vid, pid }] (sin abrirlas)- * lord.vault.fidoAttach(app) → { ok, name } — solo con el permiso usb de la app:- * lord-server abre /dev/hidrawN y le pasa el fd a lord-vault; la app nunca lo ve.- * lord.vault.promptDone(prompt, ok) → respuesta al aviso de desbloqueo de Secret Service- * Todo validado acá; nada de esto ejecuta programas ni abre rutas del llamador sin validarlas. */+ * 'r' = an existing file in the home folder or on one of the user's disks (realpath + roots);+ * 'w' = a NEW file (O_EXCL) in a valid lord.fs destination. lord-server opens them and+ * passes only the fds to lord-vault, which cannot open paths.+ * lord.vault.poll() → JSON text [{ id, kind: 'rep'|'evt', data }] or null+ * lord.vault.pending() → requests without a reply+ * lord.vault.lock(why) → lock the vault (screen lock, user switch)+ * lord.vault.fidoDevices() → [{ path, name, vid, pid }] (without opening them)+ * lord.vault.fidoAttach(app) → { ok, name } — only with the app's usb permission:+ * lord-server opens /dev/hidrawN and passes the fd to lord-vault; the app never sees it.+ * lord.vault.promptDone(prompt, ok) → answer to Secret Service's unlock prompt+ * Everything is validated here; none of this runs programs or opens caller paths without validating them. */#include "js_vault.h"#include "js_sys.h"+#include "js_err.h"#include "../fsops.h"#include "../sec/perms.h"#include "../vault/vclient.h"@@ -61,11 +62,11 @@ static JSValue f_available(JSContext *c, JSValueConst t, int argc, JSValueConststatic JSValue f_request(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {(void)t;- if (argc < 1 || !JS_IsString(argv[0])) return JS_ThrowTypeError(c, "vault.request(json)");+ if (argc < 1 || !JS_IsString(argv[0])) return js_throw_code(c, "sys.badArgument", NULL);size_t len;const char *j = JS_ToCStringLen(c, &len, argv[0]);if (!j) return JS_EXCEPTION;- if (len > (32u << 20)) { JS_FreeCString(c, j); return JS_ThrowRangeError(c, "pedido muy grande"); }+ if (len > (32u << 20)) { JS_FreeCString(c, j); return js_throw_code(c, "vault.requestTooLarge", NULL); }int fds[4], nf = 0;if (argc > 1 && JS_IsObject(argv[1])) {JSValue files = JS_GetPropertyStr(c, argv[1], "files");@@ -88,7 +89,7 @@ static JSValue f_request(JSContext *c, JSValueConst t, int argc, JSValueConst *afor (int k = 0; k < nf; k++) close(fds[k]);JS_FreeValue(c, files);JS_FreeCString(c, j);- return JS_ThrowRangeError(c, err == EEXIST ? "ya existe un archivo con ese nombre" : "archivo inválido o fuera de la carpeta personal");+ return js_throw_code(c, err == EEXIST ? "fs.exists" : "fs.outsideHome", NULL);}fds[nf++] = fd;}@@ -97,7 +98,7 @@ static JSValue f_request(JSContext *c, JSValueConst t, int argc, JSValueConst *a}int id = vc_request(j, len, fds, nf);JS_FreeCString(c, j);- if (id < 0) return JS_ThrowInternalError(c, "lord-vault no está disponible");+ if (id < 0) return js_throw_code(c, "vault.unavailable", NULL);return JS_NewInt32(c, id);}@@ -144,7 +145,7 @@ static JSValue f_fido_attach(JSContext *c, JSValueConst t, int argc, JSValueConsconst char *app = argc > 0 && JS_IsString(argv[0]) ? JS_ToCString(c, argv[0]) : NULL;int ok = app && perm_get(app, PERM_USB) == PERM_ALLOW;if (app) JS_FreeCString(c, app);- if (!ok) return JS_ThrowTypeError(c, "permiso usb denegado");+ if (!ok) return js_throw_code(c, "perm.usbDenied", NULL);char name[128] = "";int r = vc_fido_attach(name, sizeof name);JSValue o = JS_NewObject(c);@@ -177,7 +178,7 @@ void js_vault_register(JSContext *c, JSValue lord) {JSValue o = JS_NewObject(c);JS_SetPropertyFunctionList(c, o, vault_funcs, sizeof vault_funcs / sizeof vault_funcs[0]);JS_SetPropertyStr(c, lord, "vault", o);- vc_start(); /* el llavero y Secret Service andan desde el comienzo de la sesión */+ vc_start(); /* the keyring and Secret Service run from the start of the session */}/* ================= app mode =================@@ -199,8 +200,8 @@ static JSValue fa_available(JSContext *c, JSValueConst t, int argc, JSValueConststatic JSValue fa_request(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {(void)t;- if (app_fd < 0) return JS_ThrowInternalError(c, "lord-vault is not available");- if (argc < 1 || !JS_IsString(argv[0])) return JS_ThrowTypeError(c, "vault.request(json)");+ if (app_fd < 0) return js_throw_code(c, "vault.unavailable", NULL);+ if (argc < 1 || !JS_IsString(argv[0])) return js_throw_code(c, "sys.badArgument", NULL);size_t len;const char *j = JS_ToCStringLen(c, &len, argv[0]);if (!j) return JS_EXCEPTION;@@ -227,7 +228,7 @@ static JSValue fa_request(JSContext *c, JSValueConst t, int argc, JSValueConst *int r = vw_send(app_fd, VW_REQ, id, j, len, fds, nf);JS_FreeCString(c, j);for (int i = 0; i < nf; i++) close(fds[i]); /* the powerbox fds are spent */- if (r) return JS_ThrowInternalError(c, "lord-vault is not available");+ if (r) return js_throw_code(c, "vault.unavailable", NULL);app_inflight++;return JS_NewInt32(c, (int32_t)id);}diff --git a/server/src/ui/js_wasm.c b/server/src/ui/js_wasm.cindex 2cc78b6..d90bfd8 100644--- a/server/src/ui/js_wasm.c+++ b/server/src/ui/js_wasm.c@@ -64,8 +64,8 @@ static JSValue throw_wasm(JSContext *c, const WasmError *err) {return throw_cls(c, err_runtime, err->msg);case WASM_ERR_MALFORMED: case WASM_ERR_INVALID: return throw_cls(c, err_compile, err->msg);case WASM_ERR_LINK: return throw_cls(c, err_link, err->msg);- case WASM_ERR_EXHAUSTED: return JS_ThrowRangeError(c, "%s", err->msg);- case WASM_ERR_NOMEM: return JS_ThrowRangeError(c, "%s", err->msg);+ case WASM_ERR_EXHAUSTED: return JS_ThrowRangeError(c, "%s", err->msg); /* i18n-ok: WebAssembly API */+ case WASM_ERR_NOMEM: return JS_ThrowRangeError(c, "%s", err->msg); /* i18n-ok: WebAssembly API */default: return throw_cls(c, err_runtime, err->msg);}}@@ -125,12 +125,12 @@ static int to_wasm(JSContext *c, JSValueConst v, uint8_t type, WasmVal *out) {case WASM_FUNCREF: {if (JS_IsNull(v)) return 0;WasmFunc *f = JS_GetOpaque(v, cls_func);- if (!f) { JS_ThrowTypeError(c, "expected an exported WebAssembly function or null"); return -1; }+ if (!f) { JS_ThrowTypeError(c, "expected an exported WebAssembly function or null"); return -1; } /* i18n-ok: WebAssembly API */out->ref = f;return 0;}}- JS_ThrowTypeError(c, "unsupported value type");+ JS_ThrowTypeError(c, "unsupported value type"); /* i18n-ok: WebAssembly API */return -1;}@@ -195,7 +195,7 @@ out:static JSValue fn_call(JSContext *c, JSValueConst func_obj, JSValueConst this_val, int argc, JSValueConst *argv, int flags) {(void)this_val; (void)flags;WasmFunc *f = JS_GetOpaque(func_obj, cls_func);- if (!f) return JS_ThrowTypeError(c, "not a WebAssembly function");+ if (!f) return JS_ThrowTypeError(c, "not a WebAssembly function"); /* i18n-ok: WebAssembly API */return call_wasm(c, f, argc, argv);}@@ -277,7 +277,7 @@ static uint8_t *get_bytes(JSContext *c, JSValueConst v, size_t *len) {JSValue buf = JS_GetTypedArrayBuffer(c, v, &off, &blen, &per);if (JS_IsException(buf)) {JS_FreeValue(c, JS_GetException(c));- JS_ThrowTypeError(c, "expected an ArrayBuffer or a view (Uint8Array...)");+ JS_ThrowTypeError(c, "expected an ArrayBuffer or a view (Uint8Array...)"); /* i18n-ok: WebAssembly API */return NULL;}p = JS_GetArrayBuffer(c, &n, buf);@@ -325,7 +325,7 @@ static const char *kind_name(int k) {static JSValue module_exports(JSContext *c, JSValueConst this_val, int argc, JSValueConst *argv) {(void)this_val;WasmModule *m = argc ? JS_GetOpaque(argv[0], cls_module) : NULL;- if (!m) return JS_ThrowTypeError(c, "expected a WebAssembly.Module");+ if (!m) return JS_ThrowTypeError(c, "expected a WebAssembly.Module"); /* i18n-ok: WebAssembly API */JSValue arr = JS_NewArray(c);for (uint32_t i = 0; i < wasm_module_num_exports(m); i++) {size_t len;@@ -341,7 +341,7 @@ static JSValue module_exports(JSContext *c, JSValueConst this_val, int argc, JSVstatic JSValue module_imports(JSContext *c, JSValueConst this_val, int argc, JSValueConst *argv) {(void)this_val;WasmModule *m = argc ? JS_GetOpaque(argv[0], cls_module) : NULL;- if (!m) return JS_ThrowTypeError(c, "expected a WebAssembly.Module");+ if (!m) return JS_ThrowTypeError(c, "expected a WebAssembly.Module"); /* i18n-ok: WebAssembly API */JSValue arr = JS_NewArray(c);for (uint32_t i = 0; i < wasm_module_num_imports(m); i++) {size_t ml, nl;@@ -358,7 +358,7 @@ static JSValue module_imports(JSContext *c, JSValueConst this_val, int argc, JSVstatic JSValue module_custom(JSContext *c, JSValueConst this_val, int argc, JSValueConst *argv) {(void)this_val;WasmModule *m = argc ? JS_GetOpaque(argv[0], cls_module) : NULL;- if (!m) return JS_ThrowTypeError(c, "expected a WebAssembly.Module");+ if (!m) return JS_ThrowTypeError(c, "expected a WebAssembly.Module"); /* i18n-ok: WebAssembly API */const char *nm = JS_ToCString(c, argc > 1 ? argv[1] : JS_UNDEFINED);if (!nm) return JS_EXCEPTION;JSValue arr = JS_NewArray(c);@@ -420,20 +420,20 @@ static int desc_u32(JSContext *c, JSValueConst d, const char *key, uint32_t lim,int r = JS_ToFloat64(c, &x, v);JS_FreeValue(c, v);if (r) return -1;- if (x != x || x < 0 || x > lim || isinf(x)) { JS_ThrowTypeError(c, "%s out of range", key); return -1; }+ if (x != x || x < 0 || x > lim || isinf(x)) { JS_ThrowTypeError(c, "%s out of range", key); return -1; } /* i18n-ok: WebAssembly API */*out = (uint32_t)x;return 0;}static int limits_desc(JSContext *c, JSValueConst d, uint32_t lim, uint32_t *min, uint32_t *max) {- if (!JS_IsObject(d)) { JS_ThrowTypeError(c, "expected a descriptor"); return -1; }+ if (!JS_IsObject(d)) { JS_ThrowTypeError(c, "expected a descriptor"); return -1; } /* i18n-ok: WebAssembly API */int r = desc_u32(c, d, "initial", lim, min);if (r == 1) r = desc_u32(c, d, "minimum", lim, min);- if (r) { if (r == 1) JS_ThrowTypeError(c, "missing initial"); return -1; }+ if (r) { if (r == 1) JS_ThrowTypeError(c, "missing initial"); return -1; } /* i18n-ok: WebAssembly API */*max = WASM_NO_MAX;r = desc_u32(c, d, "maximum", lim, max);if (r < 0) return -1;- if (*max != WASM_NO_MAX && *max < *min) { JS_ThrowRangeError(c, "maximum less than initial"); return -1; }+ if (*max != WASM_NO_MAX && *max < *min) { JS_ThrowRangeError(c, "maximum less than initial"); return -1; } /* i18n-ok: WebAssembly API */return 0;}@@ -443,7 +443,7 @@ static JSValue memory_ctor(JSContext *c, JSValueConst new_target, int argc, JSVaif (limits_desc(c, argc ? argv[0] : JS_UNDEFINED, 65536, &min, &max)) return JS_EXCEPTION;WasmError err;WasmMemory *m = wasm_memory_new(min, max, &err);- if (!m) return JS_ThrowRangeError(c, "%s", err.msg);+ if (!m) return JS_ThrowRangeError(c, "%s", err.msg); /* i18n-ok: WebAssembly API */JSValue o = memory_obj(c, m);wasm_memory_unref(m);return o;@@ -467,9 +467,9 @@ static JSValue memory_grow(JSContext *c, JSValueConst this_val, int argc, JSValuif (!m) return JS_EXCEPTION;double d;if (JS_ToFloat64(c, &d, argc ? argv[0] : JS_UNDEFINED)) return JS_EXCEPTION;- if (d != d || d < 0 || d > 65536) return JS_ThrowTypeError(c, "delta out of range");+ if (d != d || d < 0 || d > 65536) return JS_ThrowTypeError(c, "delta out of range"); /* i18n-ok: WebAssembly API */int64_t r = wasm_memory_grow(m, (uint32_t)d);- if (r < 0) return JS_ThrowRangeError(c, "could not grow the memory");+ if (r < 0) return JS_ThrowRangeError(c, "could not grow the memory"); /* i18n-ok: WebAssembly API */return JS_NewInt64(c, r);}@@ -498,7 +498,7 @@ static JSValue table_obj(JSContext *c, WasmTable *t) {static JSValue table_ctor(JSContext *c, JSValueConst new_target, int argc, JSValueConst *argv) {(void)new_target;JSValueConst d = argc ? argv[0] : JS_UNDEFINED;- if (!JS_IsObject(d)) return JS_ThrowTypeError(c, "expected a descriptor");+ if (!JS_IsObject(d)) return JS_ThrowTypeError(c, "expected a descriptor"); /* i18n-ok: WebAssembly API */JSValue ev = JS_GetPropertyStr(c, d, "element");const char *es = JS_ToCString(c, ev);JS_FreeValue(c, ev);@@ -506,14 +506,14 @@ static JSValue table_ctor(JSContext *c, JSValueConst new_target, int argc, JSValuint8_t type;int bad = valtype_from_str(es, &type) || (type != WASM_FUNCREF && type != WASM_EXTERNREF);JS_FreeCString(c, es);- if (bad) return JS_ThrowTypeError(c, "element must be 'anyfunc' or 'externref'");+ if (bad) return JS_ThrowTypeError(c, "element must be 'anyfunc' or 'externref'"); /* i18n-ok: WebAssembly API */uint32_t min, max;if (limits_desc(c, d, 10000000, &min, &max)) return JS_EXCEPTION;WasmVal init;if (default_or(c, argc, argv, 1, type, &init)) return JS_EXCEPTION;WasmError err;WasmTable *t = wasm_table_new(type, min, max, init, &err);- if (!t) return JS_ThrowRangeError(c, "%s", err.msg);+ if (!t) return JS_ThrowRangeError(c, "%s", err.msg); /* i18n-ok: WebAssembly API */JSValue o = table_obj(c, t);wasm_table_unref(t);return o;@@ -528,7 +528,7 @@ static JSValue table_length(JSContext *c, JSValueConst this_val) {static int index_arg(JSContext *c, int argc, JSValueConst *argv, int i, uint32_t *out) {double d;if (JS_ToFloat64(c, &d, i < argc ? argv[i] : JS_UNDEFINED)) return -1;- if (d != d || d < 0 || d > 4294967295.0) { JS_ThrowTypeError(c, "index out of range"); return -1; }+ if (d != d || d < 0 || d > 4294967295.0) { JS_ThrowTypeError(c, "index out of range"); return -1; } /* i18n-ok: WebAssembly API */*out = (uint32_t)d;return 0;}@@ -538,7 +538,7 @@ static JSValue table_get(JSContext *c, JSValueConst this_val, int argc, JSValueCuint32_t i;if (!t || index_arg(c, argc, argv, 0, &i)) return JS_EXCEPTION;WasmVal v;- if (wasm_table_get(t, i, &v)) return JS_ThrowRangeError(c, "index outside the table");+ if (wasm_table_get(t, i, &v)) return JS_ThrowRangeError(c, "index outside the table"); /* i18n-ok: WebAssembly API */return from_wasm(c, wasm_table_elemtype(t), v);}@@ -548,7 +548,7 @@ static JSValue table_set(JSContext *c, JSValueConst this_val, int argc, JSValueCif (!t || index_arg(c, argc, argv, 0, &i)) return JS_EXCEPTION;WasmVal v;if (default_or(c, argc, argv, 1, wasm_table_elemtype(t), &v)) return JS_EXCEPTION;- if (wasm_table_set(t, i, v)) return JS_ThrowRangeError(c, "index outside the table");+ if (wasm_table_set(t, i, v)) return JS_ThrowRangeError(c, "index outside the table"); /* i18n-ok: WebAssembly API */return JS_UNDEFINED;}@@ -559,7 +559,7 @@ static JSValue table_grow(JSContext *c, JSValueConst this_val, int argc, JSValueWasmVal v;if (default_or(c, argc, argv, 1, wasm_table_elemtype(t), &v)) return JS_EXCEPTION;int64_t r = wasm_table_grow(t, n, v);- if (r < 0) return JS_ThrowRangeError(c, "could not grow the table");+ if (r < 0) return JS_ThrowRangeError(c, "could not grow the table"); /* i18n-ok: WebAssembly API */return JS_NewInt64(c, r);}@@ -588,7 +588,7 @@ static JSValue global_obj(JSContext *c, WasmGlobal *g) {static JSValue global_ctor(JSContext *c, JSValueConst new_target, int argc, JSValueConst *argv) {(void)new_target;JSValueConst d = argc ? argv[0] : JS_UNDEFINED;- if (!JS_IsObject(d)) return JS_ThrowTypeError(c, "expected a descriptor");+ if (!JS_IsObject(d)) return JS_ThrowTypeError(c, "expected a descriptor"); /* i18n-ok: WebAssembly API */JSValue tv = JS_GetPropertyStr(c, d, "value"), mv = JS_GetPropertyStr(c, d, "mutable");const char *ts = JS_ToCString(c, tv);int mut = JS_ToBool(c, mv);@@ -598,7 +598,7 @@ static JSValue global_ctor(JSContext *c, JSValueConst new_target, int argc, JSVauint8_t type;int bad = valtype_from_str(ts, &type);JS_FreeCString(c, ts);- if (bad) return JS_ThrowTypeError(c, "unknown global type");+ if (bad) return JS_ThrowTypeError(c, "unknown global type"); /* i18n-ok: WebAssembly API */WasmVal v;if (default_or(c, argc, argv, 1, type, &v)) return JS_EXCEPTION;WasmGlobal *g = wasm_global_new(type, mut, v);@@ -617,7 +617,7 @@ static JSValue global_value(JSContext *c, JSValueConst this_val) {static JSValue global_set_value(JSContext *c, JSValueConst this_val, JSValueConst val) {WasmGlobal *g = JS_GetOpaque2(c, this_val, cls_global);if (!g) return JS_EXCEPTION;- if (!wasm_global_mut(g)) return JS_ThrowTypeError(c, "the global is not mutable");+ if (!wasm_global_mut(g)) return JS_ThrowTypeError(c, "the global is not mutable"); /* i18n-ok: WebAssembly API */WasmVal v;if (to_wasm(c, val, wasm_global_type(g), &v)) return JS_EXCEPTION;wasm_global_set(g, v);@@ -663,7 +663,7 @@ static JSValue link_error(JSContext *c, const char *mod, const char *name, const/* Instantiates m with the imports object: the JS Instance, or an exception. */static JSValue instantiate(JSContext *c, WasmModule *m, JSValueConst imports) {uint32_t n = wasm_module_num_imports(m);- if (n && !JS_IsObject(imports)) return JS_ThrowTypeError(c, "the module has imports: the imports object is missing");+ if (n && !JS_IsObject(imports)) return JS_ThrowTypeError(c, "the module has imports: the imports object is missing"); /* i18n-ok: WebAssembly API */WasmExtern *ext = calloc(n + 1, sizeof *ext);uint8_t *temp = calloc(n + 1, 1); /* created here (they must be released) */JSValue ret = JS_EXCEPTION;@@ -674,7 +674,7 @@ static JSValue instantiate(JSContext *c, WasmModule *m, JSValueConst imports) {WasmExternType t = wasm_import_type(m, i);JSValue o = get_prop_len(c, imports, mod, ml);if (JS_IsException(o)) goto out;- if (!JS_IsObject(o)) { JS_FreeValue(c, o); ret = JS_ThrowTypeError(c, "import %s: not an object", mod); goto out; }+ if (!JS_IsObject(o)) { JS_FreeValue(c, o); ret = JS_ThrowTypeError(c, "import %s: not an object", mod); goto out; } /* i18n-ok: WebAssembly API */JSValue v = get_prop_len(c, o, nm, nl);JS_FreeValue(c, o);if (JS_IsException(v)) goto out;@@ -744,7 +744,7 @@ out:static JSValue instance_ctor(JSContext *c, JSValueConst new_target, int argc, JSValueConst *argv) {(void)new_target;WasmModule *m = argc ? JS_GetOpaque(argv[0], cls_module) : NULL;- if (!m) return JS_ThrowTypeError(c, "expected a WebAssembly.Module");+ if (!m) return JS_ThrowTypeError(c, "expected a WebAssembly.Module"); /* i18n-ok: WebAssembly API */return instantiate(c, m, argc > 1 ? argv[1] : JS_UNDEFINED);}diff --git a/server/src/ui/layout.c b/server/src/ui/layout.cindex a8d3eec..5f57e43 100644--- a/server/src/ui/layout.c+++ b/server/src/ui/layout.c@@ -6,11 +6,51 @@** `direction: 'rtl'` (inherited, as in CSS) flips the main axis of rows and the* cross-axis start of columns; left/right, margins and paddings remain- * physical (as in CSS), so absolute positions —windows, menus— don't change. */+ * physical (as in CSS), so absolute positions —windows, menus— don't change. The logical ones+ * (marginStart/End, paddingStart/End, start/end, borderStart/End…) are mapped to a physical side+ * by the node's own direction (node_resolve_edges) and win over the physical one, as in React Native. */#include "ui.h"#include <math.h>#include <stdlib.h>+#include <string.h>++/* The node's effective direction (its own, or inherited) and, if it has per-side or logical edges,+ * those edges for that direction. The parent is always prepared first (layout and measure go from+ * the root down). */+static inline void prepare(Node *n) {+ n->rtl = n->s.dir == DIR_RTL ? 1 : n->s.dir == DIR_LTR ? 0 : n->parent ? n->parent->rtl : ui.rtl;+ StyleExt *x = n->s.ext;+ if (x && (!x->r.ok || x->r.rtl != n->rtl)) node_resolve_edges(n);+}++void node_resolve_edges(Node *n) {+ const Style *s = &n->s;+ StyleExt *x = s->ext;+ if (!x) return;+ uint32_t m = x->edge_set;+ memcpy(x->r.mg, s->margin, sizeof x->r.mg);+ memcpy(x->r.pd, s->padding, sizeof x->r.pd);+ for (int i = 0; i < 4; i++) { x->r.bw[i] = s->border_width; x->r.bc[i] = s->border_color; x->r.rad[i] = s->radius; }+ int st = n->rtl ? EDGE_R : EDGE_L, en = n->rtl ? EDGE_L : EDGE_R;+ int side[6] = { EDGE_L, EDGE_T, EDGE_R, EDGE_B, st, en };+ for (int i = 0; i < 6; i++) {+ if (m & ES_BW(i)) x->r.bw[side[i]] = x->border_side[i];+ if (m & ES_BC(i)) x->r.bc[side[i]] = x->border_side_color[i];+ }+ if (m & ES_MARGIN(0)) x->r.mg[st] = x->margin_inline[0];+ if (m & ES_MARGIN(1)) x->r.mg[en] = x->margin_inline[1];+ if (m & ES_PADDING(0)) x->r.pd[st] = x->padding_inline[0];+ if (m & ES_PADDING(1)) x->r.pd[en] = x->padding_inline[1];+ /* corners: 0 TL, 1 TR, 2 BR, 3 BL; logical TS, TE, BS, BE */+ int corner[8] = { 0, 1, 2, 3, n->rtl ? 1 : 0, n->rtl ? 0 : 1, n->rtl ? 2 : 3, n->rtl ? 3 : 2 };+ for (int i = 0; i < 8; i++) if (m & ES_RADIUS(i)) x->r.rad[corner[i]] = x->radius_corner[i];+ x->r.plain = 1;+ for (int i = 1; i < 4; i++)+ if (x->r.bw[i] != x->r.bw[0] || x->r.bc[i] != x->r.bc[0] || x->r.rad[i] != x->r.rad[0]) x->r.plain = 0;+ x->r.rtl = n->rtl;+ x->r.ok = 1;+}#define MAX_KIDS 1024@@ -31,15 +71,15 @@ static int in_flow(const Node *c) {return c->type != NODE_RAW && !c->s.display_none && !c->s.absolute;}-static float pad_h(const Style *s) { return s->padding[EDGE_L] + s->padding[EDGE_R] + 2 * s->border_width; }-static float pad_v(const Style *s) { return s->padding[EDGE_T] + s->padding[EDGE_B] + 2 * s->border_width; }+static float pad_h(const Node *n) { const float *p = node_padding(n); return p[EDGE_L] + p[EDGE_R] + node_border(n, EDGE_L) + node_border(n, EDGE_R); }+static float pad_v(const Node *n) { const float *p = node_padding(n); return p[EDGE_T] + p[EDGE_B] + node_border(n, EDGE_T) + node_border(n, EDGE_B); }static char text_buf[8192];/* Intrinsic size (border-box) given the container's available space. */static void measure(Node *n, float aw, float ah, float *ow, float *oh) {- const Style *s = &n->s;- float ph = pad_h(s), pv = pad_v(s);+ const Style *s = &n->s; /* the caller ran prepare(n) */+ float ph = pad_h(n), pv = pad_v(n);float w = res(s->width, aw), h = res(s->height, ah);if (isnan(w) || isnan(h)) {float cw = 0, ch = 0;@@ -50,12 +90,14 @@ static void measure(Node *n, float aw, float ah, float *ow, float *oh) {if (maxw < 0) maxw = 0;if (!n->measure_valid || fabsf(n->measure_maxw - maxw) > 0.5f) {node_gather_text(n, text_buf, sizeof text_buf);- text_measure(text_buf, TEXT_WEIGHT(s), s->font_size, s->line_height, maxw, s->nowrap,- &n->measure_w, &n->measure_h);+ text_measure_ex(text_buf, TEXT_WEIGHT(s), s->font_size, s->line_height, maxw, s->nowrap,+ s->line_clamp, &n->measure_w, &n->measure_h);n->measure_maxw = maxw;n->measure_valid = 1;}cw = n->measure_w; ch = n->measure_h;+ /* truncated text never asks for more than the space it has (it ends in "…") */+ if ((s->text_overflow || s->line_clamp) && maxw > 0 && cw > maxw) cw = maxw;} else if (n->type == NODE_IMAGE && n->img) {int iw, ih;image_size(n->img, &iw, &ih);@@ -72,8 +114,9 @@ static void measure(Node *n, float aw, float ah, float *ow, float *oh) {int in_line = 0;for (Node *c = n->first; c; c = c->next) {if (!in_flow(c)) continue;- const Style *cs = &c->s;- float mh = cs->margin[EDGE_L] + cs->margin[EDGE_R], mv = cs->margin[EDGE_T] + cs->margin[EDGE_B];+ prepare(c);+ const float *cm = node_margin(c);+ float mh = cm[EDGE_L] + cm[EDGE_R], mv = cm[EDGE_T] + cm[EDGE_B];float c_w, c_h;measure(c, isnan(iaw) ? NAN : iaw - mh, isnan(iah) ? NAN : iah - mv, &c_w, &c_h);c_w += mh; c_h += mv;@@ -110,10 +153,18 @@ static void measure(Node *n, float aw, float ah, float *ow, float *oh) {static void layout_node(Node *n, float w, float h);static void layout_absolute(Node *n, Node *c, float w, float h) {- const Style *s = &n->s, *cs = &c->s;- float bw = s->border_width, cbw = w - 2 * bw, cbh = h - 2 * bw;- float l = res(cs->pos[EDGE_L], cbw), t = res(cs->pos[EDGE_T], cbh);- float r = res(cs->pos[EDGE_R], cbw), b = res(cs->pos[EDGE_B], cbh);+ const Style *cs = &c->s;+ prepare(c);+ float bl = node_border(n, EDGE_L), bt = node_border(n, EDGE_T);+ float cbw = w - bl - node_border(n, EDGE_R), cbh = h - bt - node_border(n, EDGE_B);+ const float *pd = node_padding(n), *cm = node_margin(c);+ /* insets straight from the style (grab.c moves a window through them without node_invalidate),+ * with the logical ones on top */+ Dim in[4] = { cs->pos[0], cs->pos[1], cs->pos[2], cs->pos[3] };+ if (cs->ext && cs->ext->inset_inline[0].unit != UNIT_AUTO) in[c->rtl ? EDGE_R : EDGE_L] = cs->ext->inset_inline[0];+ if (cs->ext && cs->ext->inset_inline[1].unit != UNIT_AUTO) in[c->rtl ? EDGE_L : EDGE_R] = cs->ext->inset_inline[1];+ float l = res(in[EDGE_L], cbw), t = res(in[EDGE_T], cbh);+ float r = res(in[EDGE_R], cbw), b = res(in[EDGE_B], cbh);float cw = res(cs->width, cbw), ch = res(cs->height, cbh);if (isnan(cw) && !isnan(l) && !isnan(r)) cw = cbw - l - r;if (isnan(ch) && !isnan(t) && !isnan(b)) ch = cbh - t - b;@@ -125,9 +176,9 @@ static void layout_absolute(Node *n, Node *c, float w, float h) {}cw = clamp_dim(cw, cs->min_w, cs->max_w, cbw);ch = clamp_dim(ch, cs->min_h, cs->max_h, cbh);- float sx = n->rtl ? cbw - s->padding[EDGE_R] - cw - cs->margin[EDGE_R] - cs->margin[EDGE_L] : s->padding[EDGE_L];- c->x = bw + (!isnan(l) ? l : !isnan(r) ? cbw - r - cw : sx) + cs->margin[EDGE_L];- c->y = bw + (!isnan(t) ? t : !isnan(b) ? cbh - b - ch : s->padding[EDGE_T]) + cs->margin[EDGE_T];+ float sx = n->rtl ? cbw - pd[EDGE_R] - cw - cm[EDGE_R] - cm[EDGE_L] : pd[EDGE_L];+ c->x = bl + (!isnan(l) ? l : !isnan(r) ? cbw - r - cw : sx) + cm[EDGE_L];+ c->y = bt + (!isnan(t) ? t : !isnan(b) ? cbh - b - ch : pd[EDGE_T]) + cm[EDGE_T];layout_node(c, cw, ch);}@@ -141,7 +192,8 @@ static void layout_line(Node *n, Node **kids, float *size_main, const float *meafloat used = k > 1 ? s->gap * (k - 1) : 0, grow = 0, shrink = 0;for (int i = 0; i < k; i++) {const Style *cs = &kids[i]->s;- used += size_main[i] + (row ? cs->margin[EDGE_L] + cs->margin[EDGE_R] : cs->margin[EDGE_T] + cs->margin[EDGE_B]);+ const float *mg = node_margin(kids[i]);+ used += size_main[i] + (row ? mg[EDGE_L] + mg[EDGE_R] : mg[EDGE_T] + mg[EDGE_B]);grow += cs->grow;shrink += cs->shrink * size_main[i];}@@ -163,8 +215,9 @@ static void layout_line(Node *n, Node **kids, float *size_main, const float *meafloat total = k > 1 ? s->gap * (k - 1) : 0;for (int i = 0; i < k; i++) {const Style *cs = &kids[i]->s;+ const float *mg = node_margin(kids[i]);size_main[i] = clamp_dim(size_main[i], row ? cs->min_w : cs->min_h, row ? cs->max_w : cs->max_h, main);- total += size_main[i] + (row ? cs->margin[EDGE_L] + cs->margin[EDGE_R] : cs->margin[EDGE_T] + cs->margin[EDGE_B]);+ total += size_main[i] + (row ? mg[EDGE_L] + mg[EDGE_R] : mg[EDGE_T] + mg[EDGE_B]);}free_space = main - total;}@@ -172,7 +225,8 @@ static void layout_line(Node *n, Node **kids, float *size_main, const float *meafor (int i = 0; i < k; i++) {Node *c = kids[i];const Style *cs = &c->s;- float mc = row ? cs->margin[EDGE_T] + cs->margin[EDGE_B] : cs->margin[EDGE_L] + cs->margin[EDGE_R];+ const float *cm = node_margin(c);+ float mc = row ? cm[EDGE_T] + cm[EDGE_B] : cm[EDGE_L] + cm[EDGE_R];int align = cs->align_self != ALIGN_AUTO ? cs->align_self : s->align_items;float ec = res(row ? cs->height : cs->width, line_cross);float sz;@@ -201,11 +255,12 @@ static void layout_line(Node *n, Node **kids, float *size_main, const float *meafor (int i = 0; i < k; i++) {Node *c = kids[i];const Style *cs = &c->s;- float ml = cs->margin[rtl ? EDGE_R : EDGE_L], mr = cs->margin[rtl ? EDGE_L : EDGE_R];- float m_start = row ? ml : cs->margin[EDGE_T];- float m_end = row ? mr : cs->margin[EDGE_B];- float c_start = row ? cs->margin[EDGE_T] : ml;- float c_end = row ? cs->margin[EDGE_B] : mr;+ const float *cm = node_margin(c);+ float ml = cm[rtl ? EDGE_R : EDGE_L], mr = cm[rtl ? EDGE_L : EDGE_R];+ float m_start = row ? ml : cm[EDGE_T];+ float m_end = row ? mr : cm[EDGE_B];+ float c_start = row ? cm[EDGE_T] : ml;+ float c_end = row ? cm[EDGE_B] : mr;int align = cs->align_self != ALIGN_AUTO ? cs->align_self : s->align_items;float cpos = c_start;if (align == ALIGN_CENTER) cpos = (line_cross - size_cross[i] - c_start - c_end) / 2 + c_start;@@ -219,13 +274,18 @@ static void layout_line(Node *n, Node **kids, float *size_main, const float *mea}static void layout_node(Node *n, float w, float h) {- n->w = w; n->h = h;- n->rtl = n->s.dir == DIR_RTL ? 1 : n->s.dir == DIR_LTR ? 0 : n->parent ? n->parent->rtl : ui.rtl;+ /* nothing changed inside since the last layout and it has the same box (a window being moved):+ * its children keep their positions, only place() runs */+ if (n->layout_ok && n->w == w && n->h == h && n->layout_rtl == n->rtl) return;+ n->w = w; n->h = h; /* prepare(n) ran in the parent's loop (layout_root for the root) */+ n->layout_ok = 1;+ n->layout_rtl = n->rtl;if (n->type == NODE_RAW || n->type == NODE_TEXT) return;const Style *s = &n->s;int row = s->row;- float ix = s->padding[EDGE_L] + s->border_width, iy = s->padding[EDGE_T] + s->border_width;- float iw = w - pad_h(s), ih = h - pad_v(s);+ const float *pd = node_padding(n);+ float ix = pd[EDGE_L] + node_border(n, EDGE_L), iy = pd[EDGE_T] + node_border(n, EDGE_T);+ float iw = w - pad_h(n), ih = h - pad_v(n);if (iw < 0) iw = 0;if (ih < 0) ih = 0;float main = row ? iw : ih, cross = row ? ih : iw;@@ -236,7 +296,9 @@ static void layout_node(Node *n, float w, float h) {for (Node *c = n->first; c && k < MAX_KIDS; c = c->next) {if (!in_flow(c)) continue;const Style *cs = &c->s;- float mc = row ? cs->margin[EDGE_T] + cs->margin[EDGE_B] : cs->margin[EDGE_L] + cs->margin[EDGE_R];+ prepare(c);+ const float *cm = node_margin(c);+ float mc = row ? cm[EDGE_T] + cm[EDGE_B] : cm[EDGE_L] + cm[EDGE_R];float basis = res(cs->basis, main);float em = res(row ? cs->width : cs->height, main);float mw = 0, mh = 0;@@ -260,8 +322,8 @@ static void layout_node(Node *n, float w, float h) {int end = start;float len = 0, lc = 0;while (end < k) {- const Style *cs = &kids[end]->s;- float mm = row ? cs->margin[EDGE_L] + cs->margin[EDGE_R] : cs->margin[EDGE_T] + cs->margin[EDGE_B];+ const float *mg = node_margin(kids[end]);+ float mm = row ? mg[EDGE_L] + mg[EDGE_R] : mg[EDGE_T] + mg[EDGE_B];float add = (end > start ? s->gap : 0) + size_main[end] + mm;if (end > start && len + add > main + 0.5f) break;len += add;@@ -278,15 +340,41 @@ static void layout_node(Node *n, float w, float h) {if (c->type != NODE_RAW && !c->s.display_none && c->s.absolute) layout_absolute(n, c, w, h);}-static void place(Node *n, float px, float py) {+/* Absolute positions and transforms: world = parent's world · own (scale/rotate around the+ * origin). Without transforms (almost always) only the flags are cleared. */+static void place(Node *n, float px, float py, const Affine *world) {n->ax = px + n->x + n->s.translate_x;n->ay = py + n->y + n->s.translate_y;- for (Node *c = n->first; c; c = c->next) place(c, n->ax, n->ay);+ n->own_tf = n->type != NODE_RAW && style_has_transform(&n->s);+ const Affine *cw = world;+ if (n->own_tf || world) {+ if (!n->tf && !(n->tf = calloc(1, sizeof *n->tf))) { n->own_tf = n->has_tf = 0; cw = NULL; goto kids; }+ NodeTf *t = n->tf;+ if (n->own_tf) {+ t->own = style_transform(&n->s, n->ax, n->ay, n->w, n->h);+ t->world = world ? affine_mul(*world, t->own) : t->own;+ } else t->world = *world;+ if (!affine_invert(t->world, &t->inv)) t->inv = (Affine){ 0, 0, 0, 0, -1e9f, -1e9f }; /* scale 0: never hit */+ cw = &t->world;+ }+ n->has_tf = cw != NULL;+kids:+ for (Node *c = n->first; c; c = c->next) place(c, n->ax, n->ay, cw);+}++static void layout_forget(Node *n) {+ n->layout_ok = 0;+ for (Node *c = n->first; c; c = c->next) layout_forget(c);}void layout_root(Node *root, float w, float h) {if (!root) return;+ /* the language changed (fonts, direction): every text may measure differently */+ static unsigned gen;+ static int rtl = -1;+ if (gen != text_generation() || rtl != ui.rtl) { layout_forget(root); gen = text_generation(); rtl = ui.rtl; }root->x = root->y = 0;+ prepare(root);layout_node(root, w, h);- place(root, 0, 0);+ place(root, 0, 0, NULL);}diff --git a/server/src/ui/node.c b/server/src/ui/node.cindex 38b0abb..8cf5ed2 100644--- a/server/src/ui/node.c+++ b/server/src/ui/node.c@@ -65,12 +65,19 @@ void damage_subtree(Node *n) {}static void invalidate_measure(Node *n) {- for (; n; n = n->parent) n->measure_valid = 0;+ for (; n; n = n->parent) n->measure_valid = n->layout_ok = 0;+ ui.dirty = 1;+}++/* Only its insets changed (grab.c): its parent places it again, its own subtree is kept. */+void node_moved(Node *n) {+ for (Node *p = n->parent; p; p = p->parent) p->layout_ok = 0;ui.dirty = 1;}void node_invalidate(Node *n) {n->paint_dirty = 1;+ if (n->s.ext) n->s.ext->r.ok = 0;if (n->type == NODE_RAW && n->parent) n->parent->paint_dirty = 1;invalidate_measure(n);}@@ -114,6 +121,8 @@ void node_destroy(Node *n) {ui.nodes[n->id] = NULL;image_release(n->img);free(n->text);+ free(n->tf);+ free(n->s.ext);free(n);ui.dirty = 1;}@@ -164,7 +173,7 @@ int node_children_ordered(Node *n, Node **out, int max) {/* Deletes all nodes (theme change). The whole screen is left to repaint. */void ui_reset(void) {for (int i = 0; i < ui.cap; i++)- if (ui.nodes[i]) { free(ui.nodes[i]->text); free(ui.nodes[i]); ui.nodes[i] = NULL; }+ if (ui.nodes[i]) { free(ui.nodes[i]->text); free(ui.nodes[i]->tf); free(ui.nodes[i]->s.ext); free(ui.nodes[i]); ui.nodes[i] = NULL; }ui.root = NULL;ui.damage = (Box){0, 0, ui.width, ui.height};ui.dirty = 1;diff --git a/server/src/ui/paint.c b/server/src/ui/paint.cindex 3dbf4b4..3b10512 100644--- a/server/src/ui/paint.c+++ b/server/src/ui/paint.c@@ -41,17 +41,40 @@ static uint32_t with_opacity(uint32_t argb, float op) {static int skip_until, skip_reached;static int layer_paint(Canvas *c, Node *n, float opacity);+static int tf_paint(Canvas *c, Node *n, float opacity);+static int tf_self, tf_unit; /* the transformed node being rasterized; the one painted at opacity 1 */++static float max4(const float r[4]) { return fmaxf(fmaxf(r[0], r[1]), fmaxf(r[2], r[3])); }++/* Lines that fit in the box (textOverflow: 'ellipsis' on wrapped text without numberOfLines). */+static int text_max_lines(const Node *n, float box_h) {+ const Style *s = &n->s;+ if (s->line_clamp) return s->line_clamp;+ if (!s->text_overflow || s->nowrap) return 0;+ float lh = text_line_height(s->font_size, s->line_height);+ int fit = lh > 0 ? (int)floorf((box_h + 0.5f) / lh) : 0;+ return fit < 1 ? 1 : fit;+}static void paint_node(Canvas *c, Node *n, float opacity) {if (n->type == NODE_RAW || n->s.display_none) return;if (layer_paint(c, n, opacity)) return;+ if (n->own_tf && n->id != tf_self && tf_paint(c, n, opacity)) return;const Style *s = &n->s;- float op = opacity * s->opacity;+ float op = n->id == tf_unit ? 1 : opacity * s->opacity;if (op < 0.004f) return;const float k = paint_view.k;float x = VX(n->ax), y = VY(n->ay), w = n->w * k, h = n->h * k, rad = s->radius * k;+ /* per-corner radii and per-side borders (not plain): the *4 canvas functions */+ int plain = node_edges_plain(n);+ const StyleExt *ex = s->ext;+ float r4[4] = { rad, rad, rad, rad };+ if (!plain) for (int i = 0; i < 4; i++) r4[i] = ex->r.rad[i] * k;+ if (!plain) rad = max4(r4);+ int corners_differ = !plain && (r4[1] != r4[0] || r4[2] != r4[0] || r4[3] != r4[0]);if (paint_capture_mode && n->protect) { /* ventana protegida: negra en cualquier captura */- canvas_rrect(c, x, y, w, h, rad, 0xff000000u);+ if (corners_differ) canvas_rrect4(c, x, y, w, h, r4, 0xff000000u);+ else canvas_rrect(c, x, y, w, h, rad, 0xff000000u);return;}if (skip_until && n->id == skip_until) skip_reached = 1;@@ -62,27 +85,45 @@ static void paint_node(Canvas *c, Node *n, float opacity) {with_opacity(s->shadow_color, op)));Corners corners = {0};- int round_clip = s->overflow_hidden && s->radius > 0;- if (round_clip) canvas_corners_save(c, &corners, x, y, w, h, rad);+ int round_clip = s->overflow_hidden && rad > 0;+ if (round_clip) {+ if (corners_differ) canvas_corners_save4(c, &corners, x, y, w, h, r4);+ else canvas_corners_save(c, &corners, x, y, w, h, rad);+ }if (own && s->backdrop_blur >= 1) PROF(1, canvas_backdrop_blur(c, x, y, w, h, rad, (int)(s->backdrop_blur * k + 0.5f)));- if (own && s->bg >> 24) PROF(2, canvas_rrect(c, x, y, w, h, rad, with_opacity(s->bg, op)));- if (own && s->has_gradient) PROF(2, canvas_rrect_gradient(c, x, y, w, h, rad, s->grad_from, s->grad_to, s->grad_angle, op));+ if (own && s->bg >> 24) {+ if (corners_differ) PROF(2, canvas_rrect4(c, x, y, w, h, r4, with_opacity(s->bg, op)));+ else PROF(2, canvas_rrect(c, x, y, w, h, rad, with_opacity(s->bg, op)));+ }+ if (own && s->has_gradient) {+ if (corners_differ) PROF(2, canvas_rrect4_gradient(c, x, y, w, h, r4, s->grad_from, s->grad_to, s->grad_angle, op));+ else PROF(2, canvas_rrect_gradient(c, x, y, w, h, rad, s->grad_from, s->grad_to, s->grad_angle, op));+ }- float bw = s->border_width;+ float bw = node_border(n, EDGE_L);/* content box: logical (Wayland surfaces take logical coordinates and scale themselves) and physical */- float lix = n->ax + s->padding[EDGE_L] + bw, liy = n->ay + s->padding[EDGE_T] + bw;- float liw = n->w - s->padding[EDGE_L] - s->padding[EDGE_R] - 2 * bw;- float lih = n->h - s->padding[EDGE_T] - s->padding[EDGE_B] - 2 * bw;+ const float *pd = node_padding(n);+ float bl = bw, bt = node_border(n, EDGE_T), br = node_border(n, EDGE_R), bb = node_border(n, EDGE_B);+ float lix = n->ax + pd[EDGE_L] + bl, liy = n->ay + pd[EDGE_T] + bt;+ float liw = n->w - pd[EDGE_L] - pd[EDGE_R] - bl - br;+ float lih = n->h - pd[EDGE_T] - pd[EDGE_B] - bt - bb;float ix = VX(lix), iy = VY(liy), iw = liw * k, ih = lih * k;if (!own) goto children;- if (n->type == NODE_IMAGE && n->img)- PROF(3, image_draw(c, n->img, ix, iy, iw, ih, (s->radius - bw) * k, s->object_fit, op));+ if (n->type == NODE_IMAGE && n->img) {+ if (corners_differ) { /* the image clipped by the per-corner shape */+ Corners ic = {0};+ canvas_corners_save4(c, &ic, x, y, w, h, r4);+ PROF(3, image_draw(c, n->img, ix, iy, iw, ih, 0, s->object_fit, op));+ canvas_corners_restore4(c, &ic, x, y, w, h, r4);+ } else PROF(3, image_draw(c, n->img, ix, iy, iw, ih, (s->radius - bw) * k, s->object_fit, op));+ }if (n->type == NODE_TERM) term_paint(c, n->term, ix, iy, iw, ih, op);if (n->type == NODE_SURFACE) wl_paint(c, n->term, n->id, lix, liy, liw, lih, op);if (n->type == NODE_MEDIA) media_paint(c, n->term, n->id, ix, iy, iw, ih, (s->radius - bw) * k, op);- if (n->type == NODE_TEXT && (s->color >> 24)) {+ /* text is clipped to its box: a label outside the clip (a list row scrolled away) isn't laid out */+ if (n->type == NODE_TEXT && (s->color >> 24) && x < c->clip.x1 && x + w > c->clip.x0 && y < c->clip.y1 && y + h > c->clip.y0) {node_gather_text(n, text_buf, sizeof text_buf);Rect old = canvas_push_clip(c, x, y, w, h);int al = s->text_align;@@ -90,8 +131,10 @@ static void paint_node(Canvas *c, Node *n, float opacity) {else if (al == TEXT_END) al = n->rtl ? TEXT_LEFT : TEXT_RIGHT;/* line breaks come from the logical metrics (the ones layout measured), glyphs at the display's size */text_paint_scale = k;- PROF(4, text_draw(c, text_buf, TEXT_WEIGHT(s), s->font_size * k, s->line_height > 4 ? s->line_height * k : s->line_height,- ix, iy, iw, al, s->nowrap, with_opacity(s->color, op)));+ int max_lines = text_max_lines(n, lih);+ int ellipsis = s->text_overflow || s->line_clamp;+ PROF(4, text_draw_ex(c, text_buf, TEXT_WEIGHT(s), s->font_size * k, s->line_height > 4 ? s->line_height * k : s->line_height,+ ix, iy, iw, al, s->nowrap, max_lines, ellipsis, with_opacity(s->color, op)));text_paint_scale = 1;canvas_set_clip(c, old);}@@ -106,9 +149,23 @@ children:;}canvas_set_clip(c, old_clip);- if (own && bw > 0 && (s->border_color >> 24))+ if (own && plain && bw > 0 && (s->border_color >> 24))PROF(5, canvas_rrect_stroke(c, x, y, w, h, rad, bw * k, with_opacity(s->border_color, op)));- if (round_clip) canvas_corners_restore(c, &corners, x, y, w, h, rad);+ if (own && !plain) {+ float b4[4];+ uint32_t c4[4];+ int any = 0;+ for (int i = 0; i < 4; i++) {+ b4[i] = ex->r.bw[i] * k;+ c4[i] = with_opacity(ex->r.bc[i], op);+ any |= b4[i] > 0 && (c4[i] >> 24);+ }+ if (any) PROF(5, canvas_border4(c, x, y, w, h, r4, b4, c4));+ }+ if (round_clip) {+ if (corners_differ) canvas_corners_restore4(c, &corners, x, y, w, h, r4);+ else canvas_corners_restore(c, &corners, x, y, w, h, rad);+ }}/* Área que ocupa un nodo en pantalla, incluida su sombra. */@@ -120,10 +177,210 @@ static Box visual_box(const Node *n) {return (Box){ floorf(n->ax - e), floorf(n->ay - e), ceilf(n->ax + n->w + e), ceilf(n->ay + n->h + e) };}+/* The same on screen: through the transforms of the node and its ancestors (bounding box). */+static inline Box screen_box(const Node *n) {+ Box b = visual_box(n);+ if (!n->has_tf) return b;+ Box t = affine_box(n->tf->world, b);+ return (Box){ floorf(t.x0) - 1, floorf(t.y0) - 1, ceilf(t.x1) + 1, ceilf(t.y1) + 1 };+}+static int box_eq(Box a, Box b) {return a.x0 == b.x0 && a.y0 == b.y0 && a.x1 == b.x1 && a.y1 == b.y1;}+/* ---- transformed subtrees (transform: scale/rotate; docs/DESIGN.md "Engine notes") ----+ * A node with its own scale or rotation is painted, with its subtree, once into an offscreen raster+ * in its untransformed layout space, and that raster is composited with the transform (bilinear).+ * The raster scale is the display's (paint_view.k) times the transform scale rounded up to a step+ * (1/8 … 4), so it stays sharp at 150 % or when scaled up, and an animation of the scale (the Dock's+ * minimize, a button's press) only re-rasterizes when it crosses a step: in between it is the same+ * raster composited at another scale. Anything that changes inside (a style, a text, a child's box)+ * invalidates it (damage_walk). The GPU path composites the same CPU canvas, so it gets the same+ * result. Subtrees with an app window or a video on the GPU, or a backdrop blur, are painted+ * untransformed; terminals and app windows on the CPU path are rasterized at the display's scale+ * and never cached. */+#define TF_CACHE 16+#define TF_MAX_PX (2048 * 2048)+typedef struct {+ int node;+ float kr; /* raster px per logical px */+ uint32_t *px;+ int w, h;+ size_t cap;+ float ox, oy; /* raster origin relative to the node (logical px, padding included) */+ int valid;+ unsigned used;+ uint64_t sig; /* the subtree's geometry when it was rasterized (damage_walk) */+ Style st; /* the node's style without transform and opacity (tf_norm) */+ StyleExt xst;+} TfLayer;+static TfLayer tfl[TF_CACHE];+static unsigned tf_tick;+static long tf_renders, tf_composites;++/* The style that decides what the raster looks like: without the transform, the opacity and the+ * position (those are applied when compositing). */+static void tf_norm(const Style *s, Style *o, StyleExt *ox) {+ *o = *s;+ o->opacity = 1;+ o->translate_x = o->translate_y = 0;+ o->z_index = 0;+ o->ext = NULL;+ memset(ox, 0, sizeof *ox);+ if (s->ext) memcpy(ox, s->ext, STYLE_EXT_VALUES);+ ox->scale_x = ox->scale_y = 1;+ ox->rotate = 0;+ ox->origin_x = ox->origin_y = (Dim){ 0, 0 };+}++/* Bounding box of the subtree in the raster's space; *ok = 0 if it can't be rasterized, *live = 1+ * if something in it changes on its own (terminal, app window: never cached). */+static void tf_bounds(const Node *n, Affine rel, Box *b, int *ok, int *live) {+ if (n->type == NODE_RAW || n->s.display_none) return;+ if (n->s.backdrop_blur >= 1) *ok = 0;+ if (n->type == NODE_MEDIA) *ok = 0;+ if (n->type == NODE_SURFACE) { if (gpu_active()) *ok = 0; *live = 1; }+ if (n->type == NODE_TERM) *live = 1;+ Affine r = n->own_tf ? affine_mul(rel, n->tf->own) : rel;+ Box v = affine_box(r, visual_box(n));+ b->x0 = fminf(b->x0, v.x0); b->y0 = fminf(b->y0, v.y0);+ b->x1 = fmaxf(b->x1, v.x1); b->y1 = fmaxf(b->y1, v.y1);+ if (n->type != NODE_TEXT) for (const Node *c = n->first; c; c = c->next) tf_bounds(c, r, b, ok, live);+}++static float tf_step(float sc) {+ static const float steps[] = { 0.125f, 0.25f, 0.5f, 0.75f, 1, 1.5f, 2, 3, 4 };+ for (size_t i = 0; i < sizeof steps / sizeof *steps; i++) if (sc <= steps[i] + 1e-4f) return steps[i];+ return 4;+}++static TfLayer *tf_slot(int node, float kr) {+ TfLayer *lru = &tfl[0];+ for (int i = 0; i < TF_CACHE; i++) {+ if (tfl[i].node == node && tfl[i].kr == kr) return &tfl[i];+ if (tfl[i].used < lru->used) lru = &tfl[i];+ }+ lru->node = node;+ lru->kr = kr;+ lru->valid = 0;+ lru->sig = 0;+ return lru;+}++static int tf_paint(Canvas *c, Node *n, float opacity) {+ if (paint_capture_mode && n->protect) return 0;+ if (skip_until && !skip_reached) return 0; /* the normal path knows how to skip */+ float sc = fmaxf(fabsf(n->s.ext->scale_x), fabsf(n->s.ext->scale_y));+ if (sc < 1e-3f) return 1; /* scale(0): nothing to paint */+ Box b = visual_box(n);+ int ok = 1, live = 0;+ Box sub = b;+ if (n->type != NODE_TEXT)+ for (const Node *k = n->first; k; k = k->next) tf_bounds(k, affine_identity(), &sub, &ok, &live);+ if (!ok) return 0;+ if (!n->s.overflow_hidden) b = sub;+ float kr = live ? paint_view.k : paint_view.k * tf_step(sc);+ const int pad = 1; /* a transparent edge: antialiased borders */+ int w, h;+ for (;;) {+ w = (int)ceilf((b.x1 - b.x0) * kr) + 2 * pad;+ h = (int)ceilf((b.y1 - b.y0) * kr) + 2 * pad;+ if (w <= 0 || h <= 0) return 1;+ if ((size_t)w * h <= TF_MAX_PX || kr < 0.05f) break;+ kr *= 0.7f;+ }+ if ((size_t)w * h > TF_MAX_PX) return 0;+ TfLayer *e = tf_slot(n->id, kr);+ e->used = ++tf_tick;+ float ox = b.x0 - n->ax - pad / kr, oy = b.y0 - n->ay - pad / kr;+ if (!e->valid || live || e->w != w || e->h != h || fabsf(e->ox - ox) > 0.01f || fabsf(e->oy - oy) > 0.01f) {+ if ((size_t)w * h > e->cap) {+ uint32_t *px = realloc(e->px, (size_t)w * h * 4);+ if (!px) return 0;+ e->px = px;+ e->cap = (size_t)w * h;+ }+ e->w = w; e->h = h; e->ox = ox; e->oy = oy;+ memset(e->px, 0, (size_t)w * h * 4);+ Canvas rc;+ canvas_init(&rc, e->px, w, h, w);+ PaintView keep = paint_view;+ paint_view = (PaintView){ n->ax + ox, n->ay + oy, kr, 0, 0, keep.index };+ int ks = skip_until, kr_self = tf_self, ku = tf_unit;+ skip_until = 0;+ tf_self = tf_unit = n->id;+ paint_node(&rc, n, 1);+ skip_until = ks; tf_self = kr_self; tf_unit = ku;+ paint_view = keep;+ tf_norm(&n->s, &e->st, &e->xst);+ e->sig = n->tf->sig;+ e->valid = !live && !paint_capture_mode;+ tf_renders++;+ }+ /* raster px → logical (Ri) → transformed (own) → this canvas (V) */+ const float k = paint_view.k;+ Affine ri = { 1 / kr, 0, 0, 1 / kr, n->ax + ox, n->ay + oy };+ Affine v = { k, 0, 0, k, paint_view.dx - paint_view.x * k, paint_view.dy - paint_view.y * k };+ Affine fwd = affine_mul(v, affine_mul(n->tf->own, ri)), inv;+ if (!affine_invert(fwd, &inv)) return 1;+ float f6[6] = { fwd.a, fwd.b, fwd.c, fwd.d, fwd.e, fwd.f }, i6[6] = { inv.a, inv.b, inv.c, inv.d, inv.e, inv.f };+ canvas_blit_affine(c, e->px, e->w, e->h, i6, f6, opacity * n->s.opacity);+ tf_composites++;+ return 1;+}++void paint_tf_stats(long *renders, long *composites) {+ *renders = tf_renders;+ *composites = tf_composites;+ tf_renders = tf_composites = 0;+}++/* damage_walk: the geometry of a transformed subtree (each node's box relative to its parent) and+ * whether a style or text changed in it; the node's own transform and opacity don't count. */+typedef struct { uint64_t h; int dirty; } TfSig;+static TfSig *walk_sig;++static void sig_mix(TfSig *g, const void *p, size_t len) {+ const unsigned char *b = p;+ for (size_t i = 0; i < len; i++) { g->h ^= b[i]; g->h *= 1099511628211ull; }+}++static void sig_node(TfSig *g, const Node *n, int self) {+ float f[6] = { self ? 0 : n->x, self ? 0 : n->y, n->w, n->h, self ? 0 : n->s.translate_x, self ? 0 : n->s.translate_y };+ sig_mix(g, f, sizeof f);+ sig_mix(g, &n->id, sizeof n->id);+ if (!self && n->own_tf) {+ float t[3] = { n->s.ext->scale_x, n->s.ext->scale_y, n->s.ext->rotate };+ sig_mix(g, t, sizeof t);+ }+}++static void tf_check(Node *n, const TfSig *g) {+ n->tf->sig = g->h;+ for (int i = 0; i < TF_CACHE; i++) {+ TfLayer *e = &tfl[i];+ if (e->node != n->id) continue;+ int changed = g->dirty || e->sig != g->h;+ if (!changed && n->paint_dirty) {+ Style st;+ StyleExt xst;+ tf_norm(&n->s, &st, &xst);+ changed = memcmp(&st, &e->st, sizeof st) != 0 || memcmp(&xst, &e->xst, STYLE_EXT_VALUES) != 0;+ }+ if (changed) e->valid = 0;+ }+}++/* Rasters not used for a while give their memory back. */+static void tf_gc(void) {+ for (int i = 0; i < TF_CACHE; i++)+ if (tfl[i].px && tf_tick - tfl[i].used > 600) {+ free(tfl[i].px);+ memset(&tfl[i], 0, sizeof tfl[i]);+ }+}+/* ---- capa de la ventana que se mueve (grab.h) ----* Al empezar a mover una ventana su árbol se pinta una vez en un búfer aparte (con su sombra) y* en cada cuadro solo se copia en la posición nueva: no se vuelve a pintar texto, terminal ni@@ -198,7 +455,7 @@ static void subtree_box(Node *n, Box *b, int *ok) {if (n->type == NODE_RAW || n->s.display_none) return;if (n->s.backdrop_blur >= 1) *ok = 0;if (gpu_active() && n->type == NODE_MEDIA) *ok = 0;- Box v = visual_box(n);+ Box v = screen_box(n);if (v.x0 < b->x0) b->x0 = v.x0;if (v.y0 < b->y0) b->y0 = v.y0;if (v.x1 > b->x1) b->x1 = v.x1;@@ -234,17 +491,17 @@ static void layer_register(Canvas *c, Node *n, float op) {if (n->type == NODE_RAW || n->s.display_none) return;op *= n->s.opacity;if (n->type == NODE_SURFACE) {- const Style *s = &n->s;- float bw = s->border_width;- wl_paint(c, n->term, n->id, n->ax + s->padding[EDGE_L] + bw, n->ay + s->padding[EDGE_T] + bw,- n->w - s->padding[EDGE_L] - s->padding[EDGE_R] - 2 * bw, n->h - s->padding[EDGE_T] - s->padding[EDGE_B] - 2 * bw, op);+ const float *pd = node_padding(n);+ float bl = node_border(n, EDGE_L), bt = node_border(n, EDGE_T), br = node_border(n, EDGE_R), bb = node_border(n, EDGE_B);+ wl_paint(c, n->term, n->id, n->ax + pd[EDGE_L] + bl, n->ay + pd[EDGE_T] + bt,+ n->w - pd[EDGE_L] - pd[EDGE_R] - bl - br, n->h - pd[EDGE_T] - pd[EDGE_B] - bt - bb, op);}if (n->type != NODE_TEXT) for (Node *k = n->first; k; k = k->next) layer_register(c, k, op);}static int layer_render(Node *n, float opacity) {Box b = visual_box(n);- int ok = 1;+ int ok = !n->has_tf; /* a transformed window is painted as usual */subtree_box(n, &b, &ok);/* the layer's pixels are the view's physical ones */int x0 = (int)floorf(VX(b.x0)), y0 = (int)floorf(VY(b.y0));@@ -391,7 +648,17 @@ static void damage_walk(Node *n, int parent_dirty, int visible, int in_layer, Boif (n->type == NODE_RAW) { n->paint_dirty = 0; return; }int vis = visible && !n->s.display_none;int dirty = parent_dirty || n->paint_dirty;- Box cur = vis ? box_and(visual_box(n), clip) : (Box){0, 0, 0, 0};+ Box cur = vis ? box_and(screen_box(n), clip) : (Box){0, 0, 0, 0};+ TfSig *outer_sig = walk_sig, sig;+ if (walk_sig && vis) {+ sig_node(walk_sig, n, 0);+ if (n->paint_dirty) walk_sig->dirty = 1;+ }+ if (vis && n->own_tf) {+ sig = (TfSig){ 1469598103934665603ull, 0 };+ sig_node(&sig, n, 1);+ walk_sig = &sig;+ }if (layer.want && n->id == layer.node) {in_layer = 1;layer.gdx = cur.x0 - n->prev_box.x0;@@ -406,8 +673,17 @@ static void damage_walk(Node *n, int parent_dirty, int visible, int in_layer, Bo}n->prev_box = cur;n->paint_dirty = 0;- Box inner = n->s.overflow_hidden ? box_and(clip, (Box){ floorf(n->ax), floorf(n->ay), ceilf(n->ax + n->w), ceilf(n->ay + n->h) }) : clip;+ Box inner = clip;+ if (n->s.overflow_hidden) {+ Box own_box = { floorf(n->ax), floorf(n->ay), ceilf(n->ax + n->w), ceilf(n->ay + n->h) };+ if (n->has_tf) {+ Box t = affine_box(n->tf->world, own_box);+ own_box = (Box){ floorf(t.x0) - 1, floorf(t.y0) - 1, ceilf(t.x1) + 1, ceilf(t.y1) + 1 };+ }+ inner = box_and(clip, own_box);+ }for (Node *c = n->first; c; c = c->next) damage_walk(c, dirty, vis, in_layer, inner);+ if (walk_sig == &sig) { tf_check(n, &sig); walk_sig = outer_sig; }}static int box_inside(Box a, Box b) { return a.x0 >= b.x0 && a.y0 >= b.y0 && a.x1 <= b.x1 && a.y1 <= b.y1; }@@ -448,7 +724,7 @@ int paint_damage(Node *root) {* mapa o una lista que se mueve adentro de una tarjeta, se pinta desde la tarjeta. */static void cover_walk(Node *n, Box d, Box clip, int *found) {const Style *s = &n->s;- if (n->type == NODE_RAW || s->display_none || s->opacity < 0.999f) return;+ if (n->type == NODE_RAW || s->display_none || s->opacity < 0.999f || n->own_tf) return; /* transformed: not where layout says */Box box = box_and((Box){ n->ax, n->ay, n->ax + n->w, n->ay + n->h }, clip);if ((s->bg >> 24) == 0xff && !s->has_gradient && s->backdrop_blur < 1) {float k = s->radius * 0.3f; /* adentro de las esquinas redondeadas */@@ -483,6 +759,7 @@ void paint_root(Canvas *c, Node *root) {}paint_node(c, root, 1);skip_until = 0;+ tf_gc();wl_paint_popups(c); /* menús de las apps Wayland, encima de todo */if (paint_profile) {fprintf(stderr, " paint:");@@ -503,7 +780,9 @@ void paint_capture(Canvas *c, Node *root) {static Node *hit(Node *n, float x, float y) {if (n->type == NODE_RAW || n->s.display_none || n->s.pointer_none) return NULL;- int inside = x >= n->ax && y >= n->ay && x < n->ax + n->w && y < n->ay + n->h;+ float lx = x, ly = y; /* through the transforms: the box as it is painted */+ if (n->has_tf) affine_apply(n->tf->inv, x, y, &lx, &ly);+ int inside = lx >= n->ax && ly >= n->ay && lx < n->ax + n->w && ly < n->ay + n->h;if (n->s.overflow_hidden && !inside) return NULL;if (n->type != NODE_TEXT) {Node *kids[MAX_KIDS];diff --git a/server/src/ui/style.c b/server/src/ui/style.cindex b0fb341..fd367e7 100644--- a/server/src/ui/style.c+++ b/server/src/ui/style.c@@ -6,13 +6,15 @@#include <stdlib.h>#include <string.h>-typedef enum { ST_DIM, ST_FLOAT, ST_COLOR, ST_ENUM } StyleType;+typedef enum { ST_DIM, ST_FLOAT, ST_COLOR, ST_ENUM, ST_U8 } StyleType;typedef struct {const char *name;StyleType type;size_t off;const char *const *values; /* ST_ENUM */+ uint32_t bit; /* ES_* bit in Style.edge_set: the value overrides the shorthand */+ uint8_t ext; /* the field is in Style.x (StyleExt), off is relative to it */} StyleProp;static const char *const E_DISPLAY[] = {"flex", "none", NULL};@@ -30,8 +32,11 @@ static const char *const E_WSPACE[] = {"normal", "nowrap", NULL};static const char *const E_WRAP[] = {"nowrap", "wrap", NULL};static const char *const E_FAMILY[] = {"sans-serif", "monospace", NULL};static const char *const E_CURSOR[] = {CURSOR_CSS_NAMES, NULL};+static const char *const E_TOVERFLOW[] = {"clip", "ellipsis", NULL};-#define P(n, t, f, e) { n, t, offsetof(Style, f), e }+#define P(n, t, f, e) { n, t, offsetof(Style, f), e, 0, 0 }+#define PB(n, t, f, b) { n, t, offsetof(StyleExt, f), NULL, b, 1 }+#define PX(n, t, f) { n, t, offsetof(StyleExt, f), NULL, 0, 1 }static const StyleProp props[] = {P("display", ST_ENUM, display_none, E_DISPLAY),@@ -88,6 +93,44 @@ static const StyleProp props[] = {P("translateX", ST_FLOAT, translate_x, NULL),P("translateY", ST_FLOAT, translate_y, NULL),P("zIndex", ST_FLOAT, z_index, NULL),+ /* text truncation */+ P("textOverflow", ST_ENUM, text_overflow, E_TOVERFLOW),+ P("numberOfLines", ST_U8, line_clamp, NULL),+ /* per-side borders (physical, then start/end that follow the direction) */+ PB("borderLeftWidth", ST_FLOAT, border_side[EDGE_L], ES_BW(EDGE_L)),+ PB("borderTopWidth", ST_FLOAT, border_side[EDGE_T], ES_BW(EDGE_T)),+ PB("borderRightWidth", ST_FLOAT, border_side[EDGE_R], ES_BW(EDGE_R)),+ PB("borderBottomWidth", ST_FLOAT, border_side[EDGE_B], ES_BW(EDGE_B)),+ PB("borderStartWidth", ST_FLOAT, border_side[SIDE_START], ES_BW(SIDE_START)),+ PB("borderEndWidth", ST_FLOAT, border_side[SIDE_END], ES_BW(SIDE_END)),+ PB("borderLeftColor", ST_COLOR, border_side_color[EDGE_L], ES_BC(EDGE_L)),+ PB("borderTopColor", ST_COLOR, border_side_color[EDGE_T], ES_BC(EDGE_T)),+ PB("borderRightColor", ST_COLOR, border_side_color[EDGE_R], ES_BC(EDGE_R)),+ PB("borderBottomColor", ST_COLOR, border_side_color[EDGE_B], ES_BC(EDGE_B)),+ PB("borderStartColor", ST_COLOR, border_side_color[SIDE_START], ES_BC(SIDE_START)),+ PB("borderEndColor", ST_COLOR, border_side_color[SIDE_END], ES_BC(SIDE_END)),+ /* per-corner radii */+ PB("borderTopLeftRadius", ST_FLOAT, radius_corner[0], ES_RADIUS(0)),+ PB("borderTopRightRadius", ST_FLOAT, radius_corner[1], ES_RADIUS(1)),+ PB("borderBottomRightRadius", ST_FLOAT, radius_corner[2], ES_RADIUS(2)),+ PB("borderBottomLeftRadius", ST_FLOAT, radius_corner[3], ES_RADIUS(3)),+ PB("borderTopStartRadius", ST_FLOAT, radius_corner[4], ES_RADIUS(4)),+ PB("borderTopEndRadius", ST_FLOAT, radius_corner[5], ES_RADIUS(5)),+ PB("borderBottomStartRadius", ST_FLOAT, radius_corner[6], ES_RADIUS(6)),+ PB("borderBottomEndRadius", ST_FLOAT, radius_corner[7], ES_RADIUS(7)),+ /* logical margins, paddings and insets */+ PB("marginStart", ST_FLOAT, margin_inline[0], ES_MARGIN(0)),+ PB("marginEnd", ST_FLOAT, margin_inline[1], ES_MARGIN(1)),+ PB("paddingStart", ST_FLOAT, padding_inline[0], ES_PADDING(0)),+ PB("paddingEnd", ST_FLOAT, padding_inline[1], ES_PADDING(1)),+ PX("start", ST_DIM, inset_inline[0]),+ PX("end", ST_DIM, inset_inline[1]),+ /* transform */+ PX("scaleX", ST_FLOAT, scale_x),+ PX("scaleY", ST_FLOAT, scale_y),+ PX("rotate", ST_FLOAT, rotate),+ PX("transformOriginX", ST_DIM, origin_x),+ PX("transformOriginY", ST_DIM, origin_y),};static const StyleProp *find(const char *key) {@@ -96,15 +139,35 @@ static const StyleProp *find(const char *key) {return NULL;}+static void ext_defaults(StyleExt *x) {+ memset(x, 0, sizeof *x);+ x->scale_x = x->scale_y = 1;+ x->origin_x = x->origin_y = (Dim){ 50, UNIT_PCT };+}++/* The field's address; the StyleExt is created on the first rare property. */+static char *field(Style *s, const StyleProp *p) {+ if (!p->ext) return (char *)s + p->off;+ if (!s->ext) {+ if (!(s->ext = malloc(sizeof *s->ext))) return NULL;+ ext_defaults(s->ext);+ }+ s->ext->r.ok = 0;+ return (char *)s->ext + p->off;+}+static size_t type_size(StyleType t) {- return t == ST_DIM ? sizeof(Dim) : t == ST_ENUM ? 1 : 4;+ return t == ST_DIM ? sizeof(Dim) : t == ST_ENUM || t == ST_U8 ? 1 : 4;}int style_set_number(Style *s, const char *key, double v) {const StyleProp *p = find(key);if (!p) return -1;- char *f = (char *)s + p->off;+ char *f = field(s, p);+ if (!f) return -1;+ if (p->bit) s->ext->edge_set |= p->bit;switch (p->type) {+ case ST_U8: *(uint8_t *)f = (uint8_t)(v < 0 ? 0 : v > 255 ? 255 : v); return 0;case ST_DIM: *(Dim *)f = (Dim){ (float)v, UNIT_PX }; return 0;case ST_FLOAT: *(float *)f = (float)v; return 0;case ST_COLOR: *(uint32_t *)f = (uint32_t)(int64_t)v; return 0;@@ -116,7 +179,10 @@ int style_set_number(Style *s, const char *key, double v) {int style_set_string(Style *s, const char *key, const char *v) {const StyleProp *p = find(key);if (!p) return -1;- char *f = (char *)s + p->off;+ char *f = field(s, p);+ if (!f) return -1;+ if (p->bit && p->type != ST_ENUM) s->ext->edge_set |= p->bit;+ if (p->type == ST_U8) { long n = strtol(v, NULL, 10); *(uint8_t *)f = (uint8_t)(n < 0 ? 0 : n > 255 ? 255 : n); return 0; }if (p->type == ST_ENUM) {for (int i = 0; p->values[i]; i++)if (!strcmp(p->values[i], v)) { *(uint8_t *)f = (uint8_t)i; return 0; }@@ -137,6 +203,15 @@ int style_set_string(Style *s, const char *key, const char *v) {int style_reset(Style *s, const char *key) {const StyleProp *p = find(key);if (!p) return -1;+ if (p->ext) {+ if (!s->ext) return 0;+ s->ext->edge_set &= ~p->bit;+ StyleExt d;+ ext_defaults(&d);+ memcpy((char *)s->ext + p->off, (char *)&d + p->off, type_size(p->type));+ s->ext->r.ok = 0;+ return 0;+ }Style d;style_defaults(&d);memcpy((char *)s + p->off, (char *)&d + p->off, type_size(p->type));diff --git a/server/src/ui/text.c b/server/src/ui/text.cindex 1c6dd14..8d96773 100644--- a/server/src/ui/text.c+++ b/server/src/ui/text.c@@ -367,22 +367,34 @@ static uint64_t tm_key(const char *s, float weight, float size, float line_h, flreturn h | 1; /* 0 = empty slot */}-static void text_measure_raw(const char *s, float weight, float size, float line_h, float max_w, int nowrap, float *w, float *h) {+/* max_lines > 0: only the first max_lines lines count; if there is more text, the last one is cut+ * with "…" and may take the whole width. */+static void text_measure_raw(const char *s, float weight, float size, float line_h, float max_w, int nowrap, int max_lines,+ float *w, float *h) {int font = font_for(weight);- if (text_needs_layout(s, font)) { text_layout_measure(s, font, size, line_h, max_w, nowrap, w, h); return; }+ if (text_needs_layout(s, font)) { text_layout_measure_ex(s, font, size, line_h, max_w, nowrap, max_lines, w, h); return; }int n = wrap(s, font, size, max_w, nowrap, lines, MAX_LINES);+ int vis = max_lines > 0 && n > max_lines ? max_lines : n;float mw = 0;- for (int i = 0; i < n; i++) if (lines[i].width > mw) mw = lines[i].width;+ for (int i = 0; i < vis; i++) if (lines[i].width > mw) mw = lines[i].width;+ if (vis < n && max_w > 0 && mw < max_w) mw = max_w;*w = ceilf(mw);- *h = n * text_line_height(size, line_h);+ *h = vis * text_line_height(size, line_h);}void text_measure(const char *s, float weight, float size, float line_h, float max_w, int nowrap, float *w, float *h) {- uint64_t k = tm_key(s, weight, size, line_h, max_w, nowrap);+ text_measure_ex(s, weight, size, line_h, max_w, nowrap, 0, w, h);+}++void text_measure_ex(const char *s, float weight, float size, float line_h, float max_w, int nowrap, int max_lines,+ float *w, float *h) {+ if (max_lines < 0) max_lines = 0;+ /* the line limit goes in the same key as nowrap (0 lines = the key of plain text_measure) */+ uint64_t k = tm_key(s, weight, size, line_h, max_w, nowrap | max_lines << 1);unsigned set = (unsigned)(k >> 20) & (TM_SETS - 1);for (int i = 0; i < TM_WAYS; i++)if (tm_cache[set][i].key == k) { *w = tm_cache[set][i].w; *h = tm_cache[set][i].h; return; }- text_measure_raw(s, weight, size, line_h, max_w, nowrap, w, h);+ text_measure_raw(s, weight, size, line_h, max_w, nowrap, max_lines, w, h);int i = tm_next[set]++ % TM_WAYS;tm_cache[set][i].key = k;tm_cache[set][i].w = *w;@@ -391,13 +403,13 @@ void text_measure(const char *s, float weight, float size, float line_h, float mfloat text_paint_scale = 1;-void text_draw(Canvas *c, const char *s, float weight, float size, float line_h,- float x, float y, float box_w, int align, int nowrap, uint32_t argb) {- int font = font_for(weight);- if (text_needs_layout(s, font)) { text_layout_draw(c, s, font, size, line_h, x, y, box_w, align, nowrap, argb); return; }+/* Fast path (Inter only): at most max_lines lines (0 = all). */+static void draw_fast(Canvas *c, const char *s, int font, float size, float line_h,+ float x, float y, float box_w, int align, int nowrap, int max_lines, uint32_t argb) {/* scaled display: break lines with the logical metrics (what layout measured), draw at `size` */float k = text_paint_scale > 0 ? text_paint_scale : 1;int n = wrap(s, font, size / k, box_w / k, nowrap, lines, MAX_LINES);+ if (max_lines > 0 && n > max_lines) n = max_lines;if (k != 1) for (int i = 0; i < n; i++) lines[i].width *= k;float lh = text_line_height(size, line_h);Font *f = &fonts[font];@@ -421,3 +433,143 @@ void text_draw(Canvas *c, const char *s, float weight, float size, float line_h,}}}++void text_draw(Canvas *c, const char *s, float weight, float size, float line_h,+ float x, float y, float box_w, int align, int nowrap, uint32_t argb) {+ int font = font_for(weight);+ if (text_needs_layout(s, font)) { text_layout_draw(c, s, font, size, line_h, x, y, box_w, align, nowrap, argb); return; }+ draw_fast(c, s, font, size, line_h, x, y, box_w, align, nowrap, 0, argb);+}++/* ---- truncation with an ellipsis ---- */++#define ELLIPSIS "\xe2\x80\xa6" /* U+2026 */++static int copy_str(char *out, int out_size, const char *s, int len) {+ if (out_size <= 0) return 0;+ if (len > out_size - 1) len = out_size - 1;+ memcpy(out, s, (size_t)len);+ out[len] = 0;+ return len;+}++/* prefix (len bytes, trailing spaces dropped) + "…" */+int text_ellipsis_join(char *out, int out_size, const char *s, int len) {+ while (len > 0 && (s[len - 1] == ' ' || s[len - 1] == '\t')) len--;+ if (len > out_size - 4) { /* keep whole UTF-8 sequences */+ len = out_size - 4;+ while (len > 0 && ((unsigned char)s[len] & 0xc0) == 0x80) len--;+ }+ if (len < 0) len = 0;+ int k = copy_str(out, out_size, s, len);+ if (k + 3 < out_size) { memcpy(out + k, ELLIPSIS, 4); k += 3; }+ return k;+}++static float ellipsize_raw(const char *s, float weight, float size, float box_w, int force, char *out, int out_size) {+ int font = font_for(weight);+ if (text_needs_layout(s, font)) return text_layout_ellipsize(s, font, size, box_w, force, out, out_size);+ /* Inter covers the whole text, and it has no marks or joiners (those go through textlayout.c):+ * every code point is a cluster */+ float ell = text_glyph(0x2026, font, size)->adv;+ float w = 0, best_w = 0;+ uint32_t prev = 0;+ int best = 0;+ const char *p = s;+ for (;;) {+ const char *q = p;+ uint32_t cp = utf8_next(&q);+ if (!cp || cp == '\n') break;+ float adv = text_glyph(cp, font, size)->adv + kern(font, size, prev, cp);+ if (w + adv + ell <= box_w + 0.5f) { best = (int)(q - s); best_w = w + adv; }+ w += adv;+ prev = cp;+ p = q;+ }+ if (!force && w <= box_w + 0.5f) { copy_str(out, out_size, s, (int)(p - s)); return -1; }+ text_ellipsis_join(out, out_size, s, best);+ return best_w + ell;+}++/* Byte ranges of the lines (logical metrics). */+/* Cut positions are remembered like measurements (a list repaints the same labels every frame):+ * key = text and parameters, value = the prefix length in bytes (-1: it fits) and the width. */+#define EC_SETS 2048+static struct { uint64_t key; int cut; float w; } ec_cache[EC_SETS];++float text_ellipsize(const char *s, float weight, float size, float box_w, int force, char *out, int out_size) {+ uint64_t k = tm_key(s, weight, size, 0, box_w, 2 + force);+ unsigned slot = (unsigned)(k >> 17) & (EC_SETS - 1);+ if (ec_cache[slot].key == k) {+ int cut = ec_cache[slot].cut;+ if (cut < 0) copy_str(out, out_size, s, (int)strlen(s));+ else text_ellipsis_join(out, out_size, s, cut);+ return ec_cache[slot].w;+ }+ float w = ellipsize_raw(s, weight, size, box_w, force, out, out_size);+ int len = (int)strlen(out);+ if (w >= 0 && out_size > 4 && len < out_size - 1) { /* only if out wasn't truncated by its size */+ ec_cache[slot].key = k;+ ec_cache[slot].cut = len >= 3 ? len - 3 : 0;+ ec_cache[slot].w = w;+ } else if (w < 0) {+ ec_cache[slot].key = k;+ ec_cache[slot].cut = -1;+ ec_cache[slot].w = w;+ }+ return w;+}++static int line_ranges(const char *s, int font, float size, float box_w, int nowrap, int *bs, int *be, int max) {+ if (text_needs_layout(s, font)) return text_layout_line_bytes(s, font, size, box_w, nowrap, bs, be, max);+ int n = wrap(s, font, size, box_w, nowrap, lines, MAX_LINES);+ if (n > max) n = max;+ for (int i = 0; i < n; i++) { bs[i] = (int)(lines[i].start - s); be[i] = (int)(lines[i].end - s); }+ return n;+}++static void draw_lines(Canvas *c, const char *s, int font, float size, float line_h,+ float x, float y, float box_w, int align, int nowrap, int max_lines, uint32_t argb) {+ if (text_needs_layout(s, font)) text_layout_draw_n(c, s, font, size, line_h, x, y, box_w, align, nowrap, max_lines, argb);+ else draw_fast(c, s, font, size, line_h, x, y, box_w, align, nowrap, max_lines, argb);+}++void text_draw_ex(Canvas *c, const char *s, float weight, float size, float line_h,+ float x, float y, float box_w, int align, int nowrap, int max_lines, int ellipsis, uint32_t argb) {+ if (max_lines < 0) max_lines = 0;+ if (!ellipsis && !max_lines) { text_draw(c, s, weight, size, line_h, x, y, box_w, align, nowrap, argb); return; }+ int font = font_for(weight);+ float k = text_paint_scale > 0 ? text_paint_scale : 1;+ float ls = size / k, lw = box_w / k, lh = text_line_height(size, line_h);+ static char buf[8192], cut[8200];+ if (nowrap && !strchr(s, '\n')) { /* the common case: one line (a file name, a title) */+ const char *t = text_ellipsize(s, weight, ls, lw, 0, cut, sizeof cut) < 0 ? s : cut;+ draw_lines(c, t, font, size, line_h, x, y, box_w, align, 1, 1, argb);+ return;+ }+ static int bs[MAX_LINES], be[MAX_LINES];+ int n = line_ranges(s, font, ls, lw, nowrap, bs, be, MAX_LINES);+ int vis = max_lines && n > max_lines ? max_lines : n;+ int more = vis < n;+ /* nothing is cut: the usual path */+ if (!more && !nowrap) { draw_lines(c, s, font, size, line_h, x, y, box_w, align, nowrap, 0, argb); return; }+ if (!more && nowrap) {+ float w, h;+ text_measure_ex(s, weight, ls, 0, 0, 1, 0, &w, &h);+ if (w <= lw + 0.5f) { draw_lines(c, s, font, size, line_h, x, y, box_w, align, nowrap, 0, argb); return; }+ }+ /* lines before the last visible one, as usual (wrapped text); nowrap lines each on their own */+ int first_cut = nowrap ? 0 : vis - 1;+ if (first_cut > 0) draw_lines(c, s, font, size, line_h, x, y, box_w, align, nowrap, first_cut, argb);+ for (int i = first_cut; i < vis; i++) {+ float ly = y + i * lh;+ if (ly > c->clip.y1 || ly + lh < c->clip.y0) continue;+ /* the last visible line of wrapped text carries the rest of its paragraph */+ int a = bs[i], b = be[i];+ if (!nowrap && i == vis - 1) { b = a; while (s[b] && s[b] != '\n') b++; }+ copy_str(buf, sizeof buf, s + a, b - a);+ int force = i == vis - 1 && more;+ text_ellipsize(buf, weight, ls, lw, force, cut, sizeof cut);+ draw_lines(c, cut, font_for(weight), size, line_h, x, ly, box_w, align, 1, 1, argb);+ }+}diff --git a/server/src/ui/textlayout.c b/server/src/ui/textlayout.cindex 1919b3a..97e3e35 100644--- a/server/src/ui/textlayout.c+++ b/server/src/ui/textlayout.c@@ -209,7 +209,8 @@ typedef struct {float width;} Layout;-#define CACHE 48+/* 128: a list of truncated labels needs each one twice (the text and its cut form) */+#define CACHE 128static Layout cache[CACHE];static unsigned tick;static Shaper shaper;@@ -219,7 +220,10 @@ static void layout_free(Layout *L) {memset(L, 0, sizeof *L);}-void text_layout_flush(void) { for (int i = 0; i < CACHE; i++) layout_free(&cache[i]); }+static unsigned generation;+unsigned text_generation(void) { return generation; }++void text_layout_flush(void) { for (int i = 0; i < CACHE; i++) layout_free(&cache[i]); generation++; }static int is_space(uint32_t cp) { return cp == ' ' || cp == 0x3000 || cp == '\t'; }@@ -470,13 +474,27 @@ static Layout *get(const char *s, int font, float size, float max_w, int nowrap)}void text_layout_measure(const char *s, int font, float size, float line_h, float max_w, int nowrap, float *w, float *h) {+ text_layout_measure_ex(s, font, size, line_h, max_w, nowrap, 0, w, h);+}++void text_layout_measure_ex(const char *s, int font, float size, float line_h, float max_w, int nowrap, int max_lines, float *w, float *h) {Layout *L = get(s, font, size, max_w, nowrap);- *w = L ? ceilf(L->width) : 0;- *h = (L ? L->nlines : 1) * text_line_height(size, line_h);+ if (!L) { *w = 0; *h = text_line_height(size, line_h); return; }+ int vis = max_lines > 0 && L->nlines > max_lines ? max_lines : L->nlines;+ float mw = 0;+ for (int i = 0; i < vis; i++) if (L->lines[i].width > mw) mw = L->lines[i].width;+ if (vis < L->nlines && max_w > 0 && mw < max_w) mw = max_w;+ *w = ceilf(vis == L->nlines ? L->width : mw);+ *h = (vis ? vis : 1) * text_line_height(size, line_h);}void text_layout_draw(Canvas *c, const char *s, int font, float size, float line_h,float x, float y, float box_w, int align, int nowrap, uint32_t argb) {+ text_layout_draw_n(c, s, font, size, line_h, x, y, box_w, align, nowrap, 0, argb);+}++void text_layout_draw_n(Canvas *c, const char *s, int font, float size, float line_h,+ float x, float y, float box_w, int align, int nowrap, int max_lines, uint32_t argb) {/* scaled display (text_paint_scale): shaped and broken at the logical size, positions scaled */float sk = text_paint_scale > 0 ? text_paint_scale : 1;Layout *L = get(s, font, size / sk, box_w / sk, nowrap);@@ -493,7 +511,8 @@ void text_layout_draw(Canvas *c, const char *s, int font, float size, float lineocap = L->ng;}float opacity = (argb >> 24) / 255.0f;- for (int li = 0; li < L->nlines; li++) {+ int nl = max_lines > 0 && L->nlines > max_lines ? max_lines : L->nlines;+ for (int li = 0; li < nl; li++) {const LLine *ln = &L->lines[li];float pen = x;if (align == TEXT_CENTER) pen += (box_w - ln->width * sk) / 2;@@ -531,6 +550,95 @@ void text_layout_draw(Canvas *c, const char *s, int font, float size, float line}}+/* ---- truncation ---- */++/* Byte offset of each code point (offs[ncp] = the end). */+static int *cp_bytes(const char *s, int ncp) {+ int *o = malloc(sizeof *o * (size_t)(ncp + 1));+ if (!o) return NULL;+ int i = 0;+ const unsigned char *p = (const unsigned char *)s;+ for (; *p && i < ncp; i++) { o[i] = (int)((const char *)p - s); utf8_decode(&p); }+ for (; i <= ncp; i++) o[i] = (int)((const char *)p - s);+ return o;+}++int text_layout_line_bytes(const char *s, int font, float size, float max_w, int nowrap, int *bs, int *be, int max) {+ Layout *L = get(s, font, size, max_w, nowrap);+ if (!L) return 0;+ int *o = cp_bytes(s, L->ncp);+ if (!o) return 0;+ int n = L->nlines < max ? L->nlines : max;+ for (int i = 0; i < n; i++) { bs[i] = o[L->lines[i].start]; be[i] = o[L->lines[i].end]; }+ free(o);+ return n;+}++static int is_ri(uint32_t cp) { return cp >= 0x1F1E6 && cp <= 0x1F1FF; }++/* May the text be cut before code point k? Only between grapheme clusters, and never inside what+ * the shaper drew as one glyph (a ligature like lam-alef, an Indic syllable, an emoji ZWJ sequence). */+static int cut_ok(const uint32_t *cp, const uint8_t *own, int n, int k) {+ if (k <= 0 || k >= n) return 1;+ uint32_t a = cp[k - 1], b = cp[k];+ if (!own[k]) return 0; /* part of the previous glyph */+ if (sticks_to_prev(b) || uc_mark(b)) return 0; /* marks, joiners, variation selectors, skin tones */+ if (a == 0x200D) return 0; /* after a ZWJ (emoji sequences) */+ if (uc_ccc(a) == 9) return 0; /* after a virama: the conjunct goes on */+ if (b == 0x0E33 || b == 0x0EB3) return 0; /* Thai and Lao SARA AM are spacing marks */+ if (is_ri(b)) { /* flags: pairs of regional indicators */+ int r = 0;+ for (int i = k - 1; i >= 0 && is_ri(cp[i]); i--) r++;+ if (r & 1) return 0;+ }+ return 1;+}++float text_layout_ellipsize(const char *s, int font, float size, float box_w, int force, char *out, int out_size) {+ Layout *L = get(s, font, size, 0, 1);+ if (!L) { text_ellipsis_join(out, out_size, "", 0); return 0; }+ if (!force && L->width <= box_w + 0.5f) { snprintf(out, (size_t)out_size, "%s", s); return -1; }+ float ell = 0;+ Layout *E = get("\xe2\x80\xa6", font, size, 0, 1);+ if (E) ell = E->width;+ L = get(s, font, size, 0, 1); /* the cache may have moved it */+ if (!L) { text_ellipsis_join(out, out_size, "", 0); return ell; }+ int n = L->ncp;+ uint8_t *own = calloc((size_t)n + 1, 1);+ int *o = cp_bytes(s, n);+ float *pre = malloc(sizeof *pre * (size_t)(n + 1));+ if (!own || !o || !pre) { free(own); free(o); free(pre); text_ellipsis_join(out, out_size, "", 0); return ell; }+ for (int g = 0; g < L->ng; g++) if (L->g[g].cp >= 0 && L->g[g].cp < n) own[L->g[g].cp] = 1;+ pre[0] = 0;+ for (int i = 0; i < n; i++) pre[i + 1] = pre[i] + L->cpw[i];+ uint32_t *cps = malloc(sizeof *cps * (size_t)(n + 1));+ if (cps) memcpy(cps, L->cp, sizeof *cps * (size_t)n);+ /* the longest prefix that fits by the original widths; the cut form is shaped again (final+ * forms, bidi with the "…" at the end of the paragraph: on the left in RTL) and, if shaping+ * made it wider, one cluster less */+ float width = ell;+ int k = n;+ while (k > 0 && (!cps || !cut_ok(cps, own, n, k) || pre[k] + ell > box_w + 0.5f)) k--;+ for (int tries = 0; tries < 16; tries++) {+ text_ellipsis_join(out, out_size, s, o[k]);+ Layout *T = get(out, font, size, 0, 1);+ width = T ? T->width : pre[k] + ell;+ if (width <= box_w + 0.5f || k == 0) break;+ do k--; while (k > 0 && (!cps || !cut_ok(cps, own, n, k)));+ }+ free(own); free(o); free(pre); free(cps);+ return width;+}++/* Debugging and tests: the logical code point index of each glyph of the first line, in visual order. */+int text_layout_visual(const char *s, int font, float size, int *cps, int max) {+ Layout *L = get(s, font, size, 0, 1);+ if (!L || !L->nlines) return 0;+ int n = 0;+ for (int k = 0; k < L->lines[0].nvis && n < max; k++) cps[n++] = L->g[L->vis[L->lines[0].vis0 + k]].cp;+ return n;+}+int text_direction(const char *s) {uint32_t buf[256];int n = 0;diff --git a/server/src/ui/transform.c b/server/src/ui/transform.cnew file mode 100644index 0000000..0b9adde--- /dev/null+++ b/server/src/ui/transform.c@@ -0,0 +1,62 @@+/* transform.c — 2D affine transforms for `transform: scale(...) rotate(...)` (paint and hit testing+ * only: layout never sees them, as in CSS). */+#include "ui.h"++#include <math.h>++Affine affine_identity(void) { return (Affine){ 1, 0, 0, 1, 0, 0 }; }++Affine affine_mul(Affine m, Affine n) {+ return (Affine){+ m.a * n.a + m.c * n.b, m.b * n.a + m.d * n.b,+ m.a * n.c + m.c * n.d, m.b * n.c + m.d * n.d,+ m.a * n.e + m.c * n.f + m.e, m.b * n.e + m.d * n.f + m.f,+ };+}++int affine_invert(Affine m, Affine *out) {+ float det = m.a * m.d - m.b * m.c;+ if (fabsf(det) < 1e-8f) return 0;+ float i = 1 / det;+ *out = (Affine){ m.d * i, -m.b * i, -m.c * i, m.a * i,+ (m.c * m.f - m.d * m.e) * i, (m.b * m.e - m.a * m.f) * i };+ return 1;+}++void affine_apply(Affine m, float x, float y, float *ox, float *oy) {+ *ox = m.a * x + m.c * y + m.e;+ *oy = m.b * x + m.d * y + m.f;+}++Box affine_box(Affine m, Box b) {+ float xs[4], ys[4];+ affine_apply(m, b.x0, b.y0, &xs[0], &ys[0]);+ affine_apply(m, b.x1, b.y0, &xs[1], &ys[1]);+ affine_apply(m, b.x1, b.y1, &xs[2], &ys[2]);+ affine_apply(m, b.x0, b.y1, &xs[3], &ys[3]);+ Box r = { xs[0], ys[0], xs[0], ys[0] };+ for (int i = 1; i < 4; i++) {+ r.x0 = fminf(r.x0, xs[i]); r.y0 = fminf(r.y0, ys[i]);+ r.x1 = fmaxf(r.x1, xs[i]); r.y1 = fmaxf(r.y1, ys[i]);+ }+ return r;+}++int style_rotates(float deg) { return fmodf(deg, 360) != 0; }++static float origin(Dim d, float size) {+ return d.unit == UNIT_PCT ? size * d.v / 100 : d.unit == UNIT_PX ? d.v : size / 2;+}++Affine style_transform(const Style *st, float x, float y, float w, float h) {+ const StyleExt *s = st->ext;+ if (!s) return affine_identity();+ float ox = x + origin(s->origin_x, w), oy = y + origin(s->origin_y, h);+ float r = s->rotate * 3.14159265358979f / 180, co = cosf(r), si = sinf(r);+ /* translate(o) · rotate(r) · scale(sx, sy) · translate(-o); y grows downwards, so a positive+ * angle turns clockwise on screen, like CSS */+ Affine m = { co * s->scale_x, si * s->scale_x, -si * s->scale_y, co * s->scale_y, 0, 0 };+ m.e = ox - (m.a * ox + m.c * oy);+ m.f = oy - (m.b * ox + m.d * oy);+ return m;+}diff --git a/server/src/ui/ui.h b/server/src/ui/ui.hindex 3528f52..19fcc46 100644--- a/server/src/ui/ui.h+++ b/server/src/ui/ui.h@@ -2,6 +2,7 @@#ifndef LORD_UI_H#define LORD_UI_H+#include <stddef.h>#include <stdint.h>#include "../canvas.h"#include "otf.h"@@ -31,6 +32,8 @@ typedef struct {float gap;uint32_t bg, border_color, color, shadow_color;uint8_t has_gradient;+ uint8_t text_overflow; /* textOverflow: 'ellipsis' */+ uint8_t line_clamp; /* numberOfLines / lineClamp: at most N lines, "…" on the last (0 = no limit) */uint32_t grad_from, grad_to;float grad_angle;float radius, border_width, opacity;@@ -38,13 +41,57 @@ typedef struct {float font_size, line_height, font_weight;float translate_x, translate_y;float z_index;+ /* Per-side and logical edges, scale/rotate: rarely used, so they live in an allocation of their+ * own (StyleExt, created by the first such property); every node walk stays as fast as before. */+ struct StyleExt *ext;} Style;+typedef struct StyleExt {+ /* A value below only overrides the shorthand (borderWidth, borderColor, borderRadius, margin*,+ * padding*) when its bit is in edge_set (ES_*); start/end follow the node's direction and win+ * over the physical side, as in React Native. */+ uint32_t edge_set;+ /* transform: scale(...) rotate(...) for painting only (layout and translate are unaffected) */+ float scale_x, scale_y, rotate;+ float border_side[6]; /* widths: left, top, right, bottom, start, end */+ uint32_t border_side_color[6];+ float margin_inline[2], padding_inline[2]; /* start, end */+ Dim inset_inline[2]; /* insetInlineStart / insetInlineEnd (auto = unset) */+ float radius_corner[8]; /* top-left, top-right, bottom-right, bottom-left, top-start, top-end, bottom-start, bottom-end */+ Dim origin_x, origin_y; /* transformOrigin, 50% 50% by default */+ /* not style: the edges resolved for the node's direction (layout.c node_resolve_edges), physical L, T, R, B */+ struct {+ float mg[4], pd[4], bw[4];+ uint32_t bc[4];+ float rad[4]; /* top-left, top-right, bottom-right, bottom-left */+ uint8_t ok, rtl, plain; /* resolved for this style and direction; uniform border and radius */+ } r;+} StyleExt;+#define STYLE_EXT_VALUES offsetof(StyleExt, r) /* what lord.setStyle compares */++enum { SIDE_START = 4, SIDE_END = 5 };+#define ES_BW(i) (1u << (i)) /* border width of side i (0..5) */+#define ES_BC(i) (1u << (6 + (i))) /* border color of side i */+#define ES_MARGIN(i) (1u << (12 + (i))) /* margin start (0) / end (1) */+#define ES_PADDING(i) (1u << (14 + (i))) /* padding start (0) / end (1) */+#define ES_RADIUS(i) (1u << (16 + (i))) /* corner i (0..7) */++/* 2D affine transform: (x, y) → (a x + c y + e, b x + d y + f). */+typedef struct { float a, b, c, d, e, f; } Affine;+typedef struct Image Image;/* Box in screen coordinates; empty if x1 <= x0. */typedef struct { float x0, y0, x1, y1; } Box;+/* Transforms (layout.c place), only for nodes that have one or are inside one: own = this node's+ * scale/rotate around its origin, in layout coordinates; world = its ancestors' and its own+ * (layout → screen); inv = the inverse of world. */+typedef struct {+ Affine own, world, inv;+ uint64_t sig; /* paint.c: geometry of its subtree in the last damage pass (own_tf) */+} NodeTf;+typedef struct Node {int id, type;Style s;@@ -53,6 +100,8 @@ typedef struct Node {int term; /* NODE_TERM: session id; NODE_SURFACE: Wayland surface id; NODE_MEDIA: source (media/) */uint8_t protect; /* protected window: black in screenshots, recordings and remote desktop (media/capture.c) */uint8_t rtl; /* effective direction (computed in layout) */+ uint8_t own_tf, has_tf; /* it has a scale/rotate; it or an ancestor has one (tf is set) */+ uint8_t layout_ok, layout_rtl; /* its subtree is laid out for its current w × h and direction */struct Node *parent, *first, *last, *next, *prev;float x, y, w, h; /* layout relative to the parent */float ax, ay; /* absolute position on screen */@@ -60,8 +109,16 @@ typedef struct Node {float measure_maxw, measure_w, measure_h;uint8_t paint_dirty; /* its style or text changed */Box prev_box; /* what it occupied on screen in the last frame */+ NodeTf *tf;} Node;+/* The node's edges for its direction (after layout's prepare): straight from the style unless it+ * has per-side or logical ones. Arrays are physical L, T, R, B. */+static inline const float *node_margin(const Node *n) { return n->s.ext ? n->s.ext->r.mg : n->s.margin; }+static inline const float *node_padding(const Node *n) { return n->s.ext ? n->s.ext->r.pd : n->s.padding; }+static inline float node_border(const Node *n, int e) { return n->s.ext ? n->s.ext->r.bw[e] : n->s.border_width; }+static inline int node_edges_plain(const Node *n) { return !n->s.ext || n->s.ext->r.plain; }+typedef struct {Node **nodes;int cap;@@ -91,6 +148,7 @@ void node_insert_before(Node *p, Node *c, Node *before);void node_detach(Node *c);void node_set_text(Node *n, const char *s);void node_invalidate(Node *n);+void node_moved(Node *n); /* only left/top changed (window drag): no repaint of its content */int node_gather_text(const Node *n, char *buf, int size);int node_children_ordered(Node *n, Node **out, int max);void damage_add(Box b);@@ -104,6 +162,23 @@ int style_reset(Style *s, const char *key);/* layout.c */void layout_root(Node *root, float w, float h);+void node_resolve_edges(Node *n);++/* transform.c: affine math shared by layout, paint and hit testing */+Affine affine_identity(void);+Affine affine_mul(Affine m, Affine n); /* m after n: (m ∘ n)(p) = m(n(p)) */+int affine_invert(Affine m, Affine *out); /* 0 if singular */+void affine_apply(Affine m, float x, float y, float *ox, float *oy);+Box affine_box(Affine m, Box b); /* bounding box of the transformed rectangle */+int style_rotates(float deg);+/* inline: layout asks it of every node */+static inline int style_has_transform(const Style *s) {+ const struct StyleExt *x = s->ext;+ return x && (x->scale_x != 1 || x->scale_y != 1 || (x->rotate != 0 && style_rotates(x->rotate)));+}+/* The node's own transform: translate(origin) · rotate · scale · translate(-origin), with the origin+ * resolved against its border box at (x, y, w, h). */+Affine style_transform(const Style *s, float x, float y, float w, float h);/* text.c */typedef struct {@@ -139,6 +214,17 @@ extern float text_paint_scale;void text_measure(const char *s, float weight, float size, float line_h, float max_w, int nowrap, float *w, float *h);void text_draw(Canvas *c, const char *s, float weight, float size, float line_h,float x, float y, float box_w, int align, int nowrap, uint32_t argb);+/* With truncation: at most max_lines lines (0 = all) and, if ellipsis, "…" where text is cut (the+ * last visible line when more text follows, and any nowrap line wider than box_w). */+void text_measure_ex(const char *s, float weight, float size, float line_h, float max_w, int nowrap,+ int max_lines, float *w, float *h);+void text_draw_ex(Canvas *c, const char *s, float weight, float size, float line_h,+ float x, float y, float box_w, int align, int nowrap, int max_lines, int ellipsis, uint32_t argb);+/* The truncated form of one line: the longest prefix that ends on a grapheme cluster (never inside+ * a ligature, a mark sequence, an emoji ZWJ sequence or a flag) and fits in box_w with "…" after it.+ * Writes it (with the "…") to out and returns its width; returns -1 and copies s if s already fits+ * and force is 0. Shaped text is re-shaped, so Arabic letters take their final forms. */+float text_ellipsize(const char *s, float weight, float size, float box_w, int force, char *out, int out_size);Otf *text_font_otf(int font);float text_font_scale(int font, float size);int text_font_kern_glyphs(int font, uint32_t a, uint32_t b); /* font units */@@ -150,6 +236,13 @@ void text_layout_measure(const char *s, int font, float size, float line_h, flovoid text_layout_draw(Canvas *c, const char *s, int font, float size, float line_h,float x, float y, float box_w, int align, int nowrap, uint32_t argb);void text_layout_flush(void);+unsigned text_generation(void); /* changes when text may measure differently (language) */+float text_layout_ellipsize(const char *s, int font, float size, float box_w, int force, char *out, int out_size);+void text_layout_measure_ex(const char *s, int font, float size, float line_h, float max_w, int nowrap, int max_lines, float *w, float *h);+void text_layout_draw_n(Canvas *c, const char *s, int font, float size, float line_h,+ float x, float y, float box_w, int align, int nowrap, int max_lines, uint32_t argb);+int text_layout_line_bytes(const char *s, int font, float size, float max_w, int nowrap, int *bs, int *be, int max);+int text_ellipsis_join(char *out, int out_size, const char *s, int len); /* prefix + "…" */void text_set_language(const char *lang); /* picks the CJK font (ja/ko/zh) */int text_script_fallback(uint32_t cp, int bold); /* terminal: font per script */int text_direction(const char *s); /* 1 if the first strong character is RTL */diff --git a/server/src/users/homedirs.c b/server/src/users/homedirs.cindex 867fdc1..77a2280 100644--- a/server/src/users/homedirs.c+++ b/server/src/users/homedirs.c@@ -11,23 +11,23 @@/* The same list as tools/iso/rootfs/usr/lib/lordos/lordos-live-prep (there with _ for spaces). */static const char *const names[3][HOMEDIRS_COUNT] = {- { "Escritorio", "Documentos", "Descargas", "Música", "Imágenes", "Videos" },+ { "Escritorio", "Documentos", "Descargas", "Música", "Imágenes", "Videos" }, /* i18n-ok */{ "Desktop", "Documents", "Downloads", "Music", "Pictures", "Videos" },- { "Área de trabalho", "Documentos", "Downloads", "Música", "Imagens", "Vídeos" },+ { "Área de trabalho", "Documentos", "Downloads", "Música", "Imagens", "Vídeos" }, /* i18n-ok */};static const char *const xdg_keys[HOMEDIRS_COUNT] = { "DESKTOP", "DOCUMENTS", "DOWNLOAD", "MUSIC", "PICTURES", "VIDEOS" };const char *homedirs_ui_lang(const char *locale) {- if (locale && !strncmp(locale, "en", 2)) return "en";+ if (locale && !strncmp(locale, "es", 2)) return "es";if (locale && !strncmp(locale, "pt", 2)) return "pt";- return "es";+ return "en"; /* English is the default language */}-static int lang_index(const char *ui) { return !strcmp(ui, "en") ? 1 : !strcmp(ui, "pt") ? 2 : 0; }+static int lang_index(const char *ui) { return !strcmp(ui, "es") ? 0 : !strcmp(ui, "pt") ? 2 : 1; }const char *homedirs_name(const char *ui_lang, int i) {if (i < 0 || i >= HOMEDIRS_COUNT) return NULL;- return names[lang_index(ui_lang ? ui_lang : "es")][i];+ return names[lang_index(ui_lang ? ui_lang : "en")][i];}/* New file (O_EXCL, no symlinks followed) relative to the open directory dfd. */diff --git a/server/src/users/homedirs.h b/server/src/users/homedirs.hindex be7bdba..a7e0128 100644--- a/server/src/users/homedirs.h+++ b/server/src/users/homedirs.h@@ -7,7 +7,7 @@#include <sys/types.h>-/* UI language for a locale ("es_AR.UTF-8" → "es"): es, en or pt (Spanish otherwise). */+/* UI language for a locale ("es_AR.UTF-8" → "es"): es, en or pt (English otherwise). */const char *homedirs_ui_lang(const char *locale);/* Visible name of each folder (0..5: desktop, documents, downloads, music, pictures, videos). */const char *homedirs_name(const char *ui_lang, int i);diff --git a/server/src/users/users_admin.c b/server/src/users/users_admin.cindex e7715f6..c0f6eef 100644--- a/server/src/users/users_admin.c+++ b/server/src/users/users_admin.c@@ -173,14 +173,14 @@ static int autologin_set(const char *user) {/* Common folders in the system language (shown by Files) and their language. */static void prepare_home(const struct passwd *pw) {- char lang[64] = "es_ES.UTF-8";+ char lang[64] = "en_US.UTF-8";FILE *f = fopen("/etc/default/locale", "r");char line[128];while (f && fgets(line, sizeof line, f)) if (sscanf(line, "LANG=%63[A-Za-z_.@0-9-]", lang) == 1) break;if (f) fclose(f);char path[PATH_MAX];/* Escritorio, Documentos… and ~/.config/user-dirs.dirs in the system language (homedirs.c) */- if (homedirs_create(pw->pw_dir, pw->pw_uid, pw->pw_gid, lang)) admin_say("LOG", "aviso: no se pudieron crear todas las carpetas");+ if (homedirs_create(pw->pw_dir, pw->pw_uid, pw->pw_gid, lang)) admin_log("users.homedirsWarning", NULL);snprintf(path, sizeof path, "%s/.config", pw->pw_dir);if (!mkdir(path, 0755) && chown(path, pw->pw_uid, pw->pw_gid)) { /* carry on */ }snprintf(path, sizeof path, "%s/.config/lordos", pw->pw_dir);@@ -190,7 +190,7 @@ static void prepare_home(const struct passwd *pw) {snprintf(text, sizeof text, "LANG=%s\n", lang);if (!write_file(path, text, strlen(text), 0644) && chown(path, pw->pw_uid, pw->pw_gid)) { /* carry on */ }snprintf(path, sizeof path, "%s/.config/lordos/settings.json", pw->pw_dir);- /* UI language: the system's if there's a catalog (es, en, pt); otherwise Spanish */+ /* UI language: the system's if there's a catalog (es, en, pt); otherwise English */const char *ui = homedirs_ui_lang(lang);snprintf(text, sizeof text, "{\n \"language\": \"%s\"\n}\n", ui);if (!write_file(path, text, strlen(text), 0644) && chown(path, pw->pw_uid, pw->pw_gid)) { /* carry on */ }@@ -201,22 +201,22 @@ static void prepare_home(const struct passwd *pw) {void users_act_add(const AdminReq *r, const char *arg, size_t len) {(void)r;char *buf = strndup(arg, len), *f[4];- if (!buf || !split(buf, f, 4)) { admin_say("ERR", "argumento inválido"); free(buf); return; }+ if (!buf || !split(buf, f, 4)) { admin_err("admin.invalidArgument", NULL); free(buf); return; }const char *name = f[0], *full = f[1], *pass = f[2];int adm = !strcmp(f[3], "1");- if (!valid_name(name) || !valid_full(full) || !valid_pass(pass)) admin_say("ERR", "nombre o contraseña inválidos");- else if (getpwnam(name) || getgrnam(name)) admin_say("ERR", "ya existe «%s»", name);+ if (!valid_name(name) || !valid_full(full) || !valid_pass(pass)) admin_err("users.badNameOrPassword", NULL);+ else if (getpwnam(name) || getgrnam(name)) admin_err("users.exists", "name", name, NULL);else {const char *const a[] = { "/usr/sbin/useradd", "--create-home", "--shell", "/bin/bash", "--user-group", "--comment", full, name, NULL };struct passwd *pw;- if (admin_run(a) || !(pw = getpwnam(name))) admin_say("ERR", "useradd falló");- else if (set_password(name, pass)) admin_say("ERR", "no se pudo poner la contraseña");+ if (admin_run(a) || !(pw = getpwnam(name))) admin_err("sys.programError", "program", "useradd", NULL);+ else if (set_password(name, pass)) admin_err("users.setPasswordFailed", NULL);else {if (adm) { const char *const g[] = { "/usr/sbin/usermod", "--append", "--groups", ADMIN_GROUP, name, NULL }; admin_run(g); print_group(name, 1); }if (getgrnam("pipewire")) { const char *const g[] = { "/usr/sbin/usermod", "--append", "--groups", "pipewire", name, NULL }; admin_run(g); } /* real-time sound (docs/SOUND.md) */if (getgrnam("plugdev")) { const char *const g[] = { "/usr/sbin/usermod", "--append", "--groups", "plugdev", name, NULL }; admin_run(g); } /* FIDO2 security keys (docs/PASSWORDS.md) */prepare_home(pw);- admin_say("OK", "usuario %s creado", name);+ admin_ok("users.created", "name", name, NULL);}}explicit_bzero(buf, len);@@ -225,13 +225,13 @@ void users_act_add(const AdminReq *r, const char *arg, size_t len) {void users_act_del(const AdminReq *r, const char *arg, size_t len) {char *buf = strndup(arg, len), *f[2];- if (!buf || !split(buf, f, 2)) { admin_say("ERR", "argumento inválido"); free(buf); return; }+ if (!buf || !split(buf, f, 2)) { admin_err("admin.invalidArgument", NULL); free(buf); return; }const char *name = f[0];int keep = !strcmp(f[1], "1");struct passwd *pw = person(name);- if (!pw) admin_say("ERR", "usuario inválido");- else if (!strcmp(name, r->user)) admin_say("ERR", "no se puede borrar la cuenta con la que estás");- else if (in_group(name, ADMIN_GROUP) && admins() <= 1) admin_say("ERR", "es el único administrador");+ if (!pw) admin_err("users.invalid", NULL);+ else if (!strcmp(name, r->user)) admin_err("users.deleteSelf", NULL);+ else if (in_group(name, ADMIN_GROUP) && admins() <= 1) admin_err("users.lastAdmin", NULL);else {/* their session (and everything of theirs) ends first */const char *const k[] = { "/usr/bin/pkill", "--signal", "KILL", "--uid", name, NULL };@@ -239,7 +239,7 @@ void users_act_del(const AdminReq *r, const char *arg, size_t len) {usleep(300000);const char *const a_keep[] = { "/usr/sbin/userdel", name, NULL };const char *const a_rm[] = { "/usr/sbin/userdel", "--remove", name, NULL };- if (admin_run(keep ? a_keep : a_rm)) admin_say("ERR", "userdel falló");+ if (admin_run(keep ? a_keep : a_rm)) admin_err("sys.programError", "program", "userdel", NULL);else {char p[128], au[40];snprintf(p, sizeof p, USERS_DIR "/%s.json", name);@@ -248,7 +248,7 @@ void users_act_del(const AdminReq *r, const char *arg, size_t len) {unlink(p);autologin_get(au, sizeof au);if (!strcmp(au, name)) autologin_set("");- admin_say("OK", "usuario %s borrado", name);+ admin_ok("users.deleted", "name", name, NULL);}}free(buf);@@ -256,32 +256,32 @@ void users_act_del(const AdminReq *r, const char *arg, size_t len) {void users_act_passwd(const AdminReq *r, const char *arg, size_t len) {char *buf = strndup(arg, len), *f[3];- if (!buf || !split(buf, f, 3)) { admin_say("ERR", "argumento inválido"); free(buf); return; }+ if (!buf || !split(buf, f, 3)) { admin_err("admin.invalidArgument", NULL); free(buf); return; }const char *name = f[0], *pass = f[1], *old = f[2];int self = !strcmp(name, r->user);- if (!person(name) || !valid_pass(pass)) admin_say("ERR", "usuario o contraseña inválidos");- else if (!self && !r->admin) admin_say("ERR", "solo un administrador cambia la contraseña de otro usuario");- else if (self && !check_password(name, old)) { sleep(1); admin_say("ERR", "la contraseña actual no es correcta"); }- else if (set_password(name, pass)) admin_say("ERR", "no se pudo cambiar la contraseña");- else admin_say("OK", "contraseña cambiada");+ if (!person(name) || !valid_pass(pass)) admin_err("users.badNameOrPassword", NULL);+ else if (!self && !r->admin) admin_err("users.passwordNotAllowed", NULL);+ else if (self && !check_password(name, old)) { sleep(1); admin_err("users.wrongPassword", NULL); }+ else if (set_password(name, pass)) admin_err("users.setPasswordFailed", NULL);+ else admin_ok("users.passwordChanged", NULL);explicit_bzero(buf, len);free(buf);}void users_act_admin(const AdminReq *r, const char *arg, size_t len) {char *buf = strndup(arg, len), *f[2];- if (!buf || !split(buf, f, 2)) { admin_say("ERR", "argumento inválido"); free(buf); return; }+ if (!buf || !split(buf, f, 2)) { admin_err("admin.invalidArgument", NULL); free(buf); return; }const char *name = f[0];int on = !strcmp(f[1], "1");(void)r;- if (!person(name) || (strcmp(f[1], "0") && strcmp(f[1], "1"))) admin_say("ERR", "argumento inválido");- else if (!on && in_group(name, ADMIN_GROUP) && admins() <= 1) admin_say("ERR", "es el único administrador");+ if (!person(name) || (strcmp(f[1], "0") && strcmp(f[1], "1"))) admin_err("admin.invalidArgument", NULL);+ else if (!on && in_group(name, ADMIN_GROUP) && admins() <= 1) admin_err("users.lastAdmin", NULL);else {const char *const add[] = { "/usr/sbin/usermod", "--append", "--groups", ADMIN_GROUP, name, NULL };const char *const del[] = { "/usr/bin/gpasswd", "--delete", name, ADMIN_GROUP, NULL };- if (on == in_group(name, ADMIN_GROUP)) admin_say("OK", "sin cambios");- else if (admin_run(on ? add : del)) admin_say("ERR", "no se pudo cambiar el grupo");- else { print_group(name, on); admin_say("OK", "%s", on ? "ahora es administrador" : "ya no es administrador"); }+ if (on == in_group(name, ADMIN_GROUP)) admin_ok("users.unchanged", NULL);+ else if (admin_run(on ? add : del)) admin_err("users.groupFailed", NULL);+ else { print_group(name, on); admin_ok(on ? "users.nowAdmin" : "users.noLongerAdmin", "name", name, NULL); }}free(buf);}@@ -312,11 +312,11 @@ static unsigned char *read_user_image(const AdminReq *r, const char *path, size_void users_act_avatar(const AdminReq *r, const char *arg, size_t len) {char *buf = strndup(arg, len), *f[3];- if (!buf || !split(buf, f, 3)) { admin_say("ERR", "argumento inválido"); free(buf); return; }+ if (!buf || !split(buf, f, 3)) { admin_err("admin.invalidArgument", NULL); free(buf); return; }const char *name = f[0], *color = f[1], *img = f[2];int ok_color = !color[0] || (strlen(color) == 7 && color[0] == '#' && strspn(color + 1, "0123456789abcdefABCDEF") == 6);- if (!person(name) || !ok_color) admin_say("ERR", "argumento inválido");- else if (strcmp(name, r->user) && !r->admin) admin_say("ERR", "solo un administrador cambia el avatar de otro usuario");+ if (!person(name) || !ok_color) admin_err("admin.invalidArgument", NULL);+ else if (strcmp(name, r->user) && !r->admin) admin_err("users.avatarNotAllowed", NULL);else {mkdir("/var/lib/lordos", 0755);mkdir(USERS_DIR, 0755);@@ -329,12 +329,12 @@ void users_act_avatar(const AdminReq *r, const char *arg, size_t len) {else if (img[0]) {size_t n = 0;unsigned char *data = read_user_image(r, img, &n);- if (!data) { admin_say("ERR", "la imagen tiene que ser PNG o JPEG de tu carpeta personal (hasta 4 MB)"); free(buf); return; }+ if (!data) { admin_err("users.badAvatarImage", NULL); free(buf); return; }bad |= write_file(p, data, n, 0644);free(data);}- if (bad) admin_say("ERR", "no se pudo guardar el avatar");- else admin_say("OK", "avatar guardado");+ if (bad) admin_err("users.avatarFailed", NULL);+ else admin_ok("users.avatarSaved", NULL);}free(buf);}@@ -342,7 +342,7 @@ void users_act_avatar(const AdminReq *r, const char *arg, size_t len) {void users_act_autologin(const AdminReq *r, const char *arg, size_t len) {(void)r;(void)len;- if (arg[0] && !person(arg)) { admin_say("ERR", "usuario inválido"); return; }- if (autologin_set(arg)) admin_say("ERR", "no se pudo escribir %s", SESSION_CONF);- else admin_say("OK", "%s", arg[0] ? "inicio automático prendido" : "inicio automático apagado");+ if (arg[0] && !person(arg)) { admin_err("users.invalid", NULL); return; }+ if (autologin_set(arg)) admin_err("sys.writeFailed", "path", SESSION_CONF, NULL);+ else admin_ok(arg[0] ? "users.autologinOn" : "users.autologinOff", NULL);}diff --git a/server/src/vault/keyring.c b/server/src/vault/keyring.cindex 018f73b..20017b1 100644--- a/server/src/vault/keyring.c+++ b/server/src/vault/keyring.c@@ -1,15 +1,15 @@-/* keyring.c — el llavero del sistema (ver docs/CONTRASENAS.md, «El llavero de la sesión»).+/* keyring.c — the system keyring (see docs/PASSWORDS.md, "The session keyring").*- * Es una bóveda aparte, login.lvault, como el llavero «inicio de sesión» de macOS: se abre sola- * al ingresar, con la contraseña de la sesión (lord-sessiond la verifica y se la pasa a la sesión- * una sola vez; lord-server la reenvía acá y la borra), y queda abierta hasta cerrar la sesión.- * Bloquear la pantalla no la cierra (la bóveda de Contraseñas sí).+ * It is a separate vault, login.lvault, like macOS's "login" keyring: it unlocks by itself at+ * login with the session password (lord-sessiond verifies it and hands it to the session+ * only once; lord-server forwards it here and wipes it), and stays open until logout.+ * Locking the screen does not lock it (the Passwords vault does lock).*- * Guarda dos clases de ítems (entradas de la bóveda con un "x" que dice de quién son):- * - del llavero de LordOS (lord.keyring / sdk keyring): x.kr = {owner, service, account, shared};- * una app ve solo los suyos, salvo que el usuario se los comparta (shared);- * - de Secret Service (D-Bus, apps Linux): x.ss = {attrs, ctype}; como en gnome-keyring,- * cualquier app de la sesión que hable D-Bus puede leerlos con el llavero abierto. */+ * It stores two kinds of items (vault entries with an "x" that says whose they are):+ * - from the LordOS keyring (lord.keyring / sdk keyring): x.kr = {owner, service, account, shared};+ * an app only sees its own, unless the user shares them with it (shared);+ * - from Secret Service (D-Bus, Linux apps): x.ss = {attrs, ctype}; as in gnome-keyring,+ * any app of the session that speaks D-Bus can read them while the keyring is open. */#include "vault_int.h"#include "smem.h"#include "secretsvc.h"@@ -29,7 +29,7 @@ static int valid_owner(const char *s) {return 1;}-/* x.kr de una entrada: owner/service/account (los copia acotados) y si ve el pedido de `who` */+/* x.kr of an entry: owner/service/account (copied, bounded) and whether `who`'s request can see it */typedef struct { char owner[72], service[256], account[256]; int shared_with; } KrInfo;static int kr_info(const VEntry *e, const char *who, KrInfo *k) {@@ -66,7 +66,7 @@ static void kr_item_json(VjB *b, const VEntry *e, const KrInfo *k, int with_secrvb_close(b, '}');}-/* arma el JSON de una entrada del llavero y la guarda con vm_upsert */+/* builds the JSON of a keyring entry and stores it with vm_upsert */static int kr_store(const char *id, const char *owner, const char *service, const char *account, const char *label, const char *secret, const char *shared_json) {VjB b;vb_init(&b);@@ -107,7 +107,7 @@ int keyring_handle(Chan *c, uint32_t id, const char *op, const Vj *j) {vj_getsbuf(j, 0, "owner", owner, sizeof owner);vj_getsbuf(j, 0, "service", service, sizeof service);vj_getsbuf(j, 0, "account", account, sizeof account);- /* la app Contraseñas administra todo el llavero; el resto pasa por lord-server, que pone el owner */+ /* the Passwords app manages the whole keyring; everything else goes through lord-server, which sets the owner */int admin = c->role == ROLE_APP || (c->role == ROLE_SYSTEM && vj_getb(j, 0, "admin", 0));if (!admin && !valid_owner(owner)) { reply_err(c, id, "bad-owner"); return 1; }if (!strcmp(op, "kr-set")) {@@ -135,7 +135,7 @@ int keyring_handle(Chan *c, uint32_t id, const char *op, const Vj *j) {}if (!found) {if (other) {- /* existe pero es de otra app: la interfaz puede preguntarle al usuario si compartirlo */+ /* it exists but belongs to another app: the interface can ask the user whether to share it */KrInfo ok;kr_info(other, NULL, &ok);VjB b; vb_init(&b); vb_open(&b, '{'); vb_ks(&b, "error", "not-shared"); vb_ks(&b, "item", other->id); vb_ks(&b, "itemOwner", ok.owner); vb_close(&b, '}');@@ -166,7 +166,7 @@ int keyring_handle(Chan *c, uint32_t id, const char *op, const Vj *j) {return 1;}if (!strcmp(op, "kr-share")) {- /* solo lord-server (después de preguntarle al usuario) o la app Contraseñas */+ /* only lord-server (after asking the user) or the Passwords app */if (c->role != ROLE_APP && !vj_getb(j, 0, "admin", 0)) { reply_err(c, id, "denied"); return 1; }char eid[40] = "", app[72] = "";vj_getsbuf(j, 0, "id", eid, sizeof eid);@@ -175,7 +175,7 @@ int keyring_handle(Chan *c, uint32_t id, const char *op, const Vj *j) {VEntry *e = vm_find(&v->m, eid);KrInfo k;if (!e || !kr_info(e, NULL, &k) || (!valid_owner(app) && strcmp(app, "*"))) { reply_err(c, id, "not-found"); return 1; }- /* lista nueva de compartidos */+ /* new list of shares */VjB sh; vb_init(&sh); vb_open(&sh, '[');Vj xj;if (!vj_parse(&xj, e->x, strlen(e->x))) {@@ -198,14 +198,14 @@ int keyring_handle(Chan *c, uint32_t id, const char *op, const Vj *j) {return 1;}-/* ---- abrir con la contraseña de la sesión ---- */+/* ---- unlock with the session password ---- */void keyring_session_password(const char *pass) {Vault *v = LOGIN;if (v->unlocked) return;char err[64];VFactors f = { .password = pass };- /* ¿existe? */+ /* does it exist? */if (v->exists != 1) {int fd = -1;(void)fd;@@ -213,14 +213,14 @@ void keyring_session_password(const char *pass) {if (vault_unlock_with(v, VS_SESSION, &f, err, sizeof err) == 0) return;if (!strcmp(err, "not-found")) {VKdf kdf;- vf_calibrate(400, &kdf, NULL); /* el ingreso no tiene que esperar mucho */+ vf_calibrate(400, &kdf, NULL); /* login must not wait long */if (vault_create(v, VS_SESSION, &f, &kdf, "", "{\"autolock\":0}", NULL) == VF_OK) {- fprintf(stderr, "lord-vault: llavero de la sesión creado\n");+ fprintf(stderr, "lord-vault: session keyring created\n");keyring_lock_changed();}return;}- /* la contraseña de la sesión cambió por fuera (passwd): la interfaz pide la anterior */+ /* the session password changed outside LordOS (passwd): the interface asks for the old one */char ev[160];snprintf(ev, sizeof ev, "{\"ev\":\"keyring-mismatch\",\"error\":\"%s\"}", err);broadcast_event(ev);@@ -230,7 +230,7 @@ void keyring_session_password(const char *pass) {static int ss_active;-/* x.ss → atributos (en smem) */+/* x.ss → attributes (in smem) */static int ss_attrs(const VEntry *e, SsAttr **out, int *n, char *ctype, size_t cn) {*out = NULL;*n = 0;@@ -352,7 +352,7 @@ static int utf8_ok(const uint8_t *s, size_t n) {return 1;}-/* guarda un ítem de Secret Service (id NULL = nuevo) */+/* stores a Secret Service item (id NULL = new) */static int ss_store(const char *id, const char *label, const SsAttr *attrs, int nattrs, const uint8_t *secret, size_t len, const char *ctype, char out_id[40]) {VjB b;vb_init(&b);@@ -407,7 +407,7 @@ static int be_create(void *ud, const char *label, const SsAttr *attrs, int nattrconst char *existing = NULL;if (replace) {char ids[1][40];- /* el mismo conjunto exacto de atributos */+ /* the exact same set of attributes */for (int i = 0; i < LOGIN->m.n && !existing; i++) {SsAttr *a;int na;@@ -474,7 +474,7 @@ static int be_remove(void *ud, const char *id) {static void be_caller(void *ud, const char *sender, uint32_t pid) {(void)ud;- if (getenv("LORD_VAULT_DEBUG")) fprintf(stderr, "lord-vault: Secret Service: pedido de %s (pid %u)\n", sender, pid);+ if (getenv("LORD_VAULT_DEBUG")) fprintf(stderr, "lord-vault: Secret Service: request from %s (pid %u)\n", sender, pid);}static const SsBackend backend = {@@ -486,9 +486,9 @@ static const SsBackend backend = {void keyring_start_bus(int busfd) {int r = ss_start(busfd, &backend, NULL);ss_active = r == 0;- if (r == 1) fprintf(stderr, "lord-vault: org.freedesktop.secrets ya tiene dueño (¿gnome-keyring?): no se atiende\n");- else if (r < 0) fprintf(stderr, "lord-vault: no se pudo hablar con el bus de la sesión\n");- else if (getenv("LORD_VAULT_DEBUG")) fprintf(stderr, "lord-vault: Secret Service en el bus (%s)\n", ss_unique_name());+ if (r == 1) fprintf(stderr, "lord-vault: org.freedesktop.secrets already has an owner (gnome-keyring?): not serving it\n");+ else if (r < 0) fprintf(stderr, "lord-vault: could not talk to the session bus\n");+ else if (getenv("LORD_VAULT_DEBUG")) fprintf(stderr, "lord-vault: Secret Service on the bus (%s)\n", ss_unique_name());if (r) close(busfd);}diff --git a/server/src/vault/secretsvc.c b/server/src/vault/secretsvc.cindex 821fe6f..3e538b6 100644--- a/server/src/vault/secretsvc.c+++ b/server/src/vault/secretsvc.c@@ -1,18 +1,18 @@-/* secretsvc.c — la API freedesktop Secret Service sobre el D-Bus propio (ver secretsvc.h y- * docs/CONTRASENAS.md, «Secret Service»).+/* secretsvc.c — the freedesktop Secret Service API over our own D-Bus code (see secretsvc.h and+ * docs/PASSWORDS.md, "Secret Service").*- * Una sola colección, el llavero de la sesión: /org/freedesktop/secrets/collection/login, con el- * alias "default" (también se acepta /org/freedesktop/secrets/aliases/default). CreateCollection- * devuelve esa misma colección (no se crean otras: así cualquier app que pida «una colección- * nueva» termina en el llavero de la sesión, como en macOS). Delete de la colección: NotSupported.+ * A single collection, the session keyring: /org/freedesktop/secrets/collection/login, with the+ * alias "default" (/org/freedesktop/secrets/aliases/default is accepted too). CreateCollection+ * returns that same collection (no others are created: so any app that asks for "a new+ * collection" ends up in the session keyring, as on macOS). Deleting the collection: NotSupported.*- * Sesiones: "plain" y "dh-ietf1024-sha256-aes128-cbc-pkcs7" (grupo MODP de 1024 bits de RFC 2409,- * HKDF-SHA256 sin salt ni info → clave AES-128, AES-128-CBC con PKCS#7 y el IV en los parámetros- * del Secret). La aritmética de 1024 bits es propia (Montgomery con palabras de 32 bits).+ * Sessions: "plain" and "dh-ietf1024-sha256-aes128-cbc-pkcs7" (the 1024-bit MODP group of RFC 2409,+ * HKDF-SHA256 without salt or info → AES-128 key, AES-128-CBC with PKCS#7 and the IV in the+ * Secret's parameters). The 1024-bit arithmetic is our own (Montgomery with 32-bit words).*- * Control de acceso: como gnome-keyring, toda app de la sesión que llega al bus puede usar la- * colección cuando está desbloqueada; el backend recibe quién llama (caller) para el registro y- * los avisos. Las apps .lpk aisladas no llegan al bus (no pueden abrir sockets). */+ * Access control: as in gnome-keyring, every app of the session that reaches the bus can use the+ * collection while it is unlocked; the backend receives the caller for the log and the+ * notices. Isolated .lpk apps do not reach the bus (they cannot open sockets). */#include "secretsvc.h"#include "dbus.h"#include "smem.h"@@ -55,7 +55,7 @@ static uint64_t created_at;#define LOG(...) do { if (debug) fprintf(stderr, "secretsvc: " __VA_ARGS__); } while (0)-/* ================= aritmética de 1024 bits (DH) ================= */+/* ================= 1024-bit arithmetic (DH) ================= */#define BN 32typedef uint32_t Bn[BN];@@ -63,7 +63,7 @@ typedef uint32_t Bn[BN];static void bn_from_be(Bn r, const uint8_t *b, size_t n) {memset(r, 0, sizeof(Bn));for (size_t i = 0; i < n && i < 128; i++) {- size_t bit = (n - 1 - i); /* byte menos significativo = el último */+ size_t bit = (n - 1 - i); /* least significant byte = the last one */r[bit / 4] |= (uint32_t)b[i] << (8 * (bit % 4));}}@@ -96,7 +96,7 @@ static void mont_mul(Bn r, const Bn a, const Bn b, const Bn m, uint32_t minv) {}Bn d;uint32_t br = bn_sub(d, t, m);- /* t >= m si hubo acarreo arriba o la resta no pidió prestado */+ /* t >= m if there was a carry out or the subtraction did not borrow */uint32_t use_d = (uint32_t)(t[BN] != 0) | (br ^ 1);uint32_t mask = (uint32_t)0 - use_d;for (int i = 0; i < BN; i++) r[i] = (d[i] & mask) | (t[i] & ~mask);@@ -113,7 +113,7 @@ int ss_dh_modexp(const uint8_t base[128], const uint8_t exp[128], const uint8_tuint32_t inv = 1;for (int i = 0; i < 5; i++) inv *= 2 - m[0] * inv;uint32_t minv = (uint32_t)0 - inv;- /* R^2 mod m con 2048 duplicaciones */+ /* R^2 mod m with 2048 doublings */memset(r2, 0, sizeof r2);r2[0] = 1;for (int i = 0; i < 2 * 32 * BN; i++) {@@ -126,7 +126,7 @@ int ss_dh_modexp(const uint8_t base[128], const uint8_t exp[128], const uint8_t}memset(one, 0, sizeof one);one[0] = 1;- mont_mul(x, one, r2, m, minv); /* 1 en forma de Montgomery */+ mont_mul(x, one, r2, m, minv); /* 1 in Montgomery form */mont_mul(a, a, r2, m, minv);for (int i = 0; i < 1024; i++) {int byte = i / 8, bit = 7 - i % 8;@@ -162,7 +162,7 @@ static int dh_pub_ok(const uint8_t y[128]) {return !bn_zero(a) && bn_cmp(a, one) != 0 && bn_cmp(a, pm1) < 0;}-/* ================= sesiones y avisos ================= */+/* ================= sessions and notices ================= */#define NSESS 64typedef struct { unsigned id; int used, dh; uint8_t key[16]; char owner[256]; } Sess;@@ -183,7 +183,7 @@ static void sess_free(Sess *s) { explicit_bzero(s, sizeof *s); }static Sess *sess_new(const char *owner) {Sess *s = NULL;for (int i = 0; i < NSESS; i++) if (!sess[i].used) { s = &sess[i]; break; }- if (!s) { /* lleno: se descarta la más vieja */+ if (!s) { /* full: the oldest one is dropped */s = &sess[0];for (int i = 1; i < NSESS; i++) if (sess[i].id < s->id) s = &sess[i];sess_free(s);@@ -253,7 +253,7 @@ static void prompt_path(unsigned id, char out[64]) { snprintf(out, 64, BASE "/prstatic int locked(void) { return B->locked ? B->locked(U) != 0 : 0; }-/* ids de los ítems que cumplen attrs (malloc; liberar con free) */+/* ids of the items that match attrs (malloc; release with free) */static int search_ids(const SsAttr *attrs, int n, char (**out)[40]) {*out = NULL;for (int max = 256; max <= 65536; max *= 4) {@@ -267,7 +267,7 @@ static int search_ids(const SsAttr *attrs, int n, char (**out)[40]) {return -1;}-/* a{ss} → arreglo de SsAttr que apunta al mensaje */+/* a{ss} → array of SsAttr pointing into the message */static int read_attrs(DRd *r, SsAttr *a, int max) {int n = 0;size_t end = dr_arr(r, 8);@@ -325,7 +325,7 @@ static void encode_secret(DBuf *w, Sess *s, const uint8_t *sec, size_t len, consdw_str(w, ctype && ctype[0] ? ctype : "text/plain");}-/* (oayays) → secreto en smem. 0 bien, -2 sin sesión, -1 inválido */+/* (oayays) → secret in smem. 0 ok, -2 no session, -1 invalid */static int decode_secret(DRd *r, const char *sender, uint8_t **out, size_t *outlen, char ctype[64]) {*out = NULL;*outlen = 0;@@ -359,7 +359,7 @@ static int decode_secret(DRd *r, const char *sender, uint8_t **out, size_t *outlreturn 0;}-/* ================= introspección ================= */+/* ================= introspection ================= */static const char X_HEAD[] = "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\" \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n<node>";static const char X_STD[] =@@ -451,7 +451,7 @@ static const char *item_type(const SsItemInfo *in) {return "org.freedesktop.Secret.Generic";}-/* Escribe el valor (variante) de una propiedad; -1 si no existe. */+/* Writes the value (variant) of a property; -1 if it does not exist. */static int put_prop(DBuf *w, int kind, const SsItemInfo *in, const char *name) {if (kind == O_SERVICE && !strcmp(name, "Collections")) {dw_variant(w, "ao");@@ -663,7 +663,7 @@ static void search_items(const DMsg *m, int service) {free(ids);}-/* objetos pedidos (ao) que son nuestros: la colección o ítems */+/* requested objects (ao) that are ours: the collection or items */static int read_objs(DRd *r, char out[][128], int max) {int n = 0;size_t end = dr_arr(r, 4);@@ -785,7 +785,7 @@ static void service_call(const DMsg *m) {} else dbus_error(&C, m, E_METHOD, mb);}-/* ================= Collection e Item ================= */+/* ================= Collection and Item ================= */static void create_item(const DMsg *m) {if (strcmp(m->sig, "a{sv}(oayays)b")) { dbus_error(&C, m, E_ARGS, "a{sv}(oayays)b"); return; }@@ -897,7 +897,7 @@ static void prompt_complete(Prompt *p) {p->used = 0;}-/* ================= despacho ================= */+/* ================= dispatch ================= */static void note_caller(const DMsg *m) {if (!m->sender || !B->caller) return;@@ -985,7 +985,7 @@ int ss_start(int busfd, const SsBackend *be, void *ud) {debug = getenv("LORD_SS_DEBUG") != NULL;B = be;U = ud;- if (dbus_open(&C, busfd, 5000)) { LOG("no se pudo autenticar con el bus\n"); dbus_close(&C); return -1; }+ if (dbus_open(&C, busfd, 5000)) { LOG("could not authenticate with the bus\n"); dbus_close(&C); return -1; }DBuf b;dw_init(&b);dw_str(&b, "org.freedesktop.secrets");@@ -1000,7 +1000,7 @@ int ss_start(int busfd, const SsBackend *be, void *ud) {dr_init(&r, &m);uint32_t res = dr_u32(&r);dbus_msg_free(&m);- if (res != 1 && res != 4) { LOG("org.freedesktop.secrets ya tiene dueño (%u)\n", res); dbus_close(&C); return 1; }+ if (res != 1 && res != 4) { LOG("org.freedesktop.secrets already has an owner (%u)\n", res); dbus_close(&C); return 1; }created_at = (uint64_t)time(NULL);running = 1;LOG("atendiendo org.freedesktop.secrets como %s\n", C.unique);@@ -1016,11 +1016,11 @@ int ss_dispatch(void) {for (int i = 0; i < 256; i++) {DMsg m;int r = dbus_next(&C, &m);- if (r < 0) { LOG("el bus se cerró\n"); ss_stop(); return -1; }+ if (r < 0) { LOG("the bus closed\n"); ss_stop(); return -1; }if (r == 0) break;if (m.type == DBUS_CALL) handle_call(&m);else if (m.type == DBUS_RETURN || m.type == DBUS_ERROR) handle_reply(&m);- else if (m.type == DBUS_SIGNAL && m.member && !strcmp(m.member, "NameLost")) LOG("se perdió el nombre\n");+ else if (m.type == DBUS_SIGNAL && m.member && !strcmp(m.member, "NameLost")) LOG("the name was lost\n");dbus_msg_free(&m);}if (dbus_flush(&C) < 0) { ss_stop(); return -1; }diff --git a/server/src/vault/vault.c b/server/src/vault/vault.cindex 98031e9..d315879 100644--- a/server/src/vault/vault.c+++ b/server/src/vault/vault.c@@ -1,15 +1,16 @@-/* vault.c — lord-vault: el ayudante de las contraseñas y el llavero (ver docs/CONTRASENAS.md).+/* vault.c — lord-vault: the passwords and keyring helper (see docs/PASSWORDS.md).*- * Lo lanza lord-server (vclient.c) con ruta fija (al lado de su binario), sin argumentos, con el- * canal de control en el fd 3. Antes de leer una sola bóveda:- * - sin core dumps ni ptrace (PR_SET_DUMPABLE 0, RLIMIT_CORE 0), muere con lord-server;- * - recibe por el canal de control la carpeta de las bóvedas (un fd) y, si hay, el socket ya- * conectado al bus de D-Bus de la sesión; y se encierra con sandbox_apply_helper: sin red, sin- * sockets nuevos, sin exec, sin archivos salvo esa carpeta (y los fds que le pasen después).- * Lo descifrado vive solo en la arena de secretos (smem.h: mlock, MADV_DONTDUMP, se borra al- * bloquear). Atiende varios canales: el de control (lord-server) y los de la app Contraseñas.- * Lo lento que espera a una persona (tocar la llave FIDO2) va en un hilo aparte; Argon2id (≈0,5–1 s)- * corre en el bucle. */+ * lord-server (vclient.c) launches it from a fixed path (next to its own binary), without+ * arguments, with the control channel on fd 3. Before reading a single vault:+ * - no core dumps or ptrace (PR_SET_DUMPABLE 0, RLIMIT_CORE 0), it dies with lord-server;+ * - it receives the vaults folder (an fd) over the control channel and, if there is one, the+ * socket already connected to the session's D-Bus bus; and confines itself with+ * sandbox_apply_helper: no network, no new sockets, no exec, no files except that folder+ * (and the fds passed to it later).+ * Decrypted data lives only in the secrets arena (smem.h: mlock, MADV_DONTDUMP, wiped on+ * lock). It serves several channels: the control one (lord-server) and those of the Passwords app.+ * Slow work that waits for a person (touching the FIDO2 key) runs in a separate thread; Argon2id+ * (≈0.5–1 s) runs in the loop. */#include "vault_int.h"#include "smem.h"#include "vcrypto.h"@@ -56,7 +57,7 @@ static int debug;static double now_ms(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec * 1e3 + t.tv_nsec / 1e6; }static int64_t now_s(void) { return (int64_t)time(NULL); }-/* ================= respuestas ================= */+/* ================= replies ================= */static const VwAlloc smalloc = { sm_alloc, sm_realloc, sm_free };@@ -84,7 +85,7 @@ static void event_v(const char *ev, int v) {broadcast_event(b);}-/* ================= bóvedas ================= */+/* ================= vaults ================= */static uint8_t *read_fd_all(int fd, size_t max, size_t *len, int secure) {struct stat st;@@ -106,7 +107,7 @@ static uint8_t *read_fd_all(int fd, size_t max, size_t *len, int secure) {}static uint8_t *read_stream(int fd, size_t max, size_t *len) {- /* un fd que puede no ser un archivo regular (un pipe del powerbox): leer hasta el final */+ /* an fd that may not be a regular file (a powerbox pipe): read up to the end */size_t cap = 65536, n = 0;uint8_t *b = sm_alloc(cap);if (!b) return NULL;@@ -128,7 +129,7 @@ static uint8_t *read_stream(int fd, size_t max, size_t *len) {return b;}-/* lee la cabecera del archivo (sin abrir): exists, ranuras */+/* reads the file header (without unlocking): exists, slots */static void vault_probe(Vault *v) {vf_header_free(&v->h);memset(&v->h, 0, sizeof v->h);@@ -140,7 +141,7 @@ static void vault_probe(Vault *v) {close(fd);if (!d) return;if (vf_parse(d, len, &v->h) == VF_OK) v->exists = 1;- else v->exists = -1; /* existe pero no se puede leer */+ else v->exists = -1; /* exists but cannot be read */free(d);}@@ -183,7 +184,7 @@ static int slot_type_of(const char *s) {return 0;}-/* abre con los factores; err recibe el código para la interfaz */+/* unlocks with the factors; err receives the code for the interface */int vault_unlock_with(Vault *v, int type, const VFactors *f, char *err, size_t errn) {if (v->unlocked) return 0;int fd = openat(vault_dirfd, v->file, O_RDONLY | O_CLOEXEC);@@ -221,7 +222,7 @@ int vault_unlock_with(Vault *v, int type, const VFactors *f, char *err, size_t ev->exists = 1;v->last_use = now_ms();if (v == &vaults[V_MAIN]) {- /* el bloqueo automático sale de los ajustes de la bóveda */+ /* the auto-lock comes from the vault's settings */Vj j;if (m.meta && !vj_parse(&j, m.meta, strlen(m.meta))) {v->autolock_s = (int)vj_getn(&j, 0, "autolock", 300);@@ -240,7 +241,7 @@ int vault_save(Vault *v) {size_t plen;char *plain = vm_dump(&v->m, &plen);if (!plain) return VF_ENOMEM;- /* adjuntos: los de las entradas; nuevos (en memoria) o del archivo actual */+ /* attachments: those of the entries; new (in memory) or from the current file */int total = 0;for (int i = 0; i < v->m.n; i++) total += v->m.e[i]->natt;VAttOut *outs = calloc((size_t)(total ? total : 1), sizeof *outs);@@ -265,7 +266,7 @@ int vault_save(Vault *v) {free(outs);sm_free(plain);if (r != VF_OK) return r;- /* volver a abrir el archivo nuevo (los adjuntos ahora salen de ahí) */+ /* reopen the new file (attachments now come from there) */int fd = openat(vault_dirfd, v->file, O_RDONLY | O_CLOEXEC);if (fd >= 0) {size_t len;@@ -299,7 +300,7 @@ int vault_create(Vault *v, int type, const VFactors *f, const VKdf *kdf, const cvc_random(vk, 32);VSlot s;memset(&s, 0, sizeof s);- if (type == VS_FIDO2) s = h.slots[0]; /* el llamador dejó cred/salt en h.slots[0] */+ if (type == VS_FIDO2) s = h.slots[0]; /* the caller left cred/salt in h.slots[0] */int r = vf_make_slot(&h, &s, type, f, vk, kdf, label);if (r != VF_OK) { sm_free(vk); return r; }h.slots[h.nslots++] = s;@@ -326,7 +327,7 @@ int vault_create(Vault *v, int type, const VFactors *f, const VKdf *kdf, const creturn VF_OK;}-/* ================= FIDO2 en un hilo ================= */+/* ================= FIDO2 in a thread ================= */enum { FJ_UNLOCK = 1, FJ_CREATE, FJ_ADD };typedef struct {@@ -336,7 +337,7 @@ typedef struct {int fd;VKdf kdf;char label[64];- /* resultado */+ /* result */int err;uint8_t secret[32];uint8_t cred[FIDO_CRED_MAX]; size_t cred_len;@@ -385,7 +386,7 @@ static const char *fido_code(int e) {return s ? s : "fido";}-/* el hilo terminó: completar el pedido en el bucle */+/* the thread finished: complete the request in the loop */static void fido_done(void) {fj.busy = 0;Vault *v = &vaults[fj.v];@@ -445,7 +446,7 @@ static int fido_start(Chan *c, uint32_t id, int kind, int vi, const Vj *j, int oreturn 0;}-/* ================= pedidos ================= */+/* ================= requests ================= */static int vault_of(const Vj *j) {int k = vj_get(j, 0, "v");@@ -496,7 +497,7 @@ static void status_json(VjB *b) {vb_close(b, '}');}-/* factores de un pedido: password, recovery y el archivo llave (fd) */+/* factors of a request: password, recovery and the key file (fd) */typedef struct { char *password, *recovery; uint8_t kf[32]; int has_kf; } Factors;static int get_factors(const Vj *j, const VMsg *m, int kf_index, Factors *F) {@@ -507,7 +508,7 @@ static int get_factors(const Vj *j, const VMsg *m, int kf_index, Factors *F) {size_t len;uint8_t *d = read_stream(m->fds[kf_index], 16u << 20, &len);if (!d) return -1;- if (len < 32) { sm_free(d); return -2; } /* muy corto para ser una llave */+ if (len < 32) { sm_free(d); return -2; } /* too short to be a key */vf_keyfile_hash(d, len, F->kf);sm_free(d);F->has_kf = 1;@@ -545,7 +546,7 @@ static void op_create(Chan *c, uint32_t id, const Vj *j, const VMsg *m) {if (!type || type == VS_RECOVERY || type == VS_SESSION) { reply_err(c, id, "bad-method"); return; }if (type == VS_FIDO2) { fido_start(c, id, FJ_CREATE, vi, j, 0); return; }Factors F;- /* archivo llave: "newkey" → se genera y se escribe en fds[0]; si no, se lee de fds[0] */+ /* key file: "newkey" → generated and written to fds[0]; otherwise read from fds[0] */int newkey = vj_getb(j, 0, "newkey", 0);uint8_t key[64];if ((type == VS_KEYFILE || type == VS_PASSKEY) && newkey) {@@ -684,7 +685,7 @@ static void op_report(Chan *c, uint32_t id, Vault *v, const VMsg *m) {vb_close(&b, '}');}vb_close(&b, ']');- /* repetidas: agrupadas por el hash de la contraseña */+ /* reused: grouped by the password's hash */vb_key(&b, "reused");vb_open(&b, '[');char *seen = calloc((size_t)(v->m.n ? v->m.n : 1), 1);@@ -704,7 +705,7 @@ static void op_report(Chan *c, uint32_t id, Vault *v, const VMsg *m) {}free(seen);vb_close(&b, ']');- /* viejas: más días que su recordatorio (o un año sin recordatorio) */+ /* old: more days than their reminder (or a year without a reminder) */vb_key(&b, "old");vb_open(&b, '[');for (int i = 0; i < v->m.n; i++) {@@ -791,7 +792,7 @@ static void op_totp(Chan *c, uint32_t id, Vault *v, const Vj *j) {reply(c, id, &b);}-/* QR: de un texto dado o del Wi-Fi de una entrada; responde las filas como hex */+/* QR: from a given text or an entry's Wi-Fi; replies with the rows as hex */static void wifi_escape(VjB *b, const char *s) {for (; s && *s; s++) {if (strchr("\\;,:\"", *s)) vb_raw(b, "\\");@@ -926,7 +927,7 @@ static void op_strength(Chan *c, uint32_t id, const Vj *j) {reply(c, id, &b);}-/* ---- adjuntos ---- */+/* ---- attachments ---- */static int hexbytes(const char *s, uint8_t *out, size_t n) {if (!s || strlen(s) != n * 2) return -1;@@ -941,7 +942,7 @@ static int att_find(VEntry *e, const char *hid) {return -1;}-/* descifra un adjunto → smem */+/* decrypts an attachment → smem */static uint8_t *att_plain(Vault *v, const VAtt *a, size_t *len) {const uint8_t *cipher = NULL;uint8_t *tmp = NULL;@@ -989,7 +990,7 @@ static int att_add_bytes(Vault *v, VEntry *e, const char *name, const char *mimememcpy(p->nonce, a->nonce, 24);memcpy(p->mac, a->mac, 16);v->npend++;- a->name = sm_strdup(name && name[0] ? name : "archivo");+ a->name = sm_strdup(name && name[0] ? name : "file");a->mime = sm_strdup(mime && mime[0] ? mime : "application/octet-stream");a->size = len;e->natt++;@@ -1037,14 +1038,14 @@ static void op_att(Chan *c, uint32_t id, Vault *v, const char *op, const Vj *j,reply(c, id, &b);return;}- if (!strcmp(op, "att-text")) { /* texto (licencias, claves): hasta 256 KB */+ if (!strcmp(op, "att-text")) { /* text (licenses, keys): up to 256 KB */if (len > 262144) { sm_free(pt); reply_err(c, id, "too-big"); return; }VjB b; vb_init(&b); vb_open(&b, '{'); vb_kb(&b, "ok", 1); vb_key(&b, "text"); vb_strn(&b, (const char *)pt, len); vb_close(&b, '}');sm_free(pt);reply(c, id, &b);return;}- /* att-preview: imagen achicada a max px, RGBA en base64 */+ /* att-preview: image shrunk to max px, RGBA in base64 */int w, h;uint32_t *px = vstb_decode_argb(pt, len, &w, &h);sm_free(pt);@@ -1060,7 +1061,7 @@ static void op_att(Chan *c, uint32_t id, Vault *v, const char *op, const Vj *j,uint8_t *rgba = sm_alloc((size_t)ow * oh * 4);for (int y = 0; rgba && y < oh; y++)for (int x = 0; x < ow; x++) {- /* promedio de la caja de origen */+ /* average of the source box */int x0 = (int)(x / sc), x1 = (int)((x + 1) / sc), y0 = (int)(y / sc), y1 = (int)((y + 1) / sc);if (x1 <= x0) x1 = x0 + 1;if (y1 <= y0) y1 = y0 + 1;@@ -1084,7 +1085,7 @@ static void op_att(Chan *c, uint32_t id, Vault *v, const char *op, const Vj *j,reply(c, id, &b);}-/* ---- importar/exportar ---- */+/* ---- import/export ---- */static const char *kind_cat(const ImpEntry *ie) {const char *k = ie->kind ? ie->kind : "";@@ -1097,13 +1098,13 @@ static const char *kind_cat(const ImpEntry *ie) {return "general";}-/* agrega a cats (JSON) una categoría de usuario por cada carpeta importada; devuelve su id */+/* adds to cats (JSON) a user category for each imported folder; returns its id */typedef struct { char path[256]; char id[40]; } GroupMap;static const char *group_cat(Vault *v, GroupMap **gm, int *ngm, const char *path, int *added) {if (!path || !path[0]) return NULL;for (int i = 0; i < *ngm; i++) if (!strcmp((*gm)[i].path, path)) return (*gm)[i].id;- /* el padre primero */+ /* the parent first */char parent[256];snprintf(parent, sizeof parent, "%s", path);char *slash = strrchr(parent, '/');@@ -1117,7 +1118,7 @@ static const char *group_cat(Vault *v, GroupMap **gm, int *ngm, const char *pathuint8_t h[8];crypto_blake2b(h, 8, (const uint8_t *)path, strlen(path));snprintf(g->id, sizeof g->id, "g%02x%02x%02x%02x%02x%02x", h[0], h[1], h[2], h[3], h[4], h[5]);- /* ¿ya existe en cats? */+ /* already in cats? */if (v->m.cats && strstr(v->m.cats, g->id)) return g->id;VjB b;vb_init(&b);@@ -1185,7 +1186,7 @@ static int import_list(Vault *v, ImpList *L, int *cats_added) {int ty = fi->type >= 0 && fi->type <= 5 ? fi->type : 0;char key[24];snprintf(key, sizeof key, "c%d", f + 1);- /* campos conocidos de las plantillas (tarjetas, identidad) entran con su clave */+ /* known template fields (cards, identity) come in with their key */const char *known = NULL;static const char *keys[] = { "holder", "number", "expiry", "cvv", "pin", "brand", "email", "phone", "address", "ssid", "security","host", "port", "server", "account", "service", "product", "license", "document", NULL };@@ -1323,7 +1324,7 @@ static void op_export_vault(Chan *c, uint32_t id, Vault *v, const VMsg *m) {for (int p = 0; p < v->h.natts && !found; p++) if (!memcmp(v->h.atts[p].id, at->id, 16)) { o->srcfd = v->fd; o->off = v->h.atts[p].off; o->len = v->h.atts[p].len; found = 1; }if (found) no++;}- VHeader h = v->h; /* misma cabecera y ranuras: se abre igual que la original */+ VHeader h = v->h; /* same header and slots: it unlocks like the original */h.atts = NULL; h.natts = 0;int r = outs ? vf_write_fd(m->fds[0], &h, v->vk, (const uint8_t *)plain, plen, outs, no) : VF_ENOMEM;free(outs);@@ -1331,7 +1332,7 @@ static void op_export_vault(Chan *c, uint32_t id, Vault *v, const VMsg *m) {if (r != VF_OK) reply_err(c, id, vf_strerror(r)); else reply_ok(c, id);}-/* abrir otra bóveda .lvault (copia, otra máquina) e incorporar sus entradas */+/* open another .lvault vault (a copy, another machine) and merge its entries */static void op_import_vault(Chan *c, uint32_t id, Vault *v, const Vj *j, const VMsg *m) {if (m->nfds < 1) { reply_err(c, id, "no-file"); return; }size_t len;@@ -1356,7 +1357,7 @@ static void op_import_vault(Chan *c, uint32_t id, Vault *v, const Vj *j, const Vint count = 0;for (int i = 0; i < om.n; i++) {VEntry *e = om.e[i];- if (vm_find(&v->m, e->id)) continue; /* ya está (misma entrada) */+ if (vm_find(&v->m, e->id)) continue; /* already there (same entry) */VjB b; vb_init(&b);vm_entry_json(&b, e, 1, 0);Vj ej; VEntry *ne = NULL; char err[64];@@ -1382,7 +1383,7 @@ static void op_import_vault(Chan *c, uint32_t id, Vault *v, const Vj *j, const Vevent_v("changed", (int)(v - vaults));}-/* ---- ranuras ---- */+/* ---- slots ---- */static int slot_index(Vault *v, const char *hid) {uint8_t sid[8];@@ -1425,7 +1426,7 @@ static void op_slot(Chan *c, uint32_t id, Vault *v, const char *op, const Vj *j,reply(c, id, &b);return;}- /* slot-add / password-change: method + factores; password-change reemplaza la(s) de contraseña */+ /* slot-add / password-change: method + factors; password-change replaces the password slot(s) */char method[16] = "";vj_getsbuf(j, 0, "method", method, sizeof method);int type = slot_type_of(method);@@ -1434,7 +1435,7 @@ static void op_slot(Chan *c, uint32_t id, Vault *v, const char *op, const Vj *j,if (v->h.nslots >= VF_MAX_SLOTS) { reply_err(c, id, "too-many"); return; }if (type == VS_FIDO2) { fido_start(c, id, FJ_ADD, (int)(v - vaults), j, 0); return; }if (!strcmp(op, "password-change")) {- /* pedir la contraseña actual (aunque esté abierta) */+ /* ask for the current password (even if it is unlocked) */char *old = vj_gets(j, 0, "old");VFactors of = { .password = old };uint8_t tmp[32];@@ -1473,7 +1474,7 @@ static void op_slot(Chan *c, uint32_t id, Vault *v, const char *op, const Vj *j,v->h.nslots--;}}- /* «contraseña + archivo llave» reemplaza a la contraseña sola (si no, el segundo factor no sirve) */+ /* "password + key file" replaces the password alone (otherwise the second factor is useless) */if (type == VS_PASSKEY && vj_getb(j, 0, "dropPassword", 1))for (int i = v->h.nslots - 1; i >= 0; i--) if (v->h.slots[i].type == VS_PASSWORD) {memmove(v->h.slots + i, v->h.slots + i + 1, sizeof(VSlot) * (size_t)(v->h.nslots - i - 1));@@ -1484,7 +1485,7 @@ static void op_slot(Chan *c, uint32_t id, Vault *v, const char *op, const Vj *j,if (r != VF_OK) reply_err(c, id, vf_strerror(r)); else reply_ok(c, id);}-/* ---- despacho ---- */+/* ---- dispatch ---- */static void handle_request(Chan *c, VMsg *m) {Vj j;@@ -1521,7 +1522,7 @@ static void handle_request(Chan *c, VMsg *m) {}else if (keyring_handle(c, id, op, &j)) { /* kr-* */ }else if (!strcmp(op, "qr")) op_qr(c, id, v, &j);- else if (!need_unlocked(c, id, v)) { /* respondió "locked" */ }+ else if (!need_unlocked(c, id, v)) { /* replied "locked" */ }else if (!strcmp(op, "list")) op_list(c, id, v);else if (!strcmp(op, "get")) {char eid[40] = "";@@ -1616,7 +1617,7 @@ static void handle_request(Chan *c, VMsg *m) {vj_free(&j);}-/* ================= control (solo lord-server) ================= */+/* ================= control (lord-server only) ================= */static void handle_ctl(Chan *c, VMsg *m) {Vj j;@@ -1659,7 +1660,7 @@ static void handle_ctl(Chan *c, VMsg *m) {vj_free(&j);}-/* ================= arranque ================= */+/* ================= startup ================= */static void lockdown(void) {static const int sys[] = { SYS_mlock, SYS_munlock,@@ -1680,19 +1681,19 @@ int main(void) {sm_harden_process();debug = getenv("LORD_VAULT_DEBUG") ? atoi(getenv("LORD_VAULT_DEBUG")) + 1 : 0;if (debug < 0) debug = 1;- /* nada heredado salvo 0–3 */+ /* nothing inherited except 0–3 */for (int fd = 4; fd < 1024; fd++) close(fd);- /* 1) init: la carpeta de bóvedas (y quizás el bus) */+ /* 1) init: the vaults folder (and maybe the bus) */VMsg m;if (vw_recv(CTL_FD, &m, &smalloc)) return 1;- if (m.kind != VW_CTL || m.nfds < 1) { fprintf(stderr, "lord-vault: falta la carpeta\n"); return 1; }+ if (m.kind != VW_CTL || m.nfds < 1) { fprintf(stderr, "lord-vault: the folder is missing\n"); return 1; }vault_dirfd = m.fds[0];m.fds[0] = -1;int busfd = -1;if (m.nfds >= 2) { busfd = m.fds[1]; m.fds[1] = -1; }uint32_t init_id = m.id;vw_msg_free(&m, &smalloc);- /* 2) encerrarse antes de tocar una bóveda */+ /* 2) confine ourselves before touching a vault */lockdown();if (pipe2(fpipe, O_CLOEXEC | O_NONBLOCK)) return 1;vg_set_lists(_binary_words_txt_start, (size_t)(_binary_words_txt_end - _binary_words_txt_start),@@ -1703,7 +1704,7 @@ int main(void) {for (int i = 0; i < V_COUNT; i++) vault_probe(&vaults[i]);if (busfd >= 0) keyring_start_bus(busfd);reply_ok(&chans[0], init_id);- /* 3) bucle */+ /* 3) loop */for (;;) {struct pollfd pf[MAX_CHANS + 2];int n = 0;@@ -1713,10 +1714,10 @@ int main(void) {if (bfd >= 0) { pf[n].fd = bfd; pf[n].events = POLLIN | (keyring_bus_wants_out() ? POLLOUT : 0); n++; }int r = poll(pf, (nfds_t)n, 1000);if (r < 0 && errno != EINTR) break;- /* bloqueo automático */+ /* auto-lock */Vault *mv = &vaults[V_MAIN];if (mv->unlocked && mv->autolock_s > 0 && !fj.busy && now_ms() - mv->last_use > mv->autolock_s * 1000.0) {- if (debug) fprintf(stderr, "lord-vault: bloqueo automático\n");+ if (debug) fprintf(stderr, "lord-vault: automatic lock\n");vault_lock(mv);}if (r <= 0) continue;@@ -1732,7 +1733,7 @@ int main(void) {if (c->role == ROLE_SYSTEM) { for (int v = 0; v < V_COUNT; v++) vault_lock(&vaults[v]); sm_wipe_all(); _exit(0); }close(c->fd);vw_rx_free(&c->rx, &smalloc);- /* canal de la app cerrado: sacarlo */+ /* app channel closed: remove it */chans[i] = chans[--nchans];i--;break;diff --git a/server/src/vault/vmodel.c b/server/src/vault/vmodel.cindex 179461d..09db8d2 100644--- a/server/src/vault/vmodel.c+++ b/server/src/vault/vmodel.c@@ -1,4 +1,4 @@-/* vmodel.c — contenido de una bóveda abierta (ver vmodel.h). Todo en la arena de secretos. */+/* vmodel.c — contents of an open vault (see vmodel.h). Everything lives in the secrets arena. */#include "vmodel.h"#include "smem.h"#include "vcrypto.h"@@ -45,10 +45,10 @@ static int valid_id(const char *s) {return 1;}-/* ---- plegado para buscar: minúsculas y sin tildes (latín) ---- */+/* ---- folding for search: lowercase and without accents (Latin) ---- */static const char *fold_cp(unsigned cp, char *tmp) {- /* U+00C0–U+00FF y algunas de Latin Extended-A */+ /* U+00C0–U+00FF and some of Latin Extended-A */static const char *lat1[64] = {"a","a","a","a","a","a","ae","c","e","e","e","e","i","i","i","i","d","n","o","o","o","o","o","x","o","u","u","u","u","y","th","ss",@@ -118,7 +118,7 @@ void vm_refresh(VEntry *e) {if (pw && pw[0]) crypto_blake2b_keyed(e->pwhash, 16, (const uint8_t *)"lordos-vault:reuse", 18, (const uint8_t *)pw, strlen(pw));}-/* ---- cargar ---- */+/* ---- load ---- */static char *raw_of(const Vj *j, int tok, const char *def) {if (tok < 0) return sm_strdup(def);@@ -182,7 +182,7 @@ static int load_atts(VEntry *e, const Vj *j, int arr) {if (hex16(buf, a->mac, 16)) continue;a->name = vj_gets(j, k, "name");a->mime = vj_gets(j, k, "mime");- if (!a->name) a->name = sm_strdup("archivo");+ if (!a->name) a->name = sm_strdup("file");if (!a->mime) a->mime = sm_strdup("application/octet-stream");a->size = (uint64_t)vj_getn(j, k, "size", 0);e->natt++;@@ -254,7 +254,7 @@ int vm_load(VModel *m, const char *json, size_t len) {return 0;}-/* ---- guardar ---- */+/* ---- save ---- */static void hexs(VjB *b, const uint8_t *p, size_t n) {char h[130];@@ -347,9 +347,9 @@ char *vm_dump(const VModel *m, size_t *len) {return b.p;}-/* ---- para la interfaz ---- */+/* ---- for the interface ---- */-/* El historial guarda los valores ocultos; sin reveal se sacan (se reescribe el JSON). */+/* The history keeps the hidden values; without reveal they are removed (the JSON is rewritten). */static void hist_json(VjB *b, const char *hist, int reveal) {if (reveal || !hist) { vb_raw(b, hist ? hist : "[]"); return; }Vj j;@@ -393,7 +393,7 @@ void vm_entry_json(VjB *b, const VEntry *e, int reveal, int hist) {vb_close(b, '}');}-/* subtítulo de la lista: usuario, correo, o los últimos 4 de una tarjeta */+/* list subtitle: username, email, or the last 4 digits of a card */static const char *subtitle(const VEntry *e, char *tmp, size_t n) {const char *u = vm_field(e, "username");if (u && u[0]) return u;@@ -408,7 +408,7 @@ static const char *subtitle(const VEntry *e, char *tmp, size_t n) {snprintf(tmp, n, "•••• %s", k >= 4 ? d + k - 4 : d);return tmp;}- /* documentos: el número (si no es oculto) */+ /* documents: the number (if it is not hidden) */for (int i = 0; i < e->nf; i++)if (!strcmp(e->f[i].k, "number") && !strcmp(e->f[i].t, "text") && e->f[i].v[0]) return e->f[i].v;for (const char *key = "ssid"; key; key = !strcmp(key, "ssid") ? "host" : !strcmp(key, "host") ? "product" : !strcmp(key, "product") ? "service" : !strcmp(key, "service") ? "account" : NULL) {@@ -495,7 +495,7 @@ int vm_remove(VModel *m, const char *id) {return 0;}-/* ---- crear/actualizar desde la interfaz ---- */+/* ---- create/update from the interface ---- */static int str_eq(const char *a, const char *b) { return !strcmp(a ? a : "", b ? b : ""); }@@ -512,7 +512,7 @@ static int valid_ftype(const char *t) {return 0;}-/* entrada nueva armada desde el JSON; old (si hay) para los "keep" */+/* new entry built from the JSON; old (if any) for the "keep" fields */static VEntry *entry_from_ui(const Vj *j, int o, const VEntry *old, char *err, size_t errn) {VEntry *e = sm_alloc(sizeof *e);if (!e) { snprintf(err, errn, "memory"); return NULL; }@@ -540,7 +540,7 @@ static VEntry *entry_from_ui(const Vj *j, int o, const VEntry *old, char *err, sif (!d->k || !d->k[0] || strlen(d->k) > 64) { sm_free(d->k); d->k = sm_strdup("field"); }if (!d->t || !valid_ftype(d->t)) { sm_free(d->t); d->t = sm_strdup("text"); }if (vj_getb(j, k, "keep", 0) && old) {- /* conservar el valor anterior del campo con la misma clave (y la misma posición si se repite) */+ /* keep the previous value of the field with the same key (and the same position if it repeats) */const char *pv = NULL;int seen = 0;for (int q = 0; q < i; q++) if (e->f[q].k && !strcmp(e->f[q].k, d->k)) seen++;@@ -568,7 +568,7 @@ static void add_history(VEntry *e, const VEntry *old, int64_t now) {vb_ks(&b, "title", old->title);fields_json(&b, old, 1);vb_close(&b, '}');- /* las anteriores, hasta HIST_MAX */+ /* the previous ones, up to HIST_MAX */Vj j;if (old->hist && !vj_parse(&j, old->hist, strlen(old->hist)) && vj_type(&j, 0) == VJ_ARR) {for (int i = 0, k = 1; i < j.t[0].count && i < HIST_MAX - 1; i++, k = j.t[k].next) {@@ -598,7 +598,7 @@ int vm_upsert(VModel *m, const Vj *j, int tok, VEntry **out, char *err, size_t ee->created = old->created;e->trash = (int64_t)vj_getn(j, tok, "trash", (double)old->trash);e->pwch = old->pwch;- /* adjuntos: los conserva (se agregan y sacan con sus propios pedidos) */+ /* attachments: kept (they are added and removed with their own requests) */e->att = old->att; e->natt = old->natt;VEntry *o2 = old;o2->att = NULL; o2->natt = 0;diff --git a/server/tests/engine_test.c b/server/tests/engine_test.cnew file mode 100644index 0000000..c67bded--- /dev/null+++ b/server/tests/engine_test.c@@ -0,0 +1,631 @@+/* engine_test.c — headless tests of the UI engine's newer features (docs/DESIGN.md "Engine notes"):+ * text truncation with an ellipsis (LTR, RTL, Arabic, Thai, emoji ZWJ sequences and flags),+ * per-side borders and per-corner radii, logical margins/insets, transform math, transformed+ * painting and hit testing. It links the real layout, text and paint code; the terminal, Wayland,+ * media and GPU hooks of paint.c are stubbed out.+ * build/engine-test runs the tests+ * build/engine-test bench times layout and paint of a 2000-row list and a window drag+ * Fallback fonts are looked up as in LordOS (DejaVu Sans covers Arabic and Hebrew in the build+ * container); the checks don't depend on which font draws a script. */+#include <math.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <time.h>++#include "ui/fonts.h"+#include "ui/ui.h"+#include "ui/unicode.h"++/* ---- stubs for what paint.c reaches outside the UI engine ---- */+void term_paint(Canvas *c, int id, float x, float y, float w, float h, float op) { (void)c; (void)id; (void)x; (void)y; (void)w; (void)h; (void)op; }+void wl_paint(Canvas *c, int id, int node, float x, float y, float w, float h, float op) { (void)c; (void)id; (void)node; (void)x; (void)y; (void)w; (void)h; (void)op; }+void wl_paint_holes(int on) { (void)on; }+void wl_paint_kept(void) {}+void wl_paint_keep(void) {}+void wl_paint_begin(void) {}+void wl_paint_popups(Canvas *c) { (void)c; }+void media_paint(Canvas *c, int id, int node, float x, float y, float w, float h, float r, float op) { (void)c; (void)id; (void)node; (void)x; (void)y; (void)w; (void)h; (void)r; (void)op; }+int media_cover_node(float x0, float y0, float x1, float y1) { (void)x0; (void)y0; (void)x1; (void)y1; return 0; }+int gpu_active(void) { return 0; }++void paint_layer_begin(int node, int resize);+void paint_layer_end(void);+void paint_layer_stats(long *renders, long *blits);+void paint_tf_stats(long *renders, long *composites);+int text_layout_visual(const char *s, int font, float size, int *cps, int max);++static int fails, checks;+static int quiet; /* bench: styles an older engine doesn't know are skipped */+#define CHECK(cond, ...) do { checks++; if (!(cond)) { fails++; printf("FAIL %s:%d: ", __FILE__, __LINE__); printf(__VA_ARGS__); printf("\n"); } } while (0)++#ifndef ENGINE_BEFORE+/* ---- UTF-8 helpers ---- */+static int u8_decode(const char *s, uint32_t *out, int max) {+ int n = 0;+ const unsigned char *p = (const unsigned char *)s;+ while (*p && n < max) {+ uint32_t c = *p;+ int k = c < 0x80 ? 0 : (c & 0xe0) == 0xc0 ? 1 : (c & 0xf0) == 0xe0 ? 2 : 3;+ c = k == 0 ? c : k == 1 ? c & 0x1f : k == 2 ? c & 0x0f : c & 0x07;+ p++;+ for (int i = 0; i < k && *p; i++, p++) c = c << 6 | (*p & 0x3f);+ out[n++] = c;+ }+ return n;+}++/* what must stay with the code point before it (a grapheme cluster continues) */+static int is_mark_like(uint32_t c) {+ return uc_mark(c) || c == 0x0E33 || c == 0x200D || c == 0xFE0F || (c >= 0x1F3FB && c <= 0x1F3FF);+}++/* Checks a truncation of `s` in a box of width w: out = prefix + "…", the prefix ends on a cluster+ * boundary and it fits. Returns the prefix length in code points (-1 = not truncated). */+static int check_cut(const char *name, const char *s, float w, int force) {+ char out[1024];+ float tw = text_ellipsize(s, 400, 13, w, force, out, sizeof out);+ if (tw < 0) { CHECK(!strcmp(out, s), "%s: fits but changed", name); return -1; }+ size_t lo = strlen(out);+ CHECK(lo >= 3 && !strcmp(out + lo - 3, "\xe2\x80\xa6"), "%s w=%.0f: no ellipsis at the end: %s", name, w, out);+ size_t lp = lo - 3;+ CHECK(!strncmp(out, s, lp), "%s w=%.0f: not a prefix: %s", name, w, out);+ uint32_t a[512], b[512];+ int na = u8_decode(s, a, 512);+ char pre[1024];+ memcpy(pre, out, lp);+ pre[lp] = 0;+ int nb = u8_decode(pre, b, 512);+ if (nb > 0 && nb < na) {+ /* trailing spaces are dropped: find where the prefix really ended in s */+ int k = nb;+ while (k < na && a[k] == ' ') k++;+ uint32_t next = a[nb], prev = a[nb - 1];+ CHECK(!is_mark_like(next), "%s w=%.0f: cut before U+%04X (prefix %d cps)", name, w, next, nb);+ CHECK(prev != 0x200D, "%s w=%.0f: cut after a ZWJ", name, w);+ if (next >= 0x1F1E6 && next <= 0x1F1FF) {+ int r = 0;+ for (int i = nb - 1; i >= 0 && a[i] >= 0x1F1E6 && a[i] <= 0x1F1FF; i--) r++;+ CHECK(!(r & 1), "%s w=%.0f: cut inside a flag", name, w);+ }+ (void)k;+ }+ if (nb > 0) CHECK(tw <= w + 0.5f, "%s w=%.0f: too wide (%.1f)", name, w, tw);+ return nb;+}++static void sweep(const char *name, const char *s) {+ int last = -1;+ for (float w = 8; w <= 400; w += 3) {+ int n = check_cut(name, s, w, 0);+ if (n < 0) break;+ CHECK(n >= last, "%s: a wider box (%.0f) kept less text (%d < %d)", name, w, n, last);+ last = n;+ }+}++/* Visual position of the "…" in the cut form: 0 = leftmost. */+static void check_side(const char *name, const char *s, float w, int want_left) {+ char out[1024];+ text_ellipsize(s, 400, 13, w, 1, out, sizeof out);+ int vis[512];+ int n = text_layout_visual(out, 0, 13, vis, 512);+ uint32_t cps[512];+ int ncp = u8_decode(out, cps, 512);+ int pos = -1;+ for (int i = 0; i < n; i++) if (vis[i] == ncp - 1) pos = i;+ CHECK(n > 0 && pos >= 0, "%s: no glyph for the ellipsis", name);+ if (pos >= 0) {+ if (want_left) CHECK(pos == 0, "%s: ellipsis at visual %d of %d, want the left edge", name, pos, n);+ else CHECK(pos == n - 1, "%s: ellipsis at visual %d of %d, want the right edge", name, pos, n);+ }+}++static void test_ellipsis(void) {+ const char *ltr = "Quarterly report for the board, final version (2).pdf";+ const char *arabic = "\xd8\xaa\xd9\x82\xd8\xb1\xd9\x8a\xd8\xb1 \xd8\xa7\xd9\x84\xd9\x85\xd8\xa8\xd9\x8a\xd8\xb9\xd8\xa7\xd8\xaa "+ "\xd8\xa7\xd9\x84\xd8\xb3\xd9\x86\xd9\x88\xd9\x8a \xd9\x84\xd9\x84\xd8\xb9\xd8\xa7\xd9\x85 \xd8\xa7\xd9\x84\xd9\x85\xd8\xa7\xd8\xb6\xd9\x8a "+ "\xd8\xa8\xd8\xa7\xd9\x84\xd8\xaa\xd9\x81\xd8\xb5\xd9\x8a\xd9\x84 \xd9\x84\xd8\xa7 \xd8\xb9\xd9\x8e\xd9\x84\xd9\x91\xd9\x8e\xd9\x85\xd9\x8e";+ const char *hebrew = "\xd7\x93\xd7\x95\xd7\x97 \xd7\xa8\xd7\x91\xd7\xa2\xd7\x95\xd7\xa0\xd7\x99 \xd7\xa1\xd7\x95\xd7\xa4\xd7\x99 \xd7\x9c\xd7\x93\xd7\x99\xd7\xa8\xd7\xa7\xd7\x98\xd7\x95\xd7\xa8\xd7\x99\xd7\x95\xd7\x9f";+ const char *thai = "\xe0\xb8\xaa\xe0\xb8\xa7\xe0\xb8\xb1\xe0\xb8\xaa\xe0\xb8\x94\xe0\xb8\xb5\xe0\xb8\x84\xe0\xb8\xa3\xe0\xb8\xb1\xe0\xb8\x9a "+ "\xe0\xb8\xa2\xe0\xb8\xb4\xe0\xb8\x99\xe0\xb8\x94\xe0\xb8\xb5\xe0\xb8\x95\xe0\xb9\x89\xe0\xb8\xad\xe0\xb8\x99\xe0\xb8\xa3\xe0\xb8\xb1\xe0\xb8\x9a "+ "\xe0\xb8\x99\xe0\xb9\x89\xe0\xb8\xb3\xe0\xb8\x97\xe0\xb8\xb3\xe0\xb8\x99\xe0\xb9\x89\xe0\xb8\xb3\xe0\xb9\x83\xe0\xb8\x88";+ const char *emoji = "Family \xf0\x9f\x91\xa8\xe2\x80\x8d\xf0\x9f\x91\xa9\xe2\x80\x8d\xf0\x9f\x91\xa7\xe2\x80\x8d\xf0\x9f\x91\xa6 trip "+ "\xf0\x9f\x87\xa6\xf0\x9f\x87\xb7\xf0\x9f\x87\xa7\xf0\x9f\x87\xb7\xf0\x9f\x87\xa8\xf0\x9f\x87\xb1 \xf0\x9f\x91\x8d\xf0\x9f\x8f\xbd "+ "\xe2\x9d\xa4\xef\xb8\x8f done";+ const char *marks = "Cafe\xcc\x81 de\xcc\x81ja\xcc\x80 vu na\xc3\xafve re\xcc\x81sume\xcc\x81 tre\xcc\x80s longue";++ /* fits: unchanged */+ char out[256];+ CHECK(text_ellipsize("Short", 400, 13, 200, 0, out, sizeof out) < 0 && !strcmp(out, "Short"), "short text was cut");+ /* forced (more lines follow) adds the ellipsis even if it fits */+ text_ellipsize("Short", 400, 13, 200, 1, out, sizeof out);+ CHECK(!strcmp(out, "Short\xe2\x80\xa6"), "forced: %s", out);+ /* a box smaller than the ellipsis: only the ellipsis */+ text_ellipsize(ltr, 400, 13, 2, 0, out, sizeof out);+ CHECK(!strcmp(out, "\xe2\x80\xa6"), "tiny box: %s", out);++ sweep("LTR", ltr);+ sweep("Arabic", arabic);+ sweep("Hebrew", hebrew);+ sweep("Thai", thai);+ sweep("emoji", emoji);+ sweep("combining", marks);++ /* the ellipsis goes on the visual left of RTL text, on the right of LTR */+ check_side("Arabic", arabic, 120, 1);+ check_side("Hebrew", hebrew, 90, 1);+ check_side("LTR in complex path", emoji, 90, 0);++ /* Arabic: the cut letter takes its final form (the cut form is shaped again), so the last+ * glyph before the ellipsis differs from the same letter in the middle of the word */+ {+ char a[256];+ text_ellipsize(arabic, 400, 13, 60, 0, a, sizeof a);+ float w1, h1;+ text_measure(a, 400, 13, 0, 0, 1, &w1, &h1);+ CHECK(w1 <= 60.5f, "Arabic cut form measures %.1f > 60", w1);+ }++ /* measure with a line clamp: at most N lines, and the width of the box when cut */+ const char *para = "The quick brown fox jumps over the lazy dog and keeps running across the whole field until night";+ float w, h, w2, h2;+ text_measure_ex(para, 400, 13, 0, 120, 0, 0, &w, &h);+ text_measure_ex(para, 400, 13, 0, 120, 0, 2, &w2, &h2);+ float lh = text_line_height(13, 0);+ CHECK(h > 2 * lh && fabsf(h2 - 2 * lh) < 0.01f, "clamp: %f lines -> %f", h / lh, h2 / lh);+ CHECK(fabsf(w2 - 120) < 0.6f, "clamp width %.1f", w2);+ text_measure_ex(arabic, 400, 13, 0, 90, 0, 2, &w2, &h2);+ CHECK(fabsf(h2 - 2 * lh) < 0.01f, "Arabic clamp: %f lines", h2 / lh);++ /* drawing: nowrap + ellipsis stays inside the box; the last clamped line ends in an ellipsis */+ static uint32_t px[300 * 80];+ Canvas c;+ canvas_init(&c, px, 300, 80, 300);+ canvas_clear(&c, 0);+ text_draw_ex(&c, ltr, 400, 13, 0, 10, 10, 100, TEXT_LEFT, 1, 0, 1, 0xffffffffu);+ int ink_out = 0, ink_in = 0;+ for (int y = 0; y < 80; y++)+ for (int x = 0; x < 300; x++)+ if (px[y * 300 + x] & 0xff) { if (x >= 111) ink_out++; else ink_in++; }+ CHECK(ink_in > 50 && ink_out == 0, "nowrap ellipsis drew outside the box (%d in, %d out)", ink_in, ink_out);+ canvas_clear(&c, 0);+ text_draw_ex(&c, para, 400, 13, 0, 10, 0, 120, TEXT_LEFT, 0, 2, 1, 0xffffffffu);+ int below = 0;+ for (int y = (int)(2 * lh) + 1; y < 80; y++) for (int x = 0; x < 300; x++) if (px[y * 300 + x] & 0xff) below++;+ CHECK(below == 0, "clamped text drew a third line (%d px)", below);+}++#endif++/* ---- nodes ---- */+static Node *view(Node *parent) {+ Node *n = node_new(NODE_VIEW);+ if (parent) node_append(parent, n);+ return n;+}+/* as lord.setStyle (js.c): set, then invalidate */+static void sn(Node *n, const char *k, double v) { if (style_set_number(&n->s, k, v) && !quiet) { printf("unknown style %s\n", k); fails++; } node_invalidate(n); }+static void ss(Node *n, const char *k, const char *v) { if (style_set_string(&n->s, k, v) && !quiet) { printf("unknown style %s=%s\n", k, v); fails++; } node_invalidate(n); }++#ifndef ENGINE_BEFORE+static uint32_t *fb;+static int FW, FH;+static Canvas frame;++static void render(Node *root, int w, int h) {+ if (FW != w || FH != h) { free(fb); fb = calloc((size_t)w * h, 4); FW = w; FH = h; }+ canvas_init(&frame, fb, w, h, w);+ layout_root(root, (float)w, (float)h);+ paint_damage(root);+ ui.damage = (Box){ 0, 0, (float)w, (float)h };+ canvas_clear(&frame, 0);+ paint_root(&frame, root);+ ui.damage = (Box){ 0, 0, 0, 0 };+}+static uint32_t pix(int x, int y) { return fb[y * FW + x] & 0xffffff; }++static void test_borders(void) {+ ui_reset();+ Node *root = view(NULL);+ ui.root = root;+ sn(root, "backgroundColor", 0xffffffff);+ /* bottom hairline 2 px red and a 1 px blue left edge, no top or right */+ Node *a = view(root);+ ss(a, "position", "absolute");+ sn(a, "left", 10); sn(a, "top", 10); sn(a, "width", 50); sn(a, "height", 30);+ sn(a, "borderBottomWidth", 2); sn(a, "borderBottomColor", 0xffff0000);+ sn(a, "borderLeftWidth", 1); sn(a, "borderLeftColor", 0xff0000ff);+ /* RTL: borderStart is the right side */+ Node *b = view(root);+ ss(b, "position", "absolute"); ss(b, "direction", "rtl");+ sn(b, "left", 70); sn(b, "top", 10); sn(b, "width", 20); sn(b, "height", 20);+ sn(b, "borderStartWidth", 3); sn(b, "borderStartColor", 0xff00ff00);+ /* only the top-left corner rounded */+ Node *r = view(root);+ ss(r, "position", "absolute");+ sn(r, "left", 10); sn(r, "top", 50); sn(r, "width", 40); sn(r, "height", 40);+ sn(r, "backgroundColor", 0xff000000); sn(r, "borderTopLeftRadius", 12);+ /* a rounded box with a per-side border: the sides meet on the corner's diagonal */+ Node *q = view(root);+ ss(q, "position", "absolute");+ sn(q, "left", 60); sn(q, "top", 50); sn(q, "width", 40); sn(q, "height", 40);+ sn(q, "borderRadius", 8); sn(q, "borderWidth", 4); sn(q, "borderColor", 0xff808080);+ sn(q, "borderTopColor", 0xffff0000);+ /* uniform border: the old path */+ Node *u = view(root);+ ss(u, "position", "absolute");+ sn(u, "left", 110); sn(u, "top", 10); sn(u, "width", 20); sn(u, "height", 20);+ sn(u, "borderWidth", 1); sn(u, "borderColor", 0xff000000);+ render(root, 140, 100);++ CHECK(!node_edges_plain(a) && node_edges_plain(u), "edges_plain flags");+ CHECK(pix(35, 39) == 0xff0000 && pix(35, 38) == 0xff0000, "bottom border: %06x", pix(35, 39));+ CHECK(pix(35, 37) == 0xffffff, "bottom border too thick: %06x", pix(35, 37));+ CHECK(pix(10, 25) == 0x0000ff, "left border: %06x", pix(10, 25));+ CHECK(pix(35, 10) == 0xffffff, "a top border appeared: %06x", pix(35, 10));+ CHECK(pix(59, 25) == 0xffffff, "a right border appeared: %06x", pix(59, 25));+ CHECK(node_border(b, EDGE_R) == 3 && node_border(b, EDGE_L) == 0, "RTL start = right (%g %g)", node_border(b, EDGE_L), node_border(b, EDGE_R));+ CHECK(pix(88, 20) == 0x00ff00 && pix(70, 20) == 0xffffff, "RTL border start: %06x %06x", pix(88, 20), pix(70, 20));+ CHECK(pix(11, 51) == 0xffffff, "top-left corner not rounded: %06x", pix(11, 51));+ CHECK(pix(48, 51) == 0x000000 && pix(11, 88) == 0x000000 && pix(48, 88) == 0x000000, "other corners should be square");+ CHECK(pix(80, 51) == 0xff0000 && pix(61, 70) == 0x808080 && pix(80, 88) == 0x808080, "rounded per-side border: %06x %06x %06x",+ pix(80, 51), pix(61, 70), pix(80, 88));+ CHECK(pix(80, 70) == 0xffffff, "rounded border filled the inside: %06x", pix(80, 70));+ CHECK(pix(110, 20) == 0x000000 && pix(120, 10) == 0x000000 && pix(120, 20) == 0xffffff, "uniform border");+ /* the content box shrinks by the per-side widths */+ Node *in = view(a);+ sn(in, "flexGrow", 1);+ render(root, 140, 100);+ CHECK(in->x == 1 && in->y == 0 && in->w == 49 && in->h == 28, "content box %g %g %g %g", in->x, in->y, in->w, in->h);+}++static void test_logical(void) {+ ui_reset();+ Node *root = view(NULL);+ ui.root = root;+ Node *col = view(root);+ sn(col, "width", 200); sn(col, "height", 100);+ Node *c1 = view(col);+ sn(c1, "height", 10); sn(c1, "marginStart", 10); sn(c1, "marginEnd", 30);+ Node *c2 = view(col);+ sn(c2, "height", 10); sn(c2, "paddingStart", 7);+ Node *t = view(c2);+ sn(t, "height", 4);+ Node *abs = view(col);+ ss(abs, "position", "absolute"); sn(abs, "width", 20); sn(abs, "height", 20); sn(abs, "start", 5); sn(abs, "top", 0);+ render(root, 300, 120);+ CHECK(c1->x == 10 && c1->w == 160, "LTR marginStart: x %g w %g", c1->x, c1->w);+ CHECK(t->x == 7, "LTR paddingStart: %g", t->x);+ CHECK(abs->x == 5, "LTR start: %g", abs->x);+ ss(col, "direction", "rtl");+ node_invalidate(col);+ render(root, 300, 120);+ CHECK(c1->x == 30 && c1->w == 160, "RTL marginStart: x %g w %g", c1->x, c1->w);+ CHECK(t->x == 0 && t->w == 193, "RTL paddingStart: x %g w %g", t->x, t->w);+ CHECK(abs->x == 175, "RTL start: %g", abs->x);+ /* a physical value loses against the logical one, as in React Native */+ sn(c1, "marginLeft", 50);+ render(root, 300, 120);+ CHECK(c1->x == 30 && node_margin(c1)[EDGE_R] == 10, "RTL marginLeft loses against marginEnd: x %g", c1->x);+ /* removing the logical values gives the physical ones back */+ style_reset(&c1->s, "marginStart");+ style_reset(&c1->s, "marginEnd");+ node_invalidate(c1);+ render(root, 300, 120);+ CHECK(c1->x == 50 && node_margin(c1)[EDGE_R] == 0, "reset marginStart/End: x %g right %g", c1->x, node_margin(c1)[EDGE_R]);+}++static void test_transform_math(void) {+ Affine s = { 2, 0, 0, 3, 5, 7 }, inv;+ CHECK(affine_invert(s, &inv), "invert");+ Affine id = affine_mul(s, inv);+ CHECK(fabsf(id.a - 1) < 1e-5f && fabsf(id.d - 1) < 1e-5f && fabsf(id.e) < 1e-4f && fabsf(id.f) < 1e-4f && fabsf(id.b) < 1e-6f,+ "m * inv(m) = identity");+ Style st;+ style_defaults(&st);+ CHECK(!style_has_transform(&st), "default style has no transform");+ style_set_number(&st, "scaleX", 2);+ style_set_number(&st, "scaleY", 2);+ Affine m = style_transform(&st, 10, 10, 20, 20); /* scale 2 around the center (20, 20) */+ float x, y;+ affine_apply(m, 20, 20, &x, &y);+ CHECK(fabsf(x - 20) < 1e-4f && fabsf(y - 20) < 1e-4f, "origin fixed: %g %g", x, y);+ affine_apply(m, 10, 10, &x, &y);+ CHECK(fabsf(x) < 1e-4f && fabsf(y) < 1e-4f, "corner scaled: %g %g", x, y);+ free(st.ext);+ style_defaults(&st);+ style_set_number(&st, "rotate", 90); /* clockwise on screen */+ m = style_transform(&st, 0, 0, 20, 20);+ affine_apply(m, 20, 10, &x, &y); /* right middle → bottom middle */+ CHECK(fabsf(x - 10) < 1e-4f && fabsf(y - 20) < 1e-4f, "rotate 90: %g %g", x, y);+ style_set_number(&st, "transformOriginX", 0);+ style_set_number(&st, "transformOriginY", 0);+ m = style_transform(&st, 0, 0, 20, 20);+ free(st.ext);+ affine_apply(m, 10, 0, &x, &y);+ CHECK(fabsf(x) < 1e-4f && fabsf(y - 10) < 1e-4f, "rotate around the top-left: %g %g", x, y);+ style_defaults(&st);+ style_set_number(&st, "rotate", 45);+ Box b = affine_box(style_transform(&st, 0, 0, 10, 10), (Box){ 0, 0, 10, 10 });+ CHECK(fabsf((b.x1 - b.x0) - 14.142f) < 0.01f, "rotated bounding box %g", b.x1 - b.x0);+ style_set_number(&st, "rotate", 360);+ CHECK(style_has_transform(&st) == 0, "rotate 360 is no transform");+ free(st.ext);+}++static void test_transform_paint_hit(void) {+ ui_reset();+ Node *root = view(NULL);+ ui.root = root;+ sn(root, "backgroundColor", 0xffffffff);+ Node *a = view(root); /* 40×40 red, scaled 0.5 around its center */+ ss(a, "position", "absolute");+ sn(a, "left", 10); sn(a, "top", 10); sn(a, "width", 40); sn(a, "height", 40);+ sn(a, "backgroundColor", 0xffff0000);+ sn(a, "scaleX", 0.5); sn(a, "scaleY", 0.5);+ Node *ac = view(a); /* a child: transformed with it */+ ss(ac, "position", "absolute");+ sn(ac, "left", 0); sn(ac, "top", 0); sn(ac, "width", 20); sn(ac, "height", 20);+ sn(ac, "backgroundColor", 0xff0000ff);+ Node *b = view(root); /* 60×10 green bar rotated 90° */+ ss(b, "position", "absolute");+ sn(b, "left", 70); sn(b, "top", 45); sn(b, "width", 60); sn(b, "height", 10);+ sn(b, "backgroundColor", 0xff00ff00);+ sn(b, "rotate", 90);+ render(root, 160, 100);++ /* layout is unaffected */+ CHECK(a->x == 10 && a->w == 40 && b->w == 60, "layout changed by the transform");+ /* painting: a covers 20..40, its child (top-left quarter) 20..30 */+ CHECK(pix(15, 15) == 0xffffff, "scaled box painted at its layout size: %06x", pix(15, 15));+ CHECK(pix(25, 25) == 0x0000ff && pix(35, 35) == 0xff0000, "scaled box and child: %06x %06x", pix(25, 25), pix(35, 35));+ CHECK(pix(45, 30) == 0xffffff, "scaled box too wide: %06x", pix(45, 30));+ /* the bar: vertical, x 95..105, y 20..80 */+ CHECK(pix(100, 25) == 0x00ff00 && pix(100, 75) == 0x00ff00, "rotated bar: %06x %06x", pix(100, 25), pix(100, 75));+ CHECK(pix(75, 50) == 0xffffff && pix(125, 50) == 0xffffff, "rotated bar still horizontal: %06x", pix(75, 50));++ /* hit testing uses the transformed boxes */+ CHECK(hit_test(root, 15, 15) == root, "hit inside the untransformed box only");+ CHECK(hit_test(root, 25, 25) == ac, "hit the child of a scaled box");+ CHECK(hit_test(root, 35, 35) == a, "hit the scaled box");+ CHECK(hit_test(root, 100, 22) == b, "hit the rotated bar's end");+ CHECK(hit_test(root, 75, 50) == root, "hit where the bar was before rotating");++ /* the raster is reused while only the scale changes within a step, and redone when a child changes */+ long r0, c0;+ paint_tf_stats(&r0, &c0);+ sn(a, "scaleX", 0.48); sn(a, "scaleY", 0.48);+ node_invalidate(a);+ render(root, 160, 100);+ long r1, c1;+ paint_tf_stats(&r1, &c1);+ CHECK(r1 == 0 && c1 == 2, "scale change re-rasterized (%ld renders, %ld composites)", r1, c1);+ sn(ac, "backgroundColor", 0xff000000);+ node_invalidate(ac);+ render(root, 160, 100);+ paint_tf_stats(&r1, &c1);+ CHECK(r1 == 1, "child change did not re-rasterize (%ld)", r1);+ CHECK(pix(26, 26) == 0x000000, "child color not updated: %06x", pix(26, 26));++ /* at 150 % the raster is at the display's resolution (sharp edge, no blur band) */+ PaintView keep = paint_view;+ paint_view = (PaintView){ 0, 0, 1.5f, 0, 0, 0 };+ sn(a, "scaleX", 1); sn(a, "scaleY", 1); sn(a, "rotate", 0);+ sn(b, "scaleX", 2); sn(b, "scaleY", 2); sn(b, "rotate", 0);+ node_invalidate(a); node_invalidate(b);+ if (FW != 240) { free(fb); fb = calloc(240 * 150, 4); FW = 240; FH = 150; }+ canvas_init(&frame, fb, 240, 150, 240);+ layout_root(root, 160, 100);+ paint_damage(root);+ ui.damage = (Box){ 0, 0, 160, 100 };+ canvas_clear(&frame, 0);+ paint_root(&frame, root);+ paint_view = keep;+ /* b: 60×10 at (70,45) scaled 2 around (100,50) → x 40..160, y 40..60 logical → 60..240, 60..90 physical */+ int soft = 0;+ for (int x = 100; x < 230; x++) { uint32_t p = pix(x, 61); if (p != 0x00ff00 && p != 0xffffff && p != 0xff0000 && p != 0x000000) soft++; }+ CHECK(pix(150, 75) == 0x00ff00, "scaled bar at 150%%: %06x", pix(150, 75));+ CHECK(soft == 0, "blurry row inside the scaled bar at 150%% (%d px)", soft);+}++#endif++/* ---- benchmark: a Files-like list and a window drag (docs/DESIGN.md, Engine notes) ---- */+static double now_ms(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec * 1e3 + t.tv_nsec / 1e6; }+static int cmp_d(const void *a, const void *b) { double x = *(const double *)a, y = *(const double *)b; return x < y ? -1 : x > y; }+static double median(double *v, int n) { qsort(v, (size_t)n, sizeof *v, cmp_d); return v[n / 2]; }++static Node *text(Node *parent, const char *s, float size) {+ Node *t = node_new(NODE_TEXT), *r = node_new(NODE_RAW);+ node_set_text(r, s);+ node_append(t, r);+ node_append(parent, t);+ sn(t, "fontSize", size);+ sn(t, "color", 0xff202020);+ return t;+}++typedef struct { int w, h; float x, k; uint32_t *px; Canvas c; } Disp;++static double t_layout, t_damage, t_paint;+static void frame_paint(Node *root, Disp *d, int nd) {+ double q0 = now_ms();+ layout_root(root, 1280, 800);+ double q1 = now_ms();+ Box dmg = { 0, 0, 0, 0 };+ if (paint_damage(root)) dmg = ui.damage;+ double q2 = now_ms();+ t_layout += q1 - q0;+ t_damage += q2 - q1;+ int ln = paint_layer_node();+ if (ln) {+ Node *w = node_get(ln);+ paint_layer_view(w && w->prev_box.x0 + (w->prev_box.x1 - w->prev_box.x0) / 2 >= 1280 / (float)nd * (nd - 1) && nd > 1 ? 1 : 0);+ }+ for (int i = 0; i < nd; i++) {+ if (dmg.x1 <= dmg.x0) break;+ float vx0 = d[i].x, vx1 = d[i].x + d[i].w / d[i].k;+ Box b = { fmaxf(dmg.x0, vx0), fmaxf(dmg.y0, 0), fminf(dmg.x1, vx1), fminf(dmg.y1, d[i].h / d[i].k) };+ if (b.x1 <= b.x0 || b.y1 <= b.y0) continue;+ paint_view = (PaintView){ d[i].x, 0, d[i].k, 0, 0, i };+ Rect r = { (int)floorf((b.x0 - d[i].x) * d[i].k), (int)floorf(b.y0 * d[i].k), (int)ceilf((b.x1 - d[i].x) * d[i].k), (int)ceilf(b.y1 * d[i].k) };+ if (r.x1 > d[i].w) r.x1 = d[i].w;+ if (r.y1 > d[i].h) r.y1 = d[i].h;+ ui.damage = b;+ canvas_set_clip(&d[i].c, r);+ canvas_clear(&d[i].c, 0);+ paint_root(&d[i].c, root);+ canvas_set_clip(&d[i].c, (Rect){ 0, 0, d[i].w, d[i].h });+ }+ paint_view = (PaintView){ 0, 0, 1, 0, 0, 0 };+ ui.damage = (Box){ 0, 0, 0, 0 };+ t_paint += now_ms() - q2;+}++static void bench(void) {+ static const char *const words[] = { "Quarterly", "report", "holiday", "photos", "final", "version", "backup", "draft",+ "invoice", "scan", "notes", "presentation", "budget", "summary" };+ quiet = 1;+ ui_reset();+ Node *root = view(NULL);+ ui.root = root;+ sn(root, "backgroundColor", 0xff3a4a5a);+ /* Files: a 900×600 window with a 2000-row list view (icon, name with ellipsis, size, date) */+ Node *win = view(root);+ ss(win, "position", "absolute");+ sn(win, "left", 120); sn(win, "top", 80); sn(win, "width", 900); sn(win, "height", 600);+ sn(win, "backgroundColor", 0xfff5f5f5); sn(win, "borderRadius", 10);+ sn(win, "shadowColor", 0x66000000); sn(win, "shadowBlur", 24); sn(win, "shadowOffsetY", 8);+ ss(win, "overflow", "hidden");+ Node *bar = view(win);+ sn(bar, "height", 44); sn(bar, "backgroundColor", 0xffe8e8e8);+ sn(bar, "borderBottomWidth", 1); sn(bar, "borderBottomColor", 0xffd0d0d0);+ Node *list = view(win);+ sn(list, "flexGrow", 1); ss(list, "overflow", "hidden");+ Node *inner = view(list);+ char name[256];+ srand(7);+ for (int i = 0; i < 2000; i++) {+ Node *row = view(inner);+ ss(row, "flexDirection", "row"); ss(row, "alignItems", "center");+ sn(row, "height", 24); sn(row, "paddingLeft", 10); sn(row, "paddingRight", 10); sn(row, "gap", 8);+ if (i & 1) sn(row, "backgroundColor", 0xffefefef);+ Node *icon = view(row);+ sn(icon, "width", 16); sn(icon, "height", 16); sn(icon, "borderRadius", 3); sn(icon, "backgroundColor", 0xff5b8def);+ int len = 0, nw = 2 + rand() % 9;+ for (int k = 0; k < nw; k++) len += snprintf(name + len, sizeof name - (size_t)len, "%s%s", k ? " " : "", words[rand() % 14]);+ snprintf(name + len, sizeof name - (size_t)len, " %d.pdf", i);+ Node *t = text(row, name, 13);+ sn(t, "flexGrow", 1); sn(t, "flexShrink", 1); sn(t, "flexBasis", 0);+ ss(t, "whiteSpace", "nowrap");+ if (!getenv("BENCH_NO_ELLIPSIS")) ss(t, "textOverflow", "ellipsis"); /* ignored by an engine without it */+ Node *size = text(row, "1.2 MB", 12);+ sn(size, "width", 70); ss(size, "textAlign", "right");+ Node *date = text(row, "18 Oct 2026, 04:20", 12);+ sn(date, "width", 130);+ }+ /* a second window to drag over it (a dialog with some controls) */+ Node *dlg = view(root);+ ss(dlg, "position", "absolute");+ sn(dlg, "left", 300); sn(dlg, "top", 200); sn(dlg, "width", 520); sn(dlg, "height", 360);+ sn(dlg, "backgroundColor", 0xffffffff); sn(dlg, "borderRadius", 10); sn(dlg, "padding", 20); sn(dlg, "gap", 8);+ sn(dlg, "shadowColor", 0x66000000); sn(dlg, "shadowBlur", 24); sn(dlg, "shadowOffsetY", 8);+ for (int i = 0; i < 12; i++) {+ Node *r = view(dlg);+ ss(r, "flexDirection", "row"); sn(r, "height", 20); sn(r, "gap", 8);+ text(r, "Label of the setting", 13);+ Node *f = view(r);+ sn(f, "flexGrow", 1); sn(f, "borderWidth", 1); sn(f, "borderColor", 0xffc0c0c0); sn(f, "borderRadius", 5);+ }+ /* a Dock with blur, above the windows */+ Node *dock = view(root);+ ss(dock, "position", "absolute");+ sn(dock, "left", 340); sn(dock, "bottom", 8); sn(dock, "width", 600); sn(dock, "height", 64);+ sn(dock, "backgroundColor", 0x80ffffff); sn(dock, "borderRadius", 16); sn(dock, "backdropBlur", 20);++ Disp d[2];+ d[0] = (Disp){ 1280, 800, 0, 1, NULL, {0} };+ d[1] = (Disp){ 1920, 1200, 1280, 1.5f, NULL, {0} };+ for (int i = 0; i < 2; i++) { d[i].px = calloc((size_t)d[i].w * d[i].h, 4); canvas_init(&d[i].c, d[i].px, d[i].w, d[i].h, d[i].w); }++ /* layout: cold (every text measured) and warm (cache); medians, the machine may be busy */+ double t0 = now_ms();+ layout_root(root, 1280, 800);+ double cold = now_ms() - t0;+ enum { N = 41 };+ double v[N];+ for (int i = 0; i < N; i++) { node_invalidate(inner); double a = now_ms(); layout_root(root, 1280, 800); v[i] = now_ms() - a; }+ double warm = median(v, N);+ /* full paint of the screen */+ paint_damage(root);+ for (int i = 0; i < N; i++) {+ ui.damage = (Box){ 0, 0, 1280, 800 };+ double a = now_ms();+ canvas_clear(&d[0].c, 0);+ paint_root(&d[0].c, root);+ v[i] = now_ms() - a;+ }+ printf("list: 2000 rows; layout cold %.2f ms, warm %.2f ms; full paint %.2f ms\n", cold, warm, median(v, N));+ /* scrolling the list: move the inner column and repaint (layout + damage + paint) */+ for (int i = 0; i < N; i++) {+ sn(inner, "marginTop", -24.0 * i);+ node_invalidate(inner);+ double a = now_ms();+ frame_paint(root, d, 1);+ v[i] = now_ms() - a;+ }+ printf("scroll frame: %.2f ms\n", median(v, N));++ /* drag: the dialog moves for 240 frames, on one display and on two (the second at 150 %) */+ for (int nd = 1; nd <= 2; nd++) {+ ui.damage = (Box){ 0, 0, 1280 * (float)nd, 800 };+ frame_paint(root, d, nd);+ paint_layer_begin(dlg->id, 0);+ long r, b;+ paint_layer_stats(&r, &b);+ double worst = 0, sum = 0;+ enum { F = 240 };+ static double fv[F];+ t_layout = t_damage = t_paint = 0;+ for (int f = 0; f < F; f++) {+ float ang = f * 0.05f;+ float x = 300 + 260 * cosf(ang) + (nd == 2 ? 340 : 0), y = 200 + 120 * sinf(ang);+ dlg->s.pos[EDGE_L] = (Dim){ x, UNIT_PX };+ dlg->s.pos[EDGE_T] = (Dim){ y, UNIT_PX };+#ifndef ENGINE_BEFORE+ node_moved(dlg); /* as grab.c does */+#endif+ ui.dirty = 1;+ double a = now_ms();+ frame_paint(root, d, nd);+ double ms = now_ms() - a;+ fv[f] = ms;+ sum += ms;+ if (f > 0 && ms > worst) worst = ms;+ }+ paint_layer_stats(&r, &b);+ paint_layer_end();+ frame_paint(root, d, nd);+ printf("drag (%d display%s): median %.2f ms per frame, mean %.2f (layout %.2f, damage %.2f, paint %.2f; worst %.2f after the first), layer renders %ld, blits %ld\n",+ nd, nd > 1 ? "s" : "", median(fv, F), sum / F, t_layout / F, t_damage / F, t_paint / F, worst, r, b);+ }+}++int main(int argc, char **argv) {+ const char *dir = getenv("LORD_FONTS") ? getenv("LORD_FONTS") : "../assets/fonts";+ fonts_set_builtin_dir(dir);+ if (text_init(dir)) { printf("engine-test: no fonts in %s\n", dir); return 1; }+ if (argc > 1 && !strcmp(argv[1], "bench")) { bench(); return 0; }+#ifdef ENGINE_BEFORE+ return 0;+#else+ test_ellipsis();+ test_borders();+ test_logical();+ test_transform_math();+ test_transform_paint_hit();+ printf("engine-test: %d checks, %d failures\n", checks, fails);+ return fails ? 1 : 0;+#endif+}diff --git a/server/tests/fw_rules_test.c b/server/tests/fw_rules_test.cindex 4b7c597..20cc073 100644--- a/server/tests/fw_rules_test.c+++ b/server/tests/fw_rules_test.c@@ -610,7 +610,7 @@ static void test_random(void) {FwDecision d = fw_decide(s, &q);uint32_t got = d.reason == FW_BY_RULE ? d.rule_id : 0;total++;- if (want != got) { mism++; if (mism < 5) fprintf(stderr, " azar: esperaba regla %u, dio %u\n", want, got); }+ if (want != got) { mism++; if (mism < 5) fprintf(stderr, " random: expected rule %u, got %u\n", want, got); }}}CHECK(mism == 0);diff --git a/server/tests/homedirs_test.c b/server/tests/homedirs_test.cindex b81c9b2..827865f 100644--- a/server/tests/homedirs_test.c+++ b/server/tests/homedirs_test.c@@ -64,7 +64,7 @@ int main(void) {lang("es_AR.UTF-8", es, "XDG_DOCUMENTS_DIR=\"$HOME/Documentos\"", "es_AR");lang("en_US.UTF-8", en, "XDG_DOWNLOAD_DIR=\"$HOME/Downloads\"", "en_US");lang("pt_BR.UTF-8", pt, "XDG_DESKTOP_DIR=\"$HOME/Área de trabalho\"", "pt_BR");- lang("C.UTF-8", es, "XDG_PICTURES_DIR=\"$HOME/Imágenes\"", "es_ES"); /* no language: Spanish */+ lang("C.UTF-8", en, "XDG_PICTURES_DIR=\"$HOME/Pictures\"", "en_US"); /* no language: English *//* ~/.config is a symlink elsewhere: nothing is written through it */char home[] = "/tmp/homedirs-test-XXXXXX", other[] = "/tmp/homedirs-other-XXXXXX";diff --git a/server/tests/net_test.c b/server/tests/net_test.cindex ca00820..52fab8e 100644--- a/server/tests/net_test.c+++ b/server/tests/net_test.c@@ -4,6 +4,7 @@* net-test state what lord.net sees without root (interfaces, routes, DNS, VPN)* net-test monitor <seconds> rtnetlink notifications* net-test ovpn-inline <path> the .ovpn with its files embedded (lord.net.prepareOvpn)+ * net-test errors config errors are code lines (errcode.h), never prose* sudo net-test act <action> <arg> runs a "net-*" action the way the helper would;* "\n" in arg is a newline, "@file" reads it* sudo net-test daemons the tests' resident processes@@ -14,6 +15,8 @@#define LORD_NET_ACTIONS#include "net/net.h"#include "net/netpriv.h"+#include "net/vpn.h"+#include "errcode.h"#include <dirent.h>#include <errno.h>@@ -218,16 +221,40 @@ static int test_crypto(void) {return fails;}+/* The UI translates these with t('errors.<code>'): the test matches codes and params, not text. */+static int test_errors(void) {+ int fails = 0, ok;+ char err[256], v[64];+ static const char *const keys[] = { "server", "user", NULL }, *const pem[] = { "ca", NULL };+ VpnKv kv;+ ok = vpn_kv_parse("server=a.example\nnot a pair\n", keys, pem, &kv, err, sizeof err) && lerr_has(err, "vpn.expectedKeyValue")+ && lerr_param(err, "line", v, sizeof v) && !strcmp(v, "2");+ printf("kv without '=': %s (%s)\n", ok ? "ok" : "BAD", err); fails += !ok;+ ok = vpn_kv_parse("color=red\n", keys, pem, &kv, err, sizeof err) && lerr_has(err, "vpn.unknownKey")+ && lerr_param(err, "key", v, sizeof v) && !strcmp(v, "color");+ printf("unknown key: %s (%s)\n", ok ? "ok" : "BAD", err); fails += !ok;+ ok = vpn_kv_parse("ca=not pem\n", keys, pem, &kv, err, sizeof err) && lerr_has(err, "vpn.pemRequired");+ printf("PEM required: %s (%s)\n", ok ? "ok" : "BAD", err); fails += !ok;+ ok = !vpn_kv_parse("server=a.example\nuser=me\n", keys, pem, &kv, err, sizeof err) && !strcmp(vpn_kv(&kv, "user"), "me");+ if (ok) vpn_kv_free(&kv);+ printf("valid kv: %s\n", ok ? "ok" : "BAD"); fails += !ok;+ ok = !net_ovpn_inline("/nonexistent/x y.ovpn", err, sizeof err) && lerr_has(err, "sys.readFailed")+ && lerr_param(err, "path", v, sizeof v) && !strcmp(v, "/nonexistent/x y.ovpn") && strstr(err, "x%20y");+ printf("ovpn missing file: %s (%s)\n", ok ? "ok" : "BAD", err); fails += !ok;+ return fails;+}+static void print_json(const char *what, char *j) {printf("%s: %s\n", what, j ? j : "(error)");free(j);}-static void on_change(const char *what) { printf("cambio: %s\n", what); fflush(stdout); }+static void on_change(const char *what) { printf("change: %s\n", what); fflush(stdout); }int main(int argc, char **argv) {- if (argc < 2) { fprintf(stderr, "usage: net-test crypto | state | monitor <s> | act <action> <arg> | daemons\n"); return 2; }+ if (argc < 2) { fprintf(stderr, "usage: net-test crypto | errors | state | monitor <s> | act <action> <arg> | daemons\n"); return 2; }if (!strcmp(argv[1], "crypto")) return test_crypto() ? 1 : 0;+ if (!strcmp(argv[1], "errors")) return test_errors() ? 1 : 0;if (!strcmp(argv[1], "state")) {print_json("interfaces", net_interfaces_json());print_json("routes", net_routes_json());diff --git a/server/tests/pkg_test.c b/server/tests/pkg_test.cindex 71f4e5d..2ddc364 100644--- a/server/tests/pkg_test.c+++ b/server/tests/pkg_test.c@@ -15,6 +15,7 @@#include "pkg/resolve.h"#include "pkg/status.h"#include "pkg/xz.h"+#include "errcode.h"#include <pwd.h>#include <stdarg.h>@@ -261,7 +262,7 @@ static void test_resolver(const char *dir) {o = (PlanOpts){ 0 };const char *rm[] = { "libfoo" };plan_make(&x, &st, NULL, 0, rm, 1, &o, &p);- CHECK(!p.ok && strstr(p.err, "también hay que quitar") && has(&p, PA_REMOVE, "oldtool") && has(&p, PA_REMOVE, "user"), "cascade asks for confirmation: %s", p.err);+ CHECK(!p.ok && lerr_has(p.err, "pkg.removeAlso") && has(&p, PA_REMOVE, "oldtool") && has(&p, PA_REMOVE, "user"), "cascade asks for confirmation: %s", p.err);plan_free(&p);o.cascade = 1;plan_make(&x, &st, NULL, 0, rm, 1, &o, &p);@@ -269,7 +270,7 @@ static void test_resolver(const char *dir) {plan_free(&p);const char *ess[] = { "dpkg" };plan_make(&x, &st, NULL, 0, ess, 1, &o, &p);- CHECK(!p.ok && strstr(p.err, "esencial"), "dpkg is not removed: %s", p.err);+ CHECK(!p.ok && lerr_has(p.err, "pkg.removeEssential"), "dpkg is not removed: %s", p.err);plan_free(&p);/* two MTAs: installing mta-a removes mta-b (with confirmation) */o = (PlanOpts){ 0 };@@ -279,19 +280,19 @@ static void test_resolver(const char *dir) {plan_free(&p);o.allow_remove = 1;plan_make(&x, &st, mta, 1, NULL, 0, &o, &p);- CHECK(p.ok && has(&p, PA_REMOVE, "mta-b") && has(&p, PA_INSTALL, "mta-a"), "mta-a reemplaza a mta-b: %s", p.err);+ CHECK(p.ok && has(&p, PA_REMOVE, "mta-b") && has(&p, PA_INSTALL, "mta-a"), "mta-a replaces mta-b: %s", p.err);plan_free(&p);/* virtual with several providers */const char *wb[] = { "web-browser" };plan_make(&x, &st, wb, 1, NULL, 0, &o, &p);- CHECK(!p.ok && strstr(p.err, "virtual"), "virtual: %s", p.err);+ CHECK(!p.ok && lerr_has(p.err, "pkg.virtual"), "virtual: %s", p.err);plan_free(&p);/* orphans: libdep, libdeep and librec are automatic dependencies of user2; libold is used by* nobody; libmanual is not automatic */static const char *const autos[] = { "libdep", "libdeep", "librec", "libold" };o = (PlanOpts){ .orphans = 1, .autos = autos, .nautos = 4 };plan_make(&x, &st, NULL, 0, NULL, 0, &o, &p);- CHECK(p.ok && p.n == 1 && has(&p, PA_REMOVE, "libold") && !strcmp(p.items[0].reason, "auto") && p.items[0].orphan, "autoremove: only libold (%d)", p.n);+ CHECK(p.ok && p.n == 1 && has(&p, PA_REMOVE, "libold") && !strcmp(p.items[0].reason, "pkg.why.auto") && p.items[0].orphan, "autoremove: only libold (%d)", p.n);plan_free(&p);const char *u2[] = { "user2" };plan_make(&x, &st, NULL, 0, u2, 1, &o, &p);@@ -330,7 +331,7 @@ static int cmd_plan(int argc, char **argv) {}Plan p;plan_make(&x, &st, ins, ni, rem, nr, &o, &p);- printf("ok=%d %s · bajar %llu bytes · %lld KB\n", p.ok, p.err, (unsigned long long)p.download, (long long)p.isize_delta);+ printf("ok=%d %s · download %llu bytes · %lld KB\n", p.ok, p.err, (unsigned long long)p.download, (long long)p.isize_delta);for (int i = 0; i < p.n; i++)printf(" %-7s %s %s%s%s (%s)\n", p.items[i].action == PA_INSTALL ? "install" : p.items[i].action == PA_UPGRADE ? "upgrade" : "remove",p.items[i].name, p.items[i].old_version ? p.items[i].old_version : "", p.items[i].old_version ? " -> " : "", p.items[i].version, p.items[i].reason);diff --git a/server/tests/sign_test.c b/server/tests/sign_test.cindex 4d6dca7..3ff3d58 100644--- a/server/tests/sign_test.c+++ b/server/tests/sign_test.c@@ -6,6 +6,7 @@#include "sec/json.h"#include "sec/sign.h"#include "pkg/crypto.h"+#include "errcode.h"#include <stdio.h>#include <stdlib.h>@@ -152,7 +153,7 @@ static void test_packages(void) {static const char evil[] = "var __lordosApp={x:1};";files[1].data = (const uint8_t *)evil;files[1].size = sizeof evil - 1;- CHECK(sig_verify_package(&pk, "hola", "1.0.0", &si, err, sizeof err) && strstr(err, "app.js"), "altered file: %s", err);+ CHECK(sig_verify_package(&pk, "hola", "1.0.0", &si, err, sizeof err) && lerr_has(err, "sig.fileModified") && strstr(err, "path=app.js"), "altered file: %s", err);files[1] = (LpkFile){ "app.js", (const uint8_t *)appjs, sizeof appjs - 1 };/* an extra file */diff --git a/themes/default/components/Dock.jsx b/themes/default/components/Dock.jsxindex 6a6d708..089cec0 100644--- a/themes/default/components/Dock.jsx+++ b/themes/default/components/Dock.jsx@@ -120,7 +120,9 @@ export function Dock({ t, items: list, running, onOpen, onContext, position = 'bconst hide = Math.round((1 - shown) * (bar + MARGIN + 2));if (autohide && shown <= 0) return null;- const BH = MAX + PAD * 2 + 34, BW = MAX + PAD * 2;+ // The hit box covers only the bar until the pointer is on it; then it grows to fit the magnified+ // icons and the tooltip. A full-height box at rest would swallow clicks on windows just above the Dock.+ const BH = m != null ? MAX + PAD * 2 + 34 : bar, BW = m != null ? MAX + PAD * 2 : bar;const box = position === 'bottom' ? { left: start, top: AB - (MARGIN - hide) - BH, width: len, height: BH }: position === 'left' ? { left: AX + MARGIN - hide, top: start, width: BW, height: len }: { left: AR - (MARGIN - hide) - BW, top: start, width: BW, height: len };diff --git a/themes/default/components/Window.jsx b/themes/default/components/Window.jsxindex 815276c..5051807 100644--- a/themes/default/components/Window.jsx+++ b/themes/default/components/Window.jsx@@ -12,10 +12,19 @@ const LIGHTS = [{ key: 'max', color: '#28c840', glyph: '+', act: (id) => wm.toggleMaximize(id) },];-export function Window({ win, app, t, focused }) {+// fx: the minimize effect ({ p: 0..1, x, y: where the Dock is}): the frame shrinks towards it.+function fxStyle(fx, geo) {+ if (!fx) return null;+ const e = fx.p * fx.p; // ease-in+ const dx = (fx.x - (geo.x + geo.w / 2)) * e, dy = (fx.y - (geo.y + geo.h / 2)) * e;+ return { transform: `translate(${dx}px, ${dy}px) scale(${1 - 0.9 * e})`, opacity: 1 - 0.7 * e, pointerEvents: 'none' };+}++export function Window({ win, app, t, focused, fx }) {const drag = useRef(null);const [hover, setHover] = useState(false);const geo = wm.frame(win);+ const fxs = fxStyle(fx, geo);useEffect(() => {const offMove = addListener('pointermove', (e) => {@@ -29,7 +38,7 @@ export function Window({ win, app, t, focused }) {if (win.args?.csd) {return (<WindowShell win={win} onMouseDown={() => wm.focus(win.id)}- style={{ boxShadow: focused ? '0 24px 56px rgba(0,0,0,0.5)' : '0 10px 28px rgba(0,0,0,0.3)' }}>+ style={{ boxShadow: focused ? '0 24px 56px rgba(0,0,0,0.5)' : '0 10px 28px rgba(0,0,0,0.3)', ...fxs }}><AppHost id={win.id} focused={focused} /></WindowShell>);@@ -40,6 +49,7 @@ export function Window({ win, app, t, focused }) {borderRadius: win.maximized ? 0 : 12, backgroundColor: app.transparent ? 'transparent' : t.windowBg, overflow: 'hidden',border: `1px solid ${t.windowBorder}`,boxShadow: focused ? '0 24px 56px rgba(0,0,0,0.55)' : '0 10px 28px rgba(0,0,0,0.32)',+ ...fxs,}}><View onMouseDown={(e) => { if (!wm.beginMove(win.id)) drag.current = { dx: e.x - geo.x, dy: e.y - geo.y }; }}onDoubleClick={() => wm.toggleMaximize(win.id)}diff --git a/themes/default/index.jsx b/themes/default/index.jsxindex 8671aad..16099de 100644--- a/themes/default/index.jsx+++ b/themes/default/index.jsx@@ -7,7 +7,7 @@ import {DesktopWidgets, registerGestureActions, screenDisplays, mainDisplay, settings,} from '@lordos/sdk';import { apps } from '@lordos/apps';-import { useEffect, useState } from 'react';+import { useEffect, useRef, useState } from 'react';import { makeTheme } from './tokens.js';import { MenuBar } from './components/MenuBar.jsx';import { Dock, LaunchpadIcon, dockThickness } from './components/Dock.jsx';@@ -43,10 +43,40 @@ wm.open('about');// Pinned by default (the user changes the Dock with «Keep in Dock»: settings.dockPinned).const DOCK_DEFAULT = [...DOCK_ORDER, ...apps.filter((a) => a.dock && !DOCK_ORDER.includes(a.id)).map((a) => a.id)];+// Minimize effect: a window that was just minimized stays drawn for MIN_MS, shrinking towards the+// Dock (transform: scale, painted from a cached raster by lord-server; layout doesn't change).+const MIN_MS = 260;+function useMinimizing(windows) {+ const prev = useRef(new Map());+ const [anim, setAnim] = useState([]); // [{ id, t0 }]+ useEffect(() => {+ const started = [];+ for (const w of windows) {+ if (w.minimized && prev.current.get(w.id) === false && !w.fullscreen && !w.pip) started.push({ id: w.id, t0: Date.now() });+ prev.current.set(w.id, !!w.minimized);+ }+ if (started.length) setAnim((a) => [...a.filter((x) => !started.some((y) => y.id === x.id)), ...started]);+ }, [windows]);+ const [, tick] = useState(0);+ useEffect(() => {+ if (!anim.length) return undefined;+ let raf = requestAnimationFrame(function step() {+ const now = Date.now();+ if (anim.some((x) => now - x.t0 >= MIN_MS)) setAnim((a) => a.filter((x) => now - x.t0 < MIN_MS));+ else { tick((n) => n + 1); raf = requestAnimationFrame(step); }+ });+ return () => cancelAnimationFrame(raf);+ }, [anim]);+ const now = Date.now();+ return anim.map((x) => ({ win: windows.find((w) => w.id === x.id), p: Math.min(1, (now - x.t0) / MIN_MS) }))+ .filter((x) => x.win && x.win.minimized);+}+function App() {const [s] = useSettings();const t = makeTheme(s);const { windows, visible, focused } = useWindows();+ const minimizing = useMinimizing(windows);const [launchpad, setLaunchpad] = useState(false);const [control, setControl] = useState(null); // the display whose menu bar opened itconst [context, setContext] = useState(null);@@ -95,6 +125,8 @@ function App() {))}<DesktopWidgets layer="below" />{visible.map((w) => <Window key={w.id} win={w} app={getApp(w.id)} t={t} focused={w.id === focused} />)}+ {minimizing.map(({ win, p }) => <Window key={win.id} win={win} app={getApp(win.id)} t={t} focused={false}+ fx={{ p, x: main.x + main.w / 2, y: main.y + main.h - 36 }} />)}<DesktopWidgets layer="above" />{bars.map((d) => (<MenuBar key={d.id + ':' + d.x} t={t} height={MENU_H} focused={focused} controlCenter={!!control} area={d}diff --git a/themes/default/tokens.js b/themes/default/tokens.jsindex da62eff..e8081c9 100644--- a/themes/default/tokens.js+++ b/themes/default/tokens.js@@ -9,11 +9,12 @@ export const accents = {grafito: '#8e8e93',};+// name: English fallback; the shown name is the translation of nameKey (assets/locales/*/shell.json).export const wallpapers = [- { id: 'aurora', name: 'Aurora', src: 'assets/aurora.png' },- { id: 'ocean', name: 'Océano', src: 'assets/ocean.png' },- { id: 'sunset', name: 'Atardecer', src: 'assets/sunset.png' },- { id: 'graphite', name: 'Grafito', src: 'assets/graphite.png' },+ { id: 'aurora', nameKey: 'shell.wallpaper.aurora', name: 'Aurora', src: 'assets/aurora.png' },+ { id: 'ocean', nameKey: 'shell.wallpaper.ocean', name: 'Ocean', src: 'assets/ocean.png' },+ { id: 'sunset', nameKey: 'shell.wallpaper.sunset', name: 'Sunset', src: 'assets/sunset.png' },+ { id: 'graphite', nameKey: 'shell.wallpaper.graphite', name: 'Graphite', src: 'assets/graphite.png' },];export function makeTheme({ mode, accent, effects }) {diff --git a/themes/greeter/index.jsx b/themes/greeter/index.jsxindex 672c686..db5272b 100644--- a/themes/greeter/index.jsx+++ b/themes/greeter/index.jsx@@ -151,10 +151,10 @@ function Greeter() {const variants = String(m.variants || '').split(',');const kbs = layouts.map((l, i) => ({ layout: l, variant: variants[i] || '' }));if (JSON.stringify(settings.get().keyboards) !== JSON.stringify(kbs)) keyboard.set(kbs);- // language: the one chosen here before or the system's (if there is no catalog, Spanish)+ // language: the one chosen here before or the system's (if there is no catalog, English)if (!['es', 'en', 'pt'].includes(settings.get().language)) {const sys = String(m.lang || '').slice(0, 2);- setLanguage(['es', 'en', 'pt'].includes(sys) ? sys : 'es');+ setLanguage(['es', 'en', 'pt'].includes(sys) ? sys : 'en');}// the selected user: the one from the locked screen, another (switch user) or the first;// only when the mode changes, so the refreshed list doesn't override what the person chosediff --git a/tools/err-check.mjs b/tools/err-check.mjsnew file mode 100644index 0000000..6a4400d--- /dev/null+++ b/tools/err-check.mjs@@ -0,0 +1,164 @@+// err-check.mjs — checks that the server reports errors and statuses as codes, not prose.+//+// node tools/err-check.mjs (also run by tools/i18n-check.mjs)+//+// Scans server/src (C, without comments) and reports:+// - codes used with admin_err/admin_ok/admin_log/admin_code, lerr_set, js_throw_code,+// js_throw_line or put_line(…, "ERR", …) that have no English string in+// assets/locales/en/errors.json (ERR) or status.json (OK/LOG);+// - prose in ERR/OK/LOG lines (admin_say("ERR", "could not…")) and in JS exceptions+// (JS_ThrowTypeError(c, "…")): they must be js_throw_code / admin_err with a code;+// - Spanish prose in any string literal (the project is English-only; UI text goes in the+// locale files).+// A line can opt out with a trailing /* i18n-ok */ comment (data, not prose: folder names,+// protocol tokens of other programs…). Files that other work still has to convert are listed in+// PENDING: their findings are warnings. See docs/LANGUAGES.md, "Error and status messages".+import fs from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++const root = path.dirname(path.dirname(fileURLToPath(import.meta.url)));+const SRC = path.join(root, 'server/src');++// Out of this pass's scope (engine and app-mode work): warnings until converted.+export const PENDING = [+ 'ui/paint.c', 'ui/layout.c', 'ui/text.c', 'ui/style.c',+ 'app/', 'sec/brokersrv.c', 'ui/js_broker.c',+];++const CODE = /^[a-z][a-zA-Z0-9]*(?:\.[a-zA-Z0-9]+)+$/;+const SPANISH = /[áéíóúñÁÉÍÓÚÑ¿¡]|\b(?:no se pudo|no hay|falta|faltan|inválid[oa]s?|desconocid[oa]s?|archivo|carpeta|contraseña|usuario|paquete|también|esencial|ayudante|conectad[oa]|desconectad[oa]|error al|demasiad[oa]s?|todavía|ningún|ninguna)\b/i;++// Replaces comments with spaces (keeping line numbers and the /* i18n-ok */ markers' lines).+function stripComments(src) {+ let out = '', i = 0;+ const ok = new Set();+ let line = 1;+ while (i < src.length) {+ const ch = src[i], nx = src[i + 1];+ if (ch === '"' || ch === "'") {+ const q = ch;+ out += ch; i++;+ while (i < src.length && src[i] !== q && src[i] !== '\n') {+ if (src[i] === '\\') { out += src[i] + (src[i + 1] ?? ''); i += 2; continue; }+ out += src[i++];+ }+ if (i < src.length) out += src[i++];+ continue;+ }+ if (ch === '/' && nx === '*') {+ const end = src.indexOf('*/', i + 2);+ const body = src.slice(i, end < 0 ? src.length : end + 2);+ if (/i18n-ok/.test(body)) ok.add(line);+ for (const c of body) { if (c === '\n') { out += '\n'; line++; } else out += ' '; }+ i += body.length;+ continue;+ }+ if (ch === '/' && nx === '/') {+ const end = src.indexOf('\n', i);+ const body = src.slice(i, end < 0 ? src.length : end);+ if (/i18n-ok/.test(body)) ok.add(line);+ out += ' '.repeat(body.length);+ i += body.length;+ continue;+ }+ if (ch === '\n') line++;+ out += ch; i++;+ }+ return { code: out, ok };+}++function walk(d, out = []) {+ for (const e of fs.readdirSync(d, { withFileTypes: true })) {+ const p = path.join(d, e.name);+ if (e.isDirectory()) walk(p, out);+ else if (/\.[ch]$/.test(e.name)) out.push(p);+ }+ return out;+}++const loadKeys = (ns) => {+ try { return JSON.parse(fs.readFileSync(path.join(root, 'assets/locales/en', `${ns}.json`), 'utf8')); } catch (e) { return {}; }+};++// The C string literal starting at s[i] ('"'), with adjacent literals joined: [text, end].+function literal(s, i) {+ let text = '';+ for (;;) {+ if (s[i] !== '"') break;+ i++;+ while (i < s.length && s[i] !== '"') { if (s[i] === '\\') { text += s[i] + s[i + 1]; i += 2; } else text += s[i++]; }+ i++;+ const m = /^\s*/.exec(s.slice(i, i + 200));+ if (s[i + m[0].length] === '"') i += m[0].length; else break;+ }+ return [text, i];+}++export function checkErrors({ quiet = false } = {}) {+ const errors = loadKeys('errors'), status = loadKeys('status');+ const problems = [], warnings = [];+ const used = new Map(); // code → { ns, where }+ for (const file of walk(SRC)) {+ const rel = path.relative(SRC, file);+ if (rel === 'errcode.h' || rel === 'ui/js_err.h') continue; // documentation examples+ const pending = PENDING.some((p) => (p.endsWith('/') ? rel.startsWith(p) : rel === p));+ const { code: src, ok } = stripComments(fs.readFileSync(file, 'utf8'));+ const lineOf = (idx) => src.slice(0, idx).split('\n').length;+ const report = (idx, msg) => {+ const ln = lineOf(idx);+ if (ok.has(ln)) return;+ (pending ? warnings : problems).push(`server/src/${rel}:${ln}: ${msg}`);+ };+ const useCode = (idx, c, ns) => {+ if (!CODE.test(c)) { report(idx, `"${c}" is not a code (module.camelCase)`); return; }+ if (!used.has(c)) used.set(c, { ns, where: `server/src/${rel}:${lineOf(idx)}`, pending });+ };+ const scan = (re, fn) => { for (const m of src.matchAll(re)) fn(m); };++ // codes+ scan(/\badmin_(err|ok|log)\s*\(\s*(?=")/g, (m) => { const [c] = literal(src, m.index + m[0].length); useCode(m.index, c, m[1] === 'err' ? 'errors' : 'status'); });+ scan(/\badmin_code\s*\(\s*"(ERR|OK|LOG)"\s*,\s*(?=")/g, (m) => { const [c] = literal(src, m.index + m[0].length); useCode(m.index, c, m[1] === 'ERR' ? 'errors' : 'status'); });+ scan(/\blerr_set\s*\(\s*[^,;]+,\s*[^,;]+,\s*(?=")/g, (m) => { const [c] = literal(src, m.index + m[0].length); useCode(m.index, c, 'any'); });+ scan(/\bjs_throw_(?:code|line)\s*\(\s*\w+\s*,\s*(?=")/g, (m) => { const [c] = literal(src, m.index + m[0].length); useCode(m.index, c, 'errors'); });+ // put_line(id, "ERR", "…") (admin.c's own replies)+ scan(/\bput_line\s*\([^,;]+,\s*"ERR"\s*,\s*(?=")/g, (m) => {+ const [c] = literal(src, m.index + m[0].length);+ if (CODE.test(c)) useCode(m.index, c, 'errors'); else report(m.index, `prose in an ERR line: "${c}"`);+ });++ // prose in ERR/OK/LOG lines+ scan(/\badmin_say\s*\(\s*"(ERR|OK|LOG)"\s*,\s*(?=")/g, (m) => {+ const [t] = literal(src, m.index + m[0].length);+ if (t === '%s' && m[1] === 'LOG') return; // a program's output, as is+ report(m.index, `prose in an ${m[1]} line: "${t}" (use admin_${m[1] === 'ERR' ? 'err' : m[1].toLowerCase()} with a code)`);+ });+ // prose in JS exceptions+ scan(/\bJS_Throw(?:Type|Range|Internal|Syntax|Reference)?Error\s*\(\s*\w+\s*,\s*(?=")/g, (m) => {+ const [t] = literal(src, m.index + m[0].length);+ report(m.index, `JS exception with prose: "${t}" (use js_throw_code / js_throw_line)`);+ });+ // Spanish in any string literal+ for (let i = src.indexOf('"'); i >= 0; ) {+ if (src[i - 1] === "'" && src[i + 1] === "'") { i = src.indexOf('"', i + 1); continue; } // '"'+ const [t, end] = literal(src, i);+ if (SPANISH.test(t)) report(i, `Spanish text in a string: "${t.length > 70 ? `${t.slice(0, 70)}…` : t}"`);+ i = src.indexOf('"', Math.max(end, i + 1));+ }+ }+ for (const [c, { ns, where, pending }] of used) {+ const inErr = c in errors, inStatus = c in status;+ const okKey = ns === 'errors' ? inErr : ns === 'status' ? inStatus : inErr || inStatus;+ if (!okKey) (pending ? warnings : problems).push(`${where}: code ${c} has no English string in ${ns === 'any' ? 'errors.json or status.json' : `${ns}.json`}`);+ }+ if (!quiet) {+ for (const w of warnings) console.log(` (pending) ${w}`);+ for (const p of problems) console.log(`✗ ${p}`);+ console.log(`errors: ${used.size} codes in the server, ${problems.length} problems${warnings.length ? `, ${warnings.length} warnings in files still pending` : ''}`);+ }+ return { problems, warnings, used };+}++if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {+ process.exit(checkErrors().problems.length ? 1 : 0);+}diff --git a/tools/gen-monitor-data.py b/tools/gen-monitor-data.pyindex 4389ad8..b8ea214 100644--- a/tools/gen-monitor-data.py+++ b/tools/gen-monitor-data.py@@ -229,7 +229,7 @@ def build_mmdb(csv_path, out):tree = bytearray()for n in order:l, r = rec(L[n]), rec(R[n])- assert l < 1 << 24 and r < 1 << 24, 'hace falta record_size 28'+ assert l < 1 << 24 and r < 1 << 24, 'record_size 28 is needed'tree += l.to_bytes(3, 'big') + r.to_bytes(3, 'big')meta = mm_map(8)meta += mm_str('node_count') + mm_uint(node_count, 6)diff --git a/tools/i18n-check.mjs b/tools/i18n-check.mjsindex 9d1691b..a7308b2 100644--- a/tools/i18n-check.mjs+++ b/tools/i18n-check.mjs@@ -6,9 +6,12 @@// Reports: keys used in the code (t('namespace.key')) that are not in the reference// catalog (en), keys each language is missing or has in excess compared to en, and// {x} variables that do not match. Exits with code 1 if something is missing.+// With every language it also runs tools/err-check.mjs: error/status codes used by the server+// without an English string, and prose (or Spanish) in ERR lines and JS exceptions.import fs from 'node:fs';import path from 'node:path';import { fileURLToPath } from 'node:url';+import { checkErrors } from './err-check.mjs';const root = path.dirname(path.dirname(fileURLToPath(import.meta.url)));const dir = path.join(root, 'assets/locales');@@ -64,4 +67,5 @@ for (const id of langs) {for (const k of varDiff) console.log(` vars ${k}: ${vars(ref[k])} ≠ ${vars(cur[k])}`);bad += missing.length + varDiff.length;}+if (!process.argv[2]) bad += checkErrors().problems.length;process.exit(bad ? 1 : 0);diff --git a/tools/iso/build.sh b/tools/iso/build.shindex 144855a..3af9901 100755--- a/tools/iso/build.sh+++ b/tools/iso/build.sh@@ -115,7 +115,7 @@ en_US.UTF-8 UTF-8pt_BR.UTF-8 UTF-8EOFin_ch locale-gen > /dev/null-echo 'LANG=es_ES.UTF-8' > "$CH/etc/default/locale"+echo 'LANG=en_US.UTF-8' > "$CH/etc/default/locale" # English by default (lordos-live-prep switches it)ln -sf /usr/share/zoneinfo/UTC "$CH/etc/localtime"; echo UTC > "$CH/etc/timezone"# ping without root (in the live system the executable's cap_net_raw capability does not survive)@@ -158,7 +158,8 @@ cp "$CH/boot/initrd.img-$KVER" "$IMG/live/initrd.img"rm -f "$IMG/live/filesystem.squashfs"mksquashfs "$CH" "$IMG/live/filesystem.squashfs" -comp xz -Xbcj x86 -b 1M -noappend -quiet > /dev/null-# 5. grub (BIOS + UEFI in the same hybrid ISO)+# 5. grub (BIOS + UEFI in the same hybrid ISO). GRUB menus are English; the entries with a+# language name pass lordos.lang to lordos-live-prep (English is the default).cat > "$IMG/boot/grub/grub.cfg" <<EOFset default=0set timeout=5@@ -166,20 +167,24 @@ insmod all_videoinsmod gfxtermloadfont unicodeterminal_output gfxterm-menuentry "LordOS $VERSION (en vivo)" {- linux /live/vmlinuz boot=live components quiet loglevel=3 splash lordos.lang=es+menuentry "LordOS $VERSION (live)" {+ linux /live/vmlinuz boot=live components quiet loglevel=3 splash lordos.lang=eninitrd /live/initrd.img}-menuentry "LordOS $VERSION (modo seguro: sin GPU)" {- linux /live/vmlinuz boot=live components quiet loglevel=3 lordos.gpu=0 lordos.lang=es+menuentry "LordOS $VERSION (safe mode: no GPU)" {+ linux /live/vmlinuz boot=live components quiet loglevel=3 lordos.gpu=0 lordos.lang=eninitrd /live/initrd.img}-menuentry "LordOS $VERSION (English)" {- linux /live/vmlinuz boot=live components quiet loglevel=3 splash lordos.lang=en+menuentry "LordOS $VERSION (Español)" {+ linux /live/vmlinuz boot=live components quiet loglevel=3 splash lordos.lang=es+ initrd /live/initrd.img+}+menuentry "LordOS $VERSION (Português)" {+ linux /live/vmlinuz boot=live components quiet loglevel=3 splash lordos.lang=ptinitrd /live/initrd.img}-menuentry "LordOS $VERSION (copiar a la RAM: se puede sacar el USB)" {- linux /live/vmlinuz boot=live components quiet loglevel=3 splash toram lordos.lang=es+menuentry "LordOS $VERSION (copy to RAM: the USB drive can be removed)" {+ linux /live/vmlinuz boot=live components quiet loglevel=3 splash toram lordos.lang=eninitrd /live/initrd.img}EOFdiff --git a/tools/iso/mkdeb.sh b/tools/iso/mkdeb.shindex 0b430ab..0eeec51 100755--- a/tools/iso/mkdeb.sh+++ b/tools/iso/mkdeb.sh@@ -104,6 +104,7 @@ Files: third_party/quickjs/* third_party/stb/*License: MIT and public-domainQuickJS (MIT) and stb (public domain / MIT), compiled into lord-server.C+chmod 644 "$D/copyright"printf 'lordos (%s) trixie; urgency=medium\n\n * Package built by tools/iso/mkdeb.sh.\n\n -- LordOS <[email protected]> %s\n' \"$VERSION" "$(date -R)" | gzip -9n > "$D/changelog.gz"chmod 644 "$D/changelog.gz"@@ -128,7 +129,7 @@ Recommends: pipewire-pulse, wireplumber, wpasupplicant, openvpn, fonts-noto-coreSection: x11Priority: optionalHomepage: https://github.com/lordbasex/LordOS-Description: LordOS desktop environment (own display server)+Description: desktop environment with its own display serverLordOS is a desktop environment with its own display server in C (DRM/KMS,evdev, Wayland compositor) and the interface in React on its own engine.It includes the native apps, the themes, the login screen and the@@ -144,5 +145,8 @@ if [ "$1" = configure ] && command -v systemctl >/dev/null 2>&1; thenfiCchmod 755 "$PKG/DEBIAN/postinst"+# files under /etc are conffiles (lintian: file-in-etc-not-marked-as-conffile)+( cd "$PKG" && find etc -type f | sed 's|^|/|' ) > "$PKG/DEBIAN/conffiles"+chmod 644 "$PKG/DEBIAN/conffiles"dpkg-deb --root-owner-group --build "$PKG" "$OUT" >/dev/nullecho "$OUT ($(du -h "$OUT" | cut -f1))"diff --git a/tools/iso/rootfs/usr/lib/lordos/lordos-live-prep b/tools/iso/rootfs/usr/lib/lordos/lordos-live-prepindex 25349a9..755fe3d 100755--- a/tools/iso/rootfs/usr/lib/lordos/lordos-live-prep+++ b/tools/iso/rootfs/usr/lib/lordos/lordos-live-prep@@ -3,7 +3,7 @@# lordos.service). On an installed system it does nothing. See docs/ISO.md and docs/SESSIONS.md.## Options on the kernel command line (grub menu):-# lordos.lang=en interface language (es by default): /etc/default/locale and the live+# lordos.lang=es interface language (en by default; es and pt): /etc/default/locale and the live# user's settings the first time# lordos.gpu=0 safe mode: everything on the CPU. lord-sessiond reads it from /proc/cmdline and# passes LORD_GPU=0 to every session (nothing is needed here).@@ -12,17 +12,17 @@ set -uUSER_NAME=lordosgetent passwd "$USER_NAME" >/dev/null || exit 0-LANG_UI=es+LANG_UI=enfor arg in $(cat /proc/cmdline); docase "$arg" in- lordos.lang=en) LANG_UI=en ;;+ lordos.lang=es) LANG_UI=es ;;lordos.lang=pt) LANG_UI=pt ;;esacdonecase "$LANG_UI" in- en) LOC=en_US.UTF-8; DIRS="Desktop Documents Downloads Music Pictures Videos" ;;+ es) LOC=es_ES.UTF-8; DIRS="Escritorio Documentos Descargas Música Imágenes Videos" ;;pt) LOC=pt_BR.UTF-8; DIRS="Área_de_trabalho Documentos Downloads Música Imagens Vídeos" ;;- *) LOC=es_ES.UTF-8; DIRS="Escritorio Documentos Descargas Música Imágenes Videos" ;;+ *) LOC=en_US.UTF-8; DIRS="Desktop Documents Downloads Music Pictures Videos" ;;esacprintf 'LANG=%s\n' "$LOC" > /etc/default/locale # also the login screen language