forked from Blendman974/faceclaw
Add calendar app and accelerometer demo
This commit is contained in:
1 parent
3cdc5ba262
commit
ff447d5161
18 files changed
+911
-5
No files matched your search
@@ -2,8 +2,10 @@ import { Application, Utils } from "@nativescript/core";
|
||||
|
||||
const PERMISSION_REQUEST_CODE = 4242;
|
||||
const VOICE_PERMISSION_REQUEST_CODE = 4243;
|
||||
const CALENDAR_PERMISSION_REQUEST_CODE = 4244;
|
||||
const POST_NOTIFICATIONS_PERMISSION = "android.permission.POST_NOTIFICATIONS";
|
||||
const RECORD_AUDIO_PERMISSION = "android.permission.RECORD_AUDIO";
|
||||
const READ_CALENDAR_PERMISSION = "android.permission.READ_CALENDAR";
|
||||
|
||||
function getActivity(): androidx.appcompat.app.AppCompatActivity {
|
||||
const activity = Application.android.foregroundActivity ?? Application.android.startActivity;
|
||||
@@ -101,3 +103,24 @@ export async function ensureVoicePermissions(): Promise<void> {
|
||||
await ensurePermissions([RECORD_AUDIO_PERMISSION], VOICE_PERMISSION_REQUEST_CODE, "Voice control");
|
||||
}
|
||||
|
||||
/** Whether READ_CALENDAR has been granted (false off-Android). */
|
||||
export function hasCalendarPermission(): boolean {
|
||||
if (!global.isAndroid) return false;
|
||||
return isPermissionGranted(READ_CALENDAR_PERMISSION);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prompt for READ_CALENDAR if not already granted. Resolves true when the
|
||||
* permission is held afterward, false if the user denied it (or no activity
|
||||
* was available to show the prompt).
|
||||
*/
|
||||
export async function ensureCalendarPermission(): Promise<boolean> {
|
||||
if (!global.isAndroid) return false;
|
||||
try {
|
||||
await ensurePermissions([READ_CALENDAR_PERMISSION], CALENDAR_PERMISSION_REQUEST_CODE, "Calendar");
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,6 +31,11 @@ import {
|
||||
NOTIFICATIONS_SURFACE_ID,
|
||||
NOTIFICATIONS_WINDOW_ID,
|
||||
} from "../ui/shell/notifications-app";
|
||||
import {
|
||||
createCalendarAppWindow,
|
||||
CALENDAR_SURFACE_ID,
|
||||
CALENDAR_WINDOW_ID,
|
||||
} from "../ui/shell/calendar-app";
|
||||
import {
|
||||
createDebugTestsAppWindow,
|
||||
DEBUG_TESTS_SURFACE_ID,
|
||||
@@ -218,6 +223,7 @@ class DashboardController {
|
||||
{ appId: "nightscout", label: "Nightscout", icon: "nightscout" },
|
||||
{ appId: "transcribe", label: "Transcribe", icon: "mic" },
|
||||
{ appId: "notifications", label: "Notifications", icon: "bell" },
|
||||
{ appId: "calendar", label: "Calendar", icon: "calendar" },
|
||||
{ appId: "debug-tests", label: "Debug tests", icon: "flask-conical" },
|
||||
{ appId: "settings", label: "Settings", icon: "settings" },
|
||||
],
|
||||
@@ -873,6 +879,10 @@ class DashboardController {
|
||||
await this.launchInProcessApp(NOTIFICATIONS_WINDOW_ID, NOTIFICATIONS_SURFACE_ID, createNotificationsAppWindow);
|
||||
return;
|
||||
}
|
||||
if (appId === "calendar") {
|
||||
await this.launchInProcessApp(CALENDAR_WINDOW_ID, CALENDAR_SURFACE_ID, createCalendarAppWindow);
|
||||
return;
|
||||
}
|
||||
if (appId === "debug-tests") {
|
||||
await this.launchInProcessApp(DEBUG_TESTS_WINDOW_ID, DEBUG_TESTS_SURFACE_ID, createDebugTestsAppWindow);
|
||||
return;
|
||||
|
||||
@@ -32,6 +32,8 @@ export const ICON_SVGS = {
|
||||
'<svg viewBox="0 0 24 24" fill="none"><path d="M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2"/></svg>',
|
||||
bell:
|
||||
'<svg viewBox="0 0 24 24" fill="none"><path d="M10.268 21a2 2 0 0 0 3.464 0"/><path d="M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326"/></svg>',
|
||||
calendar:
|
||||
'<svg viewBox="0 0 24 24" fill="none"><path d="M8 2v4"/><path d="M16 2v4"/><rect width="18" height="18" x="3" y="4" rx="2"/><path d="M3 10h18"/></svg>',
|
||||
"flask-conical":
|
||||
'<svg viewBox="0 0 24 24" fill="none"><path d="M14 2v6a2 2 0 0 0 .245.96l5.51 10.08A2 2 0 0 1 18 22H6a2 2 0 0 1-1.755-2.96l5.51-10.08A2 2 0 0 0 10 8V2"/><path d="M6.453 15h11.094"/><path d="M8.5 2h7"/></svg>',
|
||||
settings:
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
import { Utils } from "@nativescript/core";
|
||||
import { hasCalendarPermission } from "../g2/android-permissions";
|
||||
import { spanCurrent } from "./frame-timings";
|
||||
|
||||
declare const com: any;
|
||||
|
||||
/**
|
||||
* Reads upcoming calendar events through the Android Calendar provider
|
||||
* (FaceclawCalendarProvider). Results are cached briefly so repeated paints of
|
||||
* the Calendar app don't re-run the content-provider query every frame.
|
||||
*/
|
||||
|
||||
export type CalendarEvent = {
|
||||
id: number;
|
||||
title: string;
|
||||
startMs: number;
|
||||
endMs: number;
|
||||
allDay: boolean;
|
||||
location: string;
|
||||
calendarName: string;
|
||||
};
|
||||
|
||||
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;
|
||||
|
||||
/**
|
||||
* Upcoming events from now through the given window, ordered by start time.
|
||||
* Returns [] when calendar permission is absent. Cached for CACHE_MS; pass
|
||||
* forceRefresh to bypass the cache (e.g. right after the permission grant).
|
||||
*/
|
||||
export function readUpcomingEvents(
|
||||
maxEvents = DEFAULT_MAX_EVENTS,
|
||||
windowMs = DEFAULT_WINDOW_MS,
|
||||
forceRefresh = false,
|
||||
): CalendarEvent[] {
|
||||
if (!global.isAndroid || !hasCalendarPermission()) return [];
|
||||
|
||||
const now = Date.now();
|
||||
if (
|
||||
!forceRefresh &&
|
||||
cache &&
|
||||
cache.maxEvents === maxEvents &&
|
||||
cache.windowMs === windowMs &&
|
||||
now - cache.atMs < CACHE_MS
|
||||
) {
|
||||
return cache.events;
|
||||
}
|
||||
|
||||
const context = Utils.android.getApplicationContext();
|
||||
if (!context) return [];
|
||||
|
||||
try {
|
||||
const json = spanCurrent("fetch-calendar-events", () =>
|
||||
String(
|
||||
com.faceclaw.app.FaceclawCalendarProvider.getUpcomingEventsJson(
|
||||
context,
|
||||
Math.max(0, Math.round(maxEvents)),
|
||||
Math.max(0, Math.round(windowMs)),
|
||||
),
|
||||
),
|
||||
);
|
||||
const parsed = JSON.parse(json);
|
||||
const events = Array.isArray(parsed)
|
||||
? parsed.map(normalizeEvent).filter((event): event is CalendarEvent => Boolean(event))
|
||||
: [];
|
||||
cache = { events, atMs: now, maxEvents, windowMs };
|
||||
return events;
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/** Drop the cached events so the next read re-queries the provider. */
|
||||
export function invalidateCalendarCache(): void {
|
||||
cache = null;
|
||||
}
|
||||
|
||||
function normalizeEvent(value: any): CalendarEvent | null {
|
||||
if (!value || typeof value !== "object") return null;
|
||||
const startMs = Number(value.startMs);
|
||||
if (!Number.isFinite(startMs)) return null;
|
||||
return {
|
||||
id: Number(value.id) || 0,
|
||||
title: String(value.title ?? ""),
|
||||
startMs,
|
||||
endMs: Number(value.endMs) || startMs,
|
||||
allDay: Boolean(value.allDay),
|
||||
location: String(value.location ?? ""),
|
||||
calendarName: String(value.calendarName ?? ""),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
declare const com: any;
|
||||
|
||||
/**
|
||||
* IMU (accelerometer) access. The G2 gates its accelerometer stream behind an
|
||||
* ImuCtrl control message; once enabled, the firmware reports x/y/z samples as
|
||||
* sys-events, which the Java communicator decodes and forwards here.
|
||||
*
|
||||
* Note: this stream has historically been unreliable — the firmware may not
|
||||
* populate IMU data at all. Treat it as experimental.
|
||||
*
|
||||
* Talks to the active communicator via the FaceclawBleCommunicator.getActive()
|
||||
* static, so it works from any isolate without threading the bridge through.
|
||||
*/
|
||||
|
||||
export type ImuReading = { x: number; y: number; z: number; source: number };
|
||||
|
||||
function activeCommunicator(): any {
|
||||
if (!global.isAndroid) return null;
|
||||
try {
|
||||
return com.faceclaw.app.FaceclawBleCommunicator.getActive();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Enable/disable the accelerometer report stream. No-op if not connected. */
|
||||
export function setImuReportEnabled(enable: boolean, reportFreq: number): void {
|
||||
const active = activeCommunicator();
|
||||
if (!active) return;
|
||||
try {
|
||||
active.setImuReportEnabled(enable, Math.max(0, Math.round(reportFreq)));
|
||||
} catch (error) {
|
||||
console.warn(`setImuReportEnabled failed: ${error}`);
|
||||
}
|
||||
}
|
||||
|
||||
/** Subscribe to IMU readings; returns an unsubscribe function. */
|
||||
export function addImuListener(listener: (reading: ImuReading) => void): () => void {
|
||||
const active = activeCommunicator();
|
||||
if (!active) return () => {};
|
||||
const proxy = new com.faceclaw.app.FaceclawImuListener({
|
||||
onImuData: (x: number, y: number, z: number, source: number) => {
|
||||
listener({ x: Number(x), y: Number(y), z: Number(z), source: Number(source) });
|
||||
},
|
||||
});
|
||||
active.addImuListener(proxy);
|
||||
return () => {
|
||||
try {
|
||||
activeCommunicator()?.removeImuListener(proxy);
|
||||
} catch {
|
||||
// The instance may be gone after a disconnect; nothing to clean up.
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/** Map an IMU sample's EventSource to a short label. */
|
||||
export function imuSourceLabel(source: number): string {
|
||||
switch (source) {
|
||||
case 1:
|
||||
return "R arm";
|
||||
case 2:
|
||||
return "ring";
|
||||
case 3:
|
||||
return "L arm";
|
||||
default:
|
||||
return "device";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
import { getDefaultMediumFont, getDefaultSmallFont } from "../../graphics/bdffont";
|
||||
import { GrayImage } from "../../graphics/image";
|
||||
import { clamp } from "../../util/numeric-util";
|
||||
import { addImuListener, imuSourceLabel, setImuReportEnabled, type ImuReading } from "../../native/imu";
|
||||
import { GESTURE_DOUBLE_CLICK } from "../gestures";
|
||||
import { Layer, type DashboardInputEvent, type LayerContext } from "../layers";
|
||||
import { shell } from "../shell/shell";
|
||||
|
||||
// IMU report pace. This is NOT a literal Hz — the firmware only accepts the
|
||||
// ImuReportPace codes 100..1000 (step 100); the real delivery rate is
|
||||
// device-defined. An out-of-range value makes the firmware stream empty
|
||||
// (all-zero) samples. 200 matches the reference EvenHub running-tracker app.
|
||||
const IMU_REPORT_PACE = 200;
|
||||
// How often to reconcile the IMU on/off state with window visibility.
|
||||
const RECONCILE_INTERVAL_MS = 400;
|
||||
|
||||
/**
|
||||
* Accelerometer demo: turns the IMU stream on while this page is visible (the
|
||||
* Debug tests window is foregrounded and the screen is on), off otherwise, and
|
||||
* shows the latest x/y/z reading with a simple per-axis bar.
|
||||
*
|
||||
* The IMU stream is experimental — the firmware may never populate it — so the
|
||||
* page also reports how many samples have arrived.
|
||||
*/
|
||||
export class AccelerometerDemoLayer implements Layer {
|
||||
private reading: ImuReading | null = null;
|
||||
private sampleCount = 0;
|
||||
private peak = 0;
|
||||
private enabled = false;
|
||||
private removed = false;
|
||||
private reconcileTimer: ReturnType<typeof setInterval> | null = null;
|
||||
private unsubscribe: (() => void) | null = null;
|
||||
|
||||
constructor(
|
||||
private readonly windowId: string,
|
||||
private readonly requestRender: () => void,
|
||||
) {
|
||||
this.start();
|
||||
}
|
||||
|
||||
private start(): void {
|
||||
this.unsubscribe = addImuListener((reading) => {
|
||||
if (this.removed) return;
|
||||
this.reading = reading;
|
||||
this.sampleCount++;
|
||||
this.peak = Math.max(this.peak, Math.abs(reading.x), Math.abs(reading.y), Math.abs(reading.z));
|
||||
this.requestRender();
|
||||
});
|
||||
this.reconcileTimer = setInterval(() => this.reconcile(), RECONCILE_INTERVAL_MS);
|
||||
this.reconcile();
|
||||
}
|
||||
|
||||
/** Match the IMU on/off state to whether this page is currently visible. */
|
||||
private reconcile(): void {
|
||||
if (this.removed) return;
|
||||
const visible = shell.isWindowVisible(this.windowId);
|
||||
if (visible === this.enabled) return;
|
||||
this.enabled = visible;
|
||||
setImuReportEnabled(visible, IMU_REPORT_PACE);
|
||||
this.requestRender();
|
||||
}
|
||||
|
||||
onRemoved(): void {
|
||||
this.removed = true;
|
||||
if (this.reconcileTimer !== null) {
|
||||
clearInterval(this.reconcileTimer);
|
||||
this.reconcileTimer = null;
|
||||
}
|
||||
this.unsubscribe?.();
|
||||
this.unsubscribe = null;
|
||||
if (this.enabled) {
|
||||
setImuReportEnabled(false, IMU_REPORT_PACE);
|
||||
this.enabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
paint(ctx: LayerContext): GrayImage {
|
||||
const small = getDefaultSmallFont();
|
||||
const medium = getDefaultMediumFont();
|
||||
const { width, height } = ctx.stack.getBaseSize();
|
||||
const image = new GrayImage(width, height, 0);
|
||||
|
||||
image.drawText(small, 20, 8, "Accelerometer", 220);
|
||||
const status = this.enabled ? "IMU on" : "IMU off";
|
||||
image.drawText(small, width - 20 - small.measureText(status), 8, status, 150);
|
||||
|
||||
if (this.reading) {
|
||||
const axes: Array<[string, number]> = [
|
||||
["X", this.reading.x],
|
||||
["Y", this.reading.y],
|
||||
["Z", this.reading.z],
|
||||
];
|
||||
const barX = 118;
|
||||
const barW = width - barX - 24;
|
||||
const scale = Math.max(this.peak, 1e-6);
|
||||
let y = 40;
|
||||
for (const [label, value] of axes) {
|
||||
image.drawText(medium, 22, y, label, 210);
|
||||
image.drawText(medium, 44, y, value.toFixed(3), 235);
|
||||
drawCenteredBar(image, barX, y + 2, barW, 12, clamp(value / scale, -1, 1));
|
||||
y += 30;
|
||||
}
|
||||
image.drawText(
|
||||
small,
|
||||
22,
|
||||
y + 6,
|
||||
`source: ${imuSourceLabel(this.reading.source)} samples: ${this.sampleCount}`,
|
||||
130,
|
||||
);
|
||||
} else {
|
||||
const message = this.enabled
|
||||
? "Waiting for IMU data…"
|
||||
: "Paused (page not visible).";
|
||||
image.drawText(small, 22, 44, message, 190);
|
||||
image.drawText(small, 22, 66, "The firmware may not report the", 120);
|
||||
image.drawText(small, 22, 82, "accelerometer at all — experimental.", 120);
|
||||
}
|
||||
|
||||
image.drawText(small, 20, height - 16, `${GESTURE_DOUBLE_CLICK} back`, 110);
|
||||
return image;
|
||||
}
|
||||
|
||||
async handleInput(event: DashboardInputEvent, ctx: LayerContext): Promise<void> {
|
||||
if (event.type === "double-click") {
|
||||
ctx.stack.pop();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Horizontal bar centered at its midpoint; frac in [-1, 1] fills left/right. */
|
||||
function drawCenteredBar(image: GrayImage, x: number, y: number, width: number, height: number, frac: number): void {
|
||||
const mid = x + Math.round(width / 2);
|
||||
image.fillRect(x, y, width, height, 20);
|
||||
image.setPixel(mid, y - 1, 90);
|
||||
image.setPixel(mid, y + height, 90);
|
||||
const half = width / 2;
|
||||
const px = Math.round(clamp(frac, -1, 1) * half);
|
||||
if (px >= 0) {
|
||||
image.fillRect(mid, y, Math.max(1, px), height, 200);
|
||||
} else {
|
||||
image.fillRect(mid + px, y, -px, height, 200);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
import { getDefaultSmallFont, type BdfFont } from "../../graphics/bdffont";
|
||||
import { GrayImage } from "../../graphics/image";
|
||||
import { wrapText } from "../../graphics/textwrap";
|
||||
import { clamp } from "../../util/numeric-util";
|
||||
import { readUpcomingEvents, type CalendarEvent } from "../../native/calendar";
|
||||
import { timeFormatSetting } from "../dashboard-settings";
|
||||
import { GESTURE_CLICK, GESTURE_DOUBLE_CLICK } from "../gestures";
|
||||
import { hasCalendarPermission } from "../../g2/android-permissions";
|
||||
import { type DashboardInputEvent, type Layer, type LayerContext } from "../layers";
|
||||
|
||||
const PAGE_X = 12;
|
||||
const PAGE_Y = 12;
|
||||
const LIST_TOP = 38;
|
||||
const ROW_X = 16;
|
||||
const LINE_HEIGHT = 14;
|
||||
const DAY_HEADER_HEIGHT = 16;
|
||||
const ROW_GAP = 4;
|
||||
const MAX_EVENTS = 50;
|
||||
|
||||
const WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
|
||||
const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
|
||||
|
||||
type EventRow = {
|
||||
event: CalendarEvent;
|
||||
/** Day header text drawn above this row, or null when it shares the prior day. */
|
||||
dayHeader: string | null;
|
||||
lines: string[];
|
||||
height: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* The Calendar app's single screen. Without calendar permission it shows a
|
||||
* prompt telling the user to grant access on the phone (the launch path also
|
||||
* fires the system permission dialog); with permission it lists upcoming
|
||||
* events grouped by day, scrollable when they overflow the viewport.
|
||||
*/
|
||||
export class CalendarLayer implements Layer {
|
||||
private selectedIndex = 0;
|
||||
|
||||
constructor(private readonly requestPermission: () => void) {}
|
||||
|
||||
paint(ctx: LayerContext): GrayImage {
|
||||
const font = getDefaultSmallFont();
|
||||
const { width, height } = ctx.stack.getBaseSize();
|
||||
const image = new GrayImage(width, height, 0);
|
||||
image.drawText(font, PAGE_X + 12, PAGE_Y + 9, "Calendar", 220);
|
||||
|
||||
if (!hasCalendarPermission()) {
|
||||
this.paintPermissionPrompt(image, font, width, height);
|
||||
return image;
|
||||
}
|
||||
|
||||
const events = readUpcomingEvents(MAX_EVENTS);
|
||||
if (!events.length) {
|
||||
image.drawText(font, 24, 72, "No upcoming events.", 190);
|
||||
image.drawText(font, 24, height - 36, `${GESTURE_DOUBLE_CLICK} back`, 110);
|
||||
return image;
|
||||
}
|
||||
|
||||
const rows = buildEventRows(events);
|
||||
this.selectedIndex = clamp(this.selectedIndex, 0, rows.length - 1);
|
||||
image.drawText(font, width - 96, PAGE_Y + 9, `${this.selectedIndex + 1}/${rows.length}`, 150);
|
||||
|
||||
const listBottom = height;
|
||||
const scrollY = scrollForSelected(rows, this.selectedIndex, listBottom - LIST_TOP);
|
||||
let cursorY = LIST_TOP - scrollY;
|
||||
for (let index = 0; index < rows.length; index++) {
|
||||
const row = rows[index]!;
|
||||
if (cursorY + row.height >= LIST_TOP && cursorY <= listBottom) {
|
||||
drawEventRow(image, font, row, ROW_X, cursorY, width, index === this.selectedIndex);
|
||||
}
|
||||
cursorY += row.height + ROW_GAP;
|
||||
if (cursorY > listBottom + 80) break;
|
||||
}
|
||||
return image;
|
||||
}
|
||||
|
||||
handleInput(event: DashboardInputEvent): void {
|
||||
if (!hasCalendarPermission()) {
|
||||
// Any tap on the prompt re-triggers the phone-side permission request.
|
||||
if (event.type === "click") this.requestPermission();
|
||||
return;
|
||||
}
|
||||
const rows = buildEventRows(readUpcomingEvents(MAX_EVENTS));
|
||||
if (!rows.length) return;
|
||||
if (event.type === "scroll-up") {
|
||||
this.selectedIndex = Math.max(0, this.selectedIndex - 1);
|
||||
} else if (event.type === "scroll-down") {
|
||||
this.selectedIndex = Math.min(rows.length - 1, this.selectedIndex + 1);
|
||||
}
|
||||
}
|
||||
|
||||
private paintPermissionPrompt(image: GrayImage, font: BdfFont, width: number, height: number): void {
|
||||
const message = "Grant calendar permission on your phone to see your events on the glasses.";
|
||||
const lines = wrapText(font, message, width - 48);
|
||||
for (let index = 0; index < lines.length; index++) {
|
||||
image.drawText(font, 24, 72 + index * LINE_HEIGHT, lines[index]!, 190);
|
||||
}
|
||||
image.drawText(font, 24, height - 36, `${GESTURE_CLICK} request ${GESTURE_DOUBLE_CLICK} back`, 110);
|
||||
}
|
||||
}
|
||||
|
||||
function buildEventRows(events: CalendarEvent[]): EventRow[] {
|
||||
const rows: EventRow[] = [];
|
||||
let previousDayKey = "";
|
||||
for (const event of events) {
|
||||
const dayKey = dayKeyOf(event.startMs);
|
||||
const dayHeader = dayKey === previousDayKey ? null : dayHeaderLabel(event.startMs);
|
||||
previousDayKey = dayKey;
|
||||
|
||||
const lines: string[] = [];
|
||||
const timeLabel = event.allDay ? "All day" : formatEventTime(event.startMs);
|
||||
lines.push(`${timeLabel} ${event.title || "(untitled)"}`);
|
||||
if (event.location) {
|
||||
lines.push(event.location);
|
||||
}
|
||||
|
||||
rows.push({
|
||||
event,
|
||||
dayHeader,
|
||||
lines,
|
||||
height: (dayHeader ? DAY_HEADER_HEIGHT : 0) + 6 + lines.length * LINE_HEIGHT,
|
||||
});
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
function drawEventRow(
|
||||
image: GrayImage,
|
||||
font: BdfFont,
|
||||
row: EventRow,
|
||||
x: number,
|
||||
y: number,
|
||||
width: number,
|
||||
selected: boolean,
|
||||
): void {
|
||||
let cursorY = y;
|
||||
if (row.dayHeader) {
|
||||
image.drawText(font, x, cursorY + 2, row.dayHeader, 150);
|
||||
cursorY += DAY_HEADER_HEIGHT;
|
||||
}
|
||||
const bodyHeight = row.lines.length * LINE_HEIGHT + 4;
|
||||
if (selected) {
|
||||
image.fillRoundedRect(x - 6, cursorY, width - 2 * (x - 6), bodyHeight, 15, 6);
|
||||
image.drawRoundedRect(x - 6, cursorY, width - 2 * (x - 6), bodyHeight, 90, 6);
|
||||
}
|
||||
const maxTextWidth = width - 2 * x;
|
||||
for (let index = 0; index < row.lines.length; index++) {
|
||||
const value = index === 0 ? (selected ? 235 : 205) : 160;
|
||||
image.drawText(font, x, cursorY + 3 + index * LINE_HEIGHT, truncateToWidth(font, row.lines[index]!, maxTextWidth), value);
|
||||
}
|
||||
}
|
||||
|
||||
function scrollForSelected(rows: EventRow[], selectedIndex: number, viewportHeight: number): number {
|
||||
let selectedTop = 0;
|
||||
for (let index = 0; index < selectedIndex; index++) {
|
||||
selectedTop += rows[index]!.height + ROW_GAP;
|
||||
}
|
||||
const selectedBottom = selectedTop + rows[selectedIndex]!.height;
|
||||
const contentHeight = rows.reduce((sum, row) => sum + row.height + ROW_GAP, 0);
|
||||
const maxScroll = Math.max(0, contentHeight - viewportHeight);
|
||||
const centered = selectedTop - Math.max(0, (viewportHeight - (selectedBottom - selectedTop)) / 2);
|
||||
return clamp(centered | 0, 0, maxScroll);
|
||||
}
|
||||
|
||||
function dayKeyOf(timestampMs: number): string {
|
||||
const date = new Date(timestampMs);
|
||||
return `${date.getFullYear()}-${date.getMonth()}-${date.getDate()}`;
|
||||
}
|
||||
|
||||
function dayHeaderLabel(timestampMs: number): string {
|
||||
const date = new Date(timestampMs);
|
||||
const now = new Date();
|
||||
const midnight = (d: Date) => new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
|
||||
const dayDelta = Math.round((midnight(date) - midnight(now)) / (24 * 60 * 60 * 1000));
|
||||
const base = `${WEEKDAYS[date.getDay()]} ${date.getDate()} ${MONTHS[date.getMonth()]}`;
|
||||
if (dayDelta === 0) return `Today ${base}`;
|
||||
if (dayDelta === 1) return `Tomorrow ${base}`;
|
||||
return base;
|
||||
}
|
||||
|
||||
function formatEventTime(timestampMs: number): string {
|
||||
const date = new Date(timestampMs);
|
||||
const minutes = String(date.getMinutes()).padStart(2, "0");
|
||||
const hour24 = date.getHours();
|
||||
if (timeFormatSetting.get() === "12h") {
|
||||
const hour12 = ((hour24 + 11) % 12) + 1;
|
||||
return `${hour12}:${minutes} ${hour24 < 12 ? "AM" : "PM"}`;
|
||||
}
|
||||
return `${String(hour24).padStart(2, "0")}:${minutes}`;
|
||||
}
|
||||
|
||||
function truncateToWidth(font: BdfFont, text: string, width: number): string {
|
||||
if (font.measureText(text) <= width) return text;
|
||||
let out = text;
|
||||
while (out.length > 1 && font.measureText(`${out}...`) > width) {
|
||||
out = out.slice(0, -1);
|
||||
}
|
||||
return `${out}...`;
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import { ensureCalendarPermission, hasCalendarPermission } from "../../g2/android-permissions";
|
||||
import { invalidateCalendarCache } from "../../native/calendar";
|
||||
import { CalendarLayer } from "../apps/calendar";
|
||||
import {
|
||||
createInProcessWindow,
|
||||
YieldAtRootLayer,
|
||||
type InProcessAppOptions,
|
||||
type InProcessWindow,
|
||||
} from "./in-process-window";
|
||||
|
||||
export const CALENDAR_WINDOW_ID = "calendar";
|
||||
export const CALENDAR_SURFACE_ID = "window:calendar";
|
||||
|
||||
/**
|
||||
* The Calendar app: a single screen listing upcoming events from the Android
|
||||
* Calendar provider. If calendar permission is missing it shows a prompt and
|
||||
* fires the system permission dialog (on launch and on any tap); once granted
|
||||
* it re-renders with the event list.
|
||||
*/
|
||||
export function createCalendarAppWindow(options: InProcessAppOptions): InProcessWindow {
|
||||
let requesting = false;
|
||||
let app: InProcessWindow;
|
||||
|
||||
const requestPermission = () => {
|
||||
if (requesting || hasCalendarPermission()) return;
|
||||
requesting = true;
|
||||
void ensureCalendarPermission().then((granted) => {
|
||||
requesting = false;
|
||||
if (granted) {
|
||||
invalidateCalendarCache();
|
||||
app.requestRender();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
app = createInProcessWindow({
|
||||
appId: "calendar",
|
||||
windowId: CALENDAR_WINDOW_ID,
|
||||
title: "Calendar",
|
||||
iconLetter: "Ca",
|
||||
icon: "calendar",
|
||||
closeable: true,
|
||||
actions: options.actions,
|
||||
baseLayer: new YieldAtRootLayer(new CalendarLayer(requestPermission)),
|
||||
submitFrame: options.submitFrame,
|
||||
setSurfaceVisible: options.setSurfaceVisible,
|
||||
removeSurface: options.removeSurface,
|
||||
onClosed: options.onClosed,
|
||||
});
|
||||
|
||||
// Prompt immediately on launch so the user doesn't have to discover the tap.
|
||||
requestPermission();
|
||||
return app;
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { MenuLayer } from "../menu";
|
||||
import { ScreenTestLayer } from "../apps/screen-test";
|
||||
import { BuzzerDemoLayer } from "../apps/buzzer-demo";
|
||||
import { AccelerometerDemoLayer } from "../apps/accelerometer-demo";
|
||||
import { APP_VIEWPORT } from "./geometry";
|
||||
import {
|
||||
createInProcessWindow,
|
||||
@@ -29,6 +30,12 @@ export function createDebugTestsAppWindow(options: InProcessAppOptions): InProce
|
||||
ctx.stack.push(new BuzzerDemoLayer());
|
||||
},
|
||||
},
|
||||
{
|
||||
label: "Accelerometer demo",
|
||||
onSelect: (ctx) => {
|
||||
ctx.stack.push(new AccelerometerDemoLayer(DEBUG_TESTS_WINDOW_ID, ctx.actions.requestRender));
|
||||
},
|
||||
},
|
||||
],
|
||||
{
|
||||
x: 8,
|
||||
|
||||
@@ -84,6 +84,9 @@ export function createInProcessWindow(options: InProcessWindowOptions): InProces
|
||||
surfaceId: `window:${options.windowId}`,
|
||||
closeable: options.closeable,
|
||||
close: () => {
|
||||
// Fire onRemoved for any pushed layers so they release resources (e.g. a
|
||||
// demo that enabled a hardware stream) even when closed from within.
|
||||
stack.clearToBase();
|
||||
options.onClosed?.();
|
||||
options.removeSurface?.();
|
||||
},
|
||||
|
||||
@@ -367,6 +367,15 @@ class Shell {
|
||||
return this.screenOn && this.focus === "window" && this.foregroundWindow()?.windowId === windowId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a window's content is on screen: it's the foreground window and the
|
||||
* screen is on. Focus-independent — the app viewport stays visible while the
|
||||
* sidebar is focused (the sidebar is just the left strip).
|
||||
*/
|
||||
isWindowVisible(windowId: string): boolean {
|
||||
return this.screenOn && this.foregroundWindow()?.windowId === windowId;
|
||||
}
|
||||
|
||||
private handleSidebarInput(event: DashboardInputEvent): ShellInputOutcome {
|
||||
switch (event.type) {
|
||||
case "double-click":
|
||||
|
||||
Reference in new issue
Block a user