Compare commits

..
18 changed files with 171 additions and 383 deletions

No files matched your search

@@ -54,8 +54,7 @@ class FaceclawCalendarProvider private constructor() {
* boundaries the provider stores them as.
*/
@JvmStatic
@JvmOverloads
fun getUpcomingEventsJson(context: Context?, maxEvents: Int, windowMs: Long, selectedCalendarIdsJson: String = "null"): String {
fun getUpcomingEventsJson(context: Context?, maxEvents: Int, windowMs: Long): String {
if (context == null || maxEvents <= 0) {
return "[]"
}
@@ -74,21 +73,11 @@ class FaceclawCalendarProvider private constructor() {
val events = ArrayList<Event>()
var cursor: Cursor? = null
try {
// Filter instances before the cutoff/limit so excluded calendars
// cannot crowd out selected calendars, including recurrences.
val ids = if (selectedCalendarIdsJson == "null") null else JSONArray(selectedCalendarIdsJson)
if (ids != null && ids.length() == 0) return "[]"
val args = ids?.let { values -> Array(values.length()) { index ->
values.getString(index).also { require(it.matches(Regex("[0-9]+"))) }
} }
val selection = args?.let {
CalendarContract.Instances.CALENDAR_ID + " IN (" + it.joinToString(",") { "?" } + ")"
}
cursor = context.contentResolver.query(
uri,
PROJECTION,
selection,
args,
null,
null,
CalendarContract.Instances.BEGIN + " ASC")
if (cursor != null) {
val utc = Calendar.getInstance(TimeZone.getTimeZone("UTC"))
@@ -129,33 +118,6 @@ class FaceclawCalendarProvider private constructor() {
return out.toString()
}
@JvmStatic
fun getCalendarsJson(context: Context?): String {
if (context == null) return "[]"
val out = JSONArray()
try {
context.contentResolver.query(
CalendarContract.Calendars.CONTENT_URI,
arrayOf(CalendarContract.Calendars._ID, CalendarContract.Calendars.CALENDAR_DISPLAY_NAME,
CalendarContract.Calendars.ACCOUNT_NAME, CalendarContract.Calendars.ACCOUNT_TYPE),
null, null, CalendarContract.Calendars.CALENDAR_DISPLAY_NAME + " ASC",
)?.use { cursor ->
while (cursor.moveToNext()) {
out.put(JSONObject().apply {
put("id", cursor.getLong(0).toString())
put("name", cursor.getString(1) ?: "")
put("accountName", cursor.getString(2) ?: "")
put("accountType", cursor.getString(3) ?: "")
})
}
}
} catch (t: Throwable) {
Log.w(TAG, "failed to read calendars", t)
return "[]"
}
return out.toString()
}
private fun readEvent(cursor: Cursor, utc: Calendar, local: Calendar): Event {
val allDay = cursor.getInt(4) != 0
var startMs = cursor.getLong(2)
-5
View File
@@ -3,7 +3,6 @@ import { invalidateCalendarCache, onCalendarChanged } from "../../native/calenda
import { makeImageWindowIcon, windowIcon } from "../../ui/shell/chrome-layer";
import { CalendarLayer } from "./calendar";
import { renderCalendarDateIcon } from "./calendar-icon";
import { calendarSelectionMenuItems } from "./calendar-filter";
import {
createInProcessWindow,
YieldAtRootLayer,
@@ -45,10 +44,6 @@ export function createCalendarAppWindow(options: InProcessAppOptions): InProcess
icon: "calendar",
drawIcon: makeImageWindowIcon(renderCalendarDateIcon, windowIcon("calendar", "Ca")),
closeable: true,
menuItems: () => calendarSelectionMenuItems().map(item => ({ ...item, onSelect: (ctx, menu) => {
ctx.stack.pop();
return item.onSelect(ctx, menu);
} })),
actions: options.actions,
baseLayer: new YieldAtRootLayer(new CalendarLayer(requestPermission)),
submitFrame: options.submitFrame,
-94
View File
@@ -1,94 +0,0 @@
import { getDefaultSmallFont } from "../../graphics/ui-fonts";
import { type GrayImage } from "../../graphics/image";
import { truncateText } from "../../graphics/textwrap";
import { readCalendarSelection, setCalendarSelection } from "../../native/calendar-selection";
import { readAvailableCalendars } from "../../native/calendar-sources";
import { hasCalendarPermission } from "../../native/calendar-permissions";
import { type InputEvent } from "../../ui/gestures";
import { type Layer, type LayerContext, type PaintBelow } from "../../ui/layers";
import { drawToggleMenuItem, MenuLayer, type MenuItem } from "../../ui/menu";
/** Shared preference for every Android calendar reader. */
export class CalendarFilterLayer implements Layer {
private menu: MenuLayer | null = null;
private width = 0;
private keys: string[] = [];
private currentMenu(ctx: LayerContext): MenuLayer {
const calendars = readAvailableCalendars().sort((a, b) =>
a.name.localeCompare(b.name) || a.accountName.localeCompare(b.accountName) || a.id.localeCompare(b.id));
const selection = readCalendarSelection();
const known = new Set(calendars.map(calendar => calendar.id));
const keys = ["all", "none"];
const toggle = (id: string) => {
// Leaving all mode snapshots the current calendars. Newly added calendars
// then stay excluded until selected individually or all mode is restored.
const ids = new Set(readCalendarSelection() ?? calendars.map(calendar => calendar.id));
if (ids.has(id)) ids.delete(id); else ids.add(id);
setCalendarSelection(Array.from(ids));
};
const items: MenuItem[] = [{
label: "All calendars",
description: "Include all calendars, including calendars added later.",
onSelect: () => setCalendarSelection(null),
render: ({ image, x, y, width, selected }) => drawToggleMenuItem(image, getDefaultSmallFont(), x, y, width,
"All calendars", readCalendarSelection() === null, selected),
}, {
label: "No calendars",
onSelect: () => setCalendarSelection([]),
render: ({ image, x, y, width, selected }) => drawToggleMenuItem(image, getDefaultSmallFont(), x, y, width,
"No calendars", readCalendarSelection()?.length === 0, selected),
}];
const rows = [
...calendars.map(calendar => ({ id: calendar.id,
label: `${calendar.name || "(unnamed)"} / ${calendar.accountName || "Local"} (${calendar.accountType || "local"}) #${calendar.id}` })),
...(selection ?? []).filter(id => !known.has(id)).map(id => ({ id, label: `Unavailable calendar #${id}` })),
];
for (const row of rows) {
keys.push(`calendar:${row.id}`);
items.push({
label: row.label,
description: row.label,
onSelect: () => toggle(row.id),
render: ({ image, x, y, width, selected }) => {
const font = getDefaultSmallFont();
const ids = readCalendarSelection();
drawToggleMenuItem(image, font, x, y, width, truncateText(font, row.label, width - 48),
ids === null || ids.includes(row.id), selected);
},
});
}
if (!calendars.length) items.push({
label: hasCalendarPermission() ? "No calendars available" : "Grant calendar permission on your phone",
disabled: true, onSelect: () => {},
});
const key = this.menu?.selectedIndex != null ? this.keys[this.menu.selectedIndex] : "all";
const index = Math.max(0, keys.indexOf(key ?? "all"));
this.keys = keys;
const width = ctx.stack.getBaseSize().width;
if (!this.menu || this.width !== width) {
this.width = width;
this.menu = new MenuLayer("Calendars displayed", items, {
x: 8, y: 8, width: width - 16, opaque: true, showBorder: false,
footer: "Shared by Calendar and Glanceboard",
}).selectItem(index);
} else this.menu.setItems(items, index);
return this.menu;
}
paint(ctx: LayerContext, paintBelow: PaintBelow): GrayImage {
return this.currentMenu(ctx).paint(ctx, paintBelow);
}
async handleInput(event: InputEvent, ctx: LayerContext): Promise<void> {
await this.currentMenu(ctx).handleInput(event, ctx);
}
}
export function calendarSelectionMenuItems(): MenuItem[] {
return global.isAndroid ? [{
label: "Calendars displayed",
description: "Choose the calendars used by Calendar, Glanceboard and other calendar views.",
onSelect: ctx => ctx.stack.push(new CalendarFilterLayer()),
}] : [];
}
+1 -2
View File
@@ -1,6 +1,5 @@
import { type GlanceWidgetDefinition, type GlanceWidgetId } from "../widget";
import { CalendarWidget } from "./calendar-widget";
import { calendarSelectionMenuItems } from "../../calendar/calendar-filter";
import { CompassWidget } from "./compass-widget";
import { MusicWidget, musicSettingsMenuItems } from "./music-widget";
import { NightscoutWidget } from "./nightscout-widget";
@@ -12,7 +11,7 @@ import { HealthWidget } from "./health-widget";
/** Every widget a board slot can hold. */
export const GLANCE_WIDGETS: readonly GlanceWidgetDefinition[] = [
{ id: "system-card", label: "System card", settingsMenuItems: systemCardSettingsMenuItems, create: () => new SystemCardWidget() },
{ id: "calendar", label: "Calendar", tall: true, settingsMenuItems: calendarSelectionMenuItems, create: () => new CalendarWidget() },
{ id: "calendar", label: "Calendar", tall: true, create: () => new CalendarWidget() },
{ id: "terminal", label: "Terminal", tall: true, create: () => new TerminalWidget() },
{ id: "t3code", label: "T3 Code", tall: true, create: () => new T3CodeWidget() },
{ id: "nightscout", label: "Nightscout", create: () => new NightscoutWidget() },
+47 -3
View File
@@ -121,6 +121,7 @@ export type DashboardSnapshot = {
* glasses, and this says which harmless thing is actually going on.
*/
displayPreviewMessage: string;
silentModeFeedback: string;
activeTextSettingId: string | null;
activeTextEditorTitle: string;
activeTextSettingTitle: string;
@@ -294,6 +295,9 @@ class DashboardController {
/** The screen area displayPreview shows (Preview scaling), or null for the whole panel. */
private displayPreviewCrop: ScreenRect | null = null;
private silentMode = false;
private silentModeFeedback = "";
private silentModeFeedbackGeneration = 0;
private silentModeFeedbackTimer: ReturnType<typeof setTimeout> | null = null;
// Brightness value last pushed to the glasses; see pushBrightness.
private lastPushedBrightness: string | null = null;
// Last battery level the glasses reported, kept across disconnects so a
@@ -1142,6 +1146,7 @@ class DashboardController {
status: this.status,
displayPreview: this.displayPreview,
displayPreviewMessage: this.displayPreviewMessage(),
silentModeFeedback: this.silentModeFeedback,
activeTextSettingId: primaryTextSetting?.id ?? null,
activeTextEditorTitle: this.activeTextEditorTitle,
activeTextSettingTitle: primaryTextSetting?.editorTitle ?? "",
@@ -1181,6 +1186,43 @@ class DashboardController {
* charging and silent mode both make the display unavailable while BLE stays
* up, and a battery that just ran out simply stops answering.
*/
private handleSilentMode(silent: boolean): void {
if (this.silentMode === silent) return;
this.silentMode = silent;
const generation = ++this.silentModeFeedbackGeneration;
if (this.silentModeFeedbackTimer !== null) clearTimeout(this.silentModeFeedbackTimer);
this.silentModeFeedbackTimer = null;
this.silentModeFeedback = silent
? "Silent mode enabled — hold both touchpads to exit"
: "Silent mode disabled";
if (!silent) {
void this.showSilentModeExit(generation).catch(error => {
this.appendLog(`silent-mode exit feedback failed: ${this.formatError(error)}`);
});
this.silentModeFeedbackTimer = setTimeout(() => {
this.silentModeFeedbackTimer = null;
this.silentModeFeedback = "";
this.emit();
}, 5000);
}
this.emit();
}
private async showSilentModeExit(generation: number): Promise<void> {
if (this.phase !== "connected" || this.silentMode || this.glassesLocked) return;
// The firmware powered the lenses down, and Faceclaw may have gone to
// sleep/suspended EvenHub meanwhile. Reusing the ordinary wake barrier is
// essential: rendering an alert into the retained surface alone is invisible.
this.cancelEvenHubSuspendTimer();
shell.wake("sidebar");
const ready = await this.ensureEvenHubSessionActive();
if (!ready || generation !== this.silentModeFeedbackGeneration || this.silentMode ||
this.phase !== "connected" || this.glassesLocked) return;
shell.showAlert("Silent mode disabled");
shell.foregroundWindow()?.requestRender();
this.requestShellRender();
}
private displayPreviewMessage(): string {
if (this.phase === "charging") {
return chargingPreviewMessage(this.glassesDisplayState());
@@ -1604,9 +1646,7 @@ class DashboardController {
});
});
this.offSilentMode = communicator.onSilentMode((silent) => {
if (this.silentMode === silent) return;
this.silentMode = silent;
this.emit();
this.handleSilentMode(silent);
});
this.offWearState = communicator.onWearState((wearing) => {
this.handleWearState(wearing);
@@ -2984,6 +3024,10 @@ class DashboardController {
// Kept across "connecting": silent mode blocks app launches, so it can
// itself cause the reconnect churn, and Java re-reports it either way.
this.silentMode = false;
this.silentModeFeedbackGeneration++;
if (this.silentModeFeedbackTimer !== null) clearTimeout(this.silentModeFeedbackTimer);
this.silentModeFeedbackTimer = null;
this.silentModeFeedback = "";
}
this.emit();
}
-19
View File
@@ -1,19 +0,0 @@
import { getStringSetting, setStringSetting } from "./settings-store";
export const CALENDAR_SELECTION_KEY = "calendar.selectedIds";
/** null means all calendars (including future ones); [] explicitly means none. */
export function readCalendarSelection(): string[] | null {
try {
const value = JSON.parse(getStringSetting(CALENDAR_SELECTION_KEY, "null"));
if (value === null) return null;
if (!Array.isArray(value) || !value.every(id => typeof id === "string" && /^\d+$/.test(id))) return null;
return Array.from(new Set<string>(value));
} catch {
return null;
}
}
export function setCalendarSelection(ids: readonly string[] | null): void {
if (ids !== null && !ids.every(id => /^\d+$/.test(id))) throw new Error("Invalid calendar ID");
setStringSetting(CALENDAR_SELECTION_KEY, JSON.stringify(ids === null ? null : Array.from(new Set(ids))));
}
-22
View File
@@ -1,22 +0,0 @@
import { Utils } from "@nativescript/core";
import { hasCalendarPermission } from "./calendar-permissions";
declare const com: any;
export type CalendarSource = { id: string; name: string; accountName: string; accountType: string };
/** Android calendar IDs survive renames and distinguish equal display names. */
export function readAvailableCalendars(): CalendarSource[] {
if (!global.isAndroid || !hasCalendarPermission()) return [];
try {
const context = Utils.android.getApplicationContext();
if (!context) return [];
const parsed = JSON.parse(String(com.faceclaw.app.FaceclawCalendarProvider.getCalendarsJson(context)));
if (!Array.isArray(parsed)) return [];
return parsed.filter(row => row && typeof row.id === "string" && /^\d+$/.test(row.id))
.map(row => ({ id: row.id, name: String(row.name ?? ""),
accountName: String(row.accountName ?? ""), accountType: String(row.accountType ?? "") }));
} catch {
return [];
}
}
+3 -15
View File
@@ -2,8 +2,6 @@ import { Utils } from "@nativescript/core";
import { hasCalendarPermission } from "../g2/android-permissions";
import { spanCurrent } from "./frame-timings";
import { type CalendarEvent, type CalendarReadState } from "./calendar-types";
import { CALENDAR_SELECTION_KEY, readCalendarSelection } from "./calendar-selection";
import { onSettingsStoreChanged } from "./settings-store";
export type { CalendarEvent } from "./calendar-types";
declare const com: any;
@@ -15,21 +13,14 @@ declare const com: any;
*/
// Android reads synchronously; iOS notifies subscribers after background reads.
export function onCalendarChanged(listener: () => void): () => void {
return onSettingsStoreChanged(key => {
if (key === CALENDAR_SELECTION_KEY || key == null) {
invalidateCalendarCache();
listener();
}
});
}
export function onCalendarChanged(_listener: () => void): () => void { return () => {}; }
export function getCalendarReadState(): CalendarReadState { return "ready"; }
const DEFAULT_MAX_EVENTS = 50;
const DEFAULT_WINDOW_MS = 14 * 24 * 60 * 60 * 1000;
const CACHE_MS = 30_000;
let cache: { events: CalendarEvent[]; atMs: number; maxEvents: number; windowMs: number; selection: string } | null = null;
let cache: { events: CalendarEvent[]; atMs: number; maxEvents: number; windowMs: number } | null = null;
/**
* Upcoming events from now through the given window, ordered by start time.
@@ -44,11 +35,9 @@ export function readUpcomingEvents(
if (!global.isAndroid || !hasCalendarPermission()) return [];
const now = Date.now();
const selection = JSON.stringify(readCalendarSelection());
if (
!forceRefresh &&
cache &&
cache.selection === selection &&
cache.maxEvents === maxEvents &&
cache.windowMs === windowMs &&
now - cache.atMs < CACHE_MS
@@ -66,7 +55,6 @@ export function readUpcomingEvents(
context,
Math.max(0, Math.round(maxEvents)),
Math.max(0, Math.round(windowMs)),
selection,
),
),
);
@@ -74,7 +62,7 @@ export function readUpcomingEvents(
const events = Array.isArray(parsed)
? parsed.map(normalizeEvent).filter((event): event is CalendarEvent => Boolean(event))
: [];
cache = { events, atMs: now, maxEvents, windowMs, selection };
cache = { events, atMs: now, maxEvents, windowMs };
return events;
} catch {
return [];
+3
View File
@@ -74,6 +74,9 @@
class="ble-bandwidth-indicator"
horizontalAlignment="center"
verticalAlignment="bottom" />
<Label text="{{ silentModeFeedback }}" visibility="{{ silentModeFeedbackVisibility }}"
textWrap="true" horizontalAlignment="center" verticalAlignment="top"
margin="12" padding="12" backgroundColor="#333333" color="white" borderRadius="8" />
<ScrollView
class="warnings-modal"
visibility="{{ warningsModalVisibility }}"
+13
View File
@@ -37,6 +37,7 @@ export class MainViewModel extends RemoteControlsViewModel {
private _status = "Disconnected.";
private _displayPreview: ImageSource | null = null;
private _displayPreviewMessage = "";
private _silentModeFeedback = "";
private _layoutOrientation: LayoutOrientation = this.readLayoutOrientation();
private _landscapePreviewWidth = 0;
private _landscapePreviewHeight = 0;
@@ -90,6 +91,7 @@ export class MainViewModel extends RemoteControlsViewModel {
this.previewMode = snapshot.previewMode;
this.displayPreview = snapshot.displayPreview;
this.displayPreviewMessage = snapshot.displayPreviewMessage;
this.silentModeFeedback = snapshot.silentModeFeedback ?? "";
this.phase = snapshot.phase;
this.batteryLine = formatBatteryLine(
snapshot.batteries,
@@ -216,6 +218,17 @@ export class MainViewModel extends RemoteControlsViewModel {
}
}
get silentModeFeedback(): string { return this._silentModeFeedback; }
set silentModeFeedback(value: string) {
if (this._silentModeFeedback === value) return;
this._silentModeFeedback = value;
this.notifyPropertyChange("silentModeFeedback", value);
this.notifyPropertyChange("silentModeFeedbackVisibility", this.silentModeFeedbackVisibility);
}
get silentModeFeedbackVisibility(): "visible" | "collapse" {
return this._silentModeFeedback ? "visible" : "collapse";
}
get hasDisplayPreview(): boolean {
return this._displayPreview !== null;
}
-29
View File
@@ -1,29 +0,0 @@
# Android calendar selection validation
Software: `npm test` and `bash lint.sh` for changed TypeScript files.
`tests/calendar-selection.test.cjs` covers preference reloads, all versus none,
duplicate names/accounts, selection changes with cached readers, deleted IDs,
recurrence occurrences and forwarding the selection to the provider before its
limit. Provider SQL structure is checked statically; the mocked bridge does not
replace an Android CalendarContract integration test.
On an Android device (pending):
1. With no saved preference, compare events with the current release.
2. Open Calendar's window menu > Calendars displayed (also available through
Glanceboard's Calendar widget settings). Select between two equal-named
calendars belonging to different accounts. Check ID/account labels.
3. Create more than 50 early events in an excluded calendar and later recurring
events in a selected calendar. Check those later occurrences still appear.
4. Select “No calendars”: Calendar, Glanceboard and any other readers must be
empty immediately. Restart and confirm the selection persists.
5. Select individual calendars, rename one, then delete one. Remaining selections
must stay unchanged. A missing selected ID is shown as unavailable and may be
removed; it never causes a fallback to all calendars.
6. Select “All calendars”, add a calendar, and check it is included. In individual
mode, newly added calendars stay excluded. Check all-day and timed recurring
events in both Calendar and Glanceboard, including timezone/DST boundaries.
IDs are Android CalendarContract IDs, stable across display-name changes within
an installation. Removing/re-adding an account can create new calendar IDs.
The iOS calendar reader and its behavior are unchanged; iOS selection is deferred.
+11
View File
@@ -0,0 +1,11 @@
# Silent-mode feedback
The firmware blanks the lenses and stops ordinary input while silent mode is active. App code cannot display an activation popup on lenses that the firmware has switched off. The phone now shows a persistent enabled banner with the exit gesture, and a five-second disabled banner on exit. On exit, unlocked glasses wake through the normal screen/EvenHub barrier before the alert popup is rendered. This also handles the shell falling asleep during a long silent period. Locked glasses keep the phone feedback without being woken. A generation check suppresses stale notices after re-entry or disconnect. Duplicate state reports do not repeat feedback, stale timers are cancelled, and disconnect clears the notice.
Silent-off firmware pushes are not reliable. The existing fallback read used the five-minute battery cadence. While silent mode is known to be on, settings are now polled every two seconds when the session is ready and the message queues are idle. Normal battery cadence and shutdown guards are retained. This bounds ordinary missing-push recovery without assuming a touch gesture always means silent mode ended.
Independent JavaScript suite: 1065 passed, 2 skipped. TypeScript and changed-source lint passed. Controller tests cover enabled/disabled notices, duplicates, timer cancellation, disconnect and sleeping-display recovery, locked displays, wake-barrier failure and stale async completion. A Kotlin session test checks the two-second silent cadence, normal cadence and shutdown guard. Kotlin compilation and hardware checks are tracked with the combined integration validation.
Hardware validation remains pending: both transitions via the temple gesture, missing exit push, phone background/foreground, lenses that are awake/asleep/locked, reconnect and charging. No firmware was flashed.
Follow-up after device-log inspection: both silent transitions arrived, but the exit could occur after the normal idle timeout. Exit now cancels pending suspension, wakes the shell, awaits the existing EvenHub/screen wake barrier and only then shows the notice. It resets idle activity through the ordinary wake path. Re-entry, disconnect, locking or a failed resume suppress stale asynchronous notices. Activation still turns the lenses off in firmware; phone feedback does not claim a lens-side activation popup.
@@ -37,6 +37,8 @@ class ConnectionOptions {
const val HEARTBEAT_FAILURE_DEADLINE_MS = 10_000
const val HEARTBEAT_READY_MS = 4_000
const val HEARTBEAT_URGENT_MS = 6_000
// Silent-off pushes are not reliable; promptly re-read the state while silent.
const val SILENT_MODE_POLL_MS = 2_000
const val BATTERY_REFRESH_INTERVAL_MS = 5 * 60_000
const val BATTERY_INPUT_QUIET_MS = 5_000
// Poll cadence while in charging mode; also bounds how quickly we notice
@@ -1041,8 +1041,9 @@ internal fun GlassesSessionCore.shouldPollBatteryLocked(now: Long): Boolean {
&& sessionReady
&& pendingMessages.isEmpty()
&& inFlightMessages.isEmpty()
&& now - lastConnectionOrInputAtMs >= ConnectionOptions.BATTERY_INPUT_QUIET_MS
&& (lastBatteryRefreshAtMs == 0L || now - lastBatteryRefreshAtMs >= ConnectionOptions.BATTERY_REFRESH_INTERVAL_MS)
&& (silentMode == 1 || now - lastConnectionOrInputAtMs >= ConnectionOptions.BATTERY_INPUT_QUIET_MS)
&& (lastBatteryRefreshAtMs == 0L || now - lastBatteryRefreshAtMs >=
if (silentMode == 1) ConnectionOptions.SILENT_MODE_POLL_MS else ConnectionOptions.BATTERY_REFRESH_INTERVAL_MS)
}
internal fun GlassesSessionCore.createBatteryQueryMessageLocked(): OutboundMessage {
-150
View File
@@ -1,150 +0,0 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const ts = require('typescript');
const source = file => fs.readFileSync(path.join(__dirname, '..', file), 'utf8');
function load(file, modules, globals = {}) {
const context = { exports: {}, require: name => {
assert.ok(name in modules, `Unexpected import ${name}`);
return modules[name];
}, ...globals };
vm.runInNewContext(ts.transpileModule(source(file), {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
}).outputText, context);
return context.exports;
}
function fixture(settings = new Map()) {
const listeners = new Set();
const storage = {
getStringSetting: (key, fallback) => settings.get(key) ?? fallback,
setStringSetting: (key, value) => { settings.set(key, value); for (const fn of listeners) fn(key); },
onSettingsStoreChanged: fn => { listeners.add(fn); return () => listeners.delete(fn); },
};
const prefs = load('app/native/calendar-selection.ts', { './settings-store': storage });
let permitted = true;
const calls = [];
const calendars = [
{ id: '1', name: 'Work', accountName: 'one@example.com', accountType: 'google' },
{ id: '2', name: 'Work', accountName: 'two@example.com', accountType: 'google' },
];
const events = [
{ id: 1, calendarId: '1', startMs: 10000, endMs: 20000, title: 'Excluded early' },
{ id: 9, calendarId: '2', startMs: 30000, endMs: 40000, title: 'Recurrence one' },
{ id: 9, calendarId: '2', startMs: 50000, endMs: 60000, title: 'Recurrence two' },
];
const modules = {
'@nativescript/core': { Utils: { android: { getApplicationContext: () => ({}) } } },
'../g2/android-permissions': { hasCalendarPermission: () => permitted },
'./calendar-permissions': { hasCalendarPermission: () => permitted },
'./frame-timings': { spanCurrent: (_name, fn) => fn() },
'./calendar-selection': prefs,
'./settings-store': storage,
};
const globals = { global: { isAndroid: true }, com: { faceclaw: { app: { FaceclawCalendarProvider: {
getCalendarsJson: () => JSON.stringify(calendars),
getUpcomingEventsJson: (_ctx, max, window, selection) => {
calls.push({ max, window, selection });
const ids = JSON.parse(selection);
return JSON.stringify(events.filter(event => ids === null || ids.includes(event.calendarId)).slice(0, max));
},
} } } } };
const api = load('app/native/calendar.ts', modules, globals);
const sources = load('app/native/calendar-sources.ts', modules, globals);
return { api, prefs, sources, modules, globals, settings, calls, calendars,
permissions: value => { permitted = value; } };
}
test('calendar selection distinguishes all and none, survives restart and rejects invalid data', () => {
const f = fixture();
assert.equal(f.prefs.readCalendarSelection(), null);
f.prefs.setCalendarSelection([]);
assert.deepEqual(Array.from(fixture(f.settings).prefs.readCalendarSelection()), []);
f.prefs.setCalendarSelection(['2', '2', '1']);
assert.deepEqual(Array.from(fixture(f.settings).prefs.readCalendarSelection()), ['2', '1']);
f.prefs.setCalendarSelection(null);
assert.equal(fixture(f.settings).prefs.readCalendarSelection(), null);
assert.throws(() => f.prefs.setCalendarSelection(['1 OR 1=1']));
for (const value of ['oops', '{}', '[false]', '["bad"]']) {
f.settings.set(f.prefs.CALENDAR_SELECTION_KEY, value);
assert.equal(f.prefs.readCalendarSelection(), null);
}
});
test('shared reader forwards IDs before limiting, preserves recurrence occurrences and invalidates all cached query variants', async () => {
const f = fixture();
assert.equal(f.api.readUpcomingEvents(1)[0].title, 'Excluded early');
f.api.readUpcomingEvents(1);
assert.equal(f.calls.length, 1);
let notifications = 0;
const off = f.api.onCalendarChanged(() => notifications++);
f.prefs.setCalendarSelection(['2']);
const rows = f.api.readUpcomingEvents(2);
assert.deepEqual(Array.from(rows, event => event.id), [9, 9]);
assert.equal(f.calls.at(-1).selection, '["2"]');
assert.equal(notifications, 1);
assert.equal((await f.api.readUpcomingEventsAsync(1))[0].title, 'Recurrence one');
off();
f.prefs.setCalendarSelection([]);
assert.equal(notifications, 1);
assert.equal(f.api.readUpcomingEvents(1).length, 0, 'selection cache key works even without subscriptions');
assert.equal(fixture(f.settings).api.readUpcomingEvents().length, 0);
f.prefs.setCalendarSelection(['999']);
assert.equal(f.api.readUpcomingEvents().length, 0, 'deleted calendar does not revert to all');
f.permissions(false);
assert.equal(f.api.readUpcomingEvents().length, 0);
assert.equal(f.sources.readAvailableCalendars().length, 0);
});
test('calendar menu distinguishes equal names by account and ID; all, none, deleted and individual selections share preferences', () => {
const f = fixture();
const { CalendarFilterLayer } = load('app/apps/calendar/calendar-filter.ts', {
'../../graphics/ui-fonts': { getDefaultSmallFont: () => ({}) },
'../../graphics/textwrap': { truncateText: (_font, text) => text },
'../../native/calendar-selection': f.prefs,
'../../native/calendar-sources': f.sources,
'../../native/calendar-permissions': { hasCalendarPermission: () => true },
'../../ui/menu': {
drawToggleMenuItem: () => {},
MenuLayer: class {
constructor(_title, items) { this.items = items; this.selectedIndex = 0; }
selectItem(index) { this.selectedIndex = index; return this; }
setItems(items, index) { this.items = items; this.selectedIndex = index; }
paint() { return this.items; }
},
},
}, f.globals);
const layer = new CalendarFilterLayer();
const ctx = { stack: { getBaseSize: () => ({ width: 576 }) } };
const rows = () => layer.paint(ctx, () => {});
assert.ok(rows()[2].label.includes('one@example.com'));
assert.ok(rows()[3].label.includes('two@example.com'));
rows()[2].onSelect();
assert.deepEqual(Array.from(f.prefs.readCalendarSelection()), ['2']);
rows()[1].onSelect();
assert.equal(f.api.readUpcomingEvents().length, 0);
rows()[3].onSelect();
assert.deepEqual(Array.from(f.prefs.readCalendarSelection()), ['2']);
f.calendars.pop();
const missing = rows().find(row => row.label === 'Unavailable calendar #2');
assert.ok(missing);
missing.onSelect();
assert.equal(f.prefs.readCalendarSelection().length, 0);
rows()[0].onSelect();
assert.equal(f.prefs.readCalendarSelection(), null);
});
test('Android provider restricts Instances with bound calendar IDs before cutoff and limit', () => {
const kotlin = source('App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawCalendarProvider.kt');
assert.match(kotlin, /Instances\.CALENDAR_ID/);
assert.match(kotlin, /if \(ids != null && ids.length\(\) == 0\) return "\[\]"/);
assert.match(kotlin, /PROJECTION,\s+selection,\s+args,/);
assert.ok(kotlin.indexOf('selection,\n args,') < kotlin.indexOf('events.take(limit)'));
assert.match(kotlin, /CalendarContract\.Calendars\._ID/);
assert.match(kotlin, /CalendarContract\.Calendars\.ACCOUNT_NAME/);
for (const file of ['app/apps/calendar/calendar.ts', 'app/apps/glanceboard/widgets/calendar-widget.ts']) {
assert.match(source(file), /readUpcomingEvents/);
assert.match(source(file), /native\/calendar"/);
}
});
-1
View File
@@ -199,7 +199,6 @@ test('Calendar window subscribes, refreshes periodically, and cleans up on close
'../../native/calendar': { onCalendarChanged: fn => { listener = fn; return () => unsubscribed++; } },
'../../ui/shell/chrome-layer': { makeImageWindowIcon() {}, windowIcon() {} },
'./calendar': { CalendarLayer: class {} }, './calendar-icon': {},
'./calendar-filter': { calendarSelectionMenuItems: () => [] },
'../../ui/shell/in-process-window': { YieldAtRootLayer: class {}, createInProcessWindow: value => { options = value; return app; } },
}, { setInterval: fn => { tick = fn; return 1; }, clearInterval: () => cleared++ });
createCalendarAppWindow({ onClosed: () => closed++ });
@@ -316,6 +316,24 @@ private class Session {
}
class GlassesSessionCoreTest {
@Test fun silentModePollsPromptlyWithoutChangingNormalBatteryCadence() {
val s = Session()
val core = s.core
core.monitor.withLock {
core.sessionReady = true
core.silentMode = 1
core.lastBatteryRefreshAtMs = 8_000L
core.lastConnectionOrInputAtMs = 10_000L
assertFalse(core.shouldPollBatteryLocked(9_999L))
assertTrue(core.shouldPollBatteryLocked(10_000L))
core.silentMode = 0
assertFalse(core.shouldPollBatteryLocked(10_000L))
assertTrue(core.shouldPollBatteryLocked(308_000L))
core.shutdownRequested = true
assertFalse(core.shouldPollBatteryLocked(608_000L))
}
}
@Test fun brightnessConfigPrecedesFirstFrameAndSleepWakeFollowsComposites() {
val s = Session()
s.core.configureBrightness(false, 70, 2, 100, "0:0,1000:100", 280)
+67
View File
@@ -0,0 +1,67 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const vm = require('node:vm');
const ts = require('typescript');
function fixture() {
const source = ts.createSourceFile('controller.ts', fs.readFileSync('app/g2/dashboard-controller.ts', 'utf8'), ts.ScriptTarget.Latest, true);
const cls = source.statements.find(n => ts.isClassDeclaration(n) && n.name?.text === 'DashboardController');
const methods = cls.members.filter(n => ['handleSilentMode', 'showSilentModeExit', 'setPhase'].includes(n.name?.getText(source)));
const alerts = [], timers = new Map(); let next = 0, on = true, wakes = 0;
const context = { exports: {}, setTimeout: fn => { timers.set(++next, fn); return next; }, clearTimeout: id => timers.delete(id),
updateGlassesPresence() {}, shell: { isScreenOn: () => on, wake: () => { on = true; wakes++; }, showAlert: text => alerts.push(text),
foregroundWindow: () => ({ requestRender() {} }), setBatteryLevels() {}, getBatteryLevels: () => ({}) } };
vm.runInNewContext(ts.transpileModule(`export class Controller { ${methods.map(n => n.getText(source)).join('\n')} }`, {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
}).outputText, context);
const c = new context.exports.Controller();
Object.assign(c, { silentMode: false, silentModeFeedback: '', silentModeFeedbackTimer: null, silentModeFeedbackGeneration: 0, phase: 'connected', emit() {},
cancelEvenHubSuspendTimer() {}, ensureEvenHubSessionActive: async () => true, requestShellRender() {},
appendLog() {}, formatError: error => String(error) });
return { c, alerts, timers, wakes: () => wakes, dark: () => { on = false; }, expire() { const callbacks = [...timers.values()]; timers.clear(); callbacks.forEach(fn => fn()); } };
}
test('silent activation remains visible on phone; exit waits for the display wake barrier', async () => {
const h = fixture(); h.c.handleSilentMode(false);
assert.equal(h.c.silentModeFeedback, '');
h.c.handleSilentMode(true);
assert.match(h.c.silentModeFeedback, /enabled/); assert.equal(h.timers.size, 0); assert.equal(h.alerts.length, 0);
h.c.handleSilentMode(false);
assert.equal(h.c.silentModeFeedback, 'Silent mode disabled');
await new Promise(setImmediate);
assert.deepEqual(h.alerts, ['Silent mode disabled']);
h.expire(); assert.equal(h.c.silentModeFeedback, '');
});
test('repeated state reports do not duplicate feedback; an old timer cannot clear a new activation', async () => {
const h = fixture(); h.c.handleSilentMode(true); h.c.handleSilentMode(false);
h.c.handleSilentMode(false); await new Promise(setImmediate); assert.equal(h.alerts.length, 1);
h.c.handleSilentMode(true); h.expire();
assert.match(h.c.silentModeFeedback, /enabled/);
});
test('silent exit wakes a sleeping display before showing feedback but leaves locked glasses alone', async () => {
for (const locked of [false, true]) {
const h = fixture(); h.c.glassesLocked = locked; h.dark();
h.c.handleSilentMode(true); h.c.handleSilentMode(false); await new Promise(setImmediate);
assert.equal(h.wakes(), locked ? 0 : 1);
assert.equal(h.alerts.length, locked ? 0 : 1);
assert.equal(h.c.silentModeFeedback, 'Silent mode disabled');
}
});
test('an unavailable session, re-entry into silence or disconnect suppresses a stale exit popup', async () => {
for (const state of ['not-ready', 'silent', 'disconnected']) {
const h = fixture(); let finish;
h.c.ensureEvenHubSessionActive = () => new Promise(resolve => { finish = resolve; });
h.c.handleSilentMode(true); h.c.handleSilentMode(false);
assert.equal(h.alerts.length, 0);
if (state === 'silent') h.c.handleSilentMode(true);
if (state === 'disconnected') h.c.setPhase('disconnected');
finish(state !== 'not-ready'); await new Promise(setImmediate);
assert.equal(h.alerts.length, 0);
}
});
test('disconnect clears feedback and any pending timer without announcing a silent exit', () => {
const h = fixture(); h.c.handleSilentMode(true); h.c.handleSilentMode(false);
h.c.setPhase('disconnected');
assert.equal(h.c.silentModeFeedback, ''); assert.equal(h.timers.size, 0);
h.expire(); assert.equal(h.c.silentModeFeedback, '');
});