Skip to content

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

Checkpoint: Settings sections (displays, Bluetooth, power, notifications, date/time, default apps), Passwords as isolated app, mail security fixes, firewall escape work, system apps, ISO packaging

Federico Pereirac3b44a9fc912
diff --git a/.gitignore b/.gitignore
index a84b132..0d616c8 100644
--- a/.gitignore
+++ b/.gitignore
@@ -13,3 +13,4 @@ assets/app-host.bundle.js
*.lpk
.vscode/
.idea/
+assets/sysapps/
diff --git a/apps/about/index.jsx b/apps/about/index.jsx
index 159fe23..b96f0f9 100644
--- a/apps/about/index.jsx
+++ b/apps/about/index.jsx
@@ -1,17 +1,21 @@
-// Acerca de LordOS — datos reales del sistema (/proc) y del servidor gráfico.
+// About LordOS: real system data (/proc) and display server stats.
import { version as reactVersion } from 'react';
-import { View, Text, LordOSLogo, screen, system, useTheme, useSystemInfo, useServerStats, formatBytes, formatDuration, formatNumber, t as tr } from '@lordos/sdk';
+import { View, Text, LordOSLogo, screen, system, useTheme, useSystemInfo, useServerStats, formatBytes, formatDuration, formatNumber, typeScale, t as tr } from '@lordos/sdk';
export function Icon({ size }) {
return <LordOSLogo size={size} />;
}
+// One line of the spec list, like macOS "About This Mac": the label in a trailing-aligned column
+// and the value at its side.
function InfoRow({ k, v }) {
const t = useTheme();
return (
- <View style={{ flexDirection: 'row', justifyContent: 'space-between', paddingVertical: 3, gap: 12 }}>
- <Text style={{ fontSize: 12, color: t.textDim }}>{k}</Text>
- <Text style={{ fontSize: 12, fontWeight: 500, color: t.text, whiteSpace: 'nowrap' }}>{v}</Text>
+ <View style={{ flexDirection: 'row', alignItems: 'center', minHeight: 20, gap: 10 }}>
+ <Text style={{ width: 118, fontSize: typeScale.callout, color: t.textDim, textAlign: 'end', whiteSpace: 'nowrap', overflow: 'hidden' }}>{k}</Text>
+ <View style={{ flex: 1, minWidth: 0, overflow: 'hidden' }}>
+ <Text style={{ fontSize: typeScale.callout, fontWeight: 500, color: t.text, whiteSpace: 'nowrap' }}>{v}</Text>
+ </View>
</View>
);
}
@@ -22,25 +26,26 @@ export default function About() {
const st = useServerStats(2000);
const cpu = info.cpu.replace(/\(R\)|\(TM\)|CPU|Processor/g, '').replace(/\s+/g, ' ').trim();
return (
- <View style={{ flex: 1, alignItems: 'center', paddingTop: 22 }}>
- <Icon size={76} />
- <Text style={{ fontSize: 24, fontWeight: 700, color: t.text, marginTop: 12 }}>LordOS</Text>
- <Text style={{ fontSize: 12, color: t.textDim, marginTop: 4 }}>{tr('about.version', { v: system.version, m: 'M7' })}</Text>
- <View style={{ width: 360, marginTop: 16 }}>
+ <View style={{ flex: 1, alignItems: 'center', paddingHorizontal: 20, paddingTop: 20, paddingBottom: 16 }}>
+ <Icon size={64} />
+ <Text style={{ fontSize: typeScale.largeTitle, fontWeight: 600, color: t.text, marginTop: 12 }}>LordOS</Text>
+ <Text style={{ fontSize: typeScale.callout, color: t.textDim, marginTop: 2 }}>{tr('about.version', { v: system.version, m: 'M7' })}</Text>
+ <View style={{ alignSelf: 'stretch', marginTop: 16, gap: 2 }}>
<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.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 }} />
+ <View style={{ height: 1, backgroundColor: t.separator, marginVertical: 8, marginHorizontal: 24 }} />
<InfoRow k={tr('about.server')} v="lord-server (C · DRM/KMS · evdev)" />
<InfoRow k={tr('about.engine')} v={`QuickJS + React ${reactVersion}`} />
<InfoRow k={tr('about.display')} v={`${screen.width} × ${screen.height}`} />
<InfoRow k={tr('about.ram')} v={`${formatNumber(st.rssKB / 1024, 1)} MB (JS ${formatNumber(st.jsKB / 1024, 1)} MB)`} />
<InfoRow k={tr('about.render')} v={tr('about.renderValue', { ms: formatNumber(st.layoutMs + st.paintMs, 1), count: st.nodes })} />
</View>
- <Text style={{ fontSize: 10, color: t.textDim, marginTop: 10, textAlign: 'center', lineHeight: 1.4 }}>{tr('about.credits')}</Text>
+ <View style={{ flex: 1, minHeight: 12 }} />
+ <Text style={{ fontSize: typeScale.caption, color: t.textDim, textAlign: 'center', lineHeight: 1.4, maxWidth: 360 }}>{tr('about.credits')}</Text>
</View>
);
}
diff --git a/apps/calendar/editor.jsx b/apps/calendar/editor.jsx
new file mode 100644
index 0000000..ef2609e
--- /dev/null
+++ b/apps/calendar/editor.jsx
@@ -0,0 +1,215 @@
+// editor.jsx — the event sheet (new event, details and editing) and the calendar sheet
+// (new calendar or edit name and color).
+import { View, Text, useTheme, Button, Toggle, TextInput, ScrollView, calendars, calendarEvents, t } from '@lordos/sdk';
+import { useRef, useState } from 'react';
+import {
+ RED, COLORS, sod, addDays, ymd, parseYmd, minutesOf, atMinutes, Sheet, Field, Choice, TextArea, DateField, TimeField, ColorSwatches,
+ Popover, MenuList,
+} from './ui.jsx';
+
+const ALERTS = [0, 5, 10, 15, 30, 60, 1440];
+const FREQS = ['DAILY', 'WEEKLY', 'MONTHLY', 'YEARLY'];
+
+// the first occurrence of a series (saving moves the whole series by the change made to this one)
+async function seriesStart(ev) {
+ try {
+ const list = await calendarEvents.range(0, ev.occ + 1, [ev.cal]);
+ const mine = list.filter((x) => x.uid === ev.uid && !x.rid).map((x) => x.start);
+ return mine.length ? Math.min(...mine) : ev.start;
+ } catch (e) { return ev.start; }
+}
+
+function draftOf(ev, cals) {
+ const allDay = !!ev.allDay;
+ const s = allDay ? parseYmd(ev.sdate) || sod(ev.start) : new Date(ev.start);
+ const eRaw = allDay ? parseYmd(ev.edate) || sod(ev.end) : new Date(ev.end);
+ const eDay = allDay ? addDays(eRaw, -1) : sod(eRaw);
+ return {
+ title: ev.title || '', loc: ev.loc || '', notes: ev.notes || '', allDay,
+ sDay: sod(s), sMin: allDay ? 9 * 60 : minutesOf(s), eDay: eDay < sod(s) ? sod(s) : eDay, eMin: allDay ? 10 * 60 : minutesOf(eRaw),
+ rrule: ev.rrule || '', alarm: ev.alarms && ev.alarms.length ? ev.alarms[0] : -1, cal: ev.cal || (cals[0] && cals[0].id) || '',
+ };
+}
+
+function psInfo(ps) {
+ const p = String(ps || '').toUpperCase();
+ if (p === 'ACCEPTED') return ['✓', '#34c759', t('calendar.ps.accepted')];
+ if (p === 'DECLINED') return ['✕', RED, t('calendar.ps.declined')];
+ if (p === 'TENTATIVE') return ['?', '#ff9500', t('calendar.ps.tentative')];
+ if (p === 'DELEGATED') return ['→', '#8e8e93', t('calendar.ps.delegated')];
+ return ['•', '#8e8e93', t('calendar.ps.pending')];
+}
+
+export function EventSheet({ ev, isNew, cals, onClose }) {
+ const th = useTheme();
+ const [d, setD] = useState(() => draftOf(ev, cals));
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState('');
+ const [askDelete, setAskDelete] = useState(false);
+ const delRef = useRef(null);
+ const set = (patch) => setD((x) => ({ ...x, ...patch }));
+ const recurring = !isNew && !!ev.rrule && !!ev.occ;
+
+ // moving the start keeps the duration
+ const setStartDay = (day) => setD((x) => ({ ...x, sDay: sod(day), eDay: addDays(sod(day), Math.round((x.eDay - x.sDay) / 86400000)) }));
+ const setStartMin = (m) => setD((x) => {
+ const sameDayEvent = +x.eDay === +x.sDay;
+ let eMin = x.eMin + (m - x.sMin);
+ if (!sameDayEvent || eMin >= 1440 || eMin <= m) eMin = sameDayEvent ? Math.min(1439, m + 60) : x.eMin;
+ return { ...x, sMin: m, eMin };
+ });
+
+ const save = async () => {
+ if (busy) return;
+ setBusy(true);
+ setError('');
+ try {
+ let start, end;
+ if (d.allDay) {
+ start = sod(d.sDay).getTime();
+ end = addDays(d.eDay < d.sDay ? d.sDay : d.eDay, 1).getTime();
+ } else {
+ start = atMinutes(d.sDay, d.sMin).getTime();
+ end = atMinutes(d.eDay < d.sDay ? d.sDay : d.eDay, d.eMin).getTime();
+ if (end <= start) end = start + 3600000;
+ }
+ if (recurring) {
+ const first = await seriesStart(ev);
+ const len = end - start;
+ start = first + (start - ev.start);
+ end = start + len;
+ }
+ let cal = d.cal;
+ if (!cal) cal = (await calendars.create({ name: t('calendar.defaultName'), color: '#007aff', events: true, todos: false })).uid;
+ const rest = (ev.alarms || []).slice(1);
+ const event = {
+ title: d.title.trim(), loc: d.loc.trim(), notes: d.notes, allDay: d.allDay, start, end, rrule: d.rrule,
+ alarms: d.alarm >= 0 ? [d.alarm, ...rest] : [],
+ };
+ if (!isNew) event.uid = ev.uid;
+ if (ev.url) event.url = ev.url;
+ if (ev.status) event.status = ev.status;
+ if (!d.allDay && ev.tz) event.tz = ev.tz;
+ if (d.allDay) { event.sdate = ymd(new Date(start)); event.edate = ymd(new Date(end)); }
+ if (ev.att && ev.att.length) {
+ event.att = ev.att;
+ if (ev.org) { event.orgEmail = ev.org.email; event.orgName = ev.org.name; }
+ }
+ await calendarEvents.save(cal, event, !isNew && ev.cal && ev.cal !== cal ? { from: ev.cal } : {});
+ onClose();
+ } catch (e) {
+ setError(t('calendar.saveFailed'));
+ setBusy(false);
+ }
+ };
+
+ const remove = async (opts) => {
+ try { await calendarEvents.remove(ev.cal, ev.uid, opts); onClose(); } catch (e) { setError(t('calendar.deleteFailed')); }
+ };
+
+ const freq = (/FREQ=(\w+)/.exec(d.rrule) || [])[1] || '';
+ const custom = d.rrule && d.rrule !== `FREQ=${freq}`;
+ const repeatOpts = [['', t('calendar.repeat.none')], ...FREQS.map((f) => [`FREQ=${f}`, t(`calendar.repeat.${f.toLowerCase()}`)])];
+ if (custom) repeatOpts.push([d.rrule, t('calendar.repeat.custom')]);
+ const alertOpts = [[-1, t('calendar.alert.none')], ...ALERTS.map((m) => [m, m === 0 ? t('calendar.alert.atTime')
+ : m === 1440 ? t('calendar.alert.dayBefore') : m === 60 ? t('calendar.alert.hourBefore') : t('calendar.alert.minutes', { count: m })])];
+ if (d.alarm >= 0 && !ALERTS.includes(d.alarm)) alertOpts.push([d.alarm, t('calendar.alert.minutes', { count: d.alarm })]);
+ const calOpts = cals.map((c) => [c.id, c.name, c.color]);
+ const att = ev.att || [];
+
+ return (
+ <Sheet width={500} title={isNew ? t('calendar.newEvent') : null} footer={[
+ !isNew ? (
+ <View key="del" ref={delRef}>
+ <Button destructive label={t('calendar.delete')} onClick={() => (recurring ? setAskDelete(true) : remove({}))} />
+ {askDelete && (
+ <Popover anchor={delRef} width={240} onClose={() => setAskDelete(false)}>
+ <MenuList onDone={() => setAskDelete(false)} items={[
+ { label: t('calendar.deleteThis'), destructive: true, onClick: () => remove({ occ: ev.occ }) },
+ { label: t('calendar.deleteAll'), destructive: true, onClick: () => remove({ all: true }) },
+ ]} />
+ </Popover>
+ )}
+ </View>
+ ) : null,
+ <Text key="err" style={{ flex: 1, fontSize: 12, color: RED }}>{error}</Text>,
+ <Button key="c" label={t('calendar.cancel')} onClick={onClose} />,
+ <Button key="s" primary disabled={busy} label={isNew ? t('calendar.add') : t('calendar.save')} onClick={save} />,
+ ]}>
+ <TextInput value={d.title} onChange={(v) => set({ title: v })} placeholder={t('calendar.titlePlaceholder')} size={15} autoFocus={isNew} onSubmit={save} />
+ <TextInput value={d.loc} onChange={(v) => set({ loc: v })} placeholder={t('calendar.locationPlaceholder')} onSubmit={save} />
+ <View style={{ gap: 8, marginTop: 4 }}>
+ <Field label={t('calendar.allDay')}><Toggle on={d.allDay} onChange={(v) => set({ allDay: v })} /></Field>
+ <Field label={t('calendar.starts')}>
+ <DateField value={d.sDay} onChange={setStartDay} />
+ {!d.allDay ? <TimeField value={d.sMin} onChange={setStartMin} /> : null}
+ </Field>
+ <Field label={t('calendar.ends')}>
+ <DateField value={d.eDay} onChange={(v) => set({ eDay: sod(v) < d.sDay ? d.sDay : sod(v) })} />
+ {!d.allDay ? <TimeField value={d.eMin} onChange={(v) => set({ eMin: v })} /> : null}
+ </Field>
+ <Field label={t('calendar.repeat')}><Choice width={200} value={custom ? d.rrule : freq ? `FREQ=${freq}` : ''} options={repeatOpts} onChange={(v) => set({ rrule: v })} /></Field>
+ <Field label={t('calendar.alert')}><Choice width={200} value={d.alarm} options={alertOpts} onChange={(v) => set({ alarm: v })} /></Field>
+ <Field label={t('calendar.calendar')}>
+ {calOpts.length ? <Choice width={200} value={d.cal} options={calOpts} onChange={(v) => set({ cal: v })} />
+ : <Text style={{ fontSize: 12, color: th.textDim }}>{t('calendar.defaultName')}</Text>}
+ </Field>
+ {recurring ? <Field label=""><Text style={{ fontSize: 11, color: th.textDim }}>{t('calendar.seriesNote')}</Text></Field> : null}
+ </View>
+ {ev.org || att.length ? (
+ <View style={{ gap: 4 }}>
+ <Text style={{ fontSize: 11, fontWeight: 600, color: th.textDim }}>{t('calendar.invitees', { count: att.length })}</Text>
+ <View style={{ maxHeight: 110 }}>
+ <ScrollView style={{ flex: 1 }}>
+ {ev.org ? <Person name={ev.org.name || ev.org.email} detail={t('calendar.organizer')} glyph="★" color="#8e8e93" /> : null}
+ {att.map((a) => { const [g, c, label] = psInfo(a.ps); return <Person key={a.email} name={a.name || a.email} detail={label} glyph={g} color={c} />; })}
+ </ScrollView>
+ </View>
+ </View>
+ ) : null}
+ <TextArea value={d.notes} onChange={(v) => set({ notes: v })} placeholder={t('calendar.notesPlaceholder')} minHeight={60} />
+ </Sheet>
+ );
+}
+
+function Person({ name, detail, glyph, color }) {
+ const th = useTheme();
+ return (
+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 8, height: 22 }}>
+ <View style={{ width: 16, height: 16, borderRadius: 8, alignItems: 'center', justifyContent: 'center', backgroundColor: color }}>
+ <Text style={{ fontSize: 9, fontWeight: 700, color: '#fff' }}>{glyph}</Text>
+ </View>
+ <Text style={{ flex: 1, fontSize: 12, color: th.text, whiteSpace: 'nowrap', overflow: 'hidden' }}>{name}</Text>
+ <Text style={{ fontSize: 11, color: th.textDim }}>{detail}</Text>
+ </View>
+ );
+}
+
+// ---- new calendar / edit calendar ----
+
+export function CalendarSheet({ cal, onClose }) {
+ const [name, setName] = useState(cal ? cal.name : '');
+ const [color, setColor] = useState(cal ? cal.color : COLORS[5]);
+ const [error, setError] = useState('');
+ const th = useTheme();
+ const save = async () => {
+ if (!name.trim()) return;
+ try {
+ if (cal) await calendars.update(cal.id, { name: name.trim(), color });
+ else await calendars.create({ name: name.trim(), color, events: true, todos: false });
+ onClose();
+ } catch (e) { setError(t('calendar.saveFailed')); }
+ };
+ return (
+ <Sheet width={380} title={cal ? t('calendar.editCalendar') : t('calendar.newCalendar')} footer={[
+ <Text key="e" style={{ flex: 1, fontSize: 12, color: RED }}>{error}</Text>,
+ <Button key="c" label={t('calendar.cancel')} onClick={onClose} />,
+ <Button key="s" primary disabled={!name.trim()} label={cal ? t('calendar.save') : t('calendar.create')} onClick={save} />,
+ ]}>
+ <TextInput value={name} onChange={setName} placeholder={t('calendar.calendarName')} autoFocus onSubmit={save} onCancel={onClose} />
+ <Text style={{ fontSize: 11, fontWeight: 600, color: th.textDim }}>{t('calendar.color')}</Text>
+ <ColorSwatches value={color} onChange={setColor} />
+ </Sheet>
+ );
+}
+
diff --git a/apps/calendar/index.jsx b/apps/calendar/index.jsx
new file mode 100644
index 0000000..0d90b4f
--- /dev/null
+++ b/apps/calendar/index.jsx
@@ -0,0 +1,450 @@
+// Calendar — day, week and month views of the calendars kept by lord-maild (local, or synced with
+// CalDAV): see docs/MAIL.md. Data comes from the SDK (calendars, calendarEvents); every call is a
+// 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,
+} from '@lordos/sdk';
+import { useEffect, useMemo, useRef, useState } from 'react';
+import {
+ RED, sod, addDays, addMonths, sameDay, startOfWeek, ymd, parseYmd, minutesOf, monthYear, MiniMonth, ColorCheck, Layers, Popover, MenuList,
+ useLoad, useNow,
+} from './ui.jsx';
+import { EventSheet, CalendarSheet } from './editor.jsx';
+
+// ---- icon: a page with a red header strip and today's day number ----
+
+export function Icon({ size: s }) {
+ const day = new Date().getDate();
+ return (
+ <View style={{ width: s, height: s, borderRadius: s * 0.225, backgroundColor: '#ffffff', overflow: 'hidden',
+ boxShadow: `0 ${s * 0.04}px ${s * 0.12}px rgba(0,0,0,0.35)`, border: '1px solid rgba(0,0,0,0.08)' }}>
+ <View style={{ height: s * 0.27, backgroundColor: '#f2463d', alignItems: 'center', justifyContent: 'center' }}>
+ <View style={{ flexDirection: 'row', gap: s * 0.05 }}>
+ {[0, 1, 2].map((i) => <View key={i} style={{ width: s * 0.07, height: s * 0.07, borderRadius: s * 0.035, backgroundColor: 'rgba(255,255,255,0.85)' }} />)}
+ </View>
+ </View>
+ <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
+ <Text style={{ fontSize: s * 0.46, fontWeight: 300, color: '#1c1c1e' }}>{String(day)}</Text>
+ </View>
+ </View>
+ );
+}
+
+const HOUR = 48; // px per hour in the day and week grids
+const GUTTER = 56;
+
+// days an event covers (all-day: sdate..edate exclusive; timed: every day it touches)
+function eventDays(ev) {
+ if (ev.allDay) {
+ const s = parseYmd(ev.sdate) || sod(ev.start), e = parseYmd(ev.edate) || sod(ev.end);
+ const out = [];
+ for (let d = s; d < e || out.length === 0; d = addDays(d, 1)) { out.push(d); if (out.length > 366) break; }
+ return out;
+ }
+ const out = [];
+ const last = new Date(Math.max(ev.start, ev.end - 1));
+ for (let d = sod(ev.start); d <= last; d = addDays(d, 1)) { out.push(d); if (out.length > 366) break; }
+ return out;
+}
+
+// index events by 'YYYY-MM-DD'
+function byDay(events) {
+ const m = new Map();
+ for (const ev of events) for (const d of eventDays(ev)) { const k = ymd(d); if (!m.has(k)) m.set(k, []); m.get(k).push(ev); }
+ for (const l of m.values()) l.sort((a, b) => (b.allDay - a.allDay) || a.start - b.start || String(a.title).localeCompare(String(b.title)));
+ return m;
+}
+
+// overlapping timed segments of one day go side by side: [{ ev, top, bottom, col, cols }]
+function layoutDay(day, events) {
+ const d0 = sod(day).getTime(), d1 = addDays(day, 1).getTime();
+ const segs = events.filter((e) => !e.allDay).map((ev) => {
+ const s = Math.max(ev.start, d0), e = Math.min(Math.max(ev.end, ev.start + 15 * 60000), d1);
+ return { ev, top: (s - d0) / 60000, bottom: (e - d0) / 60000 };
+ }).sort((a, b) => a.top - b.top || b.bottom - a.bottom);
+ let group = [], colsEnd = [], groupEnd = -1;
+ const flush = () => { for (const g of group) g.cols = colsEnd.length; group = []; colsEnd = []; };
+ for (const s of segs) {
+ if (s.top >= groupEnd) { flush(); groupEnd = -1; }
+ let c = colsEnd.findIndex((end) => end <= s.top);
+ if (c < 0) { c = colsEnd.length; colsEnd.push(0); }
+ colsEnd[c] = Math.max(s.bottom, s.top + 20);
+ s.col = c;
+ group.push(s);
+ groupEnd = Math.max(groupEnd, colsEnd[c]);
+ }
+ flush();
+ return segs;
+}
+
+const tint = (c, a) => (/^#[0-9a-f]{6}$/i.test(c || '') ? `${c}${a}` : `rgba(0,122,255,0.2)`);
+const colorOf = (ev, cals) => ev.color || cals?.find((c) => c.id === ev.cal)?.color || '#007aff';
+
+// ---- the app ----
+
+export default function CalendarApp() {
+ const th = useTheme();
+ useLocale();
+ const rev = usePim();
+ const win = useAppWindow();
+ const [view, setView] = useWindowState('view', 'week');
+ const [cursorMs, setCursor] = useWindowState('cursor', () => sod(new Date()).getTime());
+ const [sidebar, setSidebar] = useWindowState('sidebar', true);
+ const [sheet, setSheet] = useState(null); // { ev, isNew } | { cal } | { newCal: true }
+ const now = useNow(30000);
+ const cursor = new Date(cursorMs);
+ const rangeFrom = view === 'day' ? sod(cursor) : view === 'week' ? startOfWeek(cursor) : startOfWeek(new Date(cursor.getFullYear(), cursor.getMonth(), 1));
+ const rangeTo = addDays(rangeFrom, view === 'day' ? 1 : view === 'week' ? 7 : 42);
+ const calsQ = useLoad(() => calendars.list(), [rev]);
+ const evQ = useLoad(() => calendarEvents.range(rangeFrom.getTime(), rangeTo.getTime()), [rev, rangeFrom.getTime(), rangeTo.getTime()]);
+ const cals = calsQ.data || [];
+ const eventCals = cals.filter((c) => c.events);
+ const events = evQ.data || [];
+ const days = useMemo(() => byDay(events), [events]);
+
+ // window args from an alarm's "Open": { at, uid, cal, nonce }
+ const pending = useRef(null);
+ useEffect(() => {
+ const a = win.args;
+ if (!a || !a.at) return;
+ setCursor(sod(a.at).getTime());
+ if (view === 'month') setView('day');
+ pending.current = a;
+ }, [win.args?.nonce, win.args?.at]);
+ useEffect(() => {
+ const p = pending.current;
+ if (!p || !p.uid || !evQ.data) return;
+ const ev = events.find((e) => e.uid === p.uid && (!p.cal || e.cal === p.cal) && (e.start === p.at || !e.occ));
+ if (ev) { pending.current = null; setSheet({ ev }); }
+ }, [evQ.data]);
+
+ const go = (dir) => {
+ if (view === 'day') setCursor(addDays(cursor, dir).getTime());
+ else if (view === 'week') setCursor(addDays(cursor, dir * 7).getTime());
+ else setCursor(addMonths(cursor, dir).getTime());
+ };
+ const today = () => setCursor(sod(new Date()).getTime());
+ const defaultCal = () => eventCals.find((c) => !c.hidden) || eventCals[0];
+ const newEvent = (day, min = null) => {
+ const base = min == null ? (() => { const n = new Date(); return Math.min(23 * 60, (n.getHours() + 1) * 60); })() : min;
+ const start = sod(day);
+ start.setHours(Math.floor(base / 60), base % 60, 0, 0);
+ const cal = defaultCal();
+ setSheet({ isNew: true, ev: { title: '', start: start.getTime(), end: start.getTime() + 3600000, allDay: false, alarms: [], cal: cal ? cal.id : '' } });
+ };
+
+ useKeyboard((e) => {
+ if (sheet) { if (e.key === 'Escape') setSheet(null); return; }
+ const k = String(e.base || e.key || '').toLowerCase();
+ const rtl = direction() === 'rtl';
+ if ((e.meta || e.ctrl) && k === 't') today();
+ else if ((e.meta || e.ctrl) && k === 'n') newEvent(cursor);
+ else if ((e.meta || e.ctrl) && k === '1') setView('day');
+ else if ((e.meta || e.ctrl) && k === '2') setView('week');
+ else if ((e.meta || e.ctrl) && k === '3') setView('month');
+ else if (e.key === 'ArrowLeft' && !e.meta) go(rtl ? 1 : -1);
+ else if (e.key === 'ArrowRight' && !e.meta) go(rtl ? -1 : 1);
+ });
+
+ const unavailable = calsQ.error && !calsQ.data;
+ let title;
+ if (view === 'day') title = formatDate(cursor, 'long');
+ else if (view === 'week') title = monthYear(addDays(startOfWeek(cursor), 3));
+ else title = monthYear(cursor);
+ const rtl = direction() === 'rtl';
+
+ return (
+ <View style={{ flex: 1, flexDirection: 'row', backgroundColor: th.windowBg }}>
+ {sidebar && (
+ <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>
+ <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)} />
+ </Toolbar>
+ {unavailable ? (
+ <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'); }} />
+ ) : (
+ <TimeGrid key={view} dates={view === 'day' ? [sod(cursor)] : [0, 1, 2, 3, 4, 5, 6].map((i) => addDays(startOfWeek(cursor), i))}
+ days={days} cals={cals} now={now} onOpen={(ev) => setSheet({ ev })} onSlot={newEvent}
+ onDay={(d) => { setCursor(sod(d).getTime()); setView('day'); }} />
+ )}
+ </View>
+ {sheet && sheet.ev ? <EventSheet ev={sheet.ev} isNew={sheet.isNew} cals={eventCals} onClose={() => setSheet(null)} /> : null}
+ {sheet && (sheet.newCal || sheet.cal) ? <CalendarSheet cal={sheet.cal} onClose={() => setSheet(null)} /> : null}
+ <Layers />
+ </View>
+ );
+}
+
+// ---- sidebar: calendars by account, and a month to jump around ----
+
+function Sidebar({ cals, cursor, days, onPick, onNew, onEdit }) {
+ const th = useTheme();
+ const groups = [];
+ for (const c of cals) {
+ const key = c.acct || '';
+ let g = groups.find((x) => x.key === key);
+ if (!g) { g = { key, name: key ? c.acctName || key : t('calendar.onThisComputer'), list: [] }; groups.push(g); }
+ g.list.push(c);
+ }
+ groups.sort((a, b) => (a.key === '' ? -1 : b.key === '' ? 1 : a.name.localeCompare(b.name)));
+ const marks = useMemo(() => new Set(days.keys()), [days]);
+ return (
+ <View style={{ width: 216, backgroundColor: th.sidebarBg }}>
+ <Hairline edge="end" />
+ <ScrollView style={{ flex: 1 }}>
+ <View style={{ padding: 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>
+ {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' }}>
+ <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>
+ );
+}
+
+function CalRow({ cal, onEdit }) {
+ const th = useTheme();
+ const ref = useRef(null);
+ const [menu, setMenu] = useState(false);
+ const [hover, setHover] = useState(false);
+ 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' }}>
+ <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 && (
+ <Popover anchor={ref} width={200} onClose={() => setMenu(false)}>
+ <MenuList onDone={() => setMenu(false)} items={[
+ { label: t('calendar.editCalendar'), onClick: () => onEdit(cal) },
+ { label: cal.hidden ? t('calendar.show') : t('calendar.hide'), onClick: toggle },
+ '-',
+ { label: t('calendar.deleteCalendar'), destructive: true, disabled: cal.kind !== 'local', onClick: () => calendars.remove(cal.id).catch(() => {}) },
+ ]} />
+ </Popover>
+ )}
+ </View>
+ );
+}
+
+// ---- day and week: the hour grid ----
+
+function useWidth(ref, initial = 100) {
+ 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 TimeGrid({ dates, days, cals, now, onOpen, onSlot, onDay }) {
+ const th = useTheme();
+ const scroll = useRef(null);
+ const colRef = useRef(null);
+ 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); }, []);
+ 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;
+ return (
+ <View style={{ flex: 1 }}>
+ {/* day headers */}
+ <View style={{ flexDirection: 'row', height: single ? 30 : 40 }}>
+ <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 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>
+ </View>
+ </View>
+ );
+ })}
+ </View>
+ {/* all-day row */}
+ <View style={{ flexDirection: 'row', minHeight: 24, maxHeight: 24 + 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>
+ {dates.map((d, i) => (
+ <View key={ymd(d)} onClick={() => onSlot(d, null)} style={{ flex: 1, padding: 2, gap: 2, overflow: 'hidden' }}>
+ {sep('s')}
+ {allDay[i].slice(0, 4).map((ev) => <AllDayChip key={`${ev.cal}${ev.uid}${ev.start}`} ev={ev} color={colorOf(ev, cals)} onOpen={onOpen} />)}
+ {allDay[i].length > 4 ? <Text style={{ fontSize: 10, color: th.textDim, marginHorizontal: 4 }}>{t('calendar.more', { count: allDay[i].length - 4 })}</Text> : null}
+ </View>
+ ))}
+ </View>
+ {/* hours */}
+ <ScrollView scrollRef={scroll} style={{ flex: 1 }}>
+ <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' }}>
+ {formatTime(new Date(2000, 0, 3, h, 0))}
+ </Text>
+ ))}
+ </View>
+ <View style={{ flex: 1, flexDirection: 'row' }}>
+ <View style={{ position: 'absolute', left: 0, right: 0, top: 0, bottom: 0, pointerEvents: 'none' }}>
+ {Array.from({ length: 24 }, (_, h) => (
+ <View key={h} style={{ position: 'absolute', left: 0, right: 0, top: h * HOUR, height: 1, backgroundColor: th.separator }} />
+ ))}
+ </View>
+ {dates.map((d, i) => {
+ const segs = layoutDay(d, days.get(ymd(d)) || []);
+ const today = sameDay(d, nowD);
+ return (
+ <View key={ymd(d)} ref={i === 0 ? colRef : undefined} style={{ flex: 1 }}
+ onClick={(e) => { const y = e.local(e.currentTarget).y; onSlot(d, Math.max(0, Math.min(23 * 60 + 30, Math.floor(y / (HOUR / 2)) * 30))); }}>
+ {sep('s')}
+ {segs.map((s) => {
+ const w = (colW - 4) / s.cols;
+ const left = rtl ? colW - 2 - (s.col + 1) * w : 2 + s.col * w;
+ return <EventBlock key={`${s.ev.cal}${s.ev.uid}${s.ev.start}`} seg={s} left={left} width={w - 1} color={colorOf(s.ev, cals)} onOpen={onOpen} />;
+ })}
+ {today ? (
+ <View style={{ position: 'absolute', left: 0, right: 0, top: (minutesOf(nowD) * HOUR) / 60 - 1, height: 2, backgroundColor: RED, pointerEvents: 'none' }}>
+ <View style={{ position: 'absolute', [rtl ? 'right' : 'left']: -4, top: -3, width: 8, height: 8, borderRadius: 4, backgroundColor: RED }} />
+ </View>
+ ) : null}
+ </View>
+ );
+ })}
+ </View>
+ </View>
+ </ScrollView>
+ </View>
+ );
+}
+
+function EventBlock({ seg, left, width, color, onOpen }) {
+ const th = useTheme();
+ const ev = seg.ev;
+ const h = Math.max(18, ((seg.bottom - seg.top) * HOUR) / 60 - 2);
+ const rtl = direction() === 'rtl';
+ const dark = th.mode === 'dark';
+ return (
+ <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 }}>
+ <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' }}>
+ {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}
+ </View>
+ );
+}
+
+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>
+ </View>
+ );
+}
+
+// ---- month: 6 × 7 days ----
+
+function MonthGrid({ cursor, days, cals, now, onOpen, onSlot, onDay }) {
+ const th = useTheme();
+ const box = useRef(null);
+ const [cellH, setCellH] = useState(90);
+ useEffect(() => {
+ const id = setTimeout(() => { if (box.current) { const h = lord.getLayout(box.current.id)[3] / 6; if (h && Math.abs(h - cellH) > 0.5) setCellH(h); } }, 20);
+ return () => clearTimeout(id);
+ });
+ const nowD = new Date(now);
+ const first = startOfWeek(new Date(cursor.getFullYear(), cursor.getMonth(), 1));
+ const fit = Math.max(1, Math.floor((cellH - 28) / 18));
+ const rtl = direction() === 'rtl';
+ const rows = [];
+ for (let r = 0; r < 6; r++) {
+ const cells = [];
+ for (let c = 0; c < 7; c++) {
+ const d = addDays(first, r * 7 + c);
+ const list = days.get(ymd(d)) || [];
+ const today = sameDay(d, nowD), inMonth = d.getMonth() === cursor.getMonth();
+ const shown = list.length > fit ? list.slice(0, fit - 1) : list;
+ cells.push(
+ <View key={c} onClick={() => onSlot(d)} style={{ flex: 1, padding: 3, gap: 2, overflow: 'hidden',
+ backgroundColor: inMonth ? 'transparent' : th.mode === 'dark' ? 'rgba(255,255,255,0.02)' : 'rgba(0,0,0,0.025)' }}>
+ <Hairline edge="top" />
+ {c > 0 ? <View style={{ position: 'absolute', top: 0, bottom: 0, [rtl ? 'right' : 'left']: 0, width: 1, backgroundColor: th.separator }} /> : null}
+ <View style={{ flexDirection: 'row', justifyContent: 'flex-end' }}>
+ <View onClick={(e) => { e.stopPropagation(); onDay(d); }} style={{ minWidth: 22, height: 22, paddingHorizontal: 4, borderRadius: 11, alignItems: 'center', justifyContent: 'center',
+ backgroundColor: today ? RED : 'transparent' }}>
+ <Text style={{ fontSize: 12, fontWeight: today ? 700 : 500, color: today ? '#fff' : inMonth ? th.text : th.textDim }}>
+ {String(d.getDate())}
+ </Text>
+ </View>
+ </View>
+ {shown.map((ev) => <MonthChip key={`${ev.cal}${ev.uid}${ev.start}`} ev={ev} color={colorOf(ev, cals)} onOpen={onOpen} />)}
+ {list.length > shown.length ? (
+ <Text onClick={(e) => { e.stopPropagation(); onDay(d); }} style={{ fontSize: 10, fontWeight: 600, color: th.textDim, marginHorizontal: 4 }}>
+ {t('calendar.more', { count: list.length - shown.length })}
+ </Text>
+ ) : null}
+ </View>,
+ );
+ }
+ rows.push(<View key={r} style={{ flex: 1, flexDirection: 'row' }}>{cells}</View>);
+ }
+ return (
+ <View style={{ flex: 1 }}>
+ <View style={{ flexDirection: 'row', height: 26, alignItems: 'center' }}>
+ {[1, 2, 3, 4, 5, 6, 0].map((wd) => (
+ <Text key={wd} style={{ flex: 1, fontSize: 11, fontWeight: 600, color: th.textDim, textAlign: 'end', paddingHorizontal: 8 }}>{weekdayName(wd)}</Text>
+ ))}
+ </View>
+ <View ref={box} style={{ flex: 1 }}>{rows}</View>
+ </View>
+ );
+}
+
+function MonthChip({ ev, color, onOpen }) {
+ const th = useTheme();
+ if (ev.allDay) return <AllDayChip ev={ev} color={color} onOpen={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={{ fontSize: 10, color: th.textDim, whiteSpace: 'nowrap' }}>{formatTime(new Date(ev.start))}</Text>
+ </View>
+ );
+}
+
diff --git a/apps/calendar/manifest.json b/apps/calendar/manifest.json
new file mode 100644
index 0000000..28edbe1
--- /dev/null
+++ b/apps/calendar/manifest.json
@@ -0,0 +1,10 @@
+{
+ "id": "calendar",
+ "name": "Calendar",
+ "description": "Day, week and month views of your local and synced calendars",
+ "size": [980, 640],
+ "minSize": [640, 440],
+ "dock": true,
+ "category": "Office",
+ "permissions": []
+}
diff --git a/apps/calendar/ui.jsx b/apps/calendar/ui.jsx
new file mode 100644
index 0000000..bb79c41
--- /dev/null
+++ b/apps/calendar/ui.jsx
@@ -0,0 +1,354 @@
+// ui.jsx — small widgets shared by Calendar, Contacts and Reminders (each app keeps its own copy,
+// since apps only import from '@lordos/sdk'): popovers drawn above the window, sheets, drop-down
+// choices, a multi-line field, date and time fields with a month picker, and color swatches.
+import {
+ View, Text, useTheme, useStore, createStore, useAppWindow, direction, ScrollView, Button, Hairline, takeTextFocus, releaseTextFocus,
+ weekdayName, formatTime, formatDate, t,
+} from '@lordos/sdk';
+import { useEffect, useRef, useState } from 'react';
+
+export const RED = '#ff3b30';
+export const COLORS = ['#ff3b30', '#ff9500', '#ffcc00', '#34c759', '#30b0c7', '#007aff', '#af52de', '#a2845e'];
+const pad = (n) => String(n).padStart(2, '0');
+
+// ---- dates ----
+
+export const DAY = 86400000;
+export const sod = (d) => { const x = new Date(d); x.setHours(0, 0, 0, 0); return x; };
+export const addDays = (d, n) => { const x = new Date(d); x.setDate(x.getDate() + n); return x; };
+export const addMonths = (d, n) => new Date(d.getFullYear(), d.getMonth() + n, 1);
+export const sameDay = (a, b) => a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();
+export const startOfWeek = (d) => { const x = sod(d); return addDays(x, -((x.getDay() + 6) % 7)); }; // weeks start on Monday
+export const ymd = (d) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
+export const parseYmd = (s) => { const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(s || ''); return m ? new Date(+m[1], +m[2] - 1, +m[3]) : null; };
+export const minutesOf = (d) => d.getHours() * 60 + d.getMinutes();
+export const atMinutes = (day, min) => { const x = sod(day); x.setHours(Math.floor(min / 60), min % 60, 0, 0); return x; };
+export const monthName = (m) => t(`calendar.month.${m}`);
+export const monthYear = (d) => t('calendar.monthYear', { month: monthName(d.getMonth()), year: d.getFullYear() });
+
+// ---- popovers: drawn by <Layers /> (the last child of the app) above everything ----
+
+const layers = createStore([]); // [{ key, win, node }]
+let seq = 0;
+
+export function Popover(props) {
+ const { id: win } = useAppWindow();
+ const key = useRef(null);
+ if (!key.current) key.current = `p${++seq}`;
+ useEffect(() => {
+ const node = <PopBox {...props} />;
+ layers.set((l) => (l.some((x) => x.key === key.current) ? l.map((x) => (x.key === key.current ? { ...x, node } : x)) : [...l, { key: key.current, win, node }]));
+ });
+ useEffect(() => () => layers.set((l) => l.filter((x) => x.key !== key.current)), []);
+ return null;
+}
+
+let origin = null; // the Layers box: [x, y, w, h]
+
+export function Layers() {
+ const { id } = useAppWindow();
+ const all = useStore(layers);
+ const root = useRef(null);
+ const mine = all.filter((x) => x.win === id);
+ if (root.current) { try { origin = lord.getLayout(root.current.id); } catch (e) { /* not laid out yet */ } }
+ return (
+ <>
+ <View ref={root} style={{ position: 'absolute', left: 0, top: 0, right: 0, bottom: 0, pointerEvents: 'none' }} />
+ {mine.map((x) => <View key={x.key} style={{ position: 'absolute', left: 0, top: 0, right: 0, bottom: 0, zIndex: 200 }}>{x.node}</View>)}
+ </>
+ );
+}
+
+function PopBox({ anchor, onClose, width = 240, children, padding = 6 }) {
+ const th = useTheme();
+ const box = useRef(null);
+ const [flip, setFlip] = useState(false);
+ const [, force] = useState(0);
+ const o = origin || [0, 0, 800, 600];
+ let a = null;
+ try { a = anchor?.current ? lord.getLayout(anchor.current.id) : null; } catch (e) { a = null; }
+ useEffect(() => {
+ if (!a) { const id = setTimeout(() => force((v) => v + 1), 16); return () => clearTimeout(id); }
+ if (!box.current) return undefined;
+ const h = lord.getLayout(box.current.id)[3];
+ const below = a[1] - o[1] + a[3] + 4;
+ const want = below + h > o[3] - 6 && a[1] - o[1] - h - 4 > 6;
+ if (want !== flip) setFlip(want);
+ return undefined;
+ });
+ if (!a) return null;
+ const rtl = direction() === 'rtl';
+ const w = Math.min(width, o[2] - 16);
+ let left = rtl ? a[0] - o[0] + a[2] - w : a[0] - o[0];
+ left = Math.max(8, Math.min(o[2] - w - 8, left));
+ const style = { position: 'absolute', left, width: w, padding, borderRadius: 10, backgroundColor: th.mode === 'dark' ? '#2c2c31' : '#ffffff',
+ border: `1px solid ${th.separator}`, boxShadow: '0 12px 32px rgba(0,0,0,0.32)' };
+ if (flip) style.bottom = o[3] - (a[1] - o[1]) + 4; else style.top = a[1] - o[1] + a[3] + 4;
+ return (
+ <>
+ <View onMouseDown={() => onClose?.()} style={{ position: 'absolute', left: 0, top: 0, right: 0, bottom: 0 }} />
+ <View ref={box} style={style}>{children}</View>
+ </>
+ );
+}
+
+// A menu inside a popover: items = [{ label, onClick, checked, destructive, color, disabled } | '-']
+export function MenuList({ items, onDone }) {
+ return items.map((it, i) => (it === '-' ? <Separator key={`s${i}`} /> : <MenuItem key={`${i}${it.label}`} it={it} onDone={onDone} />));
+}
+
+function Separator() {
+ const th = useTheme();
+ return <View style={{ height: 1, marginVertical: 4, marginHorizontal: 6, backgroundColor: th.separator }} />;
+}
+
+function MenuItem({ it, onDone }) {
+ const th = useTheme();
+ const [hover, setHover] = useState(false);
+ const on = hover && !it.disabled;
+ return (
+ <View onClick={() => { if (it.disabled) return; onDone?.(); it.onClick?.(); }} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
+ style={{ height: 26, paddingHorizontal: 8, borderRadius: 5, flexDirection: 'row', alignItems: 'center', gap: 6,
+ backgroundColor: on ? th.accent : 'transparent', opacity: it.disabled ? 0.4 : 1 }}>
+ <Text style={{ width: 12, fontSize: 11, color: on ? '#fff' : th.text }}>{it.checked ? '✓' : ''}</Text>
+ {it.color ? <View style={{ width: 10, height: 10, borderRadius: 5, backgroundColor: it.color }} /> : null}
+ <Text style={{ flex: 1, fontSize: 13, whiteSpace: 'nowrap', overflow: 'hidden', color: on ? '#fff' : it.destructive ? RED : th.text }}>{it.label}</Text>
+ </View>
+ );
+}
+
+// ---- sheet: a modal box centered on the window ----
+
+export function Sheet({ title, onClose, children, footer, width = 440 }) {
+ const th = useTheme();
+ return (
+ <View onMouseDown={(e) => e.stopPropagation?.()} style={{ position: 'absolute', left: 0, top: 0, right: 0, bottom: 0, zIndex: 100,
+ alignItems: 'center', justifyContent: 'center', backgroundColor: 'rgba(0,0,0,0.3)' }}>
+ <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>
+ ) : null}
+ <View style={{ paddingHorizontal: 16, paddingVertical: 10, gap: 10, flexShrink: 1 }}>{children}</View>
+ {footer ? (
+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 8, paddingHorizontal: 16, paddingVertical: 12 }}>
+ <Hairline edge="top" />
+ {footer}
+ </View>
+ ) : null}
+ </View>
+ </View>
+ );
+}
+
+// label | control row for sheets and inspectors
+export function Field({ label, children, width = 86, top }) {
+ const th = useTheme();
+ return (
+ <View style={{ flexDirection: 'row', alignItems: top ? 'flex-start' : 'center', gap: 10, minHeight: 28 }}>
+ <Text style={{ width, fontSize: 12, color: th.textDim, textAlign: 'end', marginTop: top ? 6 : 0 }}>{label}</Text>
+ <View style={{ flex: 1, flexDirection: 'row', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>{children}</View>
+ </View>
+ );
+}
+
+// ---- drop-down choice: options = [[value, label, color?]] ----
+
+export function Choice({ value, options, onChange, width = 180, height }) {
+ const th = useTheme();
+ const ref = useRef(null);
+ const scroll = useRef(null);
+ const [open, setOpen] = useState(false);
+ const cur = options.find((o) => o[0] === value);
+ const long = height || options.length > 12;
+ useEffect(() => {
+ if (!open || !long) return undefined;
+ const i = options.findIndex((o) => o[0] === value);
+ const id = setTimeout(() => scroll.current?.scrollTo(Math.max(0, i * 26 - 100)), 40);
+ return () => clearTimeout(id);
+ }, [open]);
+ const list = options.map(([v, label, color]) => ({ label, color, checked: v === value, onClick: () => onChange(v) }));
+ return (
+ <View ref={ref} style={{ width }}>
+ <View onClick={() => setOpen(!open)} style={{ height: 26, paddingHorizontal: 9, borderRadius: 6, flexDirection: 'row', alignItems: 'center', gap: 6,
+ backgroundColor: th.control }}>
+ {cur && cur[2] ? <View style={{ width: 10, height: 10, borderRadius: 5, backgroundColor: cur[2] }} /> : null}
+ <Text style={{ flex: 1, fontSize: 13, color: th.text, whiteSpace: 'nowrap', overflow: 'hidden' }}>{cur ? cur[1] : ''}</Text>
+ <Text style={{ fontSize: 9, color: th.textDim }}>▼</Text>
+ </View>
+ {open && (
+ <Popover anchor={ref} width={Math.max(width, 170)} onClose={() => setOpen(false)}>
+ {long ? (
+ <View style={{ height: height || 260 }}>
+ <ScrollView scrollRef={scroll} style={{ flex: 1 }}><MenuList items={list} onDone={() => setOpen(false)} /></ScrollView>
+ </View>
+ ) : <MenuList items={list} onDone={() => setOpen(false)} />}
+ </Popover>
+ )}
+ </View>
+ );
+}
+
+// ---- multi-line text field ----
+
+export function TextArea({ value, onChange, placeholder, minHeight = 64 }) {
+ const th = useTheme();
+ const token = useRef({}).current;
+ const [focus, setFocus] = useState(false);
+ const [blink, setBlink] = useState(true);
+ const latest = useRef();
+ latest.current = { value: value || '', onChange };
+ useEffect(() => () => releaseTextFocus(token), []);
+ useEffect(() => {
+ if (!focus) return undefined;
+ const id = setInterval(() => setBlink((b) => !b), 530);
+ return () => clearInterval(id);
+ }, [focus]);
+ const onKey = (e) => {
+ const { value: v, onChange: set } = latest.current;
+ if ((e.ctrl || e.meta) && e.base === 'v') { try { set(v + lord.clipboard.get()); } catch (err) { /* no clipboard */ } return; }
+ if (e.key === 'Backspace') set([...v].slice(0, -1).join(''));
+ else if (e.key === 'Enter') set(`${v}\n`);
+ else if (e.key === 'Escape') { releaseTextFocus(token); setFocus(false); }
+ else if (e.char && !e.ctrl && !e.meta) set(v + e.char);
+ setBlink(true);
+ };
+ const caret = focus && blink ? '▏' : '';
+ return (
+ <View onMouseDown={() => { takeTextFocus(token, onKey, () => setFocus(false)); setFocus(true); }}
+ style={{ flex: 1, minHeight, padding: 7, borderRadius: 7, backgroundColor: th.inputBg, border: `1px solid ${focus ? th.accent : th.separator}` }}>
+ {value ? <Text style={{ fontSize: 13, color: th.text, lineHeight: 18 }}>{`${value}${caret}`}</Text>
+ : <Text style={{ fontSize: 13, color: th.textDim }}>{focus ? caret || ' ' : placeholder || ''}</Text>}
+ </View>
+ );
+}
+
+// ---- month grid picker ----
+
+export function MiniMonth({ value, onPick, marks, month: ctlMonth, onMonth, cell = 26, today = new Date() }) {
+ const th = useTheme();
+ const [own, setOwn] = useState(() => new Date((value || today).getFullYear(), (value || today).getMonth(), 1));
+ const month = ctlMonth || own;
+ const setMonth = (m) => (onMonth ? onMonth(m) : setOwn(m));
+ const rtl = direction() === 'rtl';
+ const first = startOfWeek(month);
+ const rows = [];
+ for (let r = 0; r < 6; r++) {
+ const cells = [];
+ for (let c = 0; c < 7; c++) {
+ const d = addDays(first, r * 7 + c);
+ const sel = value && sameDay(d, value), isToday = sameDay(d, today), inMonth = d.getMonth() === month.getMonth();
+ cells.push(
+ <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,
+ 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}
+ </View>,
+ );
+ }
+ rows.push(<View key={r} style={{ flexDirection: 'row' }}>{cells}</View>);
+ }
+ return (
+ <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>
+ <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))} />
+ </View>
+ <View style={{ flexDirection: 'row' }}>
+ {[1, 2, 3, 4, 5, 6, 0].map((wd) => (
+ <Text key={wd} style={{ width: cell, textAlign: 'center', fontSize: 10, fontWeight: 600, color: th.textDim }}>{[...weekdayName(wd)][0] || ''}</Text>
+ ))}
+ </View>
+ {rows}
+ </View>
+ );
+}
+
+function NavArrow({ glyph, onClick, small }) {
+ const th = useTheme();
+ const [hover, setHover] = useState(false);
+ return (
+ <View onClick={onClick} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
+ style={{ width: 20, height: 20, borderRadius: 5, alignItems: 'center', justifyContent: 'center', backgroundColor: hover ? th.hover : 'transparent' }}>
+ <Text style={{ fontSize: small ? 7 : 15, color: th.textDim }}>{glyph}</Text>
+ </View>
+ );
+}
+
+// ---- date and time fields ----
+
+export function DateField({ value, onChange, width = 120 }) {
+ const th = useTheme();
+ const ref = useRef(null);
+ const [open, setOpen] = useState(false);
+ return (
+ <View ref={ref}>
+ <View onClick={() => setOpen(!open)} style={{ width, height: 26, paddingHorizontal: 9, borderRadius: 6, justifyContent: 'center', backgroundColor: th.control }}>
+ <Text style={{ fontSize: 13, color: th.text, whiteSpace: 'nowrap' }}>{value ? formatDate(value, 'numeric') : ''}</Text>
+ </View>
+ {open && (
+ <Popover anchor={ref} width={7 * 28 + 16} padding={8} onClose={() => setOpen(false)}>
+ <MiniMonth value={value} cell={28} onPick={(d) => { setOpen(false); onChange(d); }} />
+ </Popover>
+ )}
+ </View>
+ );
+}
+
+// minutes since midnight, every 15 minutes (and the current value if it is not on the grid)
+export function TimeField({ value, onChange, width = 100 }) {
+ const opts = [];
+ for (let m = 0; m < 1440; m += 15) opts.push(m);
+ if (!opts.includes(value)) { opts.push(value); opts.sort((a, b) => a - b); }
+ return <Choice width={width} value={value} onChange={onChange} options={opts.map((m) => [m, formatTime(atMinutes(new Date(2000, 0, 3), m))])} />;
+}
+
+// ---- colors ----
+
+export function ColorSwatches({ value, onChange, colors = COLORS }) {
+ const th = useTheme();
+ return (
+ <View style={{ flexDirection: 'row', gap: 8, flexWrap: 'wrap' }}>
+ {colors.map((c) => (
+ <View key={c} onClick={() => onChange(c)} style={{ width: 24, height: 24, borderRadius: 12, alignItems: 'center', justifyContent: 'center',
+ border: `2px solid ${value === c ? th.text : 'transparent'}` }}>
+ <View style={{ width: 18, height: 18, borderRadius: 9, backgroundColor: c }} />
+ </View>
+ ))}
+ </View>
+ );
+}
+
+// square check box filled with a color when on
+export function ColorCheck({ on, color, onClick, size = 14 }) {
+ return (
+ <View onClick={onClick} style={{ width: size, height: size, borderRadius: 4, alignItems: 'center', justifyContent: 'center',
+ border: `1.5px solid ${color}`, backgroundColor: on ? color : 'transparent' }}>
+ {on ? <Text style={{ fontSize: size - 4, fontWeight: 700, color: '#fff' }}>✓</Text> : null}
+ </View>
+ );
+}
+
+// a promise-returning loader that re-runs when deps change: { data, error }
+export function useLoad(fn, deps) {
+ const [st, setSt] = useState({ data: null, error: null });
+ useEffect(() => {
+ let live = true;
+ Promise.resolve().then(fn).then((data) => { if (live) setSt({ data, error: null }); }).catch((error) => { if (live) setSt((s) => ({ data: s.data, error })); });
+ return () => { live = false; };
+ }, deps);
+ return st;
+}
+
+export function useNow(ms = 30000) {
+ const [now, setNow] = useState(Date.now());
+ useEffect(() => { const id = setInterval(() => setNow(Date.now()), ms); return () => clearInterval(id); }, [ms]);
+ return now;
+}
diff --git a/apps/camera/index.jsx b/apps/camera/index.jsx
index f0497cb..e956f7c 100644
--- a/apps/camera/index.jsx
+++ b/apps/camera/index.jsx
@@ -1,8 +1,11 @@
-// Cámara — vista previa de la webcam (V4L2), fotos y videos (diseño propio, al estilo de las apps
-// de cámara de escritorio). El dispositivo lo abre lord-server después del permiso de cámara; lo
-// lee y codifica lord-media (aislado). Fotos y videos van a ~/Imágenes/Cámara.
+// Camera: webcam preview (V4L2), photos and videos (our own design, in the style of desktop camera
+// apps). lord-server opens the device after the camera permission; lord-media (sandboxed) reads
+// and encodes it. Photos and videos go to ~/Pictures/Camera.
+//
+// The window is always dark, like a viewfinder: the controls below the preview don't follow the
+// light theme.
import {
- View, Text, Image, MediaView, Segmented, Toggle, useTheme, useKeyboard, wm,
+ View, Text, Image, MediaView, Toggle, useTheme, useKeyboard, wm,
t as tr, media, usePlayer, useThumb, userDirs, fs, mediaFormatTime, useSettings,
} from '@lordos/sdk';
import { useEffect, useRef, useState } from 'react';
@@ -13,7 +16,7 @@ export function Icon({ size: s }) {
return (
<View style={{ width: s, height: s, borderRadius: s * 0.225, background: 'linear-gradient(160deg, #3a3f47, #15171b)',
boxShadow: `0 ${s * 0.04}px ${s * 0.12}px rgba(0,0,0,0.35)`, overflow: 'hidden', alignItems: 'center', justifyContent: 'center' }}>
- {/* cuerpo de cámara con lente grande */}
+ {/* camera body with a large lens */}
<View style={{ position: 'absolute', left: s * 0.16, top: s * 0.3, width: s * 0.68, height: s * 0.46, borderRadius: s * 0.08, backgroundColor: '#d9dde3' }} />
<View style={{ position: 'absolute', left: s * 0.24, top: s * 0.23, width: s * 0.18, height: s * 0.09, borderRadius: s * 0.03, backgroundColor: '#d9dde3' }} />
<View style={{ position: 'absolute', left: s * 0.32, top: s * 0.33, width: s * 0.36, height: s * 0.36, borderRadius: s * 0.18, backgroundColor: '#23262c' }} />
@@ -31,8 +34,8 @@ function stamp() {
}
function outDir() {
const dir = `${userDirs().pictures}/${tr('camera.folder')}`;
- try { fs.mkdir(userDirs().pictures); } catch (e) { /* ya está */ }
- try { fs.mkdir(dir); } catch (e) { /* ya está */ }
+ try { fs.mkdir(userDirs().pictures); } catch (e) { /* already there */ }
+ try { fs.mkdir(dir); } catch (e) { /* already there */ }
return dir;
}
function freeName(base, ext) {
@@ -47,8 +50,38 @@ function freeName(base, ext) {
function Shot({ path, onOpen }) {
const thumb = useThumb(path, 128);
return (
- <View onClick={onOpen} style={{ width: 56, height: 42, borderRadius: 6, overflow: 'hidden', backgroundColor: '#222' }}>
- {thumb ? <Image src={thumb} style={{ width: 56, height: 42, objectFit: 'cover' }} /> : null}
+ <View onClick={onOpen} style={{ width: 52, height: 40, borderRadius: 6, overflow: 'hidden', backgroundColor: '#2a2a2e', border: '1px solid rgba(255,255,255,0.12)' }}>
+ {thumb ? <Image src={thumb} style={{ width: 52, height: 40, objectFit: 'cover' }} /> : null}
+ </View>
+ );
+}
+
+// Photo / Video switch, as camera apps do it: two words, the current one in yellow.
+function ModeSwitch({ value, onChange }) {
+ return (
+ <View style={{ flexDirection: 'row', gap: 4 }}>
+ {[['photo', tr('camera.photo')], ['video', tr('camera.video')]].map(([v, label]) => (
+ <View key={v} onClick={() => onChange(v)} style={{ height: 24, paddingHorizontal: 10, borderRadius: 12, justifyContent: 'center',
+ backgroundColor: value === v ? 'rgba(255,214,10,0.14)' : 'transparent' }}>
+ <Text style={{ fontSize: 12, fontWeight: 600, color: value === v ? '#ffd60a' : 'rgba(255,255,255,0.7)', whiteSpace: 'nowrap' }}>{label}</Text>
+ </View>
+ ))}
+ </View>
+ );
+}
+
+// The empty state on the black viewfinder: a drawn camera, a title and one hint line.
+function NoCamera({ title, hint }) {
+ return (
+ <View style={{ position: 'absolute', left: 0, right: 0, top: 0, bottom: 0, alignItems: 'center', justifyContent: 'center', gap: 8, paddingHorizontal: 32 }}>
+ <View style={{ width: 52, height: 38, marginBottom: 8 }}>
+ <View style={{ position: 'absolute', left: 12, top: 0, width: 16, height: 8, borderRadius: 2, backgroundColor: 'rgba(255,255,255,0.35)' }} />
+ <View style={{ position: 'absolute', left: 0, top: 5, width: 52, height: 33, borderRadius: 7, backgroundColor: 'rgba(255,255,255,0.35)' }} />
+ <View style={{ position: 'absolute', left: 15, top: 10, width: 22, height: 22, borderRadius: 11, backgroundColor: '#0b0b0d' }} />
+ <View style={{ position: 'absolute', left: 20, top: 15, width: 12, height: 12, borderRadius: 6, backgroundColor: 'rgba(255,255,255,0.35)' }} />
+ </View>
+ <Text style={{ fontSize: 15, fontWeight: 600, color: '#f2f2f7', textAlign: 'center' }}>{title}</Text>
+ {hint ? <Text style={{ fontSize: 12, color: 'rgba(235,235,245,0.6)', textAlign: 'center', maxWidth: 360, lineHeight: 1.4 }}>{hint}</Text> : null}
</View>
);
}
@@ -69,7 +102,7 @@ export default function Camera() {
const p = usePlayer(id);
const idRef = useRef(0);
- // abrir la cámara elegida
+ // open the chosen camera
useEffect(() => {
let alive = true;
media.close(idRef.current);
@@ -86,7 +119,7 @@ export default function Camera() {
}, [dev]);
useEffect(() => () => media.close(idRef.current), []);
useEffect(() => { if (id) media.view(id, { mirror: mirror ? 1 : 0, fit: 'contain', background: 0xff000000 }); }, [id, mirror]);
- // una cámara nueva enchufada
+ // a camera that was just plugged in
useEffect(() => { const tmr = setInterval(() => setCams(media.cameras()), 3000); return () => clearInterval(tmr); }, []);
useEffect(() => { if (!dev && cams.length) setDev(cams[0].device); }, [cams]);
useEffect(() => { if (!recStart) return undefined; const tmr = setInterval(() => setNow(Date.now()), 250); return () => clearInterval(tmr); }, [recStart]);
@@ -114,59 +147,55 @@ export default function Camera() {
useKeyboard((e) => { if (e.key === ' ' || e.key === 'Enter') shoot(); });
const cam = cams.find((c) => c.device === dev);
+ const recording = mode === 'video' && recStart > 0;
return (
<View style={{ flex: 1, backgroundColor: '#0b0b0d' }}>
<View style={{ flex: 1 }}>
<MediaView media={id} style={{ position: 'absolute', left: 0, top: 0, right: 0, bottom: 0 }} />
{(!cams.length || denied || p.error) && (
- <View style={{ position: 'absolute', left: 0, right: 0, top: '40%', alignItems: 'center', gap: 6, paddingHorizontal: 24 }}>
- <Text style={{ fontSize: 30 }}>📷</Text>
- <Text style={{ fontSize: 13, color: '#ddd', textAlign: 'center' }}>
- {!cams.length ? tr('camera.none') : denied ? tr('camera.denied') : tr('camera.error', { error: p.error })}
- </Text>
- </View>
+ !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 })} />
)}
{flash && <View style={{ position: 'absolute', left: 0, top: 0, right: 0, bottom: 0, backgroundColor: 'rgba(255,255,255,0.85)' }} />}
{recStart > 0 && (
<View style={{ position: 'absolute', top: 12, left: 0, right: 0, alignItems: 'center' }}>
- <View style={{ flexDirection: 'row', gap: 8, alignItems: 'center', paddingHorizontal: 12, paddingVertical: 5, borderRadius: 14, backgroundColor: 'rgba(0,0,0,0.6)' }}>
- <View style={{ width: 9, height: 9, borderRadius: 5, backgroundColor: '#ff3b30' }} />
- <Text style={{ fontSize: 12, color: '#fff' }}>{mediaFormatTime(now - recStart)}</Text>
+ <View style={{ flexDirection: 'row', gap: 8, alignItems: 'center', paddingHorizontal: 12, height: 26, borderRadius: 13, backgroundColor: 'rgba(0,0,0,0.6)' }}>
+ <View style={{ width: 8, height: 8, borderRadius: 4, backgroundColor: '#ff3b30' }} />
+ <Text style={{ fontSize: 12, fontWeight: 500, color: '#fff', direction: 'ltr' }}>{mediaFormatTime(now - recStart)}</Text>
</View>
</View>
)}
</View>
- <View style={{ height: 78, flexDirection: 'row', alignItems: 'center', gap: 14, paddingHorizontal: 14, backgroundColor: '#18181b' }}>
- <View style={{ flexDirection: 'row', gap: 6, width: 200 }}>
+ <View style={{ height: 88, flexDirection: 'row', alignItems: 'center', gap: 16, paddingHorizontal: 20, backgroundColor: '#161618' }}>
+ <View style={{ position: 'absolute', left: 0, right: 0, top: 0, height: 1, backgroundColor: 'rgba(255,255,255,0.08)' }} />
+ <View style={{ flex: 1, flexDirection: 'row', gap: 6 }}>
{shots.slice(0, 3).map((x) => <Shot key={x} path={x} onOpen={() => wm.open(/\.mp4$/.test(x) ? 'player' : 'photos', { new: true, args: { path: x } })} />)}
</View>
- <View style={{ flex: 1, alignItems: 'center' }}>
- <View onClick={shoot} style={{ width: 56, height: 56, borderRadius: 28, border: '3px solid #fff', alignItems: 'center', justifyContent: 'center' }}>
- <View style={{ width: mode === 'video' && recStart ? 22 : 44, height: mode === 'video' && recStart ? 22 : 44, borderRadius: mode === 'video' && recStart ? 5 : 22,
- backgroundColor: mode === 'video' ? '#ff3b30' : '#fff' }} />
- </View>
+ <View onClick={shoot} style={{ width: 60, height: 60, borderRadius: 30, border: '3px solid #ffffff', alignItems: 'center', justifyContent: 'center', opacity: id ? 1 : 0.5 }}>
+ <View style={{ width: recording ? 22 : 46, height: recording ? 22 : 46, borderRadius: recording ? 5 : 23,
+ backgroundColor: mode === 'video' ? '#ff3b30' : '#ffffff' }} />
</View>
- <View style={{ width: 200, alignItems: 'flex-end', gap: 6 }}>
- <Segmented value={mode} onChange={(v) => !recStart && setMode(v)} options={[['photo', tr('camera.photo')], ['video', tr('camera.video')]]} />
+ <View style={{ flex: 1, alignItems: 'flex-end', gap: 8 }}>
+ <ModeSwitch value={mode} onChange={(v) => !recStart && setMode(v)} />
<View style={{ flexDirection: 'row', alignItems: 'center', gap: 8 }}>
- <Text style={{ fontSize: 11, color: '#bbb' }}>{tr('camera.mirror')}</Text>
+ <Text style={{ fontSize: 12, color: 'rgba(235,235,245,0.7)' }}>{tr('camera.mirror')}</Text>
<Toggle on={mirror} onChange={(v) => update({ camera: { ...(s.camera || {}), mirror: v } })} />
</View>
</View>
</View>
{cams.length > 1 && (
- <View style={{ position: 'absolute', right: 10, top: 10, flexDirection: 'row', gap: 4, padding: 4, borderRadius: 8, backgroundColor: 'rgba(0,0,0,0.55)' }}>
+ <View style={{ position: 'absolute', right: 12, top: 12, flexDirection: 'row', gap: 4, padding: 3, borderRadius: 9, backgroundColor: 'rgba(0,0,0,0.55)' }}>
{cams.map((c) => (
<View key={c.device} onClick={() => { setDev(c.device); update({ camera: { ...(s.camera || {}), device: c.device } }); }}
- style={{ paddingHorizontal: 8, height: 24, borderRadius: 6, justifyContent: 'center', backgroundColor: c.device === dev ? th.accent : 'transparent' }}>
- <Text style={{ fontSize: 11, color: '#fff' }}>{c.name}</Text>
+ style={{ paddingHorizontal: 10, height: 24, borderRadius: 6, justifyContent: 'center', backgroundColor: c.device === dev ? th.accent : 'transparent' }}>
+ <Text style={{ fontSize: 12, color: '#fff' }}>{c.name}</Text>
</View>
))}
</View>
)}
{cam && cams.length === 1 && (
- <View style={{ position: 'absolute', left: 12, top: 12, paddingHorizontal: 8, paddingVertical: 3, borderRadius: 6, backgroundColor: 'rgba(0,0,0,0.5)' }}>
- <Text style={{ fontSize: 11, color: '#ddd' }}>{cam.name}{p.info ? ` · ${p.info.width}×${p.info.height}` : ''}</Text>
+ <View style={{ position: 'absolute', left: 12, top: 12, paddingHorizontal: 10, height: 24, justifyContent: 'center', borderRadius: 12, backgroundColor: 'rgba(0,0,0,0.5)' }}>
+ <Text style={{ fontSize: 11, color: '#e5e5ea' }}>{cam.name}{p.info ? ` · ${p.info.width}×${p.info.height}` : ''}</Text>
</View>
)}
</View>
diff --git a/apps/characters/index.jsx b/apps/characters/index.jsx
index 57b7687..f8725b2 100644
--- a/apps/characters/index.jsx
+++ b/apps/characters/index.jsx
@@ -1,14 +1,17 @@
-// Emojis y símbolos — la versión en ventana del selector del sistema (❖.): emojis por categoría
-// con búsqueda en español, inglés y portugués, tonos de piel y recientes, más los símbolos de
-// Unicode por bloque. Un clic elige; «Copiar» lo deja en el portapapeles.
-import { View, Text, TextInput, Button, Segmented, ScrollView, useTheme, clipboard, emoji, EmojiGrid, EmojiToneBar, t as tr } from '@lordos/sdk';
+// Emoji & Symbols: the window version of the system picker (❖.): emoji by category with search in
+// Spanish, English and Portuguese, skin tones and recents, plus the Unicode symbols by block. A
+// click picks one; "Copy" puts it on the clipboard.
+import {
+ View, Text, Button, Segmented, ScrollView, SidebarItem, Toolbar, ToolbarSpacer, Hairline, SearchField, EmptyState, useTheme, clipboard, emoji,
+ EmojiGrid, EmojiToneBar, typeScale, t as tr,
+} from '@lordos/sdk';
import { useMemo, useState } from 'react';
export function Icon({ size: s }) {
return (
<View style={{ width: s, height: s, borderRadius: s * 0.225, background: 'linear-gradient(160deg, #5ac8fa, #5856d6)',
boxShadow: `0 ${s * 0.04}px ${s * 0.12}px rgba(0,0,0,0.35)`, overflow: 'hidden' }}>
- {/* carita propia (círculo y rasgos) y un símbolo */}
+ {/* our own smiley (a circle and its features) and a symbol */}
<View style={{ position: 'absolute', left: s * 0.14, top: s * 0.16, width: s * 0.5, height: s * 0.5, borderRadius: s * 0.25, backgroundColor: '#ffd60a' }} />
<View style={{ position: 'absolute', left: s * 0.27, top: s * 0.3, width: s * 0.06, height: s * 0.09, borderRadius: s * 0.03, backgroundColor: '#3a2a00' }} />
<View style={{ position: 'absolute', left: s * 0.45, top: s * 0.3, width: s * 0.06, height: s * 0.09, borderRadius: s * 0.03, backgroundColor: '#3a2a00' }} />
@@ -18,7 +21,7 @@ export function Icon({ size: s }) {
);
}
-// bloques de símbolos (nombre en characters.block.<id>)
+// symbol blocks (named in characters.block.<id>)
const SYMBOL_BLOCKS = [
['arrows', 0x2190, 0x21ff], ['math', 0x2200, 0x22ff], ['technical', 0x2300, 0x23ff], ['currency', 0x20a0, 0x20c0], ['letterlike', 0x2100, 0x214f],
['numberForms', 0x2150, 0x218b], ['punctuation', 0x2010, 0x205e], ['superSub', 0x2070, 0x209c], ['enclosed', 0x2460, 0x24ff], ['boxDrawing', 0x2500, 0x257f],
@@ -26,18 +29,31 @@ const SYMBOL_BLOCKS = [
['braille', 0x2800, 0x28ff], ['greek', 0x391, 0x3c9], ['latin1', 0xa1, 0xff], ['cjkSymbols', 0x3000, 0x303f], ['halfwidth', 0xff01, 0xff5e],
];
+// Inspector of the picked character (an empty state until there is one), with a hairline on its
+// leading edge.
+const PREVIEW_W = 200;
function Preview({ ch, th }) {
- if (!ch) return <View style={{ width: 220 }} />;
+ const edge = <Hairline edge="start" />;
+ if (!ch) {
+ return (
+ <View style={{ width: PREVIEW_W, backgroundColor: th.sidebarBg }}>
+ {edge}
+ <EmptyState icon="☺" title={tr('characters.pickTitle')} hint={tr('characters.pickHint')} style={{ padding: 16 }} />
+ </View>
+ );
+ }
const cps = [...ch].map((c) => `U+${c.codePointAt(0).toString(16).toUpperCase().padStart(4, '0')}`).join(' ');
const name = emoji.name(ch);
return (
- <View style={{ width: 220, alignItems: 'center', gap: 10, padding: 16, backgroundColor: th.sidebarBg }}>
- <View style={{ width: 140, height: 140, borderRadius: 16, alignItems: 'center', justifyContent: 'center', backgroundColor: th.control }}>
- <Text style={{ fontSize: 80, color: th.text, lineHeight: 120 }}>{ch}</Text>
+ <View style={{ width: PREVIEW_W, alignItems: 'center', gap: 8, paddingHorizontal: 16, paddingTop: 24, backgroundColor: th.sidebarBg }}>
+ {edge}
+ <View style={{ width: 128, height: 128, borderRadius: 14, alignItems: 'center', justifyContent: 'center', marginBottom: 6,
+ backgroundColor: th.mode === 'dark' ? 'rgba(255,255,255,0.06)' : '#ffffff', border: `1px solid ${th.separator}` }}>
+ <Text style={{ fontSize: 72, color: th.text, lineHeight: 110 }}>{ch}</Text>
</View>
- {name ? <Text style={{ fontSize: 13, fontWeight: 600, color: th.text, textAlign: 'center' }}>{name}</Text> : null}
- <Text style={{ fontSize: 11, color: th.textDim, textAlign: 'center' }}>{cps}</Text>
- <Button primary label={tr('characters.copy')} onClick={() => clipboard.set(ch)} />
+ {name ? <Text style={{ fontSize: typeScale.headline, fontWeight: 600, color: th.text, textAlign: 'center' }}>{name}</Text> : null}
+ <Text style={{ fontSize: typeScale.caption, color: th.textDim, textAlign: 'center', direction: 'ltr' }}>{cps}</Text>
+ <Button primary label={tr('characters.copy')} onClick={() => clipboard.set(ch)} style={{ marginTop: 8 }} />
</View>
);
}
@@ -64,36 +80,37 @@ export default function Characters() {
: SYMBOL_BLOCKS.map((b, i) => [i, tr(`characters.block.${b[0]}`)]);
return (
<View style={{ flex: 1 }}>
- <View style={{ height: 44, flexDirection: 'row', alignItems: 'center', gap: 10, paddingHorizontal: 12 }}>
- <Segmented value={tab} onChange={(v) => { setTab(v); setPick(null); }} options={[['emoji', tr('characters.tab.emoji')], ['symbols', tr('characters.tab.symbols')]]} />
- <View style={{ flex: 1 }} />
+ <Toolbar>
+ <Segmented appearance="neutral" value={tab} onChange={(v) => { setTab(v); setPick(null); }}
+ options={[['emoji', tr('characters.tab.emoji')], ['symbols', tr('characters.tab.symbols')]]} />
+ <ToolbarSpacer />
{tab === 'emoji' && <EmojiToneBar tone={tone} onTone={(n) => { setTone(n); emoji.setTone(n); }} th={th} />}
- {tab === 'emoji' && <TextInput value={q} onChange={setQ} placeholder={tr('emoji.search')} onCancel={() => setQ('')} style={{ width: 200, height: 26 }} />}
- </View>
- <View style={{ height: 1, backgroundColor: th.separator }} />
+ {tab === 'emoji' && <SearchField value={q} onChange={setQ} placeholder={tr('emoji.search')} width={180} />}
+ </Toolbar>
<View style={{ flex: 1, flexDirection: 'row' }}>
- <View style={{ width: 180, backgroundColor: th.sidebarBg, padding: 6 }}>
- <ScrollView style={{ flex: 1 }}>
+ <View style={{ width: 180, backgroundColor: th.sidebarBg }}>
+ <ScrollView style={{ flex: 1, paddingHorizontal: 10, paddingTop: 10 }}>
{side.map(([id, label]) => {
const on = tab === 'emoji' ? (!q.trim() && group === id) : block === id;
- return (
- <View key={id} onClick={() => { if (tab === 'emoji') { setQ(''); setGroup(id); } else setBlock(id); }}
- style={{ height: 26, paddingHorizontal: 8, flexDirection: 'row', alignItems: 'center', gap: 8, borderRadius: 6, backgroundColor: on ? th.accent : 'transparent' }}>
- <Text style={{ fontSize: 13, color: on ? '#fff' : th.text, whiteSpace: 'nowrap', overflow: 'hidden' }}>{label}</Text>
- </View>
- );
+ return <SidebarItem key={id} label={label} selected={on} onClick={() => { if (tab === 'emoji') { setQ(''); setGroup(id); } else setBlock(id); }} />;
})}
+ <View style={{ height: 10 }} />
</ScrollView>
+ <Hairline edge="end" />
</View>
- <View style={{ flex: 1, padding: 10, direction: 'ltr' }}>
+ <View style={{ flex: 1, minWidth: 0, direction: 'ltr' }}>
{tab === 'emoji' ? (
- list.length ? <ScrollView style={{ flex: 1 }}><EmojiGrid list={list} sel={-1} onPick={choose} tone={tone} size={44} th={th} /></ScrollView>
- : <Text style={{ margin: 20, fontSize: 12, color: th.textDim, textAlign: 'center' }}>{group === 'recent' && !q.trim() ? tr('emoji.noRecent') : tr('emoji.none')}</Text>
+ list.length ? (
+ <ScrollView style={{ flex: 1, padding: 12 }}>
+ <EmojiGrid list={list} sel={-1} picked={pick} onPick={choose} tone={tone} size={44} th={th} wrap />
+ </ScrollView>
+ ) : <EmptyState title={group === 'recent' && !q.trim() ? tr('emoji.noRecent') : tr('emoji.none')} />
) : (
- <ScrollView style={{ flex: 1 }}>
+ <ScrollView style={{ flex: 1, padding: 12 }}>
<View style={{ flexDirection: 'row', flexWrap: 'wrap' }}>
{chars.map((ch) => (
- <View key={ch} onClick={() => choose(ch)} style={{ width: 40, height: 40, alignItems: 'center', justifyContent: 'center', borderRadius: 6, backgroundColor: pick === ch ? th.accent : 'transparent' }}>
+ <View key={ch} onClick={() => choose(ch)} style={{ width: 44, height: 44, alignItems: 'center', justifyContent: 'center', borderRadius: 8,
+ backgroundColor: pick === ch ? th.accent : 'transparent' }}>
<Text style={{ fontSize: 20, color: pick === ch ? '#fff' : th.text }}>{ch}</Text>
</View>
))}
diff --git a/apps/contacts/card.jsx b/apps/contacts/card.jsx
new file mode 100644
index 0000000..276aaf1
--- /dev/null
+++ b/apps/contacts/card.jsx
@@ -0,0 +1,265 @@
+// card.jsx — a contact's card (read-only, with group membership and mail links) and its editor
+// (name, photo, phones, emails, addresses, web pages, birthday and notes).
+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 { RED, Popover, MenuList, Choice, TextArea, DateField, ymd, parseYmd, monthName } from './ui.jsx';
+
+const TYPES = {
+ phones: ['cell', 'home', 'work', 'main', 'other'],
+ emails: ['home', 'work', 'other'],
+ urls: ['home', 'work', 'other'],
+ addrs: ['home', 'work', 'other'],
+};
+const KINDS = ['phones', 'emails', 'urls', 'addrs'];
+
+export const blankContact = () => ({ n: { given: '', family: '' }, org: '', title: '', phones: [], emails: [], urls: [], addrs: [], notes: '', kind: 'individual' });
+
+// vCard types come as "CELL", "voice,cell", "pref,work"…: the first one we know, or the raw text
+function typeOf(kind, raw) {
+ const parts = String(raw || '').toLowerCase().split(/[,;\s]+/).filter(Boolean);
+ const known = parts.find((p) => TYPES[kind].includes(p) || (kind === 'phones' && p === 'mobile'));
+ if (known) return known === 'mobile' ? 'cell' : known;
+ return parts.find((p) => p !== 'pref' && p !== 'voice' && p !== 'internet') || 'other';
+}
+const typeLabel = (kind, raw) => {
+ const ty = typeOf(kind, raw);
+ return TYPES[kind].includes(ty) ? t(`contacts.type.${ty}`) : ty;
+};
+
+function bdayText(s) {
+ const full = parseYmd(s);
+ if (full) return formatDate(full, 'long');
+ const m = /^--(\d{2})-?(\d{2})$/.exec(s || '');
+ return m ? t('contacts.dayMonth', { day: +m[2], month: monthName(+m[1] - 1) }) : String(s || '');
+}
+
+const addrLines = (a) => [a.street, [a.code, a.city].filter(Boolean).join(' '), a.region, a.country].filter(Boolean);
+
+function openMail(name, email) {
+ if (!getApp('mail')) return;
+ wm.open('mail', { new: true, args: { compose: { to: [{ name: name || '', email }] } } });
+}
+
+// ---- card ----
+
+export function Card({ contact: c, groups, onEdit }) {
+ const th = useTheme();
+ const groupRef = useRef(null);
+ const [groupMenu, setGroupMenu] = useState(false);
+ const name = contactName(c) || t('contacts.noName');
+ const sub = [c.title, c.dept, c.org].filter(Boolean).join(' · ');
+ const n = c.n || {};
+ const showOrg = c.org && (n.given || n.family) && name !== c.org;
+ const toggleGroup = (g) => {
+ const m = g.members || [];
+ const members = m.includes(c.uid) ? m.filter((x) => x !== c.uid) : [...m, c.uid];
+ contacts.save(g.book, { ...g, members }, {}).catch(() => {});
+ };
+ const mine = groups.filter((g) => (g.members || []).includes(c.uid));
+ return (
+ <View 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>
+ </View>
+ </ScrollView>
+ <View style={{ height: 44, flexDirection: 'row', alignItems: 'center', gap: 8, paddingHorizontal: 14 }}>
+ <Hairline edge="top" />
+ <View ref={groupRef}>
+ <Button small label={t('contacts.groups')} disabled={!groups.length} onClick={() => setGroupMenu(true)} />
+ {groupMenu ? (
+ <Popover anchor={groupRef} width={220} onClose={() => setGroupMenu(false)}>
+ <MenuList onDone={() => setGroupMenu(false)} items={groups.map((g) => ({ label: contactName(g) || t('contacts.untitledGroup'),
+ checked: (g.members || []).includes(c.uid), onClick: () => toggleGroup(g) }))} />
+ </Popover>
+ ) : null}
+ </View>
+ <View style={{ flex: 1 }} />
+ <Button small label={t('contacts.edit')} onClick={onEdit} />
+ </View>
+ </View>
+ );
+}
+
+function Row({ label, value, link, onClick }) {
+ const th = useTheme();
+ return (
+ <View style={{ flexDirection: 'row', gap: 12, paddingVertical: 6 }}>
+ <Text style={{ width: 96, fontSize: 12, color: th.textDim, textAlign: 'end', paddingTop: 1 }}>{label}</Text>
+ <Text onClick={onClick} style={{ flex: 1, fontSize: 13, color: link ? th.accent : th.text, lineHeight: 18 }}>{value}</Text>
+ </View>
+ );
+}
+
+// ---- editor ----
+
+const clean = (s) => String(s || '').trim();
+
+function buildContact(d) {
+ const c = { ...d, n: { ...(d.n || {}) } };
+ for (const k of ['given', 'family', 'middle', 'prefix', 'suffix']) if (c.n[k] != null) c.n[k] = clean(c.n[k]);
+ c.org = clean(c.org);
+ c.title = clean(c.title);
+ for (const k of ['phones', 'emails', 'urls']) c[k] = (c[k] || []).map((x) => ({ type: x.type || 'other', value: clean(x.value) })).filter((x) => x.value);
+ c.addrs = (c.addrs || []).map((a) => ({ type: a.type || 'home', street: clean(a.street), city: clean(a.city), region: clean(a.region), code: clean(a.code), country: clean(a.country) }))
+ .filter((a) => a.street || a.city || a.region || a.code || a.country);
+ const full = [c.n.prefix, c.n.given, c.n.middle, c.n.family, c.n.suffix].filter(Boolean).join(' ');
+ c.fn = full || c.org || (c.emails[0] && c.emails[0].value) || (c.phones[0] && c.phones[0].value) || '';
+ return c;
+}
+
+export function Editor({ contact, groups, onCancel, onSave, onDelete }) {
+ const th = useTheme();
+ const [d, setD] = useState(() => ({ ...blankContact(), ...contact, n: { ...(contact.n || {}) } }));
+ const [photo, setPhoto] = useState('keep'); // 'keep' | 'remove' | a path
+ const [photoMenu, setPhotoMenu] = useState(false);
+ const [picking, setPicking] = useState(false);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState('');
+ const photoRef = useRef(null);
+ const set = (p) => setD((x) => ({ ...x, ...p }));
+ const setN = (p) => setD((x) => ({ ...x, n: { ...x.n, ...p } }));
+ const save = async () => {
+ if (busy) return;
+ const c = buildContact(d);
+ if (!c.fn) { setError(t('contacts.needName')); return; }
+ setBusy(true);
+ setError('');
+ try { await onSave(c, photo); } catch (e) { setBusy(false); setError(t('contacts.saveFailed')); }
+ };
+ const shownPhoto = photo === 'remove' ? { ...d, photo: false } : d;
+ return (
+ <View style={{ flex: 1 }}>
+ <ScrollView style={{ flex: 1 }}>
+ <View style={{ padding: 24, gap: 16 }}>
+ <View style={{ flexDirection: 'row', alignItems: 'flex-start', gap: 18 }}>
+ <View ref={photoRef} onClick={() => setPhotoMenu(true)} style={{ alignItems: 'center', gap: 4 }}>
+ <ContactPhoto contact={shownPhoto} size={96} />
+ <Text style={{ fontSize: 11, color: th.accent }}>{photo !== 'keep' && photo !== 'remove' ? t('contacts.photoChosen') : t('contacts.editPhoto')}</Text>
+ {photoMenu ? (
+ <Popover anchor={photoRef} width={200} onClose={() => setPhotoMenu(false)}>
+ <MenuList onDone={() => setPhotoMenu(false)} items={[
+ { label: t('contacts.choosePhoto'), onClick: () => setPicking(true) },
+ { label: t('contacts.removePhoto'), destructive: true, disabled: !d.photo && photo === 'keep', onClick: () => setPhoto('remove') },
+ ]} />
+ </Popover>
+ ) : null}
+ </View>
+ <View style={{ flex: 1, gap: 6 }}>
+ <TextInput value={d.n.given || ''} onChange={(v) => setN({ given: v })} placeholder={t('contacts.given')} autoFocus={!!contact._new} />
+ <TextInput value={d.n.family || ''} onChange={(v) => setN({ family: v })} placeholder={t('contacts.family')} />
+ <TextInput value={d.title || ''} onChange={(v) => set({ title: v })} placeholder={t('contacts.jobTitle')} />
+ <TextInput value={d.org || ''} onChange={(v) => set({ org: v })} placeholder={t('contacts.company')} />
+ </View>
+ </View>
+ {KINDS.map((k) => <MultiField key={k} kind={k} rows={d[k] || []} onChange={(rows) => set({ [k]: rows })} />)}
+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 8 }}>
+ {d.bday ? (
+ <>
+ <RoundButton glyph="−" color={RED} onClick={() => set({ bday: '' })} />
+ <Text style={{ width: 90, fontSize: 12, color: th.textDim, textAlign: 'end' }}>{t('contacts.birthday')}</Text>
+ <DateField value={parseYmd(d.bday) || (/^--(\d{2})-?(\d{2})$/.test(d.bday) ? new Date(2000, +d.bday.slice(2, 4) - 1, +d.bday.slice(-2)) : new Date())}
+ onChange={(v) => set({ bday: ymd(v) })} width={130} />
+ </>
+ ) : (
+ <AddRow label={t('contacts.addBirthday')} onClick={() => set({ bday: ymd(new Date(1990, 0, 1)) })} />
+ )}
+ </View>
+ <View style={{ gap: 4 }}>
+ <Text style={{ fontSize: 11, fontWeight: 600, color: th.textDim }}>{t('contacts.notes')}</Text>
+ <TextArea value={d.notes || ''} onChange={(v) => set({ notes: v })} minHeight={70} />
+ </View>
+ </View>
+ </ScrollView>
+ <View style={{ height: 44, flexDirection: 'row', alignItems: 'center', gap: 8, paddingHorizontal: 14 }}>
+ <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>
+ <Button small label={t('contacts.cancel')} onClick={onCancel} />
+ <Button small primary disabled={busy} label={t('contacts.done')} onClick={save} />
+ </View>
+ {picking ? (
+ <FilePicker title={t('contacts.choosePhoto')} filter={/\.(png|jpe?g|gif|bmp|webp)$/i} onClose={() => setPicking(false)}
+ onPick={(p) => { setPicking(false); if (typeof p === 'string') setPhoto(p); }} />
+ ) : null}
+ </View>
+ );
+}
+
+function RoundButton({ glyph, color, onClick }) {
+ return (
+ <View onClick={onClick} style={{ width: 18, height: 18, borderRadius: 9, alignItems: 'center', justifyContent: 'center', backgroundColor: color }}>
+ <Text style={{ fontSize: 13, fontWeight: 700, color: '#fff' }}>{glyph}</Text>
+ </View>
+ );
+}
+
+function AddRow({ label, onClick }) {
+ const th = useTheme();
+ return (
+ <View onClick={onClick} style={{ flexDirection: 'row', alignItems: 'center', gap: 8, height: 26 }}>
+ <RoundButton glyph="+" color="#34c759" onClick={onClick} />
+ <Text style={{ fontSize: 12, color: th.textDim }}>{label}</Text>
+ </View>
+ );
+}
+
+function MultiField({ kind, rows, onChange }) {
+ const th = useTheme();
+ const types = TYPES[kind];
+ const update = (i, p) => onChange(rows.map((r, j) => (j === i ? { ...r, ...p } : r)));
+ const opts = (raw) => {
+ const cur = typeOf(kind, raw);
+ const o = types.map((ty) => [ty, t(`contacts.type.${ty}`)]);
+ if (!types.includes(cur)) o.push([cur, cur]);
+ return o;
+ };
+ return (
+ <View style={{ gap: 6 }}>
+ {rows.map((r, i) => (
+ <View key={i} style={{ flexDirection: 'row', alignItems: kind === 'addrs' ? 'flex-start' : 'center', gap: 8 }}>
+ <View style={{ paddingTop: kind === 'addrs' ? 4 : 0 }}><RoundButton glyph="−" color={RED} onClick={() => onChange(rows.filter((_, j) => j !== i))} /></View>
+ <Choice width={90} value={typeOf(kind, r.type)} options={opts(r.type)} onChange={(v) => update(i, { type: v })} />
+ {kind === 'addrs' ? (
+ <View style={{ flex: 1, gap: 4 }}>
+ <TextInput value={r.street || ''} onChange={(v) => update(i, { street: v })} placeholder={t('contacts.street')} />
+ <View style={{ flexDirection: 'row', gap: 4 }}>
+ <View style={{ flex: 2 }}><TextInput value={r.city || ''} onChange={(v) => update(i, { city: v })} placeholder={t('contacts.city')} /></View>
+ <View style={{ flex: 1 }}><TextInput value={r.code || ''} onChange={(v) => update(i, { code: v })} placeholder={t('contacts.postalCode')} /></View>
+ </View>
+ <View style={{ flexDirection: 'row', gap: 4 }}>
+ <View style={{ flex: 1 }}><TextInput value={r.region || ''} onChange={(v) => update(i, { region: v })} placeholder={t('contacts.region')} /></View>
+ <View style={{ flex: 1 }}><TextInput value={r.country || ''} onChange={(v) => update(i, { country: v })} placeholder={t('contacts.country')} /></View>
+ </View>
+ </View>
+ ) : (
+ <View style={{ flex: 1 }}>
+ <TextInput value={r.value || ''} onChange={(v) => update(i, { value: v })} placeholder={t(`contacts.placeholder.${kind}`)} />
+ </View>
+ )}
+ </View>
+ ))}
+ <View style={{ flexDirection: 'row' }}>
+ <AddRow label={t(`contacts.add.${kind}`)} onClick={() => onChange([...rows, kind === 'addrs' ? { type: types[0], street: '', city: '', region: '', code: '', country: '' } : { type: types[0], value: '' }])} />
+ </View>
+ </View>
+ );
+}
diff --git a/apps/contacts/index.jsx b/apps/contacts/index.jsx
new file mode 100644
index 0000000..65eaf74
--- /dev/null
+++ b/apps/contacts/index.jsx
@@ -0,0 +1,341 @@
+// Contacts — address books kept by lord-maild (local, or synced with CardDAV): see docs/MAIL.md.
+// Three columns: books and groups, the contact list (search, letter sections, virtualized) and
+// the card, with an edit mode. Groups are contacts with kind 'group' and a list of member uids.
+import {
+ View, Text, useTheme, useLocale, useKeyboard, useWindowState, usePim, addressBooks, contacts, contactName,
+ Button, TextInput, SearchField, Hairline, EmptyState, ToolbarButton, FilePicker, addListener, direction, formatNumber, t,
+} from '@lordos/sdk';
+import { useEffect, useMemo, useRef, useState } from 'react';
+import { RED, Sheet, Popover, MenuList, Layers, useLoad } from './ui.jsx';
+import { Card, Editor, blankContact } from './card.jsx';
+
+// ---- icon: an address-book card with a person silhouette ----
+
+export function Icon({ size: s }) {
+ return (
+ <View style={{ width: s, height: s, borderRadius: s * 0.225, background: 'linear-gradient(180deg, #b49a7e, #8c7259)',
+ boxShadow: `0 ${s * 0.04}px ${s * 0.12}px rgba(0,0,0,0.35)`, overflow: 'hidden' }}>
+ {/* binding strip */}
+ <View style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: s * 0.16, backgroundColor: '#6f5843' }} />
+ {/* the card */}
+ <View style={{ position: 'absolute', left: s * 0.24, top: s * 0.14, width: s * 0.62, height: s * 0.72, borderRadius: s * 0.06,
+ backgroundColor: '#f4f1ec', overflow: 'hidden', alignItems: 'center' }}>
+ <View style={{ marginTop: s * 0.12, width: s * 0.22, height: s * 0.22, borderRadius: s * 0.11, backgroundColor: '#9b9b9f' }} />
+ <View style={{ marginTop: s * 0.04, width: s * 0.42, height: s * 0.42, borderRadius: s * 0.21, backgroundColor: '#9b9b9f' }} />
+ </View>
+ {[0.3, 0.5, 0.7].map((y) => (
+ <View key={y} style={{ position: 'absolute', left: s * 0.86, top: s * y, width: s * 0.06, height: s * 0.1, borderRadius: s * 0.02, backgroundColor: '#e0a33a' }} />
+ ))}
+ </View>
+ );
+}
+
+const ROW = 34, HEAD = 22;
+
+const sortKey = (c) => {
+ const n = c.n || {};
+ const k = [n.family, n.given].filter(Boolean).join(' ');
+ return (k || contactName(c) || '').trim();
+};
+function letterOf(c) {
+ const ch = [...sortKey(c)][0] || '';
+ return /\p{L}/u.test(ch) ? ch.toLocaleUpperCase() : '#';
+}
+const keyOf = (c) => `${c.book}/${c.uid}`;
+
+function matchesQuery(c, q) {
+ if (!q) return true;
+ const hay = [contactName(c), c.org, c.nick, ...(c.emails || []).map((x) => x.value), ...(c.phones || []).map((x) => x.value)].join('\n').toLowerCase();
+ return q.toLowerCase().split(/\s+/).filter(Boolean).every((w) => hay.includes(w));
+}
+
+export default function ContactsApp() {
+ const th = useTheme();
+ useLocale();
+ const rev = usePim();
+ const booksQ = useLoad(() => addressBooks.list(), [rev]);
+ const allQ = useLoad(() => contacts.list(), [rev]);
+ const books = booksQ.data || [];
+ const all = allQ.data || [];
+ const [src, setSrc] = useWindowState('src', 'all'); // 'all' | 'book:<id>' | 'group:<book>/<uid>'
+ const [cur, setCur] = useWindowState('cur', null); // `${book}/${uid}`
+ const [query, setQuery] = useState('');
+ const [draft, setDraft] = useState(null); // the contact being edited (edit mode)
+ const [sheet, setSheet] = useState(null); // { group } | { newGroup } | { pick: 'vcf' } | { confirm: contact } | { notice }
+
+ const people = useMemo(() => all.filter((c) => c.kind !== 'group'), [all]);
+ const groups = useMemo(() => all.filter((c) => c.kind === 'group').sort((a, b) => contactName(a).localeCompare(contactName(b))), [all]);
+ const group = src.startsWith('group:') ? groups.find((g) => keyOf(g) === src.slice(6)) : null;
+ const bookId = src.startsWith('book:') ? src.slice(5) : group ? group.book : null;
+
+ const list = useMemo(() => {
+ let l = people;
+ if (group) { const m = new Set(group.members || []); l = l.filter((c) => c.book === group.book && m.has(c.uid)); }
+ else if (bookId) l = l.filter((c) => c.book === bookId);
+ l = l.filter((c) => matchesQuery(c, query.trim()));
+ return [...l].sort((a, b) => sortKey(a).localeCompare(sortKey(b), undefined, { sensitivity: 'base' }));
+ }, [people, group, bookId, query]);
+
+ const selected = all.find((c) => keyOf(c) === cur) || null;
+ const justSaved = useRef(null); // a new contact: wait until the list has it
+ useEffect(() => {
+ if (draft) return;
+ const there = list.some((c) => keyOf(c) === cur);
+ if (justSaved.current && justSaved.current === cur) { if (there) justSaved.current = null; return; }
+ if (!there) setCur(list.length ? keyOf(list[0]) : null);
+ }, [list, draft]);
+
+ const targetBook = async () => {
+ if (bookId && books.some((b) => b.id === bookId)) return bookId;
+ if (books.length) return (books.find((b) => b.kind === 'local') || books[0]).id;
+ const r = await addressBooks.create({ name: t('contacts.defaultBook') });
+ return r.uid;
+ };
+ const startNew = () => setDraft({ ...blankContact(), _new: true });
+ const saveDraft = async (c, photo) => {
+ const isNew = !!c._new;
+ const book = isNew ? await targetBook() : c.book;
+ const { _new, ...clean } = c;
+ const uid = await contacts.save(book, clean, { photo });
+ if (isNew && group && uid) await contacts.save(group.book, { ...group, members: [...(group.members || []), uid] }, {});
+ if (uid) { justSaved.current = `${book}/${uid}`; setCur(justSaved.current); }
+ setDraft(null);
+ };
+
+ useKeyboard((e) => {
+ if (sheet || draft) { if (e.key === 'Escape') { setSheet(null); } return; }
+ const k = String(e.base || e.key || '').toLowerCase();
+ if ((e.meta || e.ctrl) && k === 'n') startNew();
+ else if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
+ const i = list.findIndex((c) => keyOf(c) === cur);
+ const j = Math.max(0, Math.min(list.length - 1, i + (e.key === 'ArrowDown' ? 1 : -1)));
+ if (list[j]) setCur(keyOf(list[j]));
+ }
+ });
+
+ const unavailable = (booksQ.error && !booksQ.data) || (allQ.error && !allQ.data);
+ const importVcf = async (path) => {
+ setSheet(null);
+ try {
+ const r = await contacts.importFile(path, await targetBook());
+ setSheet({ notice: t('contacts.imported', { count: r && r.added != null ? r.added : 0, n: formatNumber(r && r.added != null ? r.added : 0, 0) }) });
+ } catch (e) { setSheet({ notice: t('contacts.importFailed') }); }
+ };
+
+ return (
+ <View style={{ flex: 1, flexDirection: 'row', backgroundColor: th.windowBg }}>
+ <Sources books={books} groups={groups} src={src} counts={people} onSrc={(s) => { setSrc(s); setDraft(null); }}
+ onNewGroup={() => setSheet({ newGroup: true })} onImport={() => setSheet({ pick: 'vcf' })}
+ 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' }}>
+ <SearchField value={query} onChange={setQuery} placeholder={t('contacts.search')} style={{ flex: 1 }} />
+ </View>
+ {unavailable ? null : list.length ? (
+ <ContactList list={list} cur={cur} onPick={(c) => { setDraft(null); setCur(keyOf(c)); }} />
+ ) : (
+ <EmptyState title={query ? t('contacts.noResults') : t('contacts.noContacts')} />
+ )}
+ <View style={{ height: 34, flexDirection: 'row', alignItems: 'center', paddingHorizontal: 8 }}>
+ <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>
+ <View style={{ width: 22 }} />
+ </View>
+ </View>
+ <View style={{ flex: 1 }}>
+ {unavailable ? (
+ <EmptyState icon="👤" 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')} />
+ )}
+ </View>
+ {sheet && (sheet.newGroup || sheet.group) ? (
+ <GroupSheet group={sheet.group} onClose={() => setSheet(null)} onSave={async (name) => {
+ if (sheet.group) await contacts.save(sheet.group.book, { ...sheet.group, fn: name }, {});
+ else {
+ const book = await targetBook();
+ const uid = await contacts.save(book, { kind: 'group', fn: name, n: {}, members: [] }, {});
+ if (uid) setSrc(`group:${book}/${uid}`);
+ }
+ setSheet(null);
+ }} />
+ ) : null}
+ {sheet && sheet.pick ? <FilePicker title={t('contacts.importTitle')} filter={/\.vcf$/i} onClose={() => setSheet(null)} onPick={(p) => typeof p === 'string' && importVcf(p)} /> : null}
+ {sheet && sheet.confirm ? (
+ <Sheet width={360} title={t('contacts.deleteTitle', { name: contactName(sheet.confirm) || t('contacts.noName') })} footer={[
+ <View key="sp" style={{ flex: 1 }} />,
+ <Button key="c" label={t('contacts.cancel')} onClick={() => setSheet(null)} />,
+ <Button key="d" primary destructive label={t('contacts.delete')} onClick={() => {
+ const c = sheet.confirm;
+ setSheet(null); setDraft(null);
+ contacts.remove(c.book, c.uid).catch(() => {});
+ }} />]}>
+ <Text style={{ fontSize: 13, color: th.textDim }}>{t('contacts.deleteHint')}</Text>
+ </Sheet>
+ ) : null}
+ {sheet && sheet.notice ? (
+ <Sheet width={340} footer={[<View key="sp" style={{ flex: 1 }} />, <Button key="o" primary label={t('contacts.ok')} onClick={() => setSheet(null)} />]}>
+ <Text style={{ fontSize: 13, color: th.text }}>{sheet.notice}</Text>
+ </Sheet>
+ ) : null}
+ <Layers />
+ </View>
+ );
+}
+
+// ---- first column: All Contacts, books and their groups ----
+
+function Sources({ books, groups, src, counts, onSrc, onNewGroup, onImport, onRenameGroup, onDeleteGroup }) {
+ const th = useTheme();
+ return (
+ <View style={{ width: 200, 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')} />
+ {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}`)} />
+ {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)}`)}
+ menu={[{ label: t('contacts.renameGroup'), onClick: () => onRenameGroup(g) }, '-', { label: t('contacts.deleteGroup'), destructive: true, onClick: () => onDeleteGroup(g) }]} />
+ ))}
+ </View>
+ ))}
+ </View>
+ <View style={{ flexDirection: 'row', padding: 8, gap: 4 }}>
+ <Hairline edge="top" />
+ <Button small plain icon="+" label={t('contacts.newGroup')} onClick={onNewGroup} />
+ <View style={{ flex: 1 }} />
+ <Button small plain label={t('contacts.import')} onClick={onImport} />
+ </View>
+ </View>
+ );
+}
+
+function SrcRow({ icon, label, count, selected, onClick, indent, menu }) {
+ const th = useTheme();
+ const ref = useRef(null);
+ const [open, setOpen] = useState(false);
+ 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,
+ backgroundColor: selected ? th.accent : hover ? th.hover : 'transparent' }}>
+ <Text style={{ fontSize: 12, color: selected ? '#fff' : th.textDim }}>{icon}</Text>
+ <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 ? (
+ <Popover anchor={ref} width={190} onClose={() => setOpen(false)}><MenuList items={menu} onDone={() => setOpen(false)} /></Popover>
+ ) : null}
+ </View>
+ );
+}
+
+// ---- second column: the list, with letter headers, only the visible rows are drawn ----
+
+function ContactList({ list, cur, onPick }) {
+ const th = useTheme();
+ const box = useRef(null);
+ const [h, setH] = useState(400);
+ const [off, setOff] = useState(0);
+ const rows = useMemo(() => {
+ const out = [];
+ let last = null, y = 0;
+ for (const c of list) {
+ const l = letterOf(c);
+ if (l !== last) { out.push({ head: l, top: y }); y += HEAD; last = l; }
+ out.push({ c, top: y });
+ y += ROW;
+ }
+ return { out, total: y };
+ }, [list]);
+ useEffect(() => {
+ const id = setTimeout(() => { if (box.current) { const v = lord.getLayout(box.current.id)[3]; if (v && Math.abs(v - h) > 1) setH(v); } }, 30);
+ return () => clearTimeout(id);
+ });
+ const max = Math.max(0, rows.total - h);
+ const y = Math.min(off, max);
+ // keep the selected row in view
+ useEffect(() => {
+ const r = rows.out.find((x) => x.c && keyOf(x.c) === cur);
+ if (!r) return;
+ if (r.top < y) setOff(Math.max(0, r.top - HEAD));
+ else if (r.top + ROW > y + h) setOff(r.top + ROW - h);
+ }, [cur]);
+ const drag = useRef(null);
+ useEffect(() => {
+ const a = addListener('pointermove', (e) => { if (drag.current) setOff(Math.max(0, Math.min(max, drag.current.y0 + ((e.y - drag.current.py) * rows.total) / Math.max(1, h)))); });
+ const b = addListener('pointerup', () => { drag.current = null; });
+ return () => { a(); b(); };
+ });
+ // binary search for the first visible row
+ let lo = 0, hi = rows.out.length - 1;
+ while (lo < hi) { const mid = (lo + hi) >> 1; if (rows.out[mid].top + ROW < y) lo = mid + 1; else hi = mid; }
+ const shown = [];
+ for (let i = Math.max(0, lo - 1); i < rows.out.length && rows.out[i].top < y + h + ROW; i++) shown.push(rows.out[i]);
+ const bar = rows.total > h ? Math.max(28, (h * h) / rows.total) : 0;
+ const rtl = direction() === 'rtl';
+ 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>
+ ) : (
+ <ContactRow key={keyOf(r.c)} c={r.c} top={r.top - y} selected={keyOf(r.c) === cur} onPick={onPick} />
+ )))}
+ {bar > 0 ? (
+ <View onMouseDown={(e) => { drag.current = { py: e.y, y0: y }; }}
+ style={{ position: 'absolute', [rtl ? 'left' : 'right']: 2, width: 6, borderRadius: 3, height: bar, top: (h - bar) * (y / (max || 1)),
+ backgroundColor: th.mode === 'dark' ? 'rgba(255,255,255,0.3)' : 'rgba(0,0,0,0.28)' }} />
+ ) : null}
+ </View>
+ );
+}
+
+function ContactRow({ c, top, selected, onPick }) {
+ const th = useTheme();
+ const n = c.n || {};
+ const given = [n.prefix, n.given, n.middle].filter(Boolean).join(' ');
+ 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,
+ 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}
+ </>
+ ) : (
+ <Text style={{ fontSize: 13, fontWeight: 700, color: fg, whiteSpace: 'nowrap', overflow: 'hidden', flexShrink: 1 }}>{contactName(c) || t('contacts.noName')}</Text>
+ )}
+ </View>
+ );
+}
+
+// ---- new group / rename group ----
+
+function GroupSheet({ group, onClose, onSave }) {
+ const [name, setName] = useState(group ? contactName(group) : '');
+ const [error, setError] = useState('');
+ const save = async () => { if (!name.trim()) return; try { await onSave(name.trim()); } catch (e) { setError(t('contacts.saveFailed')); } };
+ return (
+ <Sheet width={360} title={group ? t('contacts.renameGroup') : t('contacts.newGroup')} footer={[
+ <Text key="e" style={{ flex: 1, fontSize: 12, color: RED }}>{error}</Text>,
+ <Button key="c" label={t('contacts.cancel')} onClick={onClose} />,
+ <Button key="s" primary disabled={!name.trim()} label={t('contacts.save')} onClick={save} />]}>
+ <TextInput value={name} onChange={setName} placeholder={t('contacts.groupName')} autoFocus onSubmit={save} onCancel={onClose} />
+ </Sheet>
+ );
+}
diff --git a/apps/contacts/manifest.json b/apps/contacts/manifest.json
new file mode 100644
index 0000000..02cf81c
--- /dev/null
+++ b/apps/contacts/manifest.json
@@ -0,0 +1,10 @@
+{
+ "id": "contacts",
+ "name": "Contacts",
+ "description": "Address books, groups and contact cards",
+ "size": [900, 580],
+ "minSize": [700, 400],
+ "dock": true,
+ "category": "Office",
+ "permissions": []
+}
diff --git a/apps/contacts/ui.jsx b/apps/contacts/ui.jsx
new file mode 100644
index 0000000..bb79c41
--- /dev/null
+++ b/apps/contacts/ui.jsx
@@ -0,0 +1,354 @@
+// ui.jsx — small widgets shared by Calendar, Contacts and Reminders (each app keeps its own copy,
+// since apps only import from '@lordos/sdk'): popovers drawn above the window, sheets, drop-down
+// choices, a multi-line field, date and time fields with a month picker, and color swatches.
+import {
+ View, Text, useTheme, useStore, createStore, useAppWindow, direction, ScrollView, Button, Hairline, takeTextFocus, releaseTextFocus,
+ weekdayName, formatTime, formatDate, t,
+} from '@lordos/sdk';
+import { useEffect, useRef, useState } from 'react';
+
+export const RED = '#ff3b30';
+export const COLORS = ['#ff3b30', '#ff9500', '#ffcc00', '#34c759', '#30b0c7', '#007aff', '#af52de', '#a2845e'];
+const pad = (n) => String(n).padStart(2, '0');
+
+// ---- dates ----
+
+export const DAY = 86400000;
+export const sod = (d) => { const x = new Date(d); x.setHours(0, 0, 0, 0); return x; };
+export const addDays = (d, n) => { const x = new Date(d); x.setDate(x.getDate() + n); return x; };
+export const addMonths = (d, n) => new Date(d.getFullYear(), d.getMonth() + n, 1);
+export const sameDay = (a, b) => a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();
+export const startOfWeek = (d) => { const x = sod(d); return addDays(x, -((x.getDay() + 6) % 7)); }; // weeks start on Monday
+export const ymd = (d) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
+export const parseYmd = (s) => { const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(s || ''); return m ? new Date(+m[1], +m[2] - 1, +m[3]) : null; };
+export const minutesOf = (d) => d.getHours() * 60 + d.getMinutes();
+export const atMinutes = (day, min) => { const x = sod(day); x.setHours(Math.floor(min / 60), min % 60, 0, 0); return x; };
+export const monthName = (m) => t(`calendar.month.${m}`);
+export const monthYear = (d) => t('calendar.monthYear', { month: monthName(d.getMonth()), year: d.getFullYear() });
+
+// ---- popovers: drawn by <Layers /> (the last child of the app) above everything ----
+
+const layers = createStore([]); // [{ key, win, node }]
+let seq = 0;
+
+export function Popover(props) {
+ const { id: win } = useAppWindow();
+ const key = useRef(null);
+ if (!key.current) key.current = `p${++seq}`;
+ useEffect(() => {
+ const node = <PopBox {...props} />;
+ layers.set((l) => (l.some((x) => x.key === key.current) ? l.map((x) => (x.key === key.current ? { ...x, node } : x)) : [...l, { key: key.current, win, node }]));
+ });
+ useEffect(() => () => layers.set((l) => l.filter((x) => x.key !== key.current)), []);
+ return null;
+}
+
+let origin = null; // the Layers box: [x, y, w, h]
+
+export function Layers() {
+ const { id } = useAppWindow();
+ const all = useStore(layers);
+ const root = useRef(null);
+ const mine = all.filter((x) => x.win === id);
+ if (root.current) { try { origin = lord.getLayout(root.current.id); } catch (e) { /* not laid out yet */ } }
+ return (
+ <>
+ <View ref={root} style={{ position: 'absolute', left: 0, top: 0, right: 0, bottom: 0, pointerEvents: 'none' }} />
+ {mine.map((x) => <View key={x.key} style={{ position: 'absolute', left: 0, top: 0, right: 0, bottom: 0, zIndex: 200 }}>{x.node}</View>)}
+ </>
+ );
+}
+
+function PopBox({ anchor, onClose, width = 240, children, padding = 6 }) {
+ const th = useTheme();
+ const box = useRef(null);
+ const [flip, setFlip] = useState(false);
+ const [, force] = useState(0);
+ const o = origin || [0, 0, 800, 600];
+ let a = null;
+ try { a = anchor?.current ? lord.getLayout(anchor.current.id) : null; } catch (e) { a = null; }
+ useEffect(() => {
+ if (!a) { const id = setTimeout(() => force((v) => v + 1), 16); return () => clearTimeout(id); }
+ if (!box.current) return undefined;
+ const h = lord.getLayout(box.current.id)[3];
+ const below = a[1] - o[1] + a[3] + 4;
+ const want = below + h > o[3] - 6 && a[1] - o[1] - h - 4 > 6;
+ if (want !== flip) setFlip(want);
+ return undefined;
+ });
+ if (!a) return null;
+ const rtl = direction() === 'rtl';
+ const w = Math.min(width, o[2] - 16);
+ let left = rtl ? a[0] - o[0] + a[2] - w : a[0] - o[0];
+ left = Math.max(8, Math.min(o[2] - w - 8, left));
+ const style = { position: 'absolute', left, width: w, padding, borderRadius: 10, backgroundColor: th.mode === 'dark' ? '#2c2c31' : '#ffffff',
+ border: `1px solid ${th.separator}`, boxShadow: '0 12px 32px rgba(0,0,0,0.32)' };
+ if (flip) style.bottom = o[3] - (a[1] - o[1]) + 4; else style.top = a[1] - o[1] + a[3] + 4;
+ return (
+ <>
+ <View onMouseDown={() => onClose?.()} style={{ position: 'absolute', left: 0, top: 0, right: 0, bottom: 0 }} />
+ <View ref={box} style={style}>{children}</View>
+ </>
+ );
+}
+
+// A menu inside a popover: items = [{ label, onClick, checked, destructive, color, disabled } | '-']
+export function MenuList({ items, onDone }) {
+ return items.map((it, i) => (it === '-' ? <Separator key={`s${i}`} /> : <MenuItem key={`${i}${it.label}`} it={it} onDone={onDone} />));
+}
+
+function Separator() {
+ const th = useTheme();
+ return <View style={{ height: 1, marginVertical: 4, marginHorizontal: 6, backgroundColor: th.separator }} />;
+}
+
+function MenuItem({ it, onDone }) {
+ const th = useTheme();
+ const [hover, setHover] = useState(false);
+ const on = hover && !it.disabled;
+ return (
+ <View onClick={() => { if (it.disabled) return; onDone?.(); it.onClick?.(); }} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
+ style={{ height: 26, paddingHorizontal: 8, borderRadius: 5, flexDirection: 'row', alignItems: 'center', gap: 6,
+ backgroundColor: on ? th.accent : 'transparent', opacity: it.disabled ? 0.4 : 1 }}>
+ <Text style={{ width: 12, fontSize: 11, color: on ? '#fff' : th.text }}>{it.checked ? '✓' : ''}</Text>
+ {it.color ? <View style={{ width: 10, height: 10, borderRadius: 5, backgroundColor: it.color }} /> : null}
+ <Text style={{ flex: 1, fontSize: 13, whiteSpace: 'nowrap', overflow: 'hidden', color: on ? '#fff' : it.destructive ? RED : th.text }}>{it.label}</Text>
+ </View>
+ );
+}
+
+// ---- sheet: a modal box centered on the window ----
+
+export function Sheet({ title, onClose, children, footer, width = 440 }) {
+ const th = useTheme();
+ return (
+ <View onMouseDown={(e) => e.stopPropagation?.()} style={{ position: 'absolute', left: 0, top: 0, right: 0, bottom: 0, zIndex: 100,
+ alignItems: 'center', justifyContent: 'center', backgroundColor: 'rgba(0,0,0,0.3)' }}>
+ <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>
+ ) : null}
+ <View style={{ paddingHorizontal: 16, paddingVertical: 10, gap: 10, flexShrink: 1 }}>{children}</View>
+ {footer ? (
+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 8, paddingHorizontal: 16, paddingVertical: 12 }}>
+ <Hairline edge="top" />
+ {footer}
+ </View>
+ ) : null}
+ </View>
+ </View>
+ );
+}
+
+// label | control row for sheets and inspectors
+export function Field({ label, children, width = 86, top }) {
+ const th = useTheme();
+ return (
+ <View style={{ flexDirection: 'row', alignItems: top ? 'flex-start' : 'center', gap: 10, minHeight: 28 }}>
+ <Text style={{ width, fontSize: 12, color: th.textDim, textAlign: 'end', marginTop: top ? 6 : 0 }}>{label}</Text>
+ <View style={{ flex: 1, flexDirection: 'row', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>{children}</View>
+ </View>
+ );
+}
+
+// ---- drop-down choice: options = [[value, label, color?]] ----
+
+export function Choice({ value, options, onChange, width = 180, height }) {
+ const th = useTheme();
+ const ref = useRef(null);
+ const scroll = useRef(null);
+ const [open, setOpen] = useState(false);
+ const cur = options.find((o) => o[0] === value);
+ const long = height || options.length > 12;
+ useEffect(() => {
+ if (!open || !long) return undefined;
+ const i = options.findIndex((o) => o[0] === value);
+ const id = setTimeout(() => scroll.current?.scrollTo(Math.max(0, i * 26 - 100)), 40);
+ return () => clearTimeout(id);
+ }, [open]);
+ const list = options.map(([v, label, color]) => ({ label, color, checked: v === value, onClick: () => onChange(v) }));
+ return (
+ <View ref={ref} style={{ width }}>
+ <View onClick={() => setOpen(!open)} style={{ height: 26, paddingHorizontal: 9, borderRadius: 6, flexDirection: 'row', alignItems: 'center', gap: 6,
+ backgroundColor: th.control }}>
+ {cur && cur[2] ? <View style={{ width: 10, height: 10, borderRadius: 5, backgroundColor: cur[2] }} /> : null}
+ <Text style={{ flex: 1, fontSize: 13, color: th.text, whiteSpace: 'nowrap', overflow: 'hidden' }}>{cur ? cur[1] : ''}</Text>
+ <Text style={{ fontSize: 9, color: th.textDim }}>▼</Text>
+ </View>
+ {open && (
+ <Popover anchor={ref} width={Math.max(width, 170)} onClose={() => setOpen(false)}>
+ {long ? (
+ <View style={{ height: height || 260 }}>
+ <ScrollView scrollRef={scroll} style={{ flex: 1 }}><MenuList items={list} onDone={() => setOpen(false)} /></ScrollView>
+ </View>
+ ) : <MenuList items={list} onDone={() => setOpen(false)} />}
+ </Popover>
+ )}
+ </View>
+ );
+}
+
+// ---- multi-line text field ----
+
+export function TextArea({ value, onChange, placeholder, minHeight = 64 }) {
+ const th = useTheme();
+ const token = useRef({}).current;
+ const [focus, setFocus] = useState(false);
+ const [blink, setBlink] = useState(true);
+ const latest = useRef();
+ latest.current = { value: value || '', onChange };
+ useEffect(() => () => releaseTextFocus(token), []);
+ useEffect(() => {
+ if (!focus) return undefined;
+ const id = setInterval(() => setBlink((b) => !b), 530);
+ return () => clearInterval(id);
+ }, [focus]);
+ const onKey = (e) => {
+ const { value: v, onChange: set } = latest.current;
+ if ((e.ctrl || e.meta) && e.base === 'v') { try { set(v + lord.clipboard.get()); } catch (err) { /* no clipboard */ } return; }
+ if (e.key === 'Backspace') set([...v].slice(0, -1).join(''));
+ else if (e.key === 'Enter') set(`${v}\n`);
+ else if (e.key === 'Escape') { releaseTextFocus(token); setFocus(false); }
+ else if (e.char && !e.ctrl && !e.meta) set(v + e.char);
+ setBlink(true);
+ };
+ const caret = focus && blink ? '▏' : '';
+ return (
+ <View onMouseDown={() => { takeTextFocus(token, onKey, () => setFocus(false)); setFocus(true); }}
+ style={{ flex: 1, minHeight, padding: 7, borderRadius: 7, backgroundColor: th.inputBg, border: `1px solid ${focus ? th.accent : th.separator}` }}>
+ {value ? <Text style={{ fontSize: 13, color: th.text, lineHeight: 18 }}>{`${value}${caret}`}</Text>
+ : <Text style={{ fontSize: 13, color: th.textDim }}>{focus ? caret || ' ' : placeholder || ''}</Text>}
+ </View>
+ );
+}
+
+// ---- month grid picker ----
+
+export function MiniMonth({ value, onPick, marks, month: ctlMonth, onMonth, cell = 26, today = new Date() }) {
+ const th = useTheme();
+ const [own, setOwn] = useState(() => new Date((value || today).getFullYear(), (value || today).getMonth(), 1));
+ const month = ctlMonth || own;
+ const setMonth = (m) => (onMonth ? onMonth(m) : setOwn(m));
+ const rtl = direction() === 'rtl';
+ const first = startOfWeek(month);
+ const rows = [];
+ for (let r = 0; r < 6; r++) {
+ const cells = [];
+ for (let c = 0; c < 7; c++) {
+ const d = addDays(first, r * 7 + c);
+ const sel = value && sameDay(d, value), isToday = sameDay(d, today), inMonth = d.getMonth() === month.getMonth();
+ cells.push(
+ <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,
+ 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}
+ </View>,
+ );
+ }
+ rows.push(<View key={r} style={{ flexDirection: 'row' }}>{cells}</View>);
+ }
+ return (
+ <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>
+ <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))} />
+ </View>
+ <View style={{ flexDirection: 'row' }}>
+ {[1, 2, 3, 4, 5, 6, 0].map((wd) => (
+ <Text key={wd} style={{ width: cell, textAlign: 'center', fontSize: 10, fontWeight: 600, color: th.textDim }}>{[...weekdayName(wd)][0] || ''}</Text>
+ ))}
+ </View>
+ {rows}
+ </View>
+ );
+}
+
+function NavArrow({ glyph, onClick, small }) {
+ const th = useTheme();
+ const [hover, setHover] = useState(false);
+ return (
+ <View onClick={onClick} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
+ style={{ width: 20, height: 20, borderRadius: 5, alignItems: 'center', justifyContent: 'center', backgroundColor: hover ? th.hover : 'transparent' }}>
+ <Text style={{ fontSize: small ? 7 : 15, color: th.textDim }}>{glyph}</Text>
+ </View>
+ );
+}
+
+// ---- date and time fields ----
+
+export function DateField({ value, onChange, width = 120 }) {
+ const th = useTheme();
+ const ref = useRef(null);
+ const [open, setOpen] = useState(false);
+ return (
+ <View ref={ref}>
+ <View onClick={() => setOpen(!open)} style={{ width, height: 26, paddingHorizontal: 9, borderRadius: 6, justifyContent: 'center', backgroundColor: th.control }}>
+ <Text style={{ fontSize: 13, color: th.text, whiteSpace: 'nowrap' }}>{value ? formatDate(value, 'numeric') : ''}</Text>
+ </View>
+ {open && (
+ <Popover anchor={ref} width={7 * 28 + 16} padding={8} onClose={() => setOpen(false)}>
+ <MiniMonth value={value} cell={28} onPick={(d) => { setOpen(false); onChange(d); }} />
+ </Popover>
+ )}
+ </View>
+ );
+}
+
+// minutes since midnight, every 15 minutes (and the current value if it is not on the grid)
+export function TimeField({ value, onChange, width = 100 }) {
+ const opts = [];
+ for (let m = 0; m < 1440; m += 15) opts.push(m);
+ if (!opts.includes(value)) { opts.push(value); opts.sort((a, b) => a - b); }
+ return <Choice width={width} value={value} onChange={onChange} options={opts.map((m) => [m, formatTime(atMinutes(new Date(2000, 0, 3), m))])} />;
+}
+
+// ---- colors ----
+
+export function ColorSwatches({ value, onChange, colors = COLORS }) {
+ const th = useTheme();
+ return (
+ <View style={{ flexDirection: 'row', gap: 8, flexWrap: 'wrap' }}>
+ {colors.map((c) => (
+ <View key={c} onClick={() => onChange(c)} style={{ width: 24, height: 24, borderRadius: 12, alignItems: 'center', justifyContent: 'center',
+ border: `2px solid ${value === c ? th.text : 'transparent'}` }}>
+ <View style={{ width: 18, height: 18, borderRadius: 9, backgroundColor: c }} />
+ </View>
+ ))}
+ </View>
+ );
+}
+
+// square check box filled with a color when on
+export function ColorCheck({ on, color, onClick, size = 14 }) {
+ return (
+ <View onClick={onClick} style={{ width: size, height: size, borderRadius: 4, alignItems: 'center', justifyContent: 'center',
+ border: `1.5px solid ${color}`, backgroundColor: on ? color : 'transparent' }}>
+ {on ? <Text style={{ fontSize: size - 4, fontWeight: 700, color: '#fff' }}>✓</Text> : null}
+ </View>
+ );
+}
+
+// a promise-returning loader that re-runs when deps change: { data, error }
+export function useLoad(fn, deps) {
+ const [st, setSt] = useState({ data: null, error: null });
+ useEffect(() => {
+ let live = true;
+ Promise.resolve().then(fn).then((data) => { if (live) setSt({ data, error: null }); }).catch((error) => { if (live) setSt((s) => ({ data: s.data, error })); });
+ return () => { live = false; };
+ }, deps);
+ return st;
+}
+
+export function useNow(ms = 30000) {
+ const [now, setNow] = useState(Date.now());
+ useEffect(() => { const id = setInterval(() => setNow(Date.now()), ms); return () => clearInterval(id); }, [ms]);
+ return now;
+}
diff --git a/apps/installer/index.jsx b/apps/installer/index.jsx
index e557d25..70e4648 100644
--- a/apps/installer/index.jsx
+++ b/apps/installer/index.jsx
@@ -1,10 +1,10 @@
-// Instalar LordOS — asistente para instalar el sistema en vivo (ISO) en el disco.
-// Solo aparece en el live ("live": true en el manifest). Lo que necesita root lo hace el
-// ayudante de administración con acciones cerradas (server/src/install): install-disks,
-// install-run (valida todo de nuevo del lado root) e install-reboot. Ver docs/ISO.md.
+// Install LordOS: a wizard that installs the live system (ISO) on the disk.
+// It only shows up in the live session ("live": true in the manifest). What needs root is done by
+// the administration helper with closed actions (server/src/install): install-disks, install-run
+// (validates everything again on the root side) and install-reboot. See docs/ISO.md.
import {
- View, Text, Button, TextInput, ScrollView, Toggle, Segmented, useTheme, useLocale, useStore, createStore,
- admin, keyboard, languages, setLanguage, formatBytes, locale, wm, useAppWindow,
+ View, Text, Button, TextInput, ScrollView, Toggle, Segmented, SearchField, Hairline, GroupBox, FormRow, useTheme, useLocale, useStore, createStore,
+ admin, keyboard, languages, setLanguage, formatBytes, locale, wm, useAppWindow, typeScale,
} from '@lordos/sdk';
import { useEffect, useState } from 'react';
@@ -12,11 +12,11 @@ export function Icon({ size: s }) {
return (
<View style={{ width: s, height: s, borderRadius: s * 0.225, background: 'linear-gradient(180deg, #5eead4, #0f766e)',
boxShadow: `0 ${s * 0.04}px ${s * 0.12}px rgba(0,0,0,0.35)`, alignItems: 'center' }}>
- {/* flecha hacia abajo */}
+ {/* down arrow */}
<View style={{ position: 'absolute', top: s * 0.14, left: s * 0.44, width: s * 0.12, height: s * 0.3, borderRadius: s * 0.03, backgroundColor: '#fff' }} />
<View style={{ position: 'absolute', top: s * 0.38, left: s * 0.35, width: s * 0.3, height: s * 0.09, borderRadius: s * 0.045, backgroundColor: '#fff' }} />
<View style={{ position: 'absolute', top: s * 0.45, left: s * 0.42, width: s * 0.16, height: s * 0.07, borderRadius: s * 0.035, backgroundColor: '#fff' }} />
- {/* el disco */}
+ {/* the disk */}
<View style={{ position: 'absolute', bottom: s * 0.14, left: s * 0.16, right: s * 0.16, height: s * 0.22, borderRadius: s * 0.06, backgroundColor: '#fff' }}>
<View style={{ position: 'absolute', right: s * 0.07, top: s * 0.08, width: s * 0.06, height: s * 0.06, borderRadius: s * 0.03, backgroundColor: '#22c55e' }} />
<View style={{ position: 'absolute', left: s * 0.07, top: s * 0.095, width: s * 0.3, height: s * 0.03, borderRadius: s * 0.015, backgroundColor: '#99f6e4' }} />
@@ -25,7 +25,7 @@ export function Icon({ size: s }) {
);
}
-// Estado del asistente: sobrevive a que la interfaz se vuelva a montar al cambiar el idioma.
+// Wizard state: it survives the UI remounting when the language changes.
const wiz = createStore({
step: 0, lang: '', region: '', zone: '', kb: null, disk: null, confirmDisk: '', confirmBox: false, swap: 2048,
fullname: '', user: '', userEdited: false, host: '', hostEdited: false, pass: '', pass2: '',
@@ -44,21 +44,22 @@ const STEPS = ['welcome', 'language', 'keyboard', 'disk', 'user', 'summary', 'in
function Card({ children, style }) {
const t = useTheme();
- return <View style={[{ padding: 14, borderRadius: 10, backgroundColor: t.hover, border: `1px solid ${t.separator}`, gap: 8 }, style]}>{children}</View>;
+ return <View style={[{ padding: 16, borderRadius: 10, backgroundColor: t.hover, border: `1px solid ${t.separator}`, gap: 8 }, style]}>{children}</View>;
}
function Field({ label, children, hint, error }) {
const t = useTheme();
return (
- <View style={{ gap: 4, marginBottom: 10 }}>
- <Text style={{ fontSize: 12, fontWeight: 600, color: t.text }}>{label}</Text>
+ <View style={{ gap: 6, marginBottom: 16 }}>
+ <Text style={{ fontSize: typeScale.callout, fontWeight: 600, color: t.text }}>{label}</Text>
{children}
- {error ? <Text style={{ fontSize: 11, color: '#ff453a' }}>{error}</Text> : hint ? <Text style={{ fontSize: 11, color: t.textDim }}>{hint}</Text> : null}
+ {error ? <Text style={{ fontSize: typeScale.caption, color: '#ff453a', lineHeight: 1.35 }}>{error}</Text>
+ : hint ? <Text style={{ fontSize: typeScale.caption, color: t.textDim, lineHeight: 1.35 }}>{hint}</Text> : null}
</View>
);
}
-// Lista con búsqueda (regiones, zonas, distribuciones).
+// A list with search (regions, zones, layouts).
function Pick({ items, value, onPick, placeholder, height = 170 }) {
const t = useTheme();
const [q, setQ] = useState('');
@@ -66,13 +67,13 @@ function Pick({ items, value, onPick, placeholder, height = 170 }) {
const shown = (n ? items.filter(([id, label]) => `${id} ${label}`.toLowerCase().includes(n)) : items).slice(0, 300);
return (
<View style={{ gap: 6 }}>
- <TextInput value={q} onChange={setQ} placeholder={placeholder} onCancel={() => setQ('')} />
- <View style={{ height, borderRadius: 8, border: `1px solid ${t.separator}` }}>
+ <SearchField value={q} onChange={setQ} placeholder={placeholder} />
+ <View style={{ height, borderRadius: 8, border: `1px solid ${t.separator}`, backgroundColor: t.mode === 'dark' ? 'rgba(255,255,255,0.03)' : 'rgba(0,0,0,0.02)' }}>
<ScrollView style={{ padding: 4 }}>
{shown.map(([id, label]) => (
<View key={id} onClick={() => onPick(id)} style={{ height: 24, justifyContent: 'center', paddingHorizontal: 8, borderRadius: 5,
backgroundColor: id === value ? t.accent : 'transparent' }}>
- <Text style={{ fontSize: 12, color: id === value ? '#fff' : t.text, whiteSpace: 'nowrap' }}>{label}</Text>
+ <Text style={{ fontSize: typeScale.callout, color: id === value ? '#fff' : t.text, whiteSpace: 'nowrap' }}>{label}</Text>
</View>
))}
</ScrollView>
@@ -81,15 +82,15 @@ function Pick({ items, value, onPick, placeholder, height = 170 }) {
);
}
-// ---- pasos ----
+// ---- steps ----
function Welcome() {
const t = useTheme();
const { t: tr } = useLocale();
return (
- <View style={{ alignItems: 'center', gap: 14, paddingTop: 30 }}>
+ <View style={{ alignItems: 'center', gap: 12, paddingTop: 40 }}>
<Icon size={96} />
- <Text style={{ fontSize: 26, fontWeight: 700, color: t.text }}>{tr('installer.welcome.title')}</Text>
+ <Text style={{ fontSize: 26, fontWeight: 600, color: t.text, marginTop: 8 }}>{tr('installer.welcome.title')}</Text>
<Text style={{ fontSize: 13, color: t.textDim, textAlign: 'center', maxWidth: 480, lineHeight: 1.45 }}>{tr('installer.welcome.text')}</Text>
{!admin.available() && <Text style={{ fontSize: 12, color: '#ff453a' }}>{tr('installer.needAdmin')}</Text>}
</View>
@@ -107,18 +108,18 @@ function Language() {
return (
<View>
<Field label={tr('installer.language.language')}>
- <Pick items={langs.map((l) => [l.id, l.english ? `${l.name} · ${l.english}` : l.name])} value={lang} height={110}
+ <Pick items={langs.map((l) => [l.id, l.english ? `${l.name} · ${l.english}` : l.name])} value={lang} height={100}
placeholder={tr('installer.search')} onPick={(id) => { set({ lang: id, region: '' }); setLanguage(id); }} />
</Field>
- <View style={{ flexDirection: 'row', gap: 14 }}>
- <View style={{ flex: 1 }}>
+ <View style={{ flexDirection: 'row', gap: 16 }}>
+ <View style={{ flex: 1, minWidth: 0 }}>
<Field label={tr('installer.language.region')} hint={tr('installer.language.regionHint')}>
- <Pick items={regions} value={s.region} onPick={(region) => set({ region })} placeholder={tr('installer.search')} height={130} />
+ <Pick items={regions} value={s.region} onPick={(region) => set({ region })} placeholder={tr('installer.search')} height={116} />
</Field>
</View>
- <View style={{ flex: 1 }}>
+ <View style={{ flex: 1, minWidth: 0 }}>
<Field label={tr('installer.language.zone')}>
- <Pick items={zones.map((z) => [z, z.replace(/_/g, ' ')])} value={s.zone} onPick={(zone) => set({ zone })} placeholder={tr('installer.search')} height={130} />
+ <Pick items={zones.map((z) => [z, z.replace(/_/g, ' ')])} value={s.zone} onPick={(zone) => set({ zone })} placeholder={tr('installer.search')} height={116} />
</Field>
</View>
</View>
@@ -134,13 +135,13 @@ function Keyboard() {
const cur = s.kb || keyboard.active() || { layout: 'us', variant: '' };
const id = cur.variant ? `${cur.layout}(${cur.variant})` : cur.layout;
const all2 = all.flatMap((l) => [[l.id, l.name], ...l.variants.map((v) => [`${l.id}(${v.id})`, `${l.name} — ${v.name}`])]);
- const items = [...all2.filter(([k]) => k === id), ...all2.filter(([k]) => k !== id)]; // la actual, primero
+ const items = [...all2.filter(([k]) => k === id), ...all2.filter(([k]) => k !== id)]; // the current one first
const pick = (v) => {
const m = /^([\w-]+)(?:\(([\w-]+)\))?$/.exec(v);
if (!m) return;
const kb = { layout: m[1], variant: m[2] || '' };
set({ kb });
- keyboard.set([kb]); // también en la sesión en vivo, para probarlo
+ keyboard.set([kb]); // also in the live session, to try it
};
return (
<View>
@@ -163,23 +164,23 @@ function DiskStep() {
const load = () => {
const found = [];
setDisks(null);
- admin.run('install-disks', '', (l) => { try { found.push(JSON.parse(l)); } catch (e) { /* texto */ } }, { quiet: true })
+ admin.run('install-disks', '', (l) => { try { found.push(JSON.parse(l)); } catch (e) { /* plain text */ } }, { quiet: true })
.then(() => setDisks(found), (e) => { setErr(e.message); setDisks([]); });
};
useEffect(load, []);
const content = (d) => (d.parts.length ? d.parts.map((p) => [p.label || p.name, p.fstype, formatBytes(p.size)].filter(Boolean).join(' ')).join(' · ')
: tr('installer.disk.empty'));
return (
- <View style={{ gap: 10 }}>
+ <View style={{ gap: 12 }}>
{err && <Text style={{ fontSize: 12, color: '#ff453a' }}>{err}</Text>}
{disks === null && <Text style={{ fontSize: 12, color: t.textDim }}>{tr('installer.disk.loading')}</Text>}
{disks && disks.length === 0 && !err && <Text style={{ fontSize: 13, color: t.text }}>{tr('installer.disk.none')}</Text>}
{(disks || []).map((d) => (
<View key={d.name} onClick={() => d.usable && set({ disk: d, confirmDisk: '', confirmBox: false })}
- style={{ padding: 12, borderRadius: 10, gap: 4, opacity: d.usable ? 1 : 0.5,
+ style={{ padding: 14, borderRadius: 10, gap: 4, opacity: d.usable ? 1 : 0.5,
border: `2px solid ${s.disk?.name === d.name ? t.accent : t.separator}`, backgroundColor: t.hover }}>
<View style={{ flexDirection: 'row', alignItems: 'center', gap: 10 }}>
- <Text style={{ flex: 1, fontSize: 14, fontWeight: 700, color: t.text }}>{[d.vendor, d.model].filter(Boolean).join(' ') || d.name}</Text>
+ <Text style={{ flex: 1, fontSize: typeScale.body, fontWeight: 600, color: t.text }}>{[d.vendor, d.model].filter(Boolean).join(' ') || d.name}</Text>
<Text style={{ fontSize: 13, fontWeight: 600, color: t.text }}>{formatBytes(d.size)}</Text>
</View>
<Text style={{ fontSize: 11, color: t.textDim }}>{`${d.path} · ${d.transport.toUpperCase()}${d.removable ? ` · ${tr('installer.disk.removable')}` : ''}`}</Text>
@@ -189,7 +190,7 @@ function DiskStep() {
))}
{s.disk && (
<Card style={{ borderColor: '#ff453a' }}>
- <Text style={{ fontSize: 13, fontWeight: 700, color: '#ff453a' }}>{tr('installer.disk.eraseTitle', { disk: s.disk.path })}</Text>
+ <Text style={{ fontSize: typeScale.body, fontWeight: 600, color: '#ff453a' }}>{tr('installer.disk.eraseTitle', { disk: s.disk.path })}</Text>
<Text style={{ fontSize: 12, color: t.text, lineHeight: 1.4 }}>{tr('installer.disk.eraseText')}</Text>
<View style={{ flexDirection: 'row', alignItems: 'center', gap: 10 }}>
<Toggle on={s.confirmBox} onChange={(confirmBox) => set({ confirmBox })} />
@@ -252,7 +253,7 @@ function UserStep() {
);
}
-// Nombre de la distribución para el resumen ("Spanish (Latin American)"), como lo da xkb.
+// Layout name for the summary ("Spanish (Latin American)"), as xkb gives it.
const kbName = (kb) => {
const l = keyboard.list().find((x) => x.id === kb.layout);
const v = l?.variants.find((x) => x.id === kb.variant);
@@ -284,16 +285,15 @@ function Summary() {
[tr('installer.summary.host'), s.host],
];
return (
- <View style={{ gap: 10 }}>
- <View style={{ borderRadius: 10, border: `1px solid ${t.separator}`, backgroundColor: t.hover }}>
- {rows.map(([k, v], i) => (
- <View key={k} style={{ flexDirection: 'row', paddingHorizontal: 12, paddingVertical: 9, gap: 12, borderTop: i ? `1px solid ${t.separator}` : '0 solid transparent' }}>
- <Text style={{ width: 150, fontSize: 12, color: t.textDim }}>{k}</Text>
- <Text style={{ flex: 1, fontSize: 12, color: t.text }}>{v}</Text>
- </View>
+ <View style={{ gap: 12 }}>
+ <GroupBox>
+ {rows.map(([k, v]) => (
+ <FormRow key={k} label={k} labelWidth={140} minHeight={34}>
+ <Text style={{ fontSize: typeScale.callout, color: t.text, lineHeight: 1.35 }}>{v}</Text>
+ </FormRow>
))}
- </View>
- <Text style={{ fontSize: 11, color: t.textDim, lineHeight: 1.4 }}>{tr('installer.summary.login')}</Text>
+ </GroupBox>
+ <Text style={{ fontSize: typeScale.caption, color: t.textDim, lineHeight: 1.4, paddingHorizontal: 8 }}>{tr('installer.summary.login')}</Text>
</View>
);
}
@@ -315,9 +315,9 @@ function Install() {
const s = useStore(wiz);
const f = s.done ? 1 : overall(s.progress);
return (
- <View style={{ gap: 14, paddingTop: 20, alignItems: 'center' }}>
+ <View style={{ gap: 14, paddingTop: 32, alignItems: 'center' }}>
<Icon size={72} />
- <Text style={{ fontSize: 20, fontWeight: 700, color: t.text }}>
+ <Text style={{ fontSize: typeScale.largeTitle, fontWeight: 600, color: t.text }}>
{s.done ? tr('installer.done.title') : s.error ? tr('installer.error.title') : tr('installer.install.title')}</Text>
{!s.error && (
<View style={{ width: 460, gap: 6 }}>
@@ -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: 10, 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' }}>{l}</Text>)}
</View>
{s.done && <Text style={{ fontSize: 12, color: t.text, maxWidth: 480, textAlign: 'center' }}>{tr('installer.done.usb')}</Text>}
</View>
@@ -345,7 +345,7 @@ function startInstall() {
disk: s.disk.name, user: s.user, fullname: s.fullname.trim(), password: s.pass, hostname: s.host,
lang: p.lang, locale: `${p.region}.UTF-8`, timezone: p.zone, kblayout: p.kb.layout, kbvariant: p.kb.variant || '', swap: s.swap,
};
- set({ pass: '', pass2: '' }); // la contraseña no queda en la interfaz
+ set({ pass: '', pass2: '' }); // the password doesn't stay in the UI
admin.run('install-run', JSON.stringify(job), (line) => {
const m = /^progress (\w+) (\d+) (\d+)$/.exec(line);
if (m) set({ progress: { phase: m[1], done: Number(m[2]), total: Number(m[3]) } });
@@ -370,32 +370,34 @@ export default function Installer() {
const steps = STEPS.slice(1, 6);
return (
<View style={{ flex: 1, flexDirection: 'row' }}>
- <View style={{ width: 190, backgroundColor: t.sidebarBg, padding: 14, gap: 6 }}>
- <Text style={{ fontSize: 13, fontWeight: 700, color: t.text, marginBottom: 8 }}>{tr('installer.title')}</Text>
+ <View style={{ width: 200, backgroundColor: t.sidebarBg, paddingHorizontal: 16, paddingTop: 20, gap: 4 }}>
+ <Hairline edge="end" />
+ <Text style={{ fontSize: typeScale.body, fontWeight: 600, color: t.text, marginBottom: 12, paddingHorizontal: 4 }}>{tr('installer.title')}</Text>
{steps.map((st) => {
const i = STEPS.indexOf(st);
const cur = i === s.step, past = i < s.step;
return (
- <View key={st} style={{ flexDirection: 'row', alignItems: 'center', gap: 8, height: 26 }}>
- <View style={{ width: 18, height: 18, borderRadius: 9, alignItems: 'center', justifyContent: 'center',
+ <View key={st} style={{ flexDirection: 'row', alignItems: 'center', gap: 10, height: 30, paddingHorizontal: 4, borderRadius: 6,
+ backgroundColor: cur ? t.hover : 'transparent' }}>
+ <View style={{ width: 20, height: 20, borderRadius: 10, alignItems: 'center', justifyContent: 'center',
backgroundColor: cur ? t.accent : past ? '#30d158' : t.control }}>
- <Text style={{ fontSize: 10, fontWeight: 700, color: cur || past ? '#fff' : t.textDim }}>{past ? '✓' : String(i)}</Text>
+ <Text style={{ fontSize: 11, fontWeight: 600, color: cur || past ? '#fff' : t.textDim }}>{past ? '✓' : String(i)}</Text>
</View>
- <Text style={{ fontSize: 12, fontWeight: cur ? 700 : 500, color: cur ? t.text : t.textDim }}>{tr(`installer.step.${st}`)}</Text>
+ <Text style={{ flex: 1, fontSize: typeScale.body, fontWeight: cur ? 600 : 400, color: cur ? t.text : t.textDim, whiteSpace: 'nowrap', overflow: 'hidden' }}>{tr(`installer.step.${st}`)}</Text>
</View>
);
})}
</View>
- <View style={{ flex: 1 }}>
- <ScrollView style={{ flex: 1, paddingHorizontal: 22, paddingTop: 18 }}>
- {name !== 'welcome' && name !== 'install' && <Text style={{ fontSize: 20, fontWeight: 700, color: t.text, marginBottom: 12 }}>{tr(`installer.step.${name}`)}</Text>}
+ <View style={{ flex: 1, minWidth: 0 }}>
+ <ScrollView style={{ flex: 1, paddingHorizontal: 24, paddingTop: 20 }}>
+ {name !== 'welcome' && name !== 'install' && <Text style={{ fontSize: typeScale.largeTitle, fontWeight: 600, color: t.text, marginBottom: 16 }}>{tr(`installer.step.${name}`)}</Text>}
<Body />
</ScrollView>
- <View style={{ flexDirection: 'row', justifyContent: 'flex-end', gap: 8, padding: 14, borderTop: `1px solid ${t.separator}` }}>
+ <View style={{ flexDirection: 'row', justifyContent: 'flex-end', gap: 8, paddingHorizontal: 16, paddingVertical: 14 }}>
+ <Hairline edge="top" />
{name !== 'install' && s.step > 0 && <Button label={tr('installer.back')} onClick={() => set({ step: s.step - 1 })} />}
{name === 'summary' && <Button primary label={tr('installer.summary.install')} onClick={startInstall} />}
- {name !== 'summary' && name !== 'install' && <Button primary label={tr('installer.next')} onClick={() => canNext && set({ step: s.step + 1 })}
- style={{ opacity: canNext ? 1 : 0.4 }} />}
+ {name !== 'summary' && name !== 'install' && <Button primary disabled={!canNext} label={tr('installer.next')} onClick={() => canNext && set({ step: s.step + 1 })} />}
{name === 'install' && s.error && <Button label={tr('installer.back')} onClick={() => set({ step: STEPS.indexOf('summary'), error: null })} />}
{name === 'install' && s.done && <Button primary label={s.rebooting ? tr('installer.done.rebooting') : tr('installer.done.reboot')}
onClick={() => { if (!s.rebooting) { set({ rebooting: true }); admin.run('install-reboot').catch((e) => set({ rebooting: false, error: e.message })); } }} />}
diff --git a/apps/mail/BodyEditor.jsx b/apps/mail/BodyEditor.jsx
new file mode 100644
index 0000000..dd0a8f0
--- /dev/null
+++ b/apps/mail/BodyEditor.jsx
@@ -0,0 +1,401 @@
+// BodyEditor — the message editor of Mail's compose window: a multi-line editor with wrapping,
+// one caret with selection, undo, and markdown shortcuts (Ctrl+B, Ctrl+I, Ctrl+K, lists). It is
+// the editor of the Notes app (apps/notes/NoteEditor.jsx), kept as a copy because apps cannot
+// import each other; the font is monospaced so every width is measured once per character.
+import { View, Text, ime, clipboard, takeTextFocus, releaseTextFocus, textFocusOwner, addListener } from '@lordos/sdk';
+import { useEffect, useRef, useState } from 'react';
+
+const MONO = 1400;
+const charW = new Map();
+const cw = (ch, size) => {
+ const k = `${size}:${ch}`;
+ if (!charW.has(k)) charW.set(k, ch === '\t' ? lord.measureText(' ', size, MONO) : lord.measureText(ch, size, MONO) || size * 0.6);
+ return charW.get(k);
+};
+const WORD = /[\p{L}\p{N}_]/u;
+
+// Visual rows: [{ start, end, line }] (end excludes the line break).
+function wrapRows(text, width, size) {
+ const rows = [];
+ let off = 0;
+ const lines = text.split('\n');
+ lines.forEach((ln, li) => {
+ if (!ln.length) { rows.push({ start: off, end: off, line: li }); off += 1; return; }
+ let rs = 0, w = 0, lastSpace = -1;
+ for (let i = 0; i < ln.length;) {
+ const cp = ln.codePointAt(i);
+ const n = cp > 0xffff ? 2 : 1;
+ const ch = ln.slice(i, i + n);
+ const adv = cw(ch, size);
+ if (w + adv > width && i > rs) {
+ const cut = lastSpace >= rs ? lastSpace + 1 : i;
+ rows.push({ start: off + rs, end: off + cut, line: li });
+ w = 0;
+ for (let j = cut; j < i;) { const c2 = ln.codePointAt(j); const n2 = c2 > 0xffff ? 2 : 1; w += cw(ln.slice(j, j + n2), size); j += n2; }
+ rs = cut;
+ lastSpace = -1;
+ }
+ if (ch === ' ') lastSpace = i;
+ w += adv;
+ i += n;
+ }
+ rows.push({ start: off + rs, end: off + ln.length, line: li });
+ off += ln.length + 1;
+ });
+ return rows;
+}
+
+const widthOf = (s, size) => { let w = 0; for (const ch of s) w += cw(ch, size); return w; };
+
+// Style of a line from its markdown (the editor does not highlight inside a line).
+function lineStyle(s, inCode) {
+ if (inCode || /^(`{3,}|~{3,})/.test(s)) return 'code';
+ const h = /^(#{1,6})\s/.exec(s);
+ if (h) return `h${h[1].length}`;
+ if (/^\s*>/.test(s)) return 'quote';
+ if (/^\s*([-*+]|\d+[.)])\s+\[[ xX]\]/.test(s)) return 'task';
+ if (/^\s*([-*+]|\d+[.)])\s/.test(s)) return 'list';
+ return 'text';
+}
+
+export function BodyEditor({ value, onChange, size = 14, colors, onPasteImage, emojiSearch, onEscape, autoFocus, padding = 10, apiRef, onBlur, onCommand }) {
+ const area = useRef(null);
+ const token = useRef({}).current;
+ const st = useRef({ undo: [], redo: [], last: 0, w: 300, h: 200 });
+ const [sel, setSel] = useState({ a: value.length, b: value.length });
+ const [scroll, setScroll] = useState(0);
+ const [focus, setFocusState] = useState(false);
+ const [blink, setBlink] = useState(true);
+ const [dims, setDims] = useState({ w: 300, h: 200 });
+ const [sugg, setSugg] = useState(null); // { q, start, items, i }
+ const LH = Math.round(size * 1.55);
+ const text = value;
+
+ const readSize = () => {
+ if (!area.current) return;
+ const [, , w, h] = lord.getLayout(area.current.id);
+ if (Math.abs(w - st.current.w) > 0.5 || Math.abs(h - st.current.h) > 0.5) { st.current.w = w; st.current.h = h; setDims({ w, h }); }
+ };
+ useEffect(() => { readSize(); const id = setInterval(readSize, 400); return () => clearInterval(id); }, []);
+
+ const rows = wrapRows(text, Math.max(40, dims.w - padding * 2 - 6), size);
+ const rowOf = (off) => {
+ for (let r = 0; r < rows.length; r++) {
+ const row = rows[r];
+ const next = rows[r + 1];
+ if (off >= row.start && (off < row.end || (off === row.end && (!next || next.line !== row.line || next.start > off)))) return r;
+ if (off === row.end && next && next.line === row.line && next.start === off) return r + 1;
+ }
+ return rows.length - 1;
+ };
+ const xOf = (off) => { const r = rows[rowOf(off)]; return widthOf(text.slice(r.start, off), size); };
+ const offAt = (x, y) => {
+ const r = Math.max(0, Math.min(rows.length - 1, Math.floor(y / LH)));
+ const row = rows[r];
+ const s = text.slice(row.start, row.end);
+ let w = 0;
+ for (let i = 0; i < s.length;) {
+ const cp = s.codePointAt(i);
+ const n = cp > 0xffff ? 2 : 1;
+ const adv = cw(s.slice(i, i + n), size);
+ if (x < w + adv / 2) return row.start + i;
+ w += adv;
+ i += n;
+ }
+ return row.end;
+ };
+
+ // ---- editing ----
+ const lo = Math.min(sel.a, sel.b), hi = Math.max(sel.a, sel.b);
+ const pushUndo = (kind) => {
+ const now = Date.now(), s = st.current;
+ if (kind !== 'type' || now - s.last > 900 || s.kind !== kind) s.undo.push({ text, sel });
+ if (s.undo.length > 300) s.undo.shift();
+ s.last = now;
+ s.kind = kind;
+ s.redo = [];
+ };
+ const ensureVisible = (off) => {
+ const y = rowOf(off) * LH, h = st.current.h - padding * 2;
+ setScroll((t) => (y < t ? y : y + LH > t + h ? y + LH - h : t));
+ };
+ const commit = (next, a, b = a, kind = 'edit') => {
+ pushUndo(kind);
+ onChange(next);
+ setSel({ a, b });
+ setBlink(true);
+ setTimeout(() => ensureVisible(b), 0);
+ // emoji suggestions: ":" + name right before the caret
+ const m = /(^|[\s(])(:[a-z0-9_+-]{2,24})$/.exec(next.slice(Math.max(0, b - 26), b));
+ if (m && emojiSearch) {
+ const items = emojiSearch(m[2].slice(1)).slice(0, 6);
+ setSugg(items.length ? { start: b - m[2].length, items, i: 0 } : null);
+ } else setSugg(null);
+ };
+ const replace = (from, to, ins, kind = 'edit', caretAt = null) => {
+ const next = text.slice(0, from) + ins + text.slice(to);
+ const c = caretAt == null ? from + ins.length : caretAt;
+ commit(next, c, c, kind);
+ };
+ const insert = (s, kind = 'type') => replace(lo, hi, s, kind);
+ const moveTo = (off, extend) => { setSel((x) => (extend ? { a: x.a, b: off } : { a: off, b: off })); setBlink(true); setTimeout(() => ensureVisible(off), 0); setSugg(null); };
+ const prevChar = (o) => (o > 0 ? o - (/[\udc00-\udfff]/.test(text[o - 1]) ? 2 : 1) : 0);
+ const nextChar = (o) => (o < text.length ? o + (/[\ud800-\udbff]/.test(text[o]) ? 2 : 1) : o);
+ const wordLeft = (o) => { let i = o; while (i > 0 && !WORD.test(text[i - 1])) i--; while (i > 0 && WORD.test(text[i - 1])) i--; return i; };
+ const wordRight = (o) => { let i = o; while (i < text.length && !WORD.test(text[i])) i++; while (i < text.length && WORD.test(text[i])) i++; return i; };
+ const lineStart = (o) => text.lastIndexOf('\n', o - 1) + 1;
+ const lineEnd = (o) => { const i = text.indexOf('\n', o); return i < 0 ? text.length : i; };
+
+ // wraps the selection (or the word) in marks: **bold**, *italic*…
+ const wrap = (before, after = before) => {
+ if (lo === hi) { replace(lo, hi, before + after, 'edit', lo + before.length); return; }
+ const inner = text.slice(lo, hi);
+ if (inner.startsWith(before) && inner.endsWith(after) && inner.length >= before.length + after.length) {
+ const next = text.slice(0, lo) + inner.slice(before.length, inner.length - after.length) + text.slice(hi);
+ commit(next, lo, hi - before.length - after.length);
+ return;
+ }
+ const next = text.slice(0, lo) + before + inner + after + text.slice(hi);
+ commit(next, lo + before.length, hi + before.length);
+ };
+ // changes the prefix of the selected lines (headings, lists, checkboxes)
+ const linePrefix = (make) => {
+ const a = lineStart(lo), b = lineEnd(hi);
+ const lines = text.slice(a, b).split('\n');
+ const out = lines.map((l, i) => make(l, i));
+ const next = text.slice(0, a) + out.join('\n') + text.slice(b);
+ const delta = next.length - text.length;
+ commit(next, a, b + delta);
+ };
+ const STRIP = /^(\s*)(#{1,6}\s+|[-*+]\s+\[[ xX]\]\s+|[-*+]\s+|\d+[.)]\s+)?/;
+ const heading = (n) => linePrefix((l) => { const m = STRIP.exec(l); const body = l.slice(m[0].length); const had = m[2] && m[2].startsWith('#'.repeat(n) + ' ') && m[2].trim() === '#'.repeat(n); return had ? body : `${'#'.repeat(n)} ${body}`; });
+ const listify = (kind) => linePrefix((l, i) => {
+ const m = STRIP.exec(l);
+ const body = l.slice(m[0].length);
+ const cur = m[2] || '';
+ const mk = kind === 'num' ? `${i + 1}. ` : kind === 'task' ? '- [ ] ' : '- ';
+ const same = (kind === 'task' && /\[[ xX]\]/.test(cur)) || (kind === 'num' && /^\d/.test(cur)) || (kind === 'bullet' && /^[-*+]\s+$/.test(cur));
+ return `${m[1]}${same ? '' : mk}${body}`;
+ });
+ const codeBlock = () => {
+ const inner = text.slice(lo, hi);
+ const pre = lo === lineStart(lo) ? '' : '\n';
+ replace(lo, hi, `${pre}\`\`\`\n${inner}\n\`\`\`\n`, 'edit', lo + pre.length + 4 + inner.length);
+ };
+
+ const newline = () => {
+ const ls = lineStart(lo);
+ const line = text.slice(ls, lo);
+ const m = /^(\s*)([-*+]\s+\[[ xX]\]\s+|[-*+]\s+|(\d+)([.)])\s+|>\s?)/.exec(line);
+ if (m) {
+ if (line.trim() === m[0].trim() && lo === hi && lineEnd(lo) === lo) { replace(ls, lo, '', 'edit'); return; } // empty item: ends the list
+ let mk = m[2];
+ if (/\[[ xX]\]/.test(mk)) mk = mk.replace(/\[[xX]\]/, '[ ]');
+ if (m[3]) mk = `${Number(m[3]) + 1}${m[4]} `;
+ insert(`\n${m[1]}${mk}`, 'edit');
+ return;
+ }
+ insert(`\n${/^\s*/.exec(line)[0]}`, 'edit');
+ };
+
+ const acceptSugg = (k = sugg?.i || 0) => {
+ const it = sugg.items[k];
+ replace(sugg.start, hi, `${it.ch} `, 'edit');
+ setSugg(null);
+ };
+
+ const undo = () => { const s = st.current; const u = s.undo.pop(); if (!u) return; s.redo.push({ text, sel }); onChange(u.text); setSel(u.sel); s.last = 0; };
+ const redo = () => { const s = st.current; const r = s.redo.pop(); if (!r) return; s.undo.push({ text, sel }); onChange(r.text); setSel(r.sel); s.last = 0; };
+
+ const onKey = (e) => {
+ const prim = e.ctrl || e.meta;
+ const k = e.key;
+ const b = (e.base || '').toLowerCase();
+ if (sugg) {
+ if (k === 'ArrowDown') return setSugg({ ...sugg, i: (sugg.i + 1) % sugg.items.length });
+ if (k === 'ArrowUp') return setSugg({ ...sugg, i: (sugg.i + sugg.items.length - 1) % sugg.items.length });
+ if (k === 'Enter' || k === 'Tab') return acceptSugg();
+ if (k === 'Escape') return setSugg(null);
+ }
+ if (prim && !e.alt) {
+ if (b === 'z' && !e.shift) return undo();
+ if ((b === 'z' && e.shift) || b === 'y') return redo();
+ if (b === 'a') return setSel({ a: 0, b: text.length });
+ if (b === 'c') { if (hi > lo) clipboard.set(text.slice(lo, hi)); return undefined; }
+ if (b === 'x') { if (hi > lo) { clipboard.set(text.slice(lo, hi)); replace(lo, hi, '', 'edit'); } return undefined; }
+ if (b === 'v') {
+ const st2 = lord.clipboard.state ? lord.clipboard.state() : { kind: 'text' };
+ if (st2.kind === 'image' && onPasteImage) { const md = onPasteImage(); if (md) insert(`${lo > 0 && text[lo - 1] !== '\n' ? '\n' : ''}${md}\n`, 'edit'); return undefined; }
+ const txt = clipboard.get();
+ if (txt) insert(txt.replace(/\r\n/g, '\n'), 'edit');
+ return undefined;
+ }
+ if (b === 'b') return wrap('**');
+ if (b === 'i' && !e.shift) return wrap('*');
+ if (b === 'k') { if (hi > lo) { const s = text.slice(lo, hi); replace(lo, hi, `[${s}](url)`, 'edit', lo + s.length + 3); } else replace(lo, hi, '[](url)', 'edit', lo + 1); return undefined; }
+ if (b === '7' && e.shift) return listify('num');
+ if (b === '8' && e.shift) return listify('bullet');
+ if (b === '9' && e.shift) return listify('task');
+ if (b === 'c' && e.shift) return codeBlock();
+ if (!e.shift && (b === '1' || b === '2' || b === '3')) return heading(Number(b));
+ if (k === 'ArrowLeft') return moveTo(wordLeft(sel.b), e.shift);
+ if (k === 'ArrowRight') return moveTo(wordRight(sel.b), e.shift);
+ if (k === 'ArrowUp' || k === 'Home') return moveTo(0, e.shift);
+ if (k === 'ArrowDown' || k === 'End') return moveTo(text.length, e.shift);
+ if (k === 'Backspace') return lo === hi ? replace(wordLeft(lo), lo, '', 'edit') : replace(lo, hi, '', 'edit');
+ if (b) onCommand?.(b, e.shift);
+ return undefined;
+ }
+ if (e.alt && (k === 'ArrowLeft' || k === 'ArrowRight')) return moveTo(k === 'ArrowLeft' ? wordLeft(sel.b) : wordRight(sel.b), e.shift);
+ const vert = (d) => {
+ const r = rowOf(sel.b) + d;
+ const goal = st.current.goal ?? xOf(sel.b);
+ if (r < 0) return 0;
+ if (r >= rows.length) return text.length;
+ const off = offAt(goal, r * LH + 1);
+ setTimeout(() => { st.current.goal = goal; }, 0);
+ return off;
+ };
+ if (k !== 'ArrowUp' && k !== 'ArrowDown') st.current.goal = null;
+ switch (k) {
+ case 'ArrowLeft': return moveTo(!e.shift && hi > lo ? lo : prevChar(sel.b), e.shift);
+ case 'ArrowRight': return moveTo(!e.shift && hi > lo ? hi : nextChar(sel.b), e.shift);
+ case 'ArrowUp': return moveTo(vert(-1), e.shift);
+ case 'ArrowDown': return moveTo(vert(1), e.shift);
+ case 'Home': { const r = rows[rowOf(sel.b)]; return moveTo(r.start, e.shift); }
+ case 'End': { const r = rows[rowOf(sel.b)]; return moveTo(r.end, e.shift); }
+ case 'Backspace': return lo === hi ? replace(prevChar(lo), lo, '', 'type') : replace(lo, hi, '', 'edit');
+ case 'Delete': return lo === hi ? replace(lo, nextChar(lo), '', 'type') : replace(lo, hi, '', 'edit');
+ case 'Enter': return newline();
+ case 'Tab': {
+ const line = text.slice(lineStart(lo), lineEnd(lo));
+ if (/^\s*([-*+]|\d+[.)])\s/.test(line) || hi > lo) return linePrefix((l) => (e.shift ? l.replace(/^ {1,2}/, '') : ` ${l}`));
+ return insert(' ');
+ }
+ case 'Escape': if (hi > lo) return setSel({ a: sel.b, b: sel.b }); return onEscape?.();
+ default: break;
+ }
+ if (e.char && !e.ctrl && !e.meta && e.char >= ' ') insert(e.char, 'type');
+ return undefined;
+ };
+
+ // the handler changes on every render: the text focus calls the current one
+ st.current.onKey = onKey;
+ const caretRect = () => {
+ if (!area.current) return null;
+ const [ax, ay] = lord.getLayout(area.current.id);
+ return { x: ax + padding + xOf(sel.b), y: ay + padding + rowOf(sel.b) * LH - scroll, h: LH };
+ };
+ st.current.caret = caretRect;
+ if (apiRef) apiRef.current = {
+ insert: (txt) => insert(txt, 'edit'), focus: () => take(),
+ wrap: (a, b) => wrap(a, b), list: (kind) => listify(kind),
+ quote: () => linePrefix((l) => (/^>\s?/.test(l) ? l.replace(/^>\s?/, '') : `> ${l}`)),
+ link: () => { if (hi > lo) { const s = text.slice(lo, hi); replace(lo, hi, `[${s}](https://)`, 'edit', lo + s.length + 3); } else replace(lo, hi, '[](https://)', 'edit', lo + 1); },
+ };
+ const take = () => {
+ if (textFocusOwner() === token) return;
+ takeTextFocus(token, (e) => st.current.onKey(e), () => setFocusState(textFocusOwner() === token));
+ setFocusState(true);
+ };
+ useEffect(() => {
+ if (!focus) return undefined;
+ ime.attach(token, () => st.current.caret(), { inline: true });
+ const id = setInterval(() => setBlink((v) => !v), 530);
+ return () => { clearInterval(id); ime.detach(token); };
+ }, [focus]);
+ useEffect(() => { if (autoFocus) take(); return () => releaseTextFocus(token); }, []);
+ const wasFocused = useRef(false);
+ useEffect(() => { if (wasFocused.current && !focus) onBlur?.(); wasFocused.current = focus; }, [focus]);
+
+ // ---- mouse ----
+ const drag = useRef(null);
+ const clicks = useRef({ t: 0, n: 0 });
+ const posFromEvent = (e) => {
+ const [ax, ay] = lord.getLayout(area.current.id);
+ return offAt(e.x - ax - padding, e.y - ay - padding + scroll);
+ };
+ const onMouseDown = (e) => {
+ take();
+ const p = posFromEvent(e);
+ const now = Date.now(), c = clicks.current;
+ c.n = now - c.t < 400 ? c.n + 1 : 1;
+ c.t = now;
+ setSugg(null);
+ if (c.n === 2) { // word
+ let a = p, b2 = p;
+ while (a > 0 && WORD.test(text[a - 1])) a--;
+ while (b2 < text.length && WORD.test(text[b2])) b2++;
+ setSel({ a, b: b2 });
+ return;
+ }
+ if (c.n >= 3) { setSel({ a: lineStart(p), b: lineEnd(p) }); return; }
+ setSel((x) => (e.shift ? { a: x.a, b: p } : { a: p, b: p }));
+ drag.current = { anchor: e.shift ? sel.a : p };
+ };
+ useEffect(() => {
+ const offMove = addListener('pointermove', (e) => {
+ if (!drag.current || !area.current) return;
+ setSel({ a: drag.current.anchor, b: posFromEvent(e) });
+ });
+ const offUp = addListener('pointerup', () => { drag.current = null; });
+ return () => { offMove(); offUp(); };
+ });
+
+ const onWheel = (e) => setScroll((s) => Math.max(0, Math.min(Math.max(0, rows.length * LH - st.current.h + padding * 2 + LH), s + e.deltaY)));
+
+ // ---- drawing ----
+ const first = Math.max(0, Math.floor(scroll / LH) - 2);
+ const last = Math.min(rows.length - 1, first + Math.ceil(dims.h / LH) + 4);
+ const lineKinds = [];
+ let inCode = false;
+ for (const ln of text.split('\n')) {
+ const fence = /^(`{3,}|~{3,})/.test(ln);
+ lineKinds.push(lineStyle(ln, inCode && !fence));
+ if (fence) inCode = !inCode;
+ }
+ const kindStyle = (kind) => {
+ if (kind[0] === 'h') return { fontWeight: 700, color: colors.heading };
+ if (kind === 'code') return { color: colors.code };
+ if (kind === 'quote') return { color: colors.dim };
+ if (kind === 'task' || kind === 'list') return { color: colors.text };
+ return { color: colors.text };
+ };
+ const out = [];
+ const selRects = [];
+ for (let r = first; r <= last; r++) {
+ const row = rows[r];
+ const kind = lineKinds[row.line] || 'text';
+ const y = padding + r * LH - scroll;
+ if (hi > lo && row.end >= lo && row.start <= hi) {
+ const a = Math.max(lo, row.start), b2 = Math.min(hi, row.end);
+ const x0 = widthOf(text.slice(row.start, a), size);
+ const x1 = widthOf(text.slice(row.start, b2), size) + (hi > row.end ? size * 0.4 : 0);
+ if (x1 > x0) selRects.push(<View key={`s${r}`} style={{ position: 'absolute', left: padding + x0, top: y, width: x1 - x0, height: LH, backgroundColor: colors.selection }} />);
+ }
+ // headings are drawn a little larger but on the same grid (the caret follows the base font)
+ out.push(<Text key={r} style={{ position: 'absolute', left: padding, top: y + (LH - size * 1.3) / 2, fontFamily: 'monospace', fontSize: size, whiteSpace: 'nowrap', ...kindStyle(kind) }}>{text.slice(row.start, row.end)}</Text>);
+ }
+ const caretRow = rowOf(sel.b);
+ return (
+ <View ref={area} onMouseDown={onMouseDown} onWheel={onWheel} style={{ flex: 1, overflow: 'hidden', direction: 'ltr' }}>
+ {selRects}
+ {out}
+ {focus && blink && caretRow >= first && caretRow <= last && (
+ <View style={{ position: 'absolute', left: padding + xOf(sel.b) - 1, top: padding + caretRow * LH - scroll + 2, width: 2, height: LH - 4, backgroundColor: colors.caret }} />
+ )}
+ {sugg && (
+ <View style={{ position: 'absolute', left: Math.min(padding + xOf(sel.b), Math.max(0, dims.w - 200)), top: padding + (caretRow + 1) * LH - scroll + 2, width: 196,
+ padding: 4, borderRadius: 8, backgroundColor: colors.popupBg, border: `1px solid ${colors.border}`, boxShadow: '0 8px 20px rgba(0,0,0,0.3)' }}>
+ {sugg.items.map((it, i) => (
+ <View key={it.ch + i} onMouseDown={(e) => { e.stopPropagation?.(); acceptSugg(i); }} style={{ flexDirection: 'row', alignItems: 'center', gap: 8, height: 24, paddingHorizontal: 6,
+ borderRadius: 5, backgroundColor: i === sugg.i ? colors.accent : 'transparent' }}>
+ <Text style={{ fontSize: 15 }}>{it.ch}</Text>
+ <Text style={{ fontSize: 12, color: i === sugg.i ? '#fff' : colors.popupText, whiteSpace: 'nowrap' }}>{`:${it.name}:`}</Text>
+ </View>
+ ))}
+ </View>
+ )}
+ </View>
+ );
+}
diff --git a/apps/mail/Compose.jsx b/apps/mail/Compose.jsx
new file mode 100644
index 0000000..1989489
--- /dev/null
+++ b/apps/mail/Compose.jsx
@@ -0,0 +1,265 @@
+// Compose.jsx — the compose window: From, To/Cc/Bcc with autocomplete (Contacts and people you
+// wrote to), subject, a body in rich text (formatting buttons and a live preview), markdown or
+// plain text, attachments, signature, drafts saved to the server, send now or later.
+import { View, Text, useTheme, useAppWindow, Button, TextInput, Segmented, ScrollView, Markdown, FilePicker, t, wm, fs, mailRequest, mailAccounts, contacts, useKeyboard } from '@lordos/sdk';
+import { useEffect, useRef, useState } from 'react';
+import { BodyEditor } from './BodyEditor.jsx';
+import { mdToHtml, mdToText } from './md.js';
+import { formatSize } from './util.js';
+
+const emailOk = (e) => /^[^@\s<>,;"]+@[^@\s<>,;"]+\.[^@\s<>,;"]+$/.test(e);
+
+function parseTyped(s) {
+ const m = /^\s*"?([^"<]*?)"?\s*<([^>]+)>\s*$/.exec(s);
+ if (m) return { name: m[1].trim(), email: m[2].trim() };
+ return { name: '', email: s.trim() };
+}
+
+// One recipients row: chips + a field that suggests addresses as you type.
+function Recipients({ label, list, onChange, autoFocus }) {
+ const th = useTheme();
+ const [q, setQ] = useState('');
+ const [sugg, setSugg] = useState([]);
+ const [i, setI] = useState(0);
+ useEffect(() => {
+ let live = true;
+ if (q.trim().length < 1) { setSugg([]); return undefined; }
+ contacts.autocomplete(q.trim()).then((r) => { if (live) { setSugg(r.filter((x) => !list.some((y) => y.email.toLowerCase() === x.email.toLowerCase())).slice(0, 8)); setI(0); } }).catch(() => {});
+ return () => { live = false; };
+ }, [q]);
+ const add = (a) => { if (a?.email && emailOk(a.email)) onChange([...list, a]); setQ(''); setSugg([]); };
+ return (
+ <View style={{ zIndex: sugg.length ? 20 : 1 }}>
+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 6, minHeight: 32, paddingHorizontal: 12 }}>
+ <Text style={{ width: 54, fontSize: 12, color: th.textDim }}>{label}</Text>
+ <View style={{ flex: 1, flexDirection: 'row', flexWrap: 'wrap', alignItems: 'center', gap: 4, paddingVertical: 4 }}>
+ {list.map((a, k) => (
+ <View key={a.email + k} style={{ flexDirection: 'row', alignItems: 'center', gap: 4, paddingHorizontal: 8, height: 22, borderRadius: 11, backgroundColor: emailOk(a.email) ? th.control : '#ff453a55' }}>
+ <Text style={{ fontSize: 12, color: th.text }}>{a.name || a.email}</Text>
+ <Text onClick={() => onChange(list.filter((_, j) => j !== k))} style={{ fontSize: 11, color: th.textDim }}>✕</Text>
+ </View>
+ ))}
+ <View style={{ flex: 1, minWidth: 140 }}>
+ <TextInput value={q} onChange={(v) => { if (/[,;]$/.test(v)) add(parseTyped(v.slice(0, -1))); else setQ(v); }} autoFocus={autoFocus}
+ onSubmit={() => (sugg[i] ? add(sugg[i]) : q.trim() && add(parseTyped(q)))}
+ onKeyDown={(e) => {
+ if (e.key === 'ArrowDown' && sugg.length) { setI((i + 1) % sugg.length); return true; }
+ if (e.key === 'ArrowUp' && sugg.length) { setI((i + sugg.length - 1) % sugg.length); return true; }
+ if (e.key === 'Tab' && (sugg[i] || q.trim())) { add(sugg[i] || parseTyped(q)); return true; }
+ if (e.key === 'Backspace' && !q && list.length) { onChange(list.slice(0, -1)); return true; }
+ return false;
+ }} style={{ backgroundColor: 'transparent', borderWidth: 0 }} />
+ </View>
+ </View>
+ {sugg.length > 0 && (
+ <View style={{ position: 'absolute', left: 66, top: 32, width: 360, padding: 4, borderRadius: 8, backgroundColor: th.windowBg, border: `1px solid ${th.separator}`,
+ boxShadow: '0 10px 26px rgba(0,0,0,0.35)', zIndex: 30 }}>
+ {sugg.map((s, k) => (
+ <View key={s.email} onMouseDown={(e) => { e.stopPropagation?.(); add(s); }} style={{ padding: 6, borderRadius: 6, backgroundColor: k === i ? th.accent : 'transparent' }}>
+ <Text style={{ fontSize: 13, color: k === i ? '#fff' : th.text }}>{s.name || s.email}</Text>
+ <Text style={{ fontSize: 11, color: k === i ? '#ffffffcc' : th.textDim }}>{`${s.email}${s.src === 'contacts' ? ` · ${t('mail.compose.fromContacts')}` : ''}`}</Text>
+ </View>
+ ))}
+ </View>
+ )}
+ </View>
+ <View style={{ height: 1, backgroundColor: th.separator }} />
+ </View>
+ );
+}
+
+const Line = ({ th }) => <View style={{ height: 1, backgroundColor: th.separator }} />;
+
+function ToolButton({ label, onClick, hint, bold }) {
+ const th = useTheme();
+ return (
+ <View onClick={onClick} style={{ minWidth: 28, height: 26, paddingHorizontal: 6, borderRadius: 6, alignItems: 'center', justifyContent: 'center', backgroundColor: th.control }}>
+ <Text style={{ fontSize: 13, fontWeight: bold ? 700 : 500, color: th.text }}>{label}</Text>
+ {hint ? null : null}
+ </View>
+ );
+}
+
+// draft = { acct, to, cc, bcc, subject, body, format, inReplyTo, references, original, attachments: [path], draftUid, draftFolder }
+export function Compose({ draft: initial }) {
+ const th = useTheme();
+ const { id: wid } = useAppWindow();
+ const accounts = mailAccounts.list().filter((a) => a.kind === 'mail');
+ const [d, setD] = useState(() => {
+ const acct = initial?.acct && accounts.some((a) => a.id === initial.acct) ? initial.acct : accounts[0]?.id;
+ const a = accounts.find((x) => x.id === acct);
+ let body = initial?.body || '';
+ if (a?.signature && !initial?.noSignature) body = `${body ? '' : '\n\n'}${body.startsWith('\n') ? '' : ''}\n\n-- \n${a.signature}${body ? `\n\n${body}` : ''}`.replace(/^\n\n\n/, '\n\n');
+ return { to: [], cc: [], bcc: [], subject: '', format: 'rich', attachments: [], ...initial, acct, body };
+ });
+ const [showCc, setShowCc] = useState(!!(initial?.cc?.length || initial?.bcc?.length));
+ const [preview, setPreview] = useState(true);
+ const [picker, setPicker] = useState(false);
+ const [busy, setBusy] = useState('');
+ const [err, setErr] = useState('');
+ const [later, setLater] = useState(false);
+ const dirty = useRef(false);
+ const ed = useRef(null);
+ const set = (patch) => { dirty.current = true; setD((x) => ({ ...x, ...patch })); };
+
+ useEffect(() => { wm.setTitle(wid, d.subject || t('mail.compose.newMessage')); }, [d.subject]);
+
+ const payload = () => {
+ const html = d.format === 'plain' ? undefined : mdToHtml(d.body);
+ const text = d.format === 'plain' ? d.body : mdToText(d.body);
+ return {
+ acct: d.acct, to: d.to, cc: d.cc, bcc: d.bcc, subject: d.subject, text, ...(html ? { html } : {}),
+ attachments: d.attachments.map((p) => ({ name: fs.basename(p) })),
+ ...(d.inReplyTo ? { inReplyTo: d.inReplyTo } : {}), ...(d.references ? { references: d.references } : {}),
+ ...(d.original ? { original: d.original } : {}),
+ ...(d.draftUid ? { draftUid: d.draftUid, draftFolder: d.draftFolder } : {}),
+ };
+ };
+
+ const saveDraft = async (quiet) => {
+ if (!d.acct) return;
+ try {
+ const r = await mailRequest('draft', { ...payload(), replace: d.draftUid || 0, format: d.format }, { files: d.attachments });
+ dirty.current = false;
+ if (r.uid) setD((x) => ({ ...x, draftUid: r.uid, draftFolder: x.draftFolder || 'Drafts' }));
+ if (!quiet) setBusy(t('mail.compose.draftSaved'));
+ setTimeout(() => setBusy(''), 1500);
+ } catch (e) { if (!quiet) setErr(e.message); }
+ };
+
+ // autosave every 30 s while there are changes
+ useEffect(() => { const id = setInterval(() => { if (dirty.current) saveDraft(true); }, 30000); return () => clearInterval(id); }, [d]);
+
+ const send = async (sendAt) => {
+ setErr('');
+ const all = [...d.to, ...d.cc, ...d.bcc];
+ if (!all.length) { setErr(t('mail.compose.noRecipients')); return; }
+ const bad = all.find((a) => !emailOk(a.email));
+ if (bad) { setErr(t('mail.compose.badAddress', { addr: bad.email })); return; }
+ setBusy(t('mail.compose.sending'));
+ try {
+ const r = await mailRequest('send', { ...payload(), ...(sendAt ? { sendAt } : {}) }, { files: d.attachments });
+ dirty.current = false;
+ setBusy(r.scheduled ? t('mail.compose.scheduled') : t('mail.compose.sent'));
+ setTimeout(() => wm.close(wid), 600);
+ } catch (e) { setBusy(''); setErr(`${t('mail.compose.failed')} ${e.message}`); }
+ };
+
+ useEffect(() => {
+ wm.setCloseGuard?.(wid, () => {
+ if (!dirty.current) return true;
+ saveDraft(true);
+ return true;
+ });
+ }, [wid, d]);
+
+ useKeyboard((e) => {
+ const m = e.ctrl || e.meta;
+ const b = (e.base || '').toLowerCase();
+ if (m && e.key === 'Enter') { send(); return true; }
+ if (m && b === 's') { saveDraft(); return true; }
+ return false;
+ });
+
+ const tomorrow8 = () => { const x = new Date(); x.setDate(x.getDate() + 1); x.setHours(8, 0, 0, 0); return +x; };
+ const monday8 = () => { const x = new Date(); x.setDate(x.getDate() + ((8 - x.getDay()) % 7 || 7)); x.setHours(8, 0, 0, 0); return +x; };
+ const colors = { text: th.text, dim: th.textDim, heading: th.text, code: th.accent, accent: th.accent, selection: `${th.accent}55`, caret: th.accent,
+ popupBg: th.windowBg, popupText: th.text, border: th.separator };
+ const fmtOpts = [['rich', t('mail.compose.rich')], ['markdown', t('mail.compose.markdown')], ['plain', t('mail.compose.plain')]];
+ const wrapSel = (a, b = a) => ed.current?.wrap?.(a, b) ?? ed.current?.insert?.(`${a}${b}`);
+ return (
+ <View style={{ flex: 1, backgroundColor: th.windowBg }}>
+ {/* toolbar */}
+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 8, paddingHorizontal: 12, height: 46 }}>
+ <Button primary label={`➤ ${t('mail.compose.send')}`} onClick={() => send()} />
+ <Button label={t('mail.compose.later')} onClick={() => setLater(!later)} />
+ <Button label={`📎 ${t('mail.compose.attach')}`} onClick={() => setPicker(true)} />
+ <Button label={t('mail.compose.saveDraft')} onClick={() => saveDraft()} />
+ <View style={{ flex: 1 }} />
+ <Segmented small options={fmtOpts} value={d.format} onChange={(format) => set({ format })} />
+ </View>
+ <Line th={th} />
+ {later && (
+ <View style={{ position: 'absolute', left: 110, top: 44, padding: 6, borderRadius: 8, backgroundColor: th.windowBg, border: `1px solid ${th.separator}`, zIndex: 40,
+ boxShadow: '0 10px 26px rgba(0,0,0,0.35)', gap: 2 }}>
+ {[[t('mail.compose.in1h'), () => Date.now() + 3600000], [t('mail.compose.tomorrow8'), tomorrow8], [t('mail.compose.monday8'), monday8]].map(([label, at]) => (
+ <View key={label} onClick={() => { setLater(false); send(at()); }} style={{ padding: 6, borderRadius: 6 }}><Text style={{ fontSize: 13, color: th.text }}>{label}</Text></View>
+ ))}
+ </View>
+ )}
+ {/* headers */}
+ {accounts.length > 1 && (
+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 6, height: 32, paddingHorizontal: 12 }}>
+ <Text style={{ width: 54, fontSize: 12, color: th.textDim }}>{t('mail.compose.from')}</Text>
+ {accounts.map((a) => (
+ <View key={a.id} onClick={() => set({ acct: a.id })} style={{ paddingHorizontal: 8, height: 22, borderRadius: 11, justifyContent: 'center', backgroundColor: a.id === d.acct ? th.accent : th.control }}>
+ <Text style={{ fontSize: 12, color: a.id === d.acct ? '#fff' : th.text }}>{a.email}</Text>
+ </View>
+ ))}
+ </View>
+ )}
+ {accounts.length > 1 && <Line th={th} />}
+ <Recipients label={t('mail.compose.to')} list={d.to} onChange={(to) => set({ to })} autoFocus={!d.to.length} />
+ {showCc ? (
+ <>
+ <Recipients label={t('mail.compose.cc')} list={d.cc} onChange={(cc) => set({ cc })} />
+ <Recipients label={t('mail.compose.bcc')} list={d.bcc} onChange={(bcc) => set({ bcc })} />
+ </>
+ ) : (
+ <Text onClick={() => setShowCc(true)} style={{ position: 'absolute', right: 14, top: accounts.length > 1 ? 86 : 54, fontSize: 12, color: th.accent, zIndex: 25 }}>{t('mail.compose.ccBcc')}</Text>
+ )}
+ <View style={{ flexDirection: 'row', alignItems: 'center', height: 34, paddingHorizontal: 12 }}>
+ <Text style={{ width: 54, fontSize: 12, color: th.textDim }}>{t('mail.compose.subject')}</Text>
+ <View style={{ flex: 1 }}><TextInput value={d.subject} onChange={(subject) => set({ subject })} style={{ backgroundColor: 'transparent', borderWidth: 0 }} /></View>
+ </View>
+ <Line th={th} />
+ {d.format !== 'plain' && (
+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 4, paddingHorizontal: 12, height: 36 }}>
+ <ToolButton label="B" bold onClick={() => wrapSel('**')} />
+ <ToolButton label="I" onClick={() => wrapSel('*')} />
+ <ToolButton label="S̶" onClick={() => wrapSel('~~')} />
+ <ToolButton label="• ≡" onClick={() => ed.current?.list?.('bullet')} />
+ <ToolButton label="1. ≡" onClick={() => ed.current?.list?.('num')} />
+ <ToolButton label="❝" onClick={() => ed.current?.quote?.()} />
+ <ToolButton label="🔗" onClick={() => ed.current?.link?.()} />
+ <ToolButton label="</>" onClick={() => wrapSel('`')} />
+ <View style={{ flex: 1 }} />
+ {d.format === 'rich' && <Button small plain label={preview ? t('mail.compose.hidePreview') : t('mail.compose.showPreview')} onClick={() => setPreview(!preview)} />}
+ </View>
+ )}
+ <View style={{ flex: 1, flexDirection: 'row' }}>
+ <View style={{ flex: 1 }}>
+ <BodyEditor value={d.body} onChange={(body) => set({ body })} colors={colors} apiRef={ed} autoFocus={!!d.to.length} padding={14} />
+ </View>
+ {d.format === 'rich' && preview && <View style={{ width: 1, backgroundColor: th.separator }} />}
+ {d.format === 'rich' && preview && (
+ <View style={{ flex: 1, backgroundColor: th.mode === 'dark' ? '#00000022' : '#f7f7f7' }}>
+ <ScrollView style={{ flex: 1 }}><View style={{ padding: 14 }}><Markdown source={d.body} width={360} /></View></ScrollView>
+ </View>
+ )}
+ </View>
+ {d.attachments.length > 0 && (
+ <View style={{ flexDirection: 'row', flexWrap: 'wrap', gap: 6, padding: 10 }}>
+ {d.attachments.map((p) => {
+ let size = 0;
+ try { size = fs.stat(p)?.size || 0; } catch (e) { size = 0; }
+ return (
+ <View key={p} style={{ flexDirection: 'row', alignItems: 'center', gap: 6, paddingHorizontal: 10, height: 28, borderRadius: 8, backgroundColor: th.control }}>
+ <Text style={{ fontSize: 12, color: th.text }}>{`📄 ${fs.basename(p)}`}</Text>
+ <Text style={{ fontSize: 11, color: th.textDim }}>{formatSize(size)}</Text>
+ <Text onClick={() => set({ attachments: d.attachments.filter((x) => x !== p) })} style={{ fontSize: 11, color: th.textDim }}>✕</Text>
+ </View>
+ );
+ })}
+ </View>
+ )}
+ {(err || busy) && (
+ <View style={{ paddingHorizontal: 12, height: 26, justifyContent: 'center', backgroundColor: err ? '#ff453a22' : th.control }}>
+ <Text style={{ fontSize: 12, color: err ? '#ff453a' : th.text }}>{err || busy}</Text>
+ </View>
+ )}
+ {picker && <FilePicker multiple title={t('mail.compose.attachTitle')} onClose={() => setPicker(false)}
+ onPick={(paths) => { setPicker(false); set({ attachments: [...d.attachments, ...[].concat(paths).filter((p) => !d.attachments.includes(p))].slice(0, 15) }); }} />}
+ </View>
+ );
+}
diff --git a/apps/mail/HtmlView.jsx b/apps/mail/HtmlView.jsx
new file mode 100644
index 0000000..bc74153
--- /dev/null
+++ b/apps/mail/HtmlView.jsx
@@ -0,0 +1,239 @@
+// HtmlView — draws the safe tree that lord-maild's sanitizer made from a message's HTML
+// (server/src/mail/html.h) with our own views: blocks, layout tables, text runs, images and
+// links. Nothing here ever interprets HTML or runs anything; images are decoded in lord-maild
+// and remote ones are requested only after the user chose to load them.
+import { View, Text, Image, useTheme, mailRequest } from '@lordos/sdk';
+import { useEffect, useRef, useState } from 'react';
+
+const MAX_WORDS = 6000; // beyond this a paragraph keeps whole runs (wrapping is coarser)
+
+function rgba(hex, fallback) {
+ if (!hex || hex[0] !== '#') return fallback;
+ if (hex.length === 9) {
+ const a = parseInt(hex.slice(7), 16) / 255;
+ const n = parseInt(hex.slice(1, 7), 16);
+ return `rgba(${n >> 16},${(n >> 8) & 255},${n & 255},${a.toFixed(2)})`;
+ }
+ return hex;
+}
+
+// ---- images ----
+
+function MailImage({ node, ctx }) {
+ const ref = useRef(null);
+ const [img, setImg] = useState(null); // { image, w, h } | { error }
+ const remote = node.src.startsWith('r:');
+ const allowed = !remote || ctx.remote;
+ const maxw = Math.max(16, Math.round(Math.min(ctx.w, node.w || ctx.w)));
+ useEffect(() => {
+ if (!allowed) return undefined;
+ let live = true;
+ mailRequest('image', { ...ctx.msg, src: node.src, maxw: Math.min(1600, maxw * 2) })
+ .then((r) => { if (live) setImg(r); }).catch((e) => { if (live) setImg({ error: e.code || 'error' }); });
+ return () => { live = false; };
+ }, [node.src, allowed, ctx.msg.uid]);
+ useEffect(() => {
+ if (ref.current && img?.image) { lord.mail.bind(ref.current.id, img.image); lord.mail.release(img.image); }
+ }, [img?.image]);
+ // size: the HTML's width/height, or the picture's own, scaled to fit
+ let w = node.wp ? (ctx.w * node.wp) / 100 : node.w || (img?.w ? img.w / 2 : Math.min(ctx.w, 200));
+ let h = node.h || (img?.h && img?.w ? (img.h * w) / img.w : node.w ? node.w * 0.5 : 60);
+ if (!node.h && node.w && img?.w) h = (img.h * node.w) / img.w;
+ if (w > ctx.w) { h = (h * ctx.w) / w; w = ctx.w; }
+ const box = { width: Math.max(1, w), height: Math.max(1, h) };
+ const click = node.l >= 0 && node.l !== undefined ? () => ctx.onLink(ctx.links[node.l]) : undefined;
+ if (img?.image) return <Image ref={ref} onClick={click} style={{ ...box, objectFit: 'contain' }} />;
+ return (
+ <View onClick={click} style={{ ...box, borderRadius: 4, borderWidth: 1, borderColor: ctx.dim, backgroundColor: 'rgba(127,127,127,0.10)',
+ alignItems: 'center', justifyContent: 'center', overflow: 'hidden' }}>
+ {h > 18 && <Text style={{ fontSize: 13, color: ctx.dim }}>{allowed && !img?.error ? '⋯' : '🖼'}</Text>}
+ {h > 36 && node.alt ? <Text style={{ fontSize: 11, color: ctx.dim, textAlign: 'center', paddingHorizontal: 4 }}>{node.alt}</Text> : null}
+ </View>
+ );
+}
+
+// ---- text ----
+
+function runStyle(s, ctx, link) {
+ const st = { fontSize: s?.fs || ctx.fs, color: link ? ctx.link : rgba(s?.c, ctx.fg) };
+ if (s?.b) st.fontWeight = 700;
+ if (s?.i && !s?.c && !link) st.color = ctx.italic; // the engine has no italic face: a tint, like Notes
+ if (s?.mono) st.fontFamily = 'monospace';
+ if (s?.bg) st.backgroundColor = rgba(s.bg, undefined);
+ return st;
+}
+
+function Word({ text, s, ctx, link }) {
+ const st = runStyle(s, ctx, link);
+ const click = link ? () => ctx.onLink(link) : undefined;
+ const underline = s?.u || link, strike = s?.st;
+ if (!underline && !strike) return <Text onClick={click} style={st}>{text}</Text>;
+ return (
+ <View onClick={click} style={{ flexDirection: 'column' }}>
+ <Text style={st}>{text}</Text>
+ {underline ? <View style={{ height: 1, marginTop: -2, backgroundColor: st.color, opacity: link ? 0.6 : 1 }} /> : null}
+ {strike ? <View style={{ position: 'absolute', left: 0, right: 0, top: (st.fontSize * 1.3) / 2, height: 1, backgroundColor: st.color }} /> : null}
+ </View>
+ );
+}
+
+// A paragraph: inline runs in a wrapping row (one <Text> per word, as the engine has no styled
+// spans inside one Text); a single plain run stays one Text that wraps by itself.
+function Para({ items, ctx, align }) {
+ const justify = align === 'c' ? 'center' : align === 'e' ? 'flex-end' : 'flex-start';
+ const textAlign = align === 'c' ? 'center' : align === 'e' ? 'end' : 'start';
+ if (items.length === 1 && items[0].t === 'x' && !(items[0].l >= 0) && !items[0].s?.u && !items[0].s?.st) {
+ const n = items[0];
+ return <Text style={{ ...runStyle(n.s, ctx, null), textAlign, lineHeight: (n.s?.fs || ctx.fs) * 1.4 }}>{n.x}</Text>;
+ }
+ const out = [];
+ let words = 0;
+ items.forEach((n, i) => {
+ if (n.t === 'br') { out.push(<View key={`b${i}`} style={{ width: '100%', height: 0 }} />); return; }
+ if (n.t === 'img') { out.push(<MailImage key={`i${i}`} node={n} ctx={ctx} />); return; }
+ const link = n.l >= 0 ? ctx.links[n.l] : null;
+ const parts = words > MAX_WORDS ? [n.x] : n.x.split(/(?<= )/);
+ words += parts.length;
+ parts.forEach((p, k) => out.push(<Word key={`${i}.${k}`} text={p} s={n.s} ctx={ctx} link={link} />));
+ });
+ return <View style={{ flexDirection: 'row', flexWrap: 'wrap', alignItems: 'flex-end', justifyContent: justify }}>{out}</View>;
+}
+
+// ---- blocks ----
+
+const pad = (s) => (s?.p ? { paddingTop: s.p[0], paddingRight: s.p[1], paddingBottom: s.p[2], paddingLeft: s.p[3] } : {});
+const padX = (s) => (s?.p ? s.p[1] + s.p[3] : 0);
+
+function blockWidth(s, avail) {
+ let w = s?.wp ? (avail * s.wp) / 100 : s?.w || null;
+ if (s?.mw && (!w || w > s.mw)) w = s.mw;
+ if (w && w > avail) w = avail;
+ return w;
+}
+
+function Children({ nodes, ctx, align }) {
+ const out = [];
+ let inline = [];
+ const flush = (key) => { if (inline.length) { out.push(<Para key={`p${key}`} items={inline} ctx={ctx} align={align} />); inline = []; } };
+ (nodes || []).forEach((n, i) => {
+ if (n.t === 'x' || n.t === 'br' || (n.t === 'img' && !n.a)) { inline.push(n); return; }
+ flush(i);
+ out.push(<Node key={i} n={n} ctx={ctx} align={align} />);
+ });
+ flush('end');
+ return out;
+}
+
+function Table({ n, ctx }) {
+ const s = n.s || {};
+ const w = blockWidth(s, ctx.w) || ctx.w;
+ const cp = n.cp || 0;
+ const border = s.bw ? { borderWidth: s.bw, borderColor: rgba(s.bc, ctx.dim) } : {};
+ const rows = (n.c || []).filter((r) => r.t === 'tr' && r.c?.length);
+ return (
+ <View style={{ width: w, alignSelf: s.ac ? 'center' : 'flex-start', backgroundColor: rgba(s.bg, undefined), borderRadius: s.r || 0, overflow: s.r ? 'hidden' : 'visible',
+ marginTop: s.mt || 0, marginBottom: s.mb || 0, ...border }}>
+ {rows.map((r, ri) => {
+ const cells = r.c.filter((c) => c.t === 'td');
+ // fixed widths first, the rest share what is left
+ let fixed = 0, flex = 0;
+ const ws = cells.map((c) => { const cw = blockWidth(c.s, w); if (cw) fixed += cw; else flex += c.cs || 1; return cw; });
+ const scale = fixed > w ? w / fixed : 1;
+ const rest = Math.max(0, w - fixed * scale);
+ return (
+ <View key={ri} style={{ flexDirection: 'row', backgroundColor: rgba(r.s?.bg, undefined) }}>
+ {cells.map((c, ci) => {
+ const cw = ws[ci] ? ws[ci] * scale : flex ? (rest * (c.cs || 1)) / flex : 0;
+ const cs = c.s || {};
+ const inner = Math.max(10, cw - (cs.p ? padX(cs) : cp * 2));
+ const va = cs.va === 'm' ? 'center' : cs.va === 'b' ? 'flex-end' : 'flex-start';
+ return (
+ <View key={ci} style={{ width: cw, backgroundColor: rgba(cs.bg, undefined), justifyContent: va, ...(cs.p ? pad(cs) : { paddingTop: cp, paddingBottom: cp, paddingLeft: cp, paddingRight: cp }),
+ ...(s.bw ? { borderWidth: 0.5, borderColor: rgba(s.bc, ctx.dim) } : {}) }}>
+ <Children nodes={c.c} ctx={{ ...ctx, w: inner }} align={cs.a} />
+ </View>
+ );
+ })}
+ </View>
+ );
+ })}
+ </View>
+ );
+}
+
+function Node({ n, ctx, align }) {
+ if (n.t === 'hr') return <View style={{ height: 1, backgroundColor: ctx.dim, opacity: 0.4, marginTop: 8, marginBottom: 8 }} />;
+ if (n.t === 'img') return <View style={{ alignItems: n.a === 'c' ? 'center' : n.a === 'e' ? 'flex-end' : 'flex-start' }}><MailImage node={n} ctx={ctx} /></View>;
+ if (n.t === 'tbl') return <Table n={n} ctx={ctx} />;
+ if (n.t === 'tr' || n.t === 'td') return <Children nodes={n.c} ctx={ctx} align={align} />;
+ const s = n.s || {};
+ const w = blockWidth(s, ctx.w);
+ const inner = Math.max(10, (w || ctx.w) - padX(s) - (s.bl || 0) - (n.mk ? 18 : 0));
+ const body = <Children nodes={n.c} ctx={{ ...ctx, w: inner }} align={s.a || align} />;
+ const style = {
+ ...pad(s), marginTop: s.mt || 0, marginBottom: s.mb || 0, backgroundColor: rgba(s.bg, undefined), borderRadius: s.r || 0,
+ ...(w ? { width: w } : {}), ...(s.ac ? { alignSelf: 'center' } : {}),
+ ...(s.bw ? { borderWidth: s.bw, borderColor: rgba(s.bc, ctx.dim) } : {}),
+ };
+ if (s.bl) {
+ return (
+ <View style={{ ...style, flexDirection: 'row' }}>
+ <View style={{ width: s.bl, backgroundColor: rgba(s.blc, ctx.dim), marginRight: 10, borderRadius: 1 }} />
+ <View style={{ flex: 1 }}>{body}</View>
+ </View>
+ );
+ }
+ if (n.mk) {
+ return (
+ <View style={{ ...style, flexDirection: 'row', gap: 6 }}>
+ <Text style={{ fontSize: ctx.fs, color: ctx.fg, width: 14, textAlign: 'end' }}>{n.mk}</Text>
+ <View style={{ flex: 1 }}>{body}</View>
+ </View>
+ );
+ }
+ return <View style={style}>{body}</View>;
+}
+
+// doc: the sanitizer's JSON; msg: { acct, folder, uid }; remote: load remote images
+export function HtmlView({ doc, msg, remote, width, onLink }) {
+ const th = useTheme();
+ // the sender chose colors: show it on its own paper (like other mail apps do in dark mode)
+ const paper = !!doc.colors || !!doc.bg || th.mode === 'light';
+ const ctx = {
+ msg, remote, onLink, links: doc.links || [], fs: 14,
+ w: Math.max(80, width - 28),
+ fg: paper ? '#1f1f1f' : th.text,
+ dim: paper ? '#8a8a8a' : th.textDim,
+ link: paper ? '#0a5fd0' : th.accent,
+ italic: paper ? '#4b3b8f' : '#e9e3ff',
+ };
+ return (
+ <View style={{ backgroundColor: paper ? rgba(doc.bg, '#ffffff') : 'transparent', padding: 14, borderRadius: 10, direction: 'ltr' }}>
+ <Children nodes={doc.blocks} ctx={ctx} />
+ </View>
+ );
+}
+
+// Plain text with clickable links and dimmed quoted lines.
+export function TextView({ text, onLink, width }) {
+ const th = useTheme();
+ const lines = String(text || '').replace(/\r\n/g, '\n').split('\n');
+ const url = /(https?:\/\/[^\s<>()]+[^\s<>().,;:!?]|mailto:[^\s<>()]+)/g;
+ return (
+ <View style={{ padding: 4, gap: 2, maxWidth: width }}>
+ {lines.slice(0, 5000).map((ln, i) => {
+ const quoted = /^\s*>/.test(ln);
+ const color = quoted ? th.textDim : th.text;
+ if (!url.test(ln)) return <Text key={i} style={{ fontSize: 14, color, minHeight: 18 }}>{ln || ' '}</Text>;
+ url.lastIndex = 0;
+ const parts = ln.split(url);
+ return (
+ <View key={i} style={{ flexDirection: 'row', flexWrap: 'wrap' }}>
+ {parts.map((p, k) => (k % 2 ? <Text key={k} onClick={() => onLink({ h: p })} style={{ fontSize: 14, color: th.accent }}>{p}</Text>
+ : p.split(/(?<= )/).map((w, j) => <Text key={`${k}.${j}`} style={{ fontSize: 14, color }}>{w}</Text>)))}
+ </View>
+ );
+ })}
+ </View>
+ );
+}
diff --git a/apps/mail/Setup.jsx b/apps/mail/Setup.jsx
new file mode 100644
index 0000000..91973b4
--- /dev/null
+++ b/apps/mail/Setup.jsx
@@ -0,0 +1,286 @@
+// Setup.jsx — adding and managing accounts: the setup sheet (our provider table, app
+// passwords, manual servers, CalDAV/CardDAV), the certificate warning, the password prompt and
+// the accounts panel. Passwords go to the system keyring (Passwords), never to a file.
+import { View, Text, useTheme, useStore, Button, TextInput, Segmented, Toggle, ScrollView, t, mailAccounts, mailStatus, mailConfig, autoconfig, OAUTH_PROVIDERS } from '@lordos/sdk';
+import { useEffect, useState } from 'react';
+
+export function Sheet({ children, onClose, width = 460 }) {
+ const th = useTheme();
+ return (
+ <View onMouseDown={(e) => { e.stopPropagation?.(); }} style={{ position: 'absolute', left: 0, right: 0, top: 0, bottom: 0, backgroundColor: 'rgba(0,0,0,0.32)', alignItems: 'center', justifyContent: 'center', zIndex: 50 }}>
+ <View onClick={(e) => e.stopPropagation?.()} style={{ width, maxHeight: '92%', padding: 18, gap: 10, borderRadius: 14, backgroundColor: th.windowBg,
+ border: `1px solid ${th.separator}`, boxShadow: '0 20px 50px rgba(0,0,0,0.45)' }}>
+ {children}
+ {onClose ? null : null}
+ </View>
+ </View>
+ );
+}
+
+function Field({ label, children }) {
+ const th = useTheme();
+ return (
+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 10 }}>
+ <Text style={{ width: 110, fontSize: 12, color: th.textDim, textAlign: 'end' }}>{label}</Text>
+ <View style={{ flex: 1 }}>{children}</View>
+ </View>
+ );
+}
+
+function ServerFields({ value, onChange, label }) {
+ const th = useTheme();
+ const opts = [['ssl', 'SSL/TLS'], ['starttls', 'STARTTLS']];
+ return (
+ <View style={{ gap: 6 }}>
+ <Text style={{ fontSize: 12, fontWeight: 600, color: th.text }}>{label}</Text>
+ <Field label={t('mail.setup.server')}><TextInput value={value.host} onChange={(host) => onChange({ ...value, host })} placeholder="imap.example.com" /></Field>
+ <Field label={t('mail.setup.port')}><TextInput value={String(value.port || '')} onChange={(p) => onChange({ ...value, port: Number(p.replace(/\D/g, '')) || 0 })} /></Field>
+ <Field label={t('mail.setup.security')}>
+ <Segmented options={opts} value={value.security} onChange={(security) => onChange({ ...value, security, port: value.port === 993 || value.port === 143 ? (security === 'ssl' ? 993 : 143) : value.port === 465 || value.port === 587 ? (security === 'ssl' ? 465 : 587) : value.port })} />
+ </Field>
+ </View>
+ );
+}
+
+// Waits for the new account's first status: connected, wrong password, certificate or offline.
+function useAccountResult(id) {
+ const st = useStore(mailStatus);
+ const s = id ? st.accounts[id]?.status : null;
+ const cert = id ? st.certs.find((c) => c.acct === id) : null;
+ const authFailed = id ? st.authFailed[id] : false;
+ if (!id) return null;
+ if (cert) return 'cert';
+ if (authFailed || s === 'auth') return 'auth';
+ if (s === 'idle') return 'ok';
+ if (s === 'offline') return 'offline';
+ return 'working';
+}
+
+export function AccountSetup({ onClose, kind: kind0 = 'mail' }) {
+ const th = useTheme();
+ const [kind, setKind] = useState(kind0);
+ const [step, setStep] = useState('who'); // who → servers → result
+ const [name, setName] = useState('');
+ const [email, setEmail] = useState('');
+ const [pw, setPw] = useState('');
+ const [cfg, setCfg] = useState(null);
+ const [manual, setManual] = useState(false);
+ const [dav, setDav] = useState({ url: '', user: '' });
+ const [withDav, setWithDav] = useState(true);
+ const [created, setCreated] = useState(null);
+ const [err, setErr] = useState('');
+ const result = useAccountResult(created);
+
+ const next = () => {
+ setErr('');
+ if (kind === 'dav') return save();
+ if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email.trim())) { setErr(t('mail.setup.badEmail')); return; }
+ const c = autoconfig(email.trim());
+ setCfg({ ...c, user: email.trim() });
+ setManual(!c.known);
+ setStep('servers');
+ };
+
+ const save = async () => {
+ setErr('');
+ try {
+ if (kind === 'dav') {
+ if (!/^https:\/\//i.test(dav.url)) { setErr(t('mail.setup.badUrl')); return; }
+ const id = await mailAccounts.add({ kind: 'dav', name: name || dav.url.replace(/^https:\/\//, '').split('/')[0], url: dav.url.trim(), user: dav.user.trim(), cal: true, card: true }, pw);
+ setCreated(id);
+ setStep('result');
+ return;
+ }
+ const acct = {
+ kind: 'mail', name: cfg.known ? `${cfg.name}` : email.trim(), email: email.trim(), fullName: name.trim(), user: cfg.user.trim(),
+ imap: cfg.imap, smtp: cfg.smtp, sentSaved: !!cfg.sentSaved, auth: 'password',
+ };
+ const id = await mailAccounts.add(acct, pw);
+ if (withDav && (cfg.caldav || cfg.carddav) && cfg.davNote !== 'oauth') {
+ await mailAccounts.add({ kind: 'dav', name: `${cfg.name} — ${t('mail.setup.calContacts')}`, url: cfg.caldav || cfg.carddav, user: cfg.user.trim(), cal: !!cfg.caldav, card: true }, pw);
+ }
+ setCreated(id);
+ setStep('result');
+ } catch (e) { setErr(e.code === 'locked' || e.code === 'no-keyring' ? t('mail.setup.keyringLocked') : `${t('mail.setup.failed')} ${e.message || ''}`); }
+ };
+
+ const title = kind === 'dav' ? t('mail.setup.titleDav') : t('mail.setup.title');
+ return (
+ <Sheet>
+ <Text style={{ fontSize: 17, fontWeight: 700, color: th.text }}>{title}</Text>
+ {step === 'who' && (
+ <View style={{ gap: 8 }}>
+ <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.url')}><TextInput value={dav.url} onChange={(url) => setDav({ ...dav, url })} placeholder="https://cloud.example.com/remote.php/dav" /></Field>
+ <Field label={t('mail.setup.user')}><TextInput value={dav.user} onChange={(user) => setDav({ ...dav, user })} /></Field>
+ </>
+ )}
+ <Field label={t('mail.setup.password')}><TextInput value={pw} onChange={setPw} secure onSubmit={next} /></Field>
+ <Text style={{ fontSize: 11, color: th.textDim }}>{t('mail.setup.keyringNote')}</Text>
+ </View>
+ )}
+ {step === 'servers' && cfg && (
+ <ScrollView style={{ maxHeight: 420 }}>
+ <View style={{ gap: 10 }}>
+ {cfg.known && (
+ <View style={{ padding: 10, borderRadius: 8, backgroundColor: th.control, gap: 4 }}>
+ <Text style={{ fontSize: 13, fontWeight: 600, color: th.text }}>{t('mail.setup.found', { name: cfg.name })}</Text>
+ <Text style={{ fontSize: 12, color: th.textDim }}>{t('mail.setup.appPassword', { name: cfg.name })}</Text>
+ {cfg.appPassword ? <Text style={{ fontSize: 11, color: th.accent }}>{cfg.appPassword}</Text> : null}
+ </View>
+ )}
+ {cfg.oauth && (
+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 8 }}>
+ <Button label={t('mail.setup.oauth', { name: cfg.name })} disabled onClick={() => {}} />
+ <Text style={{ flex: 1, fontSize: 11, color: th.textDim }}>{OAUTH_PROVIDERS[cfg.oauth]?.enabled ? '' : t('mail.setup.oauthNeedsId')}</Text>
+ </View>
+ )}
+ {(cfg.caldav || cfg.carddav) && (
+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 8 }}>
+ <Toggle on={withDav && cfg.davNote !== 'oauth'} onChange={setWithDav} />
+ <Text style={{ flex: 1, fontSize: 12, color: cfg.davNote === 'oauth' ? th.textDim : th.text }}>
+ {cfg.davNote === 'oauth' ? t('mail.setup.davOauth', { name: cfg.name }) : t('mail.setup.alsoDav', { name: cfg.name })}
+ </Text>
+ </View>
+ )}
+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 8 }}>
+ <Toggle on={manual} onChange={setManual} />
+ <Text style={{ fontSize: 12, color: th.text }}>{t('mail.setup.manual')}</Text>
+ </View>
+ {manual && (
+ <>
+ <Field label={t('mail.setup.user')}><TextInput value={cfg.user} onChange={(user) => setCfg({ ...cfg, user })} /></Field>
+ <ServerFields label={t('mail.setup.incoming')} value={cfg.imap} onChange={(imap) => setCfg({ ...cfg, imap })} />
+ <ServerFields label={t('mail.setup.outgoing')} value={cfg.smtp} onChange={(smtp) => setCfg({ ...cfg, smtp })} />
+ </>
+ )}
+ </View>
+ </ScrollView>
+ )}
+ {step === 'result' && (
+ <View style={{ gap: 8, paddingVertical: 6 }}>
+ <Text style={{ fontSize: 14, color: result === 'ok' ? '#30d158' : result === 'working' ? th.text : '#ff453a' }}>
+ {t(`mail.setup.result.${result || 'working'}`)}
+ </Text>
+ {result === 'auth' && <Text style={{ fontSize: 12, color: th.textDim }}>{t('mail.setup.authHelp')}</Text>}
+ </View>
+ )}
+ {err ? <Text style={{ fontSize: 12, color: '#ff453a' }}>{err}</Text> : null}
+ <View style={{ flexDirection: 'row', justifyContent: 'flex-end', gap: 8, marginTop: 4 }}>
+ {step === 'result' && result !== 'ok' && created ? <Button label={t('mail.setup.removeAccount')} onClick={() => { mailAccounts.remove(created); setCreated(null); setStep('who'); }} /> : null}
+ <Button label={step === 'result' ? t('mail.close') : t('mail.cancel')} onClick={onClose} />
+ {step === 'who' && <Button primary label={kind === 'dav' ? t('mail.setup.add') : t('mail.setup.next')} onClick={next} />}
+ {step === 'servers' && <Button primary label={t('mail.setup.add')} onClick={save} />}
+ </View>
+ </Sheet>
+ );
+}
+
+// A certificate that did not verify: shown as is, never accepted without the user saying so.
+export function CertDialog({ cert, onClose }) {
+ const th = useTheme();
+ const row = (k, v) => (
+ <View style={{ flexDirection: 'row', gap: 8 }}>
+ <Text style={{ width: 110, fontSize: 11, color: th.textDim, textAlign: 'end' }}>{k}</Text>
+ <Text style={{ flex: 1, fontSize: 11, color: th.text, fontFamily: 'monospace' }}>{v}</Text>
+ </View>
+ );
+ return (
+ <Sheet width={520}>
+ <Text style={{ fontSize: 16, fontWeight: 700, color: '#ff453a' }}>{t('mail.cert.title')}</Text>
+ <Text style={{ fontSize: 13, color: th.text }}>{t('mail.cert.body', { host: `${cert.host}:${cert.port}` })}</Text>
+ <View style={{ padding: 10, borderRadius: 8, backgroundColor: th.control, gap: 3 }}>
+ {row(t('mail.cert.reason'), cert.reason)}
+ {row(t('mail.cert.subject'), cert.subject)}
+ {row(t('mail.cert.issuer'), cert.issuer)}
+ {cert.notAfter ? row(t('mail.cert.expires'), cert.notAfter) : null}
+ {row('SHA-256', cert.sha256)}
+ </View>
+ <Text style={{ fontSize: 12, color: th.textDim }}>{t('mail.cert.advice')}</Text>
+ <View style={{ flexDirection: 'row', justifyContent: 'flex-end', gap: 8 }}>
+ <Button label={t('mail.cancel')} onClick={onClose} />
+ <Button label={t('mail.cert.trust')} onClick={() => { mailAccounts.trustCertificate(cert.acct, cert.smtp ? 'smtp' : mailAccounts.get(cert.acct)?.kind === 'dav' ? 'dav' : 'imap', cert.sha256); onClose(); }} />
+ </View>
+ </Sheet>
+ );
+}
+
+export function PasswordPrompt({ acct, onClose }) {
+ const th = useTheme();
+ const [pw, setPw] = useState('');
+ const [busy, setBusy] = useState(false);
+ const a = mailAccounts.get(acct);
+ const go = async () => { setBusy(true); try { await mailAccounts.setPassword(acct, pw); onClose(); } catch (e) { setBusy(false); } };
+ return (
+ <Sheet>
+ <Text style={{ fontSize: 16, fontWeight: 700, color: th.text }}>{t('mail.password.title')}</Text>
+ <Text style={{ fontSize: 13, color: th.textDim }}>{t('mail.password.body', { user: a?.user || acct })}</Text>
+ <TextInput value={pw} onChange={setPw} secure autoFocus onSubmit={go} onCancel={onClose} />
+ <View style={{ flexDirection: 'row', justifyContent: 'flex-end', gap: 8 }}>
+ <Button label={t('mail.cancel')} onClick={onClose} />
+ <Button primary label={busy ? t('mail.working') : t('mail.password.save')} onClick={go} />
+ </View>
+ </Sheet>
+ );
+}
+
+export function AccountsPanel({ onClose, onAdd }) {
+ const th = useTheme();
+ const st = useStore(mailStatus);
+ const [list, setList] = useState(mailAccounts.list());
+ const [sel, setSel] = useState(list[0]?.id || null);
+ const a = list.find((x) => x.id === sel);
+ const [sig, setSig] = useState(a?.signature || '');
+ useEffect(() => { setSig(a?.signature || ''); }, [sel]);
+ const refresh = () => setList(mailAccounts.list());
+ const cfg = mailConfig.get();
+ return (
+ <Sheet width={620}>
+ <Text style={{ fontSize: 17, fontWeight: 700, color: th.text }}>{t('mail.accounts.title')}</Text>
+ <View style={{ flexDirection: 'row', gap: 12, height: 300 }}>
+ <View style={{ width: 200, gap: 2, backgroundColor: th.sidebarBg, borderRadius: 8, padding: 6 }}>
+ <ScrollView style={{ flex: 1 }}>
+ {list.map((x) => (
+ <View key={x.id} onClick={() => setSel(x.id)} style={{ padding: 6, borderRadius: 6, backgroundColor: x.id === sel ? th.accent : 'transparent' }}>
+ <Text style={{ fontSize: 13, color: x.id === sel ? '#fff' : th.text, whiteSpace: 'nowrap', overflow: 'hidden' }}>{x.name || x.email}</Text>
+ <Text style={{ fontSize: 11, color: x.id === sel ? '#ffffffcc' : th.textDim }}>{x.kind === 'dav' ? t('mail.setup.kindDav') : x.email}</Text>
+ </View>
+ ))}
+ </ScrollView>
+ <Button label={t('mail.accounts.add')} onClick={onAdd} />
+ </View>
+ <View style={{ flex: 1, gap: 8 }}>
+ {a ? (
+ <>
+ <Text style={{ fontSize: 14, fontWeight: 600, color: th.text }}>{a.name || a.email}</Text>
+ <Text style={{ fontSize: 12, color: th.textDim }}>{`${t('mail.accounts.status')}: ${t(`mail.status.${st.accounts[a.id]?.status || 'idle'}`)} ${st.accounts[a.id]?.error ? `· ${st.accounts[a.id].error}` : ''}`}</Text>
+ {a.kind === 'mail' && (
+ <>
+ <Text style={{ fontSize: 12, color: th.textDim }}>{`IMAP ${a.imap?.host}:${a.imap?.port} · SMTP ${a.smtp?.host}:${a.smtp?.port}`}</Text>
+ <Text style={{ fontSize: 12, fontWeight: 600, color: th.text, marginTop: 6 }}>{t('mail.accounts.signature')}</Text>
+ <TextInput value={sig} onChange={setSig} placeholder={t('mail.accounts.signaturePh')} />
+ <Button label={t('mail.accounts.saveSignature')} onClick={() => { mailAccounts.update(a.id, { signature: sig }); refresh(); }} />
+ </>
+ )}
+ <View style={{ flex: 1 }} />
+ <View style={{ flexDirection: 'row', gap: 8 }}>
+ <Button label={t('mail.accounts.password')} onClick={() => mailStatus.set((s) => ({ ...s, authFailed: { ...s.authFailed, [a.id]: true } }))} />
+ <Button label={t('mail.accounts.remove')} onClick={async () => { await mailAccounts.remove(a.id); const l = mailAccounts.list(); setList(l); setSel(l[0]?.id || null); }} />
+ </View>
+ </>
+ ) : <Text style={{ fontSize: 13, color: th.textDim }}>{t('mail.accounts.none')}</Text>}
+ </View>
+ </View>
+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 8 }}>
+ <Toggle on={cfg.notify ?? true} onChange={(v) => { mailConfig.save({ ...mailConfig.get(), notify: v }); refresh(); }} />
+ <Text style={{ flex: 1, fontSize: 12, color: th.text }}>{t('mail.accounts.notify')}</Text>
+ <Button label={t('mail.close')} onClick={onClose} />
+ </View>
+ </Sheet>
+ );
+}
diff --git a/apps/mail/index.jsx b/apps/mail/index.jsx
new file mode 100644
index 0000000..3d707cf
--- /dev/null
+++ b/apps/mail/index.jsx
@@ -0,0 +1,693 @@
+// Mail — a native mail app in the spirit of a classic three-pane client: accounts and folders,
+// the message list with previews (conversations grouped), and the reading pane. Everything comes
+// from the sandboxed helper lord-maild (docs/MAIL.md): IMAP with IDLE, SMTP, a local cache with
+// 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,
+ mailRequest, onMailEvent, mailStatus, mailConfig, mailAccounts, mailAvailable, contactName, getLayout, 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 { quote } from './md.js';
+
+const ROW = 76;
+
+// ---- icon: an envelope on a blue tile (our own drawing) ----
+
+export function Icon({ size: s }) {
+ return (
+ <View style={{ width: s, height: s, borderRadius: s * 0.225, background: 'linear-gradient(165deg, #3fa9ff, #0a5fd0)', overflow: 'hidden',
+ boxShadow: `0 ${s * 0.04}px ${s * 0.12}px rgba(0,0,0,0.35)` }}>
+ <View style={{ position: 'absolute', left: s * 0.16, top: s * 0.27, width: s * 0.68, height: s * 0.46, borderRadius: s * 0.06, backgroundColor: '#ffffff',
+ boxShadow: `0 ${s * 0.02}px ${s * 0.05}px rgba(0,0,0,0.25)` }} />
+ {/* the flap: two stacked bands narrowing to a point */}
+ {[0, 1, 2, 3, 4].map((i) => (
+ <View key={i} style={{ position: 'absolute', left: s * (0.2 + i * 0.06), top: s * (0.31 + i * 0.045), width: s * (0.6 - i * 0.12), height: Math.max(1, s * 0.04),
+ borderRadius: s * 0.02, backgroundColor: i === 4 ? '#0a5fd0' : '#cfe6ff' }} />
+ ))}
+ </View>
+ );
+}
+
+// ---- the list ----
+
+function useSize(ref, every = 250) {
+ const [sz, setSz] = useState({ w: 400, h: 400 });
+ useEffect(() => {
+ const id = setInterval(() => {
+ if (!ref.current) return;
+ const [, , w, h] = getLayout(ref.current.id);
+ setSz((o) => (Math.abs(o.w - w) > 1 || Math.abs(o.h - h) > 1 ? { w, h } : o));
+ }, every);
+ return () => clearInterval(id);
+ }, []);
+ return sz;
+}
+
+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;
+ 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>
+ <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>
+ <Text style={{ fontSize: 12, color: dim, overflow: 'hidden', height: 30, lineHeight: 15 }}>{it.preview}</Text>
+ </View>
+ {cfg ? null : null}
+ </View>
+ );
+}
+
+// A virtual list: only the visible rows exist; rows load in windows from lord-maild as you scroll.
+function MessageList({ src, rev, selected, onSelect, onMenu, cfg }) {
+ const th = useTheme();
+ const box = useRef(null);
+ const { h } = useSize(box);
+ const [y, setY] = useState(0);
+ const [data, setData] = useState({ total: 0, items: new Map(), ver: null, loading: true });
+ const want = useRef(null);
+ const srcKey = JSON.stringify(src);
+ useEffect(() => { setY(0); setData({ total: 0, items: new Map(), ver: null, loading: true }); }, [srcKey]);
+ const first = Math.max(0, Math.floor(y / ROW) - 10), last = Math.ceil((y + h) / ROW) + 20;
+ useEffect(() => {
+ let live = true;
+ const key = `${srcKey}|${first}|${rev}`;
+ want.current = key;
+ const run = async () => {
+ try {
+ let r;
+ if (src.kind === 'search') r = await mailRequest('search', { q: src.q, count: 1000 });
+ else r = await mailRequest('list', { ...(src.kind === 'unified' ? { folder: '*inbox' } : { acct: src.acct, folder: src.folder }), threaded: true,
+ offset: first, count: last - first, filter: src.filter || 'all', ...(src.label ? { label: src.label } : {}) });
+ if (!live || want.current !== key) return;
+ setData((old) => {
+ const items = src.kind === 'search' || old.ver !== r.version ? new Map() : new Map(old.items);
+ const off = src.kind === 'search' ? 0 : first;
+ r.items.forEach((it, k) => items.set(off + k, it));
+ return { total: r.total, items, ver: r.version, loading: false };
+ });
+ } catch (e) { if (live) setData((o) => ({ ...o, loading: false, error: e.code })); }
+ };
+ const missing = (() => { for (let i = first; i < Math.min(last, data.total || last); i++) if (!data.items.has(i)) return true; return data.ver === null; })();
+ if (missing || rev !== data.rev) run();
+ return () => { live = false; };
+ }, [srcKey, first, rev]);
+ const total = data.total;
+ const max = Math.max(0, total * ROW - h);
+ const yy = Math.min(y, max);
+ const rows = [];
+ for (let i = Math.max(0, Math.floor(yy / ROW) - 2); i < Math.min(total, Math.ceil((yy + h) / ROW) + 2); i++) {
+ const it = data.items.get(i);
+ const key = it ? `${it.acct}|${it.folder}|${it.uid}` : `ph${i}`;
+ 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>,
+ );
+ }
+ const bar = total * ROW > h ? Math.max(28, (h * h) / (total * ROW)) : 0;
+ const drag = useRef(null);
+ useEffect(() => {
+ const offMove = addListener('pointermove', (e) => { if (drag.current) setY(Math.max(0, Math.min(max, drag.current.y0 + ((e.y - drag.current.py) * total * ROW) / Math.max(1, h)))); });
+ const offUp = addListener('pointerup', () => { drag.current = null; });
+ return () => { offMove(); offUp(); };
+ });
+ // keyboard selection needs the neighbours
+ MessageList.neighbour = (key, d) => {
+ for (const [i, it] of data.items) if (`${it.acct}|${it.folder}|${it.uid}` === key) {
+ const n = data.items.get(i + d);
+ if (n) { const ny = (i + d) * ROW; if (ny < yy) setY(ny); else if (ny + ROW > yy + h) setY(ny + ROW - h); }
+ return n ? { it: n, i: i + d } : null;
+ }
+ return null;
+ };
+ return (
+ <View ref={box} onWheel={(e) => setY((v) => Math.max(0, Math.min(max, v + e.deltaY)))} style={{ flex: 1, overflow: 'hidden' }}>
+ {rows}
+ {!total && !data.loading ? (
+ <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', padding: 20 }}>
+ <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,
+ top: (h - bar) * (yy / (max || 1)), backgroundColor: th.mode === 'dark' ? 'rgba(255,255,255,0.3)' : 'rgba(0,0,0,0.28)' }} />}
+ </View>
+ );
+}
+
+// ---- the reading pane ----
+
+function Banner({ color, children }) {
+ return <View style={{ flexDirection: 'row', alignItems: 'center', gap: 8, padding: 8, paddingHorizontal: 12, borderRadius: 8, backgroundColor: color }}>{children}</View>;
+}
+
+function Invite({ msg }) {
+ const th = useTheme();
+ const [inv, setInv] = useState(null);
+ const [done, setDone] = useState('');
+ const [busy, setBusy] = useState(false);
+ useEffect(() => {
+ let live = true;
+ setInv(null); setDone('');
+ mailRequest('invite', { acct: msg.acct, folder: msg.folder, uid: msg.uid }).then((r) => { if (live) setInv(r); }).catch(() => {});
+ return () => { live = false; };
+ }, [msg.uid, msg.folder]);
+ if (!inv) return null;
+ const ev = inv.event;
+ const when = ev.allDay ? fullDate(ev.start).split(' ').slice(0, -1).join(' ') : `${fullDate(ev.start)} – ${new Date(ev.end).toTimeString().slice(0, 5)}`;
+ const answer = async (ps) => {
+ setBusy(true);
+ try { await mailRequest('invite-respond', { acct: msg.acct, folder: msg.folder, uid: msg.uid, partstat: ps }); setDone(ps); } catch (e) { setDone(`error:${e.message}`); }
+ setBusy(false);
+ };
+ const status = done || inv.myStatus || '';
+ const isReply = inv.method === 'REPLY', isCancel = inv.method === 'CANCEL';
+ return (
+ <View style={{ padding: 12, borderRadius: 10, backgroundColor: th.control, gap: 6 }}>
+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 10 }}>
+ <View style={{ width: 44, height: 48, borderRadius: 8, backgroundColor: '#fff', overflow: 'hidden', alignItems: 'center' }}>
+ <View style={{ height: 14, alignSelf: 'stretch', backgroundColor: '#ff453a', alignItems: 'center', justifyContent: 'center' }}>
+ <Text style={{ fontSize: 9, color: '#fff', fontWeight: 700 }}>{new Date(ev.start).toLocaleDateString(undefined, { month: 'short' }).toUpperCase()}</Text>
+ </View>
+ <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: 12, color: th.textDim }}>{when}</Text>
+ {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>
+ {isReply ? <Text style={{ fontSize: 12, color: th.textDim }}>{t('mail.invite.reply')}</Text>
+ : isCancel ? <Text style={{ fontSize: 12, color: '#ff453a' }}>{t('mail.invite.cancelled')}</Text>
+ : (
+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 8 }}>
+ <Button primary={status !== 'ACCEPTED'} label={status === 'ACCEPTED' ? `✓ ${t('mail.invite.accepted')}` : t('mail.invite.accept')} disabled={busy} onClick={() => answer('ACCEPTED')} />
+ <Button label={status === 'TENTATIVE' ? `✓ ${t('mail.invite.maybe')}` : t('mail.invite.maybe')} disabled={busy} onClick={() => answer('TENTATIVE')} />
+ <Button destructive label={status === 'DECLINED' ? `✓ ${t('mail.invite.declined')}` : t('mail.invite.decline')} disabled={busy} onClick={() => answer('DECLINED')} />
+ {inv.inCalendar || done === 'ACCEPTED' || done === 'TENTATIVE' ? <Text onClick={() => wm.open('calendar', { args: { at: ev.start, uid: ev.uid, nonce: Date.now() } })} style={{ fontSize: 12, color: th.accent }}>{t('mail.invite.show')}</Text> : null}
+ </View>
+ )}
+ {done.startsWith('error:') ? <Text style={{ fontSize: 12, color: '#ff453a' }}>{done.slice(6)}</Text> : null}
+ </View>
+ );
+}
+
+function Attachments({ msg }) {
+ const th = useTheme();
+ const [busy, setBusy] = useState(null);
+ const atts = (msg.atts || []).filter((a) => !(a.inline && a.cid && msg.html));
+ if (!atts.length) return null;
+ const fetch = async (a) => {
+ const r = await mailRequest('attachment', { acct: msg.acct, folder: msg.folder, uid: msg.uid, idx: a.idx });
+ return `${lord.mail.cacheDir()}/${r.path}`;
+ };
+ const open = async (a) => { setBusy(a.idx); try { openPath(await fetch(a), a.name); } catch (e) { /* shown in the row */ } setBusy(null); };
+ const save = async (a) => {
+ setBusy(a.idx);
+ try {
+ const p = await fetch(a);
+ const dir = ['Descargas', 'Downloads', 'Transferências'].map((d) => `${fs.home()}/${d}`).find((d) => { try { return fs.stat(d); } catch (e) { return false; } }) || fs.home();
+ let dst = `${dir}/${a.name}`;
+ for (let k = 2; k < 100; k++) { let ex = false; try { ex = !!fs.stat(dst); } catch (e) { ex = false; } if (!ex) break; dst = `${dir}/${a.name.replace(/(\.[^.]*)?$/, ` (${k})$1`)}`; }
+ fs.copy(p, dst);
+ setTimeout(() => revealPath(dst), 300);
+ } catch (e) { /* ignore */ }
+ setBusy(null);
+ };
+ 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' }}>{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)} />
+ <Button small plain label={t('mail.att.save')} onClick={() => save(a)} />
+ </View>
+ ))}
+ </View>
+ );
+}
+
+function MessageView({ msg, width, onLink, cfg, onTrustSender, collapsed, onExpand }) {
+ const th = useTheme();
+ const [remote, setRemote] = useState(false);
+ const sender = msg.from?.[0]?.email?.toLowerCase() || '';
+ const trusted = (cfg.trustedSenders || []).includes(sender);
+ useEffect(() => { setRemote(false); }, [msg.uid, msg.folder]);
+ const showRemote = remote || trusted;
+ useEffect(() => { if (showRemote && msg.html?.remote?.length) lord.mail.allowImages(msg.html.remote); }, [showRemote, msg.uid]);
+ const from = msg.from?.[0] || {};
+ const nRemote = msg.html?.stats?.remote || 0, nTrackers = msg.html?.stats?.trackers || 0;
+ const 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>
+ <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>
+ <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}
+ <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}
+ </View>
+ <Text style={{ fontSize: 11, color: th.textDim }}>{fullDate(msg.date)}</Text>
+ </View>
+ {nRemote > 0 && !showRemote && (
+ <Banner color={th.control}>
+ <Text style={{ fontSize: 12, color: th.text, flex: 1 }}>{t('mail.images.blocked', { n: nRemote })}{nTrackers ? ` ${t('mail.images.trackers', { n: nTrackers })}` : ''}</Text>
+ <Button small label={t('mail.images.load')} onClick={() => setRemote(true)} />
+ <Button small plain label={t('mail.images.always')} onClick={() => { onTrustSender(sender); setRemote(true); }} />
+ </Banner>
+ )}
+ {warns.length > 0 && (
+ <Banner color="#ff9f0a33">
+ <Text style={{ fontSize: 12, color: th.text, flex: 1 }}>{`⚠ ${t('mail.links.warning', { n: warns.length })}`}</Text>
+ </Banner>
+ )}
+ {msg.invite ? <Invite msg={msg} /> : null}
+ <Attachments msg={msg} />
+ {msg.html ? <HtmlView doc={msg.html} msg={{ acct: msg.acct, folder: msg.folder, uid: msg.uid }} remote={showRemote} width={width} onLink={onLink} />
+ : <TextView text={msg.text} onLink={onLink} width={width} />}
+ {msg.unsubscribe ? <Text style={{ fontSize: 11, color: th.textDim }}>{t('mail.unsubscribeHint')}</Text> : null}
+ </View>
+ );
+}
+
+// ---- the window ----
+
+export default function Mail() {
+ const { args } = useAppWindow();
+ if (args?.compose) return <Compose draft={args.compose} />;
+ return <MailMain />;
+}
+
+function compose(draft) { wm.open('mail', { new: true, args: { compose: draft || {} } }); }
+
+function replyDraft(msg, mode) {
+ const acct = msg.acct;
+ const me = (mailAccounts.get(acct)?.email || '').toLowerCase();
+ const from = msg.replyTo?.length ? msg.replyTo : msg.from || [];
+ const subj = msg.subject || '';
+ const quoteHead = t('mail.quoteHead', { date: fullDate(msg.date), name: msg.from?.[0]?.name || msg.from?.[0]?.email || '' });
+ const body = `\n\n${quoteHead}\n${quote(msg.text || '')}`;
+ if (mode === 'forward') {
+ const head = [`---------- ${t('mail.forwarded')} ----------`, `${t('mail.from')}: ${(msg.from || []).map((a) => (a.name ? `${a.name} <${a.email}>` : a.email)).join(', ')}`,
+ `${t('mail.date')}: ${fullDate(msg.date)}`, `${t('mail.subject')}: ${subj}`, `${t('mail.to')}: ${(msg.to || []).map((a) => a.email).join(', ')}`].join('\n');
+ return { acct, subject: /^(fwd?|rv|tr):/i.test(subj) ? subj : `Fwd: ${subj}`, body: `\n\n${head}\n\n${msg.text || ''}`, original: { acct, folder: msg.folder, uid: msg.uid, forward: true }, forwardAtts: msg };
+ }
+ const to = from.filter((a) => a.email.toLowerCase() !== me);
+ const cc = mode === 'all' ? [...(msg.to || []), ...(msg.cc || [])].filter((a) => a.email.toLowerCase() !== me && !to.some((x) => x.email === a.email)) : [];
+ const refs = [msg.refs, msg.msgid].filter(Boolean).join(' ').trim();
+ return { acct, to: to.length ? to : from, cc, subject: /^re:/i.test(subj) ? subj : `Re: ${subj}`, body, inReplyTo: msg.msgid, references: refs,
+ original: { acct, folder: msg.folder, uid: msg.uid } };
+}
+
+function MailMain() {
+ const th = useTheme();
+ const { id: wid, args, focused } = useAppWindow();
+ const st = useStore(mailStatus);
+ const [folders, setFolders] = useState([]);
+ const [src, setSrc] = useState({ kind: 'unified' });
+ const [listRev, setListRev] = useState(0);
+ const [sel, setSel] = useState(null); // list item
+ const [msg, setMsg] = useState(null);
+ const [thread, setThread] = useState([]);
+ const [expanded, setExpanded] = useState({});
+ const [loadErr, setLoadErr] = useState('');
+ const [q, setQ] = useState('');
+ const [sheet, setSheet] = useState(null); // 'setup' | 'accounts' | { cert } | { password } | { link } | { menu }
+ const [cfg, setCfg] = useState(mailConfig.get());
+ const readingRef = useRef(null);
+ const { w: readW } = useSize(readingRef, 400);
+ const accounts = cfg.accounts.filter((a) => a.kind === 'mail');
+
+ const loadFolders = () => mailRequest('folders').then((r) => setFolders(r.accounts || [])).catch(() => {});
+ useEffect(() => {
+ loadFolders();
+ let timer = null;
+ const off = onMailEvent((ev) => {
+ if (ev.ev === 'changed' || ev.ev === 'folders' || ev.ev === 'status' || ev.ev === 'ready') {
+ if (!timer) timer = setTimeout(() => { timer = null; loadFolders(); setListRev((v) => v + 1); }, 400);
+ }
+ });
+ return () => { off(); if (timer) clearTimeout(timer); };
+ }, []);
+ useEffect(() => mailStatus.subscribe(() => setCfg(mailConfig.get())), []);
+
+ // opened from a notification or another app
+ useEffect(() => {
+ if (args?.acct && args?.folder) {
+ setSrc({ kind: 'folder', acct: args.acct, folder: args.folder });
+ if (args.uid) openItem({ acct: args.acct, folder: args.folder, uid: args.uid });
+ }
+ }, [args?.nonce]);
+
+ const openItem = async (it) => {
+ setSel(it);
+ setLoadErr('');
+ setExpanded({});
+ try {
+ const m = await mailRequest('open', { acct: it.acct, folder: it.folder, uid: it.uid });
+ setMsg(m);
+ if (it.n > 1 && it.tk) {
+ const r = await mailRequest('thread', { acct: it.acct, tk: it.tk }).catch(() => ({ items: [] }));
+ setThread(r.items || []);
+ } else setThread([]);
+ // marked as read after a moment, like other mail apps
+ if (!m.seen) setTimeout(() => mailRequest('flag', { acct: it.acct, folder: it.folder, uids: [it.uid], add: ['seen'] }).catch(() => {}), 1200);
+ } catch (e) { setMsg(null); setLoadErr(e.code === 'offline' ? t('mail.offlineNotCached') : e.message); }
+ };
+
+ const selKey = sel ? `${sel.acct}|${sel.folder}|${sel.uid}` : null;
+ const targets = () => {
+ if (!sel) return null;
+ const list = sel.thread?.length ? sel.thread : [{ acct: sel.acct, folder: sel.folder, uid: sel.uid }];
+ return { acct: sel.acct, folder: sel.folder, uids: list.filter((x) => x.folder === sel.folder && x.acct === sel.acct).map((x) => x.uid) };
+ };
+ const specialOf = (acct, sp) => folders.find((a) => a.id === acct)?.folders.find((f) => f.special === sp)?.name;
+ const act = {
+ reply: () => msg && compose(replyDraft(msg, 'reply')),
+ replyAll: () => msg && compose(replyDraft(msg, 'all')),
+ forward: async () => {
+ if (!msg) return;
+ const d = replyDraft(msg, 'forward');
+ // the original's attachments go along (saved from the cache)
+ const paths = [];
+ for (const a of msg.atts || []) {
+ try { const r = await mailRequest('attachment', { acct: msg.acct, folder: msg.folder, uid: msg.uid, idx: a.idx }); paths.push(`${lord.mail.cacheDir()}/${r.path}`); } catch (e) { /* skip */ }
+ }
+ delete d.forwardAtts;
+ compose({ ...d, attachments: paths, noSignature: false });
+ },
+ archive: async () => {
+ const tg = targets(); if (!tg) return;
+ let to = specialOf(tg.acct, 'archive');
+ if (!to) { await mailRequest('create-folder', { acct: tg.acct, name: 'Archive' }).catch(() => {}); to = 'Archive'; }
+ if (to === tg.folder) return;
+ await mailRequest('move', { ...tg, to }).catch(() => {});
+ setSel(null); setMsg(null); setListRev((v) => v + 1);
+ },
+ remove: async () => {
+ const tg = targets(); if (!tg) return;
+ const next = MessageList.neighbour?.(selKey, 1);
+ await mailRequest('delete', tg).catch(() => {});
+ setListRev((v) => v + 1);
+ if (next) openItem(next.it); else { setSel(null); setMsg(null); }
+ },
+ flag: async () => {
+ const tg = targets(); if (!tg) return;
+ const on = !(sel.anyFlag || sel.flagged);
+ await mailRequest('flag', { ...tg, ...(on ? { add: ['flagged'] } : { remove: ['flagged'] }) }).catch(() => {});
+ setSel({ ...sel, anyFlag: on, flagged: on });
+ },
+ unread: async () => {
+ const tg = targets(); if (!tg) return;
+ const unread = sel.unreadN !== undefined ? sel.unreadN > 0 : !sel.seen;
+ await mailRequest('flag', { ...tg, ...(unread ? { add: ['seen'] } : { remove: ['seen'] }) }).catch(() => {});
+ },
+ label: async (l) => {
+ const tg = targets(); if (!tg) return;
+ const has = (sel.labels || []).includes(l);
+ await mailRequest('flag', { ...tg, ...(has ? { remove: [`label${l}`] } : { add: [`label${l}`] }) }).catch(() => {});
+ setSel({ ...sel, labels: has ? sel.labels.filter((x) => x !== l) : [...(sel.labels || []), l] });
+ },
+ junk: async () => {
+ const tg = targets(); if (!tg) return;
+ const to = specialOf(tg.acct, 'junk');
+ if (to && to !== tg.folder) { await mailRequest('move', { ...tg, to }).catch(() => {}); setSel(null); setMsg(null); setListRev((v) => v + 1); }
+ },
+ };
+
+ const onLink = (link) => {
+ if (!link?.h) return;
+ if (/^mailto:/i.test(link.h)) {
+ const [addr, qs] = link.h.slice(7).split('?');
+ const subj = /(?:^|&)subject=([^&]*)/i.exec(qs || '');
+ compose({ to: [{ name: '', email: decodeURIComponent(addr) }], subject: subj ? decodeURIComponent(subj[1]) : '' });
+ return;
+ }
+ setSheet({ link });
+ };
+
+ const trustSender = (email) => {
+ if (!email) return;
+ const c = mailConfig.get();
+ mailConfig.save({ ...c, trustedSenders: [...new Set([...(c.trustedSenders || []), email])] });
+ setCfg(mailConfig.get());
+ };
+
+ useKeyboard((e) => {
+ if (!focused) return false;
+ const m = e.ctrl || e.meta;
+ const b = (e.base || '').toLowerCase();
+ if (m && b === 'n') { compose(); return true; }
+ if (m && b === 'r' && !e.shift) { act.reply(); return true; }
+ if (m && b === 'r' && e.shift) { act.replyAll(); return true; }
+ if (m && b === 'j') { act.forward(); return true; }
+ if (m && b === 'e') { act.archive(); return true; }
+ if (!m && (e.key === 'Delete' || (e.key === 'Backspace' && e.meta))) { act.remove(); return true; }
+ if (!m && (e.key === 'ArrowDown' || e.key === 'ArrowUp') && selKey) { const n = MessageList.neighbour?.(selKey, e.key === 'ArrowDown' ? 1 : -1); if (n) openItem(n.it); return true; }
+ return false;
+ });
+
+ useEffect(() => {
+ wm.setMenus(wid, [
+ { label: t('mail.menu.file'), items: [
+ { label: t('mail.new'), hint: '❖N', onClick: () => compose() },
+ { label: t('mail.menu.addAccount'), onClick: () => setSheet('setup') },
+ { label: t('mail.menu.accounts'), onClick: () => setSheet('accounts') }, '-',
+ { label: t('mail.menu.sync'), onClick: () => mailRequest('sync', {}).catch(() => {}) },
+ ] },
+ { label: t('mail.menu.message'), items: [
+ { label: t('mail.reply'), hint: '❖R', onClick: act.reply, disabled: !msg },
+ { label: t('mail.replyAll'), hint: '❖⇧R', onClick: act.replyAll, disabled: !msg },
+ { label: t('mail.forward'), hint: '❖J', onClick: act.forward, disabled: !msg }, '-',
+ { label: t('mail.archive'), hint: '❖E', onClick: act.archive, disabled: !sel },
+ { label: t('mail.delete'), hint: '⌦', onClick: act.remove, disabled: !sel },
+ { label: t('mail.junk'), onClick: act.junk, disabled: !sel },
+ { label: t('mail.markUnread'), onClick: act.unread, disabled: !sel },
+ { label: t('mail.flag'), onClick: act.flag, disabled: !sel },
+ ] },
+ ]);
+ });
+
+ // ---- sidebar ----
+ const sidebar = (
+ <View style={{ width: 220, backgroundColor: th.sidebarBg }}>
+ <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' })} />
+ <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 }}>
+ <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}
+ 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(''); }} />
+ ))}
+ </View>
+ );
+ })}
+ <Text style={{ fontSize: 11, fontWeight: 600, color: th.textDim, margin: 6, marginTop: 12 }}>{t('mail.categories')}</Text>
+ {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>
+ </View>
+ );
+
+ const toolbar = (
+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 6, paddingHorizontal: 10, height: 46 }}>
+ <Button primary label={`✎ ${t('mail.new')}`} onClick={() => compose()} />
+ <View style={{ width: 8 }} />
+ <Button label={`↩ ${t('mail.reply')}`} disabled={!msg} onClick={act.reply} />
+ <Button label={`↩︎↩︎ ${t('mail.replyAll')}`} disabled={!msg} onClick={act.replyAll} />
+ <Button label={`↪ ${t('mail.forward')}`} disabled={!msg} onClick={act.forward} />
+ <View style={{ width: 8 }} />
+ <Button label={`🗄 ${t('mail.archive')}`} disabled={!sel} onClick={act.archive} />
+ <Button label={`🗑 ${t('mail.delete')}`} disabled={!sel} onClick={act.remove} />
+ <Button label={`⚑ ${t('mail.flag')}`} disabled={!sel} onClick={act.flag} />
+ <Button label={`● ${t('mail.category')}`} disabled={!sel} onClick={() => setSheet({ menu: 'labels' })} />
+ <View style={{ flex: 1 }} />
+ <View style={{ width: 220 }}>
+ <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>
+ </View>
+ );
+
+ const listTitle = src.kind === 'search' ? t('mail.search.results', { q: src.q }) : src.kind === 'unified'
+ ? (src.label ? categoryName(src.label, cfg) : src.filter === 'unread' ? t('mail.unread') : src.filter === 'flagged' ? t('mail.flagged') : t('mail.unifiedInbox'))
+ : folderName(folders.find((a) => a.id === src.acct)?.folders.find((f) => f.name === src.folder) || { display: src.folder || '' });
+
+ const noAccounts = !accounts.length;
+ return (
+ <View 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>
+ <View style={{ height: 1, backgroundColor: th.separator }} />
+ {!mailAvailable() ? <Text style={{ margin: 16, fontSize: 13, color: th.textDim }}>{t('mail.unavailable')}</Text>
+ : noAccounts ? (
+ <View style={{ margin: 18, gap: 10 }}>
+ <Text style={{ fontSize: 13, color: th.textDim }}>{t('mail.noAccounts')}</Text>
+ <Button primary label={t('mail.addAccount')} onClick={() => setSheet('setup')} />
+ </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>
+ {(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>)}
+ </View>
+ ) : 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} />
+ )) : null}
+ <MessageView msg={msg} width={readW - 36} 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>
+ )}
+ </View>
+ </View>
+ </View>
+ {sheet === 'setup' && <AccountSetup onClose={() => { setSheet(null); setCfg(mailConfig.get()); loadFolders(); }} />}
+ {sheet === 'accounts' && <AccountsPanel onClose={() => { setSheet(null); setCfg(mailConfig.get()); loadFolders(); }} onAdd={() => setSheet('setup')} />}
+ {sheet?.cert && <CertDialog cert={sheet.cert} onClose={() => setSheet(null)} />}
+ {!sheet && st.certs[0] && <CertDialog cert={st.certs[0]} onClose={() => mailStatus.set((s) => ({ ...s, certs: s.certs.slice(1) }))} />}
+ {sheet?.password && <PasswordPrompt acct={sheet.password} onClose={() => setSheet(null)} />}
+ {sheet?.link && <LinkSheet link={sheet.link} onClose={() => setSheet(null)} />}
+ {sheet?.menu === 'labels' && (
+ <Sheet width={280}>
+ <Text style={{ fontSize: 14, fontWeight: 700, color: th.text }}>{t('mail.category')}</Text>
+ {CATEGORY_COLORS.map((c, i) => (
+ <View key={c} onClick={() => { act.label(i + 1); setSheet(null); }} style={{ flexDirection: 'row', alignItems: 'center', gap: 8, padding: 6, borderRadius: 6 }}>
+ <View style={{ width: 12, height: 12, borderRadius: 6, backgroundColor: c }} />
+ <Text style={{ flex: 1, fontSize: 13, color: th.text }}>{categoryName(i + 1, cfg)}</Text>
+ {(sel?.labels || []).includes(i + 1) ? <Text style={{ color: th.accent }}>✓</Text> : null}
+ </View>
+ ))}
+ <View style={{ flexDirection: 'row', justifyContent: 'flex-end' }}><Button label={t('mail.close')} onClick={() => setSheet(null)} /></View>
+ </Sheet>
+ )}
+ </View>
+ );
+}
+
+function SideRow({ icon, label, count, selected, onClick, indent = 0 }) {
+ const th = useTheme();
+ 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>}
+ <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}
+ </View>
+ );
+}
+
+function ThreadItem({ it, expanded, onToggle, width, onLink, cfg, onTrustSender }) {
+ const th = useTheme();
+ const [m, setM] = useState(null);
+ useEffect(() => { 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>
+ <Text style={{ fontSize: 11, color: th.textDim }}>{listDate(it.date)}</Text>
+ </View>
+ );
+}
+
+// A link: there is no web engine in LordOS, so the address is shown and can be copied. A link
+// whose visible text names another site is called out.
+function LinkSheet({ link, onClose }) {
+ const th = useTheme();
+ let host = '';
+ try { host = link.h.replace(/^[a-z]+:\/\//i, '').split(/[/?#]/)[0]; } catch (e) { host = ''; }
+ return (
+ <Sheet width={500}>
+ <Text style={{ fontSize: 16, fontWeight: 700, color: link.w ? '#ff453a' : th.text }}>{link.w ? t('mail.links.deceptiveTitle') : t('mail.links.title')}</Text>
+ {link.w ? <Text style={{ fontSize: 13, color: th.text }}>{t('mail.links.deceptiveBody', { shown: link.txt || '', host })}</Text> : null}
+ <View style={{ padding: 10, borderRadius: 8, backgroundColor: th.control }}><Text style={{ fontSize: 12, color: th.text, fontFamily: 'monospace' }}>{link.h}</Text></View>
+ <Text style={{ fontSize: 12, color: th.textDim }}>{t('mail.links.noBrowser')}</Text>
+ <View style={{ flexDirection: 'row', justifyContent: 'flex-end', gap: 8 }}>
+ <Button label={t('mail.close')} onClick={onClose} />
+ <Button primary={!link.w} label={t('mail.links.copy')} onClick={() => { clipboard.set(link.h); onClose(); }} />
+ </View>
+ </Sheet>
+ );
+}
+
+export { contactName };
diff --git a/apps/mail/md.js b/apps/mail/md.js
new file mode 100644
index 0000000..f3d9fb2
--- /dev/null
+++ b/apps/mail/md.js
@@ -0,0 +1,59 @@
+// md.js — what Mail sends: the body is written as markdown (in rich-text mode the toolbar adds
+// the marks for you and a preview shows the result), and goes out as text/plain plus a simple
+// text/html made here. The HTML is ours, built from parsed markdown: nothing the user types is
+// passed through as raw HTML.
+import { parseMarkdown, parseInline } from '@lordos/sdk';
+
+const esc = (s) => String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
+const safeUrl = (u) => (/^(https?:|mailto:)/i.test(u) ? u : '#');
+
+function inlineHtml(text) {
+ return parseInline(text).map((r) => {
+ if (r.image) return esc(r.alt || '');
+ let s = esc(r.text).replace(/\n/g, '<br>');
+ if (r.code) s = `<code style="font-family:monospace;background:#f2f2f2;padding:0 3px">${s}</code>`;
+ if (r.bold) s = `<b>${s}</b>`;
+ if (r.italic) s = `<i>${s}</i>`;
+ if (r.strike) s = `<s>${s}</s>`;
+ if (r.link) s = `<a href="${esc(safeUrl(r.link))}">${s}</a>`;
+ return s;
+ }).join('');
+}
+
+function blocksHtml(blocks) {
+ const out = [];
+ for (const b of blocks) {
+ if (b.type === 'heading') out.push(`<h${Math.min(3, b.level)}>${inlineHtml(b.text)}</h${Math.min(3, b.level)}>`);
+ else if (b.type === 'paragraph') out.push(`<p style="margin:0 0 10px 0">${inlineHtml(b.text)}</p>`);
+ else if (b.type === 'quote') out.push(`<blockquote style="margin:0 0 10px 0;padding-left:10px;border-left:3px solid #ccc;color:#555">${blocksHtml(b.blocks)}</blockquote>`);
+ else if (b.type === 'code') out.push(`<pre style="font-family:monospace;background:#f5f5f5;padding:8px">${esc(b.text)}</pre>`);
+ else if (b.type === 'hr') out.push('<hr>');
+ else if (b.type === 'list') {
+ const ordered = b.items[0]?.ordered;
+ out.push(ordered ? '<ol>' : '<ul>');
+ for (const it of b.items) {
+ const box = it.task === null || it.task === undefined ? '' : it.task ? '☑ ' : '☐ ';
+ out.push(`<li style="margin-left:${it.depth * 16}px">${box}${inlineHtml(it.text)}</li>`);
+ }
+ out.push(ordered ? '</ol>' : '</ul>');
+ } else if (b.type === 'table') {
+ out.push('<table border="1" cellpadding="4" style="border-collapse:collapse"><tr>');
+ out.push(b.header.map((c) => `<th>${inlineHtml(c)}</th>`).join(''));
+ out.push('</tr>');
+ for (const r of b.rows) out.push(`<tr>${r.map((c) => `<td>${inlineHtml(c)}</td>`).join('')}</tr>`);
+ out.push('</table>');
+ }
+ }
+ return out.join('\n');
+}
+
+export function mdToHtml(src) {
+ return `<div style="font-family:Inter,Arial,sans-serif;font-size:14px;line-height:1.45">${blocksHtml(parseMarkdown(src))}</div>`;
+}
+
+// The text/plain part: the markdown stays readable; links become "text <url>".
+export function mdToText(src) {
+ return String(src).replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (m, a, u) => (a === u ? u : `${a} <${u}>`)).replace(/\*\*(.+?)\*\*/g, '*$1*');
+}
+
+export const quote = (text) => String(text || '').replace(/\r\n/g, '\n').split('\n').map((l) => (l.startsWith('>') ? `>${l}` : `> ${l}`)).join('\n');
diff --git a/apps/mail/util.js b/apps/mail/util.js
new file mode 100644
index 0000000..8d90655
--- /dev/null
+++ b/apps/mail/util.js
@@ -0,0 +1,56 @@
+// util.js — small helpers for Mail: dates in the list, folder names, color categories, opening
+// an attachment the way Files would.
+import { t, formatDate, formatTime, wm, getApp, fs, defaultOpenerId, nativeOf, calendarEvents, contacts, addressBooks } from '@lordos/sdk';
+
+export const CATEGORY_COLORS = ['#ff453a', '#ff9f0a', '#ffd60a', '#30d158', '#0a84ff', '#bf5af2'];
+// labels are built at render time (they follow the language)
+export const categoryName = (i, cfg) => cfg?.categories?.[i - 1]?.name || t(`mail.cat.${i}`);
+
+export function listDate(ms) {
+ const d = new Date(ms), now = new Date();
+ if (d.toDateString() === now.toDateString()) return formatTime(d);
+ const y = new Date(now); y.setDate(now.getDate() - 1);
+ if (d.toDateString() === y.toDateString()) return t('mail.yesterday');
+ if (now - d < 6 * 86400000) return formatDate(d, { weekday: 'short' });
+ return formatDate(d, { day: 'numeric', month: 'short', ...(d.getFullYear() !== now.getFullYear() ? { year: 'numeric' } : {}) });
+}
+
+export const fullDate = (ms) => `${formatDate(new Date(ms), { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' })} ${formatTime(new Date(ms))}`;
+
+const SPECIAL_ICONS = { inbox: '📥', drafts: '📝', sent: '📤', archive: '🗄️', junk: '⚠️', trash: '🗑️', all: '📚', flagged: '🚩' };
+export const folderIcon = (f) => SPECIAL_ICONS[f.special] || '📁';
+export const folderName = (f) => (f.special && f.special !== 'all' && f.special !== 'flagged' ? t(`mail.folder.${f.special}`) : f.display);
+
+export const addrText = (a) => (a?.name ? `${a.name} <${a.email}>` : a?.email || '');
+export const addrShort = (a) => a?.name || a?.email || '';
+
+export function formatSize(n) {
+ if (n < 1024) return `${n} B`;
+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(0)} KB`;
+ return `${(n / 1048576).toFixed(1)} MB`;
+}
+
+// The same rules as Files (apps/files/ops.js): our apps for documents, images and media, the
+// system's default app for the rest, and otherwise reveal it in Files.
+export function openPath(path, name) {
+ const n = String(name || path).toLowerCase();
+ if (/\.pdf$/.test(n) && getApp('pdf')) return wm.open('pdf', { new: true, args: { path } });
+ if (/\.(png|jpe?g|gif|webp|bmp|heic|avif)$/.test(n) && getApp('photos')) return wm.open('photos', { new: true, args: { path } });
+ if (/\.(mp3|ogg|flac|wav|m4a|opus|mp4|mkv|webm|mov|avi)$/.test(n) && getApp('player')) return wm.open('player', { args: { path } });
+ if (/\.(txt|md|csv|log|json|xml|ya?ml|c|h|js|py|sh)$/.test(n) && getApp('editor')) return wm.open('editor', { args: { path } });
+ if (/\.ics$/.test(n) && getApp('calendar')) { calendarEvents.importFile(path).then(() => wm.open('calendar')).catch(() => revealPath(path)); return true; }
+ if (/\.vcf$/.test(n) && getApp('contacts')) {
+ addressBooks.list().then((b) => (b[0] ? contacts.importFile(path, b[0].id) : null)).then(() => wm.open('contacts')).catch(() => revealPath(path));
+ return true;
+ }
+ try {
+ const def = defaultOpenerId(typeof lord.mime !== 'undefined' ? lord.mime.guess(n) : '');
+ const native = nativeOf(def);
+ if (native && getApp(native)) return wm.open(native, { new: true, args: { path } });
+ if (def && lord.apps.launchWith(def.replace(/\.desktop$/, ''), path)) return true;
+ if (lord.apps.launchWith('', path)) return true;
+ } catch (e) { /* no default app */ }
+ return revealPath(path);
+}
+
+export const revealPath = (path) => wm.open('files', { new: true, args: { path: fs.parent(path), select: fs.basename(path), nonce: Date.now() } });
diff --git a/apps/monitor/Network.jsx b/apps/monitor/Network.jsx
index 06d7384..d097a96 100644
--- a/apps/monitor/Network.jsx
+++ b/apps/monitor/Network.jsx
@@ -12,7 +12,7 @@
// reglas futuras son { appKey, host | país, puerto, protocolo, dirección, verdict }: la columna
// de regla de la lista y los contadores de permitidas/denegadas ya están en su lugar.
import {
- View, Text, Image, ScrollView, TextInput, useTheme, useLocale, useStore, monitor, monitorConnections, useMonitor,
+ View, Text, Image, ScrollView, SearchField, useTheme, useLocale, useStore, monitor, monitorConnections, useMonitor,
formatBytes, formatNumber, tOptional, useSystemInfo, wm, direction, firewall, firewallState, useLauncherApps,
} from '@lordos/sdk';
import { useEffect, useMemo, useRef, useState } from 'react';
@@ -201,7 +201,7 @@ function Section({ title, children }) {
const t = useTheme();
return (
<View style={{ gap: 6 }}>
- <Text style={{ fontSize: 11, fontWeight: 700, color: t.textDim }}>{title}</Text>
+ <Text style={{ fontSize: 11, fontWeight: 600, color: t.textDim }}>{title}</Text>
{children}
</View>
);
@@ -282,7 +282,7 @@ function Detail({ g, tr, user }) {
<View style={{ flexDirection: 'row', alignItems: 'center', gap: 10 }}>
<AppGlyph item={g.item} size={32} />
<View style={{ flex: 1, minWidth: 0 }}>
- <Text style={{ fontSize: 15, fontWeight: 700, color: t.text }}>{g.key === 'lordos' ? tr('monitor.lordos') : g.name}</Text>
+ <Text style={{ fontSize: 15, fontWeight: 600, color: t.text }}>{g.key === 'lordos' ? tr('monitor.lordos') : g.name}</Text>
<Text style={{ fontSize: 11, color: t.textDim }}>{tr('monitor.net.connCount', { count: g.conns.length - g.listen.length })}</Text>
</View>
</View>
@@ -322,7 +322,7 @@ function PlaceDetail({ p, tr }) {
return (
<>
<View style={{ gap: 2 }}>
- <Text style={{ fontSize: 15, fontWeight: 700, color: t.text }}>{countryName(p.cc)}</Text>
+ <Text style={{ fontSize: 15, fontWeight: 600, color: t.text }}>{countryName(p.cc)}</Text>
<Text style={{ fontSize: 11, color: t.textDim }}>{tr('monitor.net.connCount', { count: p.count })}</Text>
</View>
<Section title={tr('monitor.net.data')}>
@@ -379,10 +379,10 @@ export function NetworkTab({ last, prefs }) {
const toggle = (key) => setOpen((s) => { const n = new Set(s); if (n.has(key)) n.delete(key); else n.add(key); return n; });
const column = { borderRadius: 12, backgroundColor: card.bg, border: `1px solid ${t.separator}`, padding: 12 };
return (
- <View style={{ flex: 1, flexDirection: 'row', gap: 12, paddingHorizontal: 16, paddingVertical: 14 }}>
- {/* izquierda */}
+ <View style={{ flex: 1, flexDirection: 'row', gap: 12, paddingHorizontal: 20, paddingVertical: 16 }}>
+ {/* left */}
<View style={{ ...column, width: 320, gap: 8, padding: 10 }}>
- <TextInput value={q} onChange={setQ} placeholder={tr('monitor.net.search')} onCancel={() => setQ('')} />
+ <SearchField value={q} onChange={setQ} placeholder={tr('monitor.net.search')} />
<View style={{ flexDirection: 'row', paddingHorizontal: 8 }}>
<Text style={{ flex: 1, fontSize: 10, fontWeight: 600, color: t.textDim }}>{tr('monitor.net.apps', { count: apps.length })}</Text>
<Text style={{ width: 54, fontSize: 10, fontWeight: 600, color: t.textDim, textAlign: 'end' }}>{tr('monitor.net.dataCol')}</Text>
@@ -402,11 +402,11 @@ export function NetworkTab({ last, prefs }) {
<View style={{ flexDirection: 'row', gap: 14, paddingHorizontal: 4 }}>
<View style={{ flex: 1 }}>
<Text style={{ fontSize: 10, color: t.textDim }}>{`↓ ${tr('monitor.received')}`}</Text>
- <Text style={{ fontSize: 14, fontWeight: 700, color: C.rx }}>{fmt.rate(tr, last.net.rx)}</Text>
+ <Text style={{ fontSize: 14, fontWeight: 600, color: C.rx }}>{fmt.rate(tr, last.net.rx)}</Text>
</View>
<View style={{ flex: 1 }}>
<Text style={{ fontSize: 10, color: t.textDim }}>{`↑ ${tr('monitor.sent')}`}</Text>
- <Text style={{ fontSize: 14, fontWeight: 700, color: C.tx }}>{fmt.rate(tr, last.net.tx)}</Text>
+ <Text style={{ fontSize: 14, fontWeight: 600, color: C.tx }}>{fmt.rate(tr, last.net.tx)}</Text>
</View>
</View>
<TrafficBarsFromStore />
diff --git a/apps/monitor/index.jsx b/apps/monitor/index.jsx
index ee3ca3e..ef2e514 100644
--- a/apps/monitor/index.jsx
+++ b/apps/monitor/index.jsx
@@ -1,10 +1,10 @@
-// Monitor — uso de CPU, memoria, red, discos y procesos de este equipo, y las conexiones de
-// red de cada app con un mapa (ver docs/MONITOR.md). Copia el Monitor de TangoOS: pestañas,
-// tarjetas oscuras con número grande y gráfico en vivo, fila de datos chicos y pie con la
-// frecuencia de muestreo. Las métricas las lee lord-server (lord.monitor) solo mientras esta
-// ventana está abierta, cuatro veces por segundo.
+// Monitor: CPU, memory, network, disk and process usage of this computer, and the network
+// connections of each app on a map (see docs/MONITOR.md). It follows TangoOS's Monitor: tabs,
+// dark cards with a big number and a live chart, a row of small stats and a footer with the
+// sampling rate. lord-server (lord.monitor) reads the metrics only while this window is open,
+// four times per second.
import {
- View, Text, Image, ScrollView, Segmented, TextInput, useTheme, useLocale, useStore, useSettings, useAppWindow,
+ View, Text, Image, ScrollView, Segmented, SearchField, Toolbar, typeScale, useTheme, useLocale, useStore, useSettings, useAppWindow,
useMonitor, monitor, monitorProcesses, monitorSamples, formatBytes, formatNumber, LordOSLogo, iconFromFile,
} from '@lordos/sdk';
import * as sdk from '@lordos/sdk';
@@ -17,15 +17,15 @@ import { FirewallPrivacy } from './Firewall.jsx';
export function Icon({ size }) { return <MonitorIcon size={size} />; }
-// Colores de las series (los de TangoOS)
+// Series colors (TangoOS's)
export const C = { mem: '#8b5cf6', cache: '#c4b5fd', rx: '#22c55e', tx: '#f97316', read: '#2f7cf6', write: '#ec4899' };
-// Settings → Privacidad → Monitor (la página es de otro módulo: se registra si existe).
+// Settings → Privacy → Monitor (the page belongs to another module: registered if it exists).
if (typeof sdk.registerPrivacySection === 'function') sdk.registerPrivacySection({ id: 'monitor', order: 10, Component: MonitorPrivacy });
-// … y «Red de las apps»: apps confiables y restringidas (lord.fw, docs/FIREWALL.md)
+// … and "App network": trusted and restricted apps (lord.fw, docs/FIREWALL.md)
if (typeof sdk.registerPrivacySection === 'function') sdk.registerPrivacySection({ id: 'firewall', order: 11, Component: FirewallPrivacy });
-// ---- formatos ----
+// ---- formats ----
export const fmt = {
pct: (tr, v) => tr('monitor.pct', { v: formatNumber(Math.round((v || 0) * 100), 0) }),
mem: (n) => formatBytes(Math.max(0, n || 0)),
@@ -33,13 +33,13 @@ export const fmt = {
load: (v) => formatNumber(v || 0, 2),
};
-// Tarjeta oscura con ícono y título (tm-card)
+// Dark card with an icon and a title (tm-card)
export function useCardStyle() {
const t = useTheme();
const dark = t.mode === 'dark';
return {
bg: dark ? '#26272c' : '#f4f4f6',
- style: { borderRadius: 12, backgroundColor: dark ? '#26272c' : '#f4f4f6', border: `1px solid ${t.separator}`, paddingHorizontal: 16, paddingTop: 14, paddingBottom: 12, gap: 10, minWidth: 0 },
+ style: { borderRadius: 12, backgroundColor: dark ? '#26272c' : '#f4f4f6', border: `1px solid ${t.separator}`, padding: 16, gap: 12, minWidth: 0 },
};
}
@@ -50,7 +50,7 @@ export function Card({ icon, title, right, children, style }) {
<View style={{ ...card.style, ...style }}>
<View style={{ flexDirection: 'row', alignItems: 'center', gap: 8 }}>
{icon ? <Glyph name={icon} color={t.accent} /> : null}
- <Text style={{ fontSize: 12, fontWeight: 600, color: t.textDim }}>{title}</Text>
+ <Text style={{ fontSize: typeScale.callout, fontWeight: 600, color: t.textDim, whiteSpace: 'nowrap' }}>{title}</Text>
<View style={{ flex: 1 }} />
{right}
</View>
@@ -63,42 +63,42 @@ export function Big({ value, small }) {
const t = useTheme();
return (
<View style={{ flexDirection: 'row', alignItems: 'flex-end', gap: 6 }}>
- <Text style={{ fontSize: 26, fontWeight: 700, color: t.text, lineHeight: 1.05 }}>{value}</Text>
+ <Text style={{ fontSize: 24, fontWeight: 600, color: t.text, lineHeight: 1.05 }}>{value}</Text>
{small ? <Text style={{ fontSize: 13, fontWeight: 500, color: t.textDim, marginBottom: 2 }}>{small}</Text> : null}
</View>
);
}
-// Par de valores con leyenda de color (Recibido / Enviado)
+// Pair of values with a color legend (Received / Sent)
export function Pair({ items }) {
const t = useTheme();
return (
- <View style={{ flexDirection: 'row', gap: 18 }}>
+ <View style={{ flexDirection: 'row', gap: 20 }}>
{items.map((i) => (
- <View key={i.label} style={{ gap: 1 }}>
+ <View key={i.label} style={{ gap: 2 }}>
<View style={{ flexDirection: 'row', alignItems: 'center', gap: 5 }}>
{i.color && <View style={{ width: 8, height: 8, borderRadius: 2, backgroundColor: i.color }} />}
<Text style={{ fontSize: 11, color: t.textDim }}>{i.label}</Text>
</View>
- <Text style={{ fontSize: 17, fontWeight: 700, color: t.text }}>{i.value}</Text>
+ <Text style={{ fontSize: typeScale.title, fontWeight: 600, color: t.text }}>{i.value}</Text>
</View>
))}
</View>
);
}
-// Dato chico (tm-stat)
+// Small stat (tm-stat)
export function Stat({ label, value, unit, icon, children }) {
const t = useTheme();
const card = useCardStyle();
return (
- <View style={{ flex: 1, minWidth: 120, borderRadius: 10, backgroundColor: card.bg, border: `1px solid ${t.separator}`, paddingHorizontal: 12, paddingVertical: 10, gap: 2 }}>
+ <View style={{ flex: 1, minWidth: 120, borderRadius: 10, backgroundColor: card.bg, border: `1px solid ${t.separator}`, paddingHorizontal: 12, paddingVertical: 10, gap: 4 }}>
<View style={{ flexDirection: 'row', alignItems: 'center', gap: 5 }}>
{icon ? <Glyph name={icon} color={t.textDim} size={11} /> : null}
<Text style={{ fontSize: 11, color: t.textDim, whiteSpace: 'nowrap' }}>{label}</Text>
</View>
<View style={{ flexDirection: 'row', alignItems: 'flex-end', gap: 4 }}>
- <Text style={{ fontSize: 17, fontWeight: 700, color: t.text, whiteSpace: 'nowrap' }}>{value}</Text>
+ <Text style={{ fontSize: typeScale.title, fontWeight: 600, color: t.text, whiteSpace: 'nowrap' }}>{value}</Text>
{unit ? <Text style={{ fontSize: 11, color: t.textDim, marginBottom: 2 }}>{unit}</Text> : null}
</View>
{children}
@@ -106,7 +106,7 @@ export function Stat({ label, value, unit, icon, children }) {
);
}
-// Series derivadas de la historia de muestras
+// Series derived from the sample history
function useSeries(samples) {
return useMemo(() => {
const pick = (f) => samples.map(f);
@@ -125,7 +125,7 @@ function useSeries(samples) {
}, [samples]);
}
-// ---- Resumen ----
+// ---- Overview ----
function TempStat({ last }) {
const t = useTheme();
@@ -197,11 +197,11 @@ function CpuTab({ s, last }) {
for (let i = 0; i < s.cores.length; i += cols) rows.push(s.cores.slice(i, i + cols).map((v, k) => [i + k, v]));
return (
<>
- <Card icon="cpu" title={tr('monitor.totalUse')} right={<Text style={{ fontSize: 20, fontWeight: 700, color: t.text }}>{fmt.pct(tr, last.cpu)}</Text>}>
+ <Card icon="cpu" title={tr('monitor.totalUse')} right={<Text style={{ fontSize: 20, fontWeight: 600, color: t.text }}>{fmt.pct(tr, last.cpu)}</Text>}>
<Chart series={[{ label: tr('monitor.cpu'), values: s.cpu, color: t.accent }]} max={1} format={(v) => fmt.pct(tr, v)} times={s.times} height={160} bg={card.bg} />
</Card>
<View style={{ flexDirection: 'row', alignItems: 'center', gap: 10 }}>
- <Text style={{ fontSize: 15, fontWeight: 700, color: t.text }}>{tr('monitor.perCore')}</Text>
+ <Text style={{ fontSize: typeScale.headline, fontWeight: 600, color: t.text }}>{tr('monitor.perCore')}</Text>
<Text style={{ fontSize: 12, color: t.textDim }}>{info?.cpuModel || ''}</Text>
</View>
{rows.map((row, r) => (
@@ -229,7 +229,7 @@ function CpuTab({ s, last }) {
);
}
-// ---- Memoria ----
+// ---- Memory ----
function MemTab({ s, last }) {
const t = useTheme();
@@ -273,9 +273,9 @@ function MemTab({ s, last }) {
);
}
-// ---- Discos ----
+// ---- Disks ----
-// Columna de tabla: la flexible se estira; las de ancho fijo no se encogen.
+// Table column: the flexible one stretches; fixed-width ones don't shrink.
const colBox = (c) => (c.flex ? { flex: c.flex, minWidth: 0 } : { width: c.width, flexShrink: 0 });
function Table({ cols, rows, onSort, sort }) {
@@ -338,7 +338,7 @@ function DisksTab({ s, last }) {
);
}
-// ---- Procesos ----
+// ---- Processes ----
export function AppGlyph({ item, size = 16 }) {
if (item.app === 'lordos') return <LordOSLogo size={size} />;
@@ -377,11 +377,11 @@ function ProcessesTab() {
return (
<>
<View style={{ flexDirection: 'row', alignItems: 'center', gap: 10 }}>
- <Text style={{ fontSize: 15, fontWeight: 700, color: t.text }}>{tr('monitor.processes')}</Text>
+ <Text style={{ fontSize: typeScale.headline, fontWeight: 600, color: t.text }}>{tr('monitor.processes')}</Text>
<Text style={{ fontSize: 12, color: t.textDim }}>{tr('monitor.procCount', { count: procs.total })}</Text>
<View style={{ flex: 1 }} />
<Segmented value={mine} onChange={setMine} options={[['mine', tr('monitor.mine')], ['all', tr('monitor.all')]]} />
- <View style={{ width: 200 }}><TextInput value={q} onChange={setQ} placeholder={tr('monitor.search')} onCancel={() => setQ('')} /></View>
+ <SearchField value={q} onChange={setQ} placeholder={tr('monitor.search')} width={200} />
</View>
<Table cols={cols} sort={sort} onSort={(key) => setSort((s0) => ({ key, dir: s0.key === key ? -s0.dir : key === 'name' || key === 'user' || key === 'pid' ? 1 : -1 }))}
rows={shown.map((p, i) => (
@@ -400,13 +400,13 @@ function ProcessesTab() {
);
}
-// ---- ventana ----
+// ---- window ----
let lastTab = 'overview';
-// Cada pestaña se suscribe a lo que muestra, al ritmo que necesita: las de gráficos con cada
-// muestra (4 por segundo al frente, 1 en segundo plano); Procesos y Red, una vez por segundo.
-// La ventana en sí no se vuelve a dibujar con cada muestra.
+// Each tab subscribes to what it shows, at the rate it needs: the chart tabs on every sample (4 per
+// second in front, 1 in the background); Processes and Network, once per second. The window itself
+// doesn't redraw on every sample.
function Charts({ tab, rate }) {
const samples = useMonitor({ everyMs: rate });
const s = useSeries(samples);
@@ -414,7 +414,7 @@ function Charts({ tab, rate }) {
if (!last) return null;
return (
<ScrollView style={{ flex: 1 }}>
- <View style={{ paddingHorizontal: 22, paddingTop: 18, paddingBottom: 26, gap: 16 }}>
+ <View style={{ paddingHorizontal: 20, paddingTop: 20, paddingBottom: 24, gap: 16 }}>
{tab === 'overview' && <Overview s={s} last={last} />}
{tab === 'cpu' && <CpuTab s={s} last={last} />}
{tab === 'memory' && <MemTab s={s} last={last} />}
@@ -437,7 +437,7 @@ function Footer() {
const samples = useMonitor({ everyMs: 1000 });
const last = samples[samples.length - 1];
return (
- <View style={{ height: 30, flexDirection: 'row', alignItems: 'center', gap: 8, paddingHorizontal: 16, backgroundColor: card.bg }}>
+ <View style={{ height: 28, flexDirection: 'row', alignItems: 'center', gap: 8, paddingHorizontal: 20, backgroundColor: card.bg }}>
<Glyph name="activity" color={t.textDim} size={11} />
<Text style={{ fontSize: 11, color: t.textDim, whiteSpace: 'nowrap' }}>{tr('monitor.footer')}</Text>
<View style={{ flex: 1 }} />
@@ -456,7 +456,7 @@ export default function Monitor() {
const setTab = (v) => { lastTab = v; setTabState(v); };
useEffect(() => { if (args?.tab) setTab(args.tab); }, [args?.tab, args?.nonce]);
const showConns = tab === 'network' && prefs.connections !== false;
- // qué listas arma lord-server (sin volver a dibujar esta ventana con cada muestra)
+ // which lists lord-server builds (without redrawing this window on every sample)
useMonitor({ procs: tab === 'processes', conns: showConns, geo: showConns && prefs.geo !== false, everyMs: 0 });
const ready = useStore(monitorSamples, (l) => l.length > 0);
const tabs = [
@@ -468,21 +468,20 @@ export default function Monitor() {
}
return (
<View style={{ flex: 1 }}>
- <View style={{ height: 46, flexDirection: 'row', alignItems: 'center', paddingHorizontal: 16, gap: 12 }}>
- <Text style={{ fontSize: 14, fontWeight: 700, color: t.text, width: 110 }}>{tr('monitor.title')}</Text>
+ <Toolbar style={{ paddingHorizontal: 20 }}>
+ <Text style={{ fontSize: typeScale.body, fontWeight: 600, color: t.text, width: 110, whiteSpace: 'nowrap' }}>{tr('monitor.title')}</Text>
<View style={{ flex: 1, alignItems: 'center' }}>
<Segmented value={tab} onChange={setTab} options={tabs} />
</View>
<View style={{ width: 110 }} />
- </View>
- <View style={{ height: 1, backgroundColor: t.separator }} />
+ </Toolbar>
{!ready ? (
- <View style={{ flex: 1, padding: 22 }}><Text style={{ fontSize: 13, color: t.textDim }}>{tr('monitor.waiting')}</Text></View>
+ <View style={{ flex: 1, padding: 20 }}><Text style={{ fontSize: 13, color: t.textDim }}>{tr('monitor.waiting')}</Text></View>
) : tab === 'network' ? (
<Network prefs={prefs} />
) : tab === 'processes' ? (
<ScrollView style={{ flex: 1 }}>
- <View style={{ paddingHorizontal: 22, paddingTop: 18, paddingBottom: 26, gap: 16 }}><ProcessesTab /></View>
+ <View style={{ paddingHorizontal: 20, paddingTop: 20, paddingBottom: 24, gap: 16 }}><ProcessesTab /></View>
</ScrollView>
) : (
<Charts tab={tab} rate={focused === false ? 1000 : 250} />
diff --git a/apps/passwords/Detail.jsx b/apps/passwords/Detail.jsx
index e15c47a..306be3f 100644
--- a/apps/passwords/Detail.jsx
+++ b/apps/passwords/Detail.jsx
@@ -5,10 +5,10 @@ import {
View, Text, Image, useTheme, useStore, Button, TextInput, Toggle, ScrollView, Markdown, wm, formatDate, formatTime, formatBytes, t,
} from '@lordos/sdk';
import { useEffect, useRef, useState } from 'react';
-import { app, req, copySecret, copyText, revealField, upsertItem, dropItem, toast, errorText } from './api.js';
+import { app, req, copySecret, copyText, revealField, upsertItem, dropItem, toast, errorText, appMode } from './api.js';
import { builtinById, fieldLabel, templateFields, allCategories, catName, FIELD_TYPES } from './templates.js';
import {
- EntryIcon, CatIcon, Sheet, b64ToBytes, Label, Hint, Warning, QrImage, TextArea, FilePicker, Choice, IconButton, Chip, StrengthBar, RED, ORANGE,
+ EntryIcon, CatIcon, Sheet, b64ToBytes, fileReq, fileName, Label, Hint, Warning, QrImage, TextArea, FilePicker, Choice, IconButton, Chip, StrengthBar, RED, ORANGE,
} from './ui.jsx';
import { GeneratorSheet } from './Generator.jsx';
@@ -157,13 +157,13 @@ function Attachments({ v, entry, onChanged }) {
{saveAtt && <FilePicker save suggest={saveAtt.name} title={t('passwords.att.save')} onClose={() => setSaveAtt(null)}
onPick={async (p) => {
const a = saveAtt; setSaveAtt(null);
- try { await req('att-get', { v, id: entry.id, att: a.id }, { files: [{ path: p, mode: 'w' }] }); toast(t('passwords.att.saved')); } catch (e) { toast(errorText(e.code)); }
+ try { await req('att-get', { v, id: entry.id, att: a.id }, fileReq([p, 'w'])); toast(t('passwords.att.saved')); } catch (e) { toast(errorText(e.code)); }
}} />}
{adding && <FilePicker title={t('passwords.att.add')} onClose={() => setAdding(false)}
onPick={async (p) => {
setAdding(false);
- const name = p.split('/').pop();
- try { const r = await req('att-add', { v, id: entry.id, name, mime: mimeOf(name) }, { files: [{ path: p, mode: 'r' }] }); upsertItem(r.item); onChanged(); toast(t('passwords.att.added')); }
+ const name = fileName(p).split('/').pop();
+ try { const r = await req('att-add', { v, id: entry.id, name, mime: mimeOf(name) }, fileReq([p, 'r'])); upsertItem(r.item); onChanged(); toast(t('passwords.att.added')); }
catch (e) { toast(errorText(e.code)); }
}} />}
</View>
@@ -273,7 +273,7 @@ export function EntryView({ v, id, onEdit, onDeleted }) {
</View>}
</View>
)}
- {b?.settingsLink && <Button label={t('passwords.vpn.openSettings')} onClick={() => wm.open('settings', { args: { page: 'network' } })} style={{ alignSelf: 'flex-start' }} />}
+ {b?.settingsLink && !appMode && <Button label={t('passwords.vpn.openSettings')} onClick={() => wm.open('settings', { args: { page: 'network' } })} style={{ alignSelf: 'flex-start' }} />}
{e.notes ? (
<View style={{ gap: 4 }}>
<Label>{t('passwords.field.notes')}</Label>
@@ -484,7 +484,7 @@ export function EntryEditor({ v, entry, catId, onDone, onCancel }) {
onPick={async (p) => {
const i = qrFor; setQrFor(null);
try {
- const r = await req('qr-scan', {}, { files: [{ path: p, mode: 'r' }] });
+ const r = await req('qr-scan', {}, fileReq([p, 'r']));
if (!r.totp) { toast(t('passwords.totp.notOtp')); return; }
setField(i, { ...fields[i], v: r.text, keep: false });
if (!title && r.issuer) setTitle(r.issuer);
diff --git a/apps/passwords/Lock.jsx b/apps/passwords/Lock.jsx
index bc29eab..a8e955c 100644
--- a/apps/passwords/Lock.jsx
+++ b/apps/passwords/Lock.jsx
@@ -2,9 +2,10 @@
// FIDO2, contraseña + archivo llave, clave de recuperación) y mostrar la clave de recuperación
// para imprimirla o guardarla.
import { View, Text, useTheme, useStore, Button, TextInput, Segmented, requestPermission, print, fs, t } from '@lordos/sdk';
+import * as React from 'react';
import { useEffect, useState } from 'react';
-import { app, req, refreshStatus, errorText, APP_ID, toast } from './api.js';
-import { StrengthBar, Hint, Warning, FilePicker, Label, RED } from './ui.jsx';
+import { app, req, refreshStatus, errorText, APP_ID, toast, appMode } from './api.js';
+import { StrengthBar, Hint, Warning, FilePicker, Label, RED, fileReq, fileName } from './ui.jsx';
function Padlock({ size = 64, open }) {
return (
@@ -20,11 +21,18 @@ function Padlock({ size = 64, open }) {
);
}
-function Shell({ children, wide }) {
+// picker: a file picker shown in place of the form, under the header (the first child), so the
+// lock screen stays recognisable instead of disappearing behind a dialog. In the app process the
+// system dialog picks the file and the form stays.
+function Shell({ children, wide, picker }) {
const th = useTheme();
+ const kids = React.Children.toArray(children);
+ const inline = picker && !appMode;
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor: th.windowBg }}>
- <View style={{ width: wide ? 520 : 380, gap: 12, alignItems: 'stretch' }}>{children}</View>
+ <View style={{ width: inline ? 520 : wide ? 520 : 380, gap: 12, alignItems: 'stretch' }}>
+ {inline ? [kids[0], <React.Fragment key="picker">{picker}</React.Fragment>] : [...kids, picker ? <React.Fragment key="picker">{picker}</React.Fragment> : null]}
+ </View>
</View>
);
}
@@ -57,7 +65,7 @@ export function UnlockView() {
if (method === 'recovery') args.recovery = rec;
if (method === 'keyfile' || method === 'passkey') {
if (!keyfile) { setBusy(false); setErr(t('passwords.unlock.needKeyfile')); return; }
- files = [{ path: keyfile, mode: 'r' }];
+ files = fileReq([keyfile, 'r']);
}
if (method === 'fido') {
const ok = await requestPermission(APP_ID, 'usb');
@@ -66,11 +74,12 @@ export function UnlockView() {
if (!a.ok) throw Object.assign(new Error(a.error), { code: a.error });
if (pin) args.pin = pin;
}
- const r = await req('unlock', args, { files });
+ const r = await req('unlock', args, files);
setMs(r.ms ?? null);
setPw(''); setRec(''); setPin('');
await refreshStatus();
} catch (e) { setErr(errorText(e.code)); }
+ if (keyfile && typeof keyfile !== 'string') setKeyfile(''); // an fd is used up: pick it again
setBusy(false);
app.set((s) => ({ ...s, touch: false }));
};
@@ -81,7 +90,7 @@ export function UnlockView() {
if (has('fido')) opts.push(['fido', t('passwords.method.fido')]);
if (has('recovery')) opts.push(['recovery', t('passwords.method.recovery')]);
return (
- <Shell>
+ <Shell picker={picking && <FilePicker inline title={t('passwords.unlock.chooseKeyfile')} onClose={() => setPicking(false)} onPick={(p) => { setKeyfile(p); setPicking(false); }} />}>
<View style={{ alignItems: 'center', gap: 6 }}>
<Padlock size={72} />
<Text style={{ fontSize: 20, fontWeight: 700, color: th.text }}>{t('passwords.unlock.title')}</Text>
@@ -93,7 +102,7 @@ export function UnlockView() {
)}
{(method === 'keyfile' || method === 'passkey') && (
<View style={{ flexDirection: 'row', gap: 8, alignItems: 'center' }}>
- <Text style={{ flex: 1, fontSize: 12, color: keyfile ? th.text : th.textDim, whiteSpace: 'nowrap', overflow: 'hidden' }}>{keyfile || t('passwords.unlock.noKeyfile')}</Text>
+ <Text style={{ flex: 1, fontSize: 12, color: keyfile ? th.text : th.textDim, whiteSpace: 'nowrap', overflow: 'hidden' }}>{fileName(keyfile) || t('passwords.unlock.noKeyfile')}</Text>
<Button label={t('passwords.unlock.chooseKeyfile')} onClick={() => setPicking(true)} />
</View>
)}
@@ -110,7 +119,6 @@ export function UnlockView() {
<Button primary label={busy ? (st.touch ? t('passwords.fido.touchShort') : t('passwords.unlock.working')) : t('passwords.unlock.button')} onClick={go} style={{ height: 34 }} />
{ms != null && <Hint>{t('passwords.unlock.took', { ms })}</Hint>}
{st.status?.main?.unreadable && <Warning>{t('passwords.unlock.unreadable')}</Warning>}
- {picking && <FilePicker title={t('passwords.unlock.chooseKeyfile')} onClose={() => setPicking(false)} onPick={(p) => { setKeyfile(p); setPicking(false); }} />}
</Shell>
);
}
@@ -149,7 +157,7 @@ export function CreateView() {
const args = { method };
let files;
if (needPw) args.password = pw;
- if (needKey) { args.newkey = true; files = [{ path: keyPath, mode: 'w' }]; }
+ if (needKey) { args.newkey = true; files = fileReq([keyPath, 'w']); }
if (method === 'fido') {
const ok = await requestPermission(APP_ID, 'usb');
if (!ok) throw Object.assign(new Error('denied'), { code: 'fido-denied' });
@@ -157,14 +165,15 @@ export function CreateView() {
if (!a.ok) throw Object.assign(new Error(a.error), { code: a.error });
if (pin) args.pin = pin;
}
- const r = await req('create', args, { files });
+ const r = await req('create', args, files);
setPw(''); setPw2('');
setRecovery(r.recovery);
} catch (e) { setErr(errorText(e.code)); }
setBusy(false);
};
return (
- <Shell wide>
+ <Shell wide picker={picking && <FilePicker inline save suggest="contrasenas.key" title={t('passwords.create.chooseKeyPath')} onClose={() => setPicking(false)}
+ onPick={(p) => { setKeyPath(p); setPicking(false); }} />}>
<View style={{ alignItems: 'center', gap: 6 }}>
<Padlock size={64} open />
<Text style={{ fontSize: 20, fontWeight: 700, color: th.text }}>{t('passwords.create.title')}</Text>
@@ -184,7 +193,7 @@ export function CreateView() {
)}
{needKey && (
<View style={{ flexDirection: 'row', gap: 8, alignItems: 'center' }}>
- <Text style={{ flex: 1, fontSize: 12, color: keyPath ? th.text : th.textDim, whiteSpace: 'nowrap', overflow: 'hidden' }}>{keyPath || t('passwords.create.keyWhere')}</Text>
+ <Text style={{ flex: 1, fontSize: 12, color: keyPath ? th.text : th.textDim, whiteSpace: 'nowrap', overflow: 'hidden' }}>{fileName(keyPath) || t('passwords.create.keyWhere')}</Text>
<Button label={t('passwords.create.chooseKeyPath')} onClick={() => setPicking(true)} />
</View>
)}
@@ -197,8 +206,6 @@ export function CreateView() {
{err ? <Text style={{ fontSize: 12, color: RED }}>{err}</Text> : null}
<Button primary label={busy ? (st.touch ? t('passwords.fido.touchShort') : t('passwords.create.working')) : t('passwords.create.button')} onClick={go} style={{ height: 34 }} />
<Hint>{t('passwords.create.local')}</Hint>
- {picking && <FilePicker save suggest="contrasenas.key" title={t('passwords.create.chooseKeyPath')} onClose={() => setPicking(false)}
- onPick={(p) => { setKeyPath(p); setPicking(false); }} />}
</Shell>
);
}
@@ -211,14 +218,22 @@ export function RecoveryView({ code, onDone }) {
const [ok, setOk] = useState(false);
const text = `${t('passwords.recovery.printTitle')}\n\n${code}\n\n${t('passwords.recovery.printBody')}\n`;
return (
- <Shell wide>
+ <Shell wide picker={saving && <FilePicker inline save suggest="clave-de-recuperacion.txt" title={t('passwords.recovery.save')} onClose={() => setSaving(false)}
+ onPick={(p) => {
+ try {
+ if (typeof p === 'string') fs.write(p, text);
+ else { const ok = lord.broker.fdWrite(p.fd, text); lord.broker.fdClose(p.fd); if (!ok) throw new Error('write'); }
+ toast(t('passwords.recovery.saved'));
+ } catch (e) { toast(errorText('file')); }
+ setSaving(false);
+ }} />}>
<Text style={{ fontSize: 20, fontWeight: 700, color: th.text, textAlign: 'center' }}>{t('passwords.recovery.title')}</Text>
<Hint>{t('passwords.recovery.body')}</Hint>
<View style={{ padding: 16, borderRadius: 10, backgroundColor: th.control, alignItems: 'center', direction: 'ltr' }}>
<Text style={{ fontSize: 17, fontWeight: 600, color: th.text, fontFamily: 'monospace' }}>{code}</Text>
</View>
<View style={{ flexDirection: 'row', gap: 8, justifyContent: 'center' }}>
- <Button label={t('passwords.recovery.print')} onClick={() => print.open({ title: t('passwords.recovery.printTitle'), text })} />
+ {!appMode && <Button label={t('passwords.recovery.print')} onClick={() => print.open({ title: t('passwords.recovery.printTitle'), text })} />}
<Button label={t('passwords.recovery.save')} onClick={() => setSaving(true)} />
</View>
<View onClick={() => setOk(!ok)} style={{ flexDirection: 'row', gap: 8, alignItems: 'center' }}>
@@ -228,8 +243,6 @@ export function RecoveryView({ code, onDone }) {
<Text style={{ flex: 1, fontSize: 12, color: th.text }}>{t('passwords.recovery.confirm')}</Text>
</View>
<Button primary label={t('passwords.recovery.done')} onClick={() => ok && onDone()} style={{ opacity: ok ? 1 : 0.5, height: 34 }} />
- {saving && <FilePicker save suggest="clave-de-recuperacion.txt" title={t('passwords.recovery.save')} onClose={() => setSaving(false)}
- onPick={(p) => { try { fs.write(p, text); toast(t('passwords.recovery.saved')); } catch (e) { toast(errorText('file')); } setSaving(false); }} />}
</Shell>
);
}
diff --git a/apps/passwords/Security.jsx b/apps/passwords/Security.jsx
index 7e75aa3..d9e44bb 100644
--- a/apps/passwords/Security.jsx
+++ b/apps/passwords/Security.jsx
@@ -5,7 +5,7 @@ import { View, Text, useTheme, useStore, Button, ScrollView, t } from '@lordos/s
import { useEffect, useRef, useState } from 'react';
import { app, req, errorText, toast, copySecret } from './api.js';
import { allCategories, builtinById } from './templates.js';
-import { EntryIcon, Hint, FilePicker, strengthColor, strengthLabel, RED, ORANGE, YELLOW, GREEN, IconButton } from './ui.jsx';
+import { EntryIcon, Hint, FilePicker, strengthColor, strengthLabel, RED, ORANGE, YELLOW, GREEN, IconButton, fileReq } from './ui.jsx';
import { Center } from './Detail.jsx';
function Card({ title, count, color, children, hint }) {
@@ -49,7 +49,7 @@ export function SecurityView({ onOpen }) {
const [busy, setBusy] = useState(false);
const run = async (file) => {
setBusy(true);
- try { setRep(await req('report', {}, file ? { files: [{ path: file, mode: 'r' }] } : undefined)); } catch (e) { toast(errorText(e.code)); }
+ try { setRep(await req('report', {}, file ? fileReq([file, 'r']) : undefined)); } catch (e) { toast(errorText(e.code)); }
setBusy(false);
};
useEffect(() => { run(hibp); }, [st.entries.length]);
@@ -93,7 +93,7 @@ export function SecurityView({ onOpen }) {
<Hint>{t('passwords.report.offline')}</Hint>
</View>
{picking && <FilePicker title={t('passwords.report.hibpChoose')} onClose={() => setPicking(false)}
- onPick={(p) => { setPicking(false); setHibp(p); run(p); }} />}
+ onPick={(p) => { setPicking(false); setHibp(typeof p === 'string' ? p : null); run(p); }} />}
</ScrollView>
);
}
diff --git a/apps/passwords/Settings.jsx b/apps/passwords/Settings.jsx
index a067504..7486dd8 100644
--- a/apps/passwords/Settings.jsx
+++ b/apps/passwords/Settings.jsx
@@ -4,7 +4,7 @@ import { View, Text, useTheme, useStore, Button, TextInput, Segmented, requestPe
import { useState } from 'react';
import { app, req, refreshStatus, reload, errorText, toast, setMeta, setCats, setTags, APP_ID } from './api.js';
import { allCategories, BUILTIN, ICONS, COLORS, FIELD_TYPES, catName, builtinById } from './templates.js';
-import { Sheet, Label, Hint, Warning, FilePicker, Choice, CatIcon, StrengthBar, RED } from './ui.jsx';
+import { Sheet, Label, Hint, Warning, FilePicker, Choice, CatIcon, StrengthBar, RED, fileReq, fileName } from './ui.jsx';
import { RecoveryView } from './Lock.jsx';
const slotIcon = { password: '🔤', keyfile: '💾', passkey: '🔤💾', fido: '🔑', recovery: '🧾', session: '👤' };
@@ -36,14 +36,14 @@ export function SettingsSheet({ onClose }) {
const args = { method: add, label: '' };
let files;
if (add === 'password' || add === 'passkey') args.password = pw;
- if (add === 'keyfile' || add === 'passkey') { if (!path) { setErr(t('passwords.create.needKeyPath')); return; } args.newkey = true; files = [{ path, mode: 'w' }]; }
+ if (add === 'keyfile' || add === 'passkey') { if (!path) { setErr(t('passwords.create.needKeyPath')); return; } args.newkey = true; files = fileReq([path, 'w']); }
if (add === 'fido') {
if (!(await requestPermission(APP_ID, 'usb'))) throw Object.assign(new Error(''), { code: 'fido-denied' });
const a = lord.vault.fidoAttach(APP_ID);
if (!a.ok) throw Object.assign(new Error(''), { code: a.error });
if (pin) args.pin = pin;
}
- await req('slot-add', args, { files });
+ await req('slot-add', args, files);
await done(t('passwords.set.added'));
});
if (rec) return <Sheet title={t('passwords.recovery.title')} onClose={() => setRec(null)} width={600}><RecoveryView code={rec} onDone={() => setRec(null)} /></Sheet>;
@@ -87,7 +87,7 @@ export function SettingsSheet({ onClose }) {
</>}
{(add === 'keyfile' || add === 'passkey') && (
<View style={{ flexDirection: 'row', gap: 8, alignItems: 'center' }}>
- <Text style={{ flex: 1, fontSize: 12, color: path ? th.text : th.textDim, whiteSpace: 'nowrap', overflow: 'hidden' }}>{path || t('passwords.create.keyWhere')}</Text>
+ <Text style={{ flex: 1, fontSize: 12, color: path ? th.text : th.textDim, whiteSpace: 'nowrap', overflow: 'hidden' }}>{fileName(path) || t('passwords.create.keyWhere')}</Text>
<Button label={t('passwords.create.chooseKeyPath')} onClick={() => setPicking(true)} />
</View>
)}
@@ -152,20 +152,21 @@ export function ImportSheet({ onClose }) {
const [busy, setBusy] = useState(false);
const [res, setRes] = useState(null);
const [err, setErr] = useState('');
- const isKdbx = /\.kdbx$/i.test(file);
- const isVault = /\.lvault$/i.test(file);
+ const isKdbx = /\.kdbx$/i.test(fileName(file));
+ const isVault = /\.lvault$/i.test(fileName(file));
const go = async () => {
if (!file) return;
setBusy(true); setErr(''); setRes(null);
try {
- const files = [{ path: file, mode: 'r' }];
- if (key) files.push({ path: key, mode: 'r' });
- const name = file.split('/').pop();
- const r = isVault ? await req('import-vault', { password: pw, recovery: '' }, { files })
- : await req('import', { name, password: pw || undefined }, { files });
+ const files = fileReq([file, 'r'], [key, 'r']);
+ const name = fileName(file).split('/').pop();
+ const r = isVault ? await req('import-vault', { password: pw, recovery: '' }, files)
+ : await req('import', { name, password: pw || undefined }, files);
setRes(r);
await reload();
} catch (e) { setErr(errorText(e.code)); }
+ // app process: a picked file is an fd that the request already used up; pick again to retry
+ if (typeof file !== 'string') { setFile(''); setKey(''); }
setBusy(false);
};
return (
@@ -174,14 +175,14 @@ export function ImportSheet({ onClose }) {
<Button key="g" primary label={busy ? t('passwords.imp.working') : t('passwords.imp.button')} onClick={go} />]}>
<Hint>{t('passwords.imp.formats')}</Hint>
<View style={{ flexDirection: 'row', gap: 8, alignItems: 'center' }}>
- <Text style={{ flex: 1, fontSize: 12, color: file ? th.text : th.textDim, whiteSpace: 'nowrap', overflow: 'hidden' }}>{file || t('passwords.imp.noFile')}</Text>
+ <Text style={{ flex: 1, fontSize: 12, color: file ? th.text : th.textDim, whiteSpace: 'nowrap', overflow: 'hidden' }}>{fileName(file) || t('passwords.imp.noFile')}</Text>
<Button label={t('passwords.imp.choose')} onClick={() => setPicking('file')} />
</View>
{(isKdbx || isVault) && (
<View style={{ gap: 8 }}>
<TextInput value={pw} onChange={setPw} secure placeholder={isVault ? t('passwords.imp.vaultPassword') : t('passwords.imp.kdbxPassword')} onSubmit={go} />
<View style={{ flexDirection: 'row', gap: 8, alignItems: 'center' }}>
- <Text style={{ flex: 1, fontSize: 12, color: key ? th.text : th.textDim, whiteSpace: 'nowrap', overflow: 'hidden' }}>{key || t('passwords.imp.noKey')}</Text>
+ <Text style={{ flex: 1, fontSize: 12, color: key ? th.text : th.textDim, whiteSpace: 'nowrap', overflow: 'hidden' }}>{fileName(key) || t('passwords.imp.noKey')}</Text>
<Button label={t('passwords.imp.chooseKey')} onClick={() => setPicking('key')} />
</View>
</View>
@@ -213,7 +214,7 @@ export function ExportSheet({ onClose }) {
const go = async (p) => {
setPicking(false); setErr('');
try {
- const r = await req(kind === 'csv' ? 'export-csv' : 'export-vault', {}, { files: [{ path: p, mode: 'w' }] });
+ const r = await req(kind === 'csv' ? 'export-csv' : 'export-vault', {}, fileReq([p, 'w']));
toast(kind === 'csv' ? t('passwords.exp.doneCsv', { count: r.count }) : t('passwords.exp.doneVault'));
onClose();
} catch (e) { setErr(errorText(e.code)); }
diff --git a/apps/passwords/api.js b/apps/passwords/api.js
index fb88fe6..c4ebd36 100644
--- a/apps/passwords/api.js
+++ b/apps/passwords/api.js
@@ -6,6 +6,10 @@ import { createStore, vaultRequest, onVaultEvent, clipboard, t } from '@lordos/s
export const APP_ID = 'passwords';
+// true when this UI runs as its own sandboxed process (lord-server --app passwords) with a direct
+// channel to lord-vault; false in the shell (in-process fallback). See docs/PASSWORDS.md.
+export const appMode = typeof lord !== 'undefined' && !!(lord.vault && lord.vault.appMode);
+
export const app = createStore({
phase: 'loading', // loading | none | locked | unlocked | unavailable
status: null, // respuesta de "status"
@@ -66,6 +70,12 @@ export function toast(text, kind = 'info') {
let clearTimer = null;
export function copySecret(value, label) {
const secs = Number(app.get().meta?.clip ?? 30) || 30;
+ if (appMode) {
+ // app process: lord-server marks it sensitive and clears it after `secs` if unchanged
+ lord.clipboard.set(value, { secure: true, clearAfter: secs });
+ toast(t('passwords.copied', { what: label, secs }));
+ return;
+ }
clipboard.set(value, { secure: true, origin: APP_ID });
if (clearTimer) clearTimeout(clearTimer);
clearTimer = setTimeout(() => {
diff --git a/apps/passwords/manifest.json b/apps/passwords/manifest.json
index 58b8a13..b3b4092 100644
--- a/apps/passwords/manifest.json
+++ b/apps/passwords/manifest.json
@@ -1,10 +1,20 @@
{
"id": "passwords",
- "name": "Contraseñas",
- "description": "Contraseñas, códigos 2FA, Wi-Fi, tarjetas y notas seguras en una bóveda cifrada; también el llavero de la sesión",
- "size": [1040, 660],
- "minSize": [820, 500],
+ "name": "Passwords",
+ "description": "Passwords, 2FA codes, Wi-Fi, cards and secure notes in an encrypted vault; also the session keyring",
+ "size": [
+ 1040,
+ 660
+ ],
+ "minSize": [
+ 820,
+ 500
+ ],
"dock": true,
"category": "Utility",
- "permissions": ["usb"]
+ "permissions": [
+ "usb"
+ ],
+ "process": "isolated",
+ "protected": true
}
diff --git a/apps/passwords/ui.jsx b/apps/passwords/ui.jsx
index 9039b55..729e05f 100644
--- a/apps/passwords/ui.jsx
+++ b/apps/passwords/ui.jsx
@@ -3,6 +3,19 @@
import { View, Text, Image, useTheme, useStore, createStore, Button, ScrollView, TextInput, takeTextFocus, releaseTextFocus, fs, t } from '@lordos/sdk';
import { useEffect, useRef, useState } from 'react';
import { builtinById } from './templates.js';
+import { appMode } from './api.js';
+
+// A picked file is a path (shell: lord-server opens it, validated like lord.fs) or { fd, name }
+// (app process: the system dialog opened it). fileReq builds the request options for either.
+export function fileReq(...items) {
+ const files = [], fds = [];
+ for (const [p, mode] of items) {
+ if (!p) continue;
+ if (typeof p === 'string') files.push({ path: p, mode }); else fds.push(p.fd);
+ }
+ return fds.length ? { fds } : { files };
+}
+export const fileName = (p) => (typeof p === 'string' ? p : p?.name || '');
export const RED = '#ff453a', ORANGE = '#ff9f0a', GREEN = '#30d158', YELLOW = '#ffd60a';
@@ -53,6 +66,13 @@ const overlays = createStore([]); // [{ key, node }]
let overlaySeq = 0;
export function Sheet(props) {
+ // inline: the panel goes in the layout where it is written, without the dimmed overlay. The lock
+ // and create screens use it so the dialog does not cover the whole (small) form behind it.
+ if (props.inline) return <SheetPanel {...props} inline />;
+ return <OverlaySheet {...props} />;
+}
+
+function OverlaySheet(props) {
const key = useRef(null);
if (!key.current) key.current = `s${++overlaySeq}`;
useEffect(() => {
@@ -68,13 +88,21 @@ export function Overlays() {
return l.map((x) => <View key={x.key} style={{ position: 'absolute', left: 0, top: 0, right: 0, bottom: 0 }}>{x.node}</View>);
}
-function SheetBox({ title, onClose, children, width = 460, footer }) {
- const th = useTheme();
+function SheetBox(props) {
return (
<View onMouseDown={(e) => e.stopPropagation?.()} style={{ position: 'absolute', left: 0, top: 0, right: 0, bottom: 0, zIndex: 50,
alignItems: 'center', justifyContent: 'center', backgroundColor: 'rgba(0,0,0,0.38)' }}>
- <View style={{ width, maxHeight: '94%', borderRadius: 14, backgroundColor: th.windowBg, border: `1px solid ${th.separator}`,
- boxShadow: '0 18px 50px rgba(0,0,0,0.5)', overflow: 'hidden' }}>
+ <SheetPanel {...props} />
+ </View>
+ );
+}
+
+function SheetPanel({ title, onClose, children, width = 460, footer, inline }) {
+ const th = useTheme();
+ return (
+ <View style={{ width: inline ? undefined : width, alignSelf: inline ? 'stretch' : undefined, maxHeight: inline ? undefined : '94%', borderRadius: 14,
+ backgroundColor: th.windowBg, border: `1px solid ${th.separator}`,
+ boxShadow: inline ? '0 6px 18px rgba(0,0,0,0.25)' : '0 18px 50px rgba(0,0,0,0.5)', overflow: 'hidden' }}>
<View style={{ flexDirection: 'row', alignItems: 'center', paddingHorizontal: 16, paddingVertical: 12, borderBottom: `1px solid ${th.separator}` }}>
<Text style={{ flex: 1, fontSize: 15, fontWeight: 700, color: th.text }}>{title}</Text>
{onClose && <View onClick={onClose} style={{ width: 24, height: 24, borderRadius: 12, alignItems: 'center', justifyContent: 'center', backgroundColor: th.control }}>
@@ -83,7 +111,6 @@ function SheetBox({ title, onClose, children, width = 460, footer }) {
<View style={{ padding: 16, gap: 10, flexShrink: 1, overflow: 'hidden' }}>{children}</View>
{footer && <View style={{ flexDirection: 'row', justifyContent: 'flex-end', gap: 8, paddingHorizontal: 16, paddingVertical: 12, borderTop: `1px solid ${th.separator}` }}>{footer}</View>}
</View>
- </View>
);
}
@@ -156,7 +183,7 @@ export function TextArea({ value, onChange, placeholder, minHeight = 90, mono, s
useEffect(() => () => releaseTextFocus(token), []);
const onKey = (e) => {
const { value: v, onChange: set } = latest.current;
- if (e.ctrl && e.base === 'v') { set(v + lord.clipboard.get()); return; }
+ if (e.ctrl && e.base === 'v') { try { set(v + lord.clipboard.get()); } catch (err) { /* no clipboard permission */ } return; }
if (e.key === 'Backspace') set([...v].slice(0, -1).join(''));
else if (e.key === 'Enter') set(`${v}\n`);
else if (e.key === 'Tab') set(`${v} `);
@@ -175,11 +202,19 @@ export function TextArea({ value, onChange, placeholder, minHeight = 90, mono, s
// ---- elegir un archivo (carpeta personal y discos del usuario: pendrives) ----
-export function FilePicker({ title, save, suggest = '', onPick, onClose, filter }) {
+export function FilePicker({ title, save, suggest = '', onPick, onClose, filter, inline }) {
const th = useTheme();
const [dir, setDir] = useState(null); // null = lugares
const [name, setName] = useState(suggest);
const [sel, setSel] = useState(null);
+ // app process: the system's own dialog (powerbox) picks the file and hands over only its fd
+ useEffect(() => {
+ if (!appMode) return;
+ let r = null;
+ try { r = lord.broker.pick(save ? 1 : 0, suggest || ''); } catch (e) { r = null; }
+ if (r && r.fd >= 0) onPick({ fd: r.fd, name: r.name }); else onClose();
+ }, []);
+ if (appMode) return null;
let entries = [];
let places = [];
if (dir === null) {
@@ -194,14 +229,14 @@ export function FilePicker({ title, save, suggest = '', onPick, onClose, filter
if (sel) onPick(fs.join(dir, sel));
};
return (
- <Sheet title={title} onClose={onClose} width={520} footer={[
+ <Sheet title={title} onClose={onClose} width={520} inline={inline} footer={[
<Button key="c" label={t('passwords.cancel')} onClick={onClose} />,
<Button key="o" primary label={save ? t('passwords.picker.save') : t('passwords.picker.open')} onClick={choose} />]}>
<View style={{ flexDirection: 'row', alignItems: 'center', gap: 8 }}>
<Button label="‹" onClick={up} />
<Text style={{ flex: 1, fontSize: 12, color: th.textDim, whiteSpace: 'nowrap', overflow: 'hidden' }}>{dir === null ? t('passwords.picker.places') : dir}</Text>
</View>
- <View style={{ height: 260, borderRadius: 8, border: `1px solid ${th.separator}`, overflow: 'hidden' }}>
+ <View style={{ height: inline ? 190 : 260, borderRadius: 8, border: `1px solid ${th.separator}`, overflow: 'hidden' }}>
<ScrollView style={{ flex: 1 }}>
{dir === null ? places.map((p) => (
<Row key={p.path} icon={p.icon} label={p.name} onClick={() => setDir(p.path)} />
diff --git a/apps/player/index.jsx b/apps/player/index.jsx
index eeb0baa..4c5aaa9 100644
--- a/apps/player/index.jsx
+++ b/apps/player/index.jsx
@@ -1,34 +1,101 @@
-// Reproductor — videos y música (al estilo de los reproductores de escritorio, con diseño propio).
+// Player: videos and music (in the style of desktop players, with our own design).
//
-// La decodificación es de lord-media (aislado); acá están la biblioteca (artista y álbum desde
-// las etiquetas, carátulas), la cola, aleatorio y repetir, los controles del video (barra de
-// tiempo, volumen, subtítulos .srt y de la pista, pantalla completa, imagen en imagen) y lo que
-// se publica para el Centro de control y las teclas multimedia (nowPlaying).
+// Decoding belongs to lord-media (sandboxed); here are the library (artist and album from the
+// tags, covers), the queue, shuffle and repeat, the video controls (time bar, volume, .srt and
+// in-stream subtitles, full screen, picture in picture) and what is published for Control Center
+// and the media keys (nowPlaying).
import {
- View, Text, Image, MediaView, ScrollView, SidebarItem, SectionTitle, useTheme, useAppWindow, useKeyboard, useStore, useWindowState, wm,
- t as tr, media, usePlayer, nowPlaying, mediaFormatTime, useThumb, fs, addListener, direction,
+ 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,
} from '@lordos/sdk';
import { useEffect, useMemo, useRef, useState } from 'react';
import { library, scan, albumsOf, artistsOf, parseSrt, AUDIO, VIDEO } from './library.js';
const APP = 'player';
-const useWindowNonce = new Map(); // último «Abrir con» atendido por ventana
+const useWindowNonce = new Map(); // last "Open with" handled, per window
-// Triángulo con barras (el motor no gira cajas): para íconos de reproducir.
-function Tri({ x, y, w, h, color, steps = 12 }) {
+// Triangle made of bars (the engine doesn't rotate boxes): for the play icons. left: pointing left.
+function Tri({ x, y, w, h, color, steps = 12, left = false }) {
const rows = [];
for (let i = 0; i < steps; i++) {
const f = 1 - Math.abs((i + 0.5) / steps - 0.5) * 2;
- rows.push(<View key={i} style={{ position: 'absolute', left: x, top: y + (h * i) / steps, width: Math.max(1, w * f), height: h / steps + 0.6, backgroundColor: color }} />);
+ const bw = Math.max(1, w * f);
+ rows.push(<View key={i} style={{ position: 'absolute', left: left ? x + w - bw : x, top: y + (h * i) / steps, width: bw, height: h / steps + 0.6, backgroundColor: color }} />);
}
return rows;
}
+// Monochrome transport glyphs drawn with boxes: the media symbols of the fonts are color emoji.
+// They always point left to right (time runs that way, also in RTL).
+function PlayGlyph({ size, color }) {
+ return <View style={{ width: size, height: size, direction: 'ltr' }}><Tri x={size * 0.2} y={0} w={size * 0.72} h={size} color={color} steps={Math.max(8, Math.round(size))} /></View>;
+}
+function PauseGlyph({ size, color }) {
+ const bw = Math.max(2, Math.round(size * 0.28));
+ return (
+ <View style={{ width: size, height: size, flexDirection: 'row', justifyContent: 'center', gap: Math.round(size * 0.2), direction: 'ltr' }}>
+ <View style={{ width: bw, height: size, borderRadius: 1, backgroundColor: color }} />
+ <View style={{ width: bw, height: size, borderRadius: 1, backgroundColor: color }} />
+ </View>
+ );
+}
+function SkipGlyph({ size, color, back }) {
+ const h = size * 0.7, w = size * 0.42, y = (size - h) / 2, steps = Math.max(8, Math.round(h));
+ return (
+ <View style={{ width: size, height: size, direction: 'ltr' }}>
+ {back ? <View style={{ position: 'absolute', left: 0, top: y, width: 2, height: h, backgroundColor: color }} /> : null}
+ <Tri x={back ? 2 : size - 2 - w * 2} y={y} w={w} h={h} color={color} steps={steps} left={back} />
+ <Tri x={back ? 2 + w : size - 2 - w} y={y} w={w} h={h} color={color} steps={steps} left={back} />
+ {back ? null : <View style={{ position: 'absolute', left: size - 2, top: y, width: 2, height: h, backgroundColor: color }} />}
+ </View>
+ );
+}
+function SpeakerGlyph({ size, color, level }) {
+ const h = size * 0.75, y = (size - h) / 2;
+ return (
+ <View style={{ width: size + 6, height: size, direction: 'ltr' }}>
+ <View style={{ position: 'absolute', left: 0, top: size * 0.36, width: size * 0.22, height: size * 0.28, backgroundColor: color }} />
+ <Tri x={0} y={y} w={size * 0.5} h={h} color={color} steps={Math.max(8, Math.round(h))} left />
+ {level > 0 ? <View style={{ position: 'absolute', left: size * 0.62, top: size * 0.36, width: 2, height: size * 0.28, borderRadius: 1, backgroundColor: color }} /> : null}
+ {level > 0.5 ? <View style={{ position: 'absolute', left: size * 0.62 + 4, top: size * 0.22, width: 2, height: size * 0.56, borderRadius: 1, backgroundColor: color }} /> : null}
+ {level > 1 ? <View style={{ position: 'absolute', left: size * 0.62 + 8, top: size * 0.08, width: 2, height: size * 0.84, borderRadius: 1, backgroundColor: color }} /> : null}
+ </View>
+ );
+}
+// Subtitles: "CC" in a rounded box.
+function CaptionsGlyph({ color }) {
+ return (
+ <View style={{ height: 14, paddingHorizontal: 3, borderRadius: 3, border: `1.5px solid ${color}`, justifyContent: 'center' }}>
+ <Text style={{ fontSize: 8, fontWeight: 700, color, lineHeight: 10 }}>CC</Text>
+ </View>
+ );
+}
+// Repeat (one): the circular arrow with a small "1".
+function RepeatGlyph({ color, one }) {
+ return (
+ <View style={{ width: 18, height: 18, alignItems: 'center', justifyContent: 'center' }}>
+ <Text style={{ fontSize: 16, color }}>↻</Text>
+ {one ? <Text style={{ position: 'absolute', right: -2, bottom: -2, fontSize: 8, fontWeight: 700, color }}>1</Text> : null}
+ </View>
+ );
+}
+
+// Width of a box after layout (to adapt the bar and the columns to the window).
+function useBoxWidth(ref, initial) {
+ const [w, setW] = useState(initial);
+ useEffect(() => {
+ if (!ref.current) return;
+ const lw = Math.round(lord.getLayout(ref.current.id)[2]);
+ if (lw > 0 && Math.abs(lw - w) > 2) setW(lw);
+ });
+ return w;
+}
+
export function Icon({ size: s }) {
return (
<View style={{ width: s, height: s, borderRadius: s * 0.225, background: 'linear-gradient(160deg, #ff7a59, #d6246e)',
boxShadow: `0 ${s * 0.04}px ${s * 0.12}px rgba(0,0,0,0.35)`, overflow: 'hidden' }}>
- {/* pantalla con perforaciones de película */}
+ {/* a screen with film perforations */}
<View style={{ position: 'absolute', left: s * 0.14, top: s * 0.22, width: s * 0.72, height: s * 0.56, borderRadius: s * 0.08, backgroundColor: 'rgba(20,10,30,0.82)' }} />
{[0, 1, 2, 3].map((i) => (
<View key={i} style={{ position: 'absolute', left: s * (0.2 + i * 0.17), top: s * 0.25, width: s * 0.08, height: s * 0.05, borderRadius: s * 0.015, backgroundColor: 'rgba(255,255,255,0.35)' }} />
@@ -45,7 +112,7 @@ const isVideo = (p) => VIDEO.test(p || '');
const isAudio = (p) => AUDIO.test(p || '');
const baseName = (p) => String(p || '').split('/').pop();
-// Barra de tiempo (y de volumen): se arrastra; fija la dirección LTR (usa la x del puntero).
+// Time (and volume) bar: draggable; fixed LTR direction (it uses the pointer's x).
function Bar({ value, onChange, onCommit, height = 4, color, track, style }) {
const ref = useRef(null), drag = useRef(false), cb = useRef({});
cb.current = { onChange, onCommit };
@@ -69,14 +136,15 @@ function Bar({ value, onChange, onCommit, height = 4, color, track, style }) {
);
}
-function IconBtn({ glyph, onClick, size = 16, color, active }) {
+// Round borderless button for a glyph (text) or a drawn icon (children).
+function IconBtn({ glyph, onClick, size = 16, color, active, children, box = 30 }) {
const th = useTheme();
const [hover, setHover] = useState(false);
return (
<View onClick={onClick} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
- style={{ minWidth: 30, height: 30, paddingHorizontal: 4, borderRadius: 15, alignItems: 'center', justifyContent: 'center',
+ style={{ minWidth: box, height: box, paddingHorizontal: 4, borderRadius: box / 2, alignItems: 'center', justifyContent: 'center',
backgroundColor: hover ? 'rgba(127,127,127,0.18)' : 'transparent' }}>
- <Text style={{ fontSize: size, color: active ? th.accent : color || th.text }}>{glyph}</Text>
+ {children || <Text style={{ fontSize: size, color: active ? th.accent : color || th.text }}>{glyph}</Text>}
</View>
);
}
@@ -92,16 +160,17 @@ function Cover({ path, size, radius = 6 }) {
);
}
-// Menú simple que se abre hacia arriba (subtítulos, audio).
+// Simple menu that opens upwards (subtitles, audio).
function Popup({ items, onClose, right = 12, bottom = 64 }) {
const th = useTheme();
return (
<View onMouseDown={(e) => e.stopPropagation?.()} style={{ position: 'absolute', right, bottom, minWidth: 200, padding: 6, borderRadius: 10, gap: 2,
backgroundColor: th.windowBg, border: `1px solid ${th.separator}`, boxShadow: '0 12px 30px rgba(0,0,0,0.45)', zIndex: 20 }}>
{items.map((it, i) => (it === '-' ? <View key={i} style={{ height: 1, backgroundColor: th.separator, marginVertical: 3 }} /> : (
- <View key={i} onClick={() => { it.onClick(); onClose(); }} style={{ paddingHorizontal: 10, height: 26, borderRadius: 6, justifyContent: 'center',
+ <View key={i} onClick={() => { it.onClick(); onClose(); }} style={{ paddingHorizontal: 8, height: 26, borderRadius: 6, flexDirection: 'row', alignItems: 'center', gap: 6,
backgroundColor: it.checked ? th.hover : 'transparent' }}>
- <Text style={{ fontSize: 12, color: th.text }}>{it.checked ? `✓ ${it.label}` : it.label}</Text>
+ <Text style={{ width: 12, fontSize: 11, color: th.text }}>{it.checked ? '✓' : ''}</Text>
+ <Text style={{ fontSize: 13, color: th.text, whiteSpace: 'nowrap' }}>{it.label}</Text>
</View>
)))}
</View>
@@ -113,20 +182,22 @@ export default function Player() {
const win = useAppWindow();
const lib = useStore(library);
const [view, setView] = useWindowState('view', 'songs'); // songs | artists | albums | videos | queue
- const [sel, setSel] = useWindowState('sel', null); // artista o álbum elegido
- const [queue, setQueue] = useWindowState('queue', []); // rutas
+ const [sel, setSel] = useWindowState('sel', null); // chosen artist or album
+ const [queue, setQueue] = useWindowState('queue', []); // paths
const [index, setIndex] = useWindowState('index', -1);
const [shuffle, setShuffle] = useWindowState('shuffle', false);
const [repeat, setRepeat] = useWindowState('repeat', 'off'); // off | all | one
const [id, setId] = useWindowState('id', 0);
const [volume, setVolume] = useWindowState('volume', 1);
const [seekPreview, setSeekPreview] = useState(null);
- const [extSubs, setExtSubs] = useWindowState('extSubs', null); // .srt al lado del video
- const [subTrack, setSubTrack] = useWindowState('subTrack', -1); // pista de subtítulos de la película
+ const [extSubs, setExtSubs] = useWindowState('extSubs', null); // .srt next to the video
+ const [subTrack, setSubTrack] = useWindowState('subTrack', -1); // subtitle track of the movie
const [menu, setMenu] = useState(null);
const [controls, setControls] = useState(true);
const [showVideo, setShowVideo] = useWindowState('showVideo', false);
- const [openFor, setOpenFor] = useWindowState('openFor', null); // ruta del reproductor abierto
+ const [openFor, setOpenFor] = useWindowState('openFor', null); // path of the open player
+ const root = useRef(null);
+ const width = useBoxWidth(root, 960);
const p = usePlayer(id);
const current = queue[index] || null;
const video = !!current && isVideo(current) && p.info && p.info.video >= 0;
@@ -136,14 +207,14 @@ export default function Player() {
state.current = { queue, index, shuffle, repeat };
useEffect(() => { scan(); }, []);
- // al cerrar la ventana (no al volver a montarse por pantalla completa o imagen en imagen)
+ // when the window closes (not when it remounts for full screen or picture in picture)
useEffect(() => () => setTimeout(() => {
if (wm.get(win.id)) return;
media.close(idRef.current);
if (nowPlaying.get()?.window === win.id) nowPlaying.set(null);
}, 0), []);
- // abrir lo que mandó Archivos («Abrir con»)
+ // open what Files sent ("Open with")
const lastNonce = useRef(null);
useEffect(() => {
const path = win.args?.path;
@@ -154,9 +225,9 @@ export default function Player() {
lastNonce.current = win.args?.nonce;
}, [win.args?.nonce]);
- // un reproductor por pista
+ // one player per track
useEffect(() => {
- if (current && current === openFor && idRef.current) return; // ya está abierto (la app se volvió a montar)
+ if (current && current === openFor && idRef.current) return; // already open (the app remounted)
media.close(idRef.current);
setId(0);
setExtSubs(null);
@@ -167,7 +238,7 @@ export default function Player() {
setId(nid || 0);
if (isVideo(current)) {
const srt = current.replace(/\.[^./]+$/, '.srt');
- try { setExtSubs(parseSrt(fs.read(srt))); } catch (e) { /* sin .srt */ }
+ try { setExtSubs(parseSrt(fs.read(srt))); } catch (e) { /* no .srt */ }
}
wm.setTitle(win.id, baseName(current));
}, [current, index]);
@@ -188,7 +259,7 @@ export default function Player() {
useEffect(() => { if (p.state === 'ended') next(true); }, [p.state]);
- // para el Centro de control y las teclas multimedia
+ // for Control Center and the media keys
const tracks = lib.tracks;
const meta = useMemo(() => tracks.find((x) => x.path === current) || null, [tracks, current]);
useEffect(() => {
@@ -201,7 +272,7 @@ export default function Player() {
});
}, [current, id, p.playing, Math.floor(p.pos / 1000), p.duration, meta, p.info]);
- // ocultar los controles del video
+ // hide the video controls
const lastMove = useRef(0);
useEffect(() => {
if (!video || !p.playing) { setControls(true); return undefined; }
@@ -230,7 +301,7 @@ export default function Player() {
const playList = (paths, i) => { setQueue(paths); setIndex(i); setShowVideo(isVideo(paths[i])); };
- // subtítulos visibles ahora
+ // subtitles visible now
const pos = seekPreview != null ? seekPreview : p.pos;
const subs = subTrack >= 0 ? p.subs : extSubs;
const cue = subs ? subs.filter((c) => c.start <= p.pos && p.pos < c.end).map((c) => c.text).join('\n') : '';
@@ -238,31 +309,52 @@ export default function Player() {
const audioStreams = (p.info?.streams || []).filter((s) => s.type === 'audio');
const label = (s, i) => [s.title, s.lang && s.lang !== 'und' ? s.lang : null].filter(Boolean).join(' · ') || tr('player.track', { n: i + 1 });
+ // ---- transport pieces (the library bar and the video overlay arrange them differently) ----
+ const buttons = (col) => (
+ <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'center', gap: 6, direction: 'ltr' }}>
+ {!video && <IconBtn glyph="⤮" size={15} color={col} active={shuffle} onClick={() => setShuffle(!shuffle)} />}
+ <IconBtn color={col} onClick={prev}><SkipGlyph size={14} color={col} back /></IconBtn>
+ <IconBtn color={col} box={36} onClick={toggle}>{p.playing ? <PauseGlyph size={16} color={col} /> : <PlayGlyph size={16} color={col} />}</IconBtn>
+ <IconBtn color={col} onClick={() => next(false)}><SkipGlyph size={14} color={col} /></IconBtn>
+ {!video && <IconBtn onClick={() => setRepeat(repeat === 'off' ? 'all' : repeat === 'all' ? 'one' : 'off')}>
+ <RepeatGlyph color={repeat !== 'off' ? th.accent : col} one={repeat === 'one'} />
+ </IconBtn>}
+ </View>
+ );
+ const progress = (dark) => {
+ const dim = dark ? 'rgba(255,255,255,0.7)' : th.textDim;
+ return (
+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 8, direction: 'ltr' }}>
+ <Text style={{ fontSize: typeScale.caption, color: dim, width: 40, textAlign: 'end' }}>{mediaFormatTime(pos)}</Text>
+ <Bar style={{ flex: 1 }} value={p.duration ? pos / p.duration : 0} color={dark ? '#fff' : th.accent} track={dark ? 'rgba(255,255,255,0.25)' : th.control}
+ onChange={(f) => setSeekPreview(f * p.duration)} onCommit={(f) => { media.control(id, 'seek', Math.round(f * p.duration)); setSeekPreview(null); }} />
+ <Text style={{ fontSize: typeScale.caption, color: dim, width: 40 }}>{mediaFormatTime(p.duration)}</Text>
+ </View>
+ );
+ };
+ const volumeCtl = (dark, col) => (
+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 6, direction: 'ltr' }}>
+ <SpeakerGlyph size={13} color={dark ? '#fff' : th.textDim} level={volume} />
+ <Bar style={{ width: 84 }} value={volume / 1.5} color={dark ? '#fff' : th.textDim} track={dark ? 'rgba(255,255,255,0.25)' : th.control}
+ onChange={(f) => changeVolume(Math.round(f * 150) / 100)} />
+ {video && <IconBtn color={col} active={subTrack >= 0 || !!extSubs} onClick={() => setMenu(menu === 'subs' ? null : 'subs')}>
+ <CaptionsGlyph color={subTrack >= 0 || extSubs ? th.accent : col} />
+ </IconBtn>}
+ {video && audioStreams.length > 1 && <IconBtn glyph="♫" color={col} onClick={() => setMenu(menu === 'audio' ? null : 'audio')} />}
+ {video && <IconBtn glyph="⧉" color={col} active={win.mode === 'pip'} onClick={pip} />}
+ {video && <IconBtn glyph={win.mode === 'fullscreen' ? '⤡' : '⤢'} color={col} onClick={fullscreen} />}
+ </View>
+ );
+ // the video overlay: progress on top, the controls and the volume below
const transport = (dark) => {
- const col = dark ? '#fff' : th.text, dim = dark ? 'rgba(255,255,255,0.7)' : th.textDim;
+ const col = dark ? '#fff' : th.text;
return (
- <View style={{ gap: 4 }}>
- <View style={{ flexDirection: 'row', alignItems: 'center', gap: 10, direction: 'ltr' }}>
- <Text style={{ fontSize: 11, color: dim, width: 52, textAlign: 'end' }}>{mediaFormatTime(pos)}</Text>
- <Bar style={{ flex: 1 }} value={p.duration ? pos / p.duration : 0} color={th.accent} track={dark ? 'rgba(255,255,255,0.25)' : th.control}
- onChange={(f) => setSeekPreview(f * p.duration)} onCommit={(f) => { media.control(id, 'seek', Math.round(f * p.duration)); setSeekPreview(null); }} />
- <Text style={{ fontSize: 11, color: dim, width: 52 }}>{mediaFormatTime(p.duration)}</Text>
- </View>
- <View style={{ flexDirection: 'row', alignItems: 'center', gap: 4, direction: 'ltr' }}>
- {!video && <IconBtn glyph="⤮" color={col} active={shuffle} onClick={() => setShuffle(!shuffle)} />}
- <IconBtn glyph="⏮" color={col} onClick={prev} />
- <IconBtn glyph={p.playing ? '⏸' : '▶'} size={22} color={col} onClick={toggle} />
- <IconBtn glyph="⏭" color={col} onClick={() => next(false)} />
- {!video && <IconBtn glyph={repeat === 'one' ? '🔂' : '🔁'} color={col} active={repeat !== 'off'}
- onClick={() => setRepeat(repeat === 'off' ? 'all' : repeat === 'all' ? 'one' : 'off')} />}
+ <View style={{ gap: 6 }}>
+ {progress(dark)}
+ <View style={{ flexDirection: 'row', alignItems: 'center', direction: 'ltr' }}>
<View style={{ flex: 1 }} />
- <Text style={{ fontSize: 14, color: col }}>{volume === 0 ? '🔇' : volume < 0.5 ? '🔈' : '🔊'}</Text>
- <Bar style={{ width: 90 }} value={volume / 1.5} color={dark ? '#fff' : th.accent} track={dark ? 'rgba(255,255,255,0.25)' : th.control}
- onChange={(f) => changeVolume(Math.round(f * 150) / 100)} />
- {video && <IconBtn glyph="💬" color={col} active={subTrack >= 0 || !!extSubs} onClick={() => setMenu(menu === 'subs' ? null : 'subs')} />}
- {video && audioStreams.length > 1 && <IconBtn glyph="♫" color={col} onClick={() => setMenu(menu === 'audio' ? null : 'audio')} />}
- {video && <IconBtn glyph="⧉" color={col} active={win.mode === 'pip'} onClick={pip} />}
- {video && <IconBtn glyph={win.mode === 'fullscreen' ? '⤡' : '⤢'} color={col} onClick={fullscreen} />}
+ {buttons(col)}
+ <View style={{ flex: 1, alignItems: 'flex-end' }}>{volumeCtl(dark, col)}</View>
</View>
</View>
);
@@ -286,17 +378,17 @@ export default function Player() {
) : null}
{small ? (
<View style={{ position: 'absolute', right: 6, top: 6, flexDirection: 'row', gap: 2 }}>
- <IconBtn glyph={p.playing ? '⏸' : '▶'} color="#fff" onClick={toggle} />
+ <IconBtn onClick={toggle}>{p.playing ? <PauseGlyph size={13} color="#fff" /> : <PlayGlyph size={13} color="#fff" />}</IconBtn>
<IconBtn glyph="⧉" color="#fff" onClick={pip} />
</View>
) : controls && (
- <View style={{ position: 'absolute', left: 0, right: 0, bottom: 0, paddingHorizontal: 14, paddingTop: 24, paddingBottom: 8,
+ <View style={{ position: 'absolute', left: 0, right: 0, bottom: 0, paddingHorizontal: 20, paddingTop: 28, paddingBottom: 12,
background: 'linear-gradient(180deg, rgba(0,0,0,0), rgba(0,0,0,0.75))' }}>
{transport(true)}
</View>
)}
{controls && !small && win.mode === 'window' && (
- <View style={{ position: 'absolute', left: 10, top: 10 }}>
+ <View style={{ position: 'absolute', left: 12, top: 12 }}>
<IconBtn glyph={direction() === 'rtl' ? '›' : '‹'} size={20} color="#fff" onClick={() => setShowVideo(false)} />
</View>
)}
@@ -311,45 +403,63 @@ export default function Player() {
);
}
- // ---- biblioteca ----
+ // ---- library ----
const albums = albumsOf(tracks), artists = artistsOf(tracks);
- const row = (x, i, list, extra) => (
- <View key={x.path} onDoubleClick={() => playList(list.map((y) => y.path), i)} onClick={() => playList(list.map((y) => y.path), i)}
- style={{ height: 34, flexDirection: 'row', alignItems: 'center', gap: 10, paddingHorizontal: 12, borderRadius: 6,
- backgroundColor: x.path === current ? th.hover : i % 2 ? 'rgba(127,127,127,0.05)' : 'transparent' }}>
- <Text style={{ width: 22, fontSize: 11, color: x.path === current ? th.accent : th.textDim, textAlign: 'end' }}>{x.path === current ? '♪' : extra ?? i + 1}</Text>
- <Text style={{ flex: 2, fontSize: 12, color: th.text, whiteSpace: 'nowrap', overflow: 'hidden' }}>{x.title}</Text>
- <Text style={{ flex: 1, fontSize: 12, color: th.textDim, whiteSpace: 'nowrap', overflow: 'hidden' }}>{x.artist}</Text>
- <Text style={{ flex: 1, fontSize: 12, color: th.textDim, whiteSpace: 'nowrap', overflow: 'hidden' }}>{x.album}</Text>
- <Text style={{ width: 48, fontSize: 11, color: th.textDim, textAlign: 'end' }}>{x.duration ? mediaFormatTime(x.duration) : ''}</Text>
+ 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 header = (
+ <View style={{ height: 26, flexDirection: 'row', alignItems: 'center', gap: 12, paddingHorizontal: 10 }}>
+ <Hairline edge="bottom" />
+ <Text style={{ width: 22, fontSize: typeScale.caption, fontWeight: 600, color: th.textDim, textAlign: 'end' }}>#</Text>
+ <Text style={col(2, { fontSize: typeScale.caption, fontWeight: 600 })}>{tr('player.col.title')}</Text>
+ {showArtist && <Text style={col(1, { fontSize: typeScale.caption, fontWeight: 600 })}>{tr('player.col.artist')}</Text>}
+ {showAlbum && <Text style={col(1, { fontSize: typeScale.caption, fontWeight: 600 })}>{tr('player.col.album')}</Text>}
+ <Text style={{ width: 56, fontSize: typeScale.caption, fontWeight: 600, color: th.textDim, textAlign: 'end', whiteSpace: 'nowrap' }}>{tr('player.col.time')}</Text>
</View>
);
+ const row = (x, i, list, extra) => {
+ const on = x.path === current;
+ return (
+ <View key={x.path} onDoubleClick={() => playList(list.map((y) => y.path), i)} onClick={() => playList(list.map((y) => y.path), i)}
+ style={{ height: 30, flexDirection: 'row', alignItems: 'center', gap: 12, paddingHorizontal: 10, borderRadius: 6,
+ backgroundColor: on ? th.hover : i % 2 ? (th.mode === 'dark' ? 'rgba(255,255,255,0.025)' : 'rgba(0,0,0,0.025)') : 'transparent' }}>
+ <Text style={{ width: 22, fontSize: typeScale.caption, color: on ? th.accent : th.textDim, textAlign: 'end' }}>{on ? '♪' : extra ?? i + 1}</Text>
+ <Text style={col(2, { fontSize: 13, color: on ? th.accent : th.text, fontWeight: on ? 500 : 400 })}>{x.title}</Text>
+ {showArtist && <Text style={col(1)}>{x.artist}</Text>}
+ {showAlbum && <Text style={col(1)}>{x.album}</Text>}
+ <Text style={{ width: 56, fontSize: typeScale.caption, color: th.textDim, textAlign: 'end', direction: 'ltr' }}>{x.duration ? mediaFormatTime(x.duration) : ''}</Text>
+ </View>
+ );
+ };
+ const songList = (list, mk) => <View>{header}<View style={{ height: 4 }} />{list.map(mk)}</View>;
let content;
if (view === 'albums' || (view === 'artists' && sel)) {
const list = view === 'artists' ? albums.filter((a) => a.artist === sel || a.tracks.some((x) => x.artist === sel)) : albums;
if (view === 'albums' && sel) {
const a = albums.find((x) => x.key === sel);
content = a ? (
- <View style={{ gap: 14 }}>
- <View style={{ flexDirection: 'row', gap: 16, alignItems: 'flex-end' }}>
+ <View style={{ gap: 20, paddingHorizontal: 10 }}>
+ <View style={{ flexDirection: 'row', gap: 20, alignItems: 'flex-end' }}>
<Cover path={a.tracks[0].path} size={140} radius={10} />
- <View style={{ gap: 4, flex: 1 }}>
- <Text style={{ fontSize: 22, fontWeight: 700, color: th.text }}>{a.album || tr('player.unknownAlbum')}</Text>
- <Text style={{ fontSize: 14, color: th.accent }}>{a.artist || tr('player.unknownArtist')}</Text>
- <Text style={{ fontSize: 12, color: th.textDim }}>{[a.year, tr('player.songs', { count: a.tracks.length })].filter(Boolean).join(' · ')}</Text>
+ <View style={{ gap: 4, flex: 1, minWidth: 0 }}>
+ <Text style={{ fontSize: typeScale.largeTitle, fontWeight: 600, color: th.text }}>{a.album || tr('player.unknownAlbum')}</Text>
+ <Text style={{ fontSize: typeScale.headline, color: th.accent }}>{a.artist || tr('player.unknownArtist')}</Text>
+ <Text style={{ fontSize: typeScale.callout, color: th.textDim }}>{[a.year, tr('player.songs', { count: a.tracks.length })].filter(Boolean).join(' · ')}</Text>
</View>
</View>
- <View>{a.tracks.map((x, i) => row(x, i, a.tracks, x.track || i + 1))}</View>
+ <View style={{ marginHorizontal: -10 }}>{songList(a.tracks, (x, i) => row(x, i, a.tracks, x.track || i + 1))}</View>
</View>
) : null;
} else {
content = (
- <View style={{ flexDirection: 'row', flexWrap: 'wrap', gap: 18 }}>
+ <View style={{ flexDirection: 'row', flexWrap: 'wrap', gap: 20, paddingHorizontal: 10 }}>
{list.map((a) => (
- <View key={a.key} onClick={() => { setView('albums'); setSel(a.key); }} style={{ width: 150, gap: 6 }}>
+ <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: 12, fontWeight: 600, color: th.text, whiteSpace: 'nowrap', overflow: 'hidden' }}>{a.album || tr('player.unknownAlbum')}</Text>
- <Text style={{ fontSize: 11, 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', 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>
</View>
))}
</View>
@@ -358,65 +468,77 @@ export default function Player() {
} else if (view === 'artists') {
content = (
<View>{artists.map((a) => (
- <View key={a.name} onClick={() => setSel(a.name)} style={{ height: 48, flexDirection: 'row', alignItems: 'center', gap: 12, paddingHorizontal: 8, borderRadius: 8 }}>
+ <View key={a.name} onClick={() => setSel(a.name)} style={{ height: 48, flexDirection: 'row', alignItems: 'center', gap: 12, paddingHorizontal: 10, borderRadius: 8 }}>
<Cover path={a.tracks[0].path} size={36} radius={18} />
- <Text style={{ flex: 1, fontSize: 13, color: th.text }}>{a.name || tr('player.unknownArtist')}</Text>
- <Text style={{ fontSize: 11, color: th.textDim }}>{tr('player.songs', { count: a.tracks.length })}</Text>
+ <Text style={{ flex: 1, minWidth: 0, fontSize: 13, color: th.text, whiteSpace: 'nowrap', overflow: 'hidden' }}>{a.name || tr('player.unknownArtist')}</Text>
+ <Text style={{ fontSize: typeScale.caption, color: th.textDim }}>{tr('player.songs', { count: a.tracks.length })}</Text>
</View>
))}</View>
);
} else if (view === 'videos') {
content = (
- <View style={{ flexDirection: 'row', flexWrap: 'wrap', gap: 16 }}>
+ <View style={{ flexDirection: 'row', flexWrap: 'wrap', gap: 20, paddingHorizontal: 10 }}>
{lib.videos.map((v, i) => <VideoCard key={v.path} v={v} onOpen={() => playList(lib.videos.map((x) => x.path), i)} />)}
</View>
);
} else if (view === 'queue') {
- content = <View>{queue.map((q, i) => row(tracks.find((x) => x.path === q) || { path: q, title: baseName(q), artist: '', album: '' }, i, queue.map((x) => ({ path: x }))))}</View>;
+ content = songList(queue, (q, i) => row(tracks.find((x) => x.path === q) || { path: q, title: baseName(q), artist: '', album: '' }, i, queue.map((x) => ({ path: x }))));
} else {
- content = <View>{tracks.slice().sort((a, b) => a.title.localeCompare(b.title)).map((x, i, list) => row(x, i, list))}</View>;
+ content = songList(tracks.slice().sort((a, b) => a.title.localeCompare(b.title)), (x, i, list) => row(x, i, list));
}
const titles = { songs: tr('player.songsTitle'), artists: sel || tr('player.artists'), albums: tr('player.albums'), videos: tr('player.videos'), queue: tr('player.queue') };
+ const empty = !((view === 'videos' ? lib.videos.length : tracks.length) || view === 'queue');
return (
- <View style={{ flex: 1, flexDirection: 'row' }} onMouseDown={() => setMenu(null)}>
- <View style={{ width: 190, backgroundColor: th.sidebarBg, padding: 8, gap: 2 }}>
- <SectionTitle>{tr('player.library')}</SectionTitle>
- {[['songs', '♪'], ['artists', '👤'], ['albums', '◫'], ['videos', '▶']].map(([k, g]) => (
- <SidebarItem key={k} label={tr(`player.nav.${k}`)} icon={g} selected={view === k} onClick={() => { setView(k); setSel(null); }} />
- ))}
- <SectionTitle>{tr('player.playing')}</SectionTitle>
- <SidebarItem label={tr('player.nav.queue')} icon="≡" selected={view === 'queue'} onClick={() => setView('queue')} />
- {current && isVideo(current) && <SidebarItem label={tr('player.nav.video')} icon="▣" selected={false} onClick={() => setShowVideo(true)} />}
- <View style={{ flex: 1 }} />
- {lib.scanning && <Text style={{ fontSize: 10, color: th.textDim, paddingHorizontal: 8 }}>{tr('player.scanning', { done: lib.done, total: lib.total })}</Text>}
- </View>
- <View style={{ flex: 1 }}>
- <View style={{ height: 44, flexDirection: 'row', alignItems: 'center', paddingHorizontal: 16, gap: 8 }}>
- {sel && <IconBtn glyph={direction() === 'rtl' ? '›' : '‹'} size={18} onClick={() => setSel(null)} />}
- <Text style={{ fontSize: 17, fontWeight: 700, color: th.text }}>{titles[view]}</Text>
+ <View ref={root} style={{ flex: 1 }} onMouseDown={() => setMenu(null)}>
+ <View style={{ flex: 1, flexDirection: 'row' }}>
+ <View style={{ width: 200, backgroundColor: th.sidebarBg, paddingHorizontal: 10, paddingTop: 4, gap: 2 }}>
+ <Hairline edge="end" />
+ <SectionTitle>{tr('player.library')}</SectionTitle>
+ {[['songs', '♪'], ['artists', '☺'], ['albums', '◫'], ['videos', '▶']].map(([k, g]) => (
+ <SidebarItem key={k} label={tr(`player.nav.${k}`)} icon={g} selected={view === k} onClick={() => { setView(k); setSel(null); }} />
+ ))}
+ <SectionTitle>{tr('player.playing')}</SectionTitle>
+ <SidebarItem label={tr('player.nav.queue')} icon="≡" selected={view === 'queue'} onClick={() => setView('queue')} />
+ {current && isVideo(current) && <SidebarItem label={tr('player.nav.video')} icon="▣" selected={false} onClick={() => setShowVideo(true)} />}
+ <View style={{ flex: 1 }} />
+ {lib.scanning && <Text style={{ fontSize: typeScale.caption, color: th.textDim, paddingHorizontal: 10, paddingBottom: 10 }}>{tr('player.scanning', { done: lib.done, total: lib.total })}</Text>}
</View>
- <ScrollView style={{ flex: 1, paddingHorizontal: 12 }}>
- {(view === 'videos' ? lib.videos.length : tracks.length) || view === 'queue' ? content : (
- <View style={{ padding: 40, alignItems: 'center', gap: 6 }}>
- <Text style={{ fontSize: 28 }}>{view === 'videos' ? '🎬' : '🎵'}</Text>
- <Text style={{ fontSize: 13, color: th.textDim, textAlign: 'center' }}>{tr(view === 'videos' ? 'player.emptyVideos' : 'player.emptyMusic')}</Text>
- </View>
- )}
- <View style={{ height: 16 }} />
- </ScrollView>
- {current && <View style={{ height: 1, backgroundColor: th.separator }} />}
- {current && (
- <View style={{ height: 84, flexDirection: 'row', alignItems: 'center', gap: 12, paddingHorizontal: 14, backgroundColor: th.sidebarBg }}>
- <View onClick={() => isVideo(current) && setShowVideo(true)}><Cover path={current} size={56} /></View>
- <View style={{ width: 170, 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: 11, color: th.textDim, whiteSpace: 'nowrap' }}>{meta?.artist || p.info?.tags?.artist || ''}</Text>
- </View>
- <View style={{ flex: 1 }}>{transport(false)}</View>
+ <View style={{ flex: 1, minWidth: 0 }}>
+ <View style={{ height: 52, flexDirection: 'row', alignItems: 'center', paddingHorizontal: 20, gap: 6 }}>
+ {sel && <ToolbarButton icon={direction() === 'rtl' ? '›' : '‹'} iconSize={20} title={tr('player.back')} onClick={() => setSel(null)} style={{ marginHorizontal: -6 }} />}
+ <Text style={{ fontSize: typeScale.largeTitle, fontWeight: 600, color: th.text, whiteSpace: 'nowrap', overflow: 'hidden' }}>{titles[view]}</Text>
</View>
- )}
+ {empty ? (
+ <EmptyState icon={view === 'videos' ? '▶' : '♪'} title={tr(view === 'videos' ? 'player.emptyVideosTitle' : 'player.emptyMusicTitle')}
+ hint={tr(view === 'videos' ? 'player.emptyVideos' : 'player.emptyMusic')} />
+ ) : (
+ <ScrollView style={{ flex: 1, paddingHorizontal: 10 }}>
+ {content}
+ <View style={{ height: 16 }} />
+ </ScrollView>
+ )}
+ </View>
</View>
+ {current && (
+ <View style={{ height: 72, flexDirection: 'row', alignItems: 'center', gap: 16, paddingHorizontal: 16, backgroundColor: th.sidebarBg }}>
+ <Hairline edge="top" />
+ <View style={[{ minWidth: 0, flexDirection: 'row', alignItems: 'center', gap: 12 }, narrow ? null : { flex: 1 }]}>
+ <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>
+ </View>
+ )}
+ </View>
+ <View style={[{ minWidth: 0, gap: 2 }, narrow ? { flex: 1 } : { width: 380 }]}>
+ {buttons(th.text)}
+ {progress(false)}
+ </View>
+ {!narrow && <View style={{ flex: 1, minWidth: 0, alignItems: 'flex-end' }}>{volumeCtl(false, th.text)}</View>}
+ </View>
+ )}
</View>
);
}
@@ -425,11 +547,11 @@ function VideoCard({ v, onOpen }) {
const th = useTheme();
const thumb = useThumb(v.path, 320);
return (
- <View onClick={onOpen} style={{ width: 200, gap: 6 }}>
+ <View onClick={onOpen} style={{ width: 200, gap: 8 }}>
<View style={{ width: 200, height: 112, borderRadius: 8, overflow: 'hidden', backgroundColor: '#111', alignItems: 'center', justifyContent: 'center' }}>
{thumb ? <Image src={thumb} style={{ width: 200, height: 112, objectFit: 'cover' }} /> : <Text style={{ fontSize: 26, color: '#666' }}>▶</Text>}
</View>
- <Text style={{ fontSize: 12, color: th.text, whiteSpace: 'nowrap', overflow: 'hidden' }}>{v.title}</Text>
+ <Text style={{ fontSize: 13, color: th.text, whiteSpace: 'nowrap', overflow: 'hidden' }}>{v.title}</Text>
</View>
);
}
diff --git a/apps/recorder/index.jsx b/apps/recorder/index.jsx
index 3e8c32b..7a1da98 100644
--- a/apps/recorder/index.jsx
+++ b/apps/recorder/index.jsx
@@ -1,10 +1,10 @@
-// Grabadora — notas de voz (diseño propio, al estilo de las grabadoras de escritorio).
+// Voice Recorder: voice memos (our own design, in the style of desktop recorders).
//
-// Graba el micrófono por PipeWire: el stream es de lord-server (después del permiso) y
-// lord-media escribe el WAV. Lista de grabaciones en ~/Música/Grabaciones, con forma de onda,
-// reproducir, renombrar, recortar y exportar a Opus, MP3 o WAV (lord-media, con FFmpeg).
+// Records the microphone through PipeWire: the stream belongs to lord-server (after the
+// permission) and lord-media writes the WAV. Recordings live in ~/Music/Recordings, with a
+// waveform, play, rename, trim and export to Opus, MP3 or WAV (lord-media, with FFmpeg).
import {
- View, Text, Image, ScrollView, Button, TextInput, Segmented, useTheme, useKeyboard,
+ View, Text, Image, ScrollView, Button, TextInput, Segmented, Hairline, EmptyState, useTheme, useKeyboard, typeScale,
t as tr, media, usePlayer, userDirs, fs, mediaFormatTime, formatDate, formatTime, addListener, useSound, microphones, defaultSource,
} from '@lordos/sdk';
import { useEffect, useMemo, useRef, useState } from 'react';
@@ -17,7 +17,7 @@ export function Icon({ size: s }) {
return (
<View style={{ width: s, height: s, borderRadius: s * 0.225, background: 'linear-gradient(160deg, #2b2b30, #0e0e10)',
boxShadow: `0 ${s * 0.04}px ${s * 0.12}px rgba(0,0,0,0.35)`, overflow: 'hidden' }}>
- {/* forma de onda roja sobre negro */}
+ {/* red waveform on black */}
{bars.map((h, i) => (
<View key={i} style={{ position: 'absolute', left: s * (0.16 + i * 0.09), top: s * (0.5 - h / 2), width: s * 0.05, height: s * h,
borderRadius: s * 0.025, backgroundColor: i === 4 ? '#fff' : '#ff453a' }} />
@@ -28,8 +28,8 @@ export function Icon({ size: s }) {
function dir() {
const d = `${userDirs().music}/${tr('recorder.folder')}`;
- try { fs.mkdir(userDirs().music); } catch (e) { /* ya está */ }
- try { fs.mkdir(d); } catch (e) { /* ya está */ }
+ try { fs.mkdir(userDirs().music); } catch (e) { /* already there */ }
+ try { fs.mkdir(d); } catch (e) { /* already there */ }
return d;
}
function freeName(base, ext) {
@@ -42,14 +42,14 @@ function freeName(base, ext) {
const baseName = (p) => String(p).split('/').pop();
const stem = (p) => baseName(p).replace(/\.[^.]+$/, '');
-// Forma de onda en un lienzo RGBA (más liviano que cientos de cajas).
+// Waveform on an RGBA canvas (lighter than hundreds of boxes).
function Wave({ peaks, width, height, color, played = 0, sel }) {
const px = useMemo(() => {
const w = Math.max(1, Math.round(width)), h = Math.max(1, Math.round(height));
const data = new Uint8Array(w * h * 4);
const c = [parseInt(color.slice(1, 3), 16), parseInt(color.slice(3, 5), 16), parseInt(color.slice(5, 7), 16)];
const n = peaks.length || 1;
- const top = Math.max(50, ...peaks); // se dibuja relativo al pico (como las grabadoras)
+ const top = Math.max(50, ...peaks); // drawn relative to the peak (as recorders do)
for (let x = 0; x < w; x++) {
const v = peaks.length ? peaks[Math.min(n - 1, Math.floor((x / w) * n))] / top : 0;
const bh = Math.max(1, Math.round(v * (h - 2)));
@@ -64,6 +64,17 @@ function Wave({ peaks, width, height, color, played = 0, sel }) {
return <Image pixels={px} style={{ width, height }} />;
}
+// Width of a box after layout (the waveform follows the window width).
+function useBoxWidth(ref, initial) {
+ const [w, setW] = useState(initial);
+ useEffect(() => {
+ if (!ref.current) return;
+ const lw = Math.round(lord.getLayout(ref.current.id)[2]);
+ if (lw > 0 && Math.abs(lw - w) > 2) setW(lw);
+ });
+ return w;
+}
+
export default function Recorder() {
const th = useTheme();
const snd = useSound();
@@ -76,7 +87,7 @@ export default function Recorder() {
const [sel, setSel] = useState(null);
const [wave, setWave] = useState(null);
const [playId, setPlayId] = useState(0);
- const [trim, setTrim] = useState(null); // [desde, hasta] 0..1
+ const [trim, setTrim] = useState(null); // [from, to] 0..1
const [renaming, setRenaming] = useState(null);
const [format, setFormat] = useState('opus');
const [msg, setMsg] = useState(null);
@@ -87,7 +98,7 @@ export default function Recorder() {
const reload = () => {
let l = [];
- try { l = fs.list(dir()).filter((e) => !e.dir && AUDIO.test(e.name)).map((e) => ({ path: `${dir()}/${e.name}`, name: e.name, mtime: e.mtime, size: e.size })); } catch (e) { /* sin carpeta */ }
+ try { l = fs.list(dir()).filter((e) => !e.dir && AUDIO.test(e.name)).map((e) => ({ path: `${dir()}/${e.name}`, name: e.name, mtime: e.mtime, size: e.size })); } catch (e) { /* no folder */ }
setList(l.sort((a, b) => b.mtime - a.mtime));
};
useEffect(reload, []);
@@ -97,7 +108,7 @@ export default function Recorder() {
}, [rp.state, rp.closed]);
useEffect(() => () => { media.close(rec); media.close(playId); }, []);
- // forma de onda de la elegida
+ // waveform of the selected one
useEffect(() => {
setWave(null); setTrim(null);
media.close(playId); setPlayId(0);
@@ -162,66 +173,81 @@ export default function Recorder() {
});
const cur = list.find((x) => x.path === sel);
- const W = 520;
+ const detail = useRef(null);
+ const W = Math.max(200, Math.min(760, useBoxWidth(detail, 560) - 40)); // the box width minus its padding
+ const WAVE_H = 120;
return (
<View style={{ flex: 1, flexDirection: 'row' }}>
<View style={{ width: 240, backgroundColor: th.sidebarBg }}>
- <View style={{ height: 40, justifyContent: 'center', paddingHorizontal: 14 }}>
- <Text style={{ fontSize: 15, fontWeight: 700, color: th.text }}>{tr('recorder.all')}</Text>
+ <Hairline edge="end" />
+ <View style={{ height: 44, justifyContent: 'center', paddingHorizontal: 20 }}>
+ <Text style={{ fontSize: typeScale.headline, fontWeight: 600, color: th.text }}>{tr('recorder.all')}</Text>
</View>
- <ScrollView style={{ flex: 1 }}>
- {!list.length && <Text style={{ fontSize: 12, color: th.textDim, padding: 14 }}>{tr('recorder.empty')}</Text>}
- {list.map((x) => (
- <View key={x.path} onClick={() => setSel(x.path)} style={{ paddingHorizontal: 14, paddingVertical: 8, gap: 2,
- backgroundColor: x.path === sel ? th.accent : 'transparent' }}>
- <Text style={{ fontSize: 13, fontWeight: 600, color: x.path === sel ? '#fff' : th.text, whiteSpace: 'nowrap', overflow: 'hidden' }}>{stem(x.path)}</Text>
- <Text style={{ fontSize: 11, color: x.path === sel ? 'rgba(255,255,255,0.8)' : th.textDim }}>
- {`${formatDate(new Date(x.mtime))} · ${baseName(x.path).split('.').pop().toUpperCase()}`}
- </Text>
- </View>
- ))}
+ <ScrollView style={{ flex: 1, paddingHorizontal: 10 }}>
+ {!list.length && <Text style={{ fontSize: typeScale.callout, color: th.textDim, paddingHorizontal: 10, paddingVertical: 8, lineHeight: 1.4 }}>{tr('recorder.empty')}</Text>}
+ {list.map((x) => {
+ const on = x.path === sel;
+ return (
+ <View key={x.path} onClick={() => setSel(x.path)} style={{ paddingHorizontal: 10, paddingVertical: 7, gap: 2, borderRadius: 7, marginBottom: 2,
+ backgroundColor: on ? th.accent : 'transparent' }}>
+ <Text style={{ fontSize: typeScale.body, fontWeight: 600, color: on ? '#fff' : th.text, whiteSpace: 'nowrap', overflow: 'hidden' }}>{stem(x.path)}</Text>
+ <Text style={{ fontSize: typeScale.caption, color: on ? 'rgba(255,255,255,0.8)' : th.textDim, whiteSpace: 'nowrap' }}>
+ {`${formatDate(new Date(x.mtime))} · ${baseName(x.path).split('.').pop().toUpperCase()}`}
+ </Text>
+ </View>
+ );
+ })}
</ScrollView>
- <View style={{ padding: 12, gap: 8, alignItems: 'center' }}>
+ <View style={{ paddingHorizontal: 16, paddingTop: 12, paddingBottom: 16, gap: 10, alignItems: 'center' }}>
+ <Hairline edge="top" />
{rec ? (
- <View style={{ alignSelf: 'stretch', height: 50, flexDirection: 'row', alignItems: 'center', gap: 1, direction: 'ltr' }}>
- {levels.map((l, i) => <View key={i} style={{ width: 1, height: Math.max(1, Math.min(48, Math.sqrt(l) * 60)), backgroundColor: '#ff453a' }} />)}
+ <View style={{ alignSelf: 'stretch', height: 48, flexDirection: 'row', alignItems: 'center', gap: 1, direction: 'ltr', overflow: 'hidden' }}>
+ {levels.map((l, i) => <View key={i} style={{ width: 1, height: Math.max(1, Math.min(46, Math.sqrt(l) * 60)), backgroundColor: '#ff453a' }} />)}
</View>
) : null}
- {rec ? <Text style={{ fontSize: 22, fontWeight: 300, color: th.text }}>{mediaFormatTime(rp.ms)}</Text> : null}
- <View style={{ flexDirection: 'row', alignItems: 'center', gap: 14 }}>
+ {rec ? <Text style={{ fontSize: 22, fontWeight: 300, color: th.text, direction: 'ltr' }}>{mediaFormatTime(rp.ms)}</Text> : null}
+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 16 }}>
{rec ? <View onClick={pause} style={{ width: 36, height: 36, borderRadius: 18, backgroundColor: th.control, alignItems: 'center', justifyContent: 'center' }}>
- <Text style={{ fontSize: 14, color: th.text }}>{paused ? '▶' : '⏸'}</Text>
+ {paused ? <Text style={{ fontSize: 13, color: th.text }}>▶</Text> : (
+ <View style={{ flexDirection: 'row', gap: 4 }}>
+ <View style={{ width: 4, height: 13, borderRadius: 1, backgroundColor: th.text }} />
+ <View style={{ width: 4, height: 13, borderRadius: 1, backgroundColor: th.text }} />
+ </View>
+ )}
</View> : null}
- <View onClick={start} style={{ width: 54, height: 54, borderRadius: 27, border: `3px solid ${th.separator}`, alignItems: 'center', justifyContent: 'center' }}>
- <View style={{ width: rec ? 20 : 40, height: rec ? 20 : 40, borderRadius: rec ? 4 : 20, backgroundColor: '#ff3b30' }} />
+ <View onClick={start} style={{ width: 56, height: 56, borderRadius: 28, border: `3px solid ${th.mode === 'dark' ? 'rgba(255,255,255,0.28)' : 'rgba(0,0,0,0.18)'}`,
+ alignItems: 'center', justifyContent: 'center' }}>
+ <View style={{ width: rec ? 20 : 42, height: rec ? 20 : 42, borderRadius: rec ? 5 : 21, backgroundColor: '#ff3b30' }} />
</View>
</View>
{mics.length > 1 && !rec && (
- <Segmented value={source || defaultSource(snd)?.name || ''} onChange={setSource}
+ <Segmented small value={source || defaultSource(snd)?.name || ''} onChange={setSource}
options={mics.slice(0, 3).map((m) => [m.name, m.description.length > 14 ? `${m.description.slice(0, 13)}…` : m.description])} />
)}
</View>
</View>
- <View style={{ flex: 1, padding: 20, gap: 14 }}>
+ <View ref={detail} style={{ flex: 1, minWidth: 0, padding: 20, gap: 12 }}>
{cur ? (
<>
- {renaming !== null ? (
- <TextInput value={renaming} autoFocus selectAll onChange={setRenaming} onSubmit={doRename} onCancel={() => setRenaming(null)} size={18} />
- ) : (
- <Text onDoubleClick={() => setRenaming(stem(cur.path))} style={{ fontSize: 20, fontWeight: 700, color: th.text }}>{stem(cur.path)}</Text>
- )}
- <Text style={{ fontSize: 12, color: th.textDim }}>{`${formatDate(new Date(cur.mtime), 'long')} · ${wave ? mediaFormatTime(wave.duration) : '…'}`}</Text>
- <View ref={waveBox} style={{ width: W, height: 110, borderRadius: 10, backgroundColor: th.hover, justifyContent: 'center', direction: 'ltr' }}
+ <View style={{ gap: 4 }}>
+ {renaming !== null ? (
+ <TextInput value={renaming} autoFocus selectAll onChange={setRenaming} onSubmit={doRename} onCancel={() => setRenaming(null)} size={17} />
+ ) : (
+ <Text onDoubleClick={() => setRenaming(stem(cur.path))} style={{ fontSize: typeScale.largeTitle, fontWeight: 600, color: th.text, whiteSpace: 'nowrap', overflow: 'hidden' }}>{stem(cur.path)}</Text>
+ )}
+ <Text style={{ fontSize: typeScale.callout, color: th.textDim }}>{`${formatDate(new Date(cur.mtime), 'long')} · ${wave ? mediaFormatTime(wave.duration) : '…'}`}</Text>
+ </View>
+ <View ref={waveBox} style={{ width: W, height: WAVE_H, borderRadius: 10, backgroundColor: th.hover, border: `1px solid ${th.separator}`, justifyContent: 'center', direction: 'ltr', overflow: 'hidden' }}
onMouseDown={(e) => {
const [lx, , w] = lord.getLayout(waveBox.current.id);
const f = (e.x - lx) / w;
if (!trim) { if (playId && wave) media.control(playId, 'seek', f * wave.duration); return; }
drag.current = { edge: Math.abs(f - trim[0]) < Math.abs(f - trim[1]) ? 0 : 1 };
}}>
- {wave ? <Wave peaks={wave.peaks} width={W} height={96} color={th.mode === 'dark' ? '#ff6961' : '#e0352b'}
- played={playId && wave.duration ? pp.pos / wave.duration : 0} sel={trim} /> : <Text style={{ fontSize: 12, color: th.textDim, textAlign: 'center' }}>…</Text>}
+ {wave ? <Wave peaks={wave.peaks} width={W - 2} height={WAVE_H - 16} color={th.mode === 'dark' ? '#ff6961' : '#e0352b'}
+ played={playId && wave.duration ? pp.pos / wave.duration : 0} sel={trim} /> : <Text style={{ fontSize: typeScale.callout, color: th.textDim, textAlign: 'center' }}>…</Text>}
{trim && [0, 1].map((k) => (
- <View key={k} style={{ position: 'absolute', left: trim[k] * W - 2, top: 0, width: 4, height: 110, borderRadius: 2, backgroundColor: '#ffcc00' }} />
+ <View key={k} style={{ position: 'absolute', left: trim[k] * W - 2, top: 0, width: 4, height: WAVE_H, borderRadius: 2, backgroundColor: '#ffcc00' }} />
))}
</View>
<View style={{ flexDirection: 'row', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
@@ -230,19 +256,17 @@ export default function Recorder() {
<Button label={trim ? tr('recorder.cancelTrim') : tr('recorder.trim')} onClick={() => setTrim(trim ? null : [0.1, 0.9])} />
{trim && <Button primary label={tr('recorder.saveTrim')} onClick={() => exportAs(/\.wav$/i.test(sel) ? 'wav' : format, true)} />}
</View>
- <View style={{ flexDirection: 'row', gap: 10, alignItems: 'center' }}>
- <Text style={{ fontSize: 12, color: th.text }}>{tr('recorder.export')}</Text>
+ <View style={{ height: 1, backgroundColor: th.separator, marginVertical: 4 }} />
+ <View style={{ flexDirection: 'row', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
+ <Text style={{ fontSize: typeScale.body, color: th.text }}>{tr('recorder.export')}</Text>
<Segmented value={format} onChange={setFormat} options={[['opus', 'Opus'], ['mp3', 'MP3'], ['wav', 'WAV']]} />
<Button label={tr('recorder.exportBtn')} onClick={() => exportAs(format, false)} />
</View>
</>
) : (
- <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', gap: 8 }}>
- <Text style={{ fontSize: 34 }}>🎙</Text>
- <Text style={{ fontSize: 13, color: th.textDim, textAlign: 'center' }}>{tr('recorder.hint')}</Text>
- </View>
+ <EmptyState icon={<Icon size={56} />} title={tr('recorder.emptyTitle')} hint={tr('recorder.hint')} />
)}
- {msg && <Text style={{ fontSize: 12, color: th.accent }}>{msg}</Text>}
+ {msg && <Text style={{ fontSize: typeScale.callout, color: th.accent }}>{msg}</Text>}
</View>
</View>
);
diff --git a/apps/reminders/index.jsx b/apps/reminders/index.jsx
new file mode 100644
index 0000000..c2bd35e
--- /dev/null
+++ b/apps/reminders/index.jsx
@@ -0,0 +1,458 @@
+// Reminders — to-do lists kept by lord-maild (local, or synced with CalDAV as VTODO): see
+// docs/MAIL.md. Smart lists (Today, Scheduled, All, Flagged, Completed) are filters over
+// reminders.items(); their alarms ring with the app closed (sdk/calendar.js, startReminders).
+import {
+ View, Text, useTheme, useLocale, useKeyboard, useWindowState, usePim, reminders, calendars,
+ Button, Toggle, Segmented, TextInput, ScrollView, Hairline, Toolbar, ToolbarButton, ToolbarSpacer, EmptyState, addListener,
+ formatDate, formatTime, direction, t,
+} from '@lordos/sdk';
+import { useEffect, useMemo, useRef, useState } from 'react';
+import {
+ RED, COLORS, sod, addDays, ymd, parseYmd, minutesOf, atMinutes, Sheet, Field, Choice, TextArea, DateField, TimeField, ColorSwatches,
+ Popover, MenuList, Layers, useLoad, useNow,
+} from './ui.jsx';
+
+// ---- icon: a white rounded square with three colored dots and lines ----
+
+export function Icon({ size: s }) {
+ const dots = ['#007aff', '#ff3b30', '#ff9500'];
+ return (
+ <View style={{ width: s, height: s, borderRadius: s * 0.225, backgroundColor: '#ffffff', border: '1px solid rgba(0,0,0,0.08)',
+ boxShadow: `0 ${s * 0.04}px ${s * 0.12}px rgba(0,0,0,0.35)`, paddingHorizontal: s * 0.17, justifyContent: 'center', gap: s * 0.09 }}>
+ {dots.map((c, i) => (
+ <View key={c} style={{ flexDirection: 'row', alignItems: 'center', gap: s * 0.08 }}>
+ <View style={{ width: s * 0.13, height: s * 0.13, borderRadius: s * 0.065, backgroundColor: c }} />
+ <View style={{ width: s * (i === 2 ? 0.3 : 0.42), height: Math.max(1, s * 0.035), borderRadius: s * 0.02, backgroundColor: '#c7c7cc' }} />
+ </View>
+ ))}
+ </View>
+ );
+}
+
+const SMART = { today: '#007aff', scheduled: RED, all: '#5b5b60', flagged: '#ff9500', completed: '#8e8e93' };
+const ORANGE = '#ff9500';
+
+const dueDay = (it) => (it.due == null ? null : it.dueAllDay ? it.dueDate || ymd(new Date(it.due)) : ymd(new Date(it.due)));
+const isOverdue = (it, now) => !it.done && it.due != null && (it.dueAllDay ? dueDay(it) < ymd(new Date(now)) : it.due < now);
+const isToday = (it, now) => it.due != null && dueDay(it) <= ymd(new Date(now));
+const prioMarks = (p) => (p === 1 ? '!!!' : p >= 2 && p <= 5 ? '!!' : p >= 6 ? '!' : '');
+
+function matches(sel, it, now) {
+ if (sel === 'today') return isToday(it, now);
+ if (sel === 'scheduled') return it.due != null;
+ if (sel === 'flagged') return !!it.flag;
+ if (sel === 'completed') return !!it.done;
+ if (sel === 'all') return true;
+ return it.list === sel.slice(5);
+}
+
+function dueText(it) {
+ if (it.due == null) return '';
+ if (it.dueAllDay) { const d = parseYmd(it.dueDate) || new Date(it.due); return formatDate(d, 'short'); }
+ const d = new Date(it.due);
+ return t('reminders.dueAt', { date: formatDate(d, 'short'), time: formatTime(d) });
+}
+
+export default function RemindersApp() {
+ const th = useTheme();
+ useLocale();
+ const rev = usePim();
+ const now = useNow(60000);
+ const [sel, setSel] = useWindowState('sel', 'today');
+ const [showDone, setShowDone] = useWindowState('showDone', false);
+ const [sheet, setSheet] = useState(null); // { newList } | { list }
+ const listsQ = useLoad(() => reminders.lists(), [rev]);
+ const lists = listsQ.data || [];
+ const ids = lists.map((l) => l.id).join('\n');
+ const itemsQ = useLoad(() => (lists.length ? reminders.items(lists.map((l) => l.id)) : Promise.resolve([])), [rev, ids]);
+ const items = itemsQ.data || [];
+ const listOf = (id) => lists.find((l) => l.id === id);
+ const curList = sel.startsWith('list:') ? listOf(sel.slice(5)) : null;
+ useEffect(() => { if (sel.startsWith('list:') && listsQ.data && !curList) setSel('today'); }, [listsQ.data]);
+
+ const counts = useMemo(() => {
+ const c = { today: 0, scheduled: 0, all: 0, flagged: 0, completed: 0, lists: {} };
+ for (const it of items) {
+ if (it.done) { c.completed++; continue; }
+ c.all++;
+ if (it.due != null) c.scheduled++;
+ if (isToday(it, now)) c.today++;
+ if (it.flag) c.flagged++;
+ c.lists[it.list] = (c.lists[it.list] || 0) + 1;
+ }
+ return c;
+ }, [items, now]);
+
+ const newRow = useRef(null);
+ useKeyboard((e) => {
+ if (sheet) { if (e.key === 'Escape') setSheet(null); return; }
+ const k = String(e.base || e.key || '').toLowerCase();
+ if ((e.meta || e.ctrl) && k === 'n') newRow.current?.();
+ });
+
+ const unavailable = listsQ.error && !listsQ.data;
+ const title = curList ? curList.name : t(`reminders.smart.${sel}`);
+ const color = curList ? curList.color || '#007aff' : SMART[sel] || th.text;
+
+ return (
+ <View style={{ flex: 1, flexDirection: 'row', backgroundColor: th.windowBg }}>
+ <Sidebar sel={sel} onSel={setSel} lists={lists} counts={counts} now={now} onAdd={() => setSheet({ newList: true })} onEdit={(l) => setSheet({ list: l })} />
+ <View style={{ flex: 1 }}>
+ <Toolbar separator={false}>
+ <ToolbarSpacer />
+ {sel !== 'completed' ? (
+ <ToolbarButton label={showDone ? t('reminders.hideCompleted') : t('reminders.showCompleted')} small onClick={() => setShowDone(!showDone)} active={showDone} />
+ ) : null}
+ <ToolbarButton icon="+" iconSize={20} title={t('reminders.newReminder')} disabled={unavailable || sel === 'completed'} onClick={() => newRow.current?.()} />
+ </Toolbar>
+ {unavailable ? (
+ <EmptyState icon="☑" title={t('reminders.unavailable')} hint={t('reminders.unavailableHint')} />
+ ) : (
+ <ListView key={sel} sel={sel} title={title} color={color} items={items} lists={lists} now={now} showDone={showDone || sel === 'completed'}
+ newRowRef={newRow} loading={!itemsQ.data} />
+ )}
+ </View>
+ {sheet ? <ListSheet list={sheet.list} onClose={() => setSheet(null)} onCreated={(id) => setSel(`list:${id}`)} /> : null}
+ <Layers />
+ </View>
+ );
+}
+
+// ---- sidebar: smart tiles and my lists ----
+
+function Sidebar({ sel, onSel, lists, counts, now, onAdd, onEdit }) {
+ const th = useTheme();
+ const tiles = ['today', 'scheduled', 'all', 'flagged', 'completed'];
+ const glyph = { today: String(new Date(now).getDate()), scheduled: '▦', all: '☰', flagged: '⚑', completed: '✓' };
+ return (
+ <View style={{ width: 236, backgroundColor: th.sidebarBg }}>
+ <Hairline edge="end" />
+ <ScrollView style={{ flex: 1 }}>
+ <View style={{ padding: 10, gap: 4 }}>
+ <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>
+ {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}
+ </View>
+ </ScrollView>
+ <View style={{ padding: 8 }}>
+ <Hairline edge="top" />
+ <Button small plain icon="⊕" label={t('reminders.addList')} onClick={onAdd} style={{ alignSelf: 'flex-start' }} />
+ </View>
+ </View>
+ );
+}
+
+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 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>
+ <View style={{ flex: 1 }} />
+ {count != null ? <Text style={{ fontSize: 19, 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>
+ );
+}
+
+function ListRow({ list, count, selected, onClick, onEdit }) {
+ const th = useTheme();
+ const ref = useRef(null);
+ const [menu, setMenu] = useState(false);
+ 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,
+ 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>
+ <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>
+ {menu && (
+ <Popover anchor={ref} width={200} onClose={() => setMenu(false)}>
+ <MenuList onDone={() => setMenu(false)} items={[
+ { label: t('reminders.editList'), onClick: () => onEdit(list) },
+ '-',
+ { label: t('reminders.deleteList'), destructive: true, disabled: list.kind !== 'local', onClick: () => calendars.remove(list.id).catch(() => {}) },
+ ]} />
+ </Popover>
+ )}
+ </View>
+ );
+}
+
+// ---- the list of reminders ----
+
+function sortItems(sel, list) {
+ const open = list.filter((x) => !x.done), done = list.filter((x) => x.done);
+ if (!sel.startsWith('list:')) open.sort((a, b) => (a.due ?? Infinity) - (b.due ?? Infinity));
+ done.sort((a, b) => (b.doneAt || 0) - (a.doneAt || 0));
+ // subtasks right after their parent
+ const out = [], byParent = new Map(), uids = new Set(open.map((x) => x.uid));
+ for (const x of open) if (x.parent && uids.has(x.parent)) { if (!byParent.has(x.parent)) byParent.set(x.parent, []); byParent.get(x.parent).push(x); }
+ for (const x of open) {
+ if (x.parent && uids.has(x.parent)) continue;
+ out.push({ it: x, depth: 0 });
+ for (const c of byParent.get(x.uid) || []) out.push({ it: c, depth: 1 });
+ }
+ for (const x of done) out.push({ it: x, depth: 0 });
+ return out;
+}
+
+function ListView({ sel, title, color, items, lists, now, showDone, newRowRef, loading }) {
+ const th = useTheme();
+ const shown = items.filter((it) => matches(sel, it, now) && (showDone || !it.done));
+ const openCount = shown.filter((x) => !x.done).length;
+ const smart = !sel.startsWith('list:');
+ const listOf = (id) => lists.find((l) => l.id === id);
+ // sections: All → by list; Scheduled → by day; others → one section
+ let sections;
+ if (sel === 'all') sections = lists.map((l) => ({ key: l.id, title: l.name, color: l.color, rows: sortItems(sel, shown.filter((x) => x.list === l.id)) })).filter((s) => s.rows.length);
+ else if (sel === 'scheduled') {
+ const m = new Map();
+ for (const x of shown) { const k = dueDay(x); if (!m.has(k)) m.set(k, []); m.get(k).push(x); }
+ const today = ymd(new Date(now));
+ sections = [...m.keys()].sort().map((k) => ({ key: k, title: k < today ? t('reminders.overdue') : k === today ? t('reminders.smart.today') : formatDate(parseYmd(k), 'long'),
+ color: k < today ? RED : th.text, rows: sortItems(sel, m.get(k)) }));
+ // merge the overdue days into one section
+ const od = sections.filter((s) => s.key < today);
+ if (od.length > 1) sections = [{ key: 'overdue', title: od[0].title, color: RED, rows: od.flatMap((s) => s.rows) }, ...sections.filter((s) => s.key >= today)];
+ } else sections = [{ key: 'one', title: null, rows: sortItems(sel, shown) }];
+
+ const target = sel.startsWith('list:') ? listOf(sel.slice(5)) : lists[0];
+ const 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>
+ <ScrollView style={{ flex: 1 }}>
+ <View style={{ paddingHorizontal: 14, 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}
+ {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 && sel !== 'all' && !sel.startsWith('list:') ? (
+ <Text style={{ fontSize: 13, color: th.textDim, marginHorizontal: 10, marginVertical: 6 }}>{t('reminders.empty')}</Text>
+ ) : null}
+ {canAdd ? <NewRow sel={sel} target={target} color={target?.color || color} registerFocus={newRowRef} /> : null}
+ </View>
+ </ScrollView>
+ </View>
+ );
+}
+
+function Circle({ done, color, onClick, size = 20 }) {
+ 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}
+ </View>
+ );
+}
+
+function ReminderRow({ item, depth, color, lists, now, listName }) {
+ const th = useTheme();
+ const row = useRef(null), info = useRef(null);
+ const [done, setDone] = useState(item.done);
+ const [editing, setEditing] = useState(null); // the title being typed
+ const [hover, setHover] = useState(false);
+ const [inspect, setInspect] = useState(false);
+ useEffect(() => setDone(item.done), [item.done]);
+ const latest = useRef();
+ latest.current = { editing, item };
+ const commit = () => {
+ const { editing: v, item: it } = latest.current;
+ setEditing(null);
+ if (v != null && v.trim() && v !== it.title) reminders.save(it.list, { ...it, title: v.trim() }).catch(() => {});
+ };
+ // a click outside the row ends editing
+ useEffect(() => {
+ if (editing == null) return undefined;
+ return addListener('pointerdown', (e) => {
+ if (!row.current) return;
+ const [x, y, w, h] = lord.getLayout(row.current.id);
+ if (e.x < x || e.x > x + w || e.y < y || e.y > y + h) commit();
+ });
+ }, [editing != null]);
+ const toggle = () => { setDone(!done); reminders.toggle(item).catch(() => setDone(item.done)); };
+ const overdue = isOverdue(item, now);
+ const marks = prioMarks(item.prio);
+ const due = dueText(item);
+ const sub = [due, listName].filter(Boolean);
+ 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 }}>
+ <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>
+ </View>
+ )}
+ {item.notes ? <Text style={{ fontSize: 12, color: th.textDim, whiteSpace: 'nowrap', overflow: 'hidden' }}>{item.notes.split('\n')[0]}</Text> : null}
+ {sub.length ? (
+ <View style={{ flexDirection: 'row', gap: 6 }}>
+ {due ? <Text style={{ fontSize: 12, color: overdue ? RED : th.textDim }}>{due}</Text> : null}
+ {listName ? <Text style={{ fontSize: 12, color: th.textDim }}>{listName}</Text> : null}
+ </View>
+ ) : null}
+ </View>
+ {item.flag ? <Text style={{ fontSize: 14, 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} />
+ {inspect ? <Inspector item={item} lists={lists} anchor={info} onClose={() => setInspect(false)} /> : null}
+ </View>
+ );
+}
+
+// ---- details popover ----
+
+function Inspector({ item, lists, anchor, onClose }) {
+ const th = useTheme();
+ const initDay = item.due != null ? (item.dueAllDay ? parseYmd(item.dueDate) || sod(item.due) : sod(item.due)) : sod(Date.now());
+ const [d, setD] = useState({
+ title: item.title || '', notes: item.notes || '', prio: item.prio || 0, flag: !!item.flag, list: item.list,
+ mode: item.due == null ? 'none' : item.dueAllDay ? 'date' : 'time', day: initDay,
+ min: item.due != null && !item.dueAllDay ? minutesOf(new Date(item.due)) : 9 * 60,
+ });
+ const set = (p) => setD((x) => ({ ...x, ...p }));
+ const save = async () => {
+ const todo = { ...item, title: d.title.trim() || item.title, notes: d.notes, prio: d.prio, flag: d.flag };
+ if (d.mode === 'none') { todo.due = null; todo.dueAllDay = false; todo.alarms = []; }
+ else if (d.mode === 'date') { todo.due = sod(d.day).getTime(); todo.dueAllDay = true; todo.alarms = []; }
+ else { todo.due = atMinutes(d.day, d.min).getTime(); todo.dueAllDay = false; todo.alarms = item.alarms && item.alarms.length ? item.alarms : [0]; }
+ delete todo.dueDate;
+ onClose();
+ try { await reminders.save(d.list, todo, d.list !== item.list ? { from: item.list } : {}); } catch (e) { /* stays as it was */ }
+ };
+ const del = () => { onClose(); reminders.remove(item.list, item.uid).catch(() => {}); };
+ return (
+ <Popover anchor={anchor} width={340} padding={12} onClose={save}>
+ <View style={{ gap: 9 }}>
+ <TextInput value={d.title} onChange={(v) => set({ title: v })} size={15} onSubmit={save} />
+ <TextArea value={d.notes} onChange={(v) => set({ notes: v })} placeholder={t('reminders.notes')} minHeight={48} />
+ <Field width={70} label={t('reminders.due')}>
+ <Segmented small value={d.mode} onChange={(v) => set({ mode: v })}
+ options={[['none', t('reminders.dueNone')], ['date', t('reminders.dueDate')], ['time', t('reminders.dueTime')]]} />
+ </Field>
+ {d.mode !== 'none' ? (
+ <Field width={70} label="">
+ <DateField value={d.day} onChange={(v) => set({ day: sod(v) })} width={110} />
+ {d.mode === 'time' ? <TimeField value={d.min} onChange={(v) => set({ min: v })} width={96} /> : null}
+ </Field>
+ ) : null}
+ <Field width={70} label={t('reminders.priority')}>
+ <Choice width={150} value={d.prio >= 6 ? 9 : d.prio >= 2 ? 5 : d.prio} onChange={(v) => set({ prio: v })}
+ options={[[0, t('reminders.prio.none')], [9, t('reminders.prio.low')], [5, t('reminders.prio.medium')], [1, t('reminders.prio.high')]]} />
+ </Field>
+ <Field width={70} label={t('reminders.flagged')}><Toggle on={d.flag} onChange={(v) => set({ flag: v })} /></Field>
+ <Field width={70} label={t('reminders.list')}>
+ <Choice width={180} value={d.list} onChange={(v) => set({ list: v })} options={lists.map((l) => [l.id, l.name, l.color])} />
+ </Field>
+ <View style={{ flexDirection: 'row', gap: 8, marginTop: 4 }}>
+ <Button small destructive label={t('reminders.delete')} onClick={del} />
+ <View style={{ flex: 1 }} />
+ <Button small primary label={t('reminders.done')} onClick={save} />
+ </View>
+ <Text style={{ fontSize: 10, color: th.textDim }}>{item.doneAt ? t('reminders.completedOn', { date: formatDate(new Date(item.doneAt), 'short') }) : ''}</Text>
+ </View>
+ </Popover>
+ );
+}
+
+// ---- "New Reminder" row ----
+
+function NewRow({ sel, target, color, registerFocus }) {
+ const th = useTheme();
+ const [text, setText] = useState('');
+ const [active, setActive] = useState(false);
+ const [error, setError] = useState('');
+ registerFocus.current = () => setActive(true);
+ const add = async (v) => {
+ const title = String(v || '').trim();
+ if (!title) { setActive(false); return; }
+ setText('');
+ try {
+ let list = target ? target.id : null;
+ if (!list) list = (await calendars.create({ name: t('reminders.defaultList'), color: COLORS[5], todos: true, events: false })).uid;
+ const todo = { title, notes: '', prio: 0, flag: sel === 'flagged', done: false, alarms: [], due: null, dueAllDay: false };
+ if (sel === 'today' || sel === 'scheduled') { todo.due = sod(Date.now()).getTime(); todo.dueAllDay = true; }
+ await reminders.save(list, todo);
+ setError('');
+ } 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>
+ {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>
+ )}
+ {error ? <Text style={{ fontSize: 12, color: RED }}>{error}</Text> : null}
+ </View>
+ );
+}
+
+// ---- new list / edit list ----
+
+function ListSheet({ list, onClose, onCreated }) {
+ const th = useTheme();
+ const [name, setName] = useState(list ? list.name : '');
+ const [color, setColor] = useState(list ? list.color : COLORS[5]);
+ const [error, setError] = useState('');
+ const save = async () => {
+ if (!name.trim()) return;
+ try {
+ if (list) await calendars.update(list.id, { name: name.trim(), color });
+ else { const r = await calendars.create({ name: name.trim(), color, todos: true, events: false }); if (r && r.uid) onCreated(r.uid); }
+ onClose();
+ } catch (e) { setError(t('reminders.saveFailed')); }
+ };
+ return (
+ <Sheet width={380} title={list ? t('reminders.editList') : t('reminders.newList')} footer={[
+ <Text key="e" style={{ flex: 1, fontSize: 12, color: RED }}>{error}</Text>,
+ <Button key="c" label={t('reminders.cancel')} onClick={onClose} />,
+ <Button key="s" primary disabled={!name.trim()} label={list ? t('reminders.save') : t('reminders.create')} onClick={save} />,
+ ]}>
+ <View style={{ alignItems: 'center', marginVertical: 4 }}>
+ <View style={{ width: 56, height: 56, borderRadius: 28, alignItems: 'center', justifyContent: 'center', backgroundColor: color }}>
+ <Text style={{ fontSize: 26, color: '#fff' }}>☰</Text>
+ </View>
+ </View>
+ <TextInput value={name} onChange={setName} placeholder={t('reminders.listName')} autoFocus onSubmit={save} onCancel={onClose} />
+ <Text style={{ fontSize: 11, fontWeight: 600, color: th.textDim }}>{t('reminders.color')}</Text>
+ <ColorSwatches value={color} onChange={setColor} />
+ </Sheet>
+ );
+}
diff --git a/apps/reminders/manifest.json b/apps/reminders/manifest.json
new file mode 100644
index 0000000..8e437aa
--- /dev/null
+++ b/apps/reminders/manifest.json
@@ -0,0 +1,10 @@
+{
+ "id": "reminders",
+ "name": "Reminders",
+ "description": "To-do lists with due dates, priorities and flags",
+ "size": [860, 580],
+ "minSize": [600, 400],
+ "dock": true,
+ "category": "Office",
+ "permissions": []
+}
diff --git a/apps/reminders/ui.jsx b/apps/reminders/ui.jsx
new file mode 100644
index 0000000..bb79c41
--- /dev/null
+++ b/apps/reminders/ui.jsx
@@ -0,0 +1,354 @@
+// ui.jsx — small widgets shared by Calendar, Contacts and Reminders (each app keeps its own copy,
+// since apps only import from '@lordos/sdk'): popovers drawn above the window, sheets, drop-down
+// choices, a multi-line field, date and time fields with a month picker, and color swatches.
+import {
+ View, Text, useTheme, useStore, createStore, useAppWindow, direction, ScrollView, Button, Hairline, takeTextFocus, releaseTextFocus,
+ weekdayName, formatTime, formatDate, t,
+} from '@lordos/sdk';
+import { useEffect, useRef, useState } from 'react';
+
+export const RED = '#ff3b30';
+export const COLORS = ['#ff3b30', '#ff9500', '#ffcc00', '#34c759', '#30b0c7', '#007aff', '#af52de', '#a2845e'];
+const pad = (n) => String(n).padStart(2, '0');
+
+// ---- dates ----
+
+export const DAY = 86400000;
+export const sod = (d) => { const x = new Date(d); x.setHours(0, 0, 0, 0); return x; };
+export const addDays = (d, n) => { const x = new Date(d); x.setDate(x.getDate() + n); return x; };
+export const addMonths = (d, n) => new Date(d.getFullYear(), d.getMonth() + n, 1);
+export const sameDay = (a, b) => a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();
+export const startOfWeek = (d) => { const x = sod(d); return addDays(x, -((x.getDay() + 6) % 7)); }; // weeks start on Monday
+export const ymd = (d) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
+export const parseYmd = (s) => { const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(s || ''); return m ? new Date(+m[1], +m[2] - 1, +m[3]) : null; };
+export const minutesOf = (d) => d.getHours() * 60 + d.getMinutes();
+export const atMinutes = (day, min) => { const x = sod(day); x.setHours(Math.floor(min / 60), min % 60, 0, 0); return x; };
+export const monthName = (m) => t(`calendar.month.${m}`);
+export const monthYear = (d) => t('calendar.monthYear', { month: monthName(d.getMonth()), year: d.getFullYear() });
+
+// ---- popovers: drawn by <Layers /> (the last child of the app) above everything ----
+
+const layers = createStore([]); // [{ key, win, node }]
+let seq = 0;
+
+export function Popover(props) {
+ const { id: win } = useAppWindow();
+ const key = useRef(null);
+ if (!key.current) key.current = `p${++seq}`;
+ useEffect(() => {
+ const node = <PopBox {...props} />;
+ layers.set((l) => (l.some((x) => x.key === key.current) ? l.map((x) => (x.key === key.current ? { ...x, node } : x)) : [...l, { key: key.current, win, node }]));
+ });
+ useEffect(() => () => layers.set((l) => l.filter((x) => x.key !== key.current)), []);
+ return null;
+}
+
+let origin = null; // the Layers box: [x, y, w, h]
+
+export function Layers() {
+ const { id } = useAppWindow();
+ const all = useStore(layers);
+ const root = useRef(null);
+ const mine = all.filter((x) => x.win === id);
+ if (root.current) { try { origin = lord.getLayout(root.current.id); } catch (e) { /* not laid out yet */ } }
+ return (
+ <>
+ <View ref={root} style={{ position: 'absolute', left: 0, top: 0, right: 0, bottom: 0, pointerEvents: 'none' }} />
+ {mine.map((x) => <View key={x.key} style={{ position: 'absolute', left: 0, top: 0, right: 0, bottom: 0, zIndex: 200 }}>{x.node}</View>)}
+ </>
+ );
+}
+
+function PopBox({ anchor, onClose, width = 240, children, padding = 6 }) {
+ const th = useTheme();
+ const box = useRef(null);
+ const [flip, setFlip] = useState(false);
+ const [, force] = useState(0);
+ const o = origin || [0, 0, 800, 600];
+ let a = null;
+ try { a = anchor?.current ? lord.getLayout(anchor.current.id) : null; } catch (e) { a = null; }
+ useEffect(() => {
+ if (!a) { const id = setTimeout(() => force((v) => v + 1), 16); return () => clearTimeout(id); }
+ if (!box.current) return undefined;
+ const h = lord.getLayout(box.current.id)[3];
+ const below = a[1] - o[1] + a[3] + 4;
+ const want = below + h > o[3] - 6 && a[1] - o[1] - h - 4 > 6;
+ if (want !== flip) setFlip(want);
+ return undefined;
+ });
+ if (!a) return null;
+ const rtl = direction() === 'rtl';
+ const w = Math.min(width, o[2] - 16);
+ let left = rtl ? a[0] - o[0] + a[2] - w : a[0] - o[0];
+ left = Math.max(8, Math.min(o[2] - w - 8, left));
+ const style = { position: 'absolute', left, width: w, padding, borderRadius: 10, backgroundColor: th.mode === 'dark' ? '#2c2c31' : '#ffffff',
+ border: `1px solid ${th.separator}`, boxShadow: '0 12px 32px rgba(0,0,0,0.32)' };
+ if (flip) style.bottom = o[3] - (a[1] - o[1]) + 4; else style.top = a[1] - o[1] + a[3] + 4;
+ return (
+ <>
+ <View onMouseDown={() => onClose?.()} style={{ position: 'absolute', left: 0, top: 0, right: 0, bottom: 0 }} />
+ <View ref={box} style={style}>{children}</View>
+ </>
+ );
+}
+
+// A menu inside a popover: items = [{ label, onClick, checked, destructive, color, disabled } | '-']
+export function MenuList({ items, onDone }) {
+ return items.map((it, i) => (it === '-' ? <Separator key={`s${i}`} /> : <MenuItem key={`${i}${it.label}`} it={it} onDone={onDone} />));
+}
+
+function Separator() {
+ const th = useTheme();
+ return <View style={{ height: 1, marginVertical: 4, marginHorizontal: 6, backgroundColor: th.separator }} />;
+}
+
+function MenuItem({ it, onDone }) {
+ const th = useTheme();
+ const [hover, setHover] = useState(false);
+ const on = hover && !it.disabled;
+ return (
+ <View onClick={() => { if (it.disabled) return; onDone?.(); it.onClick?.(); }} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
+ style={{ height: 26, paddingHorizontal: 8, borderRadius: 5, flexDirection: 'row', alignItems: 'center', gap: 6,
+ backgroundColor: on ? th.accent : 'transparent', opacity: it.disabled ? 0.4 : 1 }}>
+ <Text style={{ width: 12, fontSize: 11, color: on ? '#fff' : th.text }}>{it.checked ? '✓' : ''}</Text>
+ {it.color ? <View style={{ width: 10, height: 10, borderRadius: 5, backgroundColor: it.color }} /> : null}
+ <Text style={{ flex: 1, fontSize: 13, whiteSpace: 'nowrap', overflow: 'hidden', color: on ? '#fff' : it.destructive ? RED : th.text }}>{it.label}</Text>
+ </View>
+ );
+}
+
+// ---- sheet: a modal box centered on the window ----
+
+export function Sheet({ title, onClose, children, footer, width = 440 }) {
+ const th = useTheme();
+ return (
+ <View onMouseDown={(e) => e.stopPropagation?.()} style={{ position: 'absolute', left: 0, top: 0, right: 0, bottom: 0, zIndex: 100,
+ alignItems: 'center', justifyContent: 'center', backgroundColor: 'rgba(0,0,0,0.3)' }}>
+ <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>
+ ) : null}
+ <View style={{ paddingHorizontal: 16, paddingVertical: 10, gap: 10, flexShrink: 1 }}>{children}</View>
+ {footer ? (
+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 8, paddingHorizontal: 16, paddingVertical: 12 }}>
+ <Hairline edge="top" />
+ {footer}
+ </View>
+ ) : null}
+ </View>
+ </View>
+ );
+}
+
+// label | control row for sheets and inspectors
+export function Field({ label, children, width = 86, top }) {
+ const th = useTheme();
+ return (
+ <View style={{ flexDirection: 'row', alignItems: top ? 'flex-start' : 'center', gap: 10, minHeight: 28 }}>
+ <Text style={{ width, fontSize: 12, color: th.textDim, textAlign: 'end', marginTop: top ? 6 : 0 }}>{label}</Text>
+ <View style={{ flex: 1, flexDirection: 'row', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>{children}</View>
+ </View>
+ );
+}
+
+// ---- drop-down choice: options = [[value, label, color?]] ----
+
+export function Choice({ value, options, onChange, width = 180, height }) {
+ const th = useTheme();
+ const ref = useRef(null);
+ const scroll = useRef(null);
+ const [open, setOpen] = useState(false);
+ const cur = options.find((o) => o[0] === value);
+ const long = height || options.length > 12;
+ useEffect(() => {
+ if (!open || !long) return undefined;
+ const i = options.findIndex((o) => o[0] === value);
+ const id = setTimeout(() => scroll.current?.scrollTo(Math.max(0, i * 26 - 100)), 40);
+ return () => clearTimeout(id);
+ }, [open]);
+ const list = options.map(([v, label, color]) => ({ label, color, checked: v === value, onClick: () => onChange(v) }));
+ return (
+ <View ref={ref} style={{ width }}>
+ <View onClick={() => setOpen(!open)} style={{ height: 26, paddingHorizontal: 9, borderRadius: 6, flexDirection: 'row', alignItems: 'center', gap: 6,
+ backgroundColor: th.control }}>
+ {cur && cur[2] ? <View style={{ width: 10, height: 10, borderRadius: 5, backgroundColor: cur[2] }} /> : null}
+ <Text style={{ flex: 1, fontSize: 13, color: th.text, whiteSpace: 'nowrap', overflow: 'hidden' }}>{cur ? cur[1] : ''}</Text>
+ <Text style={{ fontSize: 9, color: th.textDim }}>▼</Text>
+ </View>
+ {open && (
+ <Popover anchor={ref} width={Math.max(width, 170)} onClose={() => setOpen(false)}>
+ {long ? (
+ <View style={{ height: height || 260 }}>
+ <ScrollView scrollRef={scroll} style={{ flex: 1 }}><MenuList items={list} onDone={() => setOpen(false)} /></ScrollView>
+ </View>
+ ) : <MenuList items={list} onDone={() => setOpen(false)} />}
+ </Popover>
+ )}
+ </View>
+ );
+}
+
+// ---- multi-line text field ----
+
+export function TextArea({ value, onChange, placeholder, minHeight = 64 }) {
+ const th = useTheme();
+ const token = useRef({}).current;
+ const [focus, setFocus] = useState(false);
+ const [blink, setBlink] = useState(true);
+ const latest = useRef();
+ latest.current = { value: value || '', onChange };
+ useEffect(() => () => releaseTextFocus(token), []);
+ useEffect(() => {
+ if (!focus) return undefined;
+ const id = setInterval(() => setBlink((b) => !b), 530);
+ return () => clearInterval(id);
+ }, [focus]);
+ const onKey = (e) => {
+ const { value: v, onChange: set } = latest.current;
+ if ((e.ctrl || e.meta) && e.base === 'v') { try { set(v + lord.clipboard.get()); } catch (err) { /* no clipboard */ } return; }
+ if (e.key === 'Backspace') set([...v].slice(0, -1).join(''));
+ else if (e.key === 'Enter') set(`${v}\n`);
+ else if (e.key === 'Escape') { releaseTextFocus(token); setFocus(false); }
+ else if (e.char && !e.ctrl && !e.meta) set(v + e.char);
+ setBlink(true);
+ };
+ const caret = focus && blink ? '▏' : '';
+ return (
+ <View onMouseDown={() => { takeTextFocus(token, onKey, () => setFocus(false)); setFocus(true); }}
+ style={{ flex: 1, minHeight, padding: 7, borderRadius: 7, backgroundColor: th.inputBg, border: `1px solid ${focus ? th.accent : th.separator}` }}>
+ {value ? <Text style={{ fontSize: 13, color: th.text, lineHeight: 18 }}>{`${value}${caret}`}</Text>
+ : <Text style={{ fontSize: 13, color: th.textDim }}>{focus ? caret || ' ' : placeholder || ''}</Text>}
+ </View>
+ );
+}
+
+// ---- month grid picker ----
+
+export function MiniMonth({ value, onPick, marks, month: ctlMonth, onMonth, cell = 26, today = new Date() }) {
+ const th = useTheme();
+ const [own, setOwn] = useState(() => new Date((value || today).getFullYear(), (value || today).getMonth(), 1));
+ const month = ctlMonth || own;
+ const setMonth = (m) => (onMonth ? onMonth(m) : setOwn(m));
+ const rtl = direction() === 'rtl';
+ const first = startOfWeek(month);
+ const rows = [];
+ for (let r = 0; r < 6; r++) {
+ const cells = [];
+ for (let c = 0; c < 7; c++) {
+ const d = addDays(first, r * 7 + c);
+ const sel = value && sameDay(d, value), isToday = sameDay(d, today), inMonth = d.getMonth() === month.getMonth();
+ cells.push(
+ <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,
+ 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}
+ </View>,
+ );
+ }
+ rows.push(<View key={r} style={{ flexDirection: 'row' }}>{cells}</View>);
+ }
+ return (
+ <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>
+ <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))} />
+ </View>
+ <View style={{ flexDirection: 'row' }}>
+ {[1, 2, 3, 4, 5, 6, 0].map((wd) => (
+ <Text key={wd} style={{ width: cell, textAlign: 'center', fontSize: 10, fontWeight: 600, color: th.textDim }}>{[...weekdayName(wd)][0] || ''}</Text>
+ ))}
+ </View>
+ {rows}
+ </View>
+ );
+}
+
+function NavArrow({ glyph, onClick, small }) {
+ const th = useTheme();
+ const [hover, setHover] = useState(false);
+ return (
+ <View onClick={onClick} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
+ style={{ width: 20, height: 20, borderRadius: 5, alignItems: 'center', justifyContent: 'center', backgroundColor: hover ? th.hover : 'transparent' }}>
+ <Text style={{ fontSize: small ? 7 : 15, color: th.textDim }}>{glyph}</Text>
+ </View>
+ );
+}
+
+// ---- date and time fields ----
+
+export function DateField({ value, onChange, width = 120 }) {
+ const th = useTheme();
+ const ref = useRef(null);
+ const [open, setOpen] = useState(false);
+ return (
+ <View ref={ref}>
+ <View onClick={() => setOpen(!open)} style={{ width, height: 26, paddingHorizontal: 9, borderRadius: 6, justifyContent: 'center', backgroundColor: th.control }}>
+ <Text style={{ fontSize: 13, color: th.text, whiteSpace: 'nowrap' }}>{value ? formatDate(value, 'numeric') : ''}</Text>
+ </View>
+ {open && (
+ <Popover anchor={ref} width={7 * 28 + 16} padding={8} onClose={() => setOpen(false)}>
+ <MiniMonth value={value} cell={28} onPick={(d) => { setOpen(false); onChange(d); }} />
+ </Popover>
+ )}
+ </View>
+ );
+}
+
+// minutes since midnight, every 15 minutes (and the current value if it is not on the grid)
+export function TimeField({ value, onChange, width = 100 }) {
+ const opts = [];
+ for (let m = 0; m < 1440; m += 15) opts.push(m);
+ if (!opts.includes(value)) { opts.push(value); opts.sort((a, b) => a - b); }
+ return <Choice width={width} value={value} onChange={onChange} options={opts.map((m) => [m, formatTime(atMinutes(new Date(2000, 0, 3), m))])} />;
+}
+
+// ---- colors ----
+
+export function ColorSwatches({ value, onChange, colors = COLORS }) {
+ const th = useTheme();
+ return (
+ <View style={{ flexDirection: 'row', gap: 8, flexWrap: 'wrap' }}>
+ {colors.map((c) => (
+ <View key={c} onClick={() => onChange(c)} style={{ width: 24, height: 24, borderRadius: 12, alignItems: 'center', justifyContent: 'center',
+ border: `2px solid ${value === c ? th.text : 'transparent'}` }}>
+ <View style={{ width: 18, height: 18, borderRadius: 9, backgroundColor: c }} />
+ </View>
+ ))}
+ </View>
+ );
+}
+
+// square check box filled with a color when on
+export function ColorCheck({ on, color, onClick, size = 14 }) {
+ return (
+ <View onClick={onClick} style={{ width: size, height: size, borderRadius: 4, alignItems: 'center', justifyContent: 'center',
+ border: `1.5px solid ${color}`, backgroundColor: on ? color : 'transparent' }}>
+ {on ? <Text style={{ fontSize: size - 4, fontWeight: 700, color: '#fff' }}>✓</Text> : null}
+ </View>
+ );
+}
+
+// a promise-returning loader that re-runs when deps change: { data, error }
+export function useLoad(fn, deps) {
+ const [st, setSt] = useState({ data: null, error: null });
+ useEffect(() => {
+ let live = true;
+ Promise.resolve().then(fn).then((data) => { if (live) setSt({ data, error: null }); }).catch((error) => { if (live) setSt((s) => ({ data: s.data, error })); });
+ return () => { live = false; };
+ }, deps);
+ return st;
+}
+
+export function useNow(ms = 30000) {
+ const [now, setNow] = useState(Date.now());
+ useEffect(() => { const id = setInterval(() => setNow(Date.now()), ms); return () => clearInterval(id); }, [ms]);
+ return now;
+}
diff --git a/apps/scanner/index.jsx b/apps/scanner/index.jsx
index 9387d40..887dbd1 100644
--- a/apps/scanner/index.jsx
+++ b/apps/scanner/index.jsx
@@ -1,8 +1,9 @@
-// Escáner — escáneres «sin controlador» de la red (eSCL / AirScan) con un cliente propio, sin
-// SANE: vista previa, área a mano, resolución, color o grises, y guardar como PDF, PNG o JPEG.
-// Lo que manda el escáner se decodifica y convierte en el ayudante encerrado lord-doc.
+// Scanner: "driverless" network scanners (eSCL / AirScan) with our own client, without SANE:
+// preview, a hand-drawn area, resolution, color or grayscale, and save as PDF, PNG or JPEG. What
+// the scanner sends is decoded and converted in the sandboxed lord-doc helper.
import {
- View, Text, Button, Segmented, useTheme, useAppWindow, wm, fs, print, DocImage, releaseImage, decodeImage, convertImage, formatDate, formatTime, t as tr,
+ View, Text, Button, Segmented, Hairline, EmptyState, ScrollView, useTheme, useAppWindow, wm, fs, print, DocImage, releaseImage, decodeImage, convertImage,
+ formatDate, formatTime, typeScale, t as tr,
} from '@lordos/sdk';
import { useEffect, useRef, useState } from 'react';
@@ -10,7 +11,7 @@ export function Icon({ size: s }) {
return (
<View style={{ width: s, height: s, borderRadius: s * 0.225, background: 'linear-gradient(160deg, #66d4cf, #0f7c78)',
boxShadow: `0 ${s * 0.04}px ${s * 0.12}px rgba(0,0,0,0.35)`, overflow: 'hidden' }}>
- {/* cama del escáner con la tapa y la luz que pasa */}
+ {/* scanner bed with the lid and the passing light */}
<View style={{ position: 'absolute', left: s * 0.12, top: s * 0.46, width: s * 0.76, height: s * 0.3, borderRadius: s * 0.06, backgroundColor: '#e9f7f6' }} />
<View style={{ position: 'absolute', left: s * 0.12, top: s * 0.3, width: s * 0.76, height: s * 0.12, borderRadius: s * 0.05, backgroundColor: '#cfe9e7' }} />
<View style={{ position: 'absolute', left: s * 0.18, top: s * 0.54, width: s * 0.64, height: s * 0.05, backgroundColor: '#7cf5a0' }} />
@@ -24,7 +25,7 @@ const COLORS = { RGB24: 'color', Grayscale8: 'gray', BlackAndWhite1: 'bw' };
function destDir(kind) {
const home = fs.home();
const names = kind === 'pdf' ? ['Documentos', 'Documents'] : ['Imágenes', 'Pictures', 'Imagens'];
- for (const n of names) { try { if (fs.stat(`${home}/${n}`).dir) return `${home}/${n}`; } catch (e) { /* no está */ } }
+ for (const n of names) { try { if (fs.stat(`${home}/${n}`).dir) return `${home}/${n}`; } catch (e) { /* not there */ } }
return home;
}
@@ -40,7 +41,7 @@ export default function Scanner() {
const [format, setFormat] = useState('pdf');
const [source, setSource] = useState('Platen');
const [preview, setPreview] = useState(null); // { image, w, h }
- const [area, setArea] = useState(null); // [x, y, w, h] en fracciones de la vista previa
+ const [area, setArea] = useState(null); // [x, y, w, h] as fractions of the preview
const [busy, setBusy] = useState(null);
const [msg, setMsg] = useState(null);
const box = useRef(null);
@@ -105,7 +106,7 @@ export default function Scanner() {
};
const lastSaved = useRef(null);
- // área: arrastrar sobre la vista previa
+ // area: drag on the preview
const onDown = (ev) => {
if (!preview || !box.current) return;
const [bx, by, bw, bh] = lord.getLayout(box.current.id);
@@ -122,27 +123,33 @@ export default function Scanner() {
const onUp = () => { const d = drag.current; drag.current = null; if (d && area && (area[2] < 0.02 || area[3] < 0.02)) setArea(null); };
if (!scanner) {
+ if (!found || !found.length) {
+ return <EmptyState icon={<Icon size={56} />} title={tr('scanner.choose')} hint={found == null ? tr('scanner.searching') : tr('scanner.none')} />;
+ }
return (
<View style={{ flex: 1, padding: 20, gap: 12 }}>
- <Text style={{ fontSize: 16, fontWeight: 700, color: th.text }}>{tr('scanner.choose')}</Text>
- {found == null ? <Text style={{ fontSize: 12, color: th.textDim }}>{tr('scanner.searching')}</Text>
- : !found.length ? <Text style={{ fontSize: 12, color: th.textDim }}>{tr('scanner.none')}</Text>
- : found.map((s) => (
- <View key={`${s.addr}:${s.port}`} onClick={() => setScanner(s)} style={{ flexDirection: 'row', gap: 10, padding: 10, borderRadius: 8, backgroundColor: th.control, alignItems: 'center' }}>
- <Icon size={28} />
- <View style={{ flex: 1 }}>
- <Text style={{ fontSize: 13, fontWeight: 600, color: th.text }}>{s.name}</Text>
- <Text style={{ fontSize: 11, color: th.textDim }}>{`${s.model || ''} ${s.addr}:${s.port}`}</Text>
- </View>
+ <Text style={{ fontSize: typeScale.headline, fontWeight: 600, color: th.text }}>{tr('scanner.choose')}</Text>
+ <View style={{ borderRadius: 10, border: `1px solid ${th.separator}`, backgroundColor: th.mode === 'dark' ? 'rgba(255,255,255,0.04)' : 'rgba(0,0,0,0.025)', paddingHorizontal: 12 }}>
+ {found.map((s, i) => (
+ <View key={`${s.addr}:${s.port}`} onClick={() => setScanner(s)} style={{ flexDirection: 'row', gap: 12, paddingVertical: 10, alignItems: 'center' }}>
+ {i > 0 ? <Hairline edge="top" /> : null}
+ <Icon size={32} />
+ <View style={{ flex: 1, minWidth: 0, gap: 2 }}>
+ <Text style={{ fontSize: typeScale.body, fontWeight: 600, color: th.text, whiteSpace: 'nowrap', overflow: 'hidden' }}>{s.name}</Text>
+ <Text style={{ fontSize: typeScale.caption, color: th.textDim, whiteSpace: 'nowrap', overflow: 'hidden' }}>{`${s.model || ''} ${s.addr}:${s.port}`}</Text>
</View>
- ))}
+ <Text style={{ fontSize: 15, color: th.textDim }}>›</Text>
+ </View>
+ ))}
+ </View>
</View>
);
}
const sel = area;
+ const caption = (text) => <Text style={{ fontSize: typeScale.caption, fontWeight: 600, color: th.textDim, marginTop: 6 }}>{text}</Text>;
return (
<View style={{ flex: 1, flexDirection: 'row' }} onMouseMove={onMove} onMouseUp={onUp}>
- <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', padding: 16, backgroundColor: th.mode === 'dark' ? '#2a2a2e' : '#d9d9de' }}>
+ <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', padding: 20, backgroundColor: th.mode === 'dark' ? '#2a2a2e' : '#e3e3e8' }}>
{preview ? (
<View ref={box} onMouseDown={onDown} style={{ width: preview.w, height: preview.h, backgroundColor: '#fff', boxShadow: '0 2px 10px rgba(0,0,0,0.35)', direction: 'ltr' }}>
<DocImage image={preview.image} style={{ width: preview.w, height: preview.h }} />
@@ -151,39 +158,50 @@ export default function Scanner() {
border: `2px solid ${th.accent}`, backgroundColor: `${th.accent}22` }} />
)}
</View>
- ) : <Text style={{ fontSize: 13, color: th.textDim, textAlign: 'center' }}>{busy === 'preview' ? tr('scanner.previewing') : tr('scanner.previewHint')}</Text>}
+ ) : <EmptyState title={busy === 'preview' ? tr('scanner.previewing') : null} hint={busy === 'preview' ? null : tr('scanner.previewHint')} />}
</View>
- <View style={{ width: 280, padding: 14, gap: 10, backgroundColor: th.sidebarBg }}>
- <Text style={{ fontSize: 14, fontWeight: 700, color: th.text }}>{scanner.name}</Text>
- <Text style={{ fontSize: 11, color: th.textDim }}>{caps ? caps.model || `${scanner.addr}:${scanner.port}` : error ? '' : tr('scanner.connecting')}</Text>
- {caps && (
- <>
- {caps.platen && caps.adf ? <Segmented value={source} onChange={setSource} options={[['Platen', tr('scanner.platen')], ['Feeder', tr('scanner.feeder')]]} /> : null}
- <Text style={{ fontSize: 11, fontWeight: 600, color: th.textDim }}>{tr('scanner.mode')}</Text>
- <Segmented value={color} onChange={setColor} options={(caps.colors.length ? caps.colors : ['RGB24']).filter((c) => COLORS[c]).map((c) => [c, tr(`scanner.color.${COLORS[c]}`)])} />
- <Text style={{ fontSize: 11, fontWeight: 600, color: th.textDim }}>{tr('scanner.resolution')}</Text>
- <View style={{ flexDirection: 'row', flexWrap: 'wrap', gap: 4 }}>
- {(caps.res.length ? caps.res : [75, 150, 300, 600]).slice(0, 8).map((r) => (
- <View key={r} onClick={() => setRes(r)} style={{ paddingHorizontal: 8, height: 22, borderRadius: 11, justifyContent: 'center', backgroundColor: res === r ? th.accent : th.control }}>
- <Text style={{ fontSize: 11, color: res === r ? '#fff' : th.text }}>{tr('scanner.dpi', { dpi: r })}</Text>
- </View>
- ))}
+ <View style={{ width: 280, backgroundColor: th.sidebarBg }}>
+ <Hairline edge="start" />
+ <ScrollView style={{ flex: 1, paddingHorizontal: 16, paddingTop: 16 }}>
+ <View style={{ gap: 8, paddingBottom: 12 }}>
+ <View style={{ gap: 2 }}>
+ <Text style={{ fontSize: typeScale.headline, fontWeight: 600, color: th.text }}>{scanner.name}</Text>
+ <Text style={{ fontSize: typeScale.caption, color: th.textDim }}>{caps ? caps.model || `${scanner.addr}:${scanner.port}` : error ? '' : tr('scanner.connecting')}</Text>
</View>
- <Text style={{ fontSize: 11, fontWeight: 600, color: th.textDim }}>{tr('scanner.format')}</Text>
- <Segmented value={format} onChange={setFormat} options={[['pdf', 'PDF'], ['png', 'PNG'], ['jpeg', 'JPEG']]} />
- <Text style={{ fontSize: 11, color: th.textDim }}>{area ? tr('scanner.areaSet', { w: Math.round(region().w / 300 * 25.4), h: Math.round(region().h / 300 * 25.4) }) : tr('scanner.areaAll')}</Text>
- </>
- )}
- {/* las acciones van arriba (no al pie): con el Dock a la vista no quedan tapadas */}
- {error ? <Text style={{ fontSize: 12, color: '#ff453a' }}>{error}</Text> : null}
- {msg ? <Text style={{ fontSize: 12, color: th.accent }}>{msg}</Text> : null}
- <View style={{ flexDirection: 'row', gap: 8, justifyContent: 'flex-end', flexWrap: 'wrap' }}>
- {lastSaved.current && format !== 'pdf' ? <Button label={tr('scanner.print')} onClick={() => print.open({ title: fs.basename(lastSaved.current), image: lastSaved.current })} /> : null}
- <Button label={busy === 'preview' ? tr('scanner.working') : tr('scanner.preview')} onClick={() => !busy && caps && doPreview()} />
- <Button primary label={busy === 'scan' ? tr('scanner.working') : tr('scanner.scan')} onClick={() => !busy && caps && doScan()} />
+ {caps && (
+ <>
+ {caps.platen && caps.adf ? <Segmented fill value={source} onChange={setSource} options={[['Platen', tr('scanner.platen')], ['Feeder', tr('scanner.feeder')]]} /> : null}
+ {caption(tr('scanner.mode'))}
+ <Segmented fill value={color} onChange={setColor} options={(caps.colors.length ? caps.colors : ['RGB24']).filter((c) => COLORS[c]).map((c) => [c, tr(`scanner.color.${COLORS[c]}`)])} />
+ {caption(tr('scanner.resolution'))}
+ <View style={{ flexDirection: 'row', flexWrap: 'wrap', gap: 6 }}>
+ {(caps.res.length ? caps.res : [75, 150, 300, 600]).slice(0, 8).map((r) => (
+ <View key={r} onClick={() => setRes(r)} style={{ paddingHorizontal: 10, height: 24, borderRadius: 12, justifyContent: 'center', backgroundColor: res === r ? th.accent : th.control }}>
+ <Text style={{ fontSize: typeScale.callout, color: res === r ? '#fff' : th.text }}>{tr('scanner.dpi', { dpi: r })}</Text>
+ </View>
+ ))}
+ </View>
+ {caption(tr('scanner.format'))}
+ <Segmented fill value={format} onChange={setFormat} options={[['pdf', 'PDF'], ['png', 'PNG'], ['jpeg', 'JPEG']]} />
+ <Text style={{ fontSize: typeScale.caption, color: th.textDim, lineHeight: 1.4, marginTop: 4 }}>{area ? tr('scanner.areaSet', { w: Math.round(region().w / 300 * 25.4), h: Math.round(region().h / 300 * 25.4) }) : tr('scanner.areaAll')}</Text>
+ </>
+ )}
+ {error ? <Text style={{ fontSize: typeScale.callout, color: '#ff453a', lineHeight: 1.4 }}>{error}</Text> : null}
+ {msg ? <Text style={{ fontSize: typeScale.callout, color: th.accent, lineHeight: 1.4 }}>{msg}</Text> : null}
+ </View>
+ </ScrollView>
+ {/* the actions sit in a fixed footer of the panel, above the Dock */}
+ <View style={{ paddingHorizontal: 16, paddingTop: 12, paddingBottom: 16, gap: 10 }}>
+ <Hairline edge="top" />
+ <View style={{ flexDirection: 'row', gap: 8, justifyContent: 'flex-end', flexWrap: 'wrap' }}>
+ {lastSaved.current && format !== 'pdf' ? <Button label={tr('scanner.print')} onClick={() => print.open({ title: fs.basename(lastSaved.current), image: lastSaved.current })} /> : null}
+ <Button label={busy === 'preview' ? tr('scanner.working') : tr('scanner.preview')} onClick={() => !busy && caps && doPreview()} />
+ <Button primary label={busy === 'scan' ? tr('scanner.working') : tr('scanner.scan')} onClick={() => !busy && caps && doScan()} />
+ </View>
+ <View onClick={() => { setScanner(null); setCaps(null); setPreview(null); }} style={{ alignSelf: 'flex-start' }}>
+ <Text style={{ fontSize: typeScale.callout, color: th.accent }}>{tr('scanner.other')}</Text>
+ </View>
</View>
- <View onClick={() => { setScanner(null); setCaps(null); setPreview(null); }}><Text style={{ fontSize: 11, color: th.accent }}>{tr('scanner.other')}</Text></View>
- <View style={{ flex: 1 }} />
</View>
</View>
);
diff --git a/apps/screenshots/index.jsx b/apps/screenshots/index.jsx
index b69bf62..46e9979 100644
--- a/apps/screenshots/index.jsx
+++ b/apps/screenshots/index.jsx
@@ -1,14 +1,15 @@
-// Capturas — capturas de pantalla y grabación de la pantalla (al estilo del panel de capturas de
-// macOS, con diseño propio).
+// Screenshots: screen captures and screen recording (in the style of the macOS screenshot panel,
+// with our own design).
//
-// Atajos (globales, también con una app Linux al frente):
-// ❖⇧3 / Impr Pant pantalla completa ❖⇧4 área (o ventana, con Espacio)
-// ❖⇧5 el panel de Capturas (y detener una grabación en curso)
-// Las ventanas protegidas (wm.setProtected) salen negras: lo hace el servidor, no esta app.
-// Después de cada captura aparece una miniatura flotante; un clic abre el editor de anotaciones
-// (flecha, recuadro, texto, desenfoque). Se guardan en ~/Imágenes/Capturas o al portapapeles.
+// Shortcuts (global, also with a Linux app in front):
+// ❖⇧3 / Print Screen entire screen ❖⇧4 area (or window, with Space)
+// ❖⇧5 the Screenshots panel (and stop a recording in progress)
+// Protected windows (wm.setProtected) come out black: the server does that, not this app.
+// After each capture a floating thumbnail shows up; a click opens the markup editor (arrow, box,
+// text, blur). They are saved in ~/Pictures/Screenshots or to the clipboard.
import {
- View, Text, MediaView, Button, Toggle, Segmented, TextInput, useTheme, useAppWindow, useKeyboard, useStore, useWindows, wm, windows,
+ View, Text, MediaView, Button, Toggle, Segmented, TextInput, Toolbar, ToolbarButton, ToolbarGroup, ToolbarDivider, ToolbarSpacer, GroupBox, FormRow,
+ useTheme, useAppWindow, useKeyboard, useStore, useWindows, wm, windows, typeScale,
t as tr, media, userDirs, fs, addListener, createStore, windowTitle, settings, useSettings,
} from '@lordos/sdk';
import { useEffect, useRef, useState } from 'react';
@@ -22,7 +23,7 @@ export function Icon({ size: s }) {
return (
<View style={{ width: s, height: s, borderRadius: s * 0.225, background: 'linear-gradient(160deg, #5e6b7a, #2c333d)',
boxShadow: `0 ${s * 0.04}px ${s * 0.12}px rgba(0,0,0,0.35)`, overflow: 'hidden' }}>
- {/* el recuadro de selección: cuatro esquinas y un lente */}
+ {/* the selection frame: four corners and a lens */}
{corner(0.18, 0.2, 0.18, 0.05)}{corner(0.18, 0.2, 0.05, 0.18)}
{corner(0.64, 0.2, 0.18, 0.05)}{corner(0.77, 0.2, 0.05, 0.18)}
{corner(0.18, 0.75, 0.18, 0.05)}{corner(0.18, 0.62, 0.05, 0.18)}
@@ -34,7 +35,7 @@ export function Icon({ size: s }) {
);
}
-// ---- archivos ----
+// ---- files ----
const pad = (n) => String(n).padStart(2, '0');
function stamp() {
@@ -43,8 +44,8 @@ function stamp() {
}
function captureDir() {
const dir = `${userDirs().pictures}/${tr('screenshots.folder')}`;
- try { fs.mkdir(userDirs().pictures); } catch (e) { /* ya está */ }
- try { fs.mkdir(dir); } catch (e) { /* ya está */ }
+ try { fs.mkdir(userDirs().pictures); } catch (e) { /* already there */ }
+ try { fs.mkdir(dir); } catch (e) { /* already there */ }
return dir;
}
function freeName(dir, base, ext) {
@@ -56,7 +57,7 @@ function freeName(dir, base, ext) {
}
const opts = () => ({ timer: 0, clipboard: false, mic: false, ...(settings.get().screenshots || {}) });
-// ---- capturar ----
+// ---- capture ----
async function finish(handle) {
if (!handle) return;
@@ -76,7 +77,7 @@ function showThumb(handle, path) {
wm.setPip(id, { x: lord.screen.width - w - 20, y: lord.screen.height - h - 90, w, h });
}
-// toma la pantalla después de que se dibuje un cuadro sin nuestras ventanas (las cierra antes)
+// takes the screen once a frame without our windows was drawn (it closes them first)
function afterHide(fn, delay = 160) {
for (const w of windows.get()) if (w.app === APP && w.id !== `${APP}#edit` && !String(w.id).startsWith(`${APP}#edit`)) wm.close(w.id, true);
setTimeout(fn, delay);
@@ -121,7 +122,7 @@ export const capture = {
},
};
-// atajos globales (evdev: 3 = KEY_2+1… KEY_3 = 4, KEY_4 = 5, KEY_5 = 6; Impr Pant = 99)
+// global shortcuts (evdev: KEY_3 = 4, KEY_4 = 5, KEY_5 = 6; Print Screen = 99)
addListener('keydown', (e) => {
if (e.repeat || typeof lord === 'undefined' || !lord.media) return;
if (e.code === 99 && !e.meta) { capture.full(); return; }
@@ -131,7 +132,7 @@ addListener('keydown', (e) => {
else if (e.code === 6) { if (recording.get()) capture.record(); else wm.open(APP); }
});
-// ---- ventanas de la app ----
+// ---- the app's windows ----
function Overlay({ handle, mode: initial }) {
const win = useAppWindow();
@@ -155,7 +156,7 @@ function Overlay({ handle, mode: initial }) {
useEffect(() => {
const offMove = addListener('pointermove', (e) => {
if (drag.current) { const d = drag.current; setRect({ x: Math.min(d.x, e.x), y: Math.min(d.y, e.y), w: Math.abs(e.x - d.x), h: Math.abs(e.y - d.y) }); return; }
- // ventana bajo el puntero (la de más arriba)
+ // window under the pointer (the topmost one)
const vis = list.filter((w) => !w.minimized && w.app !== APP);
let found = null;
for (const w of vis) { const f = wm.frame(w); if (e.x >= f.x && e.y >= f.y && e.x < f.x + f.w && e.y < f.y + f.h) found = { ...f, title: windowTitle(w) }; }
@@ -188,7 +189,7 @@ function Overlay({ handle, mode: initial }) {
</>
) : <View style={{ position: 'absolute', left: 0, top: 0, right: 0, bottom: 0, backgroundColor: dim }} />}
<View style={{ position: 'absolute', left: 0, right: 0, top: 18, alignItems: 'center', pointerEvents: 'none' }}>
- <View style={{ paddingHorizontal: 14, paddingVertical: 6, borderRadius: 8, backgroundColor: 'rgba(0,0,0,0.7)' }}>
+ <View style={{ paddingHorizontal: 14, height: 30, justifyContent: 'center', borderRadius: 15, backgroundColor: 'rgba(0,0,0,0.7)' }}>
<Text style={{ fontSize: 12, color: '#fff' }}>{tr(mode === 'window' ? 'screenshots.hintWindow' : 'screenshots.hintArea')}</Text>
</View>
</View>
@@ -213,8 +214,8 @@ function Thumb({ handle, path }) {
setTimeout(() => wm.close(win.id, true), 50);
}}>
<MediaView media={handle} style={{ flex: 1 }} />
- <View style={{ position: 'absolute', left: 0, right: 0, bottom: 0, paddingHorizontal: 8, paddingVertical: 4, backgroundColor: 'rgba(0,0,0,0.55)' }}>
- <Text style={{ fontSize: 10, color: '#fff' }}>{path ? tr('screenshots.savedTo', { folder: tr('screenshots.folder') }) : tr('screenshots.copied')}</Text>
+ <View style={{ position: 'absolute', left: 0, right: 0, bottom: 0, paddingHorizontal: 10, paddingVertical: 5, backgroundColor: 'rgba(0,0,0,0.55)' }}>
+ <Text style={{ fontSize: 11, color: '#fff' }}>{path ? tr('screenshots.savedTo', { folder: tr('screenshots.folder') }) : tr('screenshots.copied')}</Text>
</View>
</View>
);
@@ -226,7 +227,7 @@ function Countdown({ secs, start }) {
const left = Math.max(0, Math.ceil(secs - (now - start) / 1000));
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor: 'rgba(20,20,24,0.85)' }}>
- <Text style={{ fontSize: 54, fontWeight: 700, color: '#fff' }}>{left}</Text>
+ <Text style={{ fontSize: 56, fontWeight: 600, color: '#fff' }}>{left}</Text>
</View>
);
}
@@ -238,16 +239,16 @@ function RecBadge() {
const secs = rec ? Math.floor((now - rec.start) / 1000) : 0;
return (
<View style={{ flex: 1, flexDirection: 'row', alignItems: 'center', gap: 10, paddingHorizontal: 12, backgroundColor: 'rgba(30,30,34,0.92)' }}>
- <View style={{ width: 10, height: 10, borderRadius: 5, backgroundColor: '#ff3b30' }} />
- <Text style={{ fontSize: 13, color: '#fff', flex: 1 }}>{`${Math.floor(secs / 60)}:${pad(secs % 60)}`}</Text>
- <View onClick={() => capture.record()} style={{ paddingHorizontal: 10, height: 24, borderRadius: 6, justifyContent: 'center', backgroundColor: '#ff3b30' }}>
+ <View style={{ width: 9, height: 9, borderRadius: 5, backgroundColor: '#ff3b30' }} />
+ <Text style={{ fontSize: 13, fontWeight: 500, color: '#fff', flex: 1, direction: 'ltr' }}>{`${Math.floor(secs / 60)}:${pad(secs % 60)}`}</Text>
+ <View onClick={() => capture.record()} style={{ paddingHorizontal: 12, height: 24, borderRadius: 6, justifyContent: 'center', backgroundColor: '#ff3b30' }}>
<Text style={{ fontSize: 12, fontWeight: 600, color: '#fff' }}>{tr('screenshots.stop')}</Text>
</View>
</View>
);
}
-// ---- editor de anotaciones ----
+// ---- markup editor ----
const COLORS = ['#ff3b30', '#ffcc00', '#34c759', '#0a84ff', '#ffffff', '#1c1c1e'];
@@ -258,7 +259,7 @@ function Editor({ handle, path }) {
const [color, setColor] = useState(COLORS[0]);
const [ops, setOps] = useState([]);
const [draft, setDraft] = useState(null);
- const [text, setText] = useState(null); // { x, y, value } (coordenadas de la imagen)
+ const [text, setText] = useState(null); // { x, y, value } (image coordinates)
const [preview, setPreview] = useState(0);
const [msg, setMsg] = useState(null);
const box = useRef(null);
@@ -310,28 +311,31 @@ function Editor({ handle, path }) {
setTimeout(() => setMsg(null), 2500);
};
const copy = async () => { const r = await media.copyImage(preview || handle); setMsg(r.ok ? tr('screenshots.copied') : tr('screenshots.saveError')); setTimeout(() => setMsg(null), 2500); };
- const tools = [['arrow', '↗'], ['box', '▢'], ['text', 'T'], ['blur', '▒'], ['line', '╱']];
+ const tools = [['arrow', '↗', 'screenshots.tool.arrow'], ['box', '▢', 'screenshots.tool.box'], ['text', 'T', 'screenshots.tool.text'],
+ ['blur', '▒', 'screenshots.tool.blur'], ['line', '╱', 'screenshots.tool.line']];
const tp = text ? (() => { const [lx, ly, bw, bh] = box.current ? lord.getLayout(box.current.id) : [0, 0, 1, 1]; const s = Math.min(bw / info.width, bh / info.height);
return { left: (bw - info.width * s) / 2 + text.x * s, top: (bh - info.height * s) / 2 + text.y * s }; })() : null;
return (
<View style={{ flex: 1 }}>
- <View style={{ height: 44, flexDirection: 'row', alignItems: 'center', gap: 6, paddingHorizontal: 10 }}>
- {tools.map(([k, g]) => (
- <View key={k} onClick={() => setTool(k)} style={{ width: 32, height: 28, borderRadius: 7, alignItems: 'center', justifyContent: 'center',
- backgroundColor: tool === k ? th.accent : th.control }}>
- <Text style={{ fontSize: 14, color: tool === k ? '#fff' : th.text }}>{g}</Text>
- </View>
- ))}
- <View style={{ width: 10 }} />
- {COLORS.map((c) => (
- <View key={c} onClick={() => setColor(c)} style={{ width: 20, height: 20, borderRadius: 10, backgroundColor: c, border: `2px solid ${color === c ? th.accent : th.separator}` }} />
- ))}
- <View style={{ flex: 1 }} />
- <Button label={tr('screenshots.undo')} onClick={() => setOps((o) => o.slice(0, -1))} />
- <Button label={tr('screenshots.copy')} onClick={copy} />
- <Button primary label={tr('screenshots.save')} onClick={save} />
+ <Toolbar>
+ <ToolbarGroup>
+ {tools.map(([k, g, key]) => <ToolbarButton key={k} icon={g} title={tr(key)} active={tool === k} onClick={() => setTool(k)} />)}
+ </ToolbarGroup>
+ <ToolbarDivider />
+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 6 }}>
+ {COLORS.map((c) => (
+ <View key={c} onClick={() => setColor(c)} style={{ width: 22, height: 22, borderRadius: 11, alignItems: 'center', justifyContent: 'center',
+ border: `2px solid ${color === c ? th.accent : 'transparent'}` }}>
+ <View style={{ width: 16, height: 16, borderRadius: 8, backgroundColor: c, border: `1px solid ${th.separator}` }} />
+ </View>
+ ))}
+ </View>
+ <ToolbarSpacer />
+ <ToolbarButton icon="⟲" title={tr('screenshots.undo')} onClick={() => setOps((o) => o.slice(0, -1))} />
+ <ToolbarButton icon="⧉" title={tr('screenshots.copy')} onClick={copy} />
<Button label={tr('screenshots.done')} onClick={() => wm.close(win.id)} />
- </View>
+ <Button primary label={tr('screenshots.save')} onClick={save} />
+ </Toolbar>
<View ref={box} style={{ flex: 1, backgroundColor: th.mode === 'dark' ? '#111' : '#ddd', overflow: 'hidden', direction: 'ltr' }} onMouseDown={down}>
<MediaView media={preview || handle} style={{ position: 'absolute', left: 0, top: 0, right: 0, bottom: 0 }} />
{text && tp && (
@@ -340,15 +344,15 @@ function Editor({ handle, path }) {
placeholder={tr('screenshots.textHint')} />
</View>
)}
- {msg && <View style={{ position: 'absolute', left: 0, right: 0, bottom: 16, alignItems: 'center' }}>
- <View style={{ paddingHorizontal: 14, paddingVertical: 7, borderRadius: 8, backgroundColor: 'rgba(0,0,0,0.75)' }}><Text style={{ fontSize: 12, color: '#fff' }}>{msg}</Text></View>
+ {msg && <View style={{ position: 'absolute', left: 0, right: 0, bottom: 20, alignItems: 'center' }}>
+ <View style={{ paddingHorizontal: 14, height: 30, justifyContent: 'center', borderRadius: 15, backgroundColor: 'rgba(0,0,0,0.75)' }}><Text style={{ fontSize: 12, color: '#fff' }}>{msg}</Text></View>
</View>}
</View>
</View>
);
}
-// ---- el panel (ventana principal) ----
+// ---- the panel (main window) ----
function Panel() {
const th = useTheme();
@@ -368,44 +372,43 @@ function Panel() {
] }]);
}, []);
const Mode = ({ glyph, label, onClick, danger }) => (
- <View onClick={onClick} style={{ flex: 1, height: 74, borderRadius: 10, alignItems: 'center', justifyContent: 'center', gap: 6,
- backgroundColor: danger ? 'rgba(255,59,48,0.15)' : th.control }}>
+ <View onClick={onClick} style={{ flex: 1, minWidth: 0, height: 82, borderRadius: 10, alignItems: 'center', gap: 6, paddingHorizontal: 4, paddingTop: 16,
+ backgroundColor: danger ? 'rgba(255,59,48,0.14)' : th.mode === 'dark' ? 'rgba(255,255,255,0.06)' : 'rgba(0,0,0,0.04)', border: `1px solid ${th.separator}` }}>
<Text style={{ fontSize: 22, color: danger ? '#ff3b30' : th.text }}>{glyph}</Text>
- <Text style={{ fontSize: 11, color: th.text, textAlign: 'center' }}>{label}</Text>
+ <Text style={{ fontSize: typeScale.caption, fontWeight: 500, color: th.text, textAlign: 'center', lineHeight: 1.2 }}>{label}</Text>
</View>
);
const prot = windows.get().filter((w) => w.protected).length;
return (
- <View style={{ flex: 1, padding: 14, gap: 12 }}>
+ <View style={{ flex: 1, padding: 20, gap: 16 }}>
<View style={{ flexDirection: 'row', gap: 8 }}>
<Mode glyph="▣" label={tr('screenshots.mode.full')} onClick={() => capture.full()} />
<Mode glyph="⧈" label={tr('screenshots.mode.window')} onClick={() => capture.area('window')} />
<Mode glyph="⬚" label={tr('screenshots.mode.area')} onClick={() => capture.area('area')} />
<Mode glyph={rec ? '■' : '●'} danger label={tr(rec ? 'screenshots.mode.stop' : 'screenshots.mode.record')} onClick={() => capture.record()} />
</View>
- <View style={{ gap: 8, padding: 12, borderRadius: 10, backgroundColor: th.hover }}>
- <View style={{ flexDirection: 'row', alignItems: 'center', gap: 10 }}>
- <Text style={{ fontSize: 12, color: th.text, flex: 1 }}>{tr('screenshots.timer')}</Text>
- <Segmented value={o.timer} onChange={(v) => set({ timer: v })} options={[[0, tr('screenshots.timerNone')], [5, '5 s'], [10, '10 s']]} />
- </View>
- <View style={{ flexDirection: 'row', alignItems: 'center', gap: 10 }}>
- <Text style={{ fontSize: 12, color: th.text, flex: 1 }}>{tr('screenshots.toClipboard')}</Text>
- <Toggle on={!!o.clipboard} onChange={(v) => set({ clipboard: v })} />
- </View>
- <View style={{ flexDirection: 'row', alignItems: 'center', gap: 10 }}>
- <Text style={{ fontSize: 12, color: th.text, flex: 1 }}>{tr('screenshots.mic')}</Text>
- <Toggle on={!!o.mic} onChange={(v) => set({ mic: v })} />
- </View>
- </View>
- <Text style={{ fontSize: 11, color: th.textDim }}>{tr('screenshots.shortcuts')}</Text>
- {prot > 0 && <Text style={{ fontSize: 11, color: th.textDim }}>{tr('screenshots.protectedNote', { count: prot })}</Text>}
- {list.length > 0 && <Text style={{ fontSize: 12, fontWeight: 600, color: th.text }}>{tr('screenshots.recent')}</Text>}
- {list.slice(0, 5).map((r) => (
- <View key={r.path} onClick={() => wm.open(r.video ? 'player' : 'photos', { new: true, args: { path: r.path } })} style={{ flexDirection: 'row', gap: 8 }}>
- <Text style={{ fontSize: 12, color: th.textDim }}>{r.video ? '🎬' : '🖼'}</Text>
- <Text style={{ fontSize: 12, color: th.text, whiteSpace: 'nowrap', overflow: 'hidden', flex: 1 }}>{r.path.split('/').pop()}</Text>
- </View>
- ))}
+ <GroupBox footer={null}>
+ <FormRow label={tr('screenshots.timer')}>
+ <Segmented small value={o.timer} onChange={(v) => set({ timer: v })} options={[[0, tr('screenshots.timerNone')], [5, '5 s'], [10, '10 s']]} />
+ </FormRow>
+ <FormRow label={tr('screenshots.toClipboard')}><Toggle on={!!o.clipboard} onChange={(v) => set({ clipboard: v })} /></FormRow>
+ <FormRow label={tr('screenshots.mic')}><Toggle on={!!o.mic} onChange={(v) => set({ mic: v })} /></FormRow>
+ </GroupBox>
+ <Text style={{ fontSize: typeScale.caption, color: th.textDim, lineHeight: 1.45, paddingHorizontal: 8 }}>{tr('screenshots.shortcuts')}</Text>
+ {prot > 0 && <Text style={{ fontSize: typeScale.caption, color: th.textDim, paddingHorizontal: 8 }}>{tr('screenshots.protectedNote', { count: prot })}</Text>}
+ {list.length > 0 && (
+ <GroupBox title={tr('screenshots.recent')}>
+ {list.slice(0, 5).map((r) => (
+ <View key={r.path} onClick={() => wm.open(r.video ? 'player' : 'photos', { new: true, args: { path: r.path } })}
+ style={{ minHeight: 30, flexDirection: 'row', alignItems: 'center', gap: 8 }}>
+ <Text style={{ width: 16, fontSize: 12, color: th.accent, textAlign: 'center' }}>{r.video ? '▶' : '◫'}</Text>
+ <View style={{ flex: 1, minWidth: 0, overflow: 'hidden' }}>
+ <Text style={{ fontSize: typeScale.callout, color: th.text, whiteSpace: 'nowrap' }}>{r.path.split('/').pop()}</Text>
+ </View>
+ </View>
+ ))}
+ </GroupBox>
+ )}
</View>
);
}
diff --git a/apps/settings/Bluetooth.jsx b/apps/settings/Bluetooth.jsx
index 314abce..a975151 100644
--- a/apps/settings/Bluetooth.jsx
+++ b/apps/settings/Bluetooth.jsx
@@ -2,7 +2,7 @@
// (pair). BlueZ over the system bus, from lord-server (server/src/hw/bt.c); PIN and passkey
// requests are drawn by the system (sdk/hardware.jsx, BluetoothPrompt). Headphones and speakers
// show up in Sound through PipeWire. See docs/SETTINGS.md, "Bluetooth".
-import { View, Text, useTheme, useLocale, Toggle, Button, MenuButton, admin, useBluetooth, onBluetoothResult } from '@lordos/sdk';
+import { View, Text, useTheme, useLocale, Toggle, Button, admin, useBluetooth, onBluetoothResult } from '@lordos/sdk';
import { useEffect, useState } from 'react';
import { GroupBox, SettingRow, PageHeader, Note, Stack } from './ui.jsx';
@@ -44,11 +44,8 @@ function Device({ d, tr }) {
<View style={{ flexDirection: 'row', alignItems: 'center', gap: 6 }}>
{!d.busy && <Button small label={d.connected ? tr('prefs.bt.disconnect') : tr('prefs.bt.connect')}
onClick={() => (d.connected ? lord.bt.disconnect(d.path) : lord.bt.connect(d.path))} />}
- <MenuButton small title={tr('prefs.bt.more')} items={[
- { label: d.connected ? tr('prefs.bt.disconnect') : tr('prefs.bt.connect'), onClick: () => (d.connected ? lord.bt.disconnect(d.path) : lord.bt.connect(d.path)) },
- '-',
- { label: tr('prefs.bt.forget'), destructive: true, onClick: () => lord.bt.forget(d.path) },
- ]} />
+ {/* MenuButton's menu would sit under the next group (zIndex only orders siblings) */}
+ <Button small plain destructive label={tr('prefs.bt.forget')} onClick={() => lord.bt.forget(d.path)} />
</View>
</SettingRow>
);
diff --git a/apps/settings/DefaultApps.jsx b/apps/settings/DefaultApps.jsx
index 746a6b6..aa70a53 100644
--- a/apps/settings/DefaultApps.jsx
+++ b/apps/settings/DefaultApps.jsx
@@ -22,7 +22,7 @@ export function DefaultAppsSettings() {
{DEFAULT_CATEGORIES.map((c) => {
const list = candidatesFor(c.id, apps);
const cur = defaultFor(c.id);
- const opts = list.map((a) => [a.id, a.native ? a.name : `${a.name}`]);
+ const opts = list.map((a) => [a.id, a.name, a.Icon]);
if (cur && !opts.some(([id]) => id === cur)) opts.push([cur, tr('prefs.defaults.other', { id: cur.replace(/\.desktop$/, '') })]);
const [glyph, color] = LOOK[c.id];
return (
diff --git a/apps/settings/Displays.jsx b/apps/settings/Displays.jsx
index c8b2470..c894ca0 100644
--- a/apps/settings/Displays.jsx
+++ b/apps/settings/Displays.jsx
@@ -134,7 +134,8 @@ export function DisplaysSettings() {
const curRes = res.find((r) => r.w === mode.w && r.h === mode.h) || res[0];
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 sizeLine = [cur.connector, cur.diagonal ? tr('prefs.display.inches', { n: (cur.diagonal / 10).toFixed(1) }) : '', `${mode.w} × ${mode.h}`].filter(Boolean).join(' · ');
+ const looks = d.scale === 2 ? tr('prefs.display.looksLike', { w: Math.floor(mode.w / 2), h: Math.floor(mode.h / 2) }) : '';
+ const sizeLine = [cur.connector, cur.diagonal ? tr('prefs.display.inches', { n: (cur.diagonal / 10).toFixed(1) }) : '', `${mode.w} × ${mode.h}`, looks].filter(Boolean).join(' · ');
return (
<Stack>
<Arrangement outs={outs} current={cur} t={t} tr={tr} onPick={(o) => go(o, { conn: o.id, w: 0, h: 0, refresh: 0, rotation: 0 })} />
@@ -147,19 +148,20 @@ export function DisplaysSettings() {
</View>
<GroupBox>
<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: d.rotation }); }}
+ <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: d.rotation, scale: d.scale || 1 }); }}
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: d.rotation })}
+ <PopUp value={mode.refresh} onChange={(refresh) => go(cur, { w: mode.w, h: mode.h, refresh, rotation: d.rotation, scale: d.scale || 1 })}
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={d.rotation ? tr('prefs.display.rotationHint') : ''}>
- <PopUp value={d.rotation} onChange={(rotation) => go(cur, { w: mode.w, h: mode.h, refresh: mode.refresh, rotation })}
+ <PopUp value={d.rotation} onChange={(rotation) => go(cur, { w: mode.w, h: mode.h, refresh: mode.refresh, rotation, scale: d.scale || 1 })}
options={[[0, tr('prefs.display.rotStandard')], [1, '90°'], [2, '180°'], [3, '270°']]} />
</SettingRow>
- <SettingRow label={tr('prefs.display.scale')} hint={tr('prefs.display.scaleHint')} disabled>
- <Segmented small value="100" onChange={() => {}} options={[['100', '100 %'], ['125', '125 %'], ['150', '150 %'], ['200', '200 %']]} />
+ <SettingRow label={tr('prefs.display.scale')} hint={tr(d.scale === 2 ? 'prefs.display.scale2Hint' : 'prefs.display.scaleHint')}>
+ <PopUp value={d.scale || 1} onChange={(scale) => go(cur, { w: mode.w, h: mode.h, refresh: mode.refresh, rotation: d.rotation, scale })}
+ options={[[1, tr('prefs.display.scale100')], [2, tr('prefs.display.scale200')]]} />
</SettingRow>
</GroupBox>
{msg ? <Note tone="warn">{msg}</Note> : null}
diff --git a/apps/settings/Power.jsx b/apps/settings/Power.jsx
index d3b0f0a..e19ec71 100644
--- a/apps/settings/Power.jsx
+++ b/apps/settings/Power.jsx
@@ -6,7 +6,7 @@ import {
BatteryGlyph, powerPrefs,
} from '@lordos/sdk';
import { useEffect, useState } from 'react';
-import { GroupBox, SettingRow, PageHeader, PopUp, Note, Stack } from './ui.jsx';
+import { GroupBox, SettingRow, PageHeader, PopUp, Stack, Badge } from './ui.jsx';
const mins = (m) => m * 60;
const duration = (tr, m) => (m >= 60 ? tr('prefs.power.hm', { h: Math.floor(m / 60), m: m % 60 }) : tr('prefs.power.m', { m }));
@@ -87,7 +87,8 @@ export function PowerSettings() {
const lockOpts = [[0, tr('prefs.power.immediately')], [5, tr('prefs.power.secs', { s: 5 })], [60, duration(tr, 1)], [300, duration(tr, 5)], [900, duration(tr, 15)], [3600, duration(tr, 60)], [-1, tr('prefs.power.never')]];
return (
<Stack>
- {hasBattery ? <BatteryCard b={b} tr={tr} /> : <Note>{tr('prefs.power.noBattery')}</Note>}
+ {hasBattery ? <BatteryCard b={b} tr={tr} />
+ : <PageHeader icon={<Badge glyph="⚡" color="#30d158" size={44} />} title={tr('prefs.power.onPower')} subtitle={tr('prefs.power.noBattery')} />}
<GroupBox>
<ProfileRow tr={tr} />
</GroupBox>
diff --git a/apps/settings/ui.jsx b/apps/settings/ui.jsx
index 81fa443..3660f38 100644
--- a/apps/settings/ui.jsx
+++ b/apps/settings/ui.jsx
@@ -2,7 +2,7 @@
// Notifications, Date & Time, Default Apps), on top of the SDK's GroupBox (docs/DESIGN.md): a row
// with a hint, a pop-up button (macOS NSPopUpButton), a page header and a note.
import { View, Text, useTheme, addListener, GroupBox, spacing, typeScale, createStore, useStore, screen, ScrollView } from '@lordos/sdk';
-import { useEffect, useRef, useState } from 'react';
+import { createElement as h, useEffect, useRef, useState } from 'react';
export { GroupBox };
@@ -80,6 +80,7 @@ export function PopUp({ value, options, onChange, width = 190, disabled }) {
<View ref={btn} onClick={toggle} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
style={{ width, height: 24, paddingHorizontal: 9, borderRadius: 6, flexDirection: 'row', alignItems: 'center', gap: 6,
backgroundColor: t.control, opacity: disabled ? 0.45 : hover || open ? 0.88 : 1, boxShadow: '0 1px 1px rgba(0,0,0,0.12)' }}>
+ {cur && cur[2] ? h(cur[2], { size: 16 }) : null}
<Text style={{ flex: 1, fontSize: 12, color: t.text, whiteSpace: 'nowrap', overflow: 'hidden', textAlign: 'start' }}>{cur ? cur[1] : ''}</Text>
<View style={{ width: 16, height: 18, borderRadius: 4, backgroundColor: t.accent, alignItems: 'center', justifyContent: 'center' }}>
<Text style={{ fontSize: 8, color: '#fff', lineHeight: 8 }}>▲</Text>
@@ -118,20 +119,21 @@ function PopUpLayer() {
backgroundColor: t.mode === 'dark' ? '#2c2c31' : '#ffffff', border: `1px solid ${t.separator}`, boxShadow: '0 10px 30px rgba(0,0,0,0.35)' }}>
<ScrollView style={{ flex: 1 }}>
{p.options.map(([v, label], i) => (v === '-' ? <View key={`s${i}`} style={{ height: 1, marginVertical: 4, marginHorizontal: 6, backgroundColor: t.separator }} />
- : <PopRow key={String(v)} label={label} checked={v === p.value} onClick={() => { popup.set(null); if (v !== p.value) p.onChange(v); }} />))}
+ : <PopRow key={String(v)} label={label} Icon={p.options[i][2]} checked={v === p.value} onClick={() => { popup.set(null); if (v !== p.value) p.onChange(v); }} />))}
</ScrollView>
</View>
</>
);
}
-function PopRow({ label, checked, onClick }) {
+function PopRow({ label, checked, onClick, Icon }) {
const t = useTheme();
const [hover, setHover] = useState(false);
return (
<View onClick={onClick} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
- style={{ height: 24, paddingHorizontal: 6, borderRadius: 5, flexDirection: 'row', alignItems: 'center', gap: 4, backgroundColor: hover ? t.accent : 'transparent' }}>
+ style={{ height: 24, paddingHorizontal: 6, borderRadius: 5, flexDirection: 'row', alignItems: 'center', gap: 6, backgroundColor: hover ? t.accent : 'transparent' }}>
<Text style={{ width: 14, fontSize: 11, color: hover ? '#fff' : t.text }}>{checked ? '✓' : ''}</Text>
+ {Icon ? <Icon size={16} /> : null}
<Text style={{ flex: 1, fontSize: 12, whiteSpace: 'nowrap', color: hover ? '#fff' : t.text, textAlign: 'start' }}>{label}</Text>
</View>
);
diff --git a/apps/store/debian.js b/apps/store/debian.js
index 912dfce..5363e62 100644
--- a/apps/store/debian.js
+++ b/apps/store/debian.js
@@ -1,25 +1,25 @@
-// debian.js — la parte de Debian de la Tienda. Lee el índice propio (lord.pkg, sin root;
-// server/src/pkg) y modifica por el ayudante de administración (pkg-update, pkg-install,
-// pkg-remove, pkg-upgrade, pkg-install-file). Antes de cambiar algo muestra el plan: qué se
-// instala, actualiza o quita, y cuánto baja y ocupa. Ver docs/PAQUETES.md.
+// 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.
import { createElement as h, useEffect, useState } from 'react';
import {
- View, Text, Image, Button, useTheme, useStore, createStore, admin, formatBytes, formatDate,
- refreshApps, launchApp, useLauncherApps, LetterIcon, t, locale,
+ View, Text, Image, Button, EmptyState, useTheme, useStore, createStore, admin, formatBytes, formatDate,
+ refreshApps, launchApp, useLauncherApps, LetterIcon, typeScale, t, locale,
} from '@lordos/sdk';
const available = () => typeof lord.pkg !== 'undefined';
const ready = () => available() && lord.pkg.available();
const lang2 = () => (locale.get().lang || 'en').split('-')[0];
-// Estado compartido: generación (cambia cuando cambia el índice o lo instalado) y la tarea en curso.
+// Shared state: generation (changes when the index or what is installed changes) and the running job.
const state = createStore({ gen: 0, job: null, msg: null });
const bump = () => state.set((s) => ({ ...s, gen: s.gen + 1 }));
admin.onEvent((text) => {
if (text === 'pkg index' || text === 'pkg changed') { bump(); if (text === 'pkg changed') refreshApps(); }
});
-// Corre una acción de paquetes mostrando su progreso ("progress <fase> <hecho> <total>").
+// Runs a package action showing its progress ("progress <phase> <done> <total>").
function runJob(action, arg, title) {
state.set((s) => ({ ...s, job: { title, phase: '', done: 0, total: 0, log: [] }, msg: null }));
const onLog = (line) => {
@@ -40,7 +40,11 @@ export const useDebian = () => {
return { ...s, upgrades };
};
-// ---- piezas ----
+// ---- pieces ----
+
+// A rounded inset box (plan, progress), like GroupBox without rows.
+const boxStyle = (th, extra) => ({ padding: 16, borderRadius: 10, backgroundColor: th.hover, border: `1px solid ${th.separator}`, gap: 8, ...extra });
+const titleStyle = (th) => ({ fontSize: typeScale.largeTitle, fontWeight: 600, color: th.text });
function PkgIcon({ app, name, size = 48 }) {
const icon = app?.icon || (available() ? lord.pkg.icon(name) : null);
@@ -55,7 +59,7 @@ function Progress() {
if (!job) return h(Text, { style: { fontSize: 12, color: msg.ok ? '#30d158' : '#ff453a', marginBottom: 10 } }, msg.text);
const f = job.total ? Math.min(1, job.done / job.total) : 0;
const phase = job.phase ? t(`store.phase.${job.phase}`) : t('store.working');
- return h(View, { style: { padding: 12, borderRadius: 10, backgroundColor: th.hover, gap: 6, marginBottom: 12 } },
+ return h(View, { style: boxStyle(th, { gap: 6, marginBottom: 4 }) },
h(Text, { style: { fontSize: 13, fontWeight: 600, color: th.text } }, `${job.title} — ${phase}`),
h(View, { style: { height: 6, borderRadius: 3, backgroundColor: th.control, direction: 'ltr' } },
h(View, { style: { width: `${Math.round(f * 100)}%`, height: 6, borderRadius: 3, backgroundColor: th.accent } })),
@@ -63,7 +67,7 @@ function Progress() {
...job.log.map((l, i) => h(Text, { key: i, style: { fontSize: 11, color: th.textDim, whiteSpace: 'nowrap', overflow: 'hidden' } }, l)));
}
-// Resumen de un plan: lo que pasa y cuánto ocupa.
+// 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'));
@@ -80,7 +84,7 @@ function PlanView({ plan }) {
})));
}
-// ---- ficha de un paquete ----
+// ---- package page ----
function Details({ name, onBack }) {
const th = useTheme();
@@ -92,7 +96,7 @@ function Details({ name, onBack }) {
if (!info) return h(Text, { style: { color: th.textDim } }, t('store.debian.notFound', { name }));
const app = info.app;
const isAdmin = admin.available();
- // la app de escritorio instalada que corresponde (para "Abrir")
+ // the matching installed desktop app (for "Open")
const desk = app && launcher.find((a) => a.kind === 'linux' && (`${a.desktopId}.desktop` === app.id || a.desktopId === app.id));
const ask = (p) => setPlan(p);
const doInstall = () => ask({ kind: 'install', p: lord.pkg.plan({ install: [name] }) });
@@ -104,13 +108,13 @@ function Details({ name, onBack }) {
setPlan(null);
};
const desc = (info.appDescription || info.description || '').trim();
- return h(View, { style: { gap: 12 } },
- h(View, { onClick: onBack, style: { alignSelf: 'flex-start', paddingVertical: 4 } }, h(Text, { style: { fontSize: 13, color: th.accent } }, `‹ ${t('store.back')}`)),
+ return h(View, { style: { gap: 16 } },
+ h(Button, { plain: true, small: true, label: `‹ ${t('store.back')}`, onClick: onBack, style: { alignSelf: 'flex-start' } }),
h(Progress),
h(View, { style: { flexDirection: 'row', gap: 16, alignItems: 'center' } },
h(PkgIcon, { app, name, size: 72 }),
- h(View, { style: { flex: 1, gap: 4 } },
- h(Text, { style: { fontSize: 20, fontWeight: 700, color: th.text } }, app?.name || name),
+ h(View, { style: { flex: 1, minWidth: 0, gap: 4 } },
+ h(Text, { style: titleStyle(th) }, app?.name || name),
h(Text, { style: { fontSize: 13, color: th.textDim } }, app?.summary || info.summary),
h(Text, { style: { fontSize: 11, color: th.textDim } }, t('store.debian.meta', {
name, version: info.version, size: formatBytes(info.installedSize), suite: info.suite || '',
@@ -121,33 +125,43 @@ function Details({ name, onBack }) {
info.upgradable && h(Button, { label: t('store.upgrade'), onClick: () => isAdmin && !job && doInstall() }),
info.installed && !info.essential && h(Button, { label: t('store.remove'), onClick: () => isAdmin && !job && doRemove() }))),
!isAdmin && h(Text, { style: { fontSize: 11, color: '#ff9f0a' } }, t('store.debian.needAdmin')),
- plan && h(View, { style: { padding: 12, borderRadius: 10, backgroundColor: th.hover, gap: 8 } },
- h(Text, { style: { fontSize: 13, fontWeight: 600, color: th.text } }, t(plan.kind === 'install' ? 'store.plan.titleInstall' : 'store.plan.titleRemove')),
+ plan && h(View, { style: boxStyle(th) },
+ h(Text, { style: { fontSize: typeScale.headline, fontWeight: 600, color: th.text } }, t(plan.kind === 'install' ? 'store.plan.titleInstall' : 'store.plan.titleRemove')),
h(PlanView, { plan: plan.p }),
- h(View, { style: { flexDirection: 'row', gap: 8 } },
- plan.p.ok && h(Button, { primary: true, label: t('store.plan.confirm'), onClick: confirm }),
- h(Button, { label: t('store.cancel'), onClick: () => setPlan(null) }))),
+ h(View, { style: { flexDirection: 'row', gap: 8, justifyContent: 'flex-end', marginTop: 4 } },
+ h(Button, { label: t('store.cancel'), onClick: () => setPlan(null) }),
+ plan.p.ok && h(Button, { primary: true, label: t('store.plan.confirm'), onClick: confirm }))),
info.installed && h(Text, { style: { fontSize: 12, color: th.textDim } }, t('store.debian.installedVersion', { version: info.installed })),
- desc ? h(Text, { style: { fontSize: 13, color: th.text, lineHeight: 1.45 } }, desc.slice(0, 1600)) : null,
+ desc ? h(Text, { style: { fontSize: 13, color: th.text, lineHeight: 1.45, maxWidth: 640 } }, desc.slice(0, 1600)) : null,
info.homepage ? h(Text, { style: { fontSize: 11, color: th.textDim } }, info.homepage) : null);
}
-// ---- grilla de apps ----
+// ---- app grid ----
function Card({ a, onOpen }) {
const th = useTheme();
- return h(View, { onClick: onOpen, style: { width: 196, padding: 10, gap: 6, borderRadius: 10, backgroundColor: th.hover, flexDirection: 'row', alignItems: 'center' } },
+ return h(View, { onClick: onOpen, style: { width: 200, padding: 12, gap: 10, borderRadius: 10, backgroundColor: th.hover, border: `1px solid ${th.separator}`,
+ flexDirection: 'row', alignItems: 'center' } },
h(PkgIcon, { app: a.app || a, name: a.package || a.name, size: 44 }),
- h(View, { style: { flex: 1, gap: 2 } },
+ h(View, { style: { flex: 1, minWidth: 0, gap: 2 } },
h(Text, { style: { fontSize: 13, fontWeight: 600, color: th.text, whiteSpace: 'nowrap', overflow: 'hidden' } }, (a.app || a).name || a.name),
h(Text, { style: { fontSize: 11, color: th.textDim, maxHeight: 28, overflow: 'hidden', lineHeight: 1.25 } }, (a.app || a).summary || a.summary || ''),
- a.installed ? h(Text, { style: { fontSize: 10, color: '#30d158' } }, t('store.installedBadge')) : null));
+ a.installed ? h(Text, { style: { fontSize: 11, fontWeight: 500, color: '#30d158' } }, t('store.installedBadge')) : null));
}
-const Grid = ({ items, onOpen }) => h(View, { style: { flexDirection: 'row', flexWrap: 'wrap', gap: 10 } },
+const Grid = ({ items, onOpen }) => h(View, { style: { flexDirection: 'row', flexWrap: 'wrap', gap: 12 } },
...items.map((a) => h(Card, { key: `${a.package || a.name}:${a.id || ''}`, a, onOpen: () => onOpen(a.package || a.name) })));
-const Chips = ({ items }) => h(View, { style: { flexDirection: 'row', flexWrap: 'wrap', gap: 6 } }, ...items);
+const Chips = ({ items }) => h(View, { style: { flexDirection: 'row', flexWrap: 'wrap', gap: 8 } }, ...items);
+
+// A drawn bag, monochrome, for the Store's empty states.
+function StoreGlyph() {
+ const th = useTheme();
+ const c = th.textDim;
+ return h(View, { style: { width: 48, height: 48, marginBottom: 4 } },
+ h(View, { style: { position: 'absolute', left: 15, top: 2, width: 18, height: 16, borderRadius: 9, border: `3px solid ${c}` } }),
+ h(View, { style: { position: 'absolute', left: 4, top: 12, width: 40, height: 34, borderRadius: 7, backgroundColor: c } }));
+}
const CATS = ['AudioVideo', 'Development', 'Education', 'Game', 'Graphics', 'Network', 'Office', 'Science', 'System', 'Utility'];
@@ -157,11 +171,11 @@ function Discover({ query }) {
const [cat, setCat] = useState('Utility');
const [open, setOpen] = useState(null);
useEffect(() => setOpen(null), [query]);
- if (!available()) return h(Text, { style: { fontSize: 13, color: th.textDim } }, t('store.debian.unavailable'));
+ if (!available()) return h(EmptyState, { icon: 'ⓘ', title: t('store.debian.unavailable'), style: { minHeight: 360 } });
if (!ready()) {
- return h(View, { style: { gap: 10 } }, h(Progress),
- h(Text, { style: { fontSize: 13, color: th.text } }, t('store.debian.noIndex')),
- h(Button, { primary: true, label: t('store.debian.update'), onClick: () => runJob('pkg-update', '', t('store.job.update')) }));
+ return h(View, { style: { gap: 12 } }, h(Progress),
+ h(EmptyState, { icon: h(StoreGlyph), title: t('store.debian.noIndexTitle'), hint: t('store.debian.noIndex'), style: { minHeight: 380 },
+ action: h(Button, { primary: true, label: t('store.debian.update'), onClick: () => runJob('pkg-update', '', t('store.job.update')) }) }));
}
if (open) return h(Details, { name: open, onBack: () => setOpen(null) });
const q = query.trim();
@@ -169,24 +183,24 @@ function Discover({ query }) {
if (q) {
const res = lord.pkg.search(q, { limit: 60, lang: lang2() });
const apps = res.filter((r) => r.app), others = res.filter((r) => !r.app);
- return h(View, { style: { gap: 10 } },
+ return h(View, { style: { gap: 12 } },
h(Progress),
- h(Text, { style: { fontSize: 20, fontWeight: 700, color: th.text } }, t('store.debian.results', { q })),
+ h(Text, { style: titleStyle(th) }, t('store.debian.results', { q })),
apps.length ? h(Grid, { items: apps.map((r) => ({ ...r, package: r.name })), onOpen: setOpen }) : null,
- others.length ? h(Text, { style: { fontSize: 11, fontWeight: 600, color: th.textDim, marginTop: 8 } }, t('store.debian.otherPackages')) : null,
- ...others.slice(0, 30).map((r) => h(View, { key: r.name, onClick: () => setOpen(r.name), style: { flexDirection: 'row', gap: 10, paddingVertical: 6 } },
+ others.length ? h(Text, { style: { fontSize: 11, fontWeight: 600, color: th.textDim, marginTop: 12 } }, t('store.debian.otherPackages')) : null,
+ ...others.slice(0, 30).map((r) => h(View, { key: r.name, onClick: () => setOpen(r.name), style: { flexDirection: 'row', alignItems: 'center', gap: 12, minHeight: 28 } },
h(Text, { style: { width: 200, fontSize: 12, fontWeight: 600, color: th.text, whiteSpace: 'nowrap', overflow: 'hidden' } }, r.name),
- h(Text, { style: { flex: 1, fontSize: 12, color: th.textDim, whiteSpace: 'nowrap', overflow: 'hidden' } }, r.summary),
+ h(Text, { style: { flex: 1, minWidth: 0, fontSize: 12, color: th.textDim, whiteSpace: 'nowrap', overflow: 'hidden' } }, r.summary),
r.installed ? h(Text, { style: { fontSize: 11, color: '#30d158' } }, t('store.installedBadge')) : null)),
- res.length === 0 ? h(Text, { style: { fontSize: 13, color: th.textDim } }, t('store.debian.none')) : null);
+ res.length === 0 ? h(EmptyState, { title: t('store.debian.none'), style: { minHeight: 240 } }) : null);
}
const counts = lord.pkg.categories();
const list = lord.pkg.apps({ category: cat, limit: 60, lang: lang2() });
- return h(View, { style: { gap: 12 } },
+ return h(View, { style: { gap: 16 } },
h(Progress),
- h(Text, { style: { fontSize: 22, fontWeight: 700, color: th.text } }, t('store.discover.title')),
+ h(Text, { style: titleStyle(th) }, t('store.discover.title')),
h(Chips, { items: CATS.filter((c) => counts[c]).map((c) => h(View, { key: c, onClick: () => setCat(c), style: {
- paddingHorizontal: 10, paddingVertical: 5, borderRadius: 14, backgroundColor: c === cat ? th.accent : th.control } },
+ paddingHorizontal: 12, height: 26, justifyContent: 'center', borderRadius: 13, backgroundColor: c === cat ? th.accent : th.control } },
h(Text, { style: { fontSize: 12, color: c === cat ? '#fff' : th.text } }, `${t(`store.cat.${c}`)} · ${counts[c]}`))) }),
h(Grid, { items: list, onOpen: setOpen }));
}
@@ -195,42 +209,47 @@ function Updates() {
const th = useTheme();
const { job } = useStore(state);
const [plan, setPlan] = useState(null);
- if (!ready()) return h(Text, { style: { fontSize: 13, color: th.textDim } }, available() ? t('store.debian.noIndex') : t('store.debian.unavailable'));
+ if (!ready()) {
+ return available()
+ ? h(EmptyState, { icon: h(StoreGlyph), title: t('store.debian.noIndexTitle'), hint: t('store.debian.noIndex'), style: { minHeight: 380 },
+ action: h(Button, { primary: true, label: t('store.debian.update'), onClick: () => !job && runJob('pkg-update', '', t('store.job.update')) }) })
+ : h(EmptyState, { icon: 'ⓘ', title: t('store.debian.unavailable'), style: { minHeight: 360 } });
+ }
const ups = lord.pkg.upgrades();
- return h(View, { style: { gap: 10 } },
+ return h(View, { style: { gap: 12 } },
h(Progress),
- h(View, { style: { flexDirection: 'row', alignItems: 'center' } },
- h(Text, { style: { flex: 1, fontSize: 22, fontWeight: 700, color: th.text } }, t('store.updates.title')),
+ h(View, { style: { flexDirection: 'row', alignItems: 'center', gap: 8 } },
+ h(Text, { style: { flex: 1, ...titleStyle(th) } }, t('store.updates.title')),
h(Button, { label: t('store.debian.update'), onClick: () => !job && runJob('pkg-update', '', t('store.job.update')) }),
- ups.length ? h(Button, { primary: true, label: t('store.updates.all'), style: { marginLeft: 8 }, onClick: () => !job && setPlan(lord.pkg.plan({ upgrade: true })) }) : null),
- plan && h(View, { style: { padding: 12, borderRadius: 10, backgroundColor: th.hover, gap: 8 } },
+ ups.length ? h(Button, { primary: true, label: t('store.updates.all'), onClick: () => !job && setPlan(lord.pkg.plan({ upgrade: true })) }) : null),
+ plan && h(View, { style: boxStyle(th) },
h(PlanView, { plan }),
- h(View, { style: { flexDirection: 'row', gap: 8 } },
+ h(View, { style: { flexDirection: 'row', gap: 8, justifyContent: 'flex-end', marginTop: 4 } },
+ h(Button, { label: t('store.cancel'), onClick: () => setPlan(null) }),
plan.ok && h(Button, { primary: true, label: t('store.plan.confirm'), onClick: () => {
const extra = plan.items.some((i) => i.action === 'remove');
runJob('pkg-upgrade', extra ? '--allow-remove' : '', t('store.job.upgrade')); setPlan(null);
- } }),
- h(Button, { label: t('store.cancel'), onClick: () => setPlan(null) }))),
- ups.length === 0 ? h(Text, { style: { fontSize: 13, color: th.textDim } }, t('store.updates.none')) : null,
- ...ups.map((u) => h(View, { key: u.name, style: { flexDirection: 'row', alignItems: 'center', gap: 10, paddingVertical: 6 } },
- h(PkgIcon, { name: u.name, size: 28 }),
- h(View, { style: { flex: 1 } },
+ } }))),
+ ups.length === 0 ? h(EmptyState, { icon: '✓', title: t('store.updates.none'), style: { minHeight: 300 } }) : null,
+ ...ups.map((u) => h(View, { key: u.name, style: { flexDirection: 'row', alignItems: 'center', gap: 12, paddingVertical: 8 } },
+ h(PkgIcon, { name: u.name, size: 32 }),
+ h(View, { style: { flex: 1, minWidth: 0, gap: 2 } },
h(Text, { style: { fontSize: 13, fontWeight: 600, color: th.text } }, u.name),
h(Text, { style: { fontSize: 11, color: th.textDim, whiteSpace: 'nowrap', overflow: 'hidden' } }, `${u.from} → ${u.to} · ${u.summary}`)),
h(Text, { style: { fontSize: 11, color: th.textDim } }, formatBytes(u.size)))));
}
-// Pie de la barra lateral: cuándo se revisó la lista por última vez.
+// Sidebar footer: when the list was last checked.
function Status() {
const th = useTheme();
useStore(state);
if (!ready()) return null;
const at = lord.pkg.lastUpdate();
- return h(Text, { style: { fontSize: 10, color: th.textDim, lineHeight: 1.35 } },
+ return h(Text, { style: { fontSize: 11, color: th.textDim, lineHeight: 1.35 } },
at ? t('store.debian.lastUpdate', { date: formatDate(new Date(at * 1000), 'short') }) : '');
}
-// Paquete de Debian que trae una app Linux instalada (para "Quitar" en Instaladas).
+// Debian package that brings an installed Linux app (for "Remove" in Installed).
function packageOfApp(a) {
if (!ready()) return null;
const want = new Set([a.desktopId, `${a.desktopId}.desktop`]);
diff --git a/apps/store/index.jsx b/apps/store/index.jsx
index e6b7955..2c0c8c2 100644
--- a/apps/store/index.jsx
+++ b/apps/store/index.jsx
@@ -1,13 +1,13 @@
-// Tienda — apps de LordOS (paquetes .lpk, sin root) y de Debian (motor de paquetes propio,
-// server/src/pkg; instalar y quitar pasan por el ayudante de administración).
+// Store: LordOS apps (.lpk packages, no root) and Debian apps (our own package engine,
+// server/src/pkg; install and remove go through the administration helper).
import {
- View, Text, Image, useTheme, useLocale, useAppWindow, useStore, Button, TextInput, ScrollView, SidebarItem, SectionTitle,
- packages, packageList, refreshPackages, useLauncherApps, launchApp, fs, formatBytes, wm,
+ View, Text, Image, useTheme, useLocale, useAppWindow, useStore, Button, ScrollView, SidebarItem, SectionTitle, SearchField, Hairline, EmptyState,
+ packages, packageList, refreshPackages, useLauncherApps, launchApp, fs, formatBytes, wm, direction, typeScale,
} from '@lordos/sdk';
import { useEffect, useMemo, useState } from 'react';
import { debian, useDebian } from './debian.js';
-// Nivel de confianza de un paquete según su firma (ver docs/FIRMA.md).
+// Trust level of a package from its signature (see docs/FIRMA.md).
const TRUST = {
lordos: { color: '#30d158', glyph: '◆' },
verified: { color: '#0a84ff', glyph: '✓' },
@@ -44,18 +44,33 @@ export function Icon({ size: s }) {
);
}
-const Divider = () => <View style={{ height: 1, backgroundColor: useTheme().separator }} />;
+// Hairline between list rows, inset to start at the text (after the icon), as macOS lists do.
+const Divider = ({ inset = 56 }) => <View style={{ height: 1, backgroundColor: useTheme().separator, [direction() === 'rtl' ? 'marginRight' : 'marginLeft']: inset }} />;
-// Fila de una app: ícono, nombre, detalle y acciones a la derecha.
+// Page title (large title) with an optional subtitle.
+export function PageTitle({ title, subtitle, children }) {
+ const t = useTheme();
+ return (
+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 8, marginBottom: 16 }}>
+ <View style={{ flex: 1, minWidth: 0, gap: 4 }}>
+ <Text style={{ fontSize: typeScale.largeTitle, fontWeight: 600, color: t.text }}>{title}</Text>
+ {subtitle ? <Text style={{ fontSize: typeScale.callout, color: t.textDim, lineHeight: 1.4 }}>{subtitle}</Text> : null}
+ </View>
+ {children}
+ </View>
+ );
+}
+
+// An app row: icon, name, detail and actions at the end.
export function AppRow({ icon, name, detail, extra, children, onClick }) {
const t = useTheme();
return (
- <View onClick={onClick} style={{ flexDirection: 'row', alignItems: 'center', gap: 12, paddingVertical: 10, paddingHorizontal: 4 }}>
+ <View onClick={onClick} style={{ flexDirection: 'row', alignItems: 'center', gap: 12, paddingVertical: 10 }}>
{icon}
- <View style={{ flex: 1, gap: 2 }}>
- <Text style={{ fontSize: 14, fontWeight: 600, color: t.text, whiteSpace: 'nowrap', overflow: 'hidden' }}>{name}</Text>
- {detail ? <Text style={{ fontSize: 12, color: t.textDim, whiteSpace: 'nowrap', overflow: 'hidden' }}>{detail}</Text> : null}
- {extra ? <Text style={{ fontSize: 11, color: t.textDim }}>{extra}</Text> : null}
+ <View style={{ flex: 1, minWidth: 0, gap: 2 }}>
+ <Text style={{ fontSize: typeScale.body, fontWeight: 600, color: t.text, whiteSpace: 'nowrap', overflow: 'hidden' }}>{name}</Text>
+ {detail ? <Text style={{ fontSize: typeScale.callout, color: t.textDim, whiteSpace: 'nowrap', overflow: 'hidden' }}>{detail}</Text> : null}
+ {extra ? <Text style={{ fontSize: typeScale.caption, color: t.textDim }}>{extra}</Text> : null}
</View>
<View style={{ flexDirection: 'row', gap: 8 }}>{children}</View>
</View>
@@ -64,12 +79,12 @@ export function AppRow({ icon, name, detail, extra, children, onClick }) {
export function Message({ msg }) {
if (!msg) return null;
- return <Text style={{ fontSize: 12, color: msg.ok ? '#30d158' : '#ff453a', marginVertical: 8 }}>{msg.text}</Text>;
+ return <Text style={{ fontSize: typeScale.callout, color: msg.ok ? '#30d158' : '#ff453a', marginVertical: 8, lineHeight: 1.4 }}>{msg.text}</Text>;
}
-// ---- apps LordOS (.lpk) ----
+// ---- LordOS apps (.lpk) ----
-// Paquetes encontrados en la carpeta personal (Descargas, Escritorio y la raíz).
+// Packages found in the home folder (Downloads, Desktop and the top level).
function findPackageFiles() {
const out = [];
for (const dir of ['', 'Descargas', 'Downloads', 'Escritorio', 'Desktop']) {
@@ -80,7 +95,7 @@ function findPackageFiles() {
return out;
}
-// Confirmación antes de instalar un archivo: lo que dice el paquete y qué pide.
+// Confirmation before installing a file: what the package says and what it asks for.
function InstallFile({ path, onDone }) {
const t = useTheme();
const { t: tr } = useLocale();
@@ -111,12 +126,12 @@ function InstallFile({ path, onDone }) {
} catch (e) { setMsg({ ok: false, text: e.message }); }
};
return (
- <View style={{ padding: 14, borderRadius: 10, backgroundColor: t.hover, gap: 8, marginBottom: 12 }}>
- <Text style={{ fontSize: 15, fontWeight: 700, color: t.text }}>{tr('store.file.title')}</Text>
+ <View style={{ padding: 16, borderRadius: 10, backgroundColor: t.hover, border: `1px solid ${t.separator}`, gap: 8, marginBottom: 20 }}>
+ <Text style={{ fontSize: typeScale.headline, fontWeight: 600, color: t.text }}>{tr('store.file.title')}</Text>
<Text style={{ fontSize: 12, color: t.textDim }}>{path}</Text>
{m && (
<View style={{ gap: 4 }}>
- <Text style={{ fontSize: 14, fontWeight: 600, color: t.text }}>{loc(m.name)} {m.version}</Text>
+ <Text style={{ fontSize: typeScale.body, fontWeight: 600, color: t.text }}>{loc(m.name)} {m.version}</Text>
{m.description ? <Text style={{ fontSize: 12, color: t.text }}>{loc(m.description)}</Text> : null}
<Text style={{ fontSize: 12, color: t.textDim }}>{tr('store.file.size', { size: formatBytes(info.size), files: info.files })}</Text>
<Text style={{ fontSize: 12, color: t.textDim }}>
@@ -127,9 +142,9 @@ function InstallFile({ path, onDone }) {
)}
{isDeb && <Text style={{ fontSize: 12, color: t.text }}>{tr('store.file.deb')}</Text>}
<Message msg={msg} />
- <View style={{ flexDirection: 'row', gap: 8 }}>
- {(m || isDeb) && !msg?.ok && <Button primary label={busy ? tr('store.working') : tr('store.install')} onClick={() => !busy && install()} />}
+ <View style={{ flexDirection: 'row', gap: 8, justifyContent: 'flex-end', marginTop: 4 }}>
<Button label={tr('store.close')} onClick={() => onDone?.(true)} />
+ {(m || isDeb) && !msg?.ok && <Button primary label={busy ? tr('store.working') : tr('store.install')} onClick={() => !busy && install()} />}
</View>
</View>
);
@@ -146,12 +161,11 @@ function LordOSPage({ query }) {
const shown = list.filter((p) => !q || `${p.name} ${p.description} ${p.id}`.toLowerCase().includes(q));
return (
<View>
- <Text style={{ fontSize: 22, fontWeight: 700, color: t.text, marginBottom: 4 }}>{tr('store.lordos.title')}</Text>
- <Text style={{ fontSize: 12, color: t.textDim, marginBottom: 12 }}>{tr('store.lordos.subtitle')}</Text>
+ <PageTitle title={tr('store.lordos.title')} subtitle={tr('store.lordos.subtitle')} />
{pick && <InstallFile path={pick} onDone={(cancel) => { if (cancel) setPick(null); setFiles(findPackageFiles().filter((f) => /\.lpk$/i.test(f.name))); }} />}
<Message msg={msg} />
<SectionTitle>{tr('store.lordos.installedTitle')}</SectionTitle>
- {shown.length === 0 && <Text style={{ fontSize: 13, color: t.textDim, margin: 10 }}>{tr('store.lordos.none')}</Text>}
+ {shown.length === 0 && <Text style={{ fontSize: typeScale.callout, color: t.textDim, marginHorizontal: 10, marginVertical: 8 }}>{tr('store.lordos.none')}</Text>}
{shown.map((p, i) => (
<View key={p.id}>
{i > 0 && <Divider />}
@@ -163,7 +177,7 @@ function LordOSPage({ query }) {
</View>
))}
<SectionTitle>{tr('store.lordos.filesTitle')}</SectionTitle>
- {files.length === 0 && <Text style={{ fontSize: 12, color: t.textDim, margin: 10 }}>{tr('store.lordos.noFiles')}</Text>}
+ {files.length === 0 && <Text style={{ fontSize: typeScale.callout, color: t.textDim, marginHorizontal: 10, marginVertical: 8 }}>{tr('store.lordos.noFiles')}</Text>}
{files.map((f) => (
<AppRow key={f.path} icon={<Icon size={32} />} name={f.name} detail={`${f.path.replace(fs.home(), '~')} · ${formatBytes(f.size)}`}>
<Button label={tr('store.install')} onClick={() => setPick(f.path)} />
@@ -173,7 +187,7 @@ function LordOSPage({ query }) {
);
}
-// Confianza, «Modificada por vos», Restaurar original y Compartir mi versión (docs/FIRMA.md).
+// Trust, "Modified by you", Restore original and Share my version (docs/FIRMA.md).
function PkgManage({ pkg, onMsg }) {
const t = useTheme();
const { t: tr } = useLocale();
@@ -195,7 +209,7 @@ function PkgManage({ pkg, onMsg }) {
} catch (e) { onMsg({ ok: false, text: e.message }); }
};
return (
- <View style={{ marginInlineStart: 56, marginBottom: 8, gap: 6 }}>
+ <View style={{ [direction() === 'rtl' ? 'marginRight' : 'marginLeft']: 56, marginBottom: 8, gap: 6 }}>
{st.hasOriginal ? <TrustBadge sig={st} /> : <Text style={{ fontSize: 11, color: t.textDim }}>{tr('store.manage.noOriginal')}</Text>}
{st.modified && (
<View style={{ gap: 4 }}>
@@ -216,7 +230,7 @@ function PkgManage({ pkg, onMsg }) {
}
const pkgManifest = (pkg) => ({ name: pkg.name, description: pkg.description, icon: 'icon.png', size: pkg.size, minSize: pkg.minSize, permissions: pkg.permissions });
-// ---- apps instaladas (todas: LordOS, paquetes y Linux) ----
+// ---- installed apps (all of them: LordOS, packages and Linux) ----
function InstalledPage({ query }) {
const t = useTheme();
@@ -227,10 +241,10 @@ function InstalledPage({ query }) {
const kind = (a) => tr(`store.kind.${a.kind}`);
return (
<View>
- <Text style={{ fontSize: 22, fontWeight: 700, color: t.text, marginBottom: 12 }}>{tr('store.installed.title')}</Text>
+ <PageTitle title={tr('store.installed.title')} />
{shown.map((a, i) => (
<View key={a.id}>
- {i > 0 && <Divider />}
+ {i > 0 && <Divider inset={48} />}
<AppRow icon={<a.Icon size={36} />} name={a.name} detail={a.comment || a.genericName || ''} extra={kind(a)}>
<Button label={tr('store.open')} onClick={() => launchApp(a.id)} />
{a.kind === 'linux' && debian.canRemove(a) && <Button label={tr('store.remove')} onClick={() => debian.removeApp(a)} />}
@@ -241,7 +255,7 @@ function InstalledPage({ query }) {
);
}
-// ---- ventana ----
+// ---- window ----
export default function Store() {
const t = useTheme();
@@ -254,7 +268,7 @@ export default function Store() {
useEffect(() => {
if (args?.install) setFile(args.install);
if (args?.page) setPage(args.page);
- if (args?.search) { setQuery(args.search); setPage('discover'); } // desde Spotlight
+ if (args?.search) { setQuery(args.search); setPage('discover'); } // from Spotlight
}, [args?.nonce]);
const pages = [
['discover', tr('store.page.discover')],
@@ -265,17 +279,18 @@ export default function Store() {
const Page = { discover: debian.Discover, lordos: LordOSPage, installed: InstalledPage, updates: debian.Updates }[page];
return (
<View style={{ flex: 1, flexDirection: 'row' }}>
- <View style={{ width: 200, backgroundColor: t.sidebarBg, padding: 10, gap: 4 }}>
- <TextInput value={query} onChange={(v) => { setQuery(v); if (v && page !== 'discover' && page !== 'installed' && page !== 'lordos') setPage('discover'); }}
- placeholder={tr('store.search')} onCancel={() => setQuery('')} />
- <View style={{ height: 6 }} />
+ <View style={{ width: 210, backgroundColor: t.sidebarBg, paddingHorizontal: 10, paddingTop: 10, paddingBottom: 12, gap: 2 }}>
+ <Hairline edge="end" />
+ <SearchField value={query} onChange={(v) => { setQuery(v); if (v && page !== 'discover' && page !== 'installed' && page !== 'lordos') setPage('discover'); }}
+ placeholder={tr('store.search')} style={{ marginBottom: 10 }} />
{pages.map(([id, label]) => <SidebarItem key={id} label={label} selected={page === id} onClick={() => setPage(id)} />)}
<View style={{ flex: 1 }} />
- <debian.Status />
+ <View style={{ paddingHorizontal: 10 }}><debian.Status /></View>
</View>
- <ScrollView style={{ flex: 1, padding: 18 }}>
+ <ScrollView style={{ flex: 1, paddingHorizontal: 20, paddingTop: 20 }}>
{file && <InstallFile path={file} onDone={(cancel) => cancel && setFile(null)} />}
<Page query={query} onPage={setPage} />
+ <View style={{ height: 20 }} />
</ScrollView>
</View>
);
diff --git a/apps/terminal/Chrome.jsx b/apps/terminal/Chrome.jsx
index c64a322..e47c25d 100644
--- a/apps/terminal/Chrome.jsx
+++ b/apps/terminal/Chrome.jsx
@@ -1,7 +1,8 @@
-// Chrome.jsx — todo lo que rodea a los paneles: pestañas, barra de estado, buscador,
-// barra de herramientas (toolbelt), ventanas emergentes, diálogos y avisos.
+// Chrome.jsx — everything around the panes: tabs, status bar, find bar, toolbelt, popups, dialogs
+// and toasts.
import {
- View, Text, TextInput, Button, Slider, useStore, useTheme, term, clipboard, clipboardHistory, useClock, t as tr, formatTime,
+ View, Text, TextInput, Button, Slider, SearchField, ToolbarButton, Hairline, useStore, useTheme, term, clipboard, clipboardHistory, useClock,
+ t as tr, formatTime,
} from '@lordos/sdk';
import { useEffect, useRef, useState } from 'react';
import {
@@ -12,7 +13,7 @@ import { terminalSettings, getProfile, profileName } from './profiles.js';
const small = (t, extra) => ({ fontSize: 12, color: t.textDim, whiteSpace: 'nowrap', ...extra });
-// ---- pestañas ----
+// ---- tabs ----
function Tab({ t, wid, tab, active, index, maxChars }) {
const [hover, setHover] = useState(false);
@@ -25,11 +26,12 @@ function Tab({ t, wid, tab, active, index, maxChars }) {
<View onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
onMouseDown={() => selectTab(wid, tab.id)}
onMouseUp={(e) => { if (e.button === 1) closeTab(wid, tab.id); }}
- style={{ flex: 1, maxWidth: 260, minWidth: 90, height: 28, flexDirection: 'row', alignItems: 'center', paddingHorizontal: 8, gap: 6,
- borderRadius: 6, backgroundColor: active ? t.control : hover ? t.hover : 'transparent' }}>
+ style={{ flex: 1, maxWidth: 260, minWidth: 90, height: 26, flexDirection: 'row', alignItems: 'center', paddingHorizontal: 8, gap: 6,
+ borderRadius: 6, backgroundColor: active ? (t.mode === 'dark' ? 'rgba(255,255,255,0.12)' : '#ffffff') : hover ? t.hover : 'transparent',
+ boxShadow: active && t.mode !== 'dark' ? '0 1px 2px rgba(0,0,0,0.12)' : 'none' }}>
<View onClick={(e) => { e.stopPropagation(); closeTab(wid, tab.id); }} style={{ width: 16, height: 16, borderRadius: 4,
alignItems: 'center', justifyContent: 'center', backgroundColor: hover ? t.hover : 'transparent' }}>
- <Text style={{ fontSize: 13, color: hover ? t.text : 'transparent' }}>×</Text>
+ <Text style={{ fontSize: 13, color: hover ? t.textDim : 'transparent' }}>✕</Text>
</View>
{anyBell && <Text style={{ fontSize: 11, color: '#ffd60a' }}>●</Text>}
{!anyBell && anyActivity && !active && <Text style={{ fontSize: 9, color: t.accent }}>●</Text>}
@@ -38,7 +40,7 @@ function Tab({ t, wid, tab, active, index, maxChars }) {
<Text style={{ fontSize: 12, fontWeight: active ? 600 : 500, color: active ? t.text : t.textDim, whiteSpace: 'nowrap',
textAlign: 'center' }}>{title.length > maxChars ? `…${title.slice(title.length - maxChars + 1)}` : title}</Text>
</View>
- <Text style={small(t, { fontSize: 11 })}>{index < 9 ? `❖${index + 1}` : ''}</Text>
+ <Text style={small(t, { fontSize: 11, opacity: active || hover ? 1 : 0.7 })}>{index < 9 ? `❖${index + 1}` : ''}</Text>
{color ? <View style={{ position: 'absolute', left: 8, right: 8, bottom: 1, height: 3, borderRadius: 2, backgroundColor: color }} /> : null}
</View>
);
@@ -51,21 +53,20 @@ export function TabBar({ t, wid, w }) {
const tabW = Math.min(260, (width - 50) / Math.max(1, w.tabs.length));
const maxChars = Math.max(6, Math.floor((tabW - 64) / 6.6));
return (
- <View ref={ref} style={{ height: 34, flexDirection: 'row', alignItems: 'center', paddingHorizontal: 6, gap: 4, backgroundColor: t.sidebarBg }}>
+ <View ref={ref} style={{ height: 36, flexDirection: 'row', alignItems: 'center', paddingHorizontal: 8, gap: 4, backgroundColor: t.sidebarBg }}>
+ <Hairline edge="bottom" />
{w.tabs.map((tab, i) => <Tab key={tab.id} t={t} wid={wid} tab={tab} index={i} active={tab.id === w.active} maxChars={maxChars} />)}
- <View onClick={() => addTab(wid)} style={{ width: 28, height: 28, borderRadius: 6, alignItems: 'center', justifyContent: 'center' }}>
- <Text style={{ fontSize: 18, color: t.textDim }}>+</Text>
- </View>
+ <ToolbarButton icon="+" iconSize={17} small title={tr('terminal.action.newTab')} color={t.textDim} onClick={() => addTab(wid)} style={{ width: 26 }} />
{w.broadcast && (
<View style={{ paddingHorizontal: 8, height: 22, borderRadius: 5, justifyContent: 'center', backgroundColor: '#ff453a' }}>
- <Text style={{ fontSize: 11, fontWeight: 700, color: '#fff' }}>{tr('terminal.broadcasting')}</Text>
+ <Text style={{ fontSize: 11, fontWeight: 600, color: '#fff' }}>{tr('terminal.broadcasting')}</Text>
</View>
)}
</View>
);
}
-// ---- barra de estado (como la de iTerm2) ----
+// ---- status bar (like iTerm2's) ----
export function StatusBar({ t, sid }) {
const [info, setInfo] = useState(() => term.info(sid));
@@ -82,6 +83,7 @@ export function StatusBar({ t, sid }) {
const Item = ({ label, color }) => <Text style={small(t, { color: color || t.textDim })}>{label}</Text>;
return (
<View style={{ height: 24, flexDirection: 'row', alignItems: 'center', paddingHorizontal: 12, gap: 16, backgroundColor: t.sidebarBg }}>
+ <Hairline edge="top" />
<Item label={cwd || '~'} />
<Item label={info.busy ? `▶ ${info.process}` : `${info.shell || 'shell'}`} color={info.busy ? t.accent : undefined} />
{m.lastExit > 0 && <Item label={tr('terminal.status.lastExit', { code: m.lastExit })} color="#ff453a" />}
@@ -94,10 +96,10 @@ export function StatusBar({ t, sid }) {
);
}
-// ---- buscador ----
+// ---- find bar ----
-// Búsqueda con expresión regular: el motor C da el texto por líneas lógicas y recibe las
-// coincidencias como (línea, primer carácter, cantidad).
+// Regular expression search: the C engine gives the text by logical lines and takes the matches
+// as (line, first character, count).
function regexSearch(sid, q, cs) {
let re;
try { re = new RegExp(q, cs ? 'gu' : 'giu'); } catch (e) { return { count: 0, index: -1, error: true }; }
@@ -128,16 +130,11 @@ export function FindBar({ t, wid, sid, find }) {
};
const move = (d) => setRes(term.searchMove(sid, d));
const close = () => { term.search(sid, '', false); patchWin(wid, () => ({ find: null })); };
- const Btn = ({ label, onClick, on }) => (
- <View onClick={onClick} style={{ width: 26, height: 24, borderRadius: 5, alignItems: 'center', justifyContent: 'center',
- backgroundColor: on ? t.accent : t.control }}>
- <Text style={{ fontSize: 12, fontWeight: 600, color: on ? '#fff' : t.text }}>{label}</Text>
- </View>
- );
+ const Btn = ({ label, onClick, on }) => <ToolbarButton small label={label} active={on} onClick={onClick} style={{ minWidth: 26, paddingHorizontal: 4 }} />;
return (
- <View style={{ position: 'absolute', right: 14, top: 8, flexDirection: 'row', alignItems: 'center', gap: 6, padding: 6, borderRadius: 9,
+ <View style={{ position: 'absolute', right: 12, top: 8, flexDirection: 'row', alignItems: 'center', gap: 4, padding: 6, borderRadius: 10,
backgroundColor: t.windowBg, border: `1px solid ${t.separator}`, boxShadow: '0 6px 18px rgba(0,0,0,0.35)' }}>
- <TextInput value={find.query} autoFocus placeholder={tr('terminal.find.placeholder')} style={{ width: 200, height: 26 }}
+ <SearchField value={find.query} autoFocus placeholder={tr('terminal.find.placeholder')} width={200}
onChange={(q) => set({ query: q })} onSubmit={() => move(-1)} onCancel={close}
onKeyDown={(e) => {
if (e.key === 'Enter' && e.shift) { move(1); return true; }
@@ -145,12 +142,12 @@ export function FindBar({ t, wid, sid, find }) {
if (e.key === 'ArrowDown') { move(1); return true; }
return false;
}} />
- <Text style={small(t, { width: 92, textAlign: 'center' })}>{res.error ? tr('terminal.find.badRegex') : res.count ? tr('terminal.find.position', { i: res.count - res.index, n: res.count }) : find.query ? tr('terminal.find.none') : ''}</Text>
+ <Text style={small(t, { width: 88, fontSize: 11, textAlign: 'center' })}>{res.error ? tr('terminal.find.badRegex') : res.count ? tr('terminal.find.position', { i: res.count - res.index, n: res.count }) : find.query ? tr('terminal.find.none') : ''}</Text>
<Btn label="↑" onClick={() => move(-1)} />
<Btn label="↓" onClick={() => move(1)} />
<Btn label="Aa" on={find.cs} onClick={() => set({ cs: !find.cs })} />
<Btn label=".*" on={find.regex} onClick={() => set({ regex: !find.regex })} />
- <Btn label="×" onClick={close} />
+ <ToolbarButton small icon="✕" iconSize={11} title={tr('terminal.find.close')} onClick={close} />
</View>
);
}
@@ -159,8 +156,8 @@ export function FindBar({ t, wid, sid, find }) {
function Section({ t, title, children }) {
return (
- <View style={{ marginBottom: 12 }}>
- <Text style={{ fontSize: 11, fontWeight: 700, color: t.textDim, marginBottom: 6 }}>{title}</Text>
+ <View style={{ marginBottom: 16 }}>
+ <Text style={{ fontSize: 11, fontWeight: 600, color: t.textDim, marginBottom: 4, paddingHorizontal: 6 }}>{title}</Text>
{children}
</View>
);
@@ -170,9 +167,9 @@ function Row({ t, label, sub, onClick }) {
const [hover, setHover] = useState(false);
return (
<View onClick={onClick} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
- style={{ paddingVertical: 4, paddingHorizontal: 6, borderRadius: 5, backgroundColor: hover ? t.hover : 'transparent' }}>
+ style={{ paddingVertical: 4, paddingHorizontal: 6, borderRadius: 6, backgroundColor: hover ? t.hover : 'transparent' }}>
<Text style={{ fontSize: 12, color: t.text, whiteSpace: 'nowrap' }}>{label.length > 34 ? `${label.slice(0, 33)}…` : label}</Text>
- {sub ? <Text style={small(t, { fontSize: 10 })}>{sub}</Text> : null}
+ {sub ? <Text style={small(t, { fontSize: 11 })}>{sub}</Text> : null}
</View>
);
}
@@ -189,7 +186,8 @@ export function Toolbelt({ t, wid, w, sid }) {
const sessions = w.tabs.flatMap((tab) => leaves(tab.root));
const quote = (s) => `'${s.replace(/'/g, "'\\''")}'`;
return (
- <View style={{ width: 230, padding: 10, backgroundColor: t.sidebarBg, overflow: 'hidden' }}>
+ <View style={{ width: 240, paddingHorizontal: 10, paddingVertical: 12, backgroundColor: t.sidebarBg, overflow: 'hidden' }}>
+ <Hairline edge="start" />
<Section t={t} title={tr('terminal.belt.jobs')}>
{sessions.map((s) => {
const info = term.info(s);
@@ -223,21 +221,21 @@ export function Toolbelt({ t, wid, w, sid }) {
{list.map((n, i) => (
<Row key={i} t={t} label={n} sub={tr('terminal.belt.noteHint')} onClick={() => notes.set((x) => x.filter((_, j) => j !== i))} />
))}
- <TextInput value={note} placeholder={tr('terminal.belt.addNote')} onChange={setNote} style={{ height: 26, marginTop: 4 }}
+ <TextInput value={note} placeholder={tr('terminal.belt.addNote')} onChange={setNote} style={{ marginTop: 6 }}
onSubmit={(v) => { if (v.trim()) notes.set((x) => [...x, v.trim()]); setNote(''); }} />
</Section>
</View>
);
}
-// ---- ventanas emergentes: autocompletar, historial de pegado, abrir rápido, título, compositor ----
+// ---- popups: autocomplete, paste history, quick open, title, composer ----
function Popup({ t, title, children, width = 380 }) {
return (
<View style={{ position: 'absolute', left: 0, right: 0, top: 50, alignItems: 'center' }}>
- <View style={{ width, padding: 10, borderRadius: 11, backgroundColor: t.windowBg, border: `1px solid ${t.separator}`,
+ <View style={{ width, padding: 12, borderRadius: 12, backgroundColor: t.windowBg, border: `1px solid ${t.separator}`,
boxShadow: '0 16px 40px rgba(0,0,0,0.45)' }}>
- <Text style={{ fontSize: 12, fontWeight: 700, color: t.textDim, marginBottom: 8 }}>{title}</Text>
+ <Text style={{ fontSize: 11, fontWeight: 600, color: t.textDim, marginBottom: 8, paddingHorizontal: 2 }}>{title}</Text>
{children}
</View>
</View>
@@ -248,16 +246,16 @@ function ListPopup({ t, title, items, sel, empty }) {
return (
<Popup t={t} title={title}>
{items.length ? items.slice(0, 12).map((it, i) => (
- <View key={i} style={{ paddingHorizontal: 8, paddingVertical: 4, borderRadius: 5, backgroundColor: i === sel ? t.accent : 'transparent' }}>
+ <View key={i} style={{ paddingHorizontal: 8, height: 24, justifyContent: 'center', borderRadius: 5, backgroundColor: i === sel ? t.accent : 'transparent' }}>
<Text style={{ fontSize: 12, color: i === sel ? '#fff' : t.text, whiteSpace: 'nowrap' }}>{it.length > 60 ? `${it.slice(0, 59)}…` : it}</Text>
</View>
)) : <Text style={small(t)}>{empty}</Text>}
- <Text style={small(t, { fontSize: 10, marginTop: 6 })}>{tr('terminal.popup.keys')}</Text>
+ <Text style={small(t, { fontSize: 11, marginTop: 8, paddingHorizontal: 2 })}>{tr('terminal.popup.keys')}</Text>
</Popup>
);
}
-// Teclas de las listas emergentes; devuelve true si las usó.
+// Keys of the popup lists; returns true if it used them.
export function popupKey(wid, w, sid, e) {
const p = w.popup;
if (!p || p.kind === 'quick' || p.kind === 'title' || p.kind === 'composer') return false;
@@ -312,7 +310,7 @@ function QuickOpen({ t, wid }) {
}} />
<View style={{ marginTop: 8 }}>
{items.slice(0, 10).map((x, i) => (
- <View key={x.s} onClick={() => pick(x)} style={{ paddingHorizontal: 8, paddingVertical: 4, borderRadius: 5,
+ <View key={x.s} onClick={() => pick(x)} style={{ paddingHorizontal: 8, height: 24, justifyContent: 'center', borderRadius: 5,
backgroundColor: i === sel ? t.accent : 'transparent' }}>
<Text style={{ fontSize: 12, color: i === sel ? '#fff' : t.text, whiteSpace: 'nowrap' }}>{x.title}</Text>
</View>
@@ -332,13 +330,13 @@ function EditTitle({ t, wid, tab }) {
);
}
-// Compositor: escribir un comando largo antes de mandarlo (como el de iTerm2).
+// Composer: write a long command before sending it (like iTerm2's).
function Composer({ t, wid, sid, w }) {
const [v, setV] = useState('');
return (
- <View style={{ position: 'absolute', left: 12, right: 12, bottom: 12, padding: 8, borderRadius: 10, backgroundColor: t.windowBg,
+ <View style={{ position: 'absolute', left: 12, right: 12, bottom: 12, padding: 10, borderRadius: 10, backgroundColor: t.windowBg,
border: `1px solid ${t.accent}`, boxShadow: '0 10px 30px rgba(0,0,0,0.4)' }}>
- <Text style={small(t, { fontSize: 10, marginBottom: 4 })}>
+ <Text style={small(t, { fontSize: 11, marginBottom: 6 })}>
{w.broadcast ? tr('terminal.composer.broadcast') : tr('terminal.composer.hint')}
</Text>
<TextInput value={v} autoFocus onChange={setV}
@@ -362,11 +360,11 @@ export function Overlays({ t, wid, w, sid, tab }) {
{w.dialog && (
<View style={{ position: 'absolute', left: 0, right: 0, top: 0, bottom: 0, alignItems: 'center', justifyContent: 'center',
backgroundColor: 'rgba(0,0,0,0.35)' }}>
- <View style={{ width: 340, padding: 18, borderRadius: 12, backgroundColor: t.windowBg, border: `1px solid ${t.separator}`,
+ <View style={{ width: 340, padding: 20, borderRadius: 12, backgroundColor: t.windowBg, border: `1px solid ${t.separator}`,
boxShadow: '0 20px 50px rgba(0,0,0,0.5)' }}>
- <Text style={{ fontSize: 14, fontWeight: 700, color: t.text }}>{w.dialog.text}</Text>
- <Text style={{ fontSize: 12, color: t.textDim, marginTop: 6, lineHeight: 1.4 }}>{w.dialog.detail}</Text>
- <View style={{ flexDirection: 'row', justifyContent: 'flex-end', gap: 8, marginTop: 16 }}>
+ <Text style={{ fontSize: 15, fontWeight: 600, color: t.text }}>{w.dialog.text}</Text>
+ <Text style={{ fontSize: 13, color: t.textDim, marginTop: 6, lineHeight: 1.4 }}>{w.dialog.detail}</Text>
+ <View style={{ flexDirection: 'row', justifyContent: 'flex-end', gap: 8, marginTop: 20 }}>
<Button label={tr('terminal.dialog.cancel')} onClick={() => patchWin(wid, () => ({ dialog: null }))} />
<Button label={tr('terminal.dialog.close')} primary onClick={() => { const fn = w.dialog.onConfirm; patchWin(wid, () => ({ dialog: null })); fn(); }} />
</View>
@@ -394,7 +392,7 @@ export function ReplayBar({ t, wid, replay }) {
const ago = Math.max(0, Math.round((Date.now() - replay.time) / 1000));
return (
<View style={{ height: 40, flexDirection: 'row', alignItems: 'center', gap: 12, paddingHorizontal: 12, backgroundColor: '#3a1d5c' }}>
- <Text style={{ fontSize: 12, fontWeight: 700, color: '#fff' }}>INSTANT REPLAY</Text>
+ <Text style={{ fontSize: 12, fontWeight: 600, color: '#fff' }}>Instant Replay</Text>
<Button label="◀" onClick={() => go(Math.max(0, replay.index - 1))} />
<Slider value={replay.index} min={0} max={Math.max(1, replay.count - 1)} width={300} onChange={go} />
<Button label="▶" onClick={() => go(Math.min(replay.count - 1, replay.index + 1))} />
@@ -405,10 +403,10 @@ export function ReplayBar({ t, wid, replay }) {
);
}
-// ---- menú contextual de un panel ----
+// ---- a pane's context menu ----
export function ContextMenu({ t, x, y, items, onClose }) {
- // ancho según el texto más largo (cambia con el idioma)
+ // width from the longest text (it changes with the language)
const width = Math.ceil(Math.max(230, ...items.filter((it) => it !== '-').map((it) =>
40 + lord.measureText(it.label, 13, 400) + (it.hint ? 16 + lord.measureText(it.hint, 11, 400) : 0))));
return (
diff --git a/assets/locales/en/apps.json b/assets/locales/en/apps.json
index 9d7649a..9b422f6 100644
--- a/assets/locales/en/apps.json
+++ b/assets/locales/en/apps.json
@@ -23,5 +23,8 @@
"logs": "Logs",
"disks": "Disks",
"backup": "Backups",
- "passwords": "Passwords"
+ "passwords": "Passwords",
+ "calendar": "Calendar",
+ "contacts": "Contacts",
+ "reminders": "Reminders"
}
diff --git a/assets/locales/en/calendar.json b/assets/locales/en/calendar.json
new file mode 100644
index 0000000..dc17af4
--- /dev/null
+++ b/assets/locales/en/calendar.json
@@ -0,0 +1,86 @@
+{
+ "add": "Add",
+ "alarm.open": "Open",
+ "alarm.snooze": "Snooze",
+ "alert": "Alert",
+ "alert.atTime": "At time of event",
+ "alert.dayBefore": "1 day before",
+ "alert.hourBefore": "1 hour before",
+ "alert.minutes": {
+ "one": "{count} minute before",
+ "other": "{count} minutes before"
+ },
+ "alert.none": "None",
+ "allDay": "All-day",
+ "calendar": "Calendar",
+ "calendarName": "Calendar name",
+ "cancel": "Cancel",
+ "color": "Color",
+ "create": "Create",
+ "defaultName": "Calendar",
+ "delete": "Delete",
+ "deleteAll": "Delete all events",
+ "deleteCalendar": "Delete calendar",
+ "deleteFailed": "The event could not be deleted.",
+ "deleteThis": "Delete this event only",
+ "editCalendar": "Edit calendar",
+ "ends": "Ends",
+ "hide": "Hide",
+ "invitees": {
+ "one": "{count} invitee",
+ "other": "{count} invitees"
+ },
+ "locationPlaceholder": "Add location",
+ "month.0": "January",
+ "month.1": "February",
+ "month.10": "November",
+ "month.11": "December",
+ "month.2": "March",
+ "month.3": "April",
+ "month.4": "May",
+ "month.5": "June",
+ "month.6": "July",
+ "month.7": "August",
+ "month.8": "September",
+ "month.9": "October",
+ "monthYear": "{month} {year}",
+ "more": {
+ "one": "{count} more",
+ "other": "{count} more"
+ },
+ "newCalendar": "New calendar",
+ "newEvent": "New event",
+ "next": "Next",
+ "noCalendars": "No calendars yet.",
+ "notesPlaceholder": "Add notes",
+ "onThisComputer": "On this computer",
+ "organizer": "Organizer",
+ "previous": "Previous",
+ "ps.accepted": "Accepted",
+ "ps.declined": "Declined",
+ "ps.delegated": "Delegated",
+ "ps.pending": "No reply",
+ "ps.tentative": "Maybe",
+ "repeat": "Repeat",
+ "repeat.custom": "Custom",
+ "repeat.daily": "Every day",
+ "repeat.monthly": "Every month",
+ "repeat.none": "Never",
+ "repeat.weekly": "Every week",
+ "repeat.yearly": "Every year",
+ "save": "Save",
+ "saveFailed": "Could not save. Try again.",
+ "seriesNote": "Changes apply to all events in the series.",
+ "show": "Show",
+ "starts": "Starts",
+ "timeRange": "{from} – {to}",
+ "titlePlaceholder": "New event",
+ "today": "Today",
+ "toggleSidebar": "Show or hide calendars",
+ "unavailable": "Calendars are not available",
+ "unavailableHint": "The mail and calendar service (lord-maild) is not running or not installed.",
+ "untitled": "New event",
+ "view.day": "Day",
+ "view.month": "Month",
+ "view.week": "Week"
+}
diff --git a/assets/locales/en/camera.json b/assets/locales/en/camera.json
index 9555269..b5ac3ee 100644
--- a/assets/locales/en/camera.json
+++ b/assets/locales/en/camera.json
@@ -7,5 +7,8 @@
"mirror": "Mirror",
"none": "No camera was found",
"denied": "Camera is not allowed to use the camera. Change it in Settings → Privacy.",
- "error": "Could not use the camera: {error}"
+ "error": "Could not use the camera: {error}",
+ "noneHint": "Plug in a USB camera: it shows up here on its own, without restarting the app.",
+ "deniedTitle": "No access to the camera",
+ "errorTitle": "The camera could not be opened"
}
diff --git a/assets/locales/en/characters.json b/assets/locales/en/characters.json
index 6872471..8b4e0a6 100644
--- a/assets/locales/en/characters.json
+++ b/assets/locales/en/characters.json
@@ -21,5 +21,7 @@
"block.greek": "Greek",
"block.latin1": "Latin accented",
"block.cjkSymbols": "CJK symbols",
- "block.halfwidth": "Fullwidth forms"
+ "block.halfwidth": "Fullwidth forms",
+ "pickTitle": "Choose a character",
+ "pickHint": "Click one to see its name and code point, and to copy it."
}
diff --git a/assets/locales/en/contacts.json b/assets/locales/en/contacts.json
new file mode 100644
index 0000000..61a44ef
--- /dev/null
+++ b/assets/locales/en/contacts.json
@@ -0,0 +1,71 @@
+{
+ "add.addrs": "add address",
+ "add.emails": "add email",
+ "add.phones": "add phone",
+ "add.urls": "add URL",
+ "addBirthday": "add birthday",
+ "allContacts": "All Contacts",
+ "birthday": "birthday",
+ "cancel": "Cancel",
+ "choosePhoto": "Choose photo…",
+ "city": "City",
+ "company": "Company",
+ "count": {
+ "one": "{n} contact",
+ "other": "{n} contacts"
+ },
+ "country": "Country",
+ "dayMonth": "{month} {day}",
+ "defaultBook": "Contacts",
+ "delete": "Delete",
+ "deleteContact": "Delete Contact",
+ "deleteGroup": "Delete group",
+ "deleteHint": "This cannot be undone.",
+ "deleteTitle": "Delete “{name}”?",
+ "done": "Done",
+ "edit": "Edit",
+ "editPhoto": "edit",
+ "family": "Last name",
+ "given": "First name",
+ "groupName": "Group name",
+ "groups": "Groups",
+ "import": "Import…",
+ "importFailed": "The file could not be imported.",
+ "importTitle": "Import contacts (.vcf)",
+ "imported": {
+ "one": "{n} contact imported.",
+ "other": "{n} contacts imported."
+ },
+ "jobTitle": "Job title",
+ "needName": "Add a name, a company or an email.",
+ "newContact": "New contact",
+ "newGroup": "New group",
+ "noContacts": "No contacts",
+ "noName": "No name",
+ "noResults": "No results",
+ "noSelection": "No contact selected",
+ "notes": "notes",
+ "ok": "OK",
+ "onThisComputer": "On this computer",
+ "photoChosen": "new photo",
+ "placeholder.addrs": "Address",
+ "placeholder.emails": "Email",
+ "placeholder.phones": "Phone",
+ "placeholder.urls": "Web page",
+ "postalCode": "ZIP",
+ "region": "State",
+ "removePhoto": "Remove photo",
+ "renameGroup": "Rename group",
+ "save": "Save",
+ "saveFailed": "Could not save",
+ "search": "Search",
+ "street": "Street",
+ "type.cell": "mobile",
+ "type.home": "home",
+ "type.main": "main",
+ "type.other": "other",
+ "type.work": "work",
+ "unavailable": "Contacts are not available",
+ "unavailableHint": "The mail and calendar service (lord-maild) is not running or not installed.",
+ "untitledGroup": "Untitled group"
+}
diff --git a/assets/locales/en/passwords.json b/assets/locales/en/passwords.json
index 36ea5f7..d1a0d67 100644
--- a/assets/locales/en/passwords.json
+++ b/assets/locales/en/passwords.json
@@ -205,8 +205,8 @@
"rotate.never": "Never",
"rotate.days": "Every {n} days",
"rotate.year": "Every year",
- "rotate.due": "Change it every {days} days: {left} left.",
- "rotate.overdue": "Change it every {days} days: overdue by {ago}.",
+ "rotate.due": "Change it every {days} days: {left} days left.",
+ "rotate.overdue": "Change it every {days} days: overdue by {ago} days.",
"totp.left": "{s} s",
"totp.code": "Code",
"totp.placeholder": "otpauth://… or the base32 secret",
diff --git a/assets/locales/en/player.json b/assets/locales/en/player.json
index 0b27aaa..741d3cf 100644
--- a/assets/locales/en/player.json
+++ b/assets/locales/en/player.json
@@ -25,5 +25,12 @@
"emptyMusic": "There is no music in the Music folder",
"emptyVideos": "There are no videos in the Videos folder",
"error": "Could not play: {error}",
- "crashed": "The decoder stopped unexpectedly; the rest of the desktop is fine"
+ "crashed": "The decoder stopped unexpectedly; the rest of the desktop is fine",
+ "col.title": "Title",
+ "col.artist": "Artist",
+ "col.album": "Album",
+ "col.time": "Time",
+ "back": "Back",
+ "emptyMusicTitle": "No music",
+ "emptyVideosTitle": "No videos"
}
diff --git a/assets/locales/en/prefs.json b/assets/locales/en/prefs.json
index 326e021..5d1780f 100644
--- a/assets/locales/en/prefs.json
+++ b/assets/locales/en/prefs.json
@@ -9,7 +9,7 @@
"bt.err.canceled": "Pairing was canceled.",
"bt.err.failed": "The device did not respond. Make sure it is on and nearby.",
"bt.err.noProfile": "Paired, but the device offers no service LordOS can connect to (audio, input).",
- "bt.forget": "Forget This Device…",
+ "bt.forget": "Forget",
"bt.more": "More",
"bt.myDevices": "My Devices",
"bt.nearby": "Nearby Devices",
@@ -80,6 +80,7 @@
"other": "Your display settings will go back to the previous ones in {count} seconds."
},
"display.keepTitle": "Keep these display settings?",
+ "display.looksLike": "looks like {w} × {h}",
"display.makeMain": "Use as Main Display",
"display.mirror": "Mirror",
"display.multiple": "Multiple displays",
@@ -96,7 +97,10 @@
"display.rotation": "Rotation",
"display.rotationHint": "A rotated screen is composed by the CPU.",
"display.scale": "Scale",
- "display.scaleHint": "Not available yet: the interface is drawn at 100% (see docs/SETTINGS.md). On large screens, choose a lower resolution.",
+ "display.scale100": "100 % (native)",
+ "display.scale200": "200 % (doubled)",
+ "display.scale2Hint": "The interface is drawn at half the resolution and doubled: larger, but text is not as sharp as at 100 %. Composed by the CPU.",
+ "display.scaleHint": "For high-density screens, 200 % draws the interface at half the resolution and doubles every pixel (composed by the CPU). True 125 %, 150 % and sharp 200 % text are not available yet (see docs/SETTINGS.md).",
"display.unavailable": "The display information is not available.",
"display.useAs": "Use as",
"night.custom": "Custom",
@@ -190,6 +194,7 @@
"power.offBattery": "Turn display off on battery when inactive",
"power.onACFull": "Connected to the power adapter",
"power.onBattery": "On battery",
+ "power.onPower": "Power adapter",
"power.powerKey": "When the power button is pressed",
"power.profile.balanced": "Balanced",
"power.profile.performance": "Performance",
diff --git a/assets/locales/en/recorder.json b/assets/locales/en/recorder.json
index 776272c..4929cb4 100644
--- a/assets/locales/en/recorder.json
+++ b/assets/locales/en/recorder.json
@@ -17,5 +17,6 @@
"working": "Exporting…",
"exported": "Saved “{name}”",
"exportError": "Could not export",
- "renameError": "Could not rename (does that name exist already?)"
+ "renameError": "Could not rename (does that name exist already?)",
+ "emptyTitle": "Pick or make a recording"
}
diff --git a/assets/locales/en/reminders.json b/assets/locales/en/reminders.json
new file mode 100644
index 0000000..c9fd394
--- /dev/null
+++ b/assets/locales/en/reminders.json
@@ -0,0 +1,46 @@
+{
+ "addList": "Add List",
+ "alarm.done": "Mark as done",
+ "cancel": "Cancel",
+ "color": "Color",
+ "completedOn": "Completed {date}",
+ "create": "Create",
+ "defaultList": "Reminders",
+ "delete": "Delete",
+ "deleteList": "Delete list",
+ "done": "Done",
+ "due": "Due",
+ "dueAt": "{date}, {time}",
+ "dueDate": "Date",
+ "dueNone": "None",
+ "dueTime": "Date & time",
+ "editList": "Edit list",
+ "empty": "No reminders",
+ "flagged": "Flagged",
+ "hideCompleted": "Hide completed",
+ "list": "List",
+ "listName": "List name",
+ "myLists": "My Lists",
+ "newList": "New list",
+ "newReminder": "New Reminder",
+ "noLists": "No lists yet.",
+ "notes": "Notes",
+ "nothingCompleted": "No completed reminders",
+ "overdue": "Overdue",
+ "prio.high": "High",
+ "prio.low": "Low",
+ "prio.medium": "Medium",
+ "prio.none": "None",
+ "priority": "Priority",
+ "save": "Save",
+ "saveFailed": "Could not save",
+ "showCompleted": "Show completed",
+ "smart.all": "All",
+ "smart.completed": "Completed",
+ "smart.flagged": "Flagged",
+ "smart.scheduled": "Scheduled",
+ "smart.today": "Today",
+ "unavailable": "Reminders are not available",
+ "unavailableHint": "The mail and calendar service (lord-maild) is not running or not installed.",
+ "untitled": "New Reminder"
+}
diff --git a/assets/locales/en/screenshots.json b/assets/locales/en/screenshots.json
index 356979d..59508bd 100644
--- a/assets/locales/en/screenshots.json
+++ b/assets/locales/en/screenshots.json
@@ -30,5 +30,10 @@
"done": "Done",
"textHint": "Type and press Enter",
"menu.window": "Privacy",
- "menu.protect": "Protect the front window from captures"
+ "menu.protect": "Protect the front window from captures",
+ "tool.arrow": "Arrow",
+ "tool.box": "Box",
+ "tool.text": "Text",
+ "tool.blur": "Blur",
+ "tool.line": "Line"
}
diff --git a/assets/locales/en/shell.json b/assets/locales/en/shell.json
index 9b3a6ef..34f9b26 100644
--- a/assets/locales/en/shell.json
+++ b/assets/locales/en/shell.json
@@ -115,5 +115,8 @@
"help.open": "LordOS Help",
"help.tour": "Welcome to LordOS",
"spotlight.section.help": "Help",
- "spotlight.inHelp": "Help article"
+ "spotlight.inHelp": "Help article",
+ "picker.cancel": "Cancel",
+ "picker.choose": "Choose ({n})",
+ "picker.empty": "No files here."
}
diff --git a/assets/locales/en/store.json b/assets/locales/en/store.json
index ae6b562..dcd1369 100644
--- a/assets/locales/en/store.json
+++ b/assets/locales/en/store.json
@@ -106,5 +106,6 @@
"manage.share": "Share my version",
"manage.noOriginal": "Installed before signing; no original kept",
"restore.done": "“{name}” restored to the original.",
- "share.done": "Signed package written to {path} (your key {key}…)"
+ "share.done": "Signed package written to {path} (your key {key}…)",
+ "debian.noIndexTitle": "The Debian catalog is missing"
}
diff --git a/assets/locales/en/terminal.json b/assets/locales/en/terminal.json
index 8bb03c6..c455cf9 100644
--- a/assets/locales/en/terminal.json
+++ b/assets/locales/en/terminal.json
@@ -304,5 +304,6 @@
"other": "{count} sessions restored after the server restarted"
},
"toast.saveFailed": "Could not save",
- "toast.saved": "Saved to {path}"
+ "toast.saved": "Saved to {path}",
+ "find.close": "Close find"
}
diff --git a/assets/locales/es/apps.json b/assets/locales/es/apps.json
index 1a6040d..4f779af 100644
--- a/assets/locales/es/apps.json
+++ b/assets/locales/es/apps.json
@@ -23,5 +23,8 @@
"logs": "Registros",
"disks": "Discos",
"backup": "Copias de seguridad",
- "passwords": "Contraseñas"
+ "passwords": "Contraseñas",
+ "calendar": "Calendario",
+ "contacts": "Contactos",
+ "reminders": "Recordatorios"
}
diff --git a/assets/locales/es/calendar.json b/assets/locales/es/calendar.json
new file mode 100644
index 0000000..6b35ba4
--- /dev/null
+++ b/assets/locales/es/calendar.json
@@ -0,0 +1,86 @@
+{
+ "add": "Agregar",
+ "alarm.open": "Abrir",
+ "alarm.snooze": "Posponer",
+ "alert": "Aviso",
+ "alert.atTime": "A la hora del evento",
+ "alert.dayBefore": "1 día antes",
+ "alert.hourBefore": "1 hora antes",
+ "alert.minutes": {
+ "one": "{count} minuto antes",
+ "other": "{count} minutos antes"
+ },
+ "alert.none": "Ninguno",
+ "allDay": "Todo el día",
+ "calendar": "Calendario",
+ "calendarName": "Nombre del calendario",
+ "cancel": "Cancelar",
+ "color": "Color",
+ "create": "Crear",
+ "defaultName": "Calendario",
+ "delete": "Eliminar",
+ "deleteAll": "Eliminar todos los eventos",
+ "deleteCalendar": "Eliminar calendario",
+ "deleteFailed": "No se pudo eliminar el evento.",
+ "deleteThis": "Eliminar solo este evento",
+ "editCalendar": "Editar calendario",
+ "ends": "Termina",
+ "hide": "Ocultar",
+ "invitees": {
+ "one": "{count} invitado",
+ "other": "{count} invitados"
+ },
+ "locationPlaceholder": "Agregar ubicación",
+ "month.0": "enero",
+ "month.1": "febrero",
+ "month.10": "noviembre",
+ "month.11": "diciembre",
+ "month.2": "marzo",
+ "month.3": "abril",
+ "month.4": "mayo",
+ "month.5": "junio",
+ "month.6": "julio",
+ "month.7": "agosto",
+ "month.8": "septiembre",
+ "month.9": "octubre",
+ "monthYear": "{month} de {year}",
+ "more": {
+ "one": "{count} más",
+ "other": "{count} más"
+ },
+ "newCalendar": "Nuevo calendario",
+ "newEvent": "Nuevo evento",
+ "next": "Siguiente",
+ "noCalendars": "Todavía no hay calendarios.",
+ "notesPlaceholder": "Agregar notas",
+ "onThisComputer": "En esta computadora",
+ "organizer": "Organizador",
+ "previous": "Anterior",
+ "ps.accepted": "Aceptó",
+ "ps.declined": "Rechazó",
+ "ps.delegated": "Delegó",
+ "ps.pending": "Sin respuesta",
+ "ps.tentative": "Tal vez",
+ "repeat": "Repetir",
+ "repeat.custom": "Personalizado",
+ "repeat.daily": "Todos los días",
+ "repeat.monthly": "Todos los meses",
+ "repeat.none": "Nunca",
+ "repeat.weekly": "Todas las semanas",
+ "repeat.yearly": "Todos los años",
+ "save": "Guardar",
+ "saveFailed": "No se pudo guardar. Probá de nuevo.",
+ "seriesNote": "Los cambios se aplican a todos los eventos de la serie.",
+ "show": "Mostrar",
+ "starts": "Empieza",
+ "timeRange": "{from} – {to}",
+ "titlePlaceholder": "Nuevo evento",
+ "today": "Hoy",
+ "toggleSidebar": "Mostrar u ocultar los calendarios",
+ "unavailable": "Los calendarios no están disponibles",
+ "unavailableHint": "El servicio de correo y calendario (lord-maild) no está en marcha o no está instalado.",
+ "untitled": "Nuevo evento",
+ "view.day": "Día",
+ "view.month": "Mes",
+ "view.week": "Semana"
+}
diff --git a/assets/locales/es/camera.json b/assets/locales/es/camera.json
index 11d926e..27b0da3 100644
--- a/assets/locales/es/camera.json
+++ b/assets/locales/es/camera.json
@@ -7,5 +7,8 @@
"mirror": "Espejo",
"none": "No se encontró ninguna cámara",
"denied": "Cámara no tiene permiso para usar la cámara. Cambialo en Ajustes → Privacidad.",
- "error": "No se pudo usar la cámara: {error}"
+ "error": "No se pudo usar la cámara: {error}",
+ "noneHint": "Conectá una cámara USB: aparece acá sola, sin reiniciar la app.",
+ "deniedTitle": "Sin permiso para la cámara",
+ "errorTitle": "No se pudo abrir la cámara"
}
diff --git a/assets/locales/es/characters.json b/assets/locales/es/characters.json
index 22d7c4f..a296f56 100644
--- a/assets/locales/es/characters.json
+++ b/assets/locales/es/characters.json
@@ -21,5 +21,7 @@
"block.greek": "Griego",
"block.latin1": "Latín acentuado",
"block.cjkSymbols": "Signos CJK",
- "block.halfwidth": "Ancho completo"
+ "block.halfwidth": "Ancho completo",
+ "pickTitle": "Elegí un carácter",
+ "pickHint": "Hacé clic en uno para ver su nombre y su código, y copiarlo."
}
diff --git a/assets/locales/es/contacts.json b/assets/locales/es/contacts.json
new file mode 100644
index 0000000..bab632c
--- /dev/null
+++ b/assets/locales/es/contacts.json
@@ -0,0 +1,71 @@
+{
+ "add.addrs": "agregar dirección",
+ "add.emails": "agregar correo",
+ "add.phones": "agregar teléfono",
+ "add.urls": "agregar URL",
+ "addBirthday": "agregar cumpleaños",
+ "allContacts": "Todos los contactos",
+ "birthday": "cumpleaños",
+ "cancel": "Cancelar",
+ "choosePhoto": "Elegir foto…",
+ "city": "Ciudad",
+ "company": "Empresa",
+ "count": {
+ "one": "{n} contacto",
+ "other": "{n} contactos"
+ },
+ "country": "País",
+ "dayMonth": "{day} de {month}",
+ "defaultBook": "Contactos",
+ "delete": "Eliminar",
+ "deleteContact": "Eliminar contacto",
+ "deleteGroup": "Eliminar grupo",
+ "deleteHint": "Esto no se puede deshacer.",
+ "deleteTitle": "¿Eliminar «{name}»?",
+ "done": "Listo",
+ "edit": "Editar",
+ "editPhoto": "editar",
+ "family": "Apellido",
+ "given": "Nombre",
+ "groupName": "Nombre del grupo",
+ "groups": "Grupos",
+ "import": "Importar…",
+ "importFailed": "No se pudo importar el archivo.",
+ "importTitle": "Importar contactos (.vcf)",
+ "imported": {
+ "one": "Se importó {n} contacto.",
+ "other": "Se importaron {n} contactos."
+ },
+ "jobTitle": "Cargo",
+ "needName": "Agregá un nombre, una empresa o un correo.",
+ "newContact": "Nuevo contacto",
+ "newGroup": "Nuevo grupo",
+ "noContacts": "Sin contactos",
+ "noName": "Sin nombre",
+ "noResults": "Sin resultados",
+ "noSelection": "Ningún contacto seleccionado",
+ "notes": "notas",
+ "ok": "Aceptar",
+ "onThisComputer": "En esta computadora",
+ "photoChosen": "foto nueva",
+ "placeholder.addrs": "Dirección",
+ "placeholder.emails": "Correo",
+ "placeholder.phones": "Teléfono",
+ "placeholder.urls": "Página web",
+ "postalCode": "Código postal",
+ "region": "Provincia",
+ "removePhoto": "Quitar foto",
+ "renameGroup": "Renombrar grupo",
+ "save": "Guardar",
+ "saveFailed": "No se pudo guardar",
+ "search": "Buscar",
+ "street": "Calle",
+ "type.cell": "celular",
+ "type.home": "casa",
+ "type.main": "principal",
+ "type.other": "otro",
+ "type.work": "trabajo",
+ "unavailable": "Los contactos no están disponibles",
+ "unavailableHint": "El servicio de correo y calendario (lord-maild) no está en marcha o no está instalado.",
+ "untitledGroup": "Grupo sin nombre"
+}
diff --git a/assets/locales/es/passwords.json b/assets/locales/es/passwords.json
index 7c193ce..77e5480 100644
--- a/assets/locales/es/passwords.json
+++ b/assets/locales/es/passwords.json
@@ -205,8 +205,8 @@
"rotate.never": "Nunca",
"rotate.days": "Cada {n} días",
"rotate.year": "Cada año",
- "rotate.due": "Cambiarla cada {days} días: faltan {left}.",
- "rotate.overdue": "Cambiarla cada {days} días: venció hace {ago}.",
+ "rotate.due": "Cambiarla cada {days} días: faltan {left} días.",
+ "rotate.overdue": "Cambiarla cada {days} días: venció hace {ago} días.",
"totp.left": "{s} s",
"totp.code": "Código",
"totp.placeholder": "otpauth://… o el secreto en base32",
diff --git a/assets/locales/es/player.json b/assets/locales/es/player.json
index fa38305..cebdab9 100644
--- a/assets/locales/es/player.json
+++ b/assets/locales/es/player.json
@@ -25,5 +25,12 @@
"emptyMusic": "No hay música en la carpeta Música",
"emptyVideos": "No hay videos en la carpeta Videos",
"error": "No se pudo reproducir: {error}",
- "crashed": "El decodificador se cerró de golpe; el resto del escritorio sigue bien"
+ "crashed": "El decodificador se cerró de golpe; el resto del escritorio sigue bien",
+ "col.title": "Título",
+ "col.artist": "Artista",
+ "col.album": "Álbum",
+ "col.time": "Duración",
+ "back": "Atrás",
+ "emptyMusicTitle": "Sin música",
+ "emptyVideosTitle": "Sin videos"
}
diff --git a/assets/locales/es/prefs.json b/assets/locales/es/prefs.json
index c3a0b3e..3d75d1c 100644
--- a/assets/locales/es/prefs.json
+++ b/assets/locales/es/prefs.json
@@ -9,7 +9,7 @@
"bt.err.canceled": "Se canceló la vinculación.",
"bt.err.failed": "El dispositivo no respondió. Fijate que esté encendido y cerca.",
"bt.err.noProfile": "Vinculado, pero el dispositivo no ofrece ningún servicio que LordOS pueda conectar (audio, entrada).",
- "bt.forget": "Olvidar este dispositivo…",
+ "bt.forget": "Olvidar",
"bt.more": "Más",
"bt.myDevices": "Mis dispositivos",
"bt.nearby": "Dispositivos cercanos",
@@ -80,6 +80,7 @@
"other": "La pantalla vuelve a la configuración anterior en {count} segundos."
},
"display.keepTitle": "¿Mantener esta configuración de pantalla?",
+ "display.looksLike": "se ve como {w} × {h}",
"display.makeMain": "Usar como principal",
"display.mirror": "Duplicar",
"display.multiple": "Varias pantallas",
@@ -96,7 +97,10 @@
"display.rotation": "Rotación",
"display.rotationHint": "Con la pantalla girada se compone por CPU.",
"display.scale": "Escala",
- "display.scaleHint": "Todavía no está disponible: la interfaz se dibuja al 100 % (ver docs/SETTINGS.md). En pantallas grandes, elegí una resolución menor.",
+ "display.scale100": "100 % (nativa)",
+ "display.scale200": "200 % (duplicada)",
+ "display.scale2Hint": "La interfaz se dibuja a la mitad de la resolución y se duplica: más grande, pero el texto no es tan nítido como al 100 %. Compone la CPU.",
+ "display.scaleHint": "Para pantallas de alta densidad, 200 % dibuja la interfaz a la mitad de la resolución y duplica cada píxel (compone la CPU). Todavía no hay 125 %, 150 % ni un 200 % con texto nítido (ver docs/SETTINGS.md).",
"display.unavailable": "No hay información de las pantallas.",
"display.useAs": "Usar como",
"night.custom": "Personalizado",
@@ -190,6 +194,7 @@
"power.offBattery": "Apagar la pantalla con batería si está inactiva",
"power.onACFull": "Conectado al cargador",
"power.onBattery": "Con batería",
+ "power.onPower": "Corriente eléctrica",
"power.powerKey": "Al apretar el botón de encendido",
"power.profile.balanced": "Equilibrado",
"power.profile.performance": "Rendimiento",
diff --git a/assets/locales/es/recorder.json b/assets/locales/es/recorder.json
index 97019eb..6e70892 100644
--- a/assets/locales/es/recorder.json
+++ b/assets/locales/es/recorder.json
@@ -17,5 +17,6 @@
"working": "Exportando…",
"exported": "Se guardó «{name}»",
"exportError": "No se pudo exportar",
- "renameError": "No se pudo renombrar (¿ya existe ese nombre?)"
+ "renameError": "No se pudo renombrar (¿ya existe ese nombre?)",
+ "emptyTitle": "Elegí o hacé una grabación"
}
diff --git a/assets/locales/es/reminders.json b/assets/locales/es/reminders.json
new file mode 100644
index 0000000..c092004
--- /dev/null
+++ b/assets/locales/es/reminders.json
@@ -0,0 +1,46 @@
+{
+ "addList": "Agregar lista",
+ "alarm.done": "Marcar como hecho",
+ "cancel": "Cancelar",
+ "color": "Color",
+ "completedOn": "Completado el {date}",
+ "create": "Crear",
+ "defaultList": "Recordatorios",
+ "delete": "Eliminar",
+ "deleteList": "Eliminar lista",
+ "done": "Listo",
+ "due": "Fecha",
+ "dueAt": "{date}, {time}",
+ "dueDate": "Fecha",
+ "dueNone": "Ninguna",
+ "dueTime": "Fecha y hora",
+ "editList": "Editar lista",
+ "empty": "Sin recordatorios",
+ "flagged": "Con bandera",
+ "hideCompleted": "Ocultar completados",
+ "list": "Lista",
+ "listName": "Nombre de la lista",
+ "myLists": "Mis listas",
+ "newList": "Nueva lista",
+ "newReminder": "Nuevo recordatorio",
+ "noLists": "Todavía no hay listas.",
+ "notes": "Notas",
+ "nothingCompleted": "No hay recordatorios completados",
+ "overdue": "Vencidos",
+ "prio.high": "Alta",
+ "prio.low": "Baja",
+ "prio.medium": "Media",
+ "prio.none": "Ninguna",
+ "priority": "Prioridad",
+ "save": "Guardar",
+ "saveFailed": "No se pudo guardar",
+ "showCompleted": "Mostrar completados",
+ "smart.all": "Todos",
+ "smart.completed": "Completados",
+ "smart.flagged": "Con bandera",
+ "smart.scheduled": "Programados",
+ "smart.today": "Hoy",
+ "unavailable": "Los recordatorios no están disponibles",
+ "unavailableHint": "El servicio de correo y calendario (lord-maild) no está en marcha o no está instalado.",
+ "untitled": "Nuevo recordatorio"
+}
diff --git a/assets/locales/es/screenshots.json b/assets/locales/es/screenshots.json
index 6c80323..b2cb2fe 100644
--- a/assets/locales/es/screenshots.json
+++ b/assets/locales/es/screenshots.json
@@ -30,5 +30,10 @@
"done": "Listo",
"textHint": "Escribí y apretá Enter",
"menu.window": "Privacidad",
- "menu.protect": "Proteger la ventana del frente de las capturas"
+ "menu.protect": "Proteger la ventana del frente de las capturas",
+ "tool.arrow": "Flecha",
+ "tool.box": "Recuadro",
+ "tool.text": "Texto",
+ "tool.blur": "Desenfocar",
+ "tool.line": "Línea"
}
diff --git a/assets/locales/es/shell.json b/assets/locales/es/shell.json
index 8d31bd0..b57f75b 100644
--- a/assets/locales/es/shell.json
+++ b/assets/locales/es/shell.json
@@ -115,5 +115,8 @@
"help.open": "Ayuda de LordOS",
"help.tour": "Bienvenido a LordOS",
"spotlight.section.help": "Ayuda",
- "spotlight.inHelp": "Artículo de ayuda"
+ "spotlight.inHelp": "Artículo de ayuda",
+ "picker.cancel": "Cancelar",
+ "picker.choose": "Elegir ({n})",
+ "picker.empty": "No hay archivos acá."
}
diff --git a/assets/locales/es/store.json b/assets/locales/es/store.json
index 7ad55be..0547070 100644
--- a/assets/locales/es/store.json
+++ b/assets/locales/es/store.json
@@ -106,5 +106,6 @@
"manage.share": "Compartir mi versión",
"manage.noOriginal": "Instalada antes de la firma; no se guardó el original",
"restore.done": "«{name}» restaurada al original.",
- "share.done": "Paquete firmado escrito en {path} (tu clave {key}…)"
+ "share.done": "Paquete firmado escrito en {path} (tu clave {key}…)",
+ "debian.noIndexTitle": "Falta el catálogo de Debian"
}
diff --git a/assets/locales/es/terminal.json b/assets/locales/es/terminal.json
index 9ff6718..5ef40ba 100644
--- a/assets/locales/es/terminal.json
+++ b/assets/locales/es/terminal.json
@@ -304,5 +304,6 @@
"other": "{count} sesiones recuperadas tras reiniciar el servidor"
},
"toast.saveFailed": "No se pudo guardar",
- "toast.saved": "Guardado en {path}"
+ "toast.saved": "Guardado en {path}",
+ "find.close": "Cerrar la búsqueda"
}
diff --git a/assets/locales/pt/apps.json b/assets/locales/pt/apps.json
index 2f826d6..4697df4 100644
--- a/assets/locales/pt/apps.json
+++ b/assets/locales/pt/apps.json
@@ -23,5 +23,8 @@
"logs": "Registros",
"disks": "Discos",
"backup": "Cópias de segurança",
- "passwords": "Senhas"
+ "passwords": "Senhas",
+ "calendar": "Calendário",
+ "contacts": "Contatos",
+ "reminders": "Lembretes"
}
diff --git a/assets/locales/pt/calendar.json b/assets/locales/pt/calendar.json
new file mode 100644
index 0000000..cdc53ca
--- /dev/null
+++ b/assets/locales/pt/calendar.json
@@ -0,0 +1,86 @@
+{
+ "add": "Adicionar",
+ "alarm.open": "Abrir",
+ "alarm.snooze": "Adiar",
+ "alert": "Alerta",
+ "alert.atTime": "Na hora do evento",
+ "alert.dayBefore": "1 dia antes",
+ "alert.hourBefore": "1 hora antes",
+ "alert.minutes": {
+ "one": "{count} minuto antes",
+ "other": "{count} minutos antes"
+ },
+ "alert.none": "Nenhum",
+ "allDay": "Dia inteiro",
+ "calendar": "Calendário",
+ "calendarName": "Nome do calendário",
+ "cancel": "Cancelar",
+ "color": "Cor",
+ "create": "Criar",
+ "defaultName": "Calendário",
+ "delete": "Apagar",
+ "deleteAll": "Apagar todos os eventos",
+ "deleteCalendar": "Apagar calendário",
+ "deleteFailed": "Não foi possível apagar o evento.",
+ "deleteThis": "Apagar só este evento",
+ "editCalendar": "Editar calendário",
+ "ends": "Termina",
+ "hide": "Ocultar",
+ "invitees": {
+ "one": "{count} convidado",
+ "other": "{count} convidados"
+ },
+ "locationPlaceholder": "Adicionar local",
+ "month.0": "janeiro",
+ "month.1": "fevereiro",
+ "month.10": "novembro",
+ "month.11": "dezembro",
+ "month.2": "março",
+ "month.3": "abril",
+ "month.4": "maio",
+ "month.5": "junho",
+ "month.6": "julho",
+ "month.7": "agosto",
+ "month.8": "setembro",
+ "month.9": "outubro",
+ "monthYear": "{month} de {year}",
+ "more": {
+ "one": "mais {count}",
+ "other": "mais {count}"
+ },
+ "newCalendar": "Novo calendário",
+ "newEvent": "Novo evento",
+ "next": "Próximo",
+ "noCalendars": "Ainda não há calendários.",
+ "notesPlaceholder": "Adicionar notas",
+ "onThisComputer": "Neste computador",
+ "organizer": "Organizador",
+ "previous": "Anterior",
+ "ps.accepted": "Aceitou",
+ "ps.declined": "Recusou",
+ "ps.delegated": "Delegou",
+ "ps.pending": "Sem resposta",
+ "ps.tentative": "Talvez",
+ "repeat": "Repetir",
+ "repeat.custom": "Personalizado",
+ "repeat.daily": "Todos os dias",
+ "repeat.monthly": "Todos os meses",
+ "repeat.none": "Nunca",
+ "repeat.weekly": "Todas as semanas",
+ "repeat.yearly": "Todos os anos",
+ "save": "Salvar",
+ "saveFailed": "Não foi possível salvar. Tente de novo.",
+ "seriesNote": "As alterações valem para todos os eventos da série.",
+ "show": "Mostrar",
+ "starts": "Começa",
+ "timeRange": "{from} – {to}",
+ "titlePlaceholder": "Novo evento",
+ "today": "Hoje",
+ "toggleSidebar": "Mostrar ou ocultar os calendários",
+ "unavailable": "Os calendários não estão disponíveis",
+ "unavailableHint": "O serviço de e-mail e calendário (lord-maild) não está em execução ou não está instalado.",
+ "untitled": "Novo evento",
+ "view.day": "Dia",
+ "view.month": "Mês",
+ "view.week": "Semana"
+}
diff --git a/assets/locales/pt/camera.json b/assets/locales/pt/camera.json
index d62da92..5540774 100644
--- a/assets/locales/pt/camera.json
+++ b/assets/locales/pt/camera.json
@@ -7,5 +7,8 @@
"mirror": "Espelho",
"none": "Nenhuma câmera foi encontrada",
"denied": "A Câmera não tem permissão para usar a câmera. Mude isso em Ajustes → Privacidade.",
- "error": "Não foi possível usar a câmera: {error}"
+ "error": "Não foi possível usar a câmera: {error}",
+ "noneHint": "Conecte uma câmera USB: ela aparece aqui sozinha, sem reiniciar o app.",
+ "deniedTitle": "Sem permissão para a câmera",
+ "errorTitle": "Não foi possível abrir a câmera"
}
diff --git a/assets/locales/pt/characters.json b/assets/locales/pt/characters.json
index 1dc58a0..ce57ce8 100644
--- a/assets/locales/pt/characters.json
+++ b/assets/locales/pt/characters.json
@@ -21,5 +21,7 @@
"block.greek": "Grego",
"block.latin1": "Latim acentuado",
"block.cjkSymbols": "Símbolos CJK",
- "block.halfwidth": "Largura total"
+ "block.halfwidth": "Largura total",
+ "pickTitle": "Escolha um caractere",
+ "pickHint": "Clique em um para ver o nome e o código e copiá-lo."
}
diff --git a/assets/locales/pt/contacts.json b/assets/locales/pt/contacts.json
new file mode 100644
index 0000000..806b921
--- /dev/null
+++ b/assets/locales/pt/contacts.json
@@ -0,0 +1,71 @@
+{
+ "add.addrs": "adicionar endereço",
+ "add.emails": "adicionar e-mail",
+ "add.phones": "adicionar telefone",
+ "add.urls": "adicionar URL",
+ "addBirthday": "adicionar aniversário",
+ "allContacts": "Todos os contatos",
+ "birthday": "aniversário",
+ "cancel": "Cancelar",
+ "choosePhoto": "Escolher foto…",
+ "city": "Cidade",
+ "company": "Empresa",
+ "count": {
+ "one": "{n} contato",
+ "other": "{n} contatos"
+ },
+ "country": "País",
+ "dayMonth": "{day} de {month}",
+ "defaultBook": "Contatos",
+ "delete": "Apagar",
+ "deleteContact": "Apagar contato",
+ "deleteGroup": "Apagar grupo",
+ "deleteHint": "Isso não pode ser desfeito.",
+ "deleteTitle": "Apagar “{name}”?",
+ "done": "OK",
+ "edit": "Editar",
+ "editPhoto": "editar",
+ "family": "Sobrenome",
+ "given": "Nome",
+ "groupName": "Nome do grupo",
+ "groups": "Grupos",
+ "import": "Importar…",
+ "importFailed": "Não foi possível importar o arquivo.",
+ "importTitle": "Importar contatos (.vcf)",
+ "imported": {
+ "one": "{n} contato importado.",
+ "other": "{n} contatos importados."
+ },
+ "jobTitle": "Cargo",
+ "needName": "Adicione um nome, uma empresa ou um e-mail.",
+ "newContact": "Novo contato",
+ "newGroup": "Novo grupo",
+ "noContacts": "Sem contatos",
+ "noName": "Sem nome",
+ "noResults": "Sem resultados",
+ "noSelection": "Nenhum contato selecionado",
+ "notes": "notas",
+ "ok": "OK",
+ "onThisComputer": "Neste computador",
+ "photoChosen": "foto nova",
+ "placeholder.addrs": "Endereço",
+ "placeholder.emails": "E-mail",
+ "placeholder.phones": "Telefone",
+ "placeholder.urls": "Página web",
+ "postalCode": "CEP",
+ "region": "Estado",
+ "removePhoto": "Remover foto",
+ "renameGroup": "Renomear grupo",
+ "save": "Salvar",
+ "saveFailed": "Não foi possível salvar",
+ "search": "Buscar",
+ "street": "Rua",
+ "type.cell": "celular",
+ "type.home": "casa",
+ "type.main": "principal",
+ "type.other": "outro",
+ "type.work": "trabalho",
+ "unavailable": "Os contatos não estão disponíveis",
+ "unavailableHint": "O serviço de e-mail e calendário (lord-maild) não está em execução ou não está instalado.",
+ "untitledGroup": "Grupo sem nome"
+}
diff --git a/assets/locales/pt/passwords.json b/assets/locales/pt/passwords.json
index b823923..06cf5a4 100644
--- a/assets/locales/pt/passwords.json
+++ b/assets/locales/pt/passwords.json
@@ -205,8 +205,8 @@
"rotate.never": "Nunca",
"rotate.days": "A cada {n} dias",
"rotate.year": "Todo ano",
- "rotate.due": "Trocar a cada {days} dias: faltam {left}.",
- "rotate.overdue": "Trocar a cada {days} dias: venceu há {ago}.",
+ "rotate.due": "Trocar a cada {days} dias: faltam {left} dias.",
+ "rotate.overdue": "Trocar a cada {days} dias: venceu há {ago} dias.",
"totp.left": "{s} s",
"totp.code": "Código",
"totp.placeholder": "otpauth://… ou o segredo em base32",
diff --git a/assets/locales/pt/player.json b/assets/locales/pt/player.json
index d8c6e83..d151063 100644
--- a/assets/locales/pt/player.json
+++ b/assets/locales/pt/player.json
@@ -25,5 +25,12 @@
"emptyMusic": "Não há músicas na pasta Música",
"emptyVideos": "Não há vídeos na pasta Vídeos",
"error": "Não foi possível reproduzir: {error}",
- "crashed": "O decodificador parou de repente; o resto da área de trabalho está bem"
+ "crashed": "O decodificador parou de repente; o resto da área de trabalho está bem",
+ "col.title": "Título",
+ "col.artist": "Artista",
+ "col.album": "Álbum",
+ "col.time": "Duração",
+ "back": "Voltar",
+ "emptyMusicTitle": "Sem música",
+ "emptyVideosTitle": "Sem vídeos"
}
diff --git a/assets/locales/pt/prefs.json b/assets/locales/pt/prefs.json
index 7b25d58..598852f 100644
--- a/assets/locales/pt/prefs.json
+++ b/assets/locales/pt/prefs.json
@@ -9,7 +9,7 @@
"bt.err.canceled": "O pareamento foi cancelado.",
"bt.err.failed": "O dispositivo não respondeu. Verifique se está ligado e por perto.",
"bt.err.noProfile": "Pareado, mas o dispositivo não oferece nenhum serviço que o LordOS possa conectar (áudio, entrada).",
- "bt.forget": "Esquecer este dispositivo…",
+ "bt.forget": "Esquecer",
"bt.more": "Mais",
"bt.myDevices": "Meus dispositivos",
"bt.nearby": "Dispositivos próximos",
@@ -80,6 +80,7 @@
"other": "A tela volta à configuração anterior em {count} segundos."
},
"display.keepTitle": "Manter esta configuração de tela?",
+ "display.looksLike": "parece {w} × {h}",
"display.makeMain": "Usar como principal",
"display.mirror": "Espelhar",
"display.multiple": "Várias telas",
@@ -96,7 +97,10 @@
"display.rotation": "Rotação",
"display.rotationHint": "Com a tela girada, a composição é feita pela CPU.",
"display.scale": "Escala",
- "display.scaleHint": "Ainda não disponível: a interface é desenhada a 100% (veja docs/SETTINGS.md). Em telas grandes, escolha uma resolução menor.",
+ "display.scale100": "100 % (nativa)",
+ "display.scale200": "200 % (duplicada)",
+ "display.scale2Hint": "A interface é desenhada na metade da resolução e duplicada: maior, mas o texto não fica tão nítido quanto a 100 %. Composição pela CPU.",
+ "display.scaleHint": "Para telas de alta densidade, 200 % desenha a interface na metade da resolução e duplica cada pixel (composição pela CPU). Ainda não há 125 %, 150 % nem 200 % com texto nítido (veja docs/SETTINGS.md).",
"display.unavailable": "Não há informação das telas.",
"display.useAs": "Usar como",
"night.custom": "Personalizado",
@@ -190,6 +194,7 @@
"power.offBattery": "Desligar a tela na bateria quando inativa",
"power.onACFull": "Conectado ao carregador",
"power.onBattery": "Na bateria",
+ "power.onPower": "Energia da tomada",
"power.powerKey": "Ao pressionar o botão liga/desliga",
"power.profile.balanced": "Equilibrado",
"power.profile.performance": "Desempenho",
diff --git a/assets/locales/pt/recorder.json b/assets/locales/pt/recorder.json
index 662beba..6614b88 100644
--- a/assets/locales/pt/recorder.json
+++ b/assets/locales/pt/recorder.json
@@ -17,5 +17,6 @@
"working": "Exportando…",
"exported": "“{name}” foi salvo",
"exportError": "Não foi possível exportar",
- "renameError": "Não foi possível renomear (esse nome já existe?)"
+ "renameError": "Não foi possível renomear (esse nome já existe?)",
+ "emptyTitle": "Escolha ou faça uma gravação"
}
diff --git a/assets/locales/pt/reminders.json b/assets/locales/pt/reminders.json
new file mode 100644
index 0000000..e7d38f5
--- /dev/null
+++ b/assets/locales/pt/reminders.json
@@ -0,0 +1,46 @@
+{
+ "addList": "Adicionar lista",
+ "alarm.done": "Marcar como feito",
+ "cancel": "Cancelar",
+ "color": "Cor",
+ "completedOn": "Concluído em {date}",
+ "create": "Criar",
+ "defaultList": "Lembretes",
+ "delete": "Apagar",
+ "deleteList": "Apagar lista",
+ "done": "OK",
+ "due": "Data",
+ "dueAt": "{date}, {time}",
+ "dueDate": "Data",
+ "dueNone": "Nenhuma",
+ "dueTime": "Data e hora",
+ "editList": "Editar lista",
+ "empty": "Sem lembretes",
+ "flagged": "Sinalizado",
+ "hideCompleted": "Ocultar concluídos",
+ "list": "Lista",
+ "listName": "Nome da lista",
+ "myLists": "Minhas listas",
+ "newList": "Nova lista",
+ "newReminder": "Novo lembrete",
+ "noLists": "Ainda não há listas.",
+ "notes": "Notas",
+ "nothingCompleted": "Não há lembretes concluídos",
+ "overdue": "Atrasados",
+ "prio.high": "Alta",
+ "prio.low": "Baixa",
+ "prio.medium": "Média",
+ "prio.none": "Nenhuma",
+ "priority": "Prioridade",
+ "save": "Salvar",
+ "saveFailed": "Não foi possível salvar",
+ "showCompleted": "Mostrar concluídos",
+ "smart.all": "Todos",
+ "smart.completed": "Concluídos",
+ "smart.flagged": "Sinalizados",
+ "smart.scheduled": "Agendados",
+ "smart.today": "Hoje",
+ "unavailable": "Os lembretes não estão disponíveis",
+ "unavailableHint": "O serviço de e-mail e calendário (lord-maild) não está em execução ou não está instalado.",
+ "untitled": "Novo lembrete"
+}
diff --git a/assets/locales/pt/screenshots.json b/assets/locales/pt/screenshots.json
index 65dcb37..72785db 100644
--- a/assets/locales/pt/screenshots.json
+++ b/assets/locales/pt/screenshots.json
@@ -30,5 +30,10 @@
"done": "Pronto",
"textHint": "Digite e tecle Enter",
"menu.window": "Privacidade",
- "menu.protect": "Proteger a janela da frente das capturas"
+ "menu.protect": "Proteger a janela da frente das capturas",
+ "tool.arrow": "Seta",
+ "tool.box": "Retângulo",
+ "tool.text": "Texto",
+ "tool.blur": "Desfocar",
+ "tool.line": "Linha"
}
diff --git a/assets/locales/pt/shell.json b/assets/locales/pt/shell.json
index edd739a..e039970 100644
--- a/assets/locales/pt/shell.json
+++ b/assets/locales/pt/shell.json
@@ -115,5 +115,8 @@
"help.open": "Ajuda do LordOS",
"help.tour": "Bem-vindo ao LordOS",
"spotlight.section.help": "Ajuda",
- "spotlight.inHelp": "Artigo de ajuda"
+ "spotlight.inHelp": "Artigo de ajuda",
+ "picker.cancel": "Cancelar",
+ "picker.choose": "Escolher ({n})",
+ "picker.empty": "Não há arquivos aqui."
}
diff --git a/assets/locales/pt/store.json b/assets/locales/pt/store.json
index 750a463..3a162f7 100644
--- a/assets/locales/pt/store.json
+++ b/assets/locales/pt/store.json
@@ -106,5 +106,6 @@
"manage.share": "Compartilhar minha versão",
"manage.noOriginal": "Instalada antes da assinatura; sem original guardado",
"restore.done": "“{name}” restaurada ao original.",
- "share.done": "Pacote assinado escrito em {path} (sua chave {key}…)"
+ "share.done": "Pacote assinado escrito em {path} (sua chave {key}…)",
+ "debian.noIndexTitle": "Falta o catálogo do Debian"
}
diff --git a/assets/locales/pt/terminal.json b/assets/locales/pt/terminal.json
index 0ee7089..277eaf8 100644
--- a/assets/locales/pt/terminal.json
+++ b/assets/locales/pt/terminal.json
@@ -304,5 +304,6 @@
"other": "{count} sessões recuperadas após reiniciar o servidor"
},
"toast.saveFailed": "Não foi possível salvar",
- "toast.saved": "Salvo em {path}"
+ "toast.saved": "Salvo em {path}",
+ "find.close": "Fechar a busca"
}
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 143e894..995232d 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -58,6 +58,7 @@ que React Native pero sobre nuestro servidor gráfico.
| `server/src/logs/`, `js_logs.c`, `sdk/logs.js`, `apps/logs` | **M9** | Logs: our own systemd journal reader (no libsystemd), LordOS logs, system logs for admins through a closed action, live follow with inotify (see `SYSTEM.md`) |
| `server/src/ui/tzif.c`, `js_help.c`, `sdk/{notify,alarms,statusitems,help}.js`, `apps/{clock,help}` | **M9** | Clock (our own TZif reader, session alarms with the app closed), session notifications, menu-bar status items, Help (markdown articles in es/en/pt, welcome tour, Spotlight source) (see `SYSTEM.md`) |
| `server/src/ui/grab.c`, `cursor.c`, `sdk/windowshell.jsx` | **M8** | Ventanas: mover y agrandar en C (un evento por cuadro, sin JS), capa de la ventana que se mueve, bordes en los 4 lados y esquinas, cursores propios y `cursor-shape-v1` (ver `VENTANAS.md`) |
+| `server/src/hw/`, `ui/js_hw.c`, `sdk/hardware.jsx`, `sdk/defaults.js` | **M9** | Settings' hardware pages: displays (EDID, live modes with a 15 s revert, per-display persistence, software rotation and 200 % scale, Night Shift on the gamma LUT or by software), Bluetooth (BlueZ over our own D-Bus client, pairing agent), battery and power profiles, idle (DPMS, lock, sleep), date and time, notifications from Linux apps (`org.freedesktop.Notifications`) and default apps (`mimeapps.list`); kernel uevents and D-Bus signals, no polling (see `SETTINGS.md`) |
### Flujo de un frame
@@ -149,6 +150,9 @@ Desde M7, lo que LordOS hace con código propio y lo que delega en un programa d
ni SANE.
- **Servicios de Debian a los que se les habla por su protocolo:** CUPS (IPP por
`/run/cups/cups.sock`; administra la cola y los controladores, ver `IMPRESION.md`).
+- **D-Bus services (Settings, `SETTINGS.md`):** BlueZ (`bluetoothd`), power-profiles-daemon and
+ systemd-timedated on the system bus, with our own D-Bus client (`vault/dbus.c`); lord-server also
+ serves `org.freedesktop.Notifications` on the session bus. No libdbus, sd-bus or libbluetooth.
- **Programas de Debian** (con ruta fija, nunca enlazados, lanzados por el ayudante `admin.c`):
- `dpkg`: desempaquetar y configurar;
- `mkfs.vfat`, `mkfs.exfat`, `mkfs.ext4`, `mkfs.ntfs` (optional) and their label tools: formatting
@@ -156,6 +160,8 @@ Desde M7, lo que LordOS hace con código propio y lo que delega en un programa d
- `wpa_supplicant`: Wi-Fi;
- `openvpn`;
- `resolvectl` y `networkctl`.
+ - `powerprofilesctl`, `systemctl suspend`/`reload systemd-logind` and `timedatectl` (Settings'
+ closed `power-*` and `time-*` actions, `SETTINGS.md`).
- **Servidor de sonido:** PipeWire, por el protocolo de PulseAudio.
No se usan apt, libapt, gpgv, curl, zlib, liblzma, NetworkManager, wireguard-tools, libpulse,
diff --git a/docs/FIREWALL.md b/docs/FIREWALL.md
index 86cb191..83fb6b9 100644
--- a/docs/FIREWALL.md
+++ b/docs/FIREWALL.md
@@ -329,6 +329,11 @@ tests/netperm_bench.c, netperm_measure.sh mediciones
enganchar si cambió el id.
- Si el servicio se para, los links se cierran y todo queda permitido. El escritorio no depende
de él.
+ - **Also on `user@<uid>.service`** (closing the `systemd-run --user` escape, see
+ [Escape via `systemd-run --user`](#escape-via-systemd-run---user-la-unión-de-user)): the same
+ programs are attached a second time, with a `bpf_link` per session, to each LordOS session
+ user's `user@<uid>.service` cgroup. Re-attached the same way when that cgroup changes (the user
+ manager restarting) or disappears.
- **Las apps.** Lee las carpetas de las sesiones (`lordos-session-<uid>`) con inotify, más un
repaso cada 5 s:
- `server` es `lordos`;
@@ -357,12 +362,56 @@ Cada programa hace lo siguiente:
Lo que no es de una app de sesión pasa enseguida: `lord-sessiond`, la pantalla de ingreso y el
resto del sistema.
+#### Escape via `systemd-run --user` (la unión de `user@`)
+
+Root-owned scopes (see `docs/PRIVACIDAD.md`) stop an app from writing `cgroup.procs` to leave its
+scope, but an unsandboxed Linux app can still ask its own systemd **user manager** for a new unit:
+`systemd-run --user --scope <cmd>` (a scope) or `systemd-run --user <cmd>` (a transient service).
+The user manager has PID 1 do the move (`AttachProcessesToUnit`), which only checks the UID, not
+the source cgroup, so the process lands in `user@<uid>.service/app.slice/…` — outside
+`lordos.service`, where the programs above are not attached. A "no internet" app could reach the
+internet from there.
+
+**Chosen fix (option a): attach to `user@<uid>.service` + a per-user restriction union.** For each
+LordOS session user, `lord-netperm` attaches the same cgroup programs a second time to that user's
+`user@<uid>.service`. There the process is not in any app scope, so `find_app` (`np.bpf.c`) falls
+back to `np_union`, keyed by the `user@<uid>` cgroup id (the ancestor at `cfg->user_level`). Its
+value is the **strictest union** of the restrictions (the `NP_R_*` bits ORed) of all of that user's
+currently-running restricted apps, with `trusted=1` so anything the union does not forbid is
+allowed silently. If the user has no restricted app running, there is no entry and `user@` is fully
+open (the user manager and its own services are untouched). `lord-netperm` rebuilds the union
+whenever a scope or a rule changes (`sync_union`), and removes it when the user's session or user
+manager goes away.
+
+Why this and not the alternatives:
+
+- A process escaping through a `systemd-run --user` **service** is forked by the user manager, not
+ by the app, so its process lineage no longer reaches the restricted app. Carrying the app
+ identity in BPF task-local storage and inheriting it across `fork` (option c) therefore cannot
+ cover the service case — and it would also need a `BPF_PROG_TYPE_TRACING`/raw-tracepoint program
+ plus a BTF-typed task-storage map, which our own `bpf()` loader (`bpfsys.c`) does not build.
+ Kernel 6.12 has BTF and `bpf` LSM, but the loader would have to grow that machinery.
+- Denying the app access to the user bus / `$XDG_RUNTIME_DIR/systemd/private` (option b) can't be
+ enforced for unsandboxed Linux apps (Landlock is not applied to them).
+- The union is **restriction-only**: it never grants access, so an escaped process is always at
+ least as restricted as its own policy. The cost is that it is coarse — while a restricted app is
+ running, every process under that user's `user@` is held to the union. That is acceptable because
+ LordOS's own apps live under `lordos.service` (unaffected), and it activates only while a
+ restricted app runs. A precise per-process identity (option c) is a possible future refinement if
+ the loader gains tracing support.
+
+`sock_create` ("no network") is **not** enforced through the union, so the user manager can still
+create its own sockets; a "no network" escapee can open a socket but every `connect`/`sendmsg`/`bind`
+is denied by the union all the same. The decision helper (`np_decide`) is unchanged, so
+`tests/npcompile_test.c` still covers it.
+
**Mapas**
| Mapa | Tipo | Clave → valor |
|---|---|---|
-| `np_cfg` | array | nivel de las scopes, encendido |
+| `np_cfg` | array | nivel de las scopes, encendido, nivel de `user@<uid>` |
| `np_apps` | hash | id de cgroup → restricciones, confiable, modo y lista genérica (lan / internet / any) |
+| `np_union` | hash | id de `user@<uid>.service` → unión estricta de las apps restringidas del usuario |
| `np_lpm4`, `np_lpm6` | LPM trie | (índice de la app, red) → lista ordenada de reglas |
| `np_seen` | LRU | (cgroup, dirección, puerto, protocolo, dirección de la conexión, veredicto) → última vez avisada |
| `np_counts` | hash | id de cgroup → permitidas, denegadas |
@@ -565,6 +614,25 @@ y `/dev/tcp`:
- **Ajustes → Privacidad → Red de las apps:** con "sin internet" marcado en Apps restringidas, la
puerta de enlace anda e internet no.
+**`systemd-run --user` escape (the `user@` union).** With a restricted app running
+(`desktop:aisla`, "no internet"), from a `foot` terminal placed in `app-lordos-aisla.scope`:
+
+| Escape attempt | Result |
+|---|---|
+| `curl https://example.com` (direct, in the app scope) | blocked — "Could not connect" (existing scope rule) |
+| `systemd-run --user --scope curl https://example.com` | blocked — the scope lands in `user@1000`, `np_union` denies the connect |
+| `systemd-run --user curl https://example.com` (transient service) | blocked — same, even though the user manager forks it |
+| `setsid curl https://example.com` | blocked — `setsid` does not change the cgroup, stays in the app scope |
+
+`lord-netperm` logs each `user@` denial as `uid 1000 user@: denegada … (unión de apps
+restringidas no-internet)`. A normal process outside `user@`/`lordos.service` app scopes (e.g. an
+SSH session scope) still reaches the internet while the restricted app runs, so normal apps are
+unaffected. Cross-user: a restricted app for `bob` (uid 1001) blocks `bob`'s `systemd-run --user`
+escape while `lord` (uid 1000, no restricted app) keeps full access — the union is per
+`user@<uid>`, never leaking between users. The screenshot shows the four attempts blocked:
+
+![systemd-run escape blocked](m8-firewall-escape-blocked.png)
+
### Mediciones (VM 122, 4 vCPU Xeon Silver 4108, kernel 6.12)
`tests/netperm_measure.sh`: 3 corridas de 20 000 `connect()` a 127.0.0.1 adentro de una scope, y
@@ -590,10 +658,13 @@ y `/dev/tcp`:
- **App scopes are root's now** (was: «Las scopes son del usuario»). `lord-sessiond` creates the
scopes and places each process; every `cgroup.procs` of the session subtree is root-owned, so a
Linux app can no longer move itself to another scope, to `server` or to a new cgroup (tested on
- VM 122, see `PRIVACIDAD.md`, «Root-owned app scopes»). The remaining hole: `systemd-run --user
- --scope` asks PID 1 (`AttachProcessesToUnit`), which moves the process as root into
- `user@<uid>.service`, outside `lordos.service`, where no rule applies. `firewall.json` and
- `permisos.json` are still writable by an unsandboxed app running as the user.
+ VM 122, see `PRIVACIDAD.md`, «Root-owned app scopes»).
+- **`systemd-run --user` escape: closed** (was the remaining hole). The programs are now attached to
+ each user's `user@<uid>.service` too, and a process that escapes there is held to the per-user
+ restriction union (see [Escape via `systemd-run --user`](#escape-via-systemd-run---user-la-unión-de-user)).
+ Tested on VM 122 (see below). What stays coarse: the union restricts the whole `user@` subtree
+ while a restricted app runs, not just the escaped process. `firewall.json` and `permisos.json` are
+ still writable by an unsandboxed app running as the user (a filesystem matter, not the firewall).
- **Una scope recién creada** se registra con inotify en microsegundos, antes de que el programa
termine de arrancar (exec + bibliotecas). Si una conexión llegara antes, pasaría con las reglas
por omisión.
diff --git a/docs/PASSWORDS.md b/docs/PASSWORDS.md
index bc186ff..3469dc3 100644
--- a/docs/PASSWORDS.md
+++ b/docs/PASSWORDS.md
@@ -16,6 +16,12 @@ No gnome-keyring, kwallet, libsecret, libdbus or sd-bus is used by LordOS.
| An *Internet* item: website, user, hidden password (reveal/copy), live 2FA code with countdown, notes, reminder "change every 90 days" | All 2FA codes with their countdown; the TOTP secret never leaves `lord-vault` |
| ![Wi-Fi QR](m9-contrasenas-wifi-qr.png) | ![Identity document with photo](m9-contrasenas-identidad.png) |
| Wi-Fi: the QR code to join from a phone (`WIFI:T:WPA;S:…;P:…;;`) is generated inside `lord-vault` | *Identity and documents*: encrypted photo attachment previewed (decoded and downscaled inside `lord-vault`) |
+| ![Finance](m9-contrasenas-finanzas.png) | ![Card](m9-contrasenas-tarjeta.png) |
+| *Finance*: password and coordinates card revealed on request; the "change every 90 days" reminder is overdue | *Cards*: the list shows only the last 4 digits; number, CVV and PIN stay hidden |
+| ![Servers/SSH](m9-contrasenas-ssh.png) | ![Crypto](m9-contrasenas-cripto.png) |
+| *Servers/SSH* with the private key (multi-line hidden field) and host fingerprint | *Crypto*: extra warning about the seed phrase |
+| ![License with its attached file](m9-contrasenas-licencia.png) | |
+| *Licenses*: the licence key plus the attached licence file, opened from the encrypted attachment | |
| ![Security report](m9-contrasenas-seguridad.png) | ![Generator](m9-contrasenas-generador.png) |
| Security report: weak, reused, old and breached (offline) passwords | Password generator |
| ![Passphrase generator](m9-contrasenas-generador-frase.png) | ![Import KeePass](m9-contrasenas-importar.png) |
@@ -29,15 +35,18 @@ No gnome-keyring, kwallet, libsecret, libdbus or sd-bus is used by LordOS.
| ![Chromium autofills after a restart](m9-contrasenas-chromium-autocompletar.png) | ![Protected window in a capture](m9-contrasenas-captura-protegida.png) |
| After restarting Chromium it decrypts and autofills the saved login: the key came back from our service | The Passwords window comes out black in LordOS screenshots, recordings and the remote desktop |
-Main window with categories (tree) and tags: see `m9-contrasenas-categorias.png`.
+| ![Categories tree and tags](m9-contrasenas-categorias.png) | ![The real screen at the same moment](m9-contrasenas-pantalla-real.png) |
+|---|---|
+| Main window: user categories as a tree (Trabajo → Clientes, Hogar → Inventario, imported KeePass folders), tags with colours | The real monitor (QEMU screendump) when the black LordOS screenshot above was taken: only captures are blanked |
## Architecture: where the secrets live
```
- Passwords app (React, apps/passwords) Settings → Network, Mail, … (sdk keyring)
- │ lord.vault.request(json, files) │
- ▼ ▼
- lord-server (src/vault/vclient.c, src/ui/js_vault.c)
+ Passwords app process Settings → Network, Mail, … (sdk keyring)
+ (lord-server --app passwords, sandboxed; │ lord.vault.request(json, files)
+ apps/passwords, src/ui/js_vault.c app mode) │
+ │ own channel (vc_attach_app) ▼
+ │ LORD_VAULT_FD lord-server (src/vault/vclient.c, src/ui/js_vault.c)
- spawns lord-vault (fixed path, no args, minimal env), one per session
- opens files the user picked (validated like lord.fs) and passes only fds
- opens /dev/hidrawN for FIDO2 after the `usb` permission, passes the fd
@@ -66,14 +75,37 @@ the vault key and never parses the vault. The UI gets just what it shows:
- TOTP secrets never leave `lord-vault`: the UI receives the 6–8 digit code and the seconds left;
- the Wi-Fi QR is built from the item inside `lord-vault`; the UI receives a bitmap.
-**Known limitation: the UI is not a separate sandboxed process yet.** Like every other built-in app
-(Notes, Settings, Files…), the Passwords UI runs inside the session's JavaScript context, so a
-value the user reveals sits for a moment in `lord-server`'s QuickJS heap (garbage collected, not
-wiped). Only `.lpk` packages run as isolated processes today (`lord-server --app <id>`). The
-protocol is ready for it: `vc_attach_app()` gives an isolated app its own channel to `lord-vault`
-(role `app`), so moving the UI to app mode means (1) shipping it as a system package, (2) using the
-powerbox for files and a broker op for the FIDO2 device, and (3) polling the vault channel in
-`appclient.c`. That is the next step; it was not done in this milestone.
+### The UI runs in its own sandboxed process (app mode)
+
+The Passwords window is not drawn by the session's JavaScript context: it is its own process,
+`lord-server --app passwords` (a Wayland client of the compositor with Landlock + seccomp and no
+network, like an installed `.lpk`). Revealed values, edited fields and the decrypted list live only
+in that process and in `lord-vault`; `lord-server`'s QuickJS heap never sees them.
+
+| Piece | How |
+|---|---|
+| System package | `tools/build-theme.mjs` builds every built-in app whose manifest says `"process": "isolated"` into `assets/sysapps/<id>/` (`app.js`, `manifest.json`, `locales/`). `app_package_dir()` (`src/app/appspawn.c`) prefers that folder (root- or user-owned, not world-writable) over a user `.lpk` with the same id, so a package cannot shadow it. |
+| Vault channel | `app_spawn()` calls `vc_attach_app()` **only** for the system `passwords` package and hands the socket to the child as `LORD_VAULT_FD`. In the app, `js_vault_register_app()` exposes the same `lord.vault` API over that socket (non-blocking `vw_feed` polling, `lord.vault.appMode = true`). The relayed JSON is wiped after use. |
+| Files | The system's own open/save dialog (powerbox, drawn by `lord-server`) picks the file; the app gets only the fd and passes it on to `lord-vault` (`request(json, { fds })`). Key files, attachments, import, export, the breach list and QR images all go this way. |
+| FIDO2 | `BOP_VAULT_FIDO`: after the user allows `usb`, `lord-server` opens the hidraw device and gives it straight to `lord-vault` (`vc_fido_attach`); the app never holds the device. Only the app spawned with a vault channel may ask. |
+| Clipboard | `BOP_CLIP_SECRET`: the copy is marked sensitive (out of the history, password-manager hint for Wayland clients) and `lord-server` clears it after the chosen seconds if it still holds the same text (compared by SHA-256; the text is not kept). |
+| Protection | The manifest says `"protected": true`; `sdk/wayland.js` marks the app's Wayland window protected as soon as it maps, so it is black in screenshots, recordings and the remote desktop (`m9-contrasenas-app-captura.png`). |
+| Window | Opening Passwords (Dock, Launchpad, Spotlight, `wm.open('passwords')`) starts the process or focuses its window; the manifest's `size`/`minSize` now size the app window. |
+
+**Fallback.** If `lord-server` has no app mode or the system package is missing (a dev tree
+without `npm run build`), the same UI runs in the shell's context as before (path-based files, the
+in-app file picker, the shell clipboard timer). The vault itself is unchanged either way.
+
+Hidden in app mode: "Print" for the recovery key (the print dialog lives in the shell; saving it
+to a file works) and the "Open Settings" link on VPN items.
+
+| App mode: the system file dialog over the lock screen | App mode: a LordOS screenshot of the app window |
+|---|---|
+| ![Powerbox](m9-contrasenas-app-powerbox.png) | ![Protected app window](m9-contrasenas-app-captura.png) |
+
+In the in-process fallback the lock and create screens show their file picker inline, under the
+padlock and the title (`m9-contrasenas-selector-en-linea.png`), instead of a centred dialog that
+covered the whole form.
## The vault format (`.lvault`, version 1)
@@ -187,8 +219,9 @@ Locking frees the model block by block; every arena block is wiped on free.
- Wayland clients now see the extra MIME type `x-kde-passwordManagerHint` (value `secret`) on a
sensitive LordOS clipboard, the KDE/GNOME convention clipboard managers honour
(`src/wl/wl.c`). The bytes handed to Wayland clients are wiped after sending.
-- The app clears the clipboard after 30 s (configurable: 15/30/60/120 s) if it still holds the
- same value.
+- The clipboard is cleared after 30 s (configurable: 15/30/60/120 s) if it still holds the same
+ value: by `lord-server` in app mode (`BOP_CLIP_SECRET`), by the app in the in-process fallback.
+ Replacing the clipboard also wipes the previous text in `lord-server` (`term_set_clipboard`).
## The session keyring (`login.lvault`)
@@ -227,7 +260,8 @@ await keyring.list('mail'); // without secrets
- **Trust boundary:** built-in apps run in the shell's JavaScript context, so for them the owner
string is passed by trusted system code, not enforced by a process boundary. For isolated `.lpk`
apps the owner must be set by `lord-server` from the broker (the app id it already verifies);
- wiring that broker op is part of moving to app mode (see above).
+ that broker op is still to do. The Passwords app process manages the keyring over its own
+ vault channel, which only the system `passwords` package receives.
- **Settings → Network** now stores Wi-Fi passwords (`wifi:<ssid>`) and VPN credentials
(`vpn:<name>`) in the keyring when you join or save, and offers them back with the 🔑 button.
The root-owned copy that `wpa_supplicant`/the VPN daemons need to connect at boot is still
@@ -352,10 +386,14 @@ many tags (with colours), favourite, archived, trash, history, attachments and a
Not part of `make test` because they need the real helper or root:
-- `build/vault-e2e` (47/47): drives the real sandboxed `lord-vault` through `vclient.c` (create,
+- `build/vault-e2e` (51/51): drives the real sandboxed `lord-vault` through `vclient.c` (create,
unlock, wrong password, items, search, report, TOTP, QR, attachments, key file on a "USB",
recovery key, password + key file, import/export, keyring ownership and sharing, screen lock
- closing Passwords but not the keyring, `NoNewPrivs`/`Seccomp` set).
+ closing Passwords but not the keyring, `NoNewPrivs`/`Seccomp` set, and the app channel from
+ `vc_attach_app()`: requests over its own socket and the lock event reaching it).
+- App mode by hand on VM 116: the app process unlocks, reveals, copies (pasted in the Terminal,
+ empty again after 30 s), attaches a file through the powerbox, locks, and its window is black in
+ a LordOS screenshot.
- `tests/fido-soft/run-pw-116.sh` (32/32): `softfido`, a software CTAP2 authenticator on
`/dev/uhid` (CTAPHID, getInfo, clientPIN, makeCredential, getAssertion with hmac-secret), and the
client against it: same salt → same secret, other salt or credential → different, wrong key →
@@ -385,7 +423,10 @@ whose only verification is built in (fingerprint) are not implemented/tested.
| `server/src/vault/ctap2.c`, `cbor.c`, `p256.c`, `fidodev.c` | FIDO2 client, CBOR, P-256, device discovery |
| `server/src/vault/dbus.c`, `secretsvc.c` | own D-Bus and the Secret Service |
| `server/src/vault/vimport.c`, `kdbx.c`, `csvp.c`, `xmlmini.c` | importers |
-| `server/src/vault/vclient.c`, `server/src/ui/js_vault.c` | lord-server side, `lord.vault` |
+| `server/src/vault/vclient.c`, `server/src/ui/js_vault.c` | lord-server side, `lord.vault` (shell and app mode) |
+| `server/src/app/appspawn.c`, `appclient.c` | system package lookup, the vault channel for the app, window size from the manifest |
+| `server/src/sec/brokersrv.c`, `server/src/ui/js_broker.c` | `BOP_VAULT_FIDO`, `BOP_CLIP_SECRET` |
+| `assets/sysapps/passwords/` | the built app process bundle (generated by `npm run build`) |
| `server/mk/vault*.mk` | build and test rules |
| `sdk/vault.js` | `vaultRequest`, `keyring`, `autofill`, `<AutofillButton>`, `<KeyringPrompt>` |
| `apps/passwords/` | the app |
diff --git a/docs/PRIVACIDAD.md b/docs/PRIVACIDAD.md
index ea9ae32..953b275 100644
--- a/docs/PRIVACIDAD.md
+++ b/docs/PRIVACIDAD.md
@@ -17,7 +17,7 @@ primera vez y el usuario decide. Ver también [FIRMA.md](FIRMA.md) (paquetes fir
| Permisos por app, estilo TCC, guardados donde la app no escribe (`server/src/sec/perms.c`) | **hecho** |
| Avisos dibujados por el sistema (también los que pide una app aislada por el broker), Ajustes → Privacidad, puntos verde/naranja | **hecho** |
| cgroup por app (`app-lordos-lpk-<id>.scope`, `app-lordos-<id>.scope`) con límites, en el subárbol delegado de la sesión | **hecho**, probado con `lord-sessiond` y `Delegate=yes` |
-| **Root-owned app scopes**: an app can't move itself to another cgroup (`lord-sessiond` places each process, see [Root-owned app scopes](#root-owned-app-scopes)) | **done**, tested on VM 122 (the `systemd-run --user --scope` path stays open, see there) |
+| **Root-owned app scopes**: an app can't move itself to another cgroup (`lord-sessiond` places each process, see [Root-owned app scopes](#root-owned-app-scopes)) | **done**, tested on VM 122 (the `systemd-run --user` escape is now closed by the `user@` union, see there and `docs/FIREWALL.md`) |
| Firma de paquetes y niveles de confianza | **hecho**, ver [FIRMA.md](FIRMA.md) |
| Tokens del tema, idioma y dirección (RTL) **en vivo** dentro del proceso de la app | **hecho** (claro/oscuro, acento, idioma; probado con árabe) |
| Revocación en vivo: al denegar un permiso, la app suelta la cámara/el micrófono al instante | **hecho** |
@@ -434,14 +434,18 @@ by `lord-sessiond`; `systemctl restart lordos` twice with the session alive (the
`lord-sessiond` hardens the old subtree, starts a new placement service, and an app launched
afterwards still lands in its scope); `DelegateSubgroup=supervisor` in the unit.
-**Known gap: `systemd-run --user --scope`.** The same screenshot shows it: a process can still ask
-the user's systemd manager for a new scope. The user manager can't migrate it itself, so it asks
-PID 1 (`AttachProcessesToUnit`), which runs as root and only checks that the process and the
-target unit belong to the same UID; it does not look at the source cgroup. The process then runs
-in `user@<uid>.service/app.slice/run-….scope`, outside `lordos.service`, where `lord-netperm`'s
-programs aren't attached. Closing it needs either `lord-netperm` hooks on the users' `user@`
-subtrees (treating a LordOS session user's transient scopes as an unknown app) or a systemd-side
-policy; neither is done. `.lpk` apps can't do it (no D-Bus, no new sockets).
+**`systemd-run --user --scope`: closed (M8, the `user@` union).** A process can still ask the
+user's systemd manager for a new scope or service. The manager has PID 1 do the move
+(`AttachProcessesToUnit`), which runs as root and only checks that the process and the target unit
+belong to the same UID; it does not look at the source cgroup. The process then runs in
+`user@<uid>.service/app.slice/…`, outside `lordos.service`. This is closed by `lord-netperm`:
+it attaches its cgroup programs to each LordOS session user's `user@<uid>.service` too, and holds a
+process that escapes there to the strictest **union** of that user's running restricted apps'
+restrictions (restriction-only, so never less restrictive than the app's own policy). Tested on
+VM 122 with `systemd-run --user --scope`, `systemd-run --user` (service) and `setsid` — all denied,
+normal processes unaffected, and the union never leaks between users. See `docs/FIREWALL.md`,
+«Escape via `systemd-run --user`», and `docs/m8-firewall-escape-blocked.png`. `.lpk` apps couldn't
+do it anyway (no D-Bus, no new sockets).
Not tested this round: a second user over fast user switching and the remote desktop (no test
password at hand). Their code path is the same `cgroup_delegate_session()` per uid.
diff --git a/docs/RED.md b/docs/RED.md
index 2e26d7f..e3b1474 100644
--- a/docs/RED.md
+++ b/docs/RED.md
@@ -77,7 +77,7 @@ lord-server --user ana ── lord-admin ──┘ net-* actions are forwarded
### Test (VM 119, October 17)
VM 119 runs `lord-sessiond` installed like the `.deb`; it was not installed from the ISO (see
-`VM-SETUP.md`, step 20). `eth0` is managed by systemd-networkd (netplan) and LordOS leaves it
+`VM-SETUP.md`, step 23). `eth0` is managed by systemd-networkd (netplan) and LordOS leaves it
alone, so the test uses a LordOS-managed NIC: the veth `lnt0`, whose peer is in the netns `lnt`
with a `dnsmasq` there (`lordos-test-netns.service`, which starts before `lordos.service`), and
`/etc/lordos/net/if/lnt0.conf` with `method=dhcp`.
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index a399d27..5724d16 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -413,15 +413,46 @@ Details in `PASSWORDS.md`. Tested on VM 116 with a real `lord-sessiond` session
`<AutofillButton>`.
- [x] **Secret Service** with our own D-Bus code (plain + DH sessions): `secret-tool` and Chromium
work without gnome-keyring.
-- [ ] Run the Passwords UI as an isolated process (app mode); today only `lord-vault` is sandboxed.
+- [x] **The Passwords UI runs as its own sandboxed process** (`lord-server --app passwords`, a
+ system package built into `assets/sysapps/`): its own channel to `lord-vault`
+ (`vc_attach_app`), files through the powerbox, FIDO2 and secret clipboard through the broker
+ (`BOP_VAULT_FIDO`, `BOP_CLIP_SECRET`), protected Wayland window. Revealed values never enter
+ `lord-server`'s JavaScript heap. In-process fallback kept (see `PASSWORDS.md`).
+- [ ] Keyring for isolated `.lpk` apps: a broker op that sets the owner from the verified app id.
- [ ] Test with real FIDO2 keys (only the uhid software authenticator was available).
+## M9 — Settings: hardware pages ✅ (2026-10-18)
+
+Details in `SETTINGS.md`. Tested on VM 118 (`ajustes-*.png`), Bluetooth with a virtual controller
+(`btvirt`).
+
+- [x] **Displays:** outputs, resolutions and refresh rates from KMS with EDID names; live modeset
+ with the system's 15-second "Keep these display settings?"; saved per display (EDID identity) and
+ used from the first frame; main display choice and move on unplug (DRM uevents); software rotation
+ and a doubled 200 % scale (CPU path); brightness through a closed action; Night Shift on the gamma
+ LUT or by software, scheduled sunset-to-sunrise from the time zone's coordinates or custom hours.
+- [x] **Bluetooth:** BlueZ over our own D-Bus client: power, discovery, pair (system-drawn PIN,
+ passkey and confirmation prompts), connect, disconnect, forget; headsets in Sound through
+ PipeWire.
+- [x] **Energy:** battery state, time and health from sysfs, low-battery notices, percentage in the
+ menu bar, power profiles (power-profiles-daemon or the cpufreq governor), display off / lock /
+ sleep after N minutes, power button and lid (logind drop-in).
+- [x] **Notifications:** per-app allow, style, sound; Do Not Disturb with a schedule; grouping;
+ `org.freedesktop.Notifications` for Linux apps; packages use the sandbox permission.
+- [x] **Date & Time:** NTP (timesyncd) or manual time, manual time zone (never from the network),
+ 12/24 h, menu bar clock format.
+- [x] **Default Apps:** `mimeapps.list` and `xdg-terminals.list`; Files' "Open With" and
+ `lord.apps.launchWith('', path)` honor them.
+- [ ] **Pending:** extend/mirror across displays; sharp HiDPI and 125/150 %; Night Shift on the GPU
+ path without a LUT; real laptops (battery, backlight, lid) and real Bluetooth controllers;
+ notifications on the lock screen and a notification center; Wayland idle inhibit.
+
## Pendiente antes del ISO final
- [ ] **Mail, Calendario, Contactos y Recordatorios** (estilo Outlook; cuentas IMAP/SMTP, CalDAV y
CardDAV; usa el llavero de Contraseñas).
-- [ ] **Secciones de Ajustes que faltan:** Pantallas, Bluetooth, Energía, Notificaciones, Fecha y
- hora, Apps por defecto.
+- [x] **Secciones de Ajustes que faltan:** Pantallas, Bluetooth, Energía, Notificaciones, Fecha y
+ hora, Apps por defecto (see "M9 — Settings: hardware pages" above and `SETTINGS.md`).
- [ ] **Chromium y Firefox** preinstalados (apps Linux, no nativas).
- [x] **Cámara en apps aisladas** (`.lpk`) y **varias ventanas por app aislada** (VM 122,
`PRIVACIDAD.md`): read-only frame ring from `lord-media` with validated ACKs, photo/video through
diff --git a/docs/SETTINGS.md b/docs/SETTINGS.md
new file mode 100644
index 0000000..dcf1454
--- /dev/null
+++ b/docs/SETTINGS.md
@@ -0,0 +1,315 @@
+# Settings: Displays, Bluetooth, Energy, Notifications, Date & Time, Default Apps
+
+Six Settings pages modeled on macOS System Settings, with the hardware side in
+`server/src/hw/` (C, libc only) and the session side in `sdk/hardware.jsx`, `sdk/defaults.js` and
+`sdk/notify.js`. Tested on VM 118 (`lordos-notes`) with `lord-sessiond`, virtio-gpu and a virtual
+Bluetooth controller (`btvirt`). Screenshots: `docs/ajustes-*.png`.
+
+Screenshots, dark and light: Displays (`ajustes-pantallas-oscuro.png`, `-claro.png`), Bluetooth
+(`ajustes-bluetooth-*`), Energy (`ajustes-energia-*`), Notifications (`ajustes-notificaciones-*`,
+plus `ajustes-notificaciones-app-claro.png`), Date & Time (`ajustes-fecha-hora-*`), Default Apps
+(`ajustes-apps-por-defecto-*`); the revert countdown in both modes (`ajustes-pantallas-revertir.png`,
+`ajustes-pantallas-revertir-claro.png`), 200 % (`ajustes-pantallas-200.png`), rotation, Night Shift,
+pairing, Sound with a Bluetooth headset, a Linux app's notification and Files' "Open With".
+
+| Page | Sidebar group | Code |
+|---|---|---|
+| Displays | with Appearance, Wallpaper, Desktop & Dock | `apps/settings/Displays.jsx`, `hw/display.c`, `hw/edid.c`, `hw/modes.c`, `hw/night.c`, `kms.c` |
+| Bluetooth | with Network and Sound | `apps/settings/Bluetooth.jsx`, `hw/bt.c`, `hw/sysbus.c` |
+| Notifications | with Sound | `apps/settings/Notifications.jsx`, `sdk/notify.js`, `hw/notifyd.c` |
+| Date & Time | with Language & Region | `apps/settings/DateTime.jsx`, `hw/hw.c` (timedated) |
+| Default Apps | with Keyboard and Trackpad | `apps/settings/DefaultApps.jsx`, `sdk/defaults.js`, `hw/defaults.c`, `hw/mimeapps.c` |
+| Energy (Battery) | with Privacy | `apps/settings/Power.jsx`, `hw/power.c`, `hw/ppd.c` |
+
+Shared pieces: `apps/settings/ui.jsx` (a row with a hint, a pop-up button, the page header) on top of
+the SDK's `GroupBox` (`docs/DESIGN.md`). All text goes through `t()` in the `prefs` namespace
+(`assets/locales/{en,es,pt}/prefs.json`); `node tools/i18n-check.mjs` passes. Pages use
+`textAlign: 'start'` and leading/trailing layout, so they mirror in Arabic and Hebrew; sliders and
+the time fields keep `direction: 'ltr'`.
+
+## How it fits together
+
+```
+ apps/settings/*.jsx ── sdk/hardware.jsx (stores, Night Shift timer, idle, system dialogs)
+ │ ▲ __lordHw(kind, data): "display" "idle" "power" "bt" "bt-prompt"
+ ▼ │ "bt-result" "ppd" "ppd-result" "timedate" "notify" "notify-close"
+ lord.display / power / bt / mime / timedate / notifyd (server/src/ui/js_hw.c, validated)
+ │
+ ▼
+ server/src/hw/ display.c ─ kms.c (modeset, gamma LUT, DPMS) uevent.c (netlink: drm,
+ bt.c, ppd.c ─ sysbus.c ─ vault/dbus.c (system bus) power_supply, backlight)
+ notifyd.c ─ vault/dbus.c (session bus) power.c (sysfs)
+ defaults.c, mimeapps.c (~/.config/mimeapps.list)
+ │
+ ▼ root work: closed admin actions (hw/hw_admin.c)
+ admin.c ─ display-brightness, power-profile, power-suspend, power-buttons, time-ntp, time-set,
+ bt-unblock
+```
+
+Nothing polls. Hotplugged displays, batteries and chargers arrive as kernel uevents (one
+`NETLINK_KOBJECT_UEVENT` socket in the main loop), Bluetooth and power profiles as D-Bus signals,
+idle deadlines go into the main loop's poll timeout, and the Night Shift schedule is a JavaScript
+timer that sleeps until the next change (30 s steps only during the 30-minute fade).
+
+## Displays
+
+![Displays](ajustes-pantallas-oscuro.png)
+
+- **Outputs and modes.** `kms_outputs()` reads every connector with its modes and EDID blob.
+ `hw/edid.c` parses the base block (vendor, product, serial, name descriptor, size, native
+ timing) and `hw/modes.c` computes exact refresh rates (`clock·1000/(htotal·vtotal)`, interlace
+ and double-scan aware), the list of resolutions (largest first, highest rate per size) and the
+ best mode for a size and rate (progressive before interlaced; ties go to the preferred mode).
+- **Applying.** `lord.display.apply(conn, w, h, mHz, rotation, scale)` queues the change and
+ `main.c` runs it between frames (never with a page flip pending): the GPU path stops (its GBM
+ surfaces have the old size), `kms_modeset()` recreates the dumb buffers and calls `SETCRTC`, the
+ session takes the new size (`set_size`: work area, windows and Wayland outputs follow) and the GPU
+ starts again. If the driver refuses the mode, the previous one is restored.
+- **"Keep these display settings?"** The system draws the dialog (`DisplayConfirm`, mounted by
+ `startShell`, so it works even if Settings is closed) and goes back to the previous mode after
+ 15 seconds without an answer, like macOS.
+
+ ![Keep these display settings](ajustes-pantallas-revertir.png)
+ ![The same in light mode](ajustes-pantallas-revertir-claro.png)
+- **Saved per display.** "Keep" writes `~/.config/lordos/displays.json`:
+
+ ```json
+ { "main": "RHT-1234-QEMU_Monitor",
+ "displays": { "RHT-1234-QEMU_Monitor": { "w": 1920, "h": 1080, "refresh": 60000, "rotation": 0, "scale": 1 } } }
+ ```
+
+ The key is the EDID identity (`vendor-product-serial`, or the name when there is no serial).
+ `kms.c` asks `display_pick()` (registered with `kms_set_picker`) every time `lord-sessiond` lends
+ the monitor to the session, so the saved mode and main display are used from the first frame.
+ Two identical monitors without serial numbers share an identity. The greeter always uses the
+ preferred mode.
+- **Main display.** With several connected outputs, "Use as Main Display" moves the session to
+ another connector (and its preferred mode). Unplugging the display in use moves to another one
+ automatically (DRM uevent → `display_hotplug()`).
+- **Rotation (90°, 180°, 270°).** Done by software: the frame is composed upright at the logical
+ size in a staging buffer and copied rotated into the card's buffer, only the damaged rectangles.
+ The cursor is composited apart so the staging buffer stays clean. Tablets and touch screens report
+ physical positions, which are mapped back (`display_unrotate_point`). A rotated screen is always
+ composed by the CPU (the GPU path and direct scanout are off).
+
+ ![Rotated 90°](ajustes-pantallas-rotada.png)
+- **Scale.** The engine has no resolution-independent scale: styles, layout boxes, `getLayout`,
+ pointer coordinates, window grabs and Wayland surfaces are all in physical pixels. What exists
+ now is **200 %**: the session runs at half the size and every pixel is doubled while copying the
+ frame (CPU path, like rotation; both combine). Limits, documented in the page:
+ - text and icons are as sharp as on a screen of half the resolution (not Retina-sharp);
+ - no 125 % or 150 % (a fractional upscale would blur everything);
+ - Linux apps are doubled too (they see a 1× output).
+
+ ![200 %: the 1280×800 screen looks like 640×400](ajustes-pantallas-200.png)
+
+ Sharp HiDPI needs a scale factor applied when styles are parsed (`ui/style.c`: lengths and font
+ sizes), with `getLayout`, pointer and gesture coordinates divided by it in `ui/js.c`, window grabs
+ (`ui/grab.c`, `js_wm.c`) in logical units, `wl_output.scale` and `wl_surface.set_buffer_scale`
+ honored in `wl/wl.c`, and the Terminal's cell size scaled. That is pending.
+- **Brightness.** Read from `/sys/class/backlight` (anyone can), written through the closed admin
+ action `display-brightness <name> <value>`: the name must be a real backlight under `/sys/devices`
+ and the value within `0..max_brightness`. External monitors (DDC/CI) and virtual machines have
+ none; the row says so. Untested on hardware (the VM has no backlight).
+- **Night Shift.** A color temperature from 6500 K (off) down to 1900 K, from a blackbody fit
+ (`night_temp_rgb`) normalized so that 6500 K is neutral. It goes into the CRTC's gamma LUT
+ (`DRM_IOCTL_MODE_SETGAMMA`) when the card has one: free, and the cursor and direct scanout are
+ tinted too. Without a LUT (virtio-gpu, some ARM boards) a 3×256 table is applied by software to
+ each damaged rectangle while copying the frame, and the page says so; the cursor is not tinted
+ then, and the GPU path is not tinted (pending: a multiply pass in `gpu.c`).
+
+ ![Night Shift applied](ajustes-night-shift.png)
+
+ Schedule: off, **sunset to sunrise** or **custom hours**, with a 30-minute fade, plus "Turn on
+ now" (until the end of tonight's schedule, or 07:00). Sunrise and sunset come from the Almanac
+ for Computers algorithm (`night_sun_times`, within ±4 min of NOAA in the tests) at the
+ coordinates of the **chosen time zone** in `/usr/share/zoneinfo/zone1970.tab`. The location is
+ never looked up on the network.
+- **Multiple displays.** `kms.c` drives one CRTC: extending the desktop across two displays or
+ mirroring them is **not implemented**. The page shows the "Extend / Mirror" control disabled with
+ that explanation and lists the other connected displays with "Use as Main Display". Mirroring
+ needs a second CRTC flipped with the first one (or one CRTC with two connectors where the
+ encoders allow cloning); extending needs per-output scene regions and per-CRTC buffers and flips.
+
+## Bluetooth
+
+![Bluetooth](ajustes-bluetooth-oscuro.png)
+
+`hw/bt.c` talks to BlueZ (`bluetoothd`, Debian package `bluez`) on the system bus with our own D-Bus
+client (`vault/dbus.c`, plus `dbus_connect_system()`). One connection for Settings
+(`hw/sysbus.c`) carries Bluetooth, power profiles and timedated, with replies matched by serial
+and signals dispatched to handlers.
+
+- **State.** `ObjectManager.GetManagedObjects` once, then `InterfacesAdded`, `InterfacesRemoved`
+ and `PropertiesChanged` (matched with `AddMatch`, only from org.bluez's unique name).
+ `Adapter1`, `Device1` and `Battery1` properties are parsed into a small model
+ (`bt_apply_props`); changes are sent to the theme once per main-loop turn.
+- **Actions.** Power (`Properties.Set Powered`), discovery while the page is open
+ (`StartDiscovery`/`StopDiscovery`), pair (then `Trusted = true` and `Connect`, like macOS),
+ connect, disconnect and forget (`Adapter1.RemoveDevice`). A soft rfkill block is lifted with the
+ closed action `bt-unblock`.
+- **Pairing agent.** lord-server exports `org.bluez.Agent1` at `/org/lordos/BluetoothAgent` with
+ the `KeyboardDisplay` capability and becomes the default agent. PIN, passkey, numeric comparison
+ and authorization requests are drawn by the system (`BluetoothPrompt`, outside any app) and
+ answered with `lord.bt.answer`; PINs are 1–16 alphanumerics and passkeys 0–999999, validated in C.
+ Calls to the agent from anyone but bluetoothd are refused. A device that went through pairing may
+ use its services without asking again.
+
+ ![Pairing request](ajustes-bluetooth-vincular.png)
+- **Audio.** Headphones and speakers become PipeWire devices through WirePlumber's BlueZ monitor
+ (Debian `libspa-0.2-bluetooth`) and appear in Settings → Sound. WirePlumber 0.5 only enables
+ Bluetooth for a user whose session is active **on a logind seat**; sessions started by
+ `lord-sessiond` are not logind sessions, so LordOS needs this drop-in
+ (`/etc/wireplumber/wireplumber.conf.d/lordos-bluez.conf` on the ISO):
+
+ ```
+ wireplumber.profiles = {
+ main = {
+ monitor.bluez.seat-monitoring = disabled
+ }
+ }
+ ```
+
+ ![A Bluetooth headset in Sound](ajustes-sonido-bluetooth.png)
+
+Tested with `btvirt -l2` (bluez-test-tools) on VM 118: two virtual controllers on one virtual
+radio. hci1 plays a headset (class 0x240404, discoverable, a `bluetoothctl` agent fed through a
+FIFO); from Settings on hci0: discovery, pairing with the numeric-comparison prompt, connection,
+the HFP output and input in Sound, disconnect and forget. Unit tests: `build/bt-test` (managed
+objects, property dictionaries, battery, truncated input, removal, paths, state JSON). **Not tested
+with real hardware** (no controller in the VMs).
+
+## Energy (Battery)
+
+![Energy](ajustes-energia-oscuro.png)
+
+- **Battery.** `hw/power.c` reads `/sys/class/power_supply` (`energy_*`/`power_now` or
+ `charge_*`/`current_now`/`voltage_now`): percentage, time to empty or to full (the kernel's
+ `time_to_*_now` when present), health (`full / full_design`), cycles, watts, model and
+ technology. Device batteries (mice, keyboards: `scope = Device`) are listed but not counted.
+ Refreshed on `power_supply` uevents. Unit-tested over a fake sysfs tree; **untested on a real
+ laptop** (the VMs have no battery and the Debian kernel has no `test_power` module).
+- **Low battery.** A notification at 20 %, 10 % and 5 % (sticky at 5 %) while discharging.
+- **Menu bar.** A battery item with the percentage (optional) through `registerStatusItem`, so
+ every theme that draws `<StatusItems />` shows it; hidden without a system battery.
+- **Energy mode.** power-profiles-daemon over D-Bus (`org.freedesktop.UPower.PowerProfiles`, or the
+ older `net.hadess.PowerProfiles`), following its `PropertiesChanged`. Setting it as the user goes
+ to the daemon; if polkit refuses (the session is not a logind session) the page falls back to the
+ closed action `power-profile`, which runs `/usr/bin/powerprofilesctl set <p>` or, without the
+ daemon, writes the cpufreq governor (`performance`, `schedutil`/`ondemand`, `powersave`) and the
+ energy/performance preference of every policy.
+- **Display off, lock, sleep.** Seconds of inactivity (keyboard, mouse, touchpad, remote input),
+ different on battery and on power. lord-server keeps the deadlines (`display_timeout` in the
+ poll timeout): screen off is the connector's DPMS (`kms_dpms`; nothing is drawn while it is off),
+ "require password" locks the session through `lord-sessiond` N seconds after the screen goes off,
+ and sleep runs the closed action `power-suspend` (`systemctl suspend`). The VM is never put to
+ sleep in the tests.
+- **Power button and lid.** What systemd-logind does (sleep, hibernate, shut down, do nothing). The
+ admin action `power-buttons <power> <lid> <lid-on-ac>` writes
+ `/etc/systemd/logind.conf.d/lordos.conf` (a short list of values, validated) and runs
+ `systemctl reload systemd-logind`. LordOS never grabs the ACPI power button (only keyboards, mice
+ and tablets are grabbed), so logind sees it. Lid rows only show with a battery.
+
+## Notifications
+
+![Notifications](ajustes-notificaciones-oscuro.png)
+
+`sdk/notify.js` gained a policy, applied to every `notify()`:
+
+- **Per app:** allow, style (none / banners / alerts: alerts stay until dismissed), sound, and
+ "show on lock screen" (stored, shown disabled: the lock screen is the greeter and does not show
+ notifications yet). Apps appear after their first notification, plus LordOS apps that notify
+ (Backup, Clock, Settings…) and packages that declare the `notifications` permission. For `.lpk`
+ packages "allow" **is** the sandbox's `notifications` permission (`perms.set`), the same switch as
+ Privacy & Security.
+- **Do Not Disturb:** manual, and every day on a schedule. Notifications are kept in the history
+ without a banner or sound.
+- **Grouping:** several banners from the same app collapse into one with "+N".
+- **Linux apps:** `hw/notifyd.c` serves `org.freedesktop.Notifications` on the session bus
+ (spec 1.2: `Notify`, `CloseNotification`, `GetCapabilities`, `GetServerInformation`,
+ `NotificationClosed`, `ActionInvoked`), so GTK, Qt, Electron and `notify-send` notifications
+ become LordOS banners with the app's icon and actions, and follow the same per-app settings (the
+ key is `linux:<desktop id>`, from the `desktop-entry` hint). Body markup is reduced to text.
+
+ ![A Linux app's notification](ajustes-notificaciones-linux.png)
+
+## Date & Time
+
+![Date & Time](ajustes-fecha-hora-oscuro.png)
+
+- **Automatic time:** systemd-timesyncd, switched with the closed action `time-ntp on|off`
+ (`timedatectl set-ntp`); its state (NTP on, synchronized, available) is read from timedated over
+ D-Bus.
+- **Manual:** `time-set YYYY-MM-DD HH:MM:SS` (`timedatectl set-time`; a real date from 2000 to 2099,
+ only with automatic time off).
+- **Time zone:** a searchable list with the UTC offset of each zone (our TZif reader), applied with
+ the existing `timezone` action. **Never guessed from the network**: no IP leaves the computer.
+- **12/24 hours:** "like the region" (Language & Region), or forced; `formatTime` honors it
+ everywhere.
+- **Menu bar clock:** weekday and date, weekday only or time only, with or without seconds
+ (`menuClock()`; the default theme uses it, the classic one honors the seconds).
+
+## Default Apps
+
+![Default Apps](ajustes-apps-por-defecto-oscuro.png)
+
+Browser, mail, music, video, images, PDF, text editor and terminal. Candidates are LordOS's own apps
+and the Linux apps whose `.desktop` `MimeType` covers the category (terminals: `Categories` with
+`TerminalEmulator`).
+
+- Saved in `~/.config/mimeapps.list` (freedesktop spec: the `[Default Applications]` line is
+ replaced and the app goes first in `[Added Associations]`, as GLib does; every other line is
+ kept), so `xdg-open` and GNOME/KDE apps agree. LordOS apps are written as `lordos-<app>.desktop`.
+ The terminal goes in `~/.config/xdg-terminals.list`.
+- Lookup follows the spec's order (`$XDG_CONFIG_HOME`, `/etc/xdg`, `~/.local/share/applications`,
+ `/usr/local/share/applications`, `/usr/share/applications`, `defaults.list`), with the user's
+ `[Removed Associations]` applied. File types come from shared-mime-info's `globs2` (highest
+ weight, longest pattern, case-sensitive patterns first).
+- **Files** lists the default app first in "Open With", marked "(default)", and double-click opens
+ it. **`lord.apps.launchWith('', path)`** opens a file with the default Linux app for its type
+ (the same rules as `launchWith`: a real path in the home or `/media/$USER`, one argument, no
+ shell); it returns false when the default is a LordOS app, which the theme opens itself.
+
+ ![Open With](ajustes-archivos-abrir-con.png)
+
+## Admin actions
+
+All in `server/src/hw/hw_admin.c`, in the `actions` table through `HW_ADMIN_ACTIONS`:
+
+| Action | Argument | Who | Does |
+|---|---|---|---|
+| `display-brightness` | `<backlight> <value>` | anyone | writes `/sys/class/backlight/<name>/brightness` (real device under `/sys/devices`, `0..max`) |
+| `power-profile` | `performance` \| `balanced` \| `power-saver` | anyone | `/usr/bin/powerprofilesctl set`, or the cpufreq governor and EPP |
+| `power-suspend` | — | anyone | `/usr/bin/systemctl suspend` |
+| `power-buttons` | `<power> <lid> <lid-on-ac>` (`suspend`, `hibernate`, `poweroff`, `ignore`) | admin | generates `/etc/systemd/logind.conf.d/lordos.conf`, `systemctl reload systemd-logind` |
+| `time-ntp` | `on` \| `off` | admin | `/usr/bin/timedatectl set-ntp` |
+| `time-set` | `YYYY-MM-DD HH:MM:SS` | admin | `/usr/bin/timedatectl set-time` |
+| `bt-unblock` | — | anyone | rfkill "unblock all Bluetooth" on `/dev/rfkill` |
+
+The validators are unit-tested in `build/settings-hw-test`.
+
+## Tests
+
+- `build/settings-hw-test` (`make test`): EDID (QEMU's real block, serial/name identities, broken
+ checksums), mode selection and refresh rates, Night Shift math (temperature, ramp, sunrise and
+ sunset in London, Buenos Aires, Tokyo and Svalbard, schedule across midnight, zone1970.tab),
+ mimeapps.list editing and globs2, the power_supply reader, the admin validators. 129 checks.
+- `build/bt-test` (`make test`): BlueZ parsing. 32 checks.
+- On VM 118: live mode changes with revert and keep, persistence across a session restart,
+ rotation, software Night Shift, Bluetooth with `btvirt`, power profiles with
+ power-profiles-daemon (placeholder driver), the logind drop-in, NTP and manual time, Linux
+ notifications with `busctl`, default apps with `xdg-mime` and Files.
+
+## Not done or untested
+
+- Extending or mirroring across several displays (one CRTC).
+- Sharp HiDPI and fractional scales (only the doubled 200 %).
+- Night Shift on the GPU path when the card has no gamma LUT.
+- Brightness, battery, lid and power profiles on real laptops; Bluetooth with real controllers.
+- Notifications on the lock screen; a notification center listing the history.
+- Wayland idle inhibit (a video player does not keep the screen on yet).
+
+## ISO packages
+
+`bluez`, `libspa-0.2-bluetooth`, `power-profiles-daemon`, `systemd-timesyncd` and
+`shared-mime-info`, plus the WirePlumber drop-in above (see the final report for the exact lines).
diff --git a/docs/VM-SETUP.md b/docs/VM-SETUP.md
index 7ef1f65..573585b 100644
--- a/docs/VM-SETUP.md
+++ b/docs/VM-SETUP.md
@@ -767,6 +767,18 @@ Ver `FIREWALL.md`, paso 2. En la VM 122 (172.17.0.56), que ya tenía `lord-sessi
nada grande de internet.
- **Ninguna red tocada:** ni eth0 ni reglas de nftables. Los ganchos son de cgroup y solo
alcanzan a las apps de las sesiones de LordOS.
+- **`systemd-run --user` escape (M8 follow-up, no new packages).** `lord-netperm` now also attaches
+ to each session user's `user@<uid>.service` and applies the per-user restriction union there (see
+ `FIREWALL.md`, «Escape via `systemd-run --user`»). Tested as the restricted app `desktop:aisla`
+ ("no internet"): `systemd-run --user --scope curl`, `systemd-run --user curl` (service) and
+ `setsid curl` all blocked, a normal process unaffected, and `bob`'s restriction not leaking into
+ `lord`'s. Scratch scripts (outside the repo): `~/bin/escape-aisla-122.sh`,
+ `~/union-escape-122.sh`, `~/bob-escape-122.sh`, `~/bin/run-escape-shot-122.sh` and
+ `~/bin/escape-wait-122.sh`. The screenshot `docs/m8-firewall-escape-blocked.png` is a `foot`
+ window opened on the compositor (`WAYLAND_DISPLAY=wayland-0`) running the escape test inside the
+ restricted scope, captured with `qm monitor 122` `screendump`. The lock screen was cleared by a
+ full `lordos.service` restart with autologin (`rm /run/lordos/autologin-done`), not by changing
+ any password.
- **Capturas** con `qm monitor 122` (`screendump`) desde el host. El mouse va por
`/root/lord-qmp-input.py 122`.
- **Marco y colores de las apps Linux** (`WAYLAND.md`):
@@ -806,8 +818,9 @@ and `~/LordOS-m9` were not touched.
`/dev/uhid` and shows up as `/dev/hidrawN` (`root:plugdev 0660`). No real key was available.
- **Fake USB stick:** `/var/tmp/pendrive-pw-116.img` (32 MB ext4, label `PENDRIVE`) loop-mounted at
`/media/pwtest/PENDRIVE` (owned by `pwtest`) for the key-file screenshots.
-- **Remote desktop** turned on (`/etc/lordos/remote/config`: `enabled=1`, `port=5673`) while trying
- the remote-viewer capture.
+- **Remote desktop** was turned on for a while (`/etc/lordos/remote/config`: `enabled=1`,
+ `port=5673`) and turned off again afterwards (file removed). The fake USB stick is unmounted,
+ `softfido`, the local web page and Chromium were stopped at the end.
- **Demo data:** `server/build/vault-demo lordos foto.jpg`, run as `pwtest`, creates a vault with
invented items of every template (test-only master password `lordos`); `/tmp/sitio-pw/` is a
local login page served on 127.0.0.1:8080 for the Chromium test.
@@ -877,3 +890,80 @@ isolated app»). On VM 122 (172.17.0.56):
- **Screenshots:** `qm monitor 122` (`screendump`) on the Proxmox host; the mouse through
`/root/lord-qmp-input.py 122`, typing through `/root/lord-type.py 122`.
- **Network:** untouched (no eth0 change, no nftables).
+
+## Step 22 — Settings: displays, Bluetooth, energy, date and time (VM 118)
+
+See `SETTINGS.md`. On VM 118 (172.17.0.53), which already had `lord-sessiond` with
+`AUTOLOGIN=lord` (step 18):
+
+- **Tree and install:** a copy in `~/LordOS-ajustes` (sent with `tar` over ssh; the VM has no
+ rsync), built there and installed as root into `/usr/local/lib/lordos/{bin,themes,assets}`; the
+ session restarts with `systemctl kill -s KILL --kill-whom=all lordos`, `reset-failed`,
+ `rm /run/lordos/autologin-done` and `start`.
+- **Packages:**
+ - **`bluez`** and **`bluez-test-tools`** (`btvirt`). `modprobe hci_vhci` and `btvirt -l2` (as
+ root, in the background, log in `/tmp/btvirt-ajustes-118.log`) create two virtual controllers
+ on one virtual radio: hci0 is the computer, hci1 plays a headset (alias "Auriculares de prueba",
+ `btmgmt --index 1 class 4 4`, discoverable, a `bluetoothctl` agent fed through the FIFO
+ `/tmp/btctl-ajustes-118.in`, script `~/btpeer-ajustes-118.sh`). Not persistent across reboots.
+ - **`libspa-0.2-bluetooth`**: PipeWire's BlueZ support, so the headset shows up in Sound.
+ - **`power-profiles-daemon`** (placeholder driver in the VM: power-saver and balanced).
+ - `systemd-timesyncd` was already installed.
+- **WirePlumber:** `~/.config/wireplumber/wireplumber.conf.d/lordos-bluez.conf` with
+ `monitor.bluez.seat-monitoring = disabled` (lord-sessiond sessions are not logind seat sessions;
+ without it WirePlumber never enables Bluetooth audio). The ISO needs the same file in
+ `/etc/wireplumber/wireplumber.conf.d/`.
+- **Files written by the tests:** `/etc/systemd/logind.conf.d/lordos.conf` (power button back to
+ `poweroff`, lid `suspend`: logind's defaults), `~/.config/lordos/displays.json` (1280×800),
+ `~/.config/mimeapps.list` (Firefox ESR as browser, Mousepad as text editor),
+ `~/Escritorio/nota-ajustes.txt`. NTP was turned off and on again; the clock was set by hand once.
+- **Screenshots** with `qm monitor 118` (`screendump`, converted to PNG on the Mac) and the mouse
+ through `/root/lord-qmp-input.py 118`.
+
+## Step 23 — M9 system apps and `lord-netd` (VM 119 `lordos-spot`)
+
+See `SYSTEM.md` (Disks, Backups, Logs, Clock, Help) and `RED.md` ("The network belongs to the
+system"). VM 119 still runs LordOS installed like the `.deb` (step 19). It was not reinstalled from
+the ISO.
+
+**Deploy:** the tree is copied to `~/LordOS-sis` (only changed files, so `make` never keeps stale
+objects), built with `make -C server -j4`, and `lord-server`, `lord-sessiond`, `lord-media` and the
+new `lord-netd` are installed root-owned in `/usr/lib/lordos/bin`, with the themes and `assets`.
+
+**Proxmox change (approved by main):** `qm set 119 --sata1 local-lvm:8`, an 8 GB SATA disk (`sdb`,
+"QEMU HARDDISK" on AHCI). QEMU's SATA disk answers ATA SMART; the virtio-scsi `sda` doesn't. It
+**stays** attached for the Disks tests. Remove it with `qm set 119 --delete sata1` and free
+`local-lvm:vm-119-disk-1`. The boot order is unchanged (`scsi0`).
+
+**Service:** `/etc/systemd/system/lordos.service.d/delegate.conf` now has
+`DelegateSubgroup=supervisor` next to `Delegate=yes` (without it `systemctl restart lordos` failed
+while processes survived; see `SESIONES.md`).
+
+**Packages:**
+
+| Package | For |
+|---|---|
+| `exfatprogs` | Disks: format and label exFAT (`mkfs.exfat`, `exfatlabel`); also for the ISO |
+| `ntfs-3g` | Disks: NTFS (optional; without `mkfs.ntfs` the app doesn't offer it) |
+
+`dosfstools` and `e2fsprogs` were already installed.
+
+**Test-only setup (not part of LordOS):**
+
+| Item | For |
+|---|---|
+| `/usr/local/sbin/lordos-test-netns` + `lordos-test-netns.service` (enabled, `Before=lordos.service`) | netns `lnt` with `dnsmasq` (`10.77.0.50-99`, no router, `--leasefile-ro`) behind the veth `lnt0`, so `lord-netd` has a NIC of its own to bring up at boot; `eth0` (netplan) is never touched |
+| `/etc/lordos/net/if/lnt0.conf` (`method=dhcp`) | the saved profile `lord-netd` restores at boot |
+| `/etc/lordos/remote/config` `enabled=1` | remote desktop reachable before login (the test); set back to `enabled=0` after the tests if it isn't needed |
+| user `ana` ("Ana Prueba", created in Settings → Users, test password) | second user for the login/logout test and the home-folder check |
+| `dummy_hcd` + `g_mass_storage file=/var/tmp/usb-disk-sistema-119.img removable=1 stall=0` | a real USB mass-storage stick inside the VM (sdc, TRAN usb, RM 1) for Disks; remove with `sudo rmmod g_mass_storage dummy_hcd` |
+| `~/Descargas/lordos-prueba.img` (300 MB) | image for the bootable-USB test |
+| ext4 image on a loop device under `/media/lord` | Backups destination during the tests (deleted afterwards) |
+
+To undo the network test: `sudo systemctl disable --now lordos-test-netns`, `sudo ip netns del lnt`,
+`sudo rm /etc/lordos/net/if/lnt0.conf /usr/local/sbin/lordos-test-netns
+/etc/systemd/system/lordos-test-netns.service`.
+
+**Screenshots** with `qm monitor 119` (`screendump … -f png`) and the mouse through
+`/root/lord-qmp-input.py 119`, holding `flock /tmp/sistema-119-screen.lock` on the host while
+driving the screen.
diff --git a/docs/ajustes-apps-por-defecto-claro.png b/docs/ajustes-apps-por-defecto-claro.png
new file mode 100644
index 0000000..b6004d6
Binary files /dev/null and b/docs/ajustes-apps-por-defecto-claro.png differ
diff --git a/docs/ajustes-apps-por-defecto-oscuro.png b/docs/ajustes-apps-por-defecto-oscuro.png
new file mode 100644
index 0000000..91d1a68
Binary files /dev/null and b/docs/ajustes-apps-por-defecto-oscuro.png differ
diff --git a/docs/ajustes-archivos-abrir-con.png b/docs/ajustes-archivos-abrir-con.png
new file mode 100644
index 0000000..30bfeb4
Binary files /dev/null and b/docs/ajustes-archivos-abrir-con.png differ
diff --git a/docs/ajustes-bluetooth-claro.png b/docs/ajustes-bluetooth-claro.png
new file mode 100644
index 0000000..91c3452
Binary files /dev/null and b/docs/ajustes-bluetooth-claro.png differ
diff --git a/docs/ajustes-bluetooth-oscuro.png b/docs/ajustes-bluetooth-oscuro.png
new file mode 100644
index 0000000..2054363
Binary files /dev/null and b/docs/ajustes-bluetooth-oscuro.png differ
diff --git a/docs/ajustes-bluetooth-vincular.png b/docs/ajustes-bluetooth-vincular.png
new file mode 100644
index 0000000..ac56096
Binary files /dev/null and b/docs/ajustes-bluetooth-vincular.png differ
diff --git a/docs/ajustes-energia-claro.png b/docs/ajustes-energia-claro.png
new file mode 100644
index 0000000..11c9a88
Binary files /dev/null and b/docs/ajustes-energia-claro.png differ
diff --git a/docs/ajustes-energia-oscuro.png b/docs/ajustes-energia-oscuro.png
new file mode 100644
index 0000000..6e66566
Binary files /dev/null and b/docs/ajustes-energia-oscuro.png differ
diff --git a/docs/ajustes-fecha-hora-claro.png b/docs/ajustes-fecha-hora-claro.png
new file mode 100644
index 0000000..eca9cb7
Binary files /dev/null and b/docs/ajustes-fecha-hora-claro.png differ
diff --git a/docs/ajustes-fecha-hora-oscuro.png b/docs/ajustes-fecha-hora-oscuro.png
new file mode 100644
index 0000000..bd2fbde
Binary files /dev/null and b/docs/ajustes-fecha-hora-oscuro.png differ
diff --git a/docs/ajustes-night-shift.png b/docs/ajustes-night-shift.png
new file mode 100644
index 0000000..cb61d3d
Binary files /dev/null and b/docs/ajustes-night-shift.png differ
diff --git a/docs/ajustes-notificaciones-app-claro.png b/docs/ajustes-notificaciones-app-claro.png
new file mode 100644
index 0000000..db0e14d
Binary files /dev/null and b/docs/ajustes-notificaciones-app-claro.png differ
diff --git a/docs/ajustes-notificaciones-claro.png b/docs/ajustes-notificaciones-claro.png
new file mode 100644
index 0000000..0f0b0a0
Binary files /dev/null and b/docs/ajustes-notificaciones-claro.png differ
diff --git a/docs/ajustes-notificaciones-linux.png b/docs/ajustes-notificaciones-linux.png
new file mode 100644
index 0000000..4aa3ec3
Binary files /dev/null and b/docs/ajustes-notificaciones-linux.png differ
diff --git a/docs/ajustes-notificaciones-oscuro.png b/docs/ajustes-notificaciones-oscuro.png
new file mode 100644
index 0000000..92e1beb
Binary files /dev/null and b/docs/ajustes-notificaciones-oscuro.png differ
diff --git a/docs/ajustes-pantallas-200.png b/docs/ajustes-pantallas-200.png
new file mode 100644
index 0000000..cb3171d
Binary files /dev/null and b/docs/ajustes-pantallas-200.png differ
diff --git a/docs/ajustes-pantallas-claro.png b/docs/ajustes-pantallas-claro.png
new file mode 100644
index 0000000..41d6bc3
Binary files /dev/null and b/docs/ajustes-pantallas-claro.png differ
diff --git a/docs/ajustes-pantallas-oscuro.png b/docs/ajustes-pantallas-oscuro.png
new file mode 100644
index 0000000..ee07cff
Binary files /dev/null and b/docs/ajustes-pantallas-oscuro.png differ
diff --git a/docs/ajustes-pantallas-revertir-claro.png b/docs/ajustes-pantallas-revertir-claro.png
new file mode 100644
index 0000000..6f0e4f8
Binary files /dev/null and b/docs/ajustes-pantallas-revertir-claro.png differ
diff --git a/docs/ajustes-pantallas-revertir.png b/docs/ajustes-pantallas-revertir.png
new file mode 100644
index 0000000..580bf78
Binary files /dev/null and b/docs/ajustes-pantallas-revertir.png differ
diff --git a/docs/ajustes-pantallas-rotada.png b/docs/ajustes-pantallas-rotada.png
new file mode 100644
index 0000000..29d9151
Binary files /dev/null and b/docs/ajustes-pantallas-rotada.png differ
diff --git a/docs/ajustes-sonido-bluetooth.png b/docs/ajustes-sonido-bluetooth.png
new file mode 100644
index 0000000..db98e62
Binary files /dev/null and b/docs/ajustes-sonido-bluetooth.png differ
diff --git a/docs/m8-firewall-escape-blocked.png b/docs/m8-firewall-escape-blocked.png
new file mode 100644
index 0000000..b97baa2
Binary files /dev/null and b/docs/m8-firewall-escape-blocked.png differ
diff --git a/docs/m9-contrasenas-app-captura.png b/docs/m9-contrasenas-app-captura.png
new file mode 100644
index 0000000..126c638
Binary files /dev/null and b/docs/m9-contrasenas-app-captura.png differ
diff --git a/docs/m9-contrasenas-app-powerbox.png b/docs/m9-contrasenas-app-powerbox.png
new file mode 100644
index 0000000..35568e7
Binary files /dev/null and b/docs/m9-contrasenas-app-powerbox.png differ
diff --git a/docs/m9-contrasenas-captura-protegida.png b/docs/m9-contrasenas-captura-protegida.png
new file mode 100644
index 0000000..55b57e2
Binary files /dev/null and b/docs/m9-contrasenas-captura-protegida.png differ
diff --git a/docs/m9-contrasenas-categorias.png b/docs/m9-contrasenas-categorias.png
new file mode 100644
index 0000000..909b0ac
Binary files /dev/null and b/docs/m9-contrasenas-categorias.png differ
diff --git a/docs/m9-contrasenas-cripto.png b/docs/m9-contrasenas-cripto.png
new file mode 100644
index 0000000..bacd0e3
Binary files /dev/null and b/docs/m9-contrasenas-cripto.png differ
diff --git a/docs/m9-contrasenas-finanzas.png b/docs/m9-contrasenas-finanzas.png
new file mode 100644
index 0000000..a290a10
Binary files /dev/null and b/docs/m9-contrasenas-finanzas.png differ
diff --git a/docs/m9-contrasenas-licencia.png b/docs/m9-contrasenas-licencia.png
new file mode 100644
index 0000000..e8d06a2
Binary files /dev/null and b/docs/m9-contrasenas-licencia.png differ
diff --git a/docs/m9-contrasenas-pantalla-real.png b/docs/m9-contrasenas-pantalla-real.png
new file mode 100644
index 0000000..06457c3
Binary files /dev/null and b/docs/m9-contrasenas-pantalla-real.png differ
diff --git a/docs/m9-contrasenas-selector-en-linea.png b/docs/m9-contrasenas-selector-en-linea.png
new file mode 100644
index 0000000..a2961c1
Binary files /dev/null and b/docs/m9-contrasenas-selector-en-linea.png differ
diff --git a/docs/m9-contrasenas-ssh.png b/docs/m9-contrasenas-ssh.png
new file mode 100644
index 0000000..87d5c00
Binary files /dev/null and b/docs/m9-contrasenas-ssh.png differ
diff --git a/docs/m9-contrasenas-tarjeta.png b/docs/m9-contrasenas-tarjeta.png
new file mode 100644
index 0000000..a71bbd4
Binary files /dev/null and b/docs/m9-contrasenas-tarjeta.png differ
diff --git a/sdk/apps.js b/sdk/apps.js
index 5b193e0..bc181c0 100644
--- a/sdk/apps.js
+++ b/sdk/apps.js
@@ -12,7 +12,7 @@ import { createElement as h } from 'react';
import { View, Text, Image } from '@lordos/runtime';
import { createStore, useStore } from './store.js';
import { locale, appName } from './i18n.js';
-import { listApps, wm, appRegistry, getApp as registryApp } from './windows.js';
+import { listApps, wm, windows, appRegistry, getApp as registryApp } from './windows.js';
const DESKTOP = 'desktop:';
export const isLinuxApp = (id) => String(id).startsWith(DESKTOP);
@@ -81,6 +81,12 @@ export function launchApp(id) {
const app = registryApp(id);
if (app && app.package && typeof lord.apps !== 'undefined' && typeof lord.apps.launchPackage === 'function')
return lord.apps.launchPackage(id);
+ // a built-in app that runs as its own sandboxed process (manifest "process": "isolated")
+ if (app && app.isolated && typeof lord.apps !== 'undefined' && typeof lord.apps.launchPackage === 'function') {
+ const running = windows.get().filter((w) => w.args?.pkg && w.args?.appId === id);
+ if (running.length) { wm.focus(running[running.length - 1].id); return true; }
+ if (lord.apps.launchPackage(id)) return true;
+ }
return wm.open(id) != null;
}
@@ -99,7 +105,7 @@ export function windowIcon(w, getApp) {
if (String(w?.id).startsWith('linux#')) {
// una app .lpk aislada (lord-server --app) llega como ventana Wayland con app_id = su id
const pkg = appId ? registryApp(appId) : null;
- if (pkg && pkg.package && pkg.Icon) return pkg.Icon;
+ if (pkg && (pkg.package || pkg.isolated) && pkg.Icon) return pkg.Icon;
const a = linuxAppFor(appId);
return a ? a.Icon : ({ size }) => h(LetterIcon, { size, name: appId || w?.title || 'Linux' });
}
diff --git a/sdk/calendar.js b/sdk/calendar.js
new file mode 100644
index 0000000..a3f5e9f
--- /dev/null
+++ b/sdk/calendar.js
@@ -0,0 +1,149 @@
+// calendar.js — Calendar and Reminders (docs/MAIL.md): calendars, events and to-dos kept by
+// lord-maild (local, or synced with CalDAV), and the scheduler that rings their alarms with the
+// apps closed, like the Clock alarms (sdk/alarms.js).
+//
+// calendars.list() → [{ id, name, color, acct, acctName, kind: 'local'|'dav', todos, events, hidden, count }]
+// calendars.create({ name, color, todos, events }) / update(id, { name, color, hidden }) / remove(id)
+// events.range(from, to, cals?) → occurrences [{ uid, title, loc, notes, url, start, end (ms), allDay,
+// sdate, edate ('YYYY-MM-DD' for all-day), tz, rrule, occ, alarms: [minutes], org, att: [{ email, name, ps }],
+// status, cal, color }]
+// events.save(cal, event, { from }) → uid (event: { uid?, title, start, end, allDay, loc, notes, url, rrule,
+// alarms, att, tz }; from = previous calendar when moving)
+// events.remove(cal, uid, { occ, all }) one occurrence of a series (occ) or the whole event
+// events.importFile(path, cal)
+// reminders.lists() → calendars with todos
+// reminders.items(lists?) → [{ uid, title, notes, due (ms|null), dueAllDay, dueDate, prio (0, 1 high, 5, 9 low),
+// flag, done, doneAt, parent, list, color, alarms }]
+// reminders.save(list, todo, { from }) / remove(list, uid) / toggle(item)
+// usePim() → a revision number that changes whenever calendars, events, to-dos or contacts change
+// startReminders() called by startShell
+import { useEffect, useState } from 'react';
+import { createStore, useStore } from './store.js';
+import { mailRequest, onMailEvent } from './mail.js';
+import { notify, dismissNotification } from './notify.js';
+import { settings } from './settings.js';
+import { t, formatTime } from './i18n.js';
+import { wm, getApp } from './windows.js';
+
+export const pimRev = createStore(0);
+let hooked = false;
+function hook() {
+ if (hooked) return;
+ hooked = true;
+ onMailEvent((ev) => { if (ev.ev === 'pim-changed' || ev.ev === 'ready' || ev.ev === 'crash') pimRev.set((v) => v + 1); });
+}
+export function usePim() { hook(); return useStore(pimRev); }
+
+export const calendars = {
+ list: async () => { hook(); return (await mailRequest('cal-list')).cals || []; },
+ create: (c) => mailRequest('cal-create', c),
+ update: (id, patch) => mailRequest('cal-update', { id, ...patch }),
+ remove: (id) => mailRequest('cal-delete', { id }),
+};
+
+export const events = {
+ range: async (from, to, cals) => (await mailRequest('ev-list', { from: +from, to: +to, ...(cals ? { cals } : {}) })).events || [],
+ save: async (cal, event, { from } = {}) => (await mailRequest('ev-save', { cal, event, ...(from ? { from } : {}) })).uid,
+ remove: (cal, uid, { occ, all } = {}) => mailRequest('ev-delete', { cal, uid, ...(occ ? { occ } : {}), ...(all ? { all: true } : {}) }),
+ importFile: (path, cal) => mailRequest('ev-import', { cal }, { files: [path] }),
+};
+
+export const reminders = {
+ lists: async () => (await calendars.list()).filter((c) => c.todos),
+ items: async (lists) => (await mailRequest('todo-list', lists ? { lists } : {})).todos || [],
+ save: async (list, todo, { from } = {}) => (await mailRequest('todo-save', { list, todo, ...(from ? { from } : {}) })).uid,
+ remove: (list, uid) => mailRequest('todo-delete', { list, uid }),
+ toggle: (item) => reminders.save(item.list, { ...item, done: !item.done }),
+};
+
+// ---- alarms with the apps closed ----
+//
+// Upcoming alarms come from lord-maild ('alarms' for the next 36 hours). One setTimeout to the
+// next one (cut in ≤ 1 minute pieces when close, like the Clock, because the monotonic clock
+// stops during suspend). An alarm missed by less than 10 minutes still rings; what was shown is
+// remembered in settings.pimAlarms.fired so it never rings twice.
+
+const MIN = 60000, LATE = 10 * MIN, AHEAD = 36 * 60 * MIN;
+let list = [], timer = null, started = false, refreshing = false;
+const keyOf = (a) => `${a.cal}|${a.uid}|${a.at}`;
+const fired = () => settings.get().pimAlarms?.fired || {};
+function markFired(k) {
+ const now = Date.now();
+ const f = Object.fromEntries(Object.entries(fired()).filter(([, v]) => now - v < 3 * 86400000));
+ f[k] = now;
+ settings.set({ pimAlarms: { ...(settings.get().pimAlarms || {}), fired: f } });
+}
+const snoozed = createStore([]); // [{ ...alarm, at }] in memory
+
+function ring(a) {
+ markFired(keyOf(a));
+ const when = a.allDay ? '' : formatTime(new Date(a.start));
+ const body = [when, a.loc].filter(Boolean).join(' · ');
+ const isTodo = a.kind === 'todo';
+ const app = isTodo ? 'reminders' : 'calendar';
+ const actions = [
+ { id: 'snooze', label: t('calendar.alarm.snooze'), run: () => { snoozed.set((s) => [...s, { ...a, at: Date.now() + 10 * MIN, snooze: true }]); arm(); } },
+ ];
+ if (isTodo) actions.push({ id: 'done', label: t('reminders.alarm.done'), primary: true, run: () => completeTodo(a) });
+ actions.push({ id: 'open', label: t('calendar.alarm.open'), run: () => { if (getApp(app)) wm.open(app, { args: { uid: a.uid, cal: a.cal, at: a.start, nonce: Date.now() } }); } });
+ notify({ app, title: a.title || t(isTodo ? 'reminders.untitled' : 'calendar.untitled'), body, sticky: true, sound: true, actions });
+}
+
+async function completeTodo(a) {
+ try {
+ const items = await reminders.items([a.cal]);
+ const it = items.find((x) => x.uid === a.uid);
+ if (it) await reminders.save(it.list, { ...it, done: true });
+ } catch (e) { /* not running */ }
+}
+
+function arm() {
+ if (timer) { clearTimeout(timer); timer = null; }
+ const now = Date.now();
+ const f = fired();
+ const pending = [...list, ...snoozed.get()].filter((a) => !f[keyOf(a)] || a.snooze);
+ // due now (or missed by a little)
+ for (const a of pending) {
+ if (a.at <= now && now - a.at < LATE) {
+ if (a.snooze) snoozed.set((s) => s.filter((x) => x !== a));
+ ring(a);
+ }
+ }
+ const next = pending.filter((a) => a.at > now).sort((x, y) => x.at - y.at)[0];
+ const wait = next ? Math.min(next.at - now, next.at - now < 60 * MIN ? MIN : 10 * MIN) : 10 * MIN;
+ timer = setTimeout(() => { if (Date.now() - lastFetch > 30 * MIN) refresh(); else arm(); }, Math.max(500, wait));
+}
+
+let lastFetch = 0;
+async function refresh() {
+ if (refreshing) return;
+ refreshing = true;
+ try {
+ const now = Date.now();
+ const r = await mailRequest('alarms', { from: now - LATE, to: now + AHEAD });
+ list = r.alarms || [];
+ lastFetch = Date.now();
+ } catch (e) { /* lord-maild not there yet: try later */ }
+ refreshing = false;
+ arm();
+}
+
+export function startReminders() {
+ if (started || typeof lord === 'undefined' || !lord.mail || !lord.mail.available()) return;
+ started = true;
+ hook();
+ let last = pimRev.get();
+ pimRev.subscribe(() => { if (pimRev.get() !== last) { last = pimRev.get(); refresh(); } });
+ setTimeout(refresh, 1500);
+}
+
+// small helper for apps: the current date at midnight
+export const startOfDay = (d) => { const x = new Date(d); x.setHours(0, 0, 0, 0); return x; };
+export { dismissNotification };
+// a tiny hook for apps that show a value loaded from lord-maild (rev = usePim())
+export function usePimQuery(fn, deps = []) {
+ const rev = usePim();
+ const [v, setV] = useState(null);
+ useEffect(() => { let live = true; fn().then((x) => { if (live) setV(x); }).catch(() => { if (live) setV(null); }); return () => { live = false; }; }, [rev, ...deps]);
+ return v;
+}
diff --git a/sdk/contacts.js b/sdk/contacts.js
new file mode 100644
index 0000000..19ff2a9
--- /dev/null
+++ b/sdk/contacts.js
@@ -0,0 +1,78 @@
+// contacts.js — Contacts (docs/MAIL.md): address books kept by lord-maild (local, or synced
+// with CardDAV). Mail autocompletes addresses from here and from the people you write to.
+//
+// books.list() → [{ id, name, color, acct, acctName, kind: 'local'|'dav', count }]
+// books.create({ name }) / update(id, { name }) / remove(id)
+// contacts.list(book?) → [{ uid, book, fn, n: { family, given, middle, prefix, suffix }, nick, org, dept, title,
+// emails: [{ type, value }], phones, urls, im, addrs: [{ type, street, city, region, code, country }],
+// bday ('YYYY-MM-DD'), notes, cats: [], photo: bool, kind: 'individual'|'group', members: [uid] }]
+// contacts.save(book, contact, { photo: 'keep' | 'remove' | path }) → uid
+// contacts.remove(book, uid) / importFile(path, book)
+// contacts.photo(book, uid, size) → image handle for <ContactPhoto> (decoded in lord-maild)
+// contacts.autocomplete(q) → [{ name, email, src: 'contacts'|'mail' }]
+// displayName(c) / initials(c)
+// <ContactPhoto contact size /> the photo or the initials on a colored circle
+import { createElement as h, useEffect, useRef, useState } from 'react';
+import { View, Text, Image } from '@lordos/runtime';
+import { mailRequest } from './mail.js';
+import { usePim } from './calendar.js';
+
+export const books = {
+ list: async () => (await mailRequest('book-list')).books || [],
+ create: (b) => mailRequest('book-create', b),
+ update: (id, patch) => mailRequest('book-update', { id, ...patch }),
+ remove: (id) => mailRequest('book-delete', { id }),
+};
+
+export const contacts = {
+ list: async (book) => (await mailRequest('contact-list', book ? { book } : {})).contacts || [],
+ async save(book, contact, { photo = 'keep' } = {}) {
+ const isPath = photo && photo !== 'keep' && photo !== 'remove';
+ const r = await mailRequest('contact-save', { book, contact, photo: isPath ? 'new' : photo }, isPath ? { files: [photo] } : {});
+ return r.uid;
+ },
+ remove: (book, uid) => mailRequest('contact-delete', { book, uid }),
+ importFile: (path, book) => mailRequest('contact-import', { book }, { files: [path] }),
+ photo: async (book, uid, size = 128) => (await mailRequest('contact-photo', { book, uid, size })).image,
+ autocomplete: async (q) => (await mailRequest('autocomplete', { q })).items || [],
+};
+
+export function displayName(c) {
+ if (!c) return '';
+ if (c.fn) return c.fn;
+ const n = c.n || {};
+ const full = [n.prefix, n.given, n.middle, n.family, n.suffix].filter(Boolean).join(' ');
+ return full || c.org || c.emails?.[0]?.value || '';
+}
+
+export function initials(c) {
+ const n = c?.n || {};
+ const a = (n.given || '').trim()[0] || '', b = (n.family || '').trim()[0] || '';
+ if (a || b) return (a + b).toUpperCase();
+ const d = displayName(c).trim();
+ return d ? [...d][0].toUpperCase() : '?';
+}
+
+const PALETTE = ['#ff6b6b', '#f7a440', '#e0b400', '#4cb860', '#36a3d9', '#6c7ae0', '#b06ad9', '#e05f9b', '#8e8e93'];
+const colorOf = (s) => { let x = 0; for (const ch of String(s || '')) x = (x * 31 + ch.codePointAt(0)) >>> 0; return PALETTE[x % PALETTE.length]; };
+
+export function ContactPhoto({ contact, size = 40 }) {
+ const rev = usePim();
+ const ref = useRef(null);
+ const [handle, setHandle] = useState(0);
+ const want = contact?.photo && contact.book && contact.uid;
+ useEffect(() => {
+ let live = true;
+ if (!want) { setHandle(0); return undefined; }
+ contacts.photo(contact.book, contact.uid, Math.min(512, Math.round(size * 2))).then((img) => { if (live) setHandle(img || 0); }).catch(() => { if (live) setHandle(0); });
+ return () => { live = false; };
+ }, [contact?.uid, contact?.book, want, rev, size]);
+ useEffect(() => {
+ if (ref.current && handle) lord.mail.bind(ref.current.id, handle);
+ return () => { if (handle) lord.mail.release(handle); };
+ }, [handle]);
+ const box = { width: size, height: size, borderRadius: size / 2, overflow: 'hidden' };
+ if (want && handle) return h(View, { style: box }, h(Image, { ref, style: { width: size, height: size, objectFit: 'cover' } }));
+ return h(View, { style: { ...box, backgroundColor: colorOf(displayName(contact)), alignItems: 'center', justifyContent: 'center' } },
+ h(Text, { style: { color: '#fff', fontSize: size * 0.4, fontWeight: 600 } }, initials(contact)));
+}
diff --git a/sdk/controls.jsx b/sdk/controls.jsx
index 47b481c..7df594c 100644
--- a/sdk/controls.jsx
+++ b/sdk/controls.jsx
@@ -88,6 +88,18 @@ export function Toolbar({ children, style, separator = true }) {
export const ToolbarSpacer = () => <View style={{ flex: 1 }} />;
+// 1 px hairline on one edge of its parent (absolutely positioned). edge: 'top' | 'bottom' |
+// 'start' | 'end'; start and end follow the UI direction (the engine's left/right are physical).
+// inset: space left at both ends of the line.
+export function Hairline({ edge = 'bottom', inset = 0 }) {
+ const t = useTheme();
+ const rtl = direction() === 'rtl';
+ const side = edge === 'start' ? (rtl ? 'right' : 'left') : edge === 'end' ? (rtl ? 'left' : 'right') : edge;
+ const box = side === 'top' || side === 'bottom'
+ ? { left: inset, right: inset, [side]: 0, height: 1 } : { top: inset, bottom: inset, [side]: 0, width: 1 };
+ return <View style={{ position: 'absolute', backgroundColor: t.separator, pointerEvents: 'none', ...box }} />;
+}
+
// Thin vertical divider between toolbar groups.
export function ToolbarDivider() {
const t = useTheme();
diff --git a/sdk/dock.js b/sdk/dock.js
index 21e35b7..e5ecd59 100644
--- a/sdk/dock.js
+++ b/sdk/dock.js
@@ -73,7 +73,7 @@ windows.subscribe(() => {
export function launcherIdOf(w) {
if (!String(w.id).startsWith('linux#')) return appIdOf(w.id);
const appId = w.args?.appId || '';
- if (w.args?.pkg && appId && getApp(appId)?.package) return appId; // isolated .lpk app: grouped under its own entry
+ if (w.args?.pkg && appId && (getApp(appId)?.package || getApp(appId)?.isolated)) return appId; // isolated app (.lpk or built-in): grouped under its own entry
const a = linuxAppFor(appId);
return a ? a.id : `linux:${appId || w.id}`;
}
diff --git a/sdk/emoji.jsx b/sdk/emoji.jsx
index e25a39b..9472855 100644
--- a/sdk/emoji.jsx
+++ b/sdk/emoji.jsx
@@ -17,7 +17,8 @@ import { settings } from './settings.js';
import { useTheme } from './theme.js';
import { t, locale } from './i18n.js';
import { ime } from './ime.js';
-import { TextInput, ScrollView, focusToken, restoreFocus } from './components.jsx';
+import { ScrollView, focusToken, restoreFocus } from './components.jsx';
+import { SearchField } from './controls.jsx';
import { clipboard, toast } from './clipboard.js';
import { wm } from './windows.js';
import { EMOJI_GROUPS, TONED } from './emojidata.js';
@@ -136,25 +137,30 @@ addListener('keyup', (e) => { if (e.code === 125 || e.code === 126) superDown =
const GROUP_ICON = { recent: '🕘', smileys: '😀', people: '👋', animals: '🐻', food: '🍔', travel: '🚗', activities: '⚽', objects: '💡', symbols: '❤️', flags: '🏁' };
const COLS = 9, CELL = 36;
-export function Grid({ list, sel, onPick, onHover, tone, size = CELL, th }) {
+// Emoji grid. cols: cells per row (default 9, the picker's width); wrap: fill the available width
+// instead (the Characters window). picked: the chosen character, drawn selected.
+export function Grid({ list, sel, onPick, onHover, tone, size = CELL, th, cols = COLS, wrap = false, picked }) {
+ const cell = (ch, i) => {
+ const shown = emoji.withTone(ch, tone);
+ const on = sel === i || (picked != null && picked === shown);
+ return h(View, {
+ key: ch, onClick: () => onPick(shown), onMouseEnter: () => onHover?.(i),
+ style: { width: size, height: size, borderRadius: 8, alignItems: 'center', justifyContent: 'center', backgroundColor: on ? `${th.accent}55` : 'transparent' },
+ }, h(Text, { style: { fontSize: Math.round(size * 0.62), lineHeight: size } }, shown));
+ };
+ if (wrap) return h(View, { style: { flexDirection: 'row', flexWrap: 'wrap' } }, list.map(cell));
const rows = [];
- for (let i = 0; i < list.length; i += COLS) rows.push(list.slice(i, i + COLS));
+ for (let i = 0; i < list.length; i += cols) rows.push(list.slice(i, i + cols));
return h(View, { style: { gap: 0 } }, rows.map((r, ri) => h(View, { key: ri, style: { flexDirection: 'row' } },
- r.map((ch, ci) => {
- const i = ri * COLS + ci;
- const shown = emoji.withTone(ch, tone);
- return h(View, {
- key: ch, onClick: () => onPick(shown), onMouseEnter: () => onHover?.(i),
- style: { width: size, height: size, borderRadius: 7, alignItems: 'center', justifyContent: 'center', backgroundColor: sel === i ? th.accent + '55' : 'transparent' },
- }, h(Text, { style: { fontSize: Math.round(size * 0.62), lineHeight: size } }, shown));
- }))));
+ r.map((ch, ci) => cell(ch, ri * cols + ci)))));
}
-export function ToneBar({ tone, onTone, th }) {
- return h(View, { style: { flexDirection: 'row', gap: 4 } }, TONE_CP.map((cp, i) => h(View, {
+// Skin tone choice. size: the diameter of each swatch (22 by default; the picker uses a smaller one).
+export function ToneBar({ tone, onTone, th, size = 22 }) {
+ return h(View, { style: { flexDirection: 'row', gap: size < 22 ? 2 : 4 } }, TONE_CP.map((cp, i) => h(View, {
key: i, onClick: () => onTone(i),
- style: { width: 22, height: 22, borderRadius: 11, alignItems: 'center', justifyContent: 'center', border: `2px solid ${tone === i ? th.accent : 'transparent'}` },
- }, h(Text, { style: { fontSize: 14 } }, cp ? String.fromCodePoint(0x270b, cp) : '✋'))));
+ style: { width: size, height: size, borderRadius: size / 2, alignItems: 'center', justifyContent: 'center', border: `2px solid ${tone === i ? th.accent : 'transparent'}` },
+ }, h(Text, { style: { fontSize: Math.round(size * 0.62) } }, cp ? String.fromCodePoint(0x270b, cp) : '✋'))));
}
function Panel() {
@@ -186,7 +192,7 @@ function Panel() {
return false;
};
// donde está el cursor del campo; si no, al medio de la pantalla
- const W = COLS * CELL + 20, H = 400;
+ const W = COLS * CELL + 24, H = 404;
const c = target?.caret;
const left = Math.max(8, Math.min(screen.width - W - 8, c ? c.x - 20 : screen.width / 2 - W / 2));
const top = c ? (c.y + c.h + H + 8 < screen.height ? c.y + c.h + 6 : Math.max(8, c.y - H - 6)) : Math.max(40, screen.height / 2 - H / 2);
@@ -196,24 +202,26 @@ function Panel() {
return h(View, {
emojiPanel: true,
style: { position: 'absolute', left, top, width: W, height: H, borderRadius: 12, backgroundColor: th.windowBg, border: `1px solid ${th.separator}`,
- boxShadow: '0 14px 40px rgba(0,0,0,0.45)', padding: 10, gap: 8 },
+ boxShadow: '0 14px 40px rgba(0,0,0,0.45)', padding: 12, gap: 8 },
},
- h(TextInput, { value: q, onChange: setQ, autoFocus: true, placeholder: t('emoji.search'), onCancel: () => panel.set(false),
- onSubmit: () => { if (list[sel]) pick(emoji.withTone(list[sel], tone)); }, onKeyDown: onKey, style: { height: 28 } }),
+ h(SearchField, { value: q, onChange: setQ, autoFocus: true, placeholder: t('emoji.search'), onCancel: () => panel.set(false),
+ onSubmit: () => { if (list[sel]) pick(emoji.withTone(list[sel], tone)); }, onKeyDown: onKey }),
!q.trim() && h(View, { style: { flexDirection: 'row', justifyContent: 'space-between', direction: 'ltr' } }, ids.map((id) => h(View, {
key: id, onClick: () => setGroup(id),
- style: { width: 30, height: 26, borderRadius: 6, alignItems: 'center', justifyContent: 'center', backgroundColor: group === id ? th.hover : 'transparent' },
+ style: { width: 30, height: 28, borderRadius: 6, alignItems: 'center', justifyContent: 'center',
+ backgroundColor: group === id ? (th.mode === 'dark' ? 'rgba(255,255,255,0.12)' : 'rgba(0,0,0,0.08)') : 'transparent' },
}, h(Text, { style: { fontSize: 15 } }, GROUP_ICON[id])))),
- h(Text, { style: { fontSize: 11, fontWeight: 700, color: th.textDim } }, q.trim() ? t('emoji.results', { count: list.length }) : t(`emoji.group.${group}`)),
+ h(Text, { style: { fontSize: 11, fontWeight: 600, color: th.textDim, marginTop: 2, paddingHorizontal: 2 } }, q.trim() ? t('emoji.results', { count: list.length }) : t(`emoji.group.${group}`)),
h(View, { style: { flex: 1, direction: 'ltr' } },
list.length ? h(ScrollView, { style: { flex: 1 }, scrollRef: scroll }, h(Grid, { list, sel, onPick: pick, onHover: setHover, tone, th }))
: h(Text, { style: { margin: 16, fontSize: 12, color: th.textDim, textAlign: 'center' } }, group === 'recent' && !q.trim() ? t('emoji.noRecent') : t('emoji.none'))),
h(View, { style: { height: 1, backgroundColor: th.separator } }),
- h(View, { style: { flexDirection: 'row', alignItems: 'center', gap: 8 } },
- h(Text, { style: { fontSize: 22, width: 30 } }, label ? emoji.withTone(label, tone) : ''),
- h(Text, { style: { flex: 1, fontSize: 11, color: th.textDim, whiteSpace: 'nowrap', overflow: 'hidden' } }, label ? emoji.name(label) : ''),
- h(ToneBar, { tone, onTone: (n) => { setToneState(n); emoji.setTone(n); }, th }),
- h(View, { onClick: () => { panel.set(false); wm.open('characters'); }, style: { paddingHorizontal: 4 } }, h(Text, { style: { fontSize: 11, color: th.accent } }, t('emoji.more')))));
+ h(View, { style: { height: 30, flexDirection: 'row', alignItems: 'center', gap: 8 } },
+ h(Text, { style: { fontSize: 20, width: 24, textAlign: 'center' } }, label ? emoji.withTone(label, tone) : ''),
+ h(View, { style: { flex: 1, minWidth: 0, overflow: 'hidden' } },
+ h(Text, { style: { fontSize: 12, color: th.textDim, whiteSpace: 'nowrap' } }, label ? emoji.name(label) : '')),
+ h(ToneBar, { tone, onTone: (n) => { setToneState(n); emoji.setTone(n); }, th, size: 20 }),
+ h(View, { onClick: () => { panel.set(false); wm.open('characters'); }, style: { paddingHorizontal: 4 } }, h(Text, { style: { fontSize: 12, color: th.accent, whiteSpace: 'nowrap' } }, t('emoji.more')))));
}
export function EmojiPanel() {
diff --git a/sdk/filepicker.jsx b/sdk/filepicker.jsx
new file mode 100644
index 0000000..dbf06f0
--- /dev/null
+++ b/sdk/filepicker.jsx
@@ -0,0 +1,57 @@
+// filepicker.jsx — a small "choose a file" sheet for apps that run in the theme's context
+// (Mail attachments, a contact's photo, importing .ics/.vcf). Isolated .lpk apps use the
+// system powerbox (fs.openFile) instead. Only the home folder and the user's mounts are listed
+// (lord.fs enforces that anyway).
+//
+// <FilePicker onPick={(path) => …} onClose={() => …} filter={/\.(png|jpe?g)$/i} title={t('…')} multiple />
+import { useState } from 'react';
+import { View, Text } from '@lordos/runtime';
+import { useTheme } from './theme.js';
+import { t } from './i18n.js';
+import { Button, ScrollView } from './components.jsx';
+import * as fs from './fs.js';
+import { formatBytes } from './system.js';
+
+export function FilePicker({ onPick, onClose, filter = null, title = '', multiple = false, start = '' }) {
+ const th = useTheme();
+ const [dir, setDir] = useState(start);
+ const [chosen, setChosen] = useState([]);
+ let entries = [];
+ try { entries = fs.list(dir || '.').filter((e) => !e.name.startsWith('.') && (e.dir || !filter || filter.test(e.name))); } catch (e) { entries = []; }
+ entries.sort((a, b) => (b.dir - a.dir) || a.name.localeCompare(b.name));
+ const abs = (name) => `${fs.home()}/${dir ? `${dir}/` : ''}${name}`;
+ const pick = (e) => {
+ if (e.dir) { setDir(dir ? `${dir}/${e.name}` : e.name); return; }
+ if (!multiple) { onPick(abs(e.name)); return; }
+ const p = abs(e.name);
+ setChosen((c) => (c.includes(p) ? c.filter((x) => x !== p) : [...c, p]));
+ };
+ return (
+ <View onMouseDown={(e) => e.stopPropagation?.()} style={{ position: 'absolute', left: 30, top: 40, right: 30, bottom: 30, padding: 12, gap: 8, borderRadius: 12,
+ backgroundColor: th.windowBg, border: `1px solid ${th.separator}`, boxShadow: '0 16px 40px rgba(0,0,0,0.45)' }}>
+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 8 }}>
+ <Button label="‹" onClick={() => setDir(dir.split('/').slice(0, -1).join('/'))} />
+ <View style={{ flex: 1 }}>
+ {title ? <Text style={{ fontSize: 13, fontWeight: 600, color: th.text }}>{title}</Text> : null}
+ <Text style={{ fontSize: 11, color: th.textDim, whiteSpace: 'nowrap', overflow: 'hidden' }}>{`~/${dir}`}</Text>
+ </View>
+ <Button label={t('shell.picker.cancel')} onClick={onClose} />
+ {multiple && <Button primary label={t('shell.picker.choose', { n: chosen.length })} onClick={() => chosen.length && onPick(chosen)} />}
+ </View>
+ <ScrollView style={{ flex: 1 }}>
+ {entries.map((e) => {
+ const on = chosen.includes(abs(e.name));
+ return (
+ <View key={e.name} onClick={() => pick(e)} style={{ flexDirection: 'row', alignItems: 'center', gap: 8, paddingVertical: 5, paddingHorizontal: 6, borderRadius: 6,
+ backgroundColor: on ? th.accent : 'transparent' }}>
+ <Text style={{ fontSize: 15 }}>{e.dir ? '📁' : '📄'}</Text>
+ <Text style={{ flex: 1, fontSize: 13, color: on ? '#fff' : th.text, whiteSpace: 'nowrap', overflow: 'hidden' }}>{e.name}</Text>
+ {!e.dir && <Text style={{ fontSize: 11, color: on ? '#fff' : th.textDim }}>{formatBytes(e.size)}</Text>}
+ </View>
+ );
+ })}
+ {!entries.length && <Text style={{ fontSize: 12, color: th.textDim, margin: 8 }}>{t('shell.picker.empty')}</Text>}
+ </ScrollView>
+ </View>
+ );
+}
diff --git a/sdk/hardware.jsx b/sdk/hardware.jsx
index 66afc61..47da44a 100644
--- a/sdk/hardware.jsx
+++ b/sdk/hardware.jsx
@@ -140,12 +140,12 @@ export function previewNight(kelvin) { if (has('display')) call(() => lord.displ
// Applies a mode live and starts the 15-second countdown; keepDisplay() saves it, revert brings back
// the previous one (also when the countdown runs out with nobody answering).
-export function applyDisplay(out, { w, h: hh, refresh = 0, rotation = 0, conn = out.id }) {
+export function applyDisplay(out, { w, h: hh, refresh = 0, rotation = 0, scale = 1, conn = out.id }) {
if (!has('display')) return false;
const d = displays.get();
const cur = (d?.outputs || []).find((o) => o.current) || out;
- const old = { conn: cur.id, w: cur.mode?.w || 0, h: cur.mode?.h || 0, refresh: cur.mode?.refresh || 0, rotation: d?.rotation || 0 };
- if (!lord.display.apply(conn, w, hh, refresh, rotation)) return false;
+ const old = { conn: cur.id, w: cur.mode?.w || 0, h: cur.mode?.h || 0, refresh: cur.mode?.refresh || 0, rotation: d?.rotation || 0, scale: d?.scale || 1 };
+ if (!lord.display.apply(conn, w, hh, refresh, rotation, scale)) return false;
const prev = displayConfirm.get();
displayConfirm.set({ conn, old: prev ? prev.old : old, deadline: Date.now() + 15000, left: 15 });
scheduleConfirm();
@@ -174,7 +174,7 @@ export function revertDisplay() {
const c = displayConfirm.get();
clearTimeout(confirmTimer);
displayConfirm.set(null);
- if (c && has('display')) lord.display.apply(c.old.conn, c.old.w, c.old.h, c.old.refresh, c.old.rotation);
+ if (c && has('display')) lord.display.apply(c.old.conn, c.old.w, c.old.h, c.old.refresh, c.old.rotation, c.old.scale || 1);
}
// System dialogs are drawn outside the theme's provider: light or dark from the user's setting.
@@ -311,7 +311,7 @@ function linuxNotify(n) {
if (prev) dismissNotification(prev, 'replaced');
const reason = { closed: 2, expired: 1, action: 2, replaced: 0, remote: 0 };
const id = notify({
- app: key, label: app?.name || n.app, title: n.title, body: n.body, sticky: n.urgency === 2,
+ app: key, label: app?.name || n.app, icon: app?.Icon || null, title: n.title, body: n.body, sticky: n.urgency === 2,
timeout: n.timeout > 0 ? n.timeout : 6000,
actions: (n.actions || []).filter(([k]) => k !== 'default').map(([k, label]) => ({ id: k, label, run: () => lord.notifyd.action(n.id, k) })),
onClose: (why) => { if (fromLinux.get(n.id) === id) fromLinux.delete(n.id); if (reason[why]) lord.notifyd.closed(n.id, reason[why]); },
diff --git a/sdk/index.js b/sdk/index.js
index 4ce9e21..7ca40e9 100644
--- a/sdk/index.js
+++ b/sdk/index.js
@@ -71,13 +71,20 @@ export {
} from './components.jsx';
import { FloatingWindows } from './components.jsx';
export {
- ToolbarButton, ToolbarGroup, Toolbar, ToolbarSpacer, ToolbarDivider, MenuButton, SearchField, EmptyState, GroupBox, FormRow, spacing, typeScale, controlSize,
+ ToolbarButton, ToolbarGroup, Toolbar, ToolbarSpacer, ToolbarDivider, Hairline, MenuButton, SearchField, EmptyState, GroupBox, FormRow, spacing, typeScale, controlSize,
} from './controls.jsx';
export { media, useMedia, usePlayer, nowPlaying, useNowPlaying, NowPlayingTile, mediaFormatTime, thumbFor, useThumb, userDirs } from './media.js';
export { disks, useDisks } from './disks.js';
export { backup, useBackup, backupStatus } from './backup.js'; // Backups (docs/SYSTEM.md)
export { vaultAvailable, vaultRequest, onVaultEvent, keyring, autofill, autofillReveal, KeyringPrompt, AutofillButton } from './vault.js'; // Contraseñas y llavero (docs/CONTRASENAS.md)
import { KeyringPrompt } from './vault.js';
+// Mail, Calendar, Contacts and Reminders through the sandboxed helper lord-maild (docs/MAIL.md)
+export { mailAvailable, mailRequest, onMailEvent, mailConfig, mailAccounts, mailStatus, autoconfig, OAUTH_PROVIDERS } from './mail.js';
+export { calendars, events as calendarEvents, reminders, usePim, usePimQuery, pimRev, startOfDay } from './calendar.js';
+export { FilePicker } from './filepicker.jsx';
+export { books as addressBooks, contacts, displayName as contactName, initials as contactInitials, ContactPhoto } from './contacts.js';
+import { startMail } from './mail.js';
+import { startReminders } from './calendar.js';
// Settings' hardware pages (docs/SETTINGS.md): displays, Night Shift, battery, Bluetooth, idle, clock
export {
displays, useDisplays, applyDisplay, keepDisplay, revertDisplay, displayConfirm, DisplayGlyph, nightPrefs, NIGHT_DEFAULTS, nightWindow,
@@ -139,6 +146,8 @@ export function startShell(element) {
// ISO live: el asistente de instalación se abre solo, al frente
if (isLiveSystemOf() && getAppOf('installer')) setTimeout(() => wmOf.open('installer'), 300);
startAlarms(); // Clock alarms and timer, with the app closed
+ startMail(); // new-mail notifications and passwords on demand (docs/MAIL.md)
+ startReminders(); // calendar and reminder alarms, with the apps closed
maybeStartTour(); // "Welcome to LordOS", the first time
startHardware(); // Night Shift, idle timers, battery in the menu bar (hardware.jsx)
}
diff --git a/sdk/mail.js b/sdk/mail.js
new file mode 100644
index 0000000..8a74e8f
--- /dev/null
+++ b/sdk/mail.js
@@ -0,0 +1,236 @@
+// mail.js — Mail, and the shared channel for Calendar, Contacts and Reminders: everything goes
+// through lord.mail to the sandboxed helper lord-maild (docs/MAIL.md). All calls are
+// asynchronous: requests return promises; a timer reads results and events (lord.mail.poll),
+// so the desktop never waits for the network.
+//
+// mailAvailable() is lord-maild installed?
+// mailRequest(op, args, { files }) → promise with the reply, or an Error with .code
+// onMailEvent(fn) events: new, changed, folders, status, need-auth, auth-failed,
+// cert, sent, send-failed, pim-changed, crash
+// mailConfig.get() / mailConfig.save(cfg) the accounts file (no passwords: those live in the keyring)
+// mailAccounts.add(account, password) saves the account, the password in the keyring, and starts it
+// mailAccounts.remove(id) / setPassword(id, pw) / trustCertificate(id, which, sha256)
+// autoconfig(email) our provider table (Gmail, Outlook.com, Yahoo, iCloud) or a guess
+// OAUTH_PROVIDERS prepared, disabled until you register a client ID
+// mailStatus (store) { accounts: { id: { status, error } }, unread, rev, certs: [] }
+// startMail() called by startShell: new-mail notifications, passwords on demand
+import { createStore } from './store.js';
+import { keyring } from './vault.js';
+import { notify } from './notify.js';
+import { t } from './i18n.js';
+import { wm, getApp } from './windows.js';
+
+const has = () => typeof lord !== 'undefined' && typeof lord.mail !== 'undefined';
+export const mailAvailable = () => has() && lord.mail.available();
+
+const waiting = new Map();
+const listeners = new Set();
+let fast = null, slow = null;
+
+function dispatch(m) {
+ if (m.type === 'evt') {
+ for (const fn of listeners) { try { fn(m.data || {}); } catch (e) { console.log(`mail: ${e.message}`); } }
+ return;
+ }
+ if (m.type === 'crash') {
+ for (const [id, w] of waiting) { waiting.delete(id); w.reject(Object.assign(new Error('crash'), { code: 'crash' })); }
+ for (const fn of listeners) { try { fn({ ev: 'crash' }); } catch (e) { /* listener */ } }
+ return;
+ }
+ const w = waiting.get(m.id);
+ if (!w) return;
+ waiting.delete(m.id);
+ const d = m.data || {};
+ if (m.type === 'err' || d.error) w.reject(Object.assign(new Error(d.detail || d.error || 'error'), { code: d.error || 'error', data: d }));
+ else w.resolve(d);
+}
+
+function pump() {
+ let list = null;
+ try { list = lord.mail.poll(); } catch (e) { list = null; }
+ if (Array.isArray(list)) for (const m of list) dispatch(m);
+ if (!waiting.size && fast) { clearInterval(fast); fast = null; }
+}
+
+function startSlow() { if (!slow && has()) slow = setInterval(pump, 500); }
+
+export function mailRequest(op, args = {}, { files } = {}) {
+ if (!has()) return Promise.reject(Object.assign(new Error('unavailable'), { code: 'unavailable' }));
+ let id;
+ try { id = lord.mail.request(JSON.stringify({ op, ...args }), files && files.length ? files : undefined); }
+ catch (e) { return Promise.reject(Object.assign(new Error(e.message), { code: 'file' })); }
+ if (id < 0) return Promise.reject(Object.assign(new Error('unavailable'), { code: 'unavailable' }));
+ startSlow();
+ return new Promise((resolve, reject) => {
+ waiting.set(id, { resolve, reject });
+ if (!fast) fast = setInterval(pump, 12);
+ });
+}
+
+export function onMailEvent(fn) {
+ startSlow();
+ listeners.add(fn);
+ return () => listeners.delete(fn);
+}
+
+// ---- accounts ----
+
+export const mailConfig = {
+ get() {
+ if (!has()) return { accounts: [] };
+ try { const c = JSON.parse(lord.mail.config() || '{}'); return { accounts: [], ...c }; } catch (e) { return { accounts: [] }; }
+ },
+ save(cfg) { if (has()) lord.mail.saveConfig(JSON.stringify(cfg, null, 1)); bumpStatus(); },
+};
+
+export const mailStatus = createStore({ accounts: {}, unread: 0, rev: 0, certs: [], authFailed: {} });
+const bumpStatus = () => mailStatus.set((s) => ({ ...s, rev: s.rev + 1 }));
+
+const service = (id) => `mail:${id}`;
+
+async function passwordFor(acct) {
+ try { const it = await keyring.get('mail', { service: service(acct.id), account: acct.user }); return it ? it.secret : null; }
+ catch (e) { return null; }
+}
+
+const slug = (s) => String(s).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 24) || 'cuenta';
+
+export const mailAccounts = {
+ list: () => mailConfig.get().accounts,
+ get: (id) => mailConfig.get().accounts.find((a) => a.id === id),
+ newId(base) {
+ const ids = new Set(mailConfig.get().accounts.map((a) => a.id));
+ let id = slug(base), n = 2;
+ while (ids.has(id)) id = `${slug(base).slice(0, 20)}-${n++}`;
+ return id;
+ },
+ // account: { id?, kind: 'mail'|'dav', name, email, fullName, user, imap, smtp, url, cal, card, sentSaved, signature, color }
+ async add(account, password) {
+ const acct = { kind: 'mail', auth: 'password', ...account, id: account.id || mailAccounts.newId(account.email || account.name || account.url) };
+ if (password) await keyring.set('mail', { service: service(acct.id), account: acct.user, secret: password, label: `${t('mail.keyring.label')} — ${acct.email || acct.user}` });
+ const cfg = mailConfig.get();
+ cfg.accounts = [...cfg.accounts.filter((a) => a.id !== acct.id), acct];
+ mailConfig.save(cfg);
+ lord.mail.start();
+ if (password) await mailRequest('auth', { acct: acct.id, password }).catch(() => {});
+ return acct.id;
+ },
+ async update(id, patch) {
+ const cfg = mailConfig.get();
+ cfg.accounts = cfg.accounts.map((a) => (a.id === id ? { ...a, ...patch } : a));
+ mailConfig.save(cfg);
+ },
+ async remove(id) {
+ const cfg = mailConfig.get();
+ const a = cfg.accounts.find((x) => x.id === id);
+ cfg.accounts = cfg.accounts.filter((x) => x.id !== id);
+ mailConfig.save(cfg);
+ if (a) await keyring.remove('mail', { service: service(id), account: a.user }).catch(() => {});
+ },
+ async setPassword(id, password) {
+ const a = mailAccounts.get(id);
+ if (!a) return;
+ await keyring.set('mail', { service: service(id), account: a.user, secret: password, label: `${t('mail.keyring.label')} — ${a.email || a.user}` });
+ mailStatus.set((s) => ({ ...s, authFailed: { ...s.authFailed, [id]: false } }));
+ await mailRequest('auth', { acct: id, password });
+ },
+ // the user looked at the certificate and chose to trust exactly this one
+ trustCertificate(id, which, sha256) {
+ const a = mailAccounts.get(id);
+ if (!a) return;
+ mailAccounts.update(id, { trust: { ...(a.trust || {}), [which]: sha256 } });
+ mailStatus.set((s) => ({ ...s, certs: s.certs.filter((c) => c.acct !== id) }));
+ },
+ testSmtp: (id) => mailRequest('send', { acct: id, test: true }),
+};
+
+// ---- autoconfig: our own provider table (Mozilla ISPDB style, built in, no lookups) ----
+
+const PROVIDERS = [
+ { domains: ['gmail.com', 'googlemail.com'], name: 'Gmail', imap: { host: 'imap.gmail.com', port: 993, security: 'ssl' },
+ smtp: { host: 'smtp.gmail.com', port: 465, security: 'ssl' }, sentSaved: true, appPassword: 'https://myaccount.google.com/apppasswords', oauth: 'google',
+ caldav: 'https://apidata.googleusercontent.com/caldav/v2/', davNote: 'oauth' },
+ { domains: ['outlook.com', 'hotmail.com', 'live.com', 'msn.com', 'outlook.es', 'hotmail.es'], name: 'Outlook.com',
+ imap: { host: 'outlook.office365.com', port: 993, security: 'ssl' }, smtp: { host: 'smtp-mail.outlook.com', port: 587, security: 'starttls' },
+ sentSaved: true, appPassword: 'https://account.live.com/proofs/AppPassword', oauth: 'microsoft' },
+ { domains: ['yahoo.com', 'ymail.com', 'yahoo.es', 'yahoo.com.ar', 'yahoo.com.br', 'rocketmail.com'], name: 'Yahoo',
+ imap: { host: 'imap.mail.yahoo.com', port: 993, security: 'ssl' }, smtp: { host: 'smtp.mail.yahoo.com', port: 465, security: 'ssl' },
+ sentSaved: false, appPassword: 'https://login.yahoo.com/account/security' },
+ { domains: ['icloud.com', 'me.com', 'mac.com'], name: 'iCloud', imap: { host: 'imap.mail.me.com', port: 993, security: 'ssl' },
+ smtp: { host: 'smtp.mail.me.com', port: 587, security: 'starttls' }, sentSaved: false, appPassword: 'https://appleid.apple.com/account/manage',
+ caldav: 'https://caldav.icloud.com/', carddav: 'https://contacts.icloud.com/' },
+];
+
+export function autoconfig(email) {
+ const domain = String(email || '').split('@')[1]?.toLowerCase().trim();
+ if (!domain) return null;
+ const p = PROVIDERS.find((x) => x.domains.includes(domain));
+ if (p) return { ...p, user: email, known: true };
+ // a guess for custom domains: the most common names; the setup screen lets you change them
+ return { name: domain, imap: { host: `imap.${domain}`, port: 993, security: 'ssl' }, smtp: { host: `smtp.${domain}`, port: 465, security: 'ssl' },
+ sentSaved: false, user: email, known: false };
+}
+
+// OAuth2 (XOAUTH2) is prepared but OFF: Google and Microsoft only hand out tokens to apps whose
+// client ID is registered in their consoles (Google Cloud, Azure). Put yours here and enable it
+// in docs/MAIL.md, "OAuth"; until then these accounts use app passwords.
+export const OAUTH_PROVIDERS = {
+ google: { enabled: false, clientId: '', authUrl: 'https://accounts.google.com/o/oauth2/v2/auth', tokenUrl: 'https://oauth2.googleapis.com/token',
+ scopes: ['https://mail.google.com/', 'https://www.googleapis.com/auth/calendar', 'https://www.googleapis.com/auth/carddav'], needs: 'client-id' },
+ microsoft: { enabled: false, clientId: '', authUrl: 'https://login.microsoftonline.com/consumers/oauth2/v2.0/authorize',
+ tokenUrl: 'https://login.microsoftonline.com/consumers/oauth2/v2.0/token',
+ scopes: ['https://outlook.office.com/IMAP.AccessAsUser.All', 'https://outlook.office.com/SMTP.Send', 'offline_access'], needs: 'client-id' },
+};
+
+// ---- the session side: passwords on demand, notifications, unread count ----
+
+let started = false;
+
+async function refreshCounts() {
+ try { const c = await mailRequest('counts'); mailStatus.set((s) => ({ ...s, unread: c.unread || 0 })); } catch (e) { /* not running */ }
+}
+
+function openMessage(acct, folder, uid) {
+ if (getApp('mail')) wm.open('mail', { args: { acct, folder, uid, nonce: Date.now() } });
+}
+
+export function startMail() {
+ if (started || !has() || !lord.mail.available()) return;
+ started = true;
+ const cfg = mailConfig.get();
+ onMailEvent(async (ev) => {
+ if (ev.ev === 'need-auth') {
+ const a = mailAccounts.get(ev.acct);
+ const pw = a ? await passwordFor(a) : null;
+ if (pw) mailRequest('auth', { acct: ev.acct, password: pw }).catch(() => {});
+ else mailStatus.set((s) => ({ ...s, authFailed: { ...s.authFailed, [ev.acct]: true } }));
+ } else if (ev.ev === 'auth-failed') {
+ mailStatus.set((s) => ({ ...s, authFailed: { ...s.authFailed, [ev.acct]: true } }));
+ } else if (ev.ev === 'status') {
+ mailStatus.set((s) => ({ ...s, accounts: { ...s.accounts, [ev.acct]: { status: ev.status, error: ev.error } } }));
+ } else if (ev.ev === 'cert') {
+ mailStatus.set((s) => ({ ...s, certs: [...s.certs.filter((c) => !(c.acct === ev.acct && c.host === ev.host)), ev] }));
+ } else if (ev.ev === 'new') {
+ refreshCounts();
+ const prefs = (mailConfig.get().notify ?? true);
+ if (!prefs) return;
+ const one = ev.msgs?.[0];
+ if (ev.count === 1 && one) {
+ notify({ app: 'mail', title: one.from, body: one.subject || t('mail.noSubject'), timeout: 8000,
+ actions: [{ id: 'open', label: t('mail.notify.open'), run: () => openMessage(ev.acct, ev.folder, one.uid) }] });
+ } else if (ev.count > 1) {
+ notify({ app: 'mail', title: t('mail.notify.many', { n: ev.count }), body: ev.msgs.slice(0, 3).map((m) => `${m.from}: ${m.subject}`).join('\n'),
+ timeout: 8000, actions: [{ id: 'open', label: t('mail.notify.open'), run: () => openMessage(ev.acct, ev.folder) }] });
+ }
+ } else if (ev.ev === 'changed' || ev.ev === 'folders') {
+ refreshCounts();
+ } else if (ev.ev === 'send-failed') {
+ notify({ app: 'mail', title: t('mail.notify.sendFailed'), body: `${ev.subject || ''}\n${ev.error || ''}`, sticky: true });
+ } else if (ev.ev === 'ready') {
+ refreshCounts();
+ }
+ });
+ // lord-maild also keeps calendars and reminders: start it if there is anything to keep
+ lord.mail.start();
+ if (cfg.accounts.length) refreshCounts();
+}
diff --git a/sdk/notify.js b/sdk/notify.js
index 6a7fd51..e38c37c 100644
--- a/sdk/notify.js
+++ b/sdk/notify.js
@@ -64,13 +64,13 @@ function remember(app) {
settings.set((s) => ({ ...s, notifications: { ...notifyPrefs(s), seen: [app, ...notifyPrefs(s).seen].slice(0, 64) } }));
}
-export function notify({ app = '', title = '', body = '', actions = [], sound: withSound = true, sticky = false, timeout = 6000, onClose, label = '' } = {}) {
+export function notify({ app = '', title = '', body = '', actions = [], sound: withSound = true, sticky = false, timeout = 6000, onClose, label = '', icon = null } = {}) {
app = String(app);
const ap = appNotifyPrefs(app);
remember(app);
if (!ap.allow) return 0; // not delivered at all (like macOS)
const id = seq++;
- const n = { id, app, label: String(label), title: String(title), body: String(body), actions: Array.isArray(actions) ? actions.slice(0, 3) : [],
+ const n = { id, app, label: String(label), Icon: typeof icon === 'function' ? icon : null, title: String(title), body: String(body), actions: Array.isArray(actions) ? actions.slice(0, 3) : [],
sticky: !!sticky || ap.style === 'alert', time: Date.now(), onClose };
notifyHistory.set((l) => [{ id, app: n.app, label: n.label, title: n.title, body: n.body, time: n.time }, ...l].slice(0, HISTORY));
// Do Not Disturb or "no banner": kept in the history only, without a sound
@@ -109,7 +109,7 @@ function Banner({ n, th }) {
boxShadow: '0 10px 30px rgba(0,0,0,0.4)' },
},
h(View, { style: { flexDirection: 'row', gap: 10, alignItems: 'flex-start' } },
- app?.Icon ? h(app.Icon, { size: 34 }) : h(View, { style: { width: 34, height: 34, borderRadius: 8, backgroundColor: th.accent } }),
+ app?.Icon ? h(app.Icon, { size: 34 }) : n.Icon ? h(n.Icon, { size: 34 }) : h(View, { style: { width: 34, height: 34, borderRadius: 8, backgroundColor: th.accent } }),
h(View, { style: { flex: 1, gap: 2 } },
h(View, { style: { flexDirection: 'row', gap: 6 } },
h(Text, { style: { flex: 1, fontSize: 11, color: th.textDim, whiteSpace: 'nowrap', overflow: 'hidden', textAlign: 'start' } },
@@ -130,7 +130,10 @@ function Banner({ n, th }) {
export function NotificationBanner() {
const list = useNotifications();
- const th = useTheme();
+ // drawn outside the theme's provider: follow the user's light/dark setting
+ const base = useTheme(), mode = useStore(settings, (x) => x.mode);
+ const th = mode === 'light' ? { ...base, mode: 'light', windowBg: '#f6f6f8', text: '#1d1d1f', textDim: 'rgba(60,60,67,0.62)',
+ separator: 'rgba(0,0,0,0.12)', control: '#e2e2e7' } : base;
const [, force] = useState(0);
useEffect(() => { if (list.length) force((x) => x + 1); }, [list.length]);
if (!list.length) return null;
diff --git a/sdk/packages.js b/sdk/packages.js
index 882601e..b2b2080 100644
--- a/sdk/packages.js
+++ b/sdk/packages.js
@@ -60,6 +60,25 @@ function Redirect({ id }) {
return null;
}
+// A built-in app that runs as its own sandboxed process (manifest "process": "isolated", shipped as
+// <assets>/sysapps/<id>, see tools/build-theme.mjs): opening its window in the theme starts the
+// process instead and closes this placeholder. Without app mode (or without the built system
+// package) the app runs in-process as before.
+export function isolatedApp(id, Fallback) {
+ return function IsolatedApp(props) {
+ const win = sdk.useAppWindow();
+ const [inproc, setInproc] = React.useState(false);
+ React.useEffect(() => {
+ // already running: focus its window (a single window: it holds a vault)
+ const running = windows.get().filter((w) => w.args?.pkg && w.args?.appId === id);
+ if (isolated() && running.length) { wm.focus(running[running.length - 1].id); if (win && win.id) wm.close(win.id, true); }
+ else if (isolated() && lord.apps.launchPackage(id)) { if (win && win.id) wm.close(win.id, true); }
+ else setInproc(true);
+ }, []);
+ return inproc && Fallback ? h(Fallback, props) : null;
+ };
+}
+
function lazyComponent(id) {
return function PackageApp(props) {
if (isolated()) return h(Redirect, { id });
diff --git a/sdk/vault.js b/sdk/vault.js
index 51bb458..f583acb 100644
--- a/sdk/vault.js
+++ b/sdk/vault.js
@@ -52,10 +52,11 @@ function pump() {
// Los eventos (bloqueo automático, avisos de Secret Service) llegan aunque nadie espere nada.
function startSlow() { if (!slow && has()) slow = setInterval(pump, 600); }
-export function vaultRequest(op, args = {}, { files } = {}) {
+export function vaultRequest(op, args = {}, { files, fds } = {}) {
if (!has()) return Promise.reject(Object.assign(new Error('unavailable'), { code: 'unavailable' }));
let id;
- try { id = lord.vault.request(JSON.stringify({ op, ...args }), files ? { files } : undefined); }
+ // 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' })); }
startSlow();
return new Promise((resolve, reject) => {
diff --git a/sdk/wayland.js b/sdk/wayland.js
index 729f333..40a1bd3 100644
--- a/sdk/wayland.js
+++ b/sdk/wayland.js
@@ -9,7 +9,7 @@ import { createElement as h } from 'react';
import { View, Text, Surface, addListener } from '@lordos/runtime';
import { windows, wm, registerBuiltinApp, windowChrome, workArea, getApp } from './windows.js';
import { useAppWindow } from './components.jsx';
-import { locale } from './i18n.js';
+import { locale, appName } from './i18n.js';
const idOf = (sid) => `linux#${sid}`;
export const surfaceOf = (wid) => (String(wid).startsWith('linux#') ? Number(String(wid).slice(6)) || 0 : 0);
@@ -59,12 +59,14 @@ globalThis.__lordWayland = (sid, type, d = {}) => {
wm.open('linux', {
instance: String(sid),
frame: { w, h: hh, x: Math.round(area.x + (area.w - w) / 2 + (n % 5) * 24), y: Math.round(area.y + Math.max(8, (area.h - hh) / 2 - 30) + (n % 5) * 24) },
- args: { surface: sid, csd: !!d.csd, appId: d.appId || '', pkg: !!(d.appId && getApp(d.appId)?.package) },
+ args: { surface: sid, csd: !!d.csd, appId: d.appId || '', pkg: !!(d.appId && (getApp(d.appId)?.package || getApp(d.appId)?.isolated)) },
});
// app .lpk aislada: su nombre (del manifest) en vez del id
- { const pkg = d.appId ? getApp(d.appId) : null; wm.setTitle(id, pkg && pkg.package && (!d.title || d.title === d.appId) ? pkg.name : (d.title || d.appId || null)); }
+ { const pkg = d.appId ? getApp(d.appId) : null; wm.setTitle(id, pkg && (pkg.package || pkg.isolated) && (!d.title || d.title === d.appId) ? (pkg.isolated ? appName(pkg) : pkg.name) : (d.title || d.appId || null)); }
+ // a built-in isolated app that asks for it (manifest "protected": Passwords) is black in captures
+ if (d.appId && getApp(d.appId)?.isolated && getApp(d.appId)?.protected) wm.setProtected(id, true);
wm.setCloseGuard(id, () => { lord.wayland.close(sid); return false; }); // la app decide cuándo cierra
- if (d.appId && getApp(d.appId)?.package) setTimeout(() => applyAppMenus(d.appId), 0); // menús de la app aislada (ya mapeada)
+ if (d.appId && (getApp(d.appId)?.package || getApp(d.appId)?.isolated)) setTimeout(() => applyAppMenus(d.appId), 0); // menús de la app aislada (ya mapeada)
break;
}
case 'unmap': if (win) wm.close(id, true); break;
@@ -117,7 +119,7 @@ locale.subscribe(() => setTimeout(() => {
for (const w of windows.get()) {
if (!w.args?.pkg) continue;
const pkg = getApp(w.args.appId);
- if (pkg && pkg.name) wm.setTitle(w.id, pkg.name);
+ if (pkg && pkg.name) wm.setTitle(w.id, pkg.isolated ? appName(pkg) : pkg.name);
}
}, 0));
diff --git a/server/mk/mail.mk b/server/mk/mail.mk
index 6b080d2..a9fbc4e 100644
--- a/server/mk/mail.mk
+++ b/server/mk/mail.mk
@@ -25,3 +25,37 @@ build/mailc-test: tests/mailc_test.c src/mail/mailc.c src/mail/mailc.h src/doc/w
@mkdir -p build
$(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ tests/mailc_test.c src/mail/mailc.c src/doc/wire.c src/sec/json.c -lpthread -lm
./$@ || { rm -f $@; exit 1; }
+# hostile servers: HTTP chunk sizes / Content-Length / header limits and IMAP literal sizes,
+# over a socketpair (no network). Needs the OpenSSL headers (net.c), like lord-maild.
+MAILNET ?= $(shell pkg-config --exists openssl 2>/dev/null && echo 1 || echo 0)
+ifeq ($(MAILNET),1)
+test: build/mailnet-test
+endif
+MAILNET_SRC := tests/mailnet_test.c src/mail/http.c src/mail/net.c src/mail/imapio.c
+build/mailnet-test: $(MAILNET_SRC) src/mail/http.h src/mail/net.h src/mail/imapio.h
+ @mkdir -p build
+ $(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ $(MAILNET_SRC) $(shell pkg-config --libs openssl)
+ ./$@ || { rm -f $@; exit 1; }
+build/mailnet-test-asan: $(MAILNET_SRC) src/mail/http.h src/mail/net.h src/mail/imapio.h
+ @mkdir -p build
+ $(CC) $(CPPFLAGS) -O1 -g -fsanitize=address,undefined -fno-sanitize-recover=undefined $(WARN) -std=c11 -o $@ $(MAILNET_SRC) $(shell pkg-config --libs openssl)
+ ./$@
+mail-asan: build/mailnet-test-asan
+# lord-maild: the sandboxed helper (IMAP, SMTP, CalDAV, CardDAV). With lord-sessiond, the only
+# binary that links OpenSSL; built when its headers are there (MAILNET).
+LMD_SRC := src/mail/maild.c src/mail/store.c src/mail/search.c src/mail/imap.c src/mail/imapio.c src/mail/smtp.c \
+ src/mail/msgview.c src/mail/http.c src/mail/dav.c src/mail/pim.c src/mail/net.c src/mail/snpf.c $(MAIL_PARSE) \
+ src/doc/wire.c src/sec/json.c src/sec/sandbox.c src/sec/cgroup.c src/ui/tzif.c
+ifeq ($(MAILNET),1)
+all: build/lord-maild
+endif
+build/obj/mail/mimg.o: src/mail/mimg.c
+ @mkdir -p $(dir $@)
+ $(CC) $(CPPFLAGS) $(CFLAGS) -w -c -o $@ $<
+build/lord-maild: $(LMD_SRC) build/obj/mail/mimg.o $(MAIL_HDR) src/sec/sandbox.h src/sec/cgroup.h
+ @mkdir -p build
+ $(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ $(LMD_SRC) build/obj/mail/mimg.o $(shell pkg-config --libs openssl) -lpthread -lm
+# manual driver for lord-maild (not in `make test`): build/maild-cli '{"op":"status"}' --wait 5
+build/maild-cli: tests/maild_cli.c src/mail/mailc.c src/doc/wire.c src/sec/json.c src/mail/mailc.h
+ @mkdir -p build
+ $(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ tests/maild_cli.c src/mail/mailc.c src/doc/wire.c src/sec/json.c -lpthread -lm
diff --git a/server/src/app/app.h b/server/src/app/app.h
index df0ca33..dc58e56 100644
--- a/server/src/app/app.h
+++ b/server/src/app/app.h
@@ -3,6 +3,8 @@
#ifndef LORD_APP_H
#define LORD_APP_H
+#include <stddef.h>
+
/* `lord-server --app <id>`: corre la app instalada <id>. Devuelve el código de salida. */
int app_main(const char *id, const char *theme_bundle, const char *fonts);
@@ -10,4 +12,10 @@ int app_main(const char *id, const char *theme_bundle, const char *fonts);
* 0 si lanzó. El id tiene que ser de un paquete instalado (se valida). */
int app_spawn(const char *id);
+/* Package folder of app <id>. A system app shipped with LordOS (<assets>/sysapps/<id>, owned by
+ * root or the user and not writable by others) wins over a user-installed .lpk
+ * (lpk_root()/<id>), so an installed package can never shadow it. out receives the real path.
+ * Returns 1 for a system app, 0 for a user package, -1 if there is none. */
+int app_package_dir(const char *id, const char *assets, char *out, size_t n);
+
#endif
diff --git a/server/src/app/appclient.c b/server/src/app/appclient.c
index f700c49..4a31d40 100644
--- a/server/src/app/appclient.c
+++ b/server/src/app/appclient.c
@@ -419,14 +419,38 @@ static void reg_global(void *d, struct wl_registry *r, uint32_t name, const char
static void reg_remove(void *d, struct wl_registry *r, uint32_t name) { (void)d; (void)r; (void)name; }
static const struct wl_registry_listener reg_listener = { reg_global, reg_remove };
+/* "key": [w, h] from the package's manifest.json (size, minSize); 0 if missing or out of range. */
+static int manifest_pair(const char *dir, const char *key, int *w, int *h) {
+ char p[PATH_MAX + 32], buf[8192], pat[40];
+ if ((size_t)snprintf(p, sizeof p, "%s/manifest.json", dir) >= sizeof p) return 0;
+ FILE *f = fopen(p, "r");
+ if (!f) return 0;
+ size_t n = fread(buf, 1, sizeof buf - 1, f);
+ fclose(f);
+ buf[n] = 0;
+ snprintf(pat, sizeof pat, "\"%s\"", key);
+ const char *k = strstr(buf, pat);
+ if (!k || !(k = strchr(k + strlen(pat), '['))) return 0;
+ int a = 0, b = 0;
+ if (sscanf(k + 1, " %d , %d", &a, &b) != 2 || a < 160 || b < 100 || a > 8192 || b > 8192) return 0;
+ *w = a;
+ *h = b;
+ return 1;
+}
+
int app_main(const char *id, const char *theme_bundle, const char *fonts) {
if (!lpk_valid_id(id)) { fprintf(stderr, "lord-server --app: id inválido\n"); return 2; }
- const char *root = lpk_root();
char dir[PATH_MAX];
- struct stat st;
- if (!root || (size_t)snprintf(dir, sizeof dir, "%s/%s", root, id) >= sizeof dir || stat(dir, &st) || !S_ISDIR(st.st_mode)) {
- fprintf(stderr, "lord-server --app: la app '%s' no está instalada\n", id);
- return 2;
+ {
+ /* <assets> = the parent of the fonts folder; a system app there wins over a user .lpk */
+ char assets[PATH_MAX];
+ snprintf(assets, sizeof assets, "%s", fonts);
+ char *sl = strrchr(assets, '/');
+ if (sl) *sl = 0;
+ if (app_package_dir(id, assets, dir, sizeof dir) < 0) {
+ fprintf(stderr, "lord-server --app: la app '%s' no está instalada\n", id);
+ return 2;
+ }
}
/* carpeta de datos de la app (la única que puede escribir) */
const char *home = getenv("HOME");
@@ -448,7 +472,11 @@ int app_main(const char *id, const char *theme_bundle, const char *fonts) {
if (!comp || !shm || !wm) { fprintf(stderr, "lord-server --app: el compositor no ofrece lo necesario\n"); return 1; }
app_id_str = id;
- if (!win_create(0, id, 640, 480)) return 1; /* the main window (key 0) */
+ int mw = 640, mh = 480, nw = 0, nh = 0;
+ manifest_pair(dir, "size", &mw, &mh); /* the size the app asks for in its manifest */
+ AppWin *main_win = win_create(0, id, mw, mh);
+ if (!main_win) return 1; /* the main window (key 0) */
+ if (manifest_pair(dir, "minSize", &nw, &nh)) xdg_toplevel_set_min_size(main_win->top, nw, nh);
wl_display_roundtrip(dpy); /* first configure */
/* Caja de arena: después de conectar Wayland y abrir el broker, antes de cargar la app. */
diff --git a/server/src/app/appspawn.c b/server/src/app/appspawn.c
index faa47d2..1a1a115 100644
--- a/server/src/app/appspawn.c
+++ b/server/src/app/appspawn.c
@@ -6,6 +6,8 @@
#include "app.h"
#include "../lpk.h"
#include "../sec/broker.h"
+#include "../ui/js_sys.h"
+#include "../vault/vclient.h"
#include <fcntl.h>
#include <limits.h>
@@ -20,13 +22,31 @@
extern char **environ;
+int app_package_dir(const char *id, const char *assets, char *out, size_t n) {
+ if (!lpk_valid_id(id)) return -1;
+ struct stat st;
+ if (assets && assets[0]) {
+ char d[PATH_MAX], real[PATH_MAX], m[PATH_MAX + 16];
+ if ((size_t)snprintf(d, sizeof d, "%s/sysapps/%s", assets, id) < sizeof d && realpath(d, real) &&
+ !stat(real, &st) && S_ISDIR(st.st_mode) && !(st.st_mode & S_IWOTH) && (st.st_uid == 0 || st.st_uid == getuid()) &&
+ (size_t)snprintf(m, sizeof m, "%s/manifest.json", real) < sizeof m && !stat(m, &st) && S_ISREG(st.st_mode) &&
+ (size_t)snprintf(out, n, "%s", real) < n)
+ return 1;
+ }
+ const char *root = lpk_root();
+ if (root && (size_t)snprintf(out, n, "%s/%s", root, id) < n && !stat(out, &st) && S_ISDIR(st.st_mode)) return 0;
+ return -1;
+}
+
+/* System apps that get their own channel to lord-vault (vc_attach_app): only Passwords. */
+static int wants_vault(const char *id, int system) { return system == 1 && !strcmp(id, "passwords"); }
+
/* 0 si lanzó el proceso (y registró el broker). El id tiene que ser de un paquete instalado. */
int app_spawn(const char *id) {
if (!lpk_valid_id(id)) return -1;
- const char *root = lpk_root();
char dir[PATH_MAX];
- struct stat st;
- if (!root || (size_t)snprintf(dir, sizeof dir, "%s/%s", root, id) >= sizeof dir || stat(dir, &st) || !S_ISDIR(st.st_mode)) return -1;
+ int sys = app_package_dir(id, js_sys_assets(), dir, sizeof dir);
+ if (sys < 0) return -1;
/* one process per app: if it is already running, it opens another window instead */
if (!brokersrv_new_window(id)) { fprintf(stderr, "lord-server: app '%s' already running: new window\n", id); return 0; }
@@ -39,6 +59,8 @@ int app_spawn(const char *id) {
if (socketpair(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0, sv)) return -1;
/* el extremo del hijo NO es CLOEXEC: lo hereda el proceso de la app */
fcntl(sv[1], F_SETFD, 0);
+ /* Passwords talks to lord-vault on its own channel: decrypted data never passes through here */
+ int vfd = wants_vault(id, sys) ? vc_attach_app() : -1;
pid_t pid = fork();
if (pid == 0) {
@@ -52,6 +74,12 @@ int app_spawn(const char *id) {
char fdstr[16];
snprintf(fdstr, sizeof fdstr, "%d", sv[1]);
setenv(BROKER_FD_ENV, fdstr, 1);
+ if (vfd >= 0) {
+ char vstr[16];
+ fcntl(vfd, F_SETFD, 0); /* inherited by the app process (LORD_VAULT_FD) */
+ snprintf(vstr, sizeof vstr, "%d", vfd);
+ setenv("LORD_VAULT_FD", vstr, 1);
+ } else unsetenv("LORD_VAULT_FD");
int null = open("/dev/null", O_RDWR);
if (null >= 0) { dup2(null, 0); if (null > 2) close(null); }
/* el id lo pasa lord-server, ya validado; no hay argumentos del llamador */
@@ -60,9 +88,11 @@ int app_spawn(const char *id) {
_exit(127);
}
close(sv[1]);
+ if (vfd >= 0) close(vfd);
if (pid < 0) { close(sv[0]); return -1; }
waitpid(pid, NULL, 0); /* el hijo intermedio sale enseguida */
if (brokersrv_add(sv[0], id, pid)) { close(sv[0]); return -1; }
+ if (vfd >= 0) brokersrv_set_vault(sv[0]); /* this app may also ask for the FIDO2 device */
fprintf(stderr, "lord-server: app '%s' lanzada como proceso aislado\n", id);
return 0;
}
diff --git a/server/src/hw/bt.c b/server/src/hw/bt.c
index 1fab523..32fe843 100644
--- a/server/src/hw/bt.c
+++ b/server/src/hw/bt.c
@@ -326,7 +326,8 @@ static int on_call(DMsg *m) {
else if (!strcmp(mem, "RequestAuthorization") && !strcmp(sig, "o")) kind = "authorize";
else if (!strcmp(mem, "AuthorizeService") && !strcmp(sig, "os")) {
const BtDevice *d = device(&model, dev, 0);
- if (d && (d->paired || d->bonded) && d->trusted) { dbus_reply(sysbus_conn(), m, NULL, NULL); return 1; }
+ /* a device that went through pairing (the user confirmed it) may use its services */
+ if (d && (d->paired || d->bonded)) { dbus_reply(sysbus_conn(), m, NULL, NULL); return 1; }
kind = "service";
} else if (!strcmp(mem, "DisplayPinCode") && !strcmp(sig, "os")) {
const char *pin = dr_str(&r, NULL);
diff --git a/server/src/hw/display.c b/server/src/hw/display.c
index 1edaca9..a043eca 100644
--- a/server/src/hw/display.c
+++ b/server/src/hw/display.c
@@ -20,7 +20,7 @@
#define MAX_SAVED 16
#define ID_MAX 96
-typedef struct { char id[ID_MAX]; int w, h, refresh, rot; } Saved;
+typedef struct { char id[ID_MAX]; int w, h, refresh, rot, scale; } Saved;
static struct {
const DisplayHost *host;
@@ -37,9 +37,10 @@ static struct {
int done_off, done_lock, done_sleep, off;
/* queued modeset */
int pending, prot, rot, prev_rot;
+ int pscale, scale, prev_scale; /* 1, or 2: the frame is drawn at half size and doubled */
uint32_t pconn;
struct drm_mode_modeinfo pmode;
-} D = { .kelvin = NIGHT_K_MAX };
+} D = { .kelvin = NIGHT_K_MAX, .pscale = 1, .scale = 1, .prev_scale = 1 };
static double now_ms(void) {
struct timespec t;
@@ -92,6 +93,7 @@ static void load(void) {
s->h = (int)json_num(v, "h", 0);
s->refresh = (int)json_num(v, "refresh", 0);
s->rot = (int)json_num(v, "rotation", 0) & 3;
+ s->scale = json_num(v, "scale", 1) == 2 ? 2 : 1;
if (s->w < 0 || s->w > 16384 || s->h < 0 || s->h > 16384) s->w = s->h = 0;
}
json_free(&doc);
@@ -107,7 +109,7 @@ static int store(void) {
const Saved *s = &D.saved[i];
hb_printf(&b, "%s\n ", i ? "," : "");
hb_str(&b, s->id);
- hb_printf(&b, ": { \"w\": %d, \"h\": %d, \"refresh\": %d, \"rotation\": %d }", s->w, s->h, s->refresh, s->rot);
+ hb_printf(&b, ": { \"w\": %d, \"h\": %d, \"refresh\": %d, \"rotation\": %d, \"scale\": %d }", s->w, s->h, s->refresh, s->rot, s->scale);
}
hb_printf(&b, "\n }\n}\n");
char *txt = hb_take(&b);
@@ -142,7 +144,7 @@ void display_init(const DisplayHost *h) {
int n = kms_outputs(k->fd, outs, KMS_MAX_OUTPUTS), idx = -1;
struct drm_mode_modeinfo m;
if (display_pick(outs, n, &idx, &m) == 0 && idx >= 0 &&
- (outs[idx].id != k->conn_id || m.hdisplay != k->mode.hdisplay || m.vdisplay != k->mode.vdisplay || mode_refresh_mhz(&m) != mode_refresh_mhz(&k->mode) || D.prot != D.rot)) {
+ (outs[idx].id != k->conn_id || m.hdisplay != k->mode.hdisplay || m.vdisplay != k->mode.vdisplay || mode_refresh_mhz(&m) != mode_refresh_mhz(&k->mode) || D.prot != D.rot || D.pscale != D.scale)) {
D.pending = 1;
D.pconn = outs[idx].id;
D.pmode = m;
@@ -169,6 +171,8 @@ int display_pick(const KmsOutput *o, int n, int *index, struct drm_mode_modeinfo
*mode = o[sel].modes[m];
D.prot = s ? s->rot : 0;
D.rot = D.prot; /* kms_open/kms_attach use this mode right away */
+ D.pscale = s && s->scale == 2 ? 2 : 1;
+ D.scale = D.pscale;
return 0;
}
@@ -291,8 +295,8 @@ static void out_json(HBuf *b, const KmsOutput *o, const Kms *k) {
char *display_list_json(void) {
Kms *k = kms();
HBuf b = { 0 };
- hb_printf(&b, "{\"onMonitor\":%s,\"rotation\":%d,\"temperature\":%d,\"gammaSize\":%d,\"softTint\":%s,\"maxOutputs\":1,\"outputs\":[",
- k ? "true" : "false", D.rot, D.kelvin, k ? kms_gamma_size(k) : 0, D.soft ? "true" : "false");
+ hb_printf(&b, "{\"onMonitor\":%s,\"scale\":%d,\"rotation\":%d,\"temperature\":%d,\"gammaSize\":%d,\"softTint\":%s,\"maxOutputs\":1,\"outputs\":[",
+ k ? "true" : "false", D.scale, D.rot, D.kelvin, k ? kms_gamma_size(k) : 0, D.soft ? "true" : "false");
if (k) {
KmsOutput outs[KMS_MAX_OUTPUTS];
int n = kms_outputs(k->fd, outs, KMS_MAX_OUTPUTS), first = 1;
@@ -333,9 +337,9 @@ char *display_list_json(void) {
return hb_take(&b);
}
-int display_request(uint32_t conn, int w, int h, int refresh_mhz, int rotation) {
+int display_request(uint32_t conn, int w, int h, int refresh_mhz, int rotation, int scale) {
Kms *k = kms();
- if (!k || rotation < 0 || rotation > 3) return -1;
+ if (!k || rotation < 0 || rotation > 3 || (scale != 1 && scale != 2)) return -1;
KmsOutput outs[KMS_MAX_OUTPUTS];
int n = kms_outputs(k->fd, outs, KMS_MAX_OUTPUTS), ret = -1;
for (int i = 0; i < n; i++) {
@@ -346,6 +350,7 @@ int display_request(uint32_t conn, int w, int h, int refresh_mhz, int rotation)
D.pconn = conn;
D.pmode = outs[i].modes[m];
D.prot = rotation;
+ D.pscale = scale;
ret = 0;
}
kms_outputs_free(outs, n);
@@ -359,22 +364,26 @@ int display_take_modeset(uint32_t *conn, struct drm_mode_modeinfo *mode) {
*mode = D.pmode;
D.prev_rot = D.rot;
D.rot = D.prot;
+ D.prev_scale = D.scale;
+ D.scale = D.pscale;
return 1;
}
void display_modeset_done(int ok) {
- if (!ok) D.rot = D.prev_rot;
+ if (!ok) { D.rot = D.prev_rot; D.scale = D.prev_scale; }
apply_tint(); /* a new CRTC (or a modeset) can reset its LUT */
char *j = display_list_json();
if (j) { event("display", j); free(j); }
}
int display_rotation(void) { return D.rot; }
+int display_scale(void) { return D.scale; }
+int display_cpu_only(void) { return D.rot || D.scale > 1; }
void display_logical_size(int pw, int ph, int *lw, int *lh) {
int swap = D.rot & 1;
- *lw = swap ? ph : pw;
- *lh = swap ? pw : ph;
+ *lw = (swap ? ph : pw) / D.scale;
+ *lh = (swap ? pw : ph) / D.scale;
}
int display_save(uint32_t conn) {
@@ -394,6 +403,7 @@ int display_save(uint32_t conn) {
s->h = k->mode.vdisplay;
s->refresh = mode_refresh_mhz(&k->mode);
s->rot = D.rot;
+ s->scale = D.scale;
snprintf(D.main_id, sizeof D.main_id, "%s", id);
ret = store();
}
@@ -491,12 +501,15 @@ int display_is_off(void) { return D.off; }
/* ---- software rotation ---- */
Rect display_rotate_rect(Rect r, int lw, int lh, int rot) {
+ Rect o;
switch (rot & 3) {
- case 1: return (Rect){ lh - r.y1, r.x0, lh - r.y0, r.x1 }; /* (x, y) → (lh-1-y, x) */
- case 2: return (Rect){ lw - r.x1, lh - r.y1, lw - r.x0, lh - r.y0 };
- case 3: return (Rect){ r.y0, lw - r.x1, r.y1, lw - r.x0 }; /* (x, y) → (y, lw-1-x) */
- default: return r;
+ case 1: o = (Rect){ lh - r.y1, r.x0, lh - r.y0, r.x1 }; break; /* (x, y) → (lh-1-y, x) */
+ case 2: o = (Rect){ lw - r.x1, lh - r.y1, lw - r.x0, lh - r.y0 }; break;
+ case 3: o = (Rect){ r.y0, lw - r.x1, r.y1, lw - r.x0 }; break; /* (x, y) → (y, lw-1-x) */
+ default: o = r; break;
}
+ int k = D.scale; /* 200 %: every logical pixel is a 2×2 block */
+ return (Rect){ o.x0 * k, o.y0 * k, o.x1 * k, o.y1 * k };
}
/* Copies rect r (logical coordinates, inside lw×lh) to dst rotated; the logical pixel (x, y) is
@@ -508,19 +521,35 @@ void display_rotate_copy_at(const uint32_t *px, int stride, int ox, int oy, Rect
if (r.y1 > lh) r.y1 = lh;
if (r.x1 <= r.x0 || r.y1 <= r.y0) return;
rot &= 3;
+ int k = D.scale;
+ if (k == 1) {
+ for (int y = r.y0; y < r.y1; y++) {
+ const uint32_t *s = px + (size_t)(y - oy) * stride;
+ switch (rot) {
+ case 0: memcpy(dst->px + (size_t)y * dst->stride + r.x0, s + (r.x0 - ox), (size_t)(r.x1 - r.x0) * 4); break;
+ case 1: { uint32_t *col = dst->px + (lh - 1 - y); /* column lh-1-y, rows x */
+ for (int x = r.x0; x < r.x1; x++) col[(size_t)x * dst->stride] = s[x - ox];
+ break; }
+ case 2: { uint32_t *row = dst->px + (size_t)(lh - 1 - y) * dst->stride;
+ for (int x = r.x0; x < r.x1; x++) row[lw - 1 - x] = s[x - ox];
+ break; }
+ case 3: { uint32_t *col = dst->px + y; /* column y, rows lw-1-x */
+ for (int x = r.x0; x < r.x1; x++) col[(size_t)(lw - 1 - x) * dst->stride] = s[x - ox];
+ break; }
+ }
+ }
+ return;
+ }
+ /* scaled: the pixel at rotated position (rx, ry) fills the k×k block at (rx·k, ry·k) */
for (int y = r.y0; y < r.y1; y++) {
const uint32_t *s = px + (size_t)(y - oy) * stride;
- switch (rot) {
- case 0: memcpy(dst->px + (size_t)y * dst->stride + r.x0, s + (r.x0 - ox), (size_t)(r.x1 - r.x0) * 4); break;
- case 1: { uint32_t *col = dst->px + (lh - 1 - y); /* column lh-1-y, rows x */
- for (int x = r.x0; x < r.x1; x++) col[(size_t)x * dst->stride] = s[x - ox];
- break; }
- case 2: { uint32_t *row = dst->px + (size_t)(lh - 1 - y) * dst->stride;
- for (int x = r.x0; x < r.x1; x++) row[lw - 1 - x] = s[x - ox];
- break; }
- case 3: { uint32_t *col = dst->px + y; /* column y, rows lw-1-x */
- for (int x = r.x0; x < r.x1; x++) col[(size_t)(lw - 1 - x) * dst->stride] = s[x - ox];
- break; }
+ for (int x = r.x0; x < r.x1; x++) {
+ int rx = rot == 0 ? x : rot == 1 ? lh - 1 - y : rot == 2 ? lw - 1 - x : y;
+ int ry = rot == 0 ? y : rot == 1 ? x : rot == 2 ? lh - 1 - y : lw - 1 - x;
+ if (rx * k + k > dst->w || ry * k + k > dst->h) continue;
+ uint32_t v = s[x - ox], *d = dst->px + (size_t)(ry * k) * dst->stride + (size_t)rx * k;
+ for (int j = 0; j < k; j++, d += dst->stride)
+ for (int i = 0; i < k; i++) d[i] = v;
}
}
}
diff --git a/server/src/hw/display.h b/server/src/hw/display.h
index 9a710c3..ff8c6bf 100644
--- a/server/src/hw/display.h
+++ b/server/src/hw/display.h
@@ -35,9 +35,10 @@ void display_hotplug(void); /* DRM uevent: connectors may have chang
/* JSON for lord.display.list(). Returns a malloc'd string. */
char *display_list_json(void);
-/* Apply live (not saved): output id, w×h, refresh in mHz (0 = best), rotation 0..3 (×90°).
+/* Apply live (not saved): output id, w×h, refresh in mHz (0 = best), rotation 0..3 (×90°), scale
+ * 1 or 2 (200 %: drawn at half the size and doubled while copying the frame, CPU path).
* Queued; main.c runs it between frames (display_take_modeset). 0 if accepted. */
-int display_request(uint32_t conn, int w, int h, int refresh_mhz, int rotation);
+int display_request(uint32_t conn, int w, int h, int refresh_mhz, int rotation, int scale);
/* Save the current configuration of that output as its display's default (and as the main
* display). 0 if written. */
int display_save(uint32_t conn);
@@ -45,11 +46,14 @@ int display_save(uint32_t conn);
int display_take_modeset(uint32_t *conn, struct drm_mode_modeinfo *mode);
void display_modeset_done(int ok); /* main.c after kms_modeset (+ set_size, GPU restart) */
int display_rotation(void); /* 0..3: the frame is rotated by software (CPU path) */
-/* Logical size for a physical one with the current rotation (90°/270° swap). */
+int display_scale(void); /* 1 or 2 */
+int display_cpu_only(void); /* rotated or scaled: composed by the CPU, no GPU path */
+/* Logical size for a physical one with the current rotation (90°/270° swap) and scale. */
void display_logical_size(int pw, int ph, int *lw, int *lh);
-/* Software rotation (CPU path): rect r of the logical frame (lw×lh) in physical coordinates, and
- * the copy of that rect from the logical canvas into the physical one. rot 1 = 90° clockwise. */
+/* Software rotation and scale (CPU path): rect r of the logical frame (lw×lh) in physical
+ * coordinates, and the copy of that rect from the logical canvas into the physical one. rot 1 =
+ * 90° clockwise; with scale 2 every logical pixel becomes a 2×2 block. */
Rect display_rotate_rect(Rect r, int lw, int lh, int rot);
void display_rotate_copy(const Canvas *src, Rect r, Canvas *dst, int rot);
/* Same, from a buffer whose first pixel is logical (ox, oy) (a cursor composited apart). */
diff --git a/server/src/mail/html.c b/server/src/mail/html.c
index 1092496..2d9f8ca 100644
--- a/server/src/mail/html.c
+++ b/server/src/mail/html.c
@@ -520,7 +520,7 @@ static int open_frame(H *h, const char *t, const BStyle *b, const char *extra) {
if (extra) jb_raw(&h->out, extra);
jb_raw(&h->out, ",\"c\":[");
h->fr[h->nfr].kids = 0;
- h->fr[h->nfr].kind = t[0];
+ h->fr[h->nfr].kind = !strcmp(t, "tbl") ? 'T' : !strcmp(t, "tr") ? 'R' : !strcmp(t, "td") ? 'D' : 'B';
h->nfr++;
return 1;
}
@@ -799,7 +799,7 @@ static void open_tag(H *h, const char *tag, Attr *a, int na, int selfclose) {
}
if (!strcmp(tag, "a")) { int k = find_open(h, "a", STOP_CELL); if (k >= 0) pop_to(h, k); }
/* stray td inside a table without tr: open a tr */
- if ((!strcmp(tag, "td") || !strcmp(tag, "th")) && h->nfr > 0 && h->fr[h->nfr - 1].kind == 't' && h->nopen < (int)(sizeof h->open / sizeof h->open[0])) {
+ if ((!strcmp(tag, "td") || !strcmp(tag, "th")) && h->nfr > 0 && h->fr[h->nfr - 1].kind == 'T' && h->nopen < (int)(sizeof h->open / sizeof h->open[0])) {
Attr none[1];
open_tag(h, "tr", none, 0, 0);
}
diff --git a/server/src/mail/http.c b/server/src/mail/http.c
index 2dfae36..e202634 100644
--- a/server/src/mail/http.c
+++ b/server/src/mail/http.c
@@ -2,11 +2,14 @@
#include "http.h"
#include <ctype.h>
+#include <errno.h>
+#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <time.h>
+#include <limits.h>
static double now_ms(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec * 1e3 + t.tv_nsec / 1e6; }
@@ -41,6 +44,39 @@ int http_split_url(const char *url, int *tls, char *host, size_t hcap, int *port
void http_resp_free(HttpResp *r) { free(r->body); memset(r, 0, sizeof *r); }
+/* Chunk size line: hex digits, optional ";extensions", CRLF (or LF). -1 if anything else. */
+int http_chunk_size(const char *line, unsigned long long *out) {
+ const char *p = line;
+ if (!isxdigit((unsigned char)*p)) return -1;
+ char *end;
+ errno = 0;
+ unsigned long long v = strtoull(p, &end, 16);
+ if (errno == ERANGE || end == p) return -1;
+ if (end - p > 16) return -1;
+ if (*end == ';') { end++; while (*end && *end != '\r' && *end != '\n') { if ((unsigned char)*end < 0x20 && *end != '\t') return -1; end++; } }
+ while (*end == ' ' || *end == '\t') end++;
+ if (!(end[0] == '\r' && end[1] == '\n' && !end[2]) && !(end[0] == '\n' && !end[1])) return -1;
+ *out = v;
+ return 0;
+}
+
+/* Content-Length: decimal digits only (no sign, no garbage), no overflow. -1 if invalid. */
+int http_content_length(const char *v, unsigned long long *out) {
+ const char *p = v;
+ while (*p == ' ' || *p == '\t') p++;
+ if (!isdigit((unsigned char)*p)) return -1;
+ unsigned long long x = 0;
+ for (; isdigit((unsigned char)*p); p++) {
+ unsigned d = (unsigned)(*p - '0');
+ if (x > (ULLONG_MAX - d) / 10) return -1;
+ x = x * 10 + d;
+ }
+ while (*p == ' ' || *p == '\t') p++;
+ if (*p) return -1;
+ *out = x;
+ return 0;
+}
+
static void hdr_copy(const char *line, const char *name, char *out, size_t cap) {
size_t n = strlen(name);
if (strncasecmp(line, name, n) || line[n] != ':') return;
@@ -66,15 +102,22 @@ int http_request(Conn *c, const char *method, const char *host, const char *path
if (sscanf(line, "HTTP/%d.%d %d", &maj, &mn, &out->status) != 3) { free(line); return -1; }
free(line);
long long clen = -1;
- int chunked = 0, close_after = maj == 1 && mn == 0;
+ int chunked = 0, close_after = maj == 1 && mn == 0, done = 0;
+ size_t hdr_total = 0;
for (int n = 0; n < 200; n++) {
if (now_ms() > end) return -1;
line = conn_line(c, &ll, 16384);
if (!line) return -1;
- if (!strcmp(line, "\r\n") || !strcmp(line, "\n")) { free(line); break; }
+ hdr_total += ll;
+ if (hdr_total > 64 * 1024) { free(line); return -1; } /* headers: 64 KB at most */
+ if (!strcmp(line, "\r\n") || !strcmp(line, "\n")) { free(line); done = 1; break; }
char v[64] = "";
hdr_copy(line, "Content-Length", v, sizeof v);
- if (v[0]) clen = atoll(v);
+ if (v[0]) {
+ unsigned long long cl;
+ if (http_content_length(v, &cl) || cl > (unsigned long long)LLONG_MAX) { free(line); return -1; }
+ clen = (long long)cl;
+ }
v[0] = 0;
hdr_copy(line, "Transfer-Encoding", v, sizeof v);
if (strcasestr(v, "chunked")) chunked = 1;
@@ -86,6 +129,7 @@ int http_request(Conn *c, const char *method, const char *host, const char *path
hdr_copy(line, "Content-Type", out->content_type, sizeof out->content_type);
free(line);
}
+ if (!done) return -1; /* more than 200 header lines */
size_t cap = 0;
out->blen = 0;
if (!strcasecmp(method, "HEAD") || out->status == 204 || out->status == 304 || (out->status >= 100 && out->status < 200)) clen = 0;
@@ -94,20 +138,22 @@ int http_request(Conn *c, const char *method, const char *host, const char *path
if (now_ms() > end) { http_resp_free(out); return -1; }
line = conn_line(c, &ll, 1024);
if (!line) { http_resp_free(out); return -1; }
- unsigned long long sz = strtoull(line, NULL, 16);
+ unsigned long long sz;
+ int bad = http_chunk_size(line, &sz);
free(line);
+ if (bad) { http_resp_free(out); return -1; }
if (sz == 0) {
/* trailers until the empty line */
while ((line = conn_line(c, &ll, 8192))) { int done = !strcmp(line, "\r\n") || !strcmp(line, "\n"); free(line); if (done) break; }
break;
}
- if (out->blen + sz > max_body) { http_resp_free(out); return -2; }
+ if (sz > max_body || out->blen > max_body - sz) { http_resp_free(out); return -2; }
if (conn_read_n(c, (size_t)sz, &out->body, &out->blen, &cap)) { http_resp_free(out); return -1; }
line = conn_line(c, &ll, 16);
free(line);
}
} else if (clen >= 0) {
- if ((unsigned long long)clen > max_body) { http_resp_free(out); return -2; }
+ if ((unsigned long long)clen > (unsigned long long)max_body) { http_resp_free(out); return -2; }
if (clen && conn_read_n(c, (size_t)clen, &out->body, &out->blen, &cap)) { http_resp_free(out); return -1; }
} else {
/* until the server closes */
@@ -116,9 +162,16 @@ int http_request(Conn *c, const char *method, const char *host, const char *path
if (now_ms() > end) { http_resp_free(out); return -1; }
ssize_t r = conn_read_some(c, tmp, sizeof tmp);
if (r <= 0) break;
- if (out->blen + (size_t)r > max_body) { http_resp_free(out); return -2; }
size_t want = (size_t)r;
- if (out->blen + want + 1 > cap) { cap = (out->blen + want + 1) * 2; char *nb = realloc(out->body, cap); if (!nb) { http_resp_free(out); return -1; } out->body = nb; }
+ if (want > max_body || out->blen > max_body - want) { http_resp_free(out); return -2; }
+ if (out->blen + want + 1 > cap) {
+ size_t nc = out->blen + want + 1;
+ nc = nc <= SIZE_MAX / 2 ? nc * 2 : nc;
+ char *nb = realloc(out->body, nc);
+ if (!nb) { http_resp_free(out); return -1; }
+ out->body = nb;
+ cap = nc;
+ }
memcpy(out->body + out->blen, tmp, want);
out->blen += want;
}
diff --git a/server/src/mail/http.h b/server/src/mail/http.h
index b841466..99c88e5 100644
--- a/server/src/mail/http.h
+++ b/server/src/mail/http.h
@@ -23,5 +23,8 @@ int http_split_url(const char *url, int *tls, char *host, size_t hcap, int *por
int http_request(Conn *c, const char *method, const char *host, const char *path, const char *extra_headers,
const char *body, size_t blen, size_t max_body, int deadline_ms, HttpResp *out);
void http_resp_free(HttpResp *r);
+/* strict parsers (exposed for tests): 0 ok, -1 invalid */
+int http_chunk_size(const char *line, unsigned long long *out);
+int http_content_length(const char *v, unsigned long long *out);
#endif
diff --git a/server/src/mail/imap.c b/server/src/mail/imap.c
index fa86121..d2a0152 100644
--- a/server/src/mail/imap.c
+++ b/server/src/mail/imap.c
@@ -8,6 +8,7 @@
* flags, move, delete, drafts) interrupt the IDLE through an eventfd. */
#include "maild.h"
#include "imapp.h"
+#include "imapio.h"
#include "mime.h"
#include <ctype.h>
@@ -61,33 +62,10 @@ static void parse_caps(Imap *im, const char *line) {
/* One complete response (line + literals) as raw bytes. NULL on I/O error. */
static char *read_raw(Imap *im, size_t *len) {
- size_t n = 0, cap = 0;
- char *buf = NULL;
- for (;;) {
- size_t ll;
- char *line = conn_line(im->c, &ll, LINE_MAX_BYTES);
- if (!line) { free(buf); return NULL; }
- if (n + ll + 1 > cap) { cap = (n + ll + 1) * 2; char *nb = realloc(buf, cap); if (!nb) { free(line); free(buf); return NULL; } buf = nb; }
- memcpy(buf + n, line, ll);
- n += ll;
- buf[n] = 0;
- free(line);
- /* "{123}\r\n" or "{123+}\r\n" at the end: a literal follows */
- size_t e = n;
- if (e >= 2 && buf[e - 1] == '\n') e--;
- if (e >= 1 && buf[e - 1] == '\r') e--;
- if (e < 3 || buf[e - 1] != '}') break;
- size_t s = e - 1;
- while (s > 0 && buf[s - 1] != '{') s--;
- if (!s) break;
- char *endp;
- unsigned long long lit = strtoull(buf + s, &endp, 10);
- if (endp == buf + s || (*endp != '}' && *endp != '+')) break;
- if (lit > LINE_MAX_BYTES * 4) { free(buf); snprintf(im->text, sizeof im->text, "literal too big"); return NULL; }
- if (conn_read_n(im->c, (size_t)lit, &buf, &n, &cap)) { free(buf); return NULL; }
- }
- *len = n;
- return buf;
+ char err[96];
+ char *r = imap_read_response(im->c, len, LINE_MAX_BYTES, (size_t)64 << 20, err, sizeof err);
+ if (!r) snprintf(im->text, sizeof im->text, "%s", err);
+ return r;
}
typedef void (*Untagged)(Imap *im, IResp *r, void *u);
@@ -243,7 +221,7 @@ static int imap_open(Imap *im, char *err, size_t ecap) {
explicit_bzero(pw, strlen(pw));
free(pw);
if (r) {
- snprintf(err, ecap, r < 0 ? "io" : "auth: %s", im->text);
+ SNPF(err, ecap, r < 0 ? "io" : "auth: %s", im->text);
imap_close(im);
if (r > 0) {
/* wrong password: ask again (from the keyring prompt) */
@@ -295,7 +273,7 @@ static void on_list(Imap *im, IResp *r, void *u) {
f->noselect = strcasestr(fl, "\\Noselect") || strcasestr(fl, "\\NonExistent");
}
pthread_mutex_unlock(&G);
- if (lc->nseen < 512) snprintf(lc->seen[lc->nseen++], sizeof lc->seen[0], "%s", !strcasecmp(nm, "INBOX") ? "INBOX" : nm);
+ if (lc->nseen < 512) SNPF(lc->seen[lc->nseen++], sizeof lc->seen[0], "%s", !strcasecmp(nm, "INBOX") ? "INBOX" : nm);
}
static int sync_folder_list(Imap *im) {
@@ -364,6 +342,7 @@ static void addr_list_text(const char *raw, char *out, size_t cap) {
}
static void on_fetch(Imap *im, IResp *r, void *u) {
+ (void)im;
FetchCtx *fc = u;
if (!r->first || !iv_is(r->first->next, "FETCH")) return;
IVal *list = r->first->next->next;
@@ -407,7 +386,7 @@ static void on_fetch(Imap *im, IResp *r, void *u) {
}
if (mime_header(h, hl, "To", v, sizeof v)) addr_list_text(v, to, sizeof to);
if (mime_header(h, hl, "Cc", v, sizeof v)) addr_list_text(v, cc, sizeof cc);
- if (mime_header(h, hl, "Subject", v, sizeof v)) { mime_decode_words(v, dec, sizeof dec); snprintf(subject, sizeof subject, "%s", dec); }
+ if (mime_header(h, hl, "Subject", v, sizeof v)) { mime_decode_words(v, dec, sizeof dec); SNPF(subject, sizeof subject, "%s", dec); }
mime_header(h, hl, "Message-ID", msgid, sizeof msgid);
mime_header(h, hl, "In-Reply-To", irt, sizeof irt);
char *refs = mime_header_dup(h, hl, "References");
@@ -551,7 +530,7 @@ static int sync_folder(Imap *im, Folder *f) {
char set[CHUNK * 12];
imap_uidset(chunk, n, set, sizeof set);
rc = cmd(im, on_fetch, &fc, "UID FETCH %s (UID FLAGS INTERNALDATE RFC822.SIZE BODY.PEEK[HEADER.FIELDS (FROM TO CC SUBJECT DATE MESSAGE-ID IN-REPLY-TO "
- "REFERENCES CONTENT-TYPE)] BODY.PEEK[TEXT]<0.2048>)", set);
+ "REFERENCES CONTENT-TYPE CONTENT-TRANSFER-ENCODING)] BODY.PEEK[TEXT]<0.2048>)", set);
if (rc < 0) break;
pthread_mutex_lock(&G);
store_save(a, f);
diff --git a/server/src/mail/imapio.c b/server/src/mail/imapio.c
new file mode 100644
index 0000000..c934b09
--- /dev/null
+++ b/server/src/mail/imapio.c
@@ -0,0 +1,56 @@
+/* imapio.c — reading one complete IMAP response (line + literals) from a connection, with
+ * bounded, overflow-checked sizes. Separate from imap.c so the tests can drive it over a
+ * socketpair. */
+#include "imapio.h"
+
+#include <ctype.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+/* "{123}" or "{123+}" right before the final CRLF/LF: the literal size, or -1. */
+long long imap_literal_size(const char *buf, size_t n) {
+ size_t e = n;
+ if (e >= 1 && buf[e - 1] == '\n') e--;
+ if (e >= 1 && buf[e - 1] == '\r') e--;
+ if (e < 3 || buf[e - 1] != '}') return -1;
+ size_t close = e - 1, d = close;
+ if (d > 0 && buf[d - 1] == '+') d--;
+ size_t digits_end = d;
+ while (d > 0 && isdigit((unsigned char)buf[d - 1])) d--;
+ if (d == digits_end || d == 0 || buf[d - 1] != '{') return -1;
+ if (digits_end - d > 12) return -2; /* ≥ 10^12: hostile */
+ long long v = 0;
+ for (size_t i = d; i < digits_end; i++) v = v * 10 + (buf[i] - '0');
+ return v;
+}
+
+char *imap_read_response(Conn *c, size_t *len, size_t line_max, size_t literal_max, char *err, size_t ecap) {
+ size_t n = 0, cap = 0, total_max = line_max + literal_max * 4;
+ char *buf = NULL;
+ for (int parts = 0; parts < 10000; parts++) {
+ size_t ll;
+ char *line = conn_line(c, &ll, line_max);
+ if (!line) { free(buf); snprintf(err, ecap, "%s", conn_error(c)); return NULL; }
+ if (ll > total_max || n > total_max - ll) { free(line); free(buf); snprintf(err, ecap, "response too big"); return NULL; }
+ if (n + ll + 1 > cap) {
+ size_t nc = (n + ll + 1) * 2;
+ char *nb = realloc(buf, nc);
+ if (!nb) { free(line); free(buf); snprintf(err, ecap, "memory"); return NULL; }
+ buf = nb;
+ cap = nc;
+ }
+ memcpy(buf + n, line, ll);
+ n += ll;
+ buf[n] = 0; /* n + 1 <= cap */
+ free(line);
+ long long lit = imap_literal_size(buf, n);
+ if (lit == -1) { *len = n; return buf; }
+ if (lit < 0 || (unsigned long long)lit > literal_max || n > total_max - (size_t)lit) { free(buf); snprintf(err, ecap, "literal too big"); return NULL; }
+ if (conn_read_n(c, (size_t)lit, &buf, &n, &cap)) { free(buf); snprintf(err, ecap, "%s", conn_error(c)); return NULL; }
+ }
+ free(buf);
+ snprintf(err, ecap, "too many literals");
+ return NULL;
+}
diff --git a/server/src/mail/imapio.h b/server/src/mail/imapio.h
new file mode 100644
index 0000000..804a580
--- /dev/null
+++ b/server/src/mail/imapio.h
@@ -0,0 +1,13 @@
+/* imapio.h — see imapio.c. */
+#ifndef LORD_MAIL_IMAPIO_H
+#define LORD_MAIL_IMAPIO_H
+
+#include <stddef.h>
+#include "net.h"
+
+/* Size of the literal announced at the end of a line ("{n}" / "{n+}"), -1 if none, -2 if absurd. */
+long long imap_literal_size(const char *buf, size_t n);
+/* One response with its literals inline (malloc, NUL-terminated; *len without the NUL). */
+char *imap_read_response(Conn *c, size_t *len, size_t line_max, size_t literal_max, char *err, size_t ecap);
+
+#endif
diff --git a/server/src/mail/maild.h b/server/src/mail/maild.h
index 4e5ef42..2a1e4d1 100644
--- a/server/src/mail/maild.h
+++ b/server/src/mail/maild.h
@@ -26,6 +26,7 @@
#include "../doc/wire.h"
#include "../sec/json.h"
#include "net.h"
+#include "snpf.h"
extern pthread_mutex_t G;
extern int cache_fd;
diff --git a/server/src/mail/mime.c b/server/src/mail/mime.c
index 4d1c400..f0b0408 100644
--- a/server/src/mail/mime.c
+++ b/server/src/mail/mime.c
@@ -680,9 +680,22 @@ char *mime_part_text(const MimePart *p, size_t *olen) {
/* ---- addresses ---- */
+static int addrs_raw(const char *value, MimeAddr *out, int max);
+
int mime_addrs(const char *value, MimeAddr *out, int max) {
- int n = 0;
if (!value) return 0;
+ int n = addrs_raw(value, out, max);
+ /* broken mailers encode the whole "Name <addr>" as one encoded word: decode, then parse */
+ if (!n && strstr(value, "=?")) {
+ char dec[2048];
+ mime_decode_words(value, dec, sizeof dec);
+ n = addrs_raw(dec, out, max);
+ }
+ return n;
+}
+
+static int addrs_raw(const char *value, MimeAddr *out, int max) {
+ int n = 0;
const char *s = value;
while (*s && n < max) {
/* one element up to the top-level comma */
diff --git a/server/src/mail/net.c b/server/src/mail/net.c
index 7b321c2..fd71eb4 100644
--- a/server/src/mail/net.c
+++ b/server/src/mail/net.c
@@ -4,6 +4,7 @@
#include <errno.h>
#include <poll.h>
#include <stdarg.h>
+#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@@ -159,9 +160,10 @@ char *conn_line(Conn *c, size_t *len, size_t max) {
if (!fill(c)) { free(o); return NULL; }
char *nl = memchr(c->rb + c->rpos, '\n', c->rlen - c->rpos);
size_t take = nl ? (size_t)(nl - (c->rb + c->rpos)) + 1 : c->rlen - c->rpos;
+ if (n + take > max) { free(o); snprintf(c->err, sizeof c->err, "line too long"); return NULL; }
if (n + take + 1 > cap) {
while (n + take + 1 > cap) cap *= 2;
- if (cap > max + 2) { if (n + take > max) { free(o); snprintf(c->err, sizeof c->err, "line too long"); return NULL; } cap = max + 2; }
+ if (cap > max + 1) cap = max + 1; /* n + take <= max, so the NUL still fits */
char *no = realloc(o, cap);
if (!no) { free(o); return NULL; }
o = no;
@@ -177,9 +179,11 @@ char *conn_line(Conn *c, size_t *len, size_t max) {
}
int conn_read_n(Conn *c, size_t want, char **buf, size_t *len, size_t *cap) {
- if (*len + want + 1 > *cap) {
+ if (*len >= SIZE_MAX - 1 || want > SIZE_MAX - *len - 1) return -1;
+ size_t need = *len + want + 1; /* always room for the terminating NUL */
+ if (need > *cap) {
size_t nc = *cap ? *cap : 1024;
- while (nc < *len + want + 1) nc *= 2;
+ while (nc < need) { if (nc > SIZE_MAX / 2) { nc = need; break; } nc *= 2; }
char *nb = realloc(*buf, nc);
if (!nb) return -1;
*buf = nb; *cap = nc;
diff --git a/server/src/mail/pim.c b/server/src/mail/pim.c
new file mode 100644
index 0000000..3696b27
--- /dev/null
+++ b/server/src/mail/pim.c
@@ -0,0 +1,1382 @@
+/* pim.c — calendars, reminders and address books of lord-maild, local and synced with CalDAV /
+ * CardDAV (see maild.h, dav.h and docs/MAIL.md).
+ *
+ * A collection is a calendar (events and/or to-dos) or an address book. Local ones live only
+ * here; DAV ones mirror a server collection: every item keeps its href and ETag, local edits are
+ * marked dirty and pushed with If-Match, and a sync compares ETags (after the CTag says
+ * something changed) and fetches what changed with a multiget REPORT.
+ *
+ * Files under the cache: pim/colls (one line per collection), pim/<id>/meta (one line per item:
+ * file, uid, href, etag, dirty) and pim/<id>/<file> (the .ics or .vcf). Callers hold G, except
+ * pim_dav_sync, which takes it only around in-memory changes. */
+#include "maild.h"
+#include "dav.h"
+#include "ical.h"
+#include "vcard.h"
+#include "xml.h"
+#include "mime.h"
+
+#include <ctype.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <strings.h>
+#include <sys/random.h>
+#include <time.h>
+#include <unistd.h>
+
+#define MAX_COLLS 256
+
+enum { CLEAN = 0, DIRTY_PUT = 1, DIRTY_DEL = 2 };
+
+typedef struct {
+ char uid[256], file[64], href[1024], etag[256];
+ int dirty;
+ IcEvent *ev; /* calendars: master and overrides */
+ int nev;
+ char *json; /* address books: the contact as JSON */
+ char fn[256];
+ char *emails; /* "name\temail\n" lines */
+ int photo;
+} Item;
+
+typedef struct {
+ char id[80];
+ char kind; /* 'c' calendar, 'b' address book */
+ char acct[40]; /* "" = local */
+ char name[200], color[16], href[1024], ctag[256];
+ int todos, events, hidden, seen;
+ Item *items;
+ int n, cap;
+} Coll;
+
+static Coll *colls[MAX_COLLS];
+static int ncolls;
+
+/* ---- helpers ---- */
+
+static void new_uid(char *out, size_t cap) {
+ unsigned char r[16];
+ if (getrandom(r, sizeof r, 0) != (ssize_t)sizeof r) for (int i = 0; i < 16; i++) r[i] = (unsigned char)(rand() ^ (int)time(NULL));
+ r[6] = (unsigned char)((r[6] & 0x0f) | 0x40);
+ r[8] = (unsigned char)((r[8] & 0x3f) | 0x80);
+ snprintf(out, cap, "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x", r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9],
+ r[10], r[11], r[12], r[13], r[14], r[15]);
+}
+
+static void put_field(JBuf *b, const char *s) {
+ for (; s && *s; s++) {
+ if (*s == '\t') jb_raw(b, "\\t");
+ else if (*s == '\n') jb_raw(b, "\\n");
+ else if (*s == '\\') jb_raw(b, "\\\\");
+ else if (*s != '\r') { char c[2] = { *s, 0 }; jb_raw(b, c); }
+ }
+}
+
+static char *get_field(char **p) {
+ char *s = *p, *o = s, *r = s;
+ while (*s && *s != '\t' && *s != '\n') {
+ if (*s == '\\' && s[1]) { s++; *o++ = *s == 't' ? '\t' : *s == 'n' ? '\n' : *s; s++; continue; }
+ *o++ = *s++;
+ }
+ char end = *s;
+ *o = 0;
+ *p = end == '\t' ? s + 1 : s;
+ return r;
+}
+
+static void scopy(char *d, size_t cap, const char *s) { if (!cap) return; size_t n = s ? strlen(s) : 0; if (n >= cap) n = cap - 1; if (n) memcpy(d, s, n); d[n] = 0; }
+
+static Coll *coll_get(const char *id) {
+ if (!id) return NULL;
+ for (int i = 0; i < ncolls; i++) if (!strcmp(colls[i]->id, id)) return colls[i];
+ return NULL;
+}
+
+static void item_clear(Item *it) {
+ if (it->ev) ical_events_free(it->ev, it->nev);
+ free(it->json);
+ free(it->emails);
+ it->ev = NULL; it->nev = 0; it->json = NULL; it->emails = NULL;
+}
+
+static void contact_emails_cb(void *u, const char *name, const char *email) {
+ JBuf *b = u;
+ put_field(b, name);
+ jb_raw(b, "\t");
+ put_field(b, email);
+ jb_raw(b, "\n");
+}
+
+/* (Re)parse an item's text into the in-memory form. */
+static int item_parse(Coll *c, Item *it, const char *text, size_t len) {
+ item_clear(it);
+ if (c->kind == 'c') {
+ char method[24];
+ int n = ical_events(text, len, &it->ev, method, sizeof method);
+ if (n <= 0) { it->ev = NULL; return -1; }
+ it->nev = n;
+ if (!it->uid[0]) scopy(it->uid, sizeof it->uid, it->ev[0].uid);
+ return 0;
+ }
+ JBuf b;
+ jb_init(&b);
+ if (vcard_json(text, len, &b) <= 0) { jb_free(&b); return -1; }
+ it->json = b.p;
+ JDoc d;
+ if (!json_parse(it->json, b.n, &d, NULL, 0)) {
+ scopy(it->fn, sizeof it->fn, json_str(d.root, "fn"));
+ if (!it->uid[0]) scopy(it->uid, sizeof it->uid, json_str(d.root, "uid"));
+ it->photo = json_bool(d.root, "photo", 0);
+ json_free(&d);
+ }
+ JBuf e;
+ jb_init(&e);
+ vcard_emails(text, len, contact_emails_cb, &e);
+ it->emails = e.p;
+ return 0;
+}
+
+static void coll_dir(const Coll *c, const char *file, char *out, size_t cap) { snprintf(out, cap, "pim/%s/%s", c->id, file); }
+
+static void save_meta(Coll *c) {
+ JBuf b;
+ jb_init(&b);
+ for (int i = 0; i < c->n; i++) {
+ Item *it = &c->items[i];
+ put_field(&b, it->file); jb_raw(&b, "\t");
+ put_field(&b, it->uid); jb_raw(&b, "\t");
+ put_field(&b, it->href); jb_raw(&b, "\t");
+ put_field(&b, it->etag);
+ jb_printf(&b, "\t%d\n", it->dirty);
+ }
+ char rel[200];
+ coll_dir(c, "meta", rel, sizeof rel);
+ if (!b.oom) fs_write(rel, b.p ? b.p : "", b.n);
+ jb_free(&b);
+}
+
+static void save_colls(void) {
+ JBuf b;
+ jb_init(&b);
+ for (int i = 0; i < ncolls; i++) {
+ Coll *c = colls[i];
+ put_field(&b, c->id); jb_printf(&b, "\t%c\t", c->kind);
+ put_field(&b, c->acct); jb_raw(&b, "\t");
+ put_field(&b, c->name); jb_raw(&b, "\t");
+ put_field(&b, c->color); jb_raw(&b, "\t");
+ put_field(&b, c->href); jb_raw(&b, "\t");
+ put_field(&b, c->ctag);
+ jb_printf(&b, "\t%d\t%d\t%d\n", c->todos, c->events, c->hidden);
+ }
+ fs_mkdirs("pim");
+ if (!b.oom) fs_write("pim/colls", b.p ? b.p : "", b.n);
+ jb_free(&b);
+}
+
+static Coll *coll_new(const char *id, char kind, const char *acct, const char *name, const char *color) {
+ if (ncolls >= MAX_COLLS) return NULL;
+ Coll *c = calloc(1, sizeof *c);
+ if (!c) return NULL;
+ scopy(c->id, sizeof c->id, id);
+ c->kind = kind;
+ scopy(c->acct, sizeof c->acct, acct);
+ scopy(c->name, sizeof c->name, name);
+ scopy(c->color, sizeof c->color, color && *color ? color : "#0a84ff");
+ c->events = kind == 'c';
+ colls[ncolls++] = c;
+ char rel[160];
+ snprintf(rel, sizeof rel, "pim/%s", c->id);
+ fs_mkdirs(rel);
+ return c;
+}
+
+static void coll_remove(Coll *c) {
+ for (int i = 0; i < c->n; i++) item_clear(&c->items[i]);
+ free(c->items);
+ char rel[160];
+ snprintf(rel, sizeof rel, "pim/%s", c->id);
+ fs_rmtree(rel);
+ for (int i = 0; i < ncolls; i++) if (colls[i] == c) { colls[i] = colls[--ncolls]; break; }
+ free(c);
+}
+
+static Item *item_get(Coll *c, const char *uid) {
+ for (int i = 0; uid && i < c->n; i++) if (!strcmp(c->items[i].uid, uid)) return &c->items[i];
+ return NULL;
+}
+
+static Item *item_by_href(Coll *c, const char *href) {
+ for (int i = 0; href && i < c->n; i++) if (!strcmp(c->items[i].href, href)) return &c->items[i];
+ return NULL;
+}
+
+static Item *item_new(Coll *c, const char *uid) {
+ if (c->n == c->cap) {
+ int nc = c->cap ? c->cap * 2 : 32;
+ Item *ni = realloc(c->items, (size_t)nc * sizeof *ni);
+ if (!ni) return NULL;
+ c->items = ni;
+ c->cap = nc;
+ }
+ Item *it = &c->items[c->n++];
+ memset(it, 0, sizeof *it);
+ scopy(it->uid, sizeof it->uid, uid);
+ char h[17];
+ fs_hash(uid && *uid ? uid : "x", h);
+ snprintf(it->file, sizeof it->file, "%s.%s", h, c->kind == 'c' ? "ics" : "vcf");
+ return it;
+}
+
+static void item_delete(Coll *c, Item *it) {
+ char rel[200];
+ coll_dir(c, it->file, rel, sizeof rel);
+ fs_unlink(rel);
+ item_clear(it);
+ int pos = (int)(it - c->items);
+ c->items[pos] = c->items[--c->n];
+}
+
+/* Writes the item's text, parses it, and marks it for upload when the collection syncs. */
+static int item_write(Coll *c, Item *it, const char *text, size_t len, int dirty) {
+ char rel[200];
+ coll_dir(c, it->file, rel, sizeof rel);
+ if (fs_write(rel, text, len)) return -1;
+ if (item_parse(c, it, text, len)) return -1;
+ if (dirty && c->acct[0]) {
+ it->dirty = DIRTY_PUT;
+ if (!it->href[0]) {
+ char safe[200];
+ fs_safe_name(it->uid, safe, sizeof safe);
+ for (char *p = safe; *p; p++) if (!isalnum((unsigned char)*p) && *p != '-' && *p != '_' && *p != '.') *p = '_';
+ SNPF(it->href, sizeof it->href, "%s%s%s.%s", c->href, c->href[0] && c->href[strlen(c->href) - 1] == '/' ? "" : "/", safe, c->kind == 'c' ? "ics" : "vcf");
+ }
+ }
+ save_meta(c);
+ return 0;
+}
+
+static void changed_event(const char *what) {
+ JBuf b;
+ jb_init(&b);
+ jb_printf(&b, "{\"ev\":\"pim-changed\",\"what\":\"%s\"}", what);
+ send_event(&b);
+}
+
+static void push_soon(Coll *c) {
+ if (!c->acct[0]) return;
+ Account *a = acct_get(c->acct);
+ if (!a) return;
+ Job *j = job_new(J_DAV_SYNC, 0, 5);
+ if (j) job_push(a, j);
+}
+
+/* ---- loading ---- */
+
+static void load_coll(Coll *c) {
+ char rel[200];
+ coll_dir(c, "meta", rel, sizeof rel);
+ size_t n;
+ char *meta = fs_read(rel, &n, 64 << 20);
+ if (!meta) return;
+ char *p = meta;
+ while (*p) {
+ char *file = get_field(&p), *uid = get_field(&p), *href = get_field(&p), *etag = get_field(&p);
+ int dirty = atoi(p);
+ char *nl = strchr(p, '\n');
+ p = nl ? nl + 1 : p + strlen(p);
+ if (!file[0] || strchr(file, '/') || file[0] == '.') continue;
+ Item *it = item_new(c, uid);
+ if (!it) break;
+ scopy(it->file, sizeof it->file, file);
+ scopy(it->href, sizeof it->href, href);
+ scopy(it->etag, sizeof it->etag, etag);
+ it->dirty = dirty == DIRTY_PUT || dirty == DIRTY_DEL ? dirty : CLEAN;
+ char fr[200];
+ coll_dir(c, file, fr, sizeof fr);
+ size_t tl;
+ char *t = fs_read(fr, &tl, 16 << 20);
+ if (!t || (item_parse(c, it, t, tl) && it->dirty != DIRTY_DEL)) { c->n--; free(t); continue; }
+ free(t);
+ }
+ free(meta);
+}
+
+void pim_init(void) {
+ fs_mkdirs("pim");
+ size_t n;
+ char *list = fs_read("pim/colls", &n, 4 << 20);
+ if (list) {
+ char *p = list;
+ while (*p) {
+ char *id = get_field(&p), *kind = get_field(&p), *acct = get_field(&p), *name = get_field(&p), *color = get_field(&p),
+ *href = get_field(&p), *ctag = get_field(&p);
+ int todos = 0, events = 0, hidden = 0;
+ sscanf(p, "%d\t%d\t%d", &todos, &events, &hidden);
+ char *nl = strchr(p, '\n');
+ p = nl ? nl + 1 : p + strlen(p);
+ if (!id[0] || strchr(id, '/') || id[0] == '.' || (kind[0] != 'c' && kind[0] != 'b')) continue;
+ Coll *c = coll_new(id, kind[0], acct, name, color);
+ if (!c) break;
+ scopy(c->href, sizeof c->href, href);
+ scopy(c->ctag, sizeof c->ctag, ctag);
+ c->todos = todos; c->events = events; c->hidden = hidden;
+ load_coll(c);
+ }
+ free(list);
+ }
+ /* first run: a calendar, a reminders list and an address book on this computer */
+ int cal = 0, rem = 0, book = 0;
+ for (int i = 0; i < ncolls; i++) { if (colls[i]->kind == 'b') book = 1; else if (colls[i]->todos && !colls[i]->events) rem = 1; else cal = 1; }
+ if (!cal) coll_new("local-calendar", 'c', "", "Personal", "#0a84ff");
+ if (!rem) { Coll *c = coll_new("local-reminders", 'c', "", "Reminders", "#ff9f0a"); if (c) { c->todos = 1; c->events = 0; } }
+ if (!book) coll_new("local-contacts", 'b', "", "Contacts", "#8e8e93");
+ if (!cal || !rem || !book) save_colls();
+}
+
+void pim_account_removed(const char *id) {
+ pthread_mutex_lock(&G);
+ for (int i = ncolls - 1; i >= 0; i--) if (!strcmp(colls[i]->acct, id)) coll_remove(colls[i]);
+ save_colls();
+ pthread_mutex_unlock(&G);
+ changed_event("all");
+}
+
+/* ---- JSON ---- */
+
+static void coll_json(JBuf *b, const Coll *c) {
+ jb_raw(b, "{\"id\":"); jb_str(b, c->id);
+ jb_raw(b, ",\"name\":"); jb_str(b, c->name);
+ jb_raw(b, ",\"color\":"); jb_str(b, c->color);
+ jb_raw(b, ",\"acct\":"); jb_str(b, c->acct);
+ Account *a = c->acct[0] ? acct_get(c->acct) : NULL;
+ jb_raw(b, ",\"acctName\":"); jb_str(b, a ? (a->name[0] ? a->name : a->user) : "");
+ jb_printf(b, ",\"kind\":\"%s\",\"todos\":%s,\"events\":%s,\"hidden\":%s,\"count\":%d}", c->acct[0] ? "dav" : "local", c->todos ? "true" : "false",
+ c->events ? "true" : "false", c->hidden ? "true" : "false", c->n);
+}
+
+typedef struct { JBuf *b; const Coll *c; const Item *it; const IcEvent *ev; int64_t *rids; int nrids; int count, max; } OccCtx;
+
+static void occ_cb(void *u, int64_t start) {
+ OccCtx *o = u;
+ for (int i = 0; i < o->nrids; i++) if (o->rids[i] == start) return; /* replaced by an override */
+ if (o->count >= o->max) return;
+ if (o->count++) jb_raw(o->b, ",");
+ JBuf tmp;
+ jb_init(&tmp);
+ ical_event_json(&tmp, o->ev, o->ev->rrule[0] ? start : 0);
+ if (tmp.p && tmp.n > 1) {
+ tmp.p[tmp.n - 1] = 0; /* drop "}" to add the calendar */
+ jb_raw(o->b, tmp.p);
+ jb_raw(o->b, ",\"cal\":"); jb_str(o->b, o->c->id);
+ jb_raw(o->b, ",\"color\":"); jb_str(o->b, o->c->color);
+ jb_raw(o->b, "}");
+ } else jb_raw(o->b, "{}");
+ jb_free(&tmp);
+}
+
+static int cal_wanted(const Coll *c, const JVal *cals) {
+ if (!cals || cals->type != J_ARR) return !c->hidden;
+ for (const JVal *x = cals->kid; x; x = x->next) if (x->type == J_STR && !strcmp(x->str, c->id)) return 1;
+ return 0;
+}
+
+static void events_json(JBuf *b, int64_t from, int64_t to, const JVal *cals) {
+ jb_raw(b, "{\"events\":[");
+ OccCtx o = { b, NULL, NULL, NULL, NULL, 0, 0, 20000 };
+ for (int i = 0; i < ncolls; i++) {
+ Coll *c = colls[i];
+ if (c->kind != 'c' || !c->events || !cal_wanted(c, cals)) continue;
+ for (int k = 0; k < c->n; k++) {
+ Item *it = &c->items[k];
+ if (it->dirty == DIRTY_DEL) continue;
+ int64_t rids[64];
+ int nr = 0;
+ for (int e = 0; e < it->nev && nr < 64; e++) if (it->ev[e].recurrence_id) rids[nr++] = it->ev[e].recurrence_id;
+ for (int e = 0; e < it->nev; e++) {
+ IcEvent *ev = &it->ev[e];
+ if (ev->is_todo) continue;
+ o.c = c; o.it = it; o.ev = ev;
+ o.rids = ev->recurrence_id ? NULL : rids;
+ o.nrids = ev->recurrence_id ? 0 : nr;
+ ical_expand(ev, from, to, 2000, occ_cb, &o);
+ }
+ }
+ }
+ jb_raw(b, "]}");
+}
+
+static void todos_json(JBuf *b, const JVal *lists) {
+ jb_raw(b, "{\"todos\":[");
+ int n = 0;
+ for (int i = 0; i < ncolls; i++) {
+ Coll *c = colls[i];
+ if (c->kind != 'c' || !c->todos || !cal_wanted(c, lists)) continue;
+ for (int k = 0; k < c->n; k++) {
+ Item *it = &c->items[k];
+ if (it->dirty == DIRTY_DEL) continue;
+ for (int e = 0; e < it->nev; e++) {
+ if (!it->ev[e].is_todo) continue;
+ if (n++) jb_raw(b, ",");
+ JBuf tmp;
+ jb_init(&tmp);
+ ical_event_json(&tmp, &it->ev[e], 0);
+ if (tmp.p && tmp.n > 1) { tmp.p[tmp.n - 1] = 0; jb_raw(b, tmp.p); jb_raw(b, ",\"list\":"); jb_str(b, c->id); jb_raw(b, ",\"color\":"); jb_str(b, c->color); jb_raw(b, "}"); }
+ else jb_raw(b, "{}");
+ jb_free(&tmp);
+ }
+ }
+ }
+ jb_raw(b, "]}");
+}
+
+typedef struct { JBuf *b; int *count; int64_t from, to; const Coll *c; const IcEvent *ev; } AlarmCtx;
+
+static void alarm_cb(void *u, int64_t start) {
+ AlarmCtx *a = u;
+ for (int i = 0; i < a->ev->nalarms; i++) {
+ int64_t at = start - (int64_t)a->ev->alarms[i] * 60;
+ if (at < a->from || at >= a->to) continue;
+ if ((*a->count)++) jb_raw(a->b, ",");
+ jb_printf(a->b, "{\"at\":%lld,\"start\":%lld,\"kind\":\"%s\",\"cal\":", (long long)at * 1000, (long long)start * 1000, a->ev->is_todo ? "todo" : "event");
+ jb_str(a->b, a->c->id);
+ jb_raw(a->b, ",\"uid\":"); jb_str(a->b, a->ev->uid);
+ jb_raw(a->b, ",\"title\":"); jb_str(a->b, a->ev->summary);
+ jb_raw(a->b, ",\"loc\":"); jb_str(a->b, a->ev->location);
+ jb_printf(a->b, ",\"allDay\":%s}", a->ev->allday ? "true" : "false");
+ }
+}
+
+/* Upcoming alarms of events and to-dos in [from, to): the SDK schedules them as notifications,
+ * like the Clock alarms, so they ring with the apps closed. */
+void pim_alarms_json(JBuf *b, int64_t from, int64_t to) {
+ pthread_mutex_lock(&G);
+ jb_raw(b, "{\"alarms\":[");
+ int count = 0;
+ for (int i = 0; i < ncolls; i++) {
+ Coll *c = colls[i];
+ if (c->kind != 'c' || c->hidden) continue;
+ for (int k = 0; k < c->n; k++) {
+ Item *it = &c->items[k];
+ if (it->dirty == DIRTY_DEL) continue;
+ for (int e = 0; e < it->nev; e++) {
+ IcEvent *ev = &it->ev[e];
+ if (ev->is_todo) {
+ if (ev->completed || !ev->due) continue;
+ /* a to-do with a due time and no alarm rings at the due time (all-day: 9:00) */
+ int64_t at = ev->due;
+ if (ev->due_allday) at += 9 * 3600;
+ IcEvent tmp = *ev;
+ int zero = 0;
+ if (!tmp.nalarms) { tmp.nalarms = 1; memcpy(tmp.alarms, &zero, sizeof zero); }
+ AlarmCtx ac = { b, &count, from, to, c, &tmp };
+ alarm_cb(&ac, at);
+ continue;
+ }
+ if (!ev->nalarms) continue;
+ AlarmCtx ac = { b, &count, from, to, c, ev };
+ /* occurrences that start up to a week after the window (alarms ring before) */
+ ical_expand(ev, from, to + 7 * 86400, 500, alarm_cb, &ac);
+ }
+ }
+ }
+ jb_raw(b, "]}");
+ pthread_mutex_unlock(&G);
+}
+
+void pim_autocomplete(const char *q, JBuf *b, int *count, int max) {
+ char fq[256];
+ search_fold(q, fq, sizeof fq);
+ size_t ql = strlen(fq);
+ if (!ql) return;
+ for (int i = 0; i < ncolls && *count < max; i++) {
+ Coll *c = colls[i];
+ if (c->kind != 'b') continue;
+ for (int k = 0; k < c->n && *count < max; k++) {
+ Item *it = &c->items[k];
+ if (!it->emails || it->dirty == DIRTY_DEL) continue;
+ char *dup = strdup(it->emails);
+ if (!dup) continue;
+ char *p = dup;
+ while (*p && *count < max) {
+ char *name = get_field(&p);
+ char *email = get_field(&p);
+ char *nl = strchr(p, '\n');
+ p = nl ? nl + 1 : p + strlen(p);
+ char fn[300], fe[300];
+ search_fold(name, fn, sizeof fn);
+ search_fold(email, fe, sizeof fe);
+ /* a word of the name or the address starts with the query */
+ int hit = !strncmp(fe, fq, ql);
+ for (char *w = fn; !hit && *w; ) { if (!strncmp(w, fq, ql)) hit = 1; while (*w && *w != ' ') w++; while (*w == ' ') w++; }
+ if (!hit) continue;
+ if (*count) jb_raw(b, ",");
+ jb_raw(b, "{\"name\":"); jb_str(b, name);
+ jb_raw(b, ",\"email\":"); jb_str(b, email);
+ jb_raw(b, ",\"src\":\"contacts\"}");
+ (*count)++;
+ }
+ free(dup);
+ }
+ }
+}
+
+int pim_has_event(const char *uid, char *cal, size_t cap, char *ps, size_t pcap, const char *me) {
+ for (int i = 0; i < ncolls; i++) {
+ Coll *c = colls[i];
+ if (c->kind != 'c') continue;
+ Item *it = item_get(c, uid);
+ if (!it || it->dirty == DIRTY_DEL) continue;
+ scopy(cal, cap, c->id);
+ if (pcap) ps[0] = 0;
+ for (int e = 0; e < it->nev; e++) for (int k = 0; k < it->ev[e].natt; k++) if (!strcasecmp(it->ev[e].att[k].email, me)) scopy(ps, pcap, it->ev[e].att[k].partstat);
+ return 1;
+ }
+ return 0;
+}
+
+static Coll *default_calendar(void) {
+ for (int i = 0; i < ncolls; i++) if (colls[i]->kind == 'c' && colls[i]->events && !colls[i]->hidden) return colls[i];
+ return NULL;
+}
+
+/* An invitation into a calendar, with my answer in it. */
+int pim_add_invite(const char *calid, const char *ics, size_t len, const char *partstat, const char *me, char *err, size_t ecap) {
+ IcEvent *ev;
+ char method[24];
+ int n = ical_events(ics, len, &ev, method, sizeof method);
+ if (n <= 0) { scopy(err, ecap, "bad invitation"); return -1; }
+ Coll *c = coll_get(calid);
+ if (!c || c->kind != 'c') {
+ /* an existing copy keeps its calendar */
+ for (int i = 0; i < ncolls && !c; i++) if (colls[i]->kind == 'c' && item_get(colls[i], ev[0].uid)) c = colls[i];
+ if (!c) c = default_calendar();
+ }
+ if (!c) { ical_events_free(ev, n); scopy(err, ecap, "no calendar"); return -1; }
+ IcEvent *e = &ev[0];
+ int found = 0;
+ for (int k = 0; k < e->natt; k++) if (!strcasecmp(e->att[k].email, me)) { scopy(e->att[k].partstat, sizeof e->att[k].partstat, partstat); found = 1; }
+ if (!found && e->natt < IC_MAX_ATT) {
+ IcAttendee *na = realloc(e->att, (size_t)(e->natt + 1) * sizeof *na);
+ if (na) { e->att = na; memset(&e->att[e->natt], 0, sizeof *e->att); scopy(e->att[e->natt].email, sizeof e->att[0].email, me); scopy(e->att[e->natt].partstat, sizeof e->att[0].partstat, partstat); e->natt++; }
+ }
+ IcBuild b = { 0 };
+ b.uid = e->uid; b.summary = e->summary; b.location = e->location; b.description = e->description; b.url = e->url;
+ b.start = e->start; b.end = e->end; b.allday = e->allday; b.tzid = e->tzid; b.rrule = e->rrule;
+ b.alarms = e->alarms; b.nalarms = e->nalarms; b.organizer = e->organizer; b.organizer_name = e->organizer_name;
+ b.att = e->att; b.natt = e->natt; b.sequence = e->sequence; b.exdate = e->exdate; b.nexdate = e->nexdate;
+ b.status = !strcmp(partstat, "TENTATIVE") ? "TENTATIVE" : "CONFIRMED";
+ if (!b.nalarms) { static const int def[] = { 15 }; b.alarms = def; b.nalarms = 1; }
+ size_t ol;
+ char *text = ical_build(&b, &ol);
+ int r = -1;
+ if (text) {
+ Item *it = item_get(c, e->uid);
+ if (!it) it = item_new(c, e->uid);
+ if (it) r = item_write(c, it, text, ol, 1);
+ free(text);
+ }
+ ical_events_free(ev, n);
+ if (!r) { push_soon(c); changed_event("events"); }
+ else scopy(err, ecap, "write");
+ return r;
+}
+
+/* ---- requests ---- */
+
+static int64_t ms_arg(const JVal *o, const char *k) { double v = json_num(o, k, 0); return (int64_t)(v / 1000); }
+
+static void reply_ok_id(uint32_t id, const char *uid) {
+ JBuf b;
+ jb_init(&b);
+ jb_raw(&b, "{\"ok\":true");
+ if (uid) { jb_raw(&b, ",\"uid\":"); jb_str(&b, uid); }
+ jb_raw(&b, "}");
+ reply_done(id, &b);
+}
+
+static int valid_color(const char *c) {
+ if (!c || c[0] != '#' || strlen(c) != 7) return 0;
+ for (int i = 1; i < 7; i++) if (!isxdigit((unsigned char)c[i])) return 0;
+ return 1;
+}
+
+static void save_event(uint32_t id, const JVal *args, int todo) {
+ Coll *c = coll_get(json_str(args, todo ? "list" : "cal"));
+ const JVal *e = json_get(args, todo ? "todo" : "event");
+ if (!c || c->kind != 'c' || !e || e->type != J_OBJ) { reply_err(id, "bad-args", ""); return; }
+ char uid[256];
+ const char *u = json_str(e, "uid");
+ if (u && *u && strlen(u) < 200) scopy(uid, sizeof uid, u); else new_uid(uid, sizeof uid);
+ /* moved from another calendar */
+ const char *from = json_str(args, "from");
+ Coll *fc = from && strcmp(from, c->id) ? coll_get(from) : NULL;
+ Item *old = item_get(fc ? fc : c, uid);
+ const IcEvent *prev = old && old->nev ? &old->ev[0] : NULL;
+ for (int i = 0; old && i < old->nev; i++) if (!old->ev[i].recurrence_id) prev = &old->ev[i];
+ IcBuild b = { 0 };
+ b.is_todo = todo;
+ b.uid = uid;
+ b.summary = json_str(e, "title");
+ b.location = json_str(e, "loc");
+ b.description = json_str(e, "notes");
+ b.url = json_str(e, "url");
+ b.allday = json_bool(e, "allDay", 0);
+ b.start = ms_arg(e, "start");
+ b.end = ms_arg(e, "end");
+ b.tzid = json_str(e, "tz");
+ if (!b.tzid && !b.allday) b.tzid = ic_local_zone();
+ const char *rr = json_str(e, "rrule");
+ b.rrule = rr && strlen(rr) < 400 ? rr : NULL;
+ int al[8], nal = 0;
+ const JVal *alarms = json_get(e, "alarms");
+ for (const JVal *x = alarms && alarms->type == J_ARR ? alarms->kid : NULL; x && nal < 8; x = x->next) if (x->type == J_NUM && x->num > -100000 && x->num < 1000000) al[nal++] = (int)x->num;
+ b.alarms = al;
+ b.nalarms = nal;
+ b.status = json_str(e, "status");
+ b.categories = json_str(e, "cats");
+ IcAttendee att[IC_MAX_ATT];
+ int natt = 0;
+ const JVal *atl = json_get(e, "att");
+ for (const JVal *x = atl && atl->type == J_ARR ? atl->kid : NULL; x && natt < IC_MAX_ATT; x = x->next) {
+ const char *em = json_str(x, "email");
+ if (!em || !strchr(em, '@') || strlen(em) > 250) continue;
+ memset(&att[natt], 0, sizeof att[natt]);
+ scopy(att[natt].email, sizeof att[0].email, em);
+ scopy(att[natt].name, sizeof att[0].name, json_str(x, "name"));
+ scopy(att[natt].partstat, sizeof att[0].partstat, json_str(x, "ps") ? json_str(x, "ps") : "NEEDS-ACTION");
+ att[natt].rsvp = 1;
+ natt++;
+ }
+ if (natt) { b.att = att; b.natt = natt; b.organizer = json_str(e, "orgEmail"); b.organizer_name = json_str(e, "orgName"); }
+ else if (prev) { b.att = prev->att; b.natt = prev->natt; b.organizer = prev->organizer; b.organizer_name = prev->organizer_name; }
+ b.sequence = prev ? prev->sequence + 1 : 0;
+ if (prev && !json_get(e, "exdate")) { b.exdate = prev->exdate; b.nexdate = prev->nexdate; }
+ if (todo) {
+ b.due = ms_arg(e, "due");
+ b.due_allday = json_bool(e, "dueAllDay", 0);
+ b.priority = (int)json_num(e, "prio", 0);
+ if (b.priority < 0 || b.priority > 9) b.priority = 0;
+ b.flagged = json_bool(e, "flag", 0);
+ b.completed = json_bool(e, "done", 0) ? (prev && prev->completed > 1 ? prev->completed : (int64_t)time(NULL)) : 0;
+ b.parent_uid = json_str(e, "parent");
+ b.start = 0;
+ } else if (b.end <= b.start) b.end = b.start + (b.allday ? 86400 : 3600);
+ size_t len;
+ char *text = ical_build(&b, &len);
+ if (!text) { reply_err(id, "memory", ""); return; }
+ if (fc && old) {
+ /* move: delete from the old calendar */
+ if (fc->acct[0] && old->href[0]) { old->dirty = DIRTY_DEL; save_meta(fc); push_soon(fc); }
+ else { item_delete(fc, old); save_meta(fc); }
+ old = NULL;
+ }
+ Item *it = item_get(c, uid);
+ if (!it) it = item_new(c, uid);
+ int r = it ? item_write(c, it, text, len, 1) : -1;
+ free(text);
+ if (r) { reply_err(id, "write", ""); return; }
+ push_soon(c);
+ changed_event(todo ? "todos" : "events");
+ reply_ok_id(id, uid);
+}
+
+static void delete_event(uint32_t id, const JVal *args, int todo) {
+ Coll *c = coll_get(json_str(args, todo ? "list" : "cal"));
+ Item *it = c ? item_get(c, json_str(args, "uid")) : NULL;
+ if (!it) { reply_err(id, "not-found", ""); return; }
+ int64_t occ = ms_arg(args, "occ");
+ if (!todo && occ && it->nev && it->ev[0].rrule[0] && !json_bool(args, "all", 0)) {
+ /* one occurrence of a series: EXDATE */
+ IcEvent *e = NULL;
+ for (int i = 0; i < it->nev; i++) if (!it->ev[i].recurrence_id) e = &it->ev[i];
+ if (!e || e->nexdate >= 64) { reply_err(id, "too-many-exceptions", ""); return; }
+ int64_t ex[64];
+ memcpy(ex, e->exdate, sizeof ex);
+ int nex = e->nexdate;
+ ex[nex++] = occ;
+ IcBuild b = { 0 };
+ b.uid = e->uid; b.summary = e->summary; b.location = e->location; b.description = e->description; b.url = e->url;
+ b.start = e->start; b.end = e->end; b.allday = e->allday; b.tzid = e->tzid; b.rrule = e->rrule; b.status = e->status;
+ b.alarms = e->alarms; b.nalarms = e->nalarms; b.organizer = e->organizer; b.organizer_name = e->organizer_name;
+ b.att = e->att; b.natt = e->natt; b.sequence = e->sequence + 1; b.exdate = ex; b.nexdate = nex;
+ size_t len;
+ char *text = ical_build(&b, &len);
+ int r = text ? item_write(c, it, text, len, 1) : -1;
+ free(text);
+ if (r) { reply_err(id, "write", ""); return; }
+ } else if (c->acct[0] && it->href[0]) { it->dirty = DIRTY_DEL; save_meta(c); }
+ else { item_delete(c, it); save_meta(c); }
+ push_soon(c);
+ changed_event(todo ? "todos" : "events");
+ reply_ok_id(id, NULL);
+}
+
+static void contacts_json(JBuf *b, const char *book) {
+ jb_raw(b, "{\"contacts\":[");
+ int n = 0;
+ for (int i = 0; i < ncolls; i++) {
+ Coll *c = colls[i];
+ if (c->kind != 'b' || (book && *book && strcmp(book, c->id))) continue;
+ for (int k = 0; k < c->n; k++) {
+ Item *it = &c->items[k];
+ if (!it->json || it->dirty == DIRTY_DEL) continue;
+ if (n++) jb_raw(b, ",");
+ size_t l = strlen(it->json);
+ if (l > 1 && it->json[l - 1] == '}') {
+ JBuf tmp;
+ jb_init(&tmp);
+ jb_raw(&tmp, it->json);
+ tmp.p[tmp.n - 1] = 0;
+ jb_raw(b, tmp.p);
+ jb_free(&tmp);
+ jb_raw(b, ",\"book\":"); jb_str(b, c->id);
+ jb_raw(b, "}");
+ } else jb_raw(b, "{}");
+ }
+ }
+ jb_raw(b, "]}");
+}
+
+static void save_contact(uint32_t id, const JVal *args, int *fds, int nfds) {
+ Coll *c = coll_get(json_str(args, "book"));
+ const JVal *ct = json_get(args, "contact");
+ if (!c || c->kind != 'b' || !ct || ct->type != J_OBJ) { reply_err(id, "bad-args", ""); return; }
+ char uid[256];
+ const char *u = json_str(ct, "uid");
+ if (u && *u && strlen(u) < 200) scopy(uid, sizeof uid, u); else new_uid(uid, sizeof uid);
+ /* JSON with the uid set (vcard_build reads it from the object) */
+ JBuf cj;
+ jb_init(&cj);
+ {
+ /* rebuild the object with our uid: copy the members except uid */
+ jb_raw(&cj, "{\"uid\":");
+ jb_str(&cj, uid);
+ jb_raw(&cj, "}");
+ }
+ JDoc ud;
+ if (cj.oom || json_parse(cj.p, cj.n, &ud, NULL, 0)) { jb_free(&cj); reply_err(id, "memory", ""); return; }
+ /* photo: keep the old one, a new picture (fd), or none */
+ const char *ph = json_str(args, "photo");
+ unsigned char *photo = NULL;
+ size_t plen = 0;
+ Item *old = item_get(c, uid);
+ if (ph && !strcmp(ph, "new") && nfds > 0) {
+ char buf[1];
+ (void)buf;
+ size_t n = 0;
+ off_t sz = lseek(fds[0], 0, SEEK_END);
+ if (sz > 0 && sz < (off_t)(32 << 20)) {
+ unsigned char *raw = malloc((size_t)sz);
+ if (raw && pread(fds[0], raw, (size_t)sz, 0) == sz) n = (size_t)sz;
+ if (n) photo = img_thumb_jpeg(raw, n, 320, &plen);
+ free(raw);
+ }
+ if (!photo) { json_free(&ud); jb_free(&cj); reply_err(id, "photo", "unreadable image"); return; }
+ } else if ((!ph || !strcmp(ph, "keep")) && old) {
+ char rel[200];
+ coll_dir(c, old->file, rel, sizeof rel);
+ size_t tl;
+ char *t = fs_read(rel, &tl, 16 << 20);
+ if (t) { photo = vcard_photo(t, tl, &plen); free(t); }
+ }
+ /* vcard_build takes the members from `ct` but the uid from ours: patch through a copy */
+ JVal tmp = *ct;
+ JVal uidv = *json_get(ud.root, "uid");
+ uidv.next = (JVal *)ct->kid;
+ uidv.key = "uid";
+ tmp.kid = &uidv; /* json_get finds our "uid" first */
+ size_t vl;
+ char *v = vcard_build(&tmp, photo, plen, "jpeg", &vl);
+ free(photo);
+ json_free(&ud);
+ jb_free(&cj);
+ if (!v) { reply_err(id, "memory", ""); return; }
+ Item *it = old ? old : item_new(c, uid);
+ int r = it ? item_write(c, it, v, vl, 1) : -1;
+ free(v);
+ if (r) { reply_err(id, "write", ""); return; }
+ push_soon(c);
+ changed_event("contacts");
+ reply_ok_id(id, uid);
+}
+
+static void import_contacts(uint32_t id, const JVal *args, int *fds, int nfds) {
+ Coll *c = coll_get(json_str(args, "book"));
+ if (!c || c->kind != 'b' || nfds < 1) { reply_err(id, "bad-args", ""); return; }
+ off_t sz = lseek(fds[0], 0, SEEK_END);
+ if (sz <= 0 || sz > (off_t)(64 << 20)) { reply_err(id, "too-big", ""); return; }
+ char *t = malloc((size_t)sz + 1);
+ if (!t || pread(fds[0], t, (size_t)sz, 0) != sz) { free(t); reply_err(id, "read", ""); return; }
+ t[sz] = 0;
+ /* one item per VCARD */
+ int added = 0;
+ const char *p = t;
+ while ((p = strcasestr(p, "BEGIN:VCARD"))) {
+ const char *e = strcasestr(p, "END:VCARD");
+ if (!e) break;
+ e += 9;
+ size_t len = (size_t)(e - p);
+ char uid[256];
+ vcard_uid(p, len, uid, sizeof uid);
+ int fresh = !uid[0];
+ if (fresh) new_uid(uid, sizeof uid);
+ Item *it = item_get(c, uid);
+ if (!it) it = item_new(c, uid);
+ if (it) {
+ if (fresh) {
+ /* add a UID line after BEGIN:VCARD */
+ JBuf nb;
+ jb_init(&nb);
+ const char *after = strchr(p, '\n');
+ if (after) { jb_strn(&nb, "", 0); nb.n = 0; char *head = strndup(p, (size_t)(after - p + 1)); if (head) { jb_raw(&nb, head); free(head); } jb_printf(&nb, "UID:%s\r\n", uid); char *rest = strndup(after + 1, (size_t)(e - after - 1)); if (rest) { jb_raw(&nb, rest); free(rest); } }
+ if (!nb.oom && nb.p) item_write(c, it, nb.p, nb.n, 1);
+ jb_free(&nb);
+ } else item_write(c, it, p, len, 1);
+ added++;
+ }
+ p = e;
+ }
+ free(t);
+ push_soon(c);
+ changed_event("contacts");
+ JBuf b;
+ jb_init(&b);
+ jb_printf(&b, "{\"ok\":true,\"added\":%d}", added);
+ reply_done(id, &b);
+}
+
+void pim_handle(uint32_t id, const char *op, const JVal *args, int *fds, int nfds) {
+ JBuf b;
+ jb_init(&b);
+ pthread_mutex_lock(&G);
+ if (!strcmp(op, "cal-list") || !strcmp(op, "book-list")) {
+ char kind = op[0] == 'c' ? 'c' : 'b';
+ jb_raw(&b, kind == 'c' ? "{\"cals\":[" : "{\"books\":[");
+ int n = 0;
+ for (int i = 0; i < ncolls; i++) if (colls[i]->kind == kind) { if (n++) jb_raw(&b, ","); coll_json(&b, colls[i]); }
+ jb_raw(&b, "]}");
+ pthread_mutex_unlock(&G);
+ reply_done(id, &b);
+ return;
+ }
+ if (!strcmp(op, "cal-create") || !strcmp(op, "book-create")) {
+ const char *name = json_str(args, "name"), *color = json_str(args, "color");
+ if (!name || !*name || strlen(name) > 150) { pthread_mutex_unlock(&G); reply_err(id, "bad-name", ""); return; }
+ char cid[80], u[40];
+ new_uid(u, sizeof u);
+ snprintf(cid, sizeof cid, "local-%.8s", u);
+ Coll *c = coll_new(cid, op[0] == 'c' ? 'c' : 'b', "", name, valid_color(color) ? color : "#30d158");
+ if (c && op[0] == 'c') { c->todos = json_bool(args, "todos", 0); c->events = json_bool(args, "events", !c->todos); }
+ save_colls();
+ pthread_mutex_unlock(&G);
+ if (!c) { reply_err(id, "full", ""); return; }
+ changed_event("colls");
+ reply_ok_id(id, cid);
+ return;
+ }
+ if (!strcmp(op, "cal-update") || !strcmp(op, "book-update")) {
+ Coll *c = coll_get(json_str(args, "id"));
+ if (!c) { pthread_mutex_unlock(&G); reply_err(id, "not-found", ""); return; }
+ const char *name = json_str(args, "name"), *color = json_str(args, "color");
+ if (name && *name && strlen(name) <= 150) scopy(c->name, sizeof c->name, name);
+ if (valid_color(color)) scopy(c->color, sizeof c->color, color);
+ if (json_get(args, "hidden")) c->hidden = json_bool(args, "hidden", 0);
+ save_colls();
+ pthread_mutex_unlock(&G);
+ changed_event("colls");
+ reply_ok_id(id, NULL);
+ return;
+ }
+ if (!strcmp(op, "cal-delete") || !strcmp(op, "book-delete")) {
+ Coll *c = coll_get(json_str(args, "id"));
+ if (!c || c->acct[0]) { pthread_mutex_unlock(&G); reply_err(id, c ? "synced" : "not-found", "remove the account to remove its calendars"); return; }
+ coll_remove(c);
+ save_colls();
+ pthread_mutex_unlock(&G);
+ changed_event("colls");
+ reply_ok_id(id, NULL);
+ return;
+ }
+ if (!strcmp(op, "ev-list")) {
+ events_json(&b, ms_arg(args, "from"), ms_arg(args, "to"), json_get(args, "cals"));
+ pthread_mutex_unlock(&G);
+ reply_done(id, &b);
+ return;
+ }
+ if (!strcmp(op, "todo-list")) {
+ todos_json(&b, json_get(args, "lists"));
+ pthread_mutex_unlock(&G);
+ reply_done(id, &b);
+ return;
+ }
+ if (!strcmp(op, "ev-save") || !strcmp(op, "todo-save")) { save_event(id, args, op[0] == 't'); pthread_mutex_unlock(&G); jb_free(&b); return; }
+ if (!strcmp(op, "ev-delete") || !strcmp(op, "todo-delete")) { delete_event(id, args, op[0] == 't'); pthread_mutex_unlock(&G); jb_free(&b); return; }
+ if (!strcmp(op, "ev-import")) {
+ /* an .ics file (fd) into a calendar */
+ Coll *c = coll_get(json_str(args, "cal"));
+ if (!c) c = default_calendar();
+ off_t sz = nfds > 0 ? lseek(fds[0], 0, SEEK_END) : -1;
+ char *t = sz > 0 && sz < (off_t)(32 << 20) ? malloc((size_t)sz + 1) : NULL;
+ int added = 0;
+ if (c && t && pread(fds[0], t, (size_t)sz, 0) == sz) {
+ t[sz] = 0;
+ IcEvent *ev;
+ char method[24];
+ int n = ical_events(t, (size_t)sz, &ev, method, sizeof method);
+ for (int i = 0; i < n; i++) {
+ IcEvent *e = &ev[i];
+ if (e->recurrence_id) continue;
+ IcBuild bb = { 0 };
+ bb.is_todo = e->is_todo; bb.uid = e->uid[0] ? e->uid : NULL; bb.summary = e->summary; bb.location = e->location; bb.description = e->description;
+ bb.start = e->start; bb.end = e->end; bb.allday = e->allday; bb.tzid = e->tzid; bb.rrule = e->rrule; bb.alarms = e->alarms; bb.nalarms = e->nalarms;
+ bb.due = e->due; bb.due_allday = e->due_allday; bb.priority = e->priority; bb.completed = e->completed; bb.flagged = e->flagged;
+ bb.organizer = e->organizer; bb.organizer_name = e->organizer_name; bb.att = e->att; bb.natt = e->natt; bb.sequence = e->sequence;
+ char uid[256];
+ if (!bb.uid) { new_uid(uid, sizeof uid); bb.uid = uid; }
+ size_t ol;
+ char *text = ical_build(&bb, &ol);
+ if (!text) continue;
+ Item *it = item_get(c, bb.uid);
+ if (!it) it = item_new(c, bb.uid);
+ if (it && !item_write(c, it, text, ol, 1)) added++;
+ free(text);
+ }
+ if (n > 0) ical_events_free(ev, n);
+ }
+ free(t);
+ pthread_mutex_unlock(&G);
+ if (c) push_soon(c);
+ changed_event("events");
+ jb_printf(&b, "{\"ok\":true,\"added\":%d}", added);
+ reply_done(id, &b);
+ return;
+ }
+ if (!strcmp(op, "contact-list")) {
+ contacts_json(&b, json_str(args, "book"));
+ pthread_mutex_unlock(&G);
+ reply_done(id, &b);
+ return;
+ }
+ if (!strcmp(op, "contact-save")) { save_contact(id, args, fds, nfds); pthread_mutex_unlock(&G); jb_free(&b); return; }
+ if (!strcmp(op, "contact-import")) { import_contacts(id, args, fds, nfds); pthread_mutex_unlock(&G); jb_free(&b); return; }
+ if (!strcmp(op, "contact-delete")) {
+ Coll *c = coll_get(json_str(args, "book"));
+ Item *it = c ? item_get(c, json_str(args, "uid")) : NULL;
+ if (!it) { pthread_mutex_unlock(&G); reply_err(id, "not-found", ""); return; }
+ if (c->acct[0] && it->href[0]) { it->dirty = DIRTY_DEL; save_meta(c); }
+ else { item_delete(c, it); save_meta(c); }
+ push_soon(c);
+ pthread_mutex_unlock(&G);
+ changed_event("contacts");
+ reply_ok_id(id, NULL);
+ return;
+ }
+ if (!strcmp(op, "contact-photo")) {
+ Coll *c = coll_get(json_str(args, "book"));
+ Item *it = c ? item_get(c, json_str(args, "uid")) : NULL;
+ char rel[200] = "";
+ if (it) coll_dir(c, it->file, rel, sizeof rel);
+ pthread_mutex_unlock(&G);
+ if (!rel[0]) { reply_err(id, "not-found", ""); return; }
+ size_t tl, pl;
+ char *t = fs_read(rel, &tl, 16 << 20);
+ unsigned char *ph = t ? vcard_photo(t, tl, &pl) : NULL;
+ free(t);
+ int size = (int)json_num(args, "size", 128);
+ if (size < 16 || size > 1024) size = 128;
+ int w, h;
+ uint32_t *px = ph ? img_decode(ph, pl, size, size, &w, &h) : NULL;
+ free(ph);
+ if (!px) { reply_err(id, "no-photo", ""); return; }
+ reply_image(id, px, w, h);
+ free(px);
+ jb_free(&b);
+ return;
+ }
+ pthread_mutex_unlock(&G);
+ jb_free(&b);
+ reply_err(id, "unknown-op", op);
+}
+
+/* ---- CalDAV / CardDAV sync ---- */
+
+typedef struct { char href[1024], etag[256], name[200], color[16], ctag[256]; int cal, book, vevent, vtodo, ok; char *data; } DavItem;
+
+static int status_ok(const MxNode *propstat) {
+ char st[64];
+ mx_child_text(propstat, MX_NS_DAV, "status", st, sizeof st);
+ return !st[0] || strstr(st, " 200") != NULL;
+}
+
+/* Every <response> of a multistatus, with the 200 props flattened into a DavItem. */
+static int parse_multistatus(const char *body, size_t len, DavItem **out, int with_data) {
+ *out = NULL;
+ const char *err;
+ MxNode *root = mx_parse(body, len, &err);
+ if (!root) { dbg("DAV XML: %s", err); return -1; }
+ int n = 0, cap = 0;
+ DavItem *items = NULL;
+ for (MxNode *r = mx_child(root, MX_NS_DAV, "response"); r; r = mx_next(r, MX_NS_DAV, "response")) {
+ if (n == cap) { cap = cap ? cap * 2 : 32; DavItem *ni = realloc(items, (size_t)cap * sizeof *ni); if (!ni) break; items = ni; }
+ DavItem *it = &items[n];
+ memset(it, 0, sizeof *it);
+ mx_child_text(r, MX_NS_DAV, "href", it->href, sizeof it->href);
+ if (!it->href[0]) continue;
+ for (MxNode *ps = mx_child(r, MX_NS_DAV, "propstat"); ps; ps = mx_next(ps, MX_NS_DAV, "propstat")) {
+ if (!status_ok(ps)) continue;
+ MxNode *p = mx_child(ps, MX_NS_DAV, "prop");
+ if (!p) continue;
+ it->ok = 1;
+ char t[1024];
+ mx_child_text(p, MX_NS_DAV, "getetag", t, sizeof t);
+ if (t[0]) scopy(it->etag, sizeof it->etag, t);
+ mx_child_text(p, MX_NS_DAV, "displayname", t, sizeof t);
+ if (t[0]) scopy(it->name, sizeof it->name, t);
+ mx_child_text(p, MX_NS_APPLE, "calendar-color", t, sizeof t);
+ if (t[0] == '#' && strlen(t) >= 7) { t[7] = 0; scopy(it->color, sizeof it->color, t); }
+ mx_child_text(p, MX_NS_CS, "getctag", t, sizeof t);
+ if (t[0]) scopy(it->ctag, sizeof it->ctag, t);
+ else { mx_child_text(p, MX_NS_DAV, "sync-token", t, sizeof t); if (t[0]) scopy(it->ctag, sizeof it->ctag, t); }
+ MxNode *rt = mx_child(p, MX_NS_DAV, "resourcetype");
+ if (rt && mx_child(rt, MX_NS_CAL, "calendar")) it->cal = 1;
+ if (rt && mx_child(rt, MX_NS_CARD, "addressbook")) it->book = 1;
+ MxNode *comps = mx_child(p, MX_NS_CAL, "supported-calendar-component-set");
+ if (comps) {
+ /* the component names are attributes, which our reader skips: look at the raw text */
+ it->vevent = it->vtodo = 0;
+ }
+ MxNode *home = mx_child(p, MX_NS_DAV, "current-user-principal");
+ if (home) { MxNode *h = mx_child(home, MX_NS_DAV, "href"); if (h) scopy(it->name, sizeof it->name, mx_text(h)); }
+ MxNode *ch = mx_child(p, MX_NS_CAL, "calendar-home-set");
+ if (ch) { MxNode *h = mx_child(ch, MX_NS_DAV, "href"); if (h) scopy(it->color, sizeof it->color, ""), scopy(it->ctag, sizeof it->ctag, mx_text(h)); }
+ MxNode *ah = mx_child(p, MX_NS_CARD, "addressbook-home-set");
+ if (ah) { MxNode *h = mx_child(ah, MX_NS_DAV, "href"); if (h) scopy(it->etag, sizeof it->etag, mx_text(h)); }
+ if (with_data) {
+ MxNode *d = mx_child(p, MX_NS_CAL, "calendar-data");
+ if (!d) d = mx_child(p, MX_NS_CARD, "address-data");
+ if (d && d->text) it->data = strndup(d->text, d->tlen);
+ }
+ }
+ n++;
+ }
+ mx_free(root);
+ *out = items;
+ return n;
+}
+
+static void free_items(DavItem *it, int n) { for (int i = 0; i < n; i++) free(it[i].data); free(it); }
+
+/* supported components: the attribute names are not kept by our XML reader, so look at the
+ * raw response for this collection's block */
+static void comps_from_raw(const char *body, const char *href, int *vevent, int *vtodo) {
+ *vevent = 1; *vtodo = 1;
+ const char *h = strstr(body, href);
+ if (!h) return;
+ const char *end = strstr(h, "response>");
+ const char *set = strstr(h, "supported-calendar-component-set");
+ if (!set || (end && set > end)) return;
+ const char *close = strstr(set + 10, "supported-calendar-component-set");
+ if (!close) return;
+ size_t n = (size_t)(close - set);
+ char *blk = strndup(set, n);
+ if (!blk) return;
+ *vevent = strstr(blk, "VEVENT") != NULL;
+ *vtodo = strstr(blk, "VTODO") != NULL;
+ free(blk);
+}
+
+static const char *PF_HOMES =
+ "<?xml version=\"1.0\" encoding=\"utf-8\"?><d:propfind xmlns:d=\"DAV:\" xmlns:c=\"urn:ietf:params:xml:ns:caldav\" "
+ "xmlns:card=\"urn:ietf:params:xml:ns:carddav\"><d:prop><d:current-user-principal/><c:calendar-home-set/><card:addressbook-home-set/>"
+ "<d:resourcetype/></d:prop></d:propfind>";
+static const char *PF_COLLS =
+ "<?xml version=\"1.0\" encoding=\"utf-8\"?><d:propfind xmlns:d=\"DAV:\" xmlns:c=\"urn:ietf:params:xml:ns:caldav\" "
+ "xmlns:cs=\"http://calendarserver.org/ns/\" xmlns:x=\"http://apple.com/ns/ical/\"><d:prop><d:displayname/><d:resourcetype/>"
+ "<x:calendar-color/><c:supported-calendar-component-set/><cs:getctag/><d:sync-token/></d:prop></d:propfind>";
+static const char *PF_ETAGS =
+ "<?xml version=\"1.0\" encoding=\"utf-8\"?><d:propfind xmlns:d=\"DAV:\"><d:prop><d:getetag/></d:prop></d:propfind>";
+
+static void sync_failed(Account *a, Dav *d, const char *what) {
+ if (d->auth_failed) {
+ pthread_mutex_lock(&G);
+ if (a->password) { explicit_bzero(a->password, strlen(a->password)); free(a->password); a->password = NULL; }
+ pthread_mutex_unlock(&G);
+ JBuf b;
+ jb_init(&b);
+ jb_raw(&b, "{\"ev\":\"auth-failed\",\"acct\":"); jb_str(&b, a->id); jb_raw(&b, "}");
+ send_event(&b);
+ acct_status(a, "auth", "wrong password");
+ } else acct_status(a, !strcmp(d->err, "cert") ? "cert" : "offline", d->err[0] ? d->err : what);
+}
+
+/* Finds the calendar and address book homes. 0 ok. */
+static int discover(Dav *d, Account *a, char *calhome, char *cardhome, size_t cap) {
+ calhome[0] = cardhome[0] = 0;
+ int tls, port;
+ char host[256], path[1024];
+ if (http_split_url(a->url, &tls, host, sizeof host, &port, path, sizeof path)) return -1;
+ char target[1100];
+ scopy(target, sizeof target, path);
+ char principal[1024] = "";
+ for (int step = 0; step < 3; step++) {
+ HttpResp r;
+ if (dav_req(d, "PROPFIND", target, 0, PF_HOMES, "application/xml; charset=utf-8", NULL, &r)) return -1;
+ if (r.status == 401) { http_resp_free(&r); return -1; }
+ if (r.status == 404 && step == 0 && strcmp(target, "/.well-known/caldav")) {
+ http_resp_free(&r);
+ scopy(target, sizeof target, "/.well-known/caldav");
+ continue;
+ }
+ if (r.status != 207) { snprintf(d->err, sizeof d->err, "PROPFIND %d", r.status); http_resp_free(&r); return -1; }
+ DavItem *it;
+ int n = parse_multistatus(r.body, r.blen, &it, 0);
+ int is_coll = 0;
+ for (int i = 0; i < n; i++) {
+ if (it[i].ctag[0] && it[i].ctag[0] == '/') scopy(calhome, cap, it[i].ctag);
+ if (it[i].etag[0] == '/') scopy(cardhome, cap, it[i].etag);
+ if (it[i].name[0] == '/' && !principal[0]) scopy(principal, sizeof principal, it[i].name);
+ if (it[i].cal || it[i].book) is_coll = 1;
+ }
+ if (n > 0) free_items(it, n);
+ http_resp_free(&r);
+ if (calhome[0] || cardhome[0]) return 0;
+ if (is_coll) { scopy(calhome, cap, target); scopy(cardhome, cap, target); return 0; }
+ if (principal[0] && strcmp(principal, target)) { scopy(target, sizeof target, principal); continue; }
+ break;
+ }
+ /* nothing advertised: treat the URL itself as the home */
+ scopy(calhome, cap, path);
+ scopy(cardhome, cap, path);
+ return 0;
+}
+
+typedef struct { char href[1024], etag[256], file[64], uid[256]; int dirty; } PushItem;
+
+static void push_changes(Dav *d, Coll *c) {
+ pthread_mutex_lock(&G);
+ int n = 0;
+ PushItem *list = malloc(sizeof *list * (size_t)(c->n ? c->n : 1));
+ for (int i = 0; list && i < c->n; i++) if (c->items[i].dirty) {
+ PushItem *p = &list[n++];
+ scopy(p->href, sizeof p->href, c->items[i].href);
+ scopy(p->etag, sizeof p->etag, c->items[i].etag);
+ scopy(p->file, sizeof p->file, c->items[i].file);
+ scopy(p->uid, sizeof p->uid, c->items[i].uid);
+ p->dirty = c->items[i].dirty;
+ }
+ char cid[80];
+ scopy(cid, sizeof cid, c->id);
+ pthread_mutex_unlock(&G);
+ for (int i = 0; i < n; i++) {
+ PushItem *p = &list[i];
+ char hdr[400] = "";
+ if (p->etag[0]) snprintf(hdr, sizeof hdr, "If-Match: %s\r\n", p->etag);
+ else if (p->dirty == DIRTY_PUT) snprintf(hdr, sizeof hdr, "If-None-Match: *\r\n");
+ HttpResp r;
+ int rc;
+ if (p->dirty == DIRTY_DEL) rc = dav_req(d, "DELETE", p->href, -1, NULL, NULL, hdr, &r);
+ else {
+ char rel[200];
+ snprintf(rel, sizeof rel, "pim/%s/%s", cid, p->file);
+ size_t tl;
+ char *t = fs_read(rel, &tl, 16 << 20);
+ if (!t) continue;
+ rc = dav_req(d, "PUT", p->href, -1, t, c->kind == 'c' ? "text/calendar; charset=utf-8" : "text/vcard; charset=utf-8", hdr, &r);
+ free(t);
+ }
+ if (rc) break;
+ int ok = r.status >= 200 && r.status < 300;
+ int gone = r.status == 404 || r.status == 410;
+ int conflict = r.status == 412;
+ pthread_mutex_lock(&G);
+ Coll *cc = coll_get(cid);
+ Item *it = cc ? item_get(cc, p->uid) : NULL;
+ if (it && it->dirty == p->dirty) {
+ if (p->dirty == DIRTY_DEL && (ok || gone)) item_delete(cc, it);
+ else if (ok) { it->dirty = CLEAN; scopy(it->etag, sizeof it->etag, r.etag); }
+ else if (conflict) { it->dirty = CLEAN; it->etag[0] = 0; } /* the server's version wins; refetched below */
+ else dbg("DAV %s %s: %d", p->dirty == DIRTY_DEL ? "DELETE" : "PUT", p->href, r.status);
+ save_meta(cc);
+ }
+ pthread_mutex_unlock(&G);
+ http_resp_free(&r);
+ }
+ free(list);
+}
+
+static void escape_href(JBuf *b, const char *h) {
+ char e[2200];
+ mx_escape(e, sizeof e, h);
+ jb_raw(b, e);
+}
+
+static void fetch_changed(Dav *d, Coll *c) {
+ char href[1024], cid[80];
+ pthread_mutex_lock(&G);
+ scopy(href, sizeof href, c->href);
+ scopy(cid, sizeof cid, c->id);
+ char kind = c->kind;
+ pthread_mutex_unlock(&G);
+ HttpResp r;
+ if (dav_req(d, "PROPFIND", href, 1, PF_ETAGS, "application/xml; charset=utf-8", NULL, &r)) return;
+ if (r.status != 207) { http_resp_free(&r); return; }
+ DavItem *list;
+ int n = parse_multistatus(r.body, r.blen, &list, 0);
+ http_resp_free(&r);
+ if (n < 0) return;
+ /* what to download; what disappeared */
+ char **want = malloc(sizeof *want * (size_t)(n ? n : 1));
+ int nw = 0;
+ pthread_mutex_lock(&G);
+ Coll *cc = coll_get(cid);
+ if (!cc) { pthread_mutex_unlock(&G); free(want); free_items(list, n); return; }
+ for (int i = 0; i < n && want; i++) {
+ const char *h = list[i].href;
+ size_t hl = strlen(h);
+ if (!strcmp(h, href) || (hl && h[hl - 1] == '/')) continue; /* the collection itself */
+ Item *it = item_by_href(cc, h);
+ if (it && it->dirty) continue;
+ if (!it || strcmp(it->etag, list[i].etag)) want[nw++] = list[i].href;
+ }
+ for (int i = cc->n - 1; i >= 0; i--) {
+ Item *it = &cc->items[i];
+ if (it->dirty || !it->href[0]) continue;
+ int found = 0;
+ for (int k = 0; k < n && !found; k++) if (!strcmp(list[k].href, it->href)) found = 1;
+ if (!found) item_delete(cc, it);
+ }
+ save_meta(cc);
+ pthread_mutex_unlock(&G);
+ for (int off = 0; off < nw; off += 50) {
+ JBuf q;
+ jb_init(&q);
+ if (kind == 'c') jb_raw(&q, "<?xml version=\"1.0\" encoding=\"utf-8\"?><c:calendar-multiget xmlns:d=\"DAV:\" xmlns:c=\"urn:ietf:params:xml:ns:caldav\"><d:prop><d:getetag/><c:calendar-data/></d:prop>");
+ else jb_raw(&q, "<?xml version=\"1.0\" encoding=\"utf-8\"?><card:addressbook-multiget xmlns:d=\"DAV:\" xmlns:card=\"urn:ietf:params:xml:ns:carddav\"><d:prop><d:getetag/><card:address-data/></d:prop>");
+ for (int i = off; i < nw && i < off + 50; i++) { jb_raw(&q, "<d:href>"); escape_href(&q, want[i]); jb_raw(&q, "</d:href>"); }
+ jb_raw(&q, kind == 'c' ? "</c:calendar-multiget>" : "</card:addressbook-multiget>");
+ if (q.oom) { jb_free(&q); break; }
+ HttpResp mr;
+ int rc = dav_req(d, "REPORT", href, 1, q.p, "application/xml; charset=utf-8", NULL, &mr);
+ jb_free(&q);
+ if (rc) break;
+ if (mr.status != 207) { http_resp_free(&mr); break; }
+ DavItem *got;
+ int ng = parse_multistatus(mr.body, mr.blen, &got, 1);
+ http_resp_free(&mr);
+ pthread_mutex_lock(&G);
+ cc = coll_get(cid);
+ for (int i = 0; cc && i < ng; i++) {
+ if (!got[i].data) continue;
+ size_t dl = strlen(got[i].data);
+ char uid[256] = "";
+ if (kind == 'b') vcard_uid(got[i].data, dl, uid, sizeof uid);
+ else { IcEvent *ev; char m[24]; int ne = ical_events(got[i].data, dl, &ev, m, sizeof m); if (ne > 0) { scopy(uid, sizeof uid, ev[0].uid); ical_events_free(ev, ne); } }
+ if (!uid[0]) scopy(uid, sizeof uid, got[i].href);
+ Item *it = item_by_href(cc, got[i].href);
+ if (!it) it = item_get(cc, uid);
+ if (!it) it = item_new(cc, uid);
+ if (!it) continue;
+ scopy(it->href, sizeof it->href, got[i].href);
+ scopy(it->etag, sizeof it->etag, got[i].etag);
+ if (item_write(cc, it, got[i].data, dl, 0)) item_delete(cc, it);
+ }
+ if (cc) save_meta(cc);
+ pthread_mutex_unlock(&G);
+ if (ng > 0) free_items(got, ng);
+ }
+ free(want);
+ free_items(list, n);
+}
+
+void pim_dav_sync(Account *a) {
+ Dav d;
+ int r = dav_begin(&d, a);
+ if (r == -2) {
+ if (!a->need_auth_sent) {
+ a->need_auth_sent = 1;
+ JBuf b;
+ jb_init(&b);
+ jb_raw(&b, "{\"ev\":\"need-auth\",\"acct\":"); jb_str(&b, a->id);
+ jb_raw(&b, ",\"user\":"); jb_str(&b, a->user);
+ jb_raw(&b, "}");
+ send_event(&b);
+ }
+ acct_status(a, "auth", "no password");
+ dav_end(&d);
+ return;
+ }
+ if (r) { sync_failed(a, &d, "connect"); dav_end(&d); return; }
+ char calhome[1024], cardhome[1024];
+ if (discover(&d, a, calhome, cardhome, sizeof calhome)) { sync_failed(a, &d, "discovery"); dav_end(&d); return; }
+ pthread_mutex_lock(&G);
+ for (int i = 0; i < ncolls; i++) if (!strcmp(colls[i]->acct, a->id)) colls[i]->seen = 0;
+ pthread_mutex_unlock(&G);
+ int listed[2] = { 0, 0 };
+ for (int pass = 0; pass < 2; pass++) {
+ const char *home = pass ? cardhome : calhome;
+ if ((pass == 0 && !a->cal) || (pass == 1 && !a->card) || !home[0]) continue;
+ HttpResp hr;
+ if (dav_req(&d, "PROPFIND", home, 1, PF_COLLS, "application/xml; charset=utf-8", NULL, &hr)) { sync_failed(a, &d, "list"); dav_end(&d); return; }
+ if (hr.status != 207) { http_resp_free(&hr); continue; }
+ DavItem *it;
+ int n = parse_multistatus(hr.body, hr.blen, &it, 0);
+ listed[pass] = 1;
+ pthread_mutex_lock(&G);
+ for (int i = 0; i < n; i++) {
+ if (pass == 0 ? !it[i].cal : !it[i].book) continue;
+ char h[17], cid[80];
+ fs_hash(it[i].href, h);
+ snprintf(cid, sizeof cid, "%s-%s", a->id, h);
+ Coll *c = coll_get(cid);
+ int ve = 1, vt = 1;
+ if (pass == 0) comps_from_raw(hr.body, it[i].href, &ve, &vt);
+ if (!c) {
+ c = coll_new(cid, pass == 0 ? 'c' : 'b', a->id, it[i].name[0] ? it[i].name : (pass ? "Contacts" : "Calendar"), it[i].color[0] ? it[i].color : (pass ? "#8e8e93" : "#0a84ff"));
+ if (!c) continue;
+ scopy(c->href, sizeof c->href, it[i].href);
+ c->ctag[0] = 0;
+ } else {
+ if (it[i].name[0]) scopy(c->name, sizeof c->name, it[i].name);
+ if (it[i].color[0]) scopy(c->color, sizeof c->color, it[i].color);
+ }
+ if (pass == 0) { c->events = ve; c->todos = vt; }
+ c->seen = 1;
+ /* remember the server's ctag; compared after pushing */
+ scopy(c->href, sizeof c->href, it[i].href);
+ it[i].ok = strcmp(c->ctag, it[i].ctag) || !it[i].ctag[0];
+ if (it[i].ok) scopy(c->ctag, sizeof c->ctag, it[i].ctag);
+ }
+ pthread_mutex_unlock(&G);
+ http_resp_free(&hr);
+ /* sync each collection */
+ for (int i = 0; i < n; i++) {
+ if (pass == 0 ? !it[i].cal : !it[i].book) continue;
+ char h[17], cid[80];
+ fs_hash(it[i].href, h);
+ snprintf(cid, sizeof cid, "%s-%s", a->id, h);
+ pthread_mutex_lock(&G);
+ Coll *c = coll_get(cid);
+ int dirty = 0;
+ for (int k = 0; c && k < c->n; k++) if (c->items[k].dirty) dirty = 1;
+ pthread_mutex_unlock(&G);
+ if (!c) continue;
+ if (dirty) push_changes(&d, c);
+ if (it[i].ok || dirty) fetch_changed(&d, c);
+ }
+ if (n > 0) free_items(it, n);
+ }
+ /* collections gone from the server */
+ pthread_mutex_lock(&G);
+ for (int i = ncolls - 1; i >= 0; i--) {
+ Coll *c = colls[i];
+ if (strcmp(c->acct, a->id) || c->seen) continue;
+ if ((c->kind == 'c' && listed[0]) || (c->kind == 'b' && listed[1])) coll_remove(c);
+ }
+ save_colls();
+ pthread_mutex_unlock(&G);
+ dav_end(&d);
+ a->last_sync = time(NULL);
+ acct_status(a, "idle", "");
+ changed_event("all");
+}
diff --git a/server/src/mail/smtp.c b/server/src/mail/smtp.c
index 63af833..1787601 100644
--- a/server/src/mail/smtp.c
+++ b/server/src/mail/smtp.c
@@ -9,6 +9,7 @@
#include <ctype.h>
#include <errno.h>
+#include <fcntl.h>
#include <poll.h>
#include <stdio.h>
#include <stdlib.h>
@@ -125,9 +126,9 @@ char *compose_message(Account *a, const JVal *m, int *fds, int nfds, size_t *ole
int natt = nfds;
char bm[48], ba[48];
rand_hex(rnd, 12);
- snprintf(bm, sizeof bm, "=_lordos_m_%s", rnd);
+ SNPF(bm, sizeof bm, "=_lordos_m_%s", rnd);
rand_hex(rnd, 12);
- snprintf(ba, sizeof ba, "=_lordos_a_%s", rnd);
+ SNPF(ba, sizeof ba, "=_lordos_a_%s", rnd);
int mixed = natt > 0;
int alt = (html && *html) || (ics && *ics);
if (mixed) jb_printf(&b, "Content-Type: multipart/mixed; boundary=\"%s\"\r\n\r\nThis is a multi-part message in MIME format.\r\n--%s\r\n", bm, bm);
diff --git a/server/src/mail/snpf.c b/server/src/mail/snpf.c
new file mode 100644
index 0000000..181635e
--- /dev/null
+++ b/server/src/mail/snpf.c
@@ -0,0 +1,12 @@
+/* snpf.c — see snpf.h. */
+#include "snpf.h"
+#include <stdarg.h>
+#include <stdio.h>
+
+void snpf(char *dst, size_t cap, const char *fmt, ...) {
+ if (!cap) return;
+ va_list ap;
+ va_start(ap, fmt);
+ if (vsnprintf(dst, cap, fmt, ap) < 0) dst[0] = 0;
+ va_end(ap);
+}
diff --git a/server/src/mail/snpf.h b/server/src/mail/snpf.h
new file mode 100644
index 0000000..501c8fb
--- /dev/null
+++ b/server/src/mail/snpf.h
@@ -0,0 +1,9 @@
+/* snpf.h — formatting into fixed-size fields where cutting the text is intended (folder
+ * names, headers shown in the UI). A real function, so -Wformat-truncation stays meaningful for
+ * every other snprintf. */
+#ifndef LORD_MAIL_SNPF_H
+#define LORD_MAIL_SNPF_H
+#include <stddef.h>
+void snpf(char *dst, size_t cap, const char *fmt, ...) __attribute__((format(printf, 3, 4)));
+#define SNPF snpf
+#endif
diff --git a/server/src/mail/store.c b/server/src/mail/store.c
index a368a8c..23268ca 100644
--- a/server/src/mail/store.c
+++ b/server/src/mail/store.c
@@ -3,6 +3,7 @@
* with 10,000 messages opens instantly and offline. Callers hold G. */
#include "maild.h"
#include "mime.h"
+#include "proto.h"
#include <stdio.h>
#include <stdlib.h>
diff --git a/server/src/main.c b/server/src/main.c
index a40776d..e207e19 100644
--- a/server/src/main.c
+++ b/server/src/main.c
@@ -376,7 +376,7 @@ static void display_attach(const int *fds, int n) {
s->gpu_paused = 0;
struct stat st;
if (fstat(s->kms.fd, &st) == 0) wl_set_drm_device(st.st_rdev);
- if (display_rotation() || mirror_clients() || media_needs_cpu() || gpu_start(s)) s->gpu_paused = mirror_clients() > 0 || media_needs_cpu();
+ if (display_cpu_only() || mirror_clients() || media_needs_cpu() || gpu_start(s)) s->gpu_paused = mirror_clients() > 0 || media_needs_cpu();
/* el puntero donde está (una tablet absoluta no avisa si no se mueve) o en el medio */
s->cx = s->W / 2;
s->cy = s->H / 2;
@@ -709,11 +709,11 @@ static void render_frame(Server *s) {
} else {
KmsBuffer *b = kms_back(&s->kms);
Canvas out, phys;
- /* rotated (Settings → Displays): the frame is composed upright in s->frame and copied
- * rotated into the card's buffer; otherwise straight into the buffer */
- int rot = display_rotation();
- canvas_init(&phys, b->map, rot ? (int)s->kms.width : s->W, rot ? (int)s->kms.height : s->H, (int)(b->pitch / 4));
- if (rot) canvas_init(&out, s->frame, s->W, s->H, s->W);
+ /* rotated or at 200 % (Settings → Displays): the frame is composed upright and at the logical size
+ * in s->frame and copied rotated/doubled into the card's buffer; otherwise straight into it */
+ int rot = display_rotation(), xf = display_cpu_only(); /* rotated or at 200 % */
+ canvas_init(&phys, b->map, xf ? (int)s->kms.width : s->W, xf ? (int)s->kms.height : s->H, (int)(b->pitch / 4));
+ if (xf) canvas_init(&out, s->frame, s->W, s->H, s->W);
else out = phys;
int bi = s->kms.front ^ 1, fs = wl_fullscreen_active();
if (fs != s->was_fs) { s->was_fs = fs; s->full_copy = 2; }
@@ -746,7 +746,7 @@ static void render_frame(Server *s) {
mirror_cursor(s->cx, s->cy, mode, px, w, h, hx, hy, gen);
cursor_local(s, &k); /* la flecha también es una imagen (cursor.c) */
Rect cr = { s->cx - k.hx, s->cy - k.hy, s->cx - k.hx + k.w, s->cy - k.hy + k.h };
- if (!rot) {
+ if (!xf) {
display_tint(&out, need); /* Night Shift without a gamma LUT (software) */
if (k.mode == 1) {
canvas_blit(&out, k.px, k.w, k.h, s->cx - k.hx, s->cy - k.hy, 0, 1, 0);
@@ -828,7 +828,7 @@ static void run_modeset(Server *s, uint32_t conn, const struct drm_mode_modeinfo
memset(s->stale, 0, sizeof s->stale);
memset(s->curs, 0, sizeof s->curs);
s->full_copy = 2;
- if (gpu_was_on && !display_rotation() && !mirror_clients() && !media_needs_cpu() && gpu_start(s) == 0) gpu_was_on = 0;
+ if (gpu_was_on && !display_cpu_only() && !mirror_clients() && !media_needs_cpu() && gpu_start(s) == 0) gpu_was_on = 0;
display_modeset_done(ok);
hw_redraw();
}
@@ -938,7 +938,7 @@ int main(int argc, char **argv) {
kms_set_picker(display_pick);
hw_server = &s;
if (ok && !s.greeter) hw_start(&hw_host, 1);
- if (ok && !s.headless && !display_rotation()) gpu_start(&s);
+ if (ok && !s.headless && !display_cpu_only()) gpu_start(&s);
{
struct stat st;
if (s.kms.fd >= 0 && fstat(s.kms.fd, &st) == 0) wl_set_drm_device(st.st_rdev);
@@ -1086,7 +1086,7 @@ int main(int argc, char **argv) {
for (int k = nlost - 1; k >= 0; k--) input_remove(&s.input, lost[k]);
if (nlost) wl_input_devices_changed();
/* la GPU vuelve cuando ya nadie mira desde la red */
- if (s.gpu_paused && !s.headless && !mirror_clients() && !media_needs_cpu() && !s.kms.flip_pending && !display_rotation()) {
+ if (s.gpu_paused && !s.headless && !mirror_clients() && !media_needs_cpu() && !s.kms.flip_pending && !display_cpu_only()) {
s.gpu_paused = 0;
gpu_start(&s);
}
diff --git a/server/src/netperm/netperm.c b/server/src/netperm/netperm.c
index 656e5e6..1a50386 100644
--- a/server/src/netperm/netperm.c
+++ b/server/src/netperm/netperm.c
@@ -47,8 +47,10 @@
#define CG_ROOT "/sys/fs/cgroup"
#define CG_SERVICE "system.slice/lordos.service"
+#define CG_USER "user.slice" /* user.slice/user-<uid>.slice/user@<uid>.service */
#define SVC_LEVEL 2 /* system.slice/lordos.service */
#define SCOPE_LEVEL (SVC_LEVEL + 2) /* lordos-session-<uid>/<scope> */
+#define USER_LEVEL 3 /* user.slice/user-<uid>.slice/user@<uid>.service */
#define NAMES_APP "lordos" /* clave de dnsmap para lo que dice el resolvedor */
#define MAX_SESS 64
#define MAX_CLIENTS 64
@@ -73,6 +75,8 @@ typedef struct {
Scope *sc;
int nsc, cap;
int dirty_counts;
+ uint64_t user_cg; /* id de user@<uid>.service, o 0 si no está (ni enganchado) */
+ int ulinks[16], nulinks; /* los programas enganchados en user@<uid>.service */
} Session;
typedef struct {
@@ -93,7 +97,7 @@ typedef struct {
static struct {
int bpf_ok;
char bpf_err[200];
- int m_cfg, m_apps, m_lpm4, m_lpm6, m_seen, m_counts, m_events;
+ 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;
uint32_t attach[16];
@@ -192,6 +196,7 @@ static void load_rules(Session *s) {
static int map_fd(const char *name) {
if (!strcmp(name, "np_cfg")) return G.m_cfg;
if (!strcmp(name, "np_apps")) return G.m_apps;
+ if (!strcmp(name, "np_union")) return G.m_union;
if (!strcmp(name, "np_lpm4")) return G.m_lpm4;
if (!strcmp(name, "np_lpm6")) return G.m_lpm6;
if (!strcmp(name, "np_seen")) return G.m_seen;
@@ -281,6 +286,70 @@ static void drop_scope(Scope *sc) {
prune(sc->idx, 0);
}
+/* ---- user@<uid>.service: la fuga de systemd-run --------------------------------------------- */
+
+/* Una app sin caja de arena, corriendo como el usuario, puede pedirle a su gestor de systemd
+ * (systemd-run --user, scope o servicio) que mueva un proceso a user@<uid>.service, fuera de
+ * lordos.service, donde las scopes de las apps no llegan. Para cerrarlo se enganchan los mismos
+ * programas también en user@<uid>.service de cada sesión y, cuando el proceso no está en la scope
+ * de ninguna app, cae en np_union[user@]: la unión estricta (OR de las restricciones NP_R_*) de
+ * las apps restringidas del usuario. Así un proceso escapado nunca es menos restrictivo que su
+ * propia política; no otorga nada. Si no hay ninguna app restringida corriendo, no hay entrada y
+ * user@ queda libre (el gestor de usuario y sus servicios no se tocan). */
+
+/* Recompila la unión del usuario desde las flags de sus scopes y la escribe (o la borra si no hay
+ * ninguna restricción). Solo tiene efecto con user@ enganchado. */
+static void sync_union(Session *s) {
+ if (!G.bpf_ok || !s->user_cg) return;
+ NpApp u;
+ memset(&u, 0, sizeof u);
+ for (int k = 0; k < s->nsc; k++) u.flags |= s->sc[k].app_v.flags;
+ if (u.flags) {
+ u.trusted = 1; /* lo que la unión no restringe, se permite sin avisar */
+ u.mode = NP_M_SILENT;
+ if (bpfs_map_update(G.m_union, &s->user_cg, &u, BPF_ANY)) logf_("np_union: %s", strerror(errno));
+ } else {
+ bpfs_map_delete(G.m_union, &s->user_cg);
+ }
+}
+
+static void drop_user_links(Session *s) {
+ for (int i = 0; i < s->nulinks; i++) close(s->ulinks[i]);
+ s->nulinks = 0;
+}
+
+/* Engancha (o re-engancha) los programas en user@<uid>.service. systemd lo crea al ingresar y lo
+ * borra y recrea con otro id al reiniciar el gestor de usuario, así que esto se llama en cada
+ * repaso: si el id cambió (o desapareció), suelta los links viejos y la unión vieja. */
+static void sync_user_scope(Session *s) {
+ if (!G.bpf_ok) return;
+ char path[200];
+ snprintf(path, sizeof path, CG_ROOT "/" CG_USER "/user-%u.slice", s->uid);
+ char leaf[64];
+ snprintf(leaf, sizeof leaf, "user@%u.service", s->uid);
+ uint64_t id = 0;
+ int ufd = -1, sfd = open(path, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
+ if (sfd >= 0) {
+ id = bpfs_cgroup_id(sfd, leaf);
+ if (id) ufd = openat(sfd, leaf, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
+ close(sfd);
+ }
+ if (id == s->user_cg) { if (ufd >= 0) close(ufd); return; }
+ drop_user_links(s);
+ if (s->user_cg) { bpfs_map_delete(G.m_union, &s->user_cg); bpfs_map_delete(G.m_counts, &s->user_cg); }
+ s->user_cg = 0;
+ if (!id || ufd < 0) { if (ufd >= 0) close(ufd); return; }
+ for (int i = 0; i < G.nprogs && s->nulinks < (int)(sizeof s->ulinks / sizeof s->ulinks[0]); i++) {
+ int l = bpfs_link_create(G.progs[i], ufd, G.attach[i]);
+ if (l < 0) { logf_("uid %u: no se pudo enganchar en user@: %s", s->uid, strerror(errno)); drop_user_links(s); close(ufd); return; }
+ s->ulinks[s->nulinks++] = l;
+ }
+ close(ufd);
+ s->user_cg = id;
+ logf_("uid %u: %d programas enganchados en user@%u.service", s->uid, s->nulinks, s->uid);
+ sync_union(s);
+}
+
/* ---- sesiones y scopes ----------------------------------------------------------------------- */
static int scope_app(const char *name, char *app) {
@@ -331,11 +400,15 @@ static void scan_session(Session *s) {
drop_scope(&s->sc[i]);
s->sc[i] = s->sc[--s->nsc];
}
+ sync_user_scope(s); /* engancha/re-engancha user@ y recompila la unión */
+ sync_union(s);
}
static void drop_session(int k) {
Session *s = &G.sess[k];
for (int i = 0; i < s->nsc; i++) drop_scope(&s->sc[i]);
+ drop_user_links(s);
+ if (s->user_cg) { bpfs_map_delete(G.m_union, &s->user_cg); bpfs_map_delete(G.m_counts, &s->user_cg); }
if (s->wd >= 0) inotify_rm_watch(G.ifd, s->wd);
free(s->sc);
fw_store_free(s->store);
@@ -380,6 +453,11 @@ static Scope *scope_by_cgid(uint64_t id, Session **out) {
return NULL;
}
+static Session *session_by_user_cg(uint64_t id) {
+ for (int i = 0; i < G.nsess; i++) if (G.sess[i].user_cg && G.sess[i].user_cg == id) return &G.sess[i];
+ return NULL;
+}
+
/* ---- clientes -------------------------------------------------------------------------------- */
static void cl_drop(int k) {
@@ -449,6 +527,7 @@ static void reload_uid(unsigned uid) {
if (G.sess[i].uid != uid) continue;
load_rules(&G.sess[i]);
for (int k = 0; k < G.sess[i].nsc; k++) sync_scope(&G.sess[i], &G.sess[i].sc[k]);
+ sync_union(&G.sess[i]);
}
}
@@ -483,10 +562,18 @@ static void on_event(void *u, const void *data, uint32_t len) {
memcpy(&ev, data, sizeof ev);
Session *s;
Scope *sc = scope_by_cgid(ev.cgid, &s);
- if (!sc) return;
char addr[INET6_ADDRSTRLEN] = "";
if (ev.fam == 4) inet_ntop(AF_INET, ev.addr, addr, sizeof addr);
else if (ev.fam == 6) inet_ntop(AF_INET6, ev.addr, addr, sizeof addr);
+ if (!sc) {
+ /* la unión de user@: un proceso que se escapó con systemd-run --user (sin scope de app) */
+ Session *us = session_by_user_cg(ev.cgid);
+ if (us && ev.verdict == NP_V_DENY)
+ logf_("uid %u user@: denegada %s %s %s:%u (unión de apps restringidas%s%s)", us->uid,
+ ev.dir == NP_D_IN ? "entrada" : "salida", ev.proto == NP_P_TCP ? "tcp" : ev.proto == NP_P_UDP ? "udp" : "otro",
+ addr[0] ? addr : "?", ev.port, ev.flag ? " " : "", ev.flag ? fw_flag_name(ev.flag) : "");
+ return;
+ }
const char *flag = ev.flag ? fw_flag_name(ev.flag) : "";
char app[FW_APP_MAX * 2 + 4], j[700];
json_quote(app, sizeof app, sc->app);
@@ -570,12 +657,13 @@ static int bpf_setup(void) {
#else
G.m_cfg = bpfs_map_create(BPF_MAP_TYPE_ARRAY, 4, sizeof(NpCfg), 1, 0, "np_cfg");
G.m_apps = bpfs_map_create(BPF_MAP_TYPE_HASH, 8, sizeof(NpApp), NP_MAX_APPS, 0, "np_apps");
+ G.m_union = bpfs_map_create(BPF_MAP_TYPE_HASH, 8, sizeof(NpApp), MAX_SESS, 0, "np_union");
G.m_lpm4 = bpfs_map_create(BPF_MAP_TYPE_LPM_TRIE, sizeof(NpLpm4Key), sizeof(NpList), NP_MAX_LPM, BPF_F_NO_PREALLOC, "np_lpm4");
G.m_lpm6 = bpfs_map_create(BPF_MAP_TYPE_LPM_TRIE, sizeof(NpLpm6Key), sizeof(NpList), NP_MAX_LPM, BPF_F_NO_PREALLOC, "np_lpm6");
G.m_seen = bpfs_map_create(BPF_MAP_TYPE_LRU_HASH, sizeof(NpSeenKey), 8, NP_MAX_SEEN, 0, "np_seen");
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_lpm4 < 0 || G.m_lpm6 < 0 || G.m_seen < 0 || G.m_counts < 0 || G.m_events < 0) {
+ 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, "no se pudieron crear los mapas BPF: %s", strerror(errno));
return -1;
}
@@ -610,7 +698,7 @@ static int bpf_setup(void) {
G.progs[np++] = fd;
}
G.nprogs = np;
- NpCfg cfg = { SCOPE_LEVEL, 1 };
+ 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; }
logf_("%d programas BPF cargados", np);
diff --git a/server/src/netperm/np.bpf.c b/server/src/netperm/np.bpf.c
index 8948038..80afbbd 100644
--- a/server/src/netperm/np.bpf.c
+++ b/server/src/netperm/np.bpf.c
@@ -10,7 +10,14 @@
* cgroup/bind4, bind6 "sin conexiones entrantes" y reglas de entrada (puerto local != 0)
* cgroup/sock_create "sin red": ni siquiera crear un socket AF_INET/AF_INET6
*
- * Cada uno: busca la app por la scope del proceso (antepasado de nivel cfg.level), decide con
+ * Los mismos programas se enganchan además en el user@<uid>.service de cada sesión de LordOS, para
+ * cerrar la fuga de `systemd-run --user` (el proceso termina ahí, fuera de lordos.service). Un
+ * proceso que no está en la scope de ninguna app (antepasado de nivel cfg.level) cae en la unión
+ * estricta de las restricciones de las apps restringidas del usuario (np_union, con la clave del
+ * user@<uid> en el nivel cfg.user_level): nunca es menos restrictivo que su propia política.
+ *
+ * Cada uno: busca la app por la scope del proceso (antepasado de nivel cfg.level) o, si no, por la
+ * unión de user@ (nivel cfg.user_level), decide con
* np_decide (np_shared.h, lo mismo que prueba tests/npcompile_test.c) y devuelve 1 (permitir) o
* 0 (el kernel le devuelve EPERM a la app). Cuenta la conexión y avisa a lord-netperm por el anillo
* solo si es nueva (np_seen, 5 s). Nada por paquete: solo por conexión, bind o sendto. Un connect()
@@ -32,6 +39,7 @@ static long (*bpf_ringbuf_output)(void *ringbuf, void *data, unsigned long long
/* los mapas: solo sus nombres (los define lord-netperm, netperm.c) */
char np_cfg[4] SEC("maps");
char np_apps[4] SEC("maps");
+char np_union[4] SEC("maps");
char np_lpm4[4] SEC("maps");
char np_lpm6[4] SEC("maps");
char np_seen[4] SEC("maps");
@@ -47,6 +55,26 @@ NP_INLINE int proto_of(np_u32 p) {
return p == IPPROTO_TCP ? NP_P_TCP : p == IPPROTO_UDP ? NP_P_UDP : NP_P_OTHER;
}
+/* Busca la política del proceso actual: primero su scope de app (np_apps, antepasado de nivel
+ * cfg->level); si no está (por ejemplo salió a user@<uid> con systemd-run), la unión estricta de
+ * las apps restringidas del usuario (np_union, antepasado de nivel cfg->user_level). Devuelve la
+ * NpApp y deja en *cgid la clave con la que contar y avisar (la scope o el user@). 0 si no aplica. */
+NP_INLINE NpApp *find_app(NpCfg *cfg, np_u64 *cgid) {
+ np_u64 id = bpf_get_current_ancestor_cgroup_id((int)cfg->level);
+ if (id) {
+ NpApp *app = bpf_map_lookup_elem(&np_apps, &id);
+ if (app) { *cgid = id; return app; }
+ }
+ if (cfg->user_level) {
+ np_u64 uid = bpf_get_current_ancestor_cgroup_id((int)cfg->user_level);
+ if (uid) {
+ NpApp *app = bpf_map_lookup_elem(&np_union, &uid);
+ if (app) { *cgid = uid; return app; }
+ }
+ }
+ return 0;
+}
+
NP_INLINE void count(np_u64 cgid, int deny) {
NpCount *c = bpf_map_lookup_elem(&np_counts, &cgid);
if (!c) {
@@ -65,10 +93,9 @@ NP_INLINE int handle(int fam, np_u8 *addr, int port, int proto, int dir, int alw
np_u32 zero = 0;
NpCfg *cfg = bpf_map_lookup_elem(&np_cfg, &zero);
if (!cfg || !cfg->on) return 1;
- np_u64 cgid = bpf_get_current_ancestor_cgroup_id((int)cfg->level);
- if (!cgid) return 1;
- NpApp *app = bpf_map_lookup_elem(&np_apps, &cgid);
- if (!app) return 1; /* fuera de las apps de una sesión */
+ np_u64 cgid = 0;
+ NpApp *app = find_app(cfg, &cgid);
+ if (!app) return 1; /* ni una scope de app ni user@ restringido */
int lan = -1;
NpList *l = 0;
diff --git a/server/src/netperm/np_shared.h b/server/src/netperm/np_shared.h
index 1385323..791d301 100644
--- a/server/src/netperm/np_shared.h
+++ b/server/src/netperm/np_shared.h
@@ -9,6 +9,7 @@
* Mapas (los crea lord-netperm; los programas los ven por nombre):
* np_cfg ARRAY [0] → NpCfg nivel de la scope de las apps, encendido
* np_apps HASH id de cgroup (u64) → NpApp restricciones, confiable, modo, lista genérica
+ * np_union HASH id de user@<uid> (u64) → NpApp unión estricta de las apps restringidas del usuario
* np_lpm4 LPM (idx de app, IPv4/n) → NpList reglas de red y de dominio, ordenadas
* np_lpm6 LPM (idx de app, IPv6/n) → NpList
* np_seen LRU NpSeenKey → u64 ns para avisar solo las conexiones nuevas
@@ -86,6 +87,7 @@ typedef struct { np_u32 prefixlen; np_u8 data[20]; } NpLpm6Key; /* idx (big en
typedef struct {
np_u32 level; /* profundidad de las scopes de apps (bpf_get_current_ancestor_cgroup_id) */
np_u32 on; /* 0: todo se permite sin mirar nada */
+ np_u32 user_level; /* profundidad de user@<uid>.service; 0: no mirar la unión de user@ */
} NpCfg;
typedef struct {
diff --git a/server/src/sec/broker.h b/server/src/sec/broker.h
index 1c0a55f..781ac41 100644
--- a/server/src/sec/broker.h
+++ b/server/src/sec/broker.h
@@ -35,6 +35,10 @@ enum BrokerOp {
BOP_CAMERA, /* payload "list" | "open dev w h" | "ring sid" (→ read-only ring fd) | "ack sid id" |
* "size sid w h" | "photo sid mirror name" | "record sid mirror mic name" |
* "recstop sid" | "close sid". See brokercam.c */
+ BOP_VAULT_FIDO = 40,/* (Passwords only) open the FIDO2 key for lord-vault after the `usb` permission →
+ * "name"; the app never gets the device (docs/PASSWORDS.md) */
+ BOP_CLIP_SECRET, /* payload "seconds\0text": a secret to the clipboard, marked sensitive (out of
+ * the history, x-kde-passwordManagerHint) and cleared after `seconds` if unchanged */
BOP_EVENT = 100, /* servidor → app, sin pedido (reqid 0): payload "tipo\0json" */
};
@@ -63,6 +67,9 @@ void brokersrv_events(BrokerEventFn fn);
/* Respuesta del usuario a un aviso (desde JS: lord.broker.resolve). */
void brokersrv_resolve(uint32_t reqid, int allow);
int brokersrv_count(void);
+/* The app on broker fd `fd` was spawned with a channel to lord-vault (system Passwords app): it may
+ * use BOP_VAULT_FIDO. */
+void brokersrv_set_vault(int fd);
/* The app <id> is running: ask it for a new window. 0 if sent, -1 if it is not running. */
int brokersrv_new_window(const char *id);
/* El tema publica su estado (tipo "theme" o "locale", JSON) y se reenvía en vivo a todas las
diff --git a/server/src/sec/brokersrv.c b/server/src/sec/brokersrv.c
index 2a82710..fd3cb3e 100644
--- a/server/src/sec/brokersrv.c
+++ b/server/src/sec/brokersrv.c
@@ -10,6 +10,8 @@
#include "../media/media_int.h"
#include "../media/aring.h"
#include "../keyboard.h"
+#include "../vault/vclient.h"
+#include "../pkg/crypto.h"
#include <dirent.h>
#include <errno.h>
@@ -21,12 +23,13 @@
#include <string.h>
#include <sys/socket.h>
#include <sys/stat.h>
+#include <time.h>
#include <unistd.h>
#define MAX_APPS 32
#define MAX_PENDING 32
-typedef struct { int fd, pid, used, resync; char id[48]; MAudio *mic; int mic_ringfd; } AppConn;
+typedef struct { int fd, pid, used, resync; char id[48]; MAudio *mic; int mic_ringfd; int vault; } AppConn;
static AppConn apps[MAX_APPS];
/* avisos pendientes de respuesta del usuario (reqid → app + fd + permiso) */
@@ -91,6 +94,7 @@ int brokersrv_publish(const char *kind, const char *json, size_t len) {
}
static int send_reply_fd(int fd, uint32_t reqid, int status, const void *data, uint32_t len, int passfd);
+static void clip_secret_tick(void);
static int send_reply(int fd, uint32_t reqid, int status, const void *data, uint32_t len);
/* picker (powerbox): avisos pendientes de que el usuario elija un archivo */
@@ -139,6 +143,7 @@ void brokersrv_revoke(const char *app, const char *perm) {
void brokersrv_tick(void) {
brokercam_tick();
+ clip_secret_tick();
char kb[512];
keyboard_json(kb, sizeof kb);
int kb_changed = strcmp(kb, sent_kb) != 0;
@@ -172,6 +177,24 @@ int brokersrv_new_window(const char *id) {
return -1;
}
+void brokersrv_set_vault(int fd) { for (int i = 0; i < MAX_APPS; i++) if (apps[i].used && apps[i].fd == fd) apps[i].vault = 1; }
+
+/* A secret an isolated app put on the clipboard: cleared at `deadline` if it is still there
+ * (compared by hash, the text itself is not kept). */
+static struct { double deadline; uint8_t hash[32]; } clip_secret;
+
+static double mono_s(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec + t.tv_nsec / 1e9; }
+
+static void clip_secret_tick(void) {
+ if (!clip_secret.deadline || mono_s() < clip_secret.deadline) return;
+ clip_secret.deadline = 0;
+ const char *cur = term_clipboard();
+ uint8_t h[32];
+ sha256(cur ? cur : "", cur ? strlen(cur) : 0, h);
+ if (!memcmp(h, clip_secret.hash, 32)) { term_set_clipboard("", 0); term_clipboard_mark("lordos", 0); }
+ explicit_bzero(h, sizeof h);
+}
+
int brokersrv_count(void) { int n = 0; for (int i = 0; i < MAX_APPS; i++) n += apps[i].used; return n; }
static void drop(AppConn *a) {
@@ -371,6 +394,33 @@ static void handle(AppConn *a, BrokerHdr *h, char *payload) {
close(ro);
break;
}
+ case BOP_CLIP_SECRET: {
+ /* "seconds\0text": sensitive copy (Passwords), cleared later if unchanged */
+ char *nul = memchr(payload, 0, h->len);
+ if (!nul) { send_reply(fd, h->reqid, BST_ERROR, NULL, 0); break; }
+ int secs = atoi(payload);
+ const char *txt = nul + 1;
+ size_t tl = h->len - (size_t)(txt - payload);
+ term_set_clipboard(txt, tl);
+ term_clipboard_mark(a->id, 1);
+ if (secs > 0 && secs <= 600) {
+ sha256(txt, tl, clip_secret.hash);
+ clip_secret.deadline = mono_s() + secs;
+ }
+ explicit_bzero(payload, h->len);
+ send_reply(fd, h->reqid, BST_OK, NULL, 0);
+ break;
+ }
+ case BOP_VAULT_FIDO: {
+ /* only the system Passwords app (spawned with a vault channel), only with `usb` allowed; the
+ * hidraw fd goes from here straight to lord-vault */
+ if (!a->vault || perm_get(a->id, PERM_USB) != PERM_ALLOW) { send_reply(fd, h->reqid, BST_DENIED, NULL, 0); break; }
+ char name[128] = "";
+ int r = vc_fido_attach(name, sizeof name);
+ if (r) send_reply(fd, h->reqid, BST_ERROR, r == -1 ? "no-device" : "no-access", r == -1 ? 9 : 9);
+ else send_reply(fd, h->reqid, BST_OK, name, (uint32_t)strlen(name));
+ break;
+ }
case BOP_QUIT:
send_reply(fd, h->reqid, BST_OK, NULL, 0);
break;
diff --git a/server/src/term/term.c b/server/src/term/term.c
index 5bc6bee..ce48385 100644
--- a/server/src/term/term.c
+++ b/server/src/term/term.c
@@ -186,6 +186,7 @@ void term_set_clipboard(const char *s, size_t n) {
if (!c) return;
memcpy(c, s, n);
c[n] = 0;
+ if (clip) explicit_bzero(clip, strlen(clip)); /* the previous copy may have been a password */
free(clip);
clip = c;
clip_gen++;
diff --git a/server/src/ui/js.c b/server/src/ui/js.c
index 583ee1f..3ddaf61 100644
--- a/server/src/ui/js.c
+++ b/server/src/ui/js.c
@@ -450,6 +450,7 @@ int js_init_app(const char *host_bundle, const char *app_id) {
JS_SetPropertyStr(ctx, lord, "screen", screen);
JS_SetPropertyStr(ctx, lord, "version", JS_NewString(ctx, "0.7.0"));
js_broker_register(ctx, lord, app_id); /* fs/clipboard/perms por el broker + appId */
+ js_vault_register_app(ctx, lord); /* Passwords only: its own channel to lord-vault */
js_sys_register_app(ctx, lord); /* lord.text (idioma, dirección) y lord.image */
js_wasm_register(ctx, g); /* WebAssembly para loadWasm de la app */
JS_SetPropertyStr(ctx, g, "lord", lord);
diff --git a/server/src/ui/js_broker.c b/server/src/ui/js_broker.c
index 9345a29..65b911b 100644
--- a/server/src/ui/js_broker.c
+++ b/server/src/ui/js_broker.c
@@ -230,14 +230,48 @@ static JSValue f_clip_get(JSContext *c, JSValueConst t, int argc, JSValueConst *
return v;
}
static JSValue f_clip_set(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
- (void)t; (void)argc;
- const char *s = JS_ToCString(c, argv[0]);
+ (void)t;
+ size_t sl = 0;
+ const char *s = JS_ToCStringLen(c, &sl, argv[0]);
int st;
- if (s) rpc(BOP_CLIP_SET, s, (uint32_t)strlen(s), &st, NULL, NULL);
+ /* lord.clipboard.set(text, { secure, clearAfter }): a secret (Passwords) is marked sensitive and
+ * cleared by lord-server after clearAfter seconds if it is still there */
+ int secure = 0, clear_after = 0;
+ if (argc > 1 && JS_IsObject(argv[1])) {
+ JSValue v = JS_GetPropertyStr(c, argv[1], "secure");
+ secure = JS_ToBool(c, v);
+ JS_FreeValue(c, v);
+ v = JS_GetPropertyStr(c, argv[1], "clearAfter");
+ int32_t ca = 0;
+ if (JS_IsNumber(v)) JS_ToInt32(c, &ca, v);
+ JS_FreeValue(c, v);
+ clear_after = ca > 0 && ca <= 600 ? ca : 0;
+ }
+ if (s && secure) {
+ char *buf = malloc(sl + 16);
+ if (buf) {
+ int k = snprintf(buf, 16, "%d", clear_after) + 1;
+ memcpy(buf + k, s, sl);
+ rpc(BOP_CLIP_SECRET, buf, (uint32_t)(k + sl), &st, NULL, NULL);
+ explicit_bzero(buf, (size_t)k + sl);
+ free(buf);
+ }
+ } else if (s) rpc(BOP_CLIP_SET, s, (uint32_t)sl, &st, NULL, NULL);
if (s) JS_FreeCString(c, s);
return JS_UNDEFINED;
}
+/* For js_vault.c (Passwords in app mode): lord-server opens the FIDO2 key for lord-vault after the
+ * `usb` permission. 0 and the device name, or -1 with err ("denied", "no-device"…). */
+int js_broker_vault_fido(char *name, size_t n, char *err, size_t en) {
+ int st = BST_ERROR; char *out = NULL; uint32_t len = 0;
+ int r = rpc(BOP_VAULT_FIDO, NULL, 0, &st, &out, &len);
+ if (!r && st == BST_OK) { snprintf(name, n, "%.*s", (int)len, out ? out : ""); free(out); return 0; }
+ snprintf(err, en, "%s", st == BST_DENIED ? "fido-denied" : out && len ? out : "no-device");
+ free(out);
+ return -1;
+}
+
/* ---- lord.broker: pedir un permiso (aviso del sistema) y marcar un dispositivo en uso ---- */
/* RPC que recibe un fd por SCM_RIGHTS (powerbox). Devuelve el fd, o -1; name el nombre elegido. */
diff --git a/server/src/ui/js_broker.h b/server/src/ui/js_broker.h
index 8bd5ac0..b4cb3ed 100644
--- a/server/src/ui/js_broker.h
+++ b/server/src/ui/js_broker.h
@@ -26,4 +26,7 @@ int js_broker_send(int op, const void *payload, uint32_t len);
void js_brokercam_register(JSContext *c, JSValue lord);
void js_brokercam_event(const char *data, size_t len);
+/* Passwords (app mode): ask lord-server to hand the FIDO2 key to lord-vault (see js_broker.c). */
+int js_broker_vault_fido(char *name, size_t n, char *err, size_t en);
+
#endif
diff --git a/server/src/ui/js_hw.c b/server/src/ui/js_hw.c
index 27bd660..acdcf93 100644
--- a/server/src/ui/js_hw.c
+++ b/server/src/ui/js_hw.c
@@ -4,7 +4,7 @@
* arrive in JS as __lordHw(kind, data).
*
* lord.display.list() outputs, modes, Night Shift, backlight
- * lord.display.apply(conn, w, h, mHz, rot) live (queued between frames); true if accepted
+ * lord.display.apply(conn, w, h, mHz, rot, scale) live (queued between frames); true if accepted
* lord.display.save(conn) keep the current mode for that display
* lord.display.setTemperature(K) / temperature()
* lord.display.sun(zone, y, m, d) { rise, set } minutes UTC, or null
@@ -65,9 +65,9 @@ static JSValue f_display_apply(JSContext *c, JSValueConst t, int argc, JSValueCo
(void)t;
if (argc < 5) return JS_FALSE;
int conn = arg_int(c, argv[0], 0), w = arg_int(c, argv[1], 0), h = arg_int(c, argv[2], 0);
- int hz = arg_int(c, argv[3], 0), rot = arg_int(c, argv[4], 0);
- if (conn <= 0 || w < 0 || h < 0 || w > 16384 || h > 16384 || hz < 0 || hz > 1000000 || rot < 0 || rot > 3) return JS_FALSE;
- return JS_NewBool(c, display_request((uint32_t)conn, w, h, hz, rot) == 0);
+ int hz = arg_int(c, argv[3], 0), rot = arg_int(c, argv[4], 0), scale = argc > 5 ? arg_int(c, argv[5], 1) : 1;
+ if (conn <= 0 || w < 0 || h < 0 || w > 16384 || h > 16384 || hz < 0 || hz > 1000000 || rot < 0 || rot > 3 || (scale != 1 && scale != 2)) return JS_FALSE;
+ return JS_NewBool(c, display_request((uint32_t)conn, w, h, hz, rot, scale) == 0);
}
static JSValue f_display_save(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
@@ -117,7 +117,7 @@ static JSValue f_display_wake(JSContext *c, JSValueConst t, int argc, JSValueCon
static const JSCFunctionListEntry display_funcs[] = {
JS_CFUNC_DEF("list", 0, f_display_list),
- JS_CFUNC_DEF("apply", 5, f_display_apply),
+ JS_CFUNC_DEF("apply", 6, f_display_apply),
JS_CFUNC_DEF("save", 1, f_display_save),
JS_CFUNC_DEF("setTemperature", 1, f_display_set_temp),
JS_CFUNC_DEF("temperature", 0, f_display_temp),
diff --git a/server/src/ui/js_vault.c b/server/src/ui/js_vault.c
index 8091238..13a39bd 100644
--- a/server/src/ui/js_vault.c
+++ b/server/src/ui/js_vault.c
@@ -20,6 +20,8 @@
#include "../sec/perms.h"
#include "../vault/vclient.h"
#include "../vault/fidodev.h"
+#include "../vault/vwire.h"
+#include "js_broker.h"
#include <errno.h>
#include <fcntl.h>
@@ -177,3 +179,145 @@ void js_vault_register(JSContext *c, JSValue lord) {
JS_SetPropertyStr(c, lord, "vault", o);
vc_start(); /* el llavero y Secret Service andan desde el comienzo de la sesión */
}
+
+/* ================= app mode =================
+ * The Passwords app runs as its own sandboxed process (lord-server --app passwords). lord-server
+ * gave it a channel of its own to lord-vault (vc_attach_app, env LORD_VAULT_FD): requests and
+ * replies, including revealed secrets, travel between the two sandboxed processes only; lord-server
+ * never sees them. Same lord.vault API as in the shell, except that files are fds the user picked
+ * in the system dialog (powerbox): request(json, { fds: [fd…] }). */
+
+static int app_fd = -1;
+static uint32_t app_next = 1;
+static int app_inflight;
+static VwRx app_rx;
+
+static JSValue fa_available(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t; (void)argc; (void)argv;
+ return JS_NewBool(c, app_fd >= 0);
+}
+
+static 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)");
+ size_t len;
+ const char *j = JS_ToCStringLen(c, &len, argv[0]);
+ if (!j) return JS_EXCEPTION;
+ int fds[VW_MAX_FDS], nf = 0;
+ if (argc > 1 && JS_IsObject(argv[1])) {
+ JSValue arr = JS_GetPropertyStr(c, argv[1], "fds");
+ if (JS_IsArray(c, arr)) {
+ JSValue lv = JS_GetPropertyStr(c, arr, "length");
+ int32_t n = 0;
+ JS_ToInt32(c, &n, lv);
+ JS_FreeValue(c, lv);
+ for (int i = 0; i < n && nf < VW_MAX_FDS; i++) {
+ JSValue v = JS_GetPropertyUint32(c, arr, (uint32_t)i);
+ int32_t fd = -1;
+ JS_ToInt32(c, &fd, v);
+ JS_FreeValue(c, v);
+ if (fd > 2) fds[nf++] = fd;
+ }
+ }
+ JS_FreeValue(c, arr);
+ }
+ uint32_t id = app_next++;
+ if (app_next > 0x7fffffff) app_next = 1;
+ 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");
+ app_inflight++;
+ return JS_NewInt32(c, (int32_t)id);
+}
+
+static JSValue fa_poll(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t; (void)argc; (void)argv;
+ if (app_fd < 0) return JS_NULL;
+ size_t cap = 0, o = 0;
+ char *out = NULL;
+ for (;;) {
+ VMsg m;
+ int r = vw_feed(app_fd, &app_rx, &m, &vw_malloc);
+ if (r == 0) break;
+ if (r < 0) { /* lord-vault went away */
+ close(app_fd);
+ app_fd = -1;
+ static const char crash[] = "{\"id\":0,\"kind\":\"evt\",\"data\":{\"ev\":\"crash\"}}";
+ size_t need = o + sizeof crash + 4;
+ char *nb = realloc(out, need);
+ if (nb) { out = nb; cap = need; o += (size_t)snprintf(out + o, cap - o, "%s%s", o ? "," : "[", crash); }
+ break;
+ }
+ for (int i = 0; i < m.nfds; i++) close(m.fds[i]);
+ if (m.kind == VW_REP && app_inflight > 0) app_inflight--;
+ size_t need = o + m.len + 80;
+ if (need > cap) {
+ size_t nc = cap ? cap * 2 : 4096;
+ while (nc < need) nc *= 2;
+ char *nb = malloc(nc);
+ if (!nb) { vw_msg_free(&m, &vw_malloc); break; }
+ if (out) { memcpy(nb, out, o); explicit_bzero(out, cap); free(out); }
+ out = nb;
+ cap = nc;
+ }
+ o += (size_t)snprintf(out + o, cap - o, "%s{\"id\":%u,\"kind\":\"%s\",\"data\":", o ? "," : "[", m.id, m.kind == VW_EVT ? "evt" : "rep");
+ if (m.len) { memcpy(out + o, m.json, m.len); o += m.len; } else { memcpy(out + o, "{}", 2); o += 2; }
+ out[o++] = '}';
+ vw_msg_free(&m, &vw_malloc); /* wipes the text */
+ }
+ if (!out) return JS_NULL;
+ out[o++] = ']';
+ JSValue v = JS_NewStringLen(c, out, o);
+ explicit_bzero(out, cap);
+ free(out);
+ return v;
+}
+
+static JSValue fa_pending(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t; (void)argc; (void)argv;
+ return JS_NewInt32(c, app_inflight);
+}
+
+static JSValue fa_lock(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)c; (void)t; (void)argc; (void)argv;
+ if (app_fd >= 0 && !vw_send(app_fd, VW_REQ, app_next++, "{\"op\":\"lock\"}", 13, NULL, 0)) app_inflight++;
+ return JS_UNDEFINED;
+}
+
+static JSValue fa_fido_attach(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t; (void)argc; (void)argv;
+ char name[128] = "", err[64] = "";
+ int r = js_broker_vault_fido(name, sizeof name, err, sizeof err);
+ JSValue o = JS_NewObject(c);
+ JS_SetPropertyStr(c, o, "ok", JS_NewBool(c, r == 0));
+ if (r) JS_SetPropertyStr(c, o, "error", JS_NewString(c, err));
+ else JS_SetPropertyStr(c, o, "name", JS_NewString(c, name));
+ return o;
+}
+
+static JSValue fa_noop(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) { (void)c; (void)t; (void)argc; (void)argv; return JS_UNDEFINED; }
+
+static const JSCFunctionListEntry vault_app_funcs[] = {
+ JS_CFUNC_DEF("available", 0, fa_available),
+ JS_CFUNC_DEF("request", 2, fa_request),
+ JS_CFUNC_DEF("poll", 0, fa_poll),
+ JS_CFUNC_DEF("pending", 0, fa_pending),
+ JS_CFUNC_DEF("lock", 1, fa_lock),
+ JS_CFUNC_DEF("fidoAttach", 1, fa_fido_attach),
+ JS_CFUNC_DEF("promptDone", 2, fa_noop),
+};
+
+void js_vault_register_app(JSContext *c, JSValue lord) {
+ const char *s = getenv("LORD_VAULT_FD");
+ if (!s) return; /* only the app spawned with a vault channel */
+ app_fd = atoi(s);
+ if (app_fd <= 2) { app_fd = -1; return; }
+ fcntl(app_fd, F_SETFD, FD_CLOEXEC);
+ unsetenv("LORD_VAULT_FD");
+ JSValue o = JS_NewObject(c);
+ JS_SetPropertyFunctionList(c, o, vault_app_funcs, sizeof vault_app_funcs / sizeof vault_app_funcs[0]);
+ JS_SetPropertyStr(c, o, "appMode", JS_TRUE);
+ JS_SetPropertyStr(c, lord, "vault", o);
+}
diff --git a/server/src/ui/js_vault.h b/server/src/ui/js_vault.h
index 47a55fe..67065f4 100644
--- a/server/src/ui/js_vault.h
+++ b/server/src/ui/js_vault.h
@@ -6,4 +6,7 @@
void js_vault_register(JSContext *c, JSValue lord);
+/* App process (lord-server --app): lord.vault on the app's own channel to lord-vault (LORD_VAULT_FD). */
+void js_vault_register_app(JSContext *c, JSValue lord);
+
#endif
diff --git a/server/tests/mail_test.c b/server/tests/mail_test.c
index b9f9fd1..e6795ee 100644
--- a/server/tests/mail_test.c
+++ b/server/tests/mail_test.c
@@ -15,6 +15,7 @@
#include <stdlib.h>
#include <string.h>
#include <time.h>
+#include <unistd.h>
#include <ctype.h>
static int fails, checks;
@@ -415,9 +416,20 @@ static void test_html(void) {
CHECK(strstr(j, "\"bg\":\"#f4f4f4\"") != NULL);
CHECK(strstr(j, "\"mk\":\"2.\"") != NULL);
CHECK(strstr(j, "{\"t\":\"tbl\"") != NULL);
+ CHECK(strstr(j, "\"c\":[]}") == NULL || !strstr(j, "{\"t\":\"tr\",\"s\":{\"_\":0},\"c\":[]}")); /* no empty rows */
for (int i = 0; i < nd; i++) free((void *)data[i].p);
free(j);
+ {
+ const char *tb = "<table><tr><td>a</td><td>b</td></tr><tr><td>c<td>d</table>";
+ size_t tn;
+ char *tj = html_sanitize(tb, strlen(tb), &tn, &st, NULL, NULL);
+ int rows = 0, cells = 0;
+ for (const char *p = tj; (p = strstr(p, "\"t\":\"tr\"")); p++) rows++;
+ for (const char *p = tj; (p = strstr(p, "\"t\":\"td\"")); p++) cells++;
+ CHECK(rows == 2 && cells == 4);
+ free(tj);
+ }
CHECK(html_link_warning("https://www.mibanco.com", "https://mibanco.com.evil.net/") != NULL);
CHECK(html_link_warning("www.mibanco.com", "https://login.mibanco.com/x") == NULL);
CHECK(html_link_warning("Ver más", "https://cualquier.net/") == NULL);
@@ -728,6 +740,7 @@ static void test_vcard(void) {
}
int main(void) {
+ alarm(300); /* never hang a `make test`: SIGALRM kills a runaway parser */
clock_t t0 = clock();
static const struct { const char *name; void (*fn)(void); } parts[] = {
{ "imap", test_imap }, { "mime", test_mime }, { "html", test_html }, { "xml", test_xml }, { "ical", test_ical }, { "vcard", test_vcard },
diff --git a/server/tests/maild_cli.c b/server/tests/maild_cli.c
new file mode 100644
index 0000000..1e4de6f
--- /dev/null
+++ b/server/tests/maild_cli.c
@@ -0,0 +1,59 @@
+/* maild_cli.c — drives lord-maild the way lord-server does (mailc.c), from a terminal, for
+ * manual tests against local servers (docs/MAIL.md, "Testing"). Not part of `make test`.
+ *
+ * build/maild-cli '{"op":"status"}' '{"op":"list","acct":"ana","folder":"INBOX"}' --wait 5
+ * Each request waits for its answer; events are printed as they come. The accounts come from
+ * ~/.config/lordos/mail/accounts.json; a password can be given with {"op":"auth",…}. */
+#include "mail/mailc.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+#include <unistd.h>
+#include <fcntl.h>
+
+static int wait_for(int id, double seconds) {
+ struct timespec t0, t;
+ clock_gettime(CLOCK_MONOTONIC, &t0);
+ int got = 0;
+ for (;;) {
+ char *s = mail_poll();
+ if (s) {
+ printf("%s\n", s);
+ char key[32];
+ snprintf(key, sizeof key, "{\"id\":%d,", id);
+ if (id > 0 && strstr(s, key)) got = 1;
+ free(s);
+ fflush(stdout);
+ }
+ if (got) return 0;
+ clock_gettime(CLOCK_MONOTONIC, &t);
+ if ((t.tv_sec - t0.tv_sec) + (t.tv_nsec - t0.tv_nsec) / 1e9 > seconds) return id > 0 ? -1 : 0;
+ usleep(20000);
+ }
+}
+
+int main(int argc, char **argv) {
+ if (mail_start()) { fprintf(stderr, "lord-maild did not start (is it next to this binary?)\n"); return 1; }
+ for (int i = 1; i < argc; i++) {
+ if (!strcmp(argv[i], "--wait") && i + 1 < argc) { wait_for(0, atof(argv[++i])); continue; }
+ if (!strcmp(argv[i], "--file") && i + 2 < argc) {
+ /* --file <path> <json>: the request with one file attached */
+ int fd = open(argv[i + 1], 0);
+ int fds[1] = { fd };
+ int id = mail_request(argv[i + 2], strlen(argv[i + 2]), fds, fd >= 0 ? 1 : 0);
+ i += 2;
+ if (wait_for(id, 60)) fprintf(stderr, "request %d: no answer\n", id);
+ continue;
+ }
+ struct timespec a, b;
+ clock_gettime(CLOCK_MONOTONIC, &a);
+ int id = mail_request(argv[i], strlen(argv[i]), NULL, 0);
+ if (id < 0) { fprintf(stderr, "request failed\n"); return 1; }
+ if (wait_for(id, 120)) fprintf(stderr, "request %d: no answer\n", id);
+ clock_gettime(CLOCK_MONOTONIC, &b);
+ fprintf(stderr, "request %d: %.1f ms\n", id, (b.tv_sec - a.tv_sec) * 1e3 + (b.tv_nsec - a.tv_nsec) / 1e6);
+ }
+ return 0;
+}
diff --git a/server/tests/mailnet_test.c b/server/tests/mailnet_test.c
new file mode 100644
index 0000000..b074f89
--- /dev/null
+++ b/server/tests/mailnet_test.c
@@ -0,0 +1,144 @@
+/* mailnet_test.c — lord-maild's wire readers against hostile servers (docs/MAIL.md): HTTP chunk
+ * sizes and Content-Length (overflow, garbage, negative), header limits, IMAP literal sizes near
+ * SIZE_MAX, and lines that never end. Everything runs over a local socketpair: no network and a
+ * global alarm, so `make test` can never hang on it. */
+#include "mail/http.h"
+#include "mail/imapio.h"
+#include "mail/net.h"
+
+#include <signal.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <sys/wait.h>
+#include <unistd.h>
+
+static int fails, checks;
+#define CHECK(c) do { checks++; if (!(c)) { fails++; fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #c); } } while (0)
+
+/* A "server" child that writes `resp` (len bytes, then repeats `tail` n times) and closes. */
+static Conn *serve(const char *resp, size_t len, const char *tail, long reps) {
+ int sv[2];
+ if (socketpair(AF_UNIX, SOCK_STREAM, 0, sv)) return NULL;
+ pid_t p = fork();
+ if (p == 0) {
+ close(sv[0]);
+ signal(SIGPIPE, SIG_IGN);
+ /* drain what the client sends */
+ if (fork() == 0) { char b[4096]; while (read(sv[1], b, sizeof b) > 0) {} _exit(0); }
+ if (len && write(sv[1], resp, len) < 0) _exit(1);
+ for (long i = 0; tail && i < reps; i++) if (write(sv[1], tail, strlen(tail)) < 0) break;
+ shutdown(sv[1], SHUT_WR);
+ _exit(0);
+ }
+ close(sv[1]);
+ return conn_new(sv[0], "test", 5000);
+}
+
+static int http_case(const char *resp, size_t max, HttpResp *r) {
+ Conn *c = serve(resp, strlen(resp), NULL, 0);
+ int rc = http_request(c, "GET", "test", "/", NULL, NULL, 0, max, 5000, r);
+ conn_close(c);
+ while (waitpid(-1, NULL, WNOHANG) > 0) {}
+ return rc;
+}
+
+int main(void) {
+ alarm(60);
+ signal(SIGPIPE, SIG_IGN);
+ unsigned long long v;
+ CHECK(http_chunk_size("1a\r\n", &v) == 0 && v == 26);
+ CHECK(http_chunk_size("0\r\n", &v) == 0 && v == 0);
+ CHECK(http_chunk_size("10;name=val\r\n", &v) == 0 && v == 16);
+ CHECK(http_chunk_size("ffffffffffffffff\r\n", &v) == 0 && v == 0xffffffffffffffffull); /* parsed, then rejected by size */
+ CHECK(http_chunk_size("1ffffffffffffffff\r\n", &v) == -1); /* 17 digits: ERANGE */
+ CHECK(http_chunk_size("-1\r\n", &v) == -1);
+ CHECK(http_chunk_size("zz\r\n", &v) == -1);
+ CHECK(http_chunk_size("12 garbage\r\n", &v) == -1);
+ CHECK(http_chunk_size("\r\n", &v) == -1);
+ CHECK(http_content_length("123", &v) == 0 && v == 123);
+ CHECK(http_content_length(" 42 ", &v) == 0 && v == 42);
+ CHECK(http_content_length("-5", &v) == -1);
+ CHECK(http_content_length("99999999999999999999999", &v) == -1);
+ CHECK(http_content_length("12abc", &v) == -1);
+ CHECK(http_content_length("", &v) == -1);
+
+ HttpResp r;
+ CHECK(http_case("HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n6\r\n world\r\n0\r\n\r\n", 1 << 20, &r) == 0 && r.blen == 11 && !strcmp(r.body, "hello world"));
+ http_resp_free(&r);
+ CHECK(http_case("HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\nffffffffffffffff\r\nxx", 1 << 20, &r) == -2);
+ CHECK(http_case("HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\nfffffffffffffff0\r\nxx", 1 << 20, &r) == -2);
+ CHECK(http_case("HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\nfffffffffffffffb\r\nx", 1 << 20, &r) == -2);
+ CHECK(http_case("HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n5 junk\r\nhello\r\n0\r\n\r\n", 1 << 20, &r) == -1);
+ CHECK(http_case("HTTP/1.1 200 OK\r\nContent-Length: 18446744073709551615\r\n\r\nx", 1 << 20, &r) == -1);
+ CHECK(http_case("HTTP/1.1 200 OK\r\nContent-Length: 9223372036854775807\r\n\r\nx", 1 << 20, &r) == -2);
+ CHECK(http_case("HTTP/1.1 200 OK\r\nContent-Length: -1\r\n\r\nx", 1 << 20, &r) == -1);
+ CHECK(http_case("HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\nabcd", 1 << 20, &r) == 0 && r.blen == 4);
+ http_resp_free(&r);
+ CHECK(http_case("HTTP/1.1 200 OK\r\nContent-Length: 400\r\n\r\nabcd", 100, &r) == -2);
+ /* endless headers and an endless header line */
+ {
+ Conn *c = serve("HTTP/1.1 200 OK\r\n", 17, "X-A: b\r\n", 100000);
+ CHECK(http_request(c, "GET", "test", "/", NULL, NULL, 0, 1 << 20, 5000, &r) == -1);
+ conn_close(c);
+ c = serve("HTTP/1.1 200 OK\r\nX-Long: ", 25, "aaaaaaaaaaaaaaaa", 100000);
+ CHECK(http_request(c, "GET", "test", "/", NULL, NULL, 0, 1 << 20, 5000, &r) == -1);
+ conn_close(c);
+ c = serve("HTTP/1.1 200 OK\r\n\r\n", 19, "0123456789abcdef", 100000); /* body until close, over the cap */
+ CHECK(http_request(c, "GET", "test", "/", NULL, NULL, 0, 4096, 5000, &r) == -2);
+ conn_close(c);
+ }
+ /* IMAP literals */
+ CHECK(imap_literal_size("* 1 FETCH (BODY[] {12}\r\n", 24) == 12);
+ CHECK(imap_literal_size("* 1 FETCH (BODY[] {12+}\r\n", 25) == 12);
+ CHECK(imap_literal_size("* OK done\r\n", 11) == -1);
+ CHECK(imap_literal_size("a {}\r\n", 6) == -1);
+ CHECK(imap_literal_size("a {18446744073709551615}\r\n", 26) == -2);
+ CHECK(imap_literal_size("a {99999999999}\r\n", 17) == 99999999999LL);
+ char err[96];
+ size_t len;
+ const char *ok = "* 1 FETCH (BODY[] {5}\r\nhello)\r\n";
+ Conn *c = serve(ok, strlen(ok), NULL, 0);
+ char *resp = imap_read_response(c, &len, 1 << 20, 1 << 20, err, sizeof err);
+ CHECK(resp && len == strlen(ok) && !memcmp(resp, ok, len) && resp[len] == 0);
+ free(resp);
+ conn_close(c);
+ static const char *bad[] = {
+ "* 1 FETCH (BODY[] {18446744073709551615}\r\nx",
+ "* 1 FETCH (BODY[] {18446744073709551614}\r\nx",
+ "* 1 FETCH (BODY[] {4294967296}\r\nx",
+ "* 1 FETCH (BODY[] {2000000}\r\nshort",
+ };
+ for (size_t i = 0; i < sizeof bad / sizeof bad[0]; i++) {
+ c = serve(bad[i], strlen(bad[i]), NULL, 0);
+ resp = imap_read_response(c, &len, 1 << 20, 1 << 20, err, sizeof err);
+ CHECK(resp == NULL);
+ free(resp);
+ conn_close(c);
+ }
+ /* literals of every size around the buffer growth boundaries (off-by-one hunting under ASan) */
+ for (int n = 0; n < 1100; n += (n < 70 ? 1 : 37)) {
+ char head[64];
+ int hl = snprintf(head, sizeof head, "* 1 FETCH (BODY[] {%d}\r\n", n);
+ char *msg = malloc((size_t)hl + (size_t)n + 4);
+ memcpy(msg, head, (size_t)hl);
+ memset(msg + hl, 'x', (size_t)n);
+ memcpy(msg + hl + n, ")\r\n", 3);
+ c = serve(msg, (size_t)hl + (size_t)n + 3, NULL, 0);
+ resp = imap_read_response(c, &len, 1 << 20, 1 << 20, err, sizeof err);
+ CHECK(resp && len == (size_t)hl + (size_t)n + 3 && resp[len] == 0);
+ free(resp);
+ conn_close(c);
+ free(msg);
+ }
+ /* a line that never ends */
+ c = serve("* OK ", 5, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 100000);
+ resp = imap_read_response(c, &len, 65536, 1 << 20, err, sizeof err);
+ CHECK(resp == NULL);
+ conn_close(c);
+ while (waitpid(-1, NULL, WNOHANG) > 0) {}
+ printf("mailnet-test: %d/%d checks ok\n", checks - fails, checks);
+ return fails ? 1 : 0;
+}
diff --git a/server/tests/vault_e2e.c b/server/tests/vault_e2e.c
index 6ec9ade..cecd472 100644
--- a/server/tests/vault_e2e.c
+++ b/server/tests/vault_e2e.c
@@ -6,6 +6,7 @@
* Se corre con `make build/vault-e2e && build/vault-e2e` (necesita build/lord-vault al lado). */
#include "vault/vclient.h"
#include "vault/vjson.h"
+#include "vault/vwire.h"
#include "vault/smem.h"
#include <fcntl.h>
@@ -159,6 +160,32 @@ int main(void) {
r = req(p, NULL, 0);
check(ok(r) && strstr(r, "CLAVE-DE-LICENCIA-1234"), "adjunto después de guardar y abrir");
+ /* App channel (vc_attach_app): what the sandboxed Passwords process (lord-server --app) uses.
+ * Same API on its own socket; a lock from the control channel reaches it as an event. */
+ {
+ int afd = vc_attach_app();
+ check(afd >= 0, "app channel: attach");
+ if (afd >= 0) {
+ VMsg m;
+ int got = 0, locked_ev = 0;
+ vw_send(afd, VW_REQ, 7, "{\"op\":\"list\"}", 13, NULL, 0);
+ while (!got && vw_recv(afd, &m, &vw_malloc) == 0) {
+ if (m.kind == VW_REP && m.id == 7) got = ok(m.json) && strstr(m.json, "Banco Ejemplo") != NULL;
+ vw_msg_free(&m, &vw_malloc);
+ }
+ check(got, "app channel: list over its own socket");
+ r = req("{\"op\":\"lock\"}", NULL, 0);
+ for (int k = 0; k < 8 && !locked_ev && vw_recv(afd, &m, &vw_malloc) == 0; k++) {
+ if (m.kind == VW_EVT && strstr(m.json, "\"locked\"")) locked_ev = 1;
+ vw_msg_free(&m, &vw_malloc);
+ }
+ check(locked_ev, "app channel: lock event");
+ close(afd);
+ r = req("{\"op\":\"unlock\",\"method\":\"password\",\"password\":\"Contraseña maestra 1\"}", NULL, 0);
+ check(ok(r), "unlock again after the app channel closed");
+ }
+ }
+
/* archivo llave nuevo (como en un pendrive) + abrir con él */
snprintf(f, sizeof f, "%s/pendrive.key", home);
fd = openw(f);
diff --git a/tools/build-theme.mjs b/tools/build-theme.mjs
index 17e2fba..c8fc9c4 100644
--- a/tools/build-theme.mjs
+++ b/tools/build-theme.mjs
@@ -21,8 +21,14 @@ const appsPlugin = {
return `import * as A${i} from ${JSON.stringify(path.join(base, 'index.jsx'))};\n` +
`import M${i} from ${JSON.stringify(path.join(base, 'manifest.json'))};`;
});
- const list = ids.map((_, i) => `{ ...M${i}, Component: A${i}.default, Icon: A${i}.Icon }`).join(',\n ');
- return { contents: `${lines.join('\n')}\nexport const apps = [\n ${list}\n];\n`, resolveDir: root, loader: 'js' };
+ // "process": "isolated": a built-in app that runs as its own sandboxed process (its window in
+ // the theme only starts it; see sdk/packages.js isolatedApp and buildSysApps below)
+ const iso = ids.map((id) => JSON.parse(fs.readFileSync(path.join(dir, id, 'manifest.json'), 'utf8')).process === 'isolated');
+ const list = ids.map((_, i) => (iso[i]
+ ? `{ ...M${i}, isolated: true, Component: isolatedApp(M${i}.id, A${i}.default), Icon: A${i}.Icon }`
+ : `{ ...M${i}, Component: A${i}.default, Icon: A${i}.Icon }`)).join(',\n ');
+ const head = iso.some(Boolean) ? `import { isolatedApp } from ${JSON.stringify(path.join(root, 'sdk', 'packages.js'))};\n` : '';
+ return { contents: `${head}${lines.join('\n')}\nexport const apps = [\n ${list}\n];\n`, resolveDir: root, loader: 'js' };
});
},
};
@@ -67,7 +73,48 @@ async function buildAppHost() {
console.log(`app-host: ${(bytes / 1024).toFixed(0)} KB en ${Date.now() - t0} ms`);
}
+// Built-in apps with "process": "isolated" (Passwords): their app.js for `lord-server --app <id>`,
+// built like an .lpk (React and the SDK come from the app host), into assets/sysapps/<id>/.
+// lord-server prefers this read-only system package over any user package with the same id.
+async function buildSysApps() {
+ const dir = path.join(root, 'apps');
+ const sharedPlugin = {
+ name: 'lordos-shared',
+ setup(b) {
+ b.onResolve({ filter: /^(react|react\/jsx-runtime|@lordos\/sdk|@lordos\/runtime)$/ }, (a) => ({ path: a.path, namespace: 'lordos-shared' }));
+ b.onLoad({ filter: /.*/, namespace: 'lordos-shared' }, (a) => ({
+ contents: `module.exports = globalThis.__lordos.require(${JSON.stringify(a.path)});`, loader: 'js',
+ }));
+ },
+ };
+ for (const id of fs.readdirSync(dir).sort()) {
+ const mf = path.join(dir, id, 'manifest.json');
+ if (!fs.existsSync(mf)) continue;
+ const manifest = JSON.parse(fs.readFileSync(mf, 'utf8'));
+ if (manifest.process !== 'isolated') continue;
+ const t0 = Date.now();
+ const out = path.join(root, 'assets', 'sysapps', id);
+ fs.mkdirSync(out, { recursive: true });
+ const result = await build({
+ entryPoints: [path.join(dir, id, 'index.jsx')],
+ bundle: true, write: false, format: 'iife', globalName: '__lordosApp', target: 'es2020', minify: true,
+ jsx: 'automatic', plugins: [sharedPlugin], define: { 'process.env.NODE_ENV': '"production"' }, logLevel: 'warning',
+ });
+ fs.writeFileSync(path.join(out, 'app.js'), result.outputFiles[0].contents);
+ fs.writeFileSync(path.join(out, 'manifest.json'), `${JSON.stringify(manifest, null, 2)}\n`);
+ // the app process reads the texts of its own namespace from the package (lord.locale.catalog)
+ for (const lang of fs.readdirSync(path.join(root, 'assets', 'locales'))) {
+ const src = path.join(root, 'assets', 'locales', lang, `${id}.json`);
+ if (!fs.existsSync(src)) continue;
+ fs.mkdirSync(path.join(out, 'locales'), { recursive: true });
+ fs.copyFileSync(src, path.join(out, 'locales', `${lang}.json`));
+ }
+ console.log(`system app ${id}: ${(result.outputFiles[0].contents.length / 1024).toFixed(0)} KB in ${Date.now() - t0} ms`);
+ }
+}
+
const all = fs.readdirSync(path.join(root, 'themes'))
.filter((d) => fs.existsSync(path.join(root, 'themes', d, 'index.jsx')));
-for (const name of (names.length ? names : all).filter((n) => n !== 'app-host')) await buildTheme(name);
+for (const name of (names.length ? names : all).filter((n) => n !== 'app-host' && n !== 'sysapps')) await buildTheme(name);
if (!names.length || names.includes('app-host')) await buildAppHost();
+if (!names.length || names.includes('sysapps')) await buildSysApps();
diff --git a/tools/iso/build.sh b/tools/iso/build.sh
index 6bd109c..44b5f62 100755
--- a/tools/iso/build.sh
+++ b/tools/iso/build.sh
@@ -34,8 +34,9 @@ PKGS_BASE="linux-image-amd64 initramfs-tools live-boot live-boot-initramfs-tools
PKGS_LORDOS="libwayland-server0 libwayland-client0 libxkbcommon0 xkb-data pipewire pipewire-pulse pipewire-alsa wireplumber rtkit
alsa-ucm-conf wpasupplicant openvpn fonts-noto-core fonts-noto-cjk fonts-noto-color-emoji libthai-data
skkdic rime-data-pinyin-simp fonts-dejavu-core
- libpoppler-glib8t64 libarchive13t64 poppler-data cups avahi-daemon
- libavcodec61 libavformat61 libavutil59 libswscale8 libswresample5 libva2 libva-drm2 mesa-va-drivers"
+ libpoppler-glib8t64 libarchive13t64 poppler-data cups avahi-daemon exfatprogs ntfs-3g
+ libavcodec61 libavformat61 libavutil59 libswscale8 libswresample5 libva2 libva-drm2 mesa-va-drivers
+ bluez libspa-0.2-bluetooth power-profiles-daemon systemd-timesyncd shared-mime-info"
PKGS_FIRMWARE="firmware-amd-graphics firmware-misc-nonfree firmware-iwlwifi firmware-realtek firmware-atheros
firmware-sof-signed"
PKGS_GPU="libgl1-mesa-dri libegl1 libgles2 libgbm1 mesa-vulkan-drivers mesa-utils vulkan-tools glmark2-es2-wayland"
@@ -97,6 +98,7 @@ json.dump(d, open(p, "w"), indent=2)
PY
fi
# Firefox ESR: igual (el usuario lo cambia en Personalizar barra de herramientas > Barra de título)
+install -D -m 644 tools/iso/rootfs/etc/wireplumber/wireplumber.conf.d/lordos-bluez.conf "$CH/etc/wireplumber/wireplumber.conf.d/lordos-bluez.conf"
install -d "$CH/etc/firefox-esr"
printf '%s\n' '// LordOS: las ventanas de Firefox usan el marco del sistema (el del tema); se cambia en' \
'// Personalizar barra de herramientas > Barra de título, o en about:config.' \
diff --git a/tools/iso/mkdeb.sh b/tools/iso/mkdeb.sh
index 97c9c97..ca774fe 100755
--- a/tools/iso/mkdeb.sh
+++ b/tools/iso/mkdeb.sh
@@ -53,11 +53,14 @@ for d in themes/*/; do
install -m 644 "$d/theme.json" "$d/theme.bundle.js" "$L/themes/$n/"
[ -d "$d/assets" ] && cp -r "$d/assets" "$L/themes/$n/"
done
-cp -r assets/fonts assets/locales assets/shell assets/icons assets/monitor "$L/assets/"
+cp -r assets/fonts assets/locales assets/shell assets/icons assets/monitor assets/help "$L/assets/"
# el proceso de cada app aislada (lord-server --app) carga su runtime de acá
[ -f assets/app-host.bundle.js ] || { echo "falta assets/app-host.bundle.js (npm run build)" >&2; exit 1; }
install -m 644 assets/app-host.bundle.js "$L/assets/app-host.bundle.js"
+# system apps that run as their own sandboxed process (manifest "process": "isolated"; e.g. Passwords)
+[ -d assets/sysapps ] && cp -r assets/sysapps "$L/assets/"
install -m 755 tools/iso/rootfs/usr/lib/lordos/lordos-live-prep "$L/lordos-live-prep"
+install -D -m 644 tools/iso/rootfs/etc/wireplumber/wireplumber.conf.d/lordos-bluez.conf "$PKG/etc/wireplumber/wireplumber.conf.d/lordos-bluez.conf"
install -m 644 tools/iso/rootfs/etc/systemd/system/lordos.service "$PKG/usr/lib/systemd/system/lordos.service"
# temas GTK3 de LordOS (los elige el portal de ajustes según claro/oscuro)
install -d "$PKG/usr/share/themes"
@@ -118,7 +121,7 @@ Architecture: ${DEB_ARCH:-$(dpkg --print-architecture)}
Maintainer: LordOS <[email protected]>
Installed-Size: $SIZE
Depends: libc6 (>= 2.38), libwayland-server0 (>= 1.22), libwayland-client0 (>= 1.22), libxkbcommon0 (>= 1.5), libcrypt1, libssl3t64 | libssl3, passwd, procps, xkb-data$GPUDEPS$DOCDEPS$MEDIADEPS
-Recommends: pipewire-pulse, wireplumber, wpasupplicant, openvpn, fonts-noto-core, locales, tzdata, sudo, cups, cups-client, avahi-daemon, mesa-va-drivers
+Recommends: pipewire-pulse, wireplumber, wpasupplicant, openvpn, fonts-noto-core, locales, tzdata, sudo, cups, cups-client, avahi-daemon, mesa-va-drivers, bluez, libspa-0.2-bluetooth, power-profiles-daemon, systemd-timesyncd, shared-mime-info
Section: x11
Priority: optional
Homepage: https://github.com/lordbasex/LordOS
diff --git a/tools/iso/rootfs/etc/wireplumber/wireplumber.conf.d/lordos-bluez.conf b/tools/iso/rootfs/etc/wireplumber/wireplumber.conf.d/lordos-bluez.conf
new file mode 100644
index 0000000..ab99eab
--- /dev/null
+++ b/tools/iso/rootfs/etc/wireplumber/wireplumber.conf.d/lordos-bluez.conf
@@ -0,0 +1,7 @@
+# LordOS: lord-sessiond sessions are not logind seat sessions, so WirePlumber's seat
+# monitoring would never enable Bluetooth audio. See docs/SETTINGS.md.
+wireplumber.profiles = {
+ main = {
+ monitor.bluez.seat-monitoring = disabled
+ }
+}