mirror of
https://git.undefined-dev.fr/Blendman974/faceclaw.git
synced 2026-11-19 21:03:09 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9e6bb8473a
|
No files matched your search
@@ -249,8 +249,6 @@ class FaceclawBleCommunicator(context: Context, rightAddress: String?, leftAddre
|
||||
|
||||
fun enableWearDetectionAndRequestState() = core.enableWearDetectionAndRequestState()
|
||||
|
||||
fun configureHeadUpWake(enabled: Int, angle: Int) = core.configureHeadUpWake(enabled, angle)
|
||||
|
||||
fun startBandwidthBenchmark(messageSize: Int, windowSize: Int, durationMs: Int): Boolean =
|
||||
core.startBandwidthBenchmark(messageSize, windowSize, durationMs)
|
||||
|
||||
|
||||
@@ -54,7 +54,8 @@ class FaceclawCalendarProvider private constructor() {
|
||||
* boundaries the provider stores them as.
|
||||
*/
|
||||
@JvmStatic
|
||||
fun getUpcomingEventsJson(context: Context?, maxEvents: Int, windowMs: Long): String {
|
||||
@JvmOverloads
|
||||
fun getUpcomingEventsJson(context: Context?, maxEvents: Int, windowMs: Long, selectedCalendarIdsJson: String = "null"): String {
|
||||
if (context == null || maxEvents <= 0) {
|
||||
return "[]"
|
||||
}
|
||||
@@ -73,11 +74,21 @@ 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,
|
||||
null,
|
||||
null,
|
||||
selection,
|
||||
args,
|
||||
CalendarContract.Instances.BEGIN + " ASC")
|
||||
if (cursor != null) {
|
||||
val utc = Calendar.getInstance(TimeZone.getTimeZone("UTC"))
|
||||
@@ -118,6 +129,33 @@ 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)
|
||||
|
||||
@@ -3,6 +3,7 @@ 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,
|
||||
@@ -44,6 +45,10 @@ 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,
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
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,5 +1,6 @@
|
||||
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";
|
||||
@@ -11,7 +12,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, create: () => new CalendarWidget() },
|
||||
{ id: "calendar", label: "Calendar", tall: true, settingsMenuItems: calendarSelectionMenuItems, 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() },
|
||||
|
||||
@@ -78,7 +78,7 @@ import { loadPersistedOpenApps, savePersistedOpenApps } from "../ui/shell/open-a
|
||||
import { appViewportRect, isOnSwitcherEdge, sidebarStripVisible, type ScreenRect, type WindowHeightMode } from "../ui/shell/geometry";
|
||||
import { type ContinuousCaptureOptions, type LayerActions, type TextSettingsEditToggle, type TranscriptionChoice } from "../ui/layers";
|
||||
import { type KeyboardInputSession } from "../ui/shell/keyboard-input";
|
||||
import { appSwitcherPositionSetting, statusBarPositionSetting, statusBarVisibilitySetting, windowBorderSetting, assistantAllowProactiveSetting, assistantBackendSetting, assistantBridgeHostSetting, assistantBridgePortSetting, assistantBridgeTokenSetting, getBrightnessPreferences, getHeadUpPreferences, displayLayoutSetting, navigateDisplayLayoutSetting, terminalDisplayLayoutSetting, elevenLabsApiKeySetting, getStringSettingById, openAiApiKeySetting, nightscoutApiTokenSetting, firmwareDebugFlagsSetting, whisperServerApiKeySetting, whisperServerLanguageSetting, whisperServerModelSetting, whisperServerUrlSetting, lockScreenEnabledSetting, nightscoutSiteUrlSetting, onAnySettingChanged, previewColorSetting, ringConnectionModeSetting, type RingConnectionMode, saveVoiceRecordingsSetting, sonioxApiKeySetting, screenTimeoutSetting, screenTimeoutSettingToMs, suspendEvenHubWhenScreenOffSetting, voiceProviderSetting, wakeWordActionSetting, type ConfigSettingString } from "../ui/dashboard-settings";
|
||||
import { appSwitcherPositionSetting, statusBarPositionSetting, statusBarVisibilitySetting, windowBorderSetting, assistantAllowProactiveSetting, assistantBackendSetting, assistantBridgeHostSetting, assistantBridgePortSetting, assistantBridgeTokenSetting, getBrightnessPreferences, displayLayoutSetting, navigateDisplayLayoutSetting, terminalDisplayLayoutSetting, elevenLabsApiKeySetting, getStringSettingById, openAiApiKeySetting, nightscoutApiTokenSetting, firmwareDebugFlagsSetting, whisperServerApiKeySetting, whisperServerLanguageSetting, whisperServerModelSetting, whisperServerUrlSetting, lockScreenEnabledSetting, nightscoutSiteUrlSetting, onAnySettingChanged, previewColorSetting, ringConnectionModeSetting, type RingConnectionMode, saveVoiceRecordingsSetting, sonioxApiKeySetting, screenTimeoutSetting, screenTimeoutSettingToMs, suspendEvenHubWhenScreenOffSetting, voiceProviderSetting, wakeWordActionSetting, type ConfigSettingString } from "../ui/dashboard-settings";
|
||||
import { isIgnoringBatteryOptimizations, requestIgnoreBatteryOptimizations } from "../native/battery-optimization";
|
||||
import {
|
||||
getInstalledEvenHubAppById,
|
||||
@@ -296,7 +296,6 @@ class DashboardController {
|
||||
private silentMode = false;
|
||||
// Brightness value last pushed to the glasses; see pushBrightness.
|
||||
private lastPushedBrightness: string | null = null;
|
||||
private lastPushedHeadUp: string | null = null;
|
||||
// Last battery level the glasses reported, kept across disconnects so a
|
||||
// drop-off right after a low reading can be explained as a flat battery.
|
||||
private lastHeadsetBattery: number | null = null;
|
||||
@@ -477,7 +476,6 @@ class DashboardController {
|
||||
// Apply a firmware-debug-flags toggle live while connected (Java dedups).
|
||||
this.pushFirmwareDebugFlags();
|
||||
this.pushBrightness();
|
||||
this.pushHeadUpPreferences();
|
||||
this.syncEvenHubScreenOffSetting();
|
||||
// Display mode size first: a reflow repositions every surface too, so
|
||||
// the band-position check after it then has nothing left to do.
|
||||
@@ -1086,19 +1084,6 @@ class DashboardController {
|
||||
});
|
||||
}
|
||||
|
||||
private pushHeadUpPreferences(force = false): void {
|
||||
if (!global.isAndroid || !this.communicator) return;
|
||||
const { enabled, angle } = getHeadUpPreferences();
|
||||
if (enabled < 0 && angle < 0) return;
|
||||
const value = JSON.stringify({ enabled, angle });
|
||||
if (!force && value === this.lastPushedHeadUp) return;
|
||||
this.lastPushedHeadUp = value;
|
||||
void this.communicator.configureHeadUpWake(enabled, angle).catch(error => {
|
||||
this.lastPushedHeadUp = null;
|
||||
this.appendLog(`head-up configuration failed: ${this.formatError(error)}`);
|
||||
});
|
||||
}
|
||||
|
||||
/** Save the occupied part of the composited screen as a 4-bit grayscale PNG. */
|
||||
saveScreenshot(): string {
|
||||
const path = this.display?.saveScreenshot(shell.screenshotCropRect()) ?? "";
|
||||
@@ -1548,7 +1533,6 @@ class DashboardController {
|
||||
// ahead of them. Mirrors ensurePreviewDisplay.
|
||||
await communicator.configureCompositorScreen(G2_LENS_WIDTH, G2_LENS_HEIGHT);
|
||||
await communicator.configureBrightness(getBrightnessPreferences());
|
||||
this.pushHeadUpPreferences(true);
|
||||
this.offState = communicator.onStateChange((state) => {
|
||||
if (state.phase !== "connected") resetRingInputFilter();
|
||||
if (isHaltedSessionPhase(state.phase)) {
|
||||
@@ -1586,7 +1570,6 @@ class DashboardController {
|
||||
// mode-7 control message once the dashboard container is warmed up.
|
||||
this.pushFirmwareDebugFlags();
|
||||
this.pushBrightness(true);
|
||||
this.pushHeadUpPreferences(true);
|
||||
this.handRingBackToGlassesIfNeeded();
|
||||
}
|
||||
if (mappedPhase !== "connected" && mappedPhase !== "charging") {
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
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))));
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
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 [];
|
||||
}
|
||||
}
|
||||
+15
-3
@@ -2,6 +2,8 @@ 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;
|
||||
@@ -13,14 +15,21 @@ declare const com: any;
|
||||
*/
|
||||
|
||||
// Android reads synchronously; iOS notifies subscribers after background reads.
|
||||
export function onCalendarChanged(_listener: () => void): () => void { return () => {}; }
|
||||
export function onCalendarChanged(listener: () => void): () => void {
|
||||
return onSettingsStoreChanged(key => {
|
||||
if (key === CALENDAR_SELECTION_KEY || key == null) {
|
||||
invalidateCalendarCache();
|
||||
listener();
|
||||
}
|
||||
});
|
||||
}
|
||||
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 } | null = null;
|
||||
let cache: { events: CalendarEvent[]; atMs: number; maxEvents: number; windowMs: number; selection: string } | null = null;
|
||||
|
||||
/**
|
||||
* Upcoming events from now through the given window, ordered by start time.
|
||||
@@ -35,9 +44,11 @@ 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
|
||||
@@ -55,6 +66,7 @@ export function readUpcomingEvents(
|
||||
context,
|
||||
Math.max(0, Math.round(maxEvents)),
|
||||
Math.max(0, Math.round(windowMs)),
|
||||
selection,
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -62,7 +74,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 };
|
||||
cache = { events, atMs: now, maxEvents, windowMs, selection };
|
||||
return events;
|
||||
} catch {
|
||||
return [];
|
||||
|
||||
@@ -519,11 +519,6 @@ export class FaceclawCommunicatorBridge {
|
||||
await this.enqueueJavaCall(() => this.communicator.enableWearDetectionAndRequestState());
|
||||
}
|
||||
|
||||
/** -1 leaves a field unchanged. The native session retains explicit values across reconnects. */
|
||||
async configureHeadUpWake(enabled: number, angle: number): Promise<void> {
|
||||
await this.enqueueJavaCall(() => this.communicator.configureHeadUpWake(enabled, angle));
|
||||
}
|
||||
|
||||
/** Whether the transport prelude has finished (each arm reports "connected" before it). */
|
||||
isSessionReady(): boolean {
|
||||
return Boolean(this.communicator.isSessionReady());
|
||||
|
||||
@@ -555,38 +555,6 @@ export const brightnessSetting = new ConfigSettingEnum<BrightnessSetting>({
|
||||
description: "Auto uses Faceclaw's ambient-light curve; numbers set a fixed level. 2 is the dimmest level.",
|
||||
});
|
||||
|
||||
/** String storage distinguishes an untouched firmware preference from explicit ON/OFF. */
|
||||
class HeadUpWakeSetting extends ConfigSettingBoolean {
|
||||
get(): boolean { return getStringSetting(this.storageKey, "true") !== "false"; }
|
||||
set(value: boolean): boolean { setStringSetting(this.storageKey, String(value)); return value; }
|
||||
}
|
||||
|
||||
export const headUpWakeSetting = new HeadUpWakeSetting({
|
||||
id: "head-up-wake", label: "Head-up wake", storageKey: "display.headUpWake", defaultValue: true,
|
||||
description: "Enable waking the glasses when you look up. Until changed, the glasses keep their current setting. Glanceboard's Show on head tilt chooses what appears after waking.",
|
||||
});
|
||||
|
||||
export function normalizeHeadUpAngle(value: string | null | undefined): string {
|
||||
if (value == null || value.trim() === "" || !Number.isFinite(Number(value))) return "30";
|
||||
return String(Math.max(0, Math.min(60, Math.round(Number(value)))));
|
||||
}
|
||||
|
||||
export const headUpAngleSetting = new ConfigSettingEnum({
|
||||
id: "head-up-angle", label: "Head-up angle", storageKey: "display.headUpAngle", defaultValue: "30",
|
||||
values: Array.from({ length: 61 }, (_, angle) => String(angle)),
|
||||
normalize: normalizeHeadUpAngle,
|
||||
formatValue: angle => `${angle}°`,
|
||||
description: "Look-up trigger angle, 0–60 degrees. Until changed, the glasses keep their current angle. Requires validation on your Faceclaw firmware.",
|
||||
});
|
||||
|
||||
/** -1 means leave that firmware field unchanged; no writes on an untouched installation. */
|
||||
export function getHeadUpPreferences(): { enabled: number; angle: number } {
|
||||
const enabled = getStringSetting("display.headUpWake", "");
|
||||
const angle = getStringSetting("display.headUpAngle", "");
|
||||
return { enabled: enabled === "true" ? 1 : enabled === "false" ? 0 : -1,
|
||||
angle: angle === "" ? -1 : Number(normalizeHeadUpAngle(angle)) };
|
||||
}
|
||||
|
||||
const AUTO_BRIGHTNESS_LEVELS = ["2", "5", "10", "20", "25", "30", "40", "50", "60", "70", "80", "90", "100"] as const;
|
||||
export const autoBrightnessMinSetting = new ConfigSettingEnum({
|
||||
id: "autoBrightnessMin", label: "Auto minimum", storageKey: "display.autoBrightnessMin",
|
||||
|
||||
@@ -49,8 +49,6 @@ import {
|
||||
veniceWebSearchSetting,
|
||||
batteryDisplayModeSetting,
|
||||
brightnessSetting,
|
||||
headUpWakeSetting,
|
||||
headUpAngleSetting,
|
||||
autoBrightnessMinSetting,
|
||||
autoBrightnessMaxSetting,
|
||||
autoBrightnessCurveSetting,
|
||||
@@ -120,7 +118,6 @@ function settingsSections(): SettingsSection[] {
|
||||
// the dashboard controller when changed and on each connect.
|
||||
enumSettingMenuItem(brightnessSetting),
|
||||
autoBrightnessMenuItem(),
|
||||
...(!global.isIOS ? [toggleSettingMenuItem(headUpWakeSetting), enumSettingMenuItem(headUpAngleSetting)] : []),
|
||||
enumSettingMenuItem(screenTimeoutSetting, {
|
||||
onChange: () => {
|
||||
shell.noteUserActivity();
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
# 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.
|
||||
@@ -1,53 +0,0 @@
|
||||
# Head-up wake: software and hardware validation
|
||||
|
||||
The Android Display settings now contain “Head-up wake” and “Head-up angle”.
|
||||
Glanceboard's “Show on head tilt” still only chooses which UI appears on wake.
|
||||
|
||||
Protocol reference: [OpenG2 Companion G2Protocol.swift](https://github.com/mmirman/open-g2-companion/blob/1400d1006ba045379a3ff34d0832add6fa10ced4/modules/ffs-ble/ios/G2Protocol.swift),
|
||||
`setHeadUpSwitch` / `setHeadUpAngle`; dispatch to both lenses in
|
||||
[`G2Central.swift`](https://github.com/mmirman/open-g2-companion/blob/1400d1006ba045379a3ff34d0832add6fa10ced4/modules/ffs-ble/ios/G2Central.swift).
|
||||
|
||||
Wire format uses Faceclaw's UI-settings sid 0x09, request flag, command 1, transaction
|
||||
magic, device-receive-info field 3 / head-up field 4. Switch (field 1) and
|
||||
angle (field 2) are sent in separate messages, including explicit zero values.
|
||||
Angles are clamped to the reference's 0–60 degree range. No firmware patch,
|
||||
firmware download or flash is needed by this implementation.
|
||||
|
||||
Untouched installations send neither field. The UI describes this inherited
|
||||
state; its displayed ON/30 degree fallback is not a read-back of device state.
|
||||
Changing just one control preserves the other device field. Explicit choices
|
||||
are persisted in the existing settings store and resent on every connection.
|
||||
The native session also retains them through transport reconnects and retries
|
||||
after setting ACK timeouts. ACK reception confirms transport, not physical wake.
|
||||
|
||||
Software checks:
|
||||
|
||||
- `tests/head-up-wake.test.cjs`: persistence, untouched fields, angle bounds,
|
||||
independence from Glanceboard, deduplication, reconnect and error recovery.
|
||||
- `HeadUpProtocolTest`: byte-for-byte settings messages, including OFF and 0°.
|
||||
- `GlassesSessionCoreTest`: both lenses, separate writes, pre-existing device
|
||||
settings preserved, angle clamp and automatic transport reconnection.
|
||||
|
||||
Hardware validation: **pending**. Implementation was requested without device
|
||||
access; protocol compatibility and physical effect on the target Faceclaw CFW
|
||||
are not established by these software tests. The reference targets stock
|
||||
2.2.6.10, while this repository normally uses newer Faceclaw firmware.
|
||||
|
||||
Source inspection of [Faceclaw's gesture forwarding](https://github.com/jimrandomh/g2flash/blob/845f665e0dfdcfd06b7d3a294388de6f17a5bd59/patches/gesture_fwd.c)
|
||||
confirms that head-up/down forwarding while a page owns the screen checks the
|
||||
stock `head_up_switch`. This supports using the existing setting rather than a
|
||||
firmware patch, but does not establish the physical angle or wake behavior.
|
||||
|
||||
On the target glasses, record both lens firmware versions and test:
|
||||
|
||||
1. Leave preferences untouched and verify prior wake behavior remains unchanged.
|
||||
2. Disable Head-up wake; sleep the display, raise the head repeatedly, and confirm
|
||||
no wake. Check taps still wake normally.
|
||||
3. Enable it and compare 0°, 30° and 60° trigger angles. Confirm other wake
|
||||
gestures remain usable, including at the extreme values.
|
||||
4. Reconnect Bluetooth, then restart the phone app; repeat ON/OFF and angle checks.
|
||||
5. Toggle Glanceboard and “Show on head tilt” independently; disabled wake should
|
||||
stay disabled, enabled wake should show the selected UI.
|
||||
6. Check both lenses remain synchronized, including reconnecting only one arm.
|
||||
|
||||
Do not change firmware to run these checks without explicit permission.
|
||||
@@ -497,23 +497,6 @@ class BleProtocol {
|
||||
)
|
||||
}
|
||||
|
||||
/** Stock HeadUpSetting: switch and angle are separate oneof writes (field 4 of device info). */
|
||||
@JvmStatic
|
||||
fun buildSetHeadUpWake(magic: Int, enabled: Boolean): ByteArray = concat(
|
||||
CollectionUtils.listOf(
|
||||
encodeVarintField(1, 1), encodeVarintField(2, magic),
|
||||
encodeMessageField(3, encodeMessageField(4, encodeVarintField(1, if (enabled) 1 else 0))),
|
||||
)
|
||||
)
|
||||
|
||||
@JvmStatic
|
||||
fun buildSetHeadUpAngle(magic: Int, angle: Int): ByteArray = concat(
|
||||
CollectionUtils.listOf(
|
||||
encodeVarintField(1, 1), encodeVarintField(2, magic),
|
||||
encodeMessageField(3, encodeMessageField(4, encodeVarintField(2, angle.coerceIn(0, 60)))),
|
||||
)
|
||||
)
|
||||
|
||||
/** Enable the firmware's wear detector (DeviceReceiveInfoFromAPP field 5). */
|
||||
@JvmStatic
|
||||
fun buildSetWearDetection(magic: Int, enabled: Boolean): ByteArray {
|
||||
|
||||
-11
@@ -188,17 +188,6 @@ class MessageBuilder {
|
||||
)
|
||||
}
|
||||
|
||||
fun headUpControl(leftArm: Boolean, enabled: Boolean?, angle: Int): OutboundMessage {
|
||||
val magic = magicPool.allocate()
|
||||
return OutboundMessage(
|
||||
"head-up-control", if (enabled == null) "head-up angle=$angle" else "head-up wake=$enabled",
|
||||
BleProtocol.SID_UI_SETTING, BleProtocol.FLAG_REQUEST, magic,
|
||||
if (enabled == null) BleProtocol.buildSetHeadUpAngle(magic, angle)
|
||||
else BleProtocol.buildSetHeadUpWake(magic, enabled),
|
||||
ACK_TIMEOUT_MS, -1, leftArm,
|
||||
)
|
||||
}
|
||||
|
||||
fun createLayout(): OutboundMessage {
|
||||
var magic: Int = magicPool.allocate()
|
||||
return OutboundMessage(
|
||||
|
||||
-12
@@ -304,8 +304,6 @@ class GlassesSessionCore(
|
||||
internal var brightnessSentLevel = -1
|
||||
internal var brightnessAlsStartedAt = -2000L
|
||||
internal var brightnessDemoPolling = false
|
||||
internal var headUpPreferences: Pair<Int, Int>? = null
|
||||
internal var headUpSent: Pair<Int, Int>? = null
|
||||
internal var cfwCleanupDelivered = false
|
||||
internal var lastCfwCleanupAckMagic = 0
|
||||
|
||||
@@ -922,15 +920,6 @@ class GlassesSessionCore(
|
||||
interruptibleSleep.interrupt()
|
||||
}
|
||||
|
||||
/** Explicit preferences only; -1 leaves the corresponding firmware field alone. */
|
||||
fun configureHeadUpWake(enabled: Int, angle: Int) {
|
||||
require(enabled in -1..1)
|
||||
monitor.withLock {
|
||||
headUpPreferences = Pair(enabled, if (angle < 0) -1 else angle.coerceIn(0, 60))
|
||||
}
|
||||
interruptibleSleep.interrupt()
|
||||
}
|
||||
|
||||
/**
|
||||
* Enable the stock wear detector, then ask CFW to emit its current cached
|
||||
* state. The queue order matters: the query must run after the setting is
|
||||
@@ -2243,7 +2232,6 @@ class GlassesSessionCore(
|
||||
shutdownRequested = false
|
||||
fixedLayoutCreated = false
|
||||
clearAllMessagesLocked("session ready")
|
||||
headUpSent = null
|
||||
displayedFingerprint = ""
|
||||
lastAckAtMs = now()
|
||||
lastIncomingAtMs = lastAckAtMs
|
||||
|
||||
-22
@@ -1,22 +0,0 @@
|
||||
package com.faceclaw.app
|
||||
|
||||
/** Both arms receive separate stock settings messages; no CFW changes required. */
|
||||
internal fun GlassesSessionCore.enqueueHeadUpPreferencesLocked() {
|
||||
val desired = headUpPreferences ?: return
|
||||
if (!sessionReady || shutdownRequested || chargingMode || headUpSent == desired
|
||||
|| hasPendingOrInflightKindLocked("head-up-control")) return
|
||||
for (leftArm in listOf(true, false)) {
|
||||
// Set the angle before enabling wake. Omitted fields preserve device preferences.
|
||||
if (desired.second >= 0) {
|
||||
val message = messageBuilder.headUpControl(leftArm, null, desired.second)
|
||||
message.onTimeout = MessageCallback { headUpSent = null; logLine("head-up angle ack timeout") }
|
||||
pendingMessages.addLast(message)
|
||||
}
|
||||
if (desired.first >= 0) {
|
||||
val message = messageBuilder.headUpControl(leftArm, desired.first == 1, -1)
|
||||
message.onTimeout = MessageCallback { headUpSent = null; logLine("head-up wake ack timeout") }
|
||||
pendingMessages.addLast(message)
|
||||
}
|
||||
}
|
||||
headUpSent = desired
|
||||
}
|
||||
-1
@@ -74,7 +74,6 @@ internal fun GlassesSessionCore.driveSession(): Long {
|
||||
clearPendingMessagesLocked("after CFW cleanup")
|
||||
return 250
|
||||
}
|
||||
enqueueHeadUpPreferencesLocked()
|
||||
if (sessionReady
|
||||
&& now - lastFaceclawFramebufferLeaseQueuedAtMs >= FACECLAW_WAKE_LEASE_RENEW_MS
|
||||
&& !hasPendingOrInflightKindLocked("framebuffer-lease-control")) {
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
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,76 +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 evaluate(code, globals) {
|
||||
const context = { exports: {}, ...globals };
|
||||
vm.runInNewContext(ts.transpileModule(code, {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
|
||||
}).outputText, context);
|
||||
return context.exports;
|
||||
}
|
||||
function settings(values = new Map()) {
|
||||
const file = ts.createSourceFile('settings.ts', source('app/ui/dashboard-settings.ts'), ts.ScriptTarget.Latest, true);
|
||||
const names = new Set(['ConfigSetting', 'ConfigSettingBoolean', 'ConfigSettingEnum', 'HeadUpWakeSetting',
|
||||
'headUpWakeSetting', 'normalizeHeadUpAngle', 'headUpAngleSetting', 'getHeadUpPreferences']);
|
||||
const code = file.statements.filter(node => names.has(node.name?.text) ||
|
||||
(ts.isVariableStatement(node) && node.declarationList.declarations.some(d => names.has(d.name.getText(file)))))
|
||||
.map(node => node.getText(file)).join('\n');
|
||||
return evaluate(code, {
|
||||
fixedChoiceSettings: new Map(),
|
||||
getStringSetting: (key, fallback) => values.get(key) ?? fallback,
|
||||
setStringSetting: (key, value) => values.set(key, value),
|
||||
});
|
||||
}
|
||||
|
||||
test('head-up preferences preserve untouched device fields and persist each explicit choice separately', () => {
|
||||
const values = new Map();
|
||||
let prefs = settings(values);
|
||||
assert.equal(prefs.getHeadUpPreferences().enabled, -1);
|
||||
assert.equal(prefs.getHeadUpPreferences().angle, -1);
|
||||
prefs.headUpWakeSetting.set(false);
|
||||
prefs = settings(values);
|
||||
assert.equal(prefs.headUpWakeSetting.get(), false);
|
||||
assert.equal(prefs.getHeadUpPreferences().enabled, 0);
|
||||
assert.equal(prefs.getHeadUpPreferences().angle, -1);
|
||||
prefs.headUpAngleSetting.set('75');
|
||||
prefs = settings(values);
|
||||
assert.equal(prefs.headUpAngleSetting.get(), '60');
|
||||
assert.equal(prefs.getHeadUpPreferences().enabled, 0);
|
||||
assert.equal(prefs.getHeadUpPreferences().angle, 60);
|
||||
for (const [input, expected] of [['-5', '0'], ['20.8', '21'], ['NaN', '30'], ['', '30']]) {
|
||||
assert.equal(prefs.headUpAngleSetting.set(input), expected);
|
||||
}
|
||||
assert.equal(values.has('glanceboard.showOnHeadTilt'), false);
|
||||
});
|
||||
|
||||
test('controller skips unset preferences, deduplicates changes and forces reconnect synchronization', async () => {
|
||||
const file = ts.createSourceFile('controller.ts', source('app/g2/dashboard-controller.ts'), ts.ScriptTarget.Latest, true);
|
||||
const controller = file.statements.find(node => ts.isClassDeclaration(node) && node.name.text === 'DashboardController');
|
||||
const method = controller.members.find(node => node.name?.getText(file) === 'pushHeadUpPreferences').getText(file);
|
||||
let prefs = { enabled: -1, angle: -1 };
|
||||
const { Harness } = evaluate(`export class Harness { ${method} }`, {
|
||||
global: { isAndroid: true }, getHeadUpPreferences: () => prefs,
|
||||
});
|
||||
const h = new Harness(), calls = [];
|
||||
h.communicator = { configureHeadUpWake: async (...args) => calls.push(args) };
|
||||
h.pushHeadUpPreferences(); assert.equal(calls.length, 0);
|
||||
prefs = { enabled: 0, angle: 25 };
|
||||
h.pushHeadUpPreferences(); h.pushHeadUpPreferences();
|
||||
assert.deepEqual(calls, [[0, 25]]);
|
||||
h.pushHeadUpPreferences(true); assert.equal(calls.length, 2);
|
||||
prefs = { enabled: 1, angle: 40 }; h.pushHeadUpPreferences();
|
||||
assert.deepEqual(calls.at(-1), [1, 40]);
|
||||
let failures = 0;
|
||||
h.communicator.configureHeadUpWake = async () => { throw new Error('offline'); };
|
||||
h.appendLog = () => failures++;
|
||||
h.formatError = error => error.message;
|
||||
h.pushHeadUpPreferences(true);
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
assert.equal(h.lastPushedHeadUp, null); assert.equal(failures, 1);
|
||||
const connect = controller.members.find(node => node.name?.getText(file) === 'connect').getText(file);
|
||||
assert.match(connect, /pushHeadUpPreferences\(true\)/);
|
||||
});
|
||||
@@ -199,6 +199,7 @@ 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,33 +316,6 @@ private class Session {
|
||||
}
|
||||
|
||||
class GlassesSessionCoreTest {
|
||||
@Test fun headUpWritesOnlyExplicitFieldsToBothArmsAndResendsAfterReconnect() {
|
||||
val s = Session()
|
||||
try {
|
||||
s.startAndAwaitLayout()
|
||||
fun writes() = s.link.writes.filter { it.kind == "head-up-control" }
|
||||
assertEquals(0, writes().size, "untouched firmware preferences must not be written")
|
||||
s.core.configureHeadUpWake(0, 30)
|
||||
assertTrue(waitUntil(5_000) { writes().size == 4 })
|
||||
for (arm in listOf(LEFT, RIGHT)) {
|
||||
val commands = writes().filter { it.address == arm }
|
||||
assertContentEquals(BleProtocol.buildSetHeadUpAngle(commands[0].magic, 30), commands[0].pb)
|
||||
assertContentEquals(BleProtocol.buildSetHeadUpWake(commands[1].magic, false), commands[1].pb)
|
||||
}
|
||||
s.core.handleTransportFailure("head-up reconnect test")
|
||||
assertTrue(waitUntil(5_000) { !s.layoutCreated() })
|
||||
s.platform.offsetMs += 10_000
|
||||
s.core.interruptibleSleep.interrupt()
|
||||
assertTrue(waitUntil(5_000) { s.layoutCreated() && writes().size == 8 }, s.host.logs().takeLast(10).toString())
|
||||
s.core.configureHeadUpWake(-1, 100)
|
||||
assertTrue(waitUntil(5_000) { writes().size == 10 })
|
||||
assertTrue(writes().takeLast(2).all { it.label == "head-up angle=60" })
|
||||
s.core.configureHeadUpWake(1, -1)
|
||||
assertTrue(waitUntil(5_000) { writes().size == 12 })
|
||||
assertTrue(writes().takeLast(2).all { it.label == "head-up wake=true" })
|
||||
} finally { s.core.close() }
|
||||
}
|
||||
|
||||
@Test fun brightnessConfigPrecedesFirstFrameAndSleepWakeFollowsComposites() {
|
||||
val s = Session()
|
||||
s.core.configureBrightness(false, 70, 2, 100, "0:0,1000:100", 280)
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
package com.faceclaw.app
|
||||
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertContentEquals
|
||||
|
||||
class HeadUpProtocolTest {
|
||||
private fun bytes(hex: String) = hex.chunked(2).map { it.toInt(16).toByte() }.toByteArray()
|
||||
|
||||
@Test fun separateSwitchAndAngleMessagesMatchReferenceWireFormat() {
|
||||
// G2SettingPackage{1=1, 2=magic, 3={4=HeadUpSetting{1=switch | 2=angle}}}.
|
||||
assertContentEquals(bytes("080110071a0422020800"), BleProtocol.buildSetHeadUpWake(7, false))
|
||||
assertContentEquals(bytes("080110071a0422020801"), BleProtocol.buildSetHeadUpWake(7, true))
|
||||
assertContentEquals(bytes("080110071a042202101e"), BleProtocol.buildSetHeadUpAngle(7, 30))
|
||||
assertContentEquals(bytes("080110071a0422021000"), BleProtocol.buildSetHeadUpAngle(7, -10))
|
||||
assertContentEquals(bytes("080110071a042202103c"), BleProtocol.buildSetHeadUpAngle(7, 100))
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user