forked from Blendman974/faceclaw
iOS calendar integration
This commit is contained in:
1 parent
50431c7c6f
commit
32063e57cd
18 files changed
+646
-37
No files matched your search
@@ -1,5 +1,5 @@
|
||||
import { ensureCalendarPermission, hasCalendarPermission } from "../../g2/android-permissions";
|
||||
import { invalidateCalendarCache } from "../../native/calendar";
|
||||
import { ensureCalendarPermission, hasCalendarPermission } from "../../native/calendar-permissions";
|
||||
import { invalidateCalendarCache, onCalendarChanged } from "../../native/calendar";
|
||||
import { makeImageWindowIcon, windowIcon } from "../../ui/shell/chrome-layer";
|
||||
import { CalendarLayer } from "./calendar";
|
||||
import { renderCalendarDateIcon } from "./calendar-icon";
|
||||
@@ -14,25 +14,27 @@ 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
|
||||
* The Calendar app: a single screen listing upcoming events from the phone's
|
||||
* calendars. 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;
|
||||
let unsubscribe = () => {};
|
||||
let tick: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
const requestPermission = () => {
|
||||
if (requesting || hasCalendarPermission()) return;
|
||||
requesting = true;
|
||||
void ensureCalendarPermission().then((granted) => {
|
||||
requesting = false;
|
||||
if (granted) {
|
||||
invalidateCalendarCache();
|
||||
app.requestRender();
|
||||
}
|
||||
});
|
||||
}).catch(error => console.warn("Calendar permission failed", error))
|
||||
.finally(() => { requesting = false; });
|
||||
};
|
||||
|
||||
app = createInProcessWindow({
|
||||
@@ -48,9 +50,15 @@ export function createCalendarAppWindow(options: InProcessAppOptions): InProcess
|
||||
submitFrame: options.submitFrame,
|
||||
setSurfaceVisible: options.setSurfaceVisible,
|
||||
removeSurface: options.removeSurface,
|
||||
onClosed: options.onClosed,
|
||||
onClosed: () => {
|
||||
unsubscribe();
|
||||
if (tick !== null) clearInterval(tick);
|
||||
options.onClosed();
|
||||
},
|
||||
});
|
||||
|
||||
unsubscribe = onCalendarChanged(app.requestRender);
|
||||
tick = setInterval(app.requestRender, 30_000);
|
||||
// Prompt immediately on launch so the user doesn't have to discover the tap.
|
||||
requestPermission();
|
||||
return app;
|
||||
|
||||
@@ -2,10 +2,10 @@ import { getDefaultSmallFont } from "../../graphics/ui-fonts";
|
||||
import { GrayImage, type UiFont } from "../../graphics/image";
|
||||
import { wrapText, truncateText } from "../../graphics/textwrap";
|
||||
import { clamp } from "../../util/numeric-util";
|
||||
import { readUpcomingEvents, type CalendarEvent } from "../../native/calendar";
|
||||
import { getCalendarReadState, readUpcomingEvents, type CalendarEvent } from "../../native/calendar";
|
||||
import { timeFormatSetting } from "../../ui/dashboard-settings";
|
||||
import { GESTURE_CLICK, type InputEvent } from "../../ui/gestures";
|
||||
import { hasCalendarPermission } from "../../g2/android-permissions";
|
||||
import { hasCalendarPermission } from "../../native/calendar-permissions";
|
||||
import { type Layer, type LayerContext } from "../../ui/layers";
|
||||
import { lineStep } from "../../ui/metrics";
|
||||
|
||||
@@ -58,7 +58,9 @@ export class CalendarLayer implements Layer {
|
||||
const events = readUpcomingEvents(MAX_EVENTS);
|
||||
if (!events.length) {
|
||||
image.drawText(font, TITLE_X, TITLE_Y, "Calendar", 220);
|
||||
image.drawText(font, 24, 72, "No upcoming events.", 190);
|
||||
const state = getCalendarReadState();
|
||||
image.drawText(font, 24, 72, state === "loading" ? "Loading calendar..."
|
||||
: state === "error" ? "Calendar unavailable. Try again shortly." : "No upcoming events.", 190);
|
||||
return image;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { type GrayImage, type UiFont } from "../../../graphics/image";
|
||||
import { truncateText } from "../../../graphics/textwrap";
|
||||
import { getDefaultMediumFont, getDefaultSmallFont } from "../../../graphics/ui-fonts";
|
||||
import { hasCalendarPermission } from "../../../g2/android-permissions";
|
||||
import { readUpcomingEvents, type CalendarEvent } from "../../../native/calendar";
|
||||
import { hasCalendarPermission } from "../../../native/calendar-permissions";
|
||||
import { getCalendarReadState, onCalendarChanged, readUpcomingEvents, type CalendarEvent } from "../../../native/calendar";
|
||||
import { lineStep } from "../../../ui/metrics";
|
||||
import { dayHeaderLabel, formatEventTime } from "../../calendar/calendar";
|
||||
import { type GlanceWidget } from "../widget";
|
||||
@@ -22,14 +22,19 @@ const HOUR_MS = 60 * MINUTE_MS;
|
||||
*/
|
||||
export class CalendarWidget implements GlanceWidget {
|
||||
private tick: ReturnType<typeof setInterval> | null = null;
|
||||
private unsubscribe: (() => void) | null = null;
|
||||
|
||||
start(requestRender: () => void): void {
|
||||
this.stop();
|
||||
this.unsubscribe = onCalendarChanged(requestRender);
|
||||
this.tick = setInterval(requestRender, MINUTE_MS);
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
if (this.tick !== null) clearInterval(this.tick);
|
||||
this.tick = null;
|
||||
this.unsubscribe?.();
|
||||
this.unsubscribe = null;
|
||||
}
|
||||
|
||||
paint(image: GrayImage): void {
|
||||
@@ -50,7 +55,9 @@ export class CalendarWidget implements GlanceWidget {
|
||||
const events = readUpcomingEvents().filter((event) => event.endMs > nowMs);
|
||||
if (!events.length) {
|
||||
image.drawText(small, PAD, PAD, "Calendar", 150);
|
||||
image.drawText(small, PAD, PAD + step + 4, "No upcoming events", 140);
|
||||
const state = getCalendarReadState();
|
||||
image.drawText(small, PAD, PAD + step + 4, state === "loading" ? "Loading calendar..."
|
||||
: state === "error" ? "Calendar unavailable" : "No upcoming events", 140);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,6 @@ const unavailable: Record<string, string> = {
|
||||
music: 'Media-player integration is not available on iOS yet.',
|
||||
transcribe: 'Voice capture and transcription are not available on iOS yet.',
|
||||
microphones: 'Glasses microphone capture is not available on iOS yet.',
|
||||
calendar: 'Calendar access is not available on iOS yet.',
|
||||
}
|
||||
export function iosAppUnavailableReason(appId: string): string | null {
|
||||
return unavailable[appId] ?? null
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { readUpcomingEvents, type CalendarEvent } from "../native/calendar";
|
||||
import { readUpcomingEventsAsync, type CalendarEvent } from "../native/calendar";
|
||||
import { hasCalendarPermission } from "../native/calendar-permissions";
|
||||
import { mediaControllerBridge } from "../native/media-controller";
|
||||
import { dismissNotification, readActiveNotifications } from "../native/notification-icons";
|
||||
import { shell } from "../ui/shell/shell";
|
||||
@@ -54,9 +55,6 @@ export function registerSystemTools(registry: ToolRegistry = toolRegistry): void
|
||||
},
|
||||
);
|
||||
|
||||
// Calendar, phone media and notifications have no iOS backend yet.
|
||||
if (global.isIOS) return;
|
||||
|
||||
registry.registerSystemTool(
|
||||
{
|
||||
name: "calendar.list_events",
|
||||
@@ -74,15 +72,23 @@ export function registerSystemTools(registry: ToolRegistry = toolRegistry): void
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
(args) => {
|
||||
async (args) => {
|
||||
if (!hasCalendarPermission()) return err("Calendar access is not granted. Open Calendar or Permissions on your phone to allow access.");
|
||||
const withinHours = clampNumber(args?.within_hours, 1, 24 * 60, 168);
|
||||
const maxEvents = clampNumber(args?.max_events, 1, 50, 10);
|
||||
const events = readUpcomingEvents(maxEvents, withinHours * 60 * 60 * 1000);
|
||||
if (!events.length) return ok("No upcoming events in that window.");
|
||||
return ok(events.map(formatEvent).join("\n"));
|
||||
try {
|
||||
const events = await readUpcomingEventsAsync(maxEvents, withinHours * 60 * 60 * 1000);
|
||||
if (!events.length) return ok("No upcoming events in that window.");
|
||||
return ok(events.map(formatEvent).join("\n"));
|
||||
} catch {
|
||||
return err("Calendar events could not be read. Check calendar access on your phone and try again.");
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// Phone media and Android notification tools are still platform-specific.
|
||||
if (global.isIOS) return;
|
||||
|
||||
registry.registerSystemTool(
|
||||
{
|
||||
name: "media.now_playing",
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import { Dialogs, Utils } from "@nativescript/core";
|
||||
|
||||
declare const FaceclawCalendar: any;
|
||||
|
||||
export function hasCalendarPermission(): boolean {
|
||||
return FaceclawCalendar.shared().hasPermission();
|
||||
}
|
||||
|
||||
let pending: Promise<boolean> | null = null;
|
||||
|
||||
export function ensureCalendarPermission(): Promise<boolean> {
|
||||
if (hasCalendarPermission()) return Promise.resolve(true);
|
||||
if (!pending) pending = requestPermission().finally(() => { pending = null; });
|
||||
return pending;
|
||||
}
|
||||
|
||||
async function requestPermission(): Promise<boolean> {
|
||||
const calendar = FaceclawCalendar.shared();
|
||||
const status = String(calendar.permissionStatus());
|
||||
if (status === "denied") {
|
||||
const open = await Dialogs.confirm({
|
||||
title: "Calendar Access",
|
||||
message: "Allow calendar access in Settings to display your events on the glasses. On iOS 17 or later, choose Full Access.",
|
||||
okButtonText: "Open Settings",
|
||||
cancelButtonText: "Cancel",
|
||||
});
|
||||
if (open) await Utils.openUrl("app-settings:");
|
||||
return false;
|
||||
}
|
||||
if (status === "restricted") {
|
||||
await Dialogs.alert({
|
||||
title: "Calendar Access Restricted",
|
||||
message: "Calendar access is restricted on this iPhone. Check Screen Time or device management settings.",
|
||||
okButtonText: "OK",
|
||||
});
|
||||
return false;
|
||||
}
|
||||
return new Promise<boolean>((resolve, reject) => {
|
||||
calendar.requestPermission((granted: boolean, error: string | null) => {
|
||||
if (error) reject(new Error(String(error)));
|
||||
else resolve(granted);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { ensureCalendarPermission, hasCalendarPermission } from "../g2/android-permissions";
|
||||
@@ -0,0 +1,12 @@
|
||||
export type CalendarEvent = {
|
||||
/** Android event ID or EventKit event identifier. */
|
||||
id: number | string;
|
||||
title: string;
|
||||
startMs: number;
|
||||
endMs: number;
|
||||
allDay: boolean;
|
||||
location: string;
|
||||
calendarName: string;
|
||||
};
|
||||
|
||||
export type CalendarReadState = "ready" | "loading" | "error";
|
||||
@@ -0,0 +1,122 @@
|
||||
import { hasCalendarPermission } from "./calendar-permissions";
|
||||
import { type CalendarEvent, type CalendarReadState } from "./calendar-types";
|
||||
export type { CalendarEvent } from "./calendar-types";
|
||||
|
||||
declare const FaceclawCalendar: any;
|
||||
|
||||
const DEFAULT_WINDOW_MS = 14 * 24 * 60 * 60 * 1000;
|
||||
const CACHE_MS = 30_000;
|
||||
type Cache = {
|
||||
events: CalendarEvent[];
|
||||
atMs: number;
|
||||
maxEvents: number;
|
||||
windowMs: number;
|
||||
state: CalendarReadState;
|
||||
pending: boolean;
|
||||
};
|
||||
let cache: Cache | null = null;
|
||||
let bound = false;
|
||||
const listeners = new Set<() => void>();
|
||||
|
||||
function calendar(): any {
|
||||
const bridge = FaceclawCalendar.shared();
|
||||
if (!bound) {
|
||||
bound = true;
|
||||
bridge.changeHandler = invalidateCalendarCache;
|
||||
}
|
||||
return bridge;
|
||||
}
|
||||
|
||||
export function onCalendarChanged(listener: () => void): () => void {
|
||||
calendar();
|
||||
listeners.add(listener);
|
||||
return () => { listeners.delete(listener); };
|
||||
}
|
||||
|
||||
function notifyChanged(): void {
|
||||
for (const listener of listeners) listener();
|
||||
}
|
||||
|
||||
export function invalidateCalendarCache(): void {
|
||||
// In-flight callbacks retain their old entry, so cannot restore invalid data.
|
||||
cache = null;
|
||||
notifyChanged();
|
||||
}
|
||||
|
||||
export function getCalendarReadState(): CalendarReadState {
|
||||
return cache?.state ?? "ready";
|
||||
}
|
||||
|
||||
/** Return cached events immediately, refreshing asynchronously when needed. */
|
||||
export function readUpcomingEvents(maxEvents = 50, windowMs = DEFAULT_WINDOW_MS, forceRefresh = false): CalendarEvent[] {
|
||||
if (!hasCalendarPermission()) {
|
||||
cache = null;
|
||||
return [];
|
||||
}
|
||||
maxEvents = Number.isFinite(maxEvents) ? Math.min(200, Math.max(0, Math.round(maxEvents))) : 0;
|
||||
windowMs = Number.isFinite(windowMs) ? Math.min(366 * 24 * 60 * 60 * 1000, Math.max(0, Math.round(windowMs))) : 0;
|
||||
if (!maxEvents || !windowMs) return [];
|
||||
|
||||
const now = Date.now();
|
||||
const sameQuery = cache?.maxEvents === maxEvents && cache?.windowMs === windowMs;
|
||||
if (!sameQuery || !cache!.pending && (forceRefresh || now - cache!.atMs >= CACHE_MS)) {
|
||||
const entry: Cache = {
|
||||
events: sameQuery ? cache!.events : [], atMs: now, maxEvents, windowMs,
|
||||
state: sameQuery && cache!.events.length ? "ready" : "loading", pending: true,
|
||||
};
|
||||
cache = entry;
|
||||
const finish = (json: string, error: string | null) => {
|
||||
if (cache !== entry) return;
|
||||
if (!hasCalendarPermission()) { invalidateCalendarCache(); return; }
|
||||
try {
|
||||
entry.events = parseEvents(json, error, maxEvents, now + windowMs);
|
||||
entry.state = "ready";
|
||||
} catch {
|
||||
entry.events = [];
|
||||
entry.state = "error";
|
||||
}
|
||||
entry.pending = false;
|
||||
entry.atMs = Date.now();
|
||||
notifyChanged();
|
||||
};
|
||||
try { calendar().readUpcomingEventsWindowMsCompletion(maxEvents, windowMs, finish); }
|
||||
catch { finish("[]", "Calendar unavailable"); }
|
||||
}
|
||||
return (cache?.events ?? []).filter(event => event.endMs > now);
|
||||
}
|
||||
|
||||
/** Assistant queries await their own result without replacing the display cache. */
|
||||
export async function readUpcomingEventsAsync(maxEvents = 50, windowMs = DEFAULT_WINDOW_MS): Promise<CalendarEvent[]> {
|
||||
if (!hasCalendarPermission()) throw new Error("Calendar permission is required.");
|
||||
maxEvents = Number.isFinite(maxEvents) ? Math.min(200, Math.max(0, Math.round(maxEvents))) : 0;
|
||||
windowMs = Number.isFinite(windowMs) ? Math.min(366 * 24 * 60 * 60 * 1000, Math.max(0, Math.round(windowMs))) : 0;
|
||||
if (!maxEvents || !windowMs) return [];
|
||||
const endMs = Date.now() + windowMs;
|
||||
return new Promise((resolve, reject) => {
|
||||
calendar().readUpcomingEventsWindowMsCompletion(maxEvents, windowMs, (json: string, error: string | null) => {
|
||||
try {
|
||||
if (!hasCalendarPermission()) throw new Error("Calendar permission is required.");
|
||||
resolve(parseEvents(json, error, maxEvents, endMs));
|
||||
} catch (error) { reject(error); }
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function parseEvents(json: string, error: string | null, maxEvents: number, endMs: number): CalendarEvent[] {
|
||||
if (error) throw new Error(String(error));
|
||||
const rows = JSON.parse(String(json));
|
||||
if (!Array.isArray(rows)) throw new Error("Invalid calendar response");
|
||||
return rows.map(normalizeEvent).filter((event): event is CalendarEvent => event !== null)
|
||||
.filter(event => event.endMs > Date.now() && event.startMs < endMs)
|
||||
.sort((a, b) => a.startMs - b.startMs).slice(0, maxEvents);
|
||||
}
|
||||
|
||||
function normalizeEvent(value: any): CalendarEvent | null {
|
||||
if (!value || typeof value !== "object" || typeof value.startMs !== "number" || typeof value.endMs !== "number" ||
|
||||
!Number.isFinite(value.startMs) || !Number.isFinite(value.endMs) || value.endMs < value.startMs) return null;
|
||||
return {
|
||||
id: String(value.id ?? ""), title: String(value.title ?? ""),
|
||||
startMs: value.startMs, endMs: value.endMs, allDay: Boolean(value.allDay),
|
||||
location: String(value.location ?? ""), calendarName: String(value.calendarName ?? ""),
|
||||
};
|
||||
}
|
||||
+10
-9
@@ -1,6 +1,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";
|
||||
export type { CalendarEvent } from "./calendar-types";
|
||||
|
||||
declare const com: any;
|
||||
|
||||
@@ -10,15 +12,9 @@ declare const com: any;
|
||||
* 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;
|
||||
};
|
||||
// Android reads synchronously; iOS notifies subscribers after background reads.
|
||||
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;
|
||||
@@ -73,6 +69,11 @@ export function readUpcomingEvents(
|
||||
}
|
||||
}
|
||||
|
||||
/** Awaitable API shared with the iOS background reader. */
|
||||
export async function readUpcomingEventsAsync(maxEvents = DEFAULT_MAX_EVENTS, windowMs = DEFAULT_WINDOW_MS): Promise<CalendarEvent[]> {
|
||||
return readUpcomingEvents(maxEvents, windowMs);
|
||||
}
|
||||
|
||||
/** Drop the cached events so the next read re-queries the provider. */
|
||||
export function invalidateCalendarCache(): void {
|
||||
cache = null;
|
||||
|
||||
@@ -2,10 +2,8 @@ import { iosBluetooth } from "../native/ios-bluetooth";
|
||||
import { Application, Dialogs, EventData, Frame, Observable, View } from "@nativescript/core";
|
||||
|
||||
import {
|
||||
ensureCalendarPermission,
|
||||
ensureFineLocationPermission,
|
||||
hasBlePermissions,
|
||||
hasCalendarPermission,
|
||||
hasFineLocationPermission,
|
||||
hasMicrophonePermission,
|
||||
hasPostNotificationsPermission,
|
||||
@@ -13,6 +11,7 @@ import {
|
||||
requestMicrophonePermission,
|
||||
requestPostNotificationsPermission,
|
||||
} from "../g2/android-permissions";
|
||||
import { ensureCalendarPermission, hasCalendarPermission } from "../native/calendar-permissions";
|
||||
import { isIgnoringBatteryOptimizations, requestIgnoreBatteryOptimizations } from "../native/battery-optimization";
|
||||
import { isNotificationListenerEnabled, requestNotificationListenerAccess } from "../native/notification-access";
|
||||
|
||||
@@ -97,6 +96,12 @@ const PERMISSIONS: PermissionDefinition[] = global.isIOS ? [{
|
||||
description: "Needed to communicate with your smart glasses over Bluetooth.", optional: false,
|
||||
isGranted: () => iosBluetooth().state === 5,
|
||||
request: () => iosBluetooth().ensureReady(),
|
||||
}, {
|
||||
id: "calendar", title: "Calendar",
|
||||
description: "Optional: display upcoming events in Calendar and Glanceboard on your glasses. Choose Full Access when asked; Faceclaw only reads events.",
|
||||
optional: true,
|
||||
isGranted: hasCalendarPermission,
|
||||
request: ensureCalendarPermission,
|
||||
}] : ANDROID_PERMISSIONS;
|
||||
|
||||
/** One Repeater card: the permission's copy plus the display-only fields the XML binds. */
|
||||
@@ -110,7 +115,7 @@ export type PermissionCardItem = {
|
||||
};
|
||||
|
||||
/**
|
||||
* The Permissions screen: one card per Android permission Faceclaw uses, with
|
||||
* The Permissions screen: one card per permission Faceclaw uses, with
|
||||
* a checkmark when it is already granted and tap-to-grant otherwise. Reached
|
||||
* both from onboarding (between the disclaimer and the firmware step) and from
|
||||
* the main-screen menu.
|
||||
@@ -152,7 +157,7 @@ export class PermissionsViewModel extends Observable {
|
||||
}
|
||||
|
||||
get instructions(): string {
|
||||
if (global.isIOS) return "Faceclaw uses Bluetooth to communicate with your smart glasses. Tap the card to allow access; a checkmark means Bluetooth is ready.";
|
||||
if (global.isIOS) return "Faceclaw uses Bluetooth to communicate with your smart glasses. Calendar access is optional. Tap a card to allow access; a checkmark means it is ready.";
|
||||
return this.onboarding
|
||||
? `Faceclaw uses these ${global.isIOS ? "iOS" : "Android"} permissions. Tap a card to grant one; a checkmark means it is already granted. ` +
|
||||
"Optional permissions can also be granted later, from the Permissions item in the main-screen menu."
|
||||
@@ -226,7 +231,7 @@ export class PermissionsViewModel extends Observable {
|
||||
try {
|
||||
await definition.request();
|
||||
} catch (error) {
|
||||
if (global.isIOS) await Dialogs.alert({ title: "Bluetooth Unavailable", message: String((error as Error).message ?? error), okButtonText: "OK" });
|
||||
if (global.isIOS) await Dialogs.alert({ title: `${definition.title} Unavailable`, message: String((error as Error).message ?? error), okButtonText: "OK" });
|
||||
// A denial simply leaves the card unchecked; the user can tap again.
|
||||
} finally {
|
||||
this.requesting = false;
|
||||
|
||||
Reference in new issue
Block a user