From 32063e57cd252fe875d9ebc04f55012f308b9d7f Mon Sep 17 00:00:00 2001 From: James Babcock Date: Sat, 19 Sep 2026 20:52:03 -0700 Subject: [PATCH] iOS calendar integration --- App_Resources/iOS/Info.plist | 4 + App_Resources/iOS/build.xcconfig | 2 +- App_Resources/iOS/src/FaceclawCalendar.h | 13 + App_Resources/iOS/src/FaceclawCalendar.m | 115 ++++++++ App_Resources/iOS/src/module.modulemap | 1 + CHANGELOG | 4 + app/apps/calendar/calendar-app.ts | 22 +- app/apps/calendar/calendar.ts | 8 +- .../glanceboard/widgets/calendar-widget.ts | 13 +- app/apps/ios-availability.ts | 1 - app/assistant/system-tools.ts | 22 +- app/native/calendar-permissions.ios.ts | 44 +++ app/native/calendar-permissions.ts | 1 + app/native/calendar-types.ts | 12 + app/native/calendar.ios.ts | 122 ++++++++ app/native/calendar.ts | 19 +- app/phone-ui/permissions-view-model.ts | 15 +- tests/ios-calendar.test.cjs | 265 ++++++++++++++++++ 18 files changed, 646 insertions(+), 37 deletions(-) create mode 100644 App_Resources/iOS/src/FaceclawCalendar.h create mode 100644 App_Resources/iOS/src/FaceclawCalendar.m create mode 100644 app/native/calendar-permissions.ios.ts create mode 100644 app/native/calendar-permissions.ts create mode 100644 app/native/calendar-types.ts create mode 100644 app/native/calendar.ios.ts create mode 100644 tests/ios-calendar.test.cjs diff --git a/App_Resources/iOS/Info.plist b/App_Resources/iOS/Info.plist index 29862f9f..06e087f3 100644 --- a/App_Resources/iOS/Info.plist +++ b/App_Resources/iOS/Info.plist @@ -24,6 +24,10 @@ Faceclaw turns audio from your glasses microphone into text for the app you choose. Dictation uses on-device recognition. NSCameraUsageDescription Faceclaw uses the camera to scan QR codes for app URLs you open in Developer. + NSCalendarsUsageDescription + Faceclaw reads your upcoming calendar events to display them in Calendar and Glanceboard on your glasses. + NSCalendarsFullAccessUsageDescription + Faceclaw reads your upcoming calendar events to display them in Calendar and Glanceboard on your glasses. Faceclaw does not create, edit, or delete events. NSLocationWhenInUseUsageDescription Faceclaw uses your location for local weather, turn-by-turn navigation, and true north on the glasses compass. NSLocationTemporaryUsageDescriptionDictionary diff --git a/App_Resources/iOS/build.xcconfig b/App_Resources/iOS/build.xcconfig index d6de5450..abc28fff 100644 --- a/App_Resources/iOS/build.xcconfig +++ b/App_Resources/iOS/build.xcconfig @@ -3,7 +3,7 @@ TARGETED_DEVICE_FAMILY = 1; CODE_SIGN_STYLE = Automatic; // Select the local signing team in Xcode or pass --teamId to the iOS scripts. -OTHER_LDFLAGS = $(inherited) -framework CoreBluetooth -framework CoreLocation -framework CoreText -framework Speech -framework AVFoundation -framework WebKit -framework UniformTypeIdentifiers -framework ImageIO +OTHER_LDFLAGS = $(inherited) -framework CoreBluetooth -framework CoreLocation -framework CoreText -framework Speech -framework AVFoundation -framework WebKit -framework UniformTypeIdentifiers -framework ImageIO -framework EventKit ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; diff --git a/App_Resources/iOS/src/FaceclawCalendar.h b/App_Resources/iOS/src/FaceclawCalendar.h new file mode 100644 index 00000000..d76ed117 --- /dev/null +++ b/App_Resources/iOS/src/FaceclawCalendar.h @@ -0,0 +1,13 @@ +#import + +/** Read-only EventKit bridge. Callbacks are delivered on the main queue. */ +@interface FaceclawCalendar : NSObject ++ (instancetype)shared; +@property(nonatomic, copy) void (^changeHandler)(void); +- (BOOL)hasPermission; +- (NSString *)permissionStatus; +- (void)requestPermission:(void (^)(BOOL granted, NSString *error))completion; +- (void)readUpcomingEvents:(NSInteger)maxEvents + windowMs:(double)windowMs + completion:(void (^)(NSString *json, NSString *error))completion; +@end diff --git a/App_Resources/iOS/src/FaceclawCalendar.m b/App_Resources/iOS/src/FaceclawCalendar.m new file mode 100644 index 00000000..78c247f9 --- /dev/null +++ b/App_Resources/iOS/src/FaceclawCalendar.m @@ -0,0 +1,115 @@ +#import "FaceclawCalendar.h" +#import +#import +#import + +@interface FaceclawCalendar () +@property(nonatomic, strong) EKEventStore *store; +@property(nonatomic, strong) dispatch_queue_t queue; +@end + +@implementation FaceclawCalendar ++ (instancetype)shared { + static FaceclawCalendar *instance; + static dispatch_once_t once; + dispatch_once(&once, ^{ instance = [FaceclawCalendar new]; }); + return instance; +} +- (instancetype)init { + if ((self = [super init])) { + _queue = dispatch_queue_create("com.faceclaw.calendar", DISPATCH_QUEUE_SERIAL); + _store = [EKEventStore new]; + NSNotificationCenter *center = NSNotificationCenter.defaultCenter; + [center addObserver:self selector:@selector(calendarChanged:) name:EKEventStoreChangedNotification object:_store]; + // Re-query after Settings changes, calendar sync, or a timezone change. + [center addObserver:self selector:@selector(calendarChanged:) name:UIApplicationDidBecomeActiveNotification object:nil]; + [center addObserver:self selector:@selector(calendarChanged:) name:UIApplicationSignificantTimeChangeNotification object:nil]; + } + return self; +} +- (BOOL)hasPermission { + EKAuthorizationStatus status = [EKEventStore authorizationStatusForEntityType:EKEntityTypeEvent]; + if (@available(iOS 17.0, *)) return status == EKAuthorizationStatusFullAccess; + return status == EKAuthorizationStatusAuthorized; +} +- (NSString *)permissionStatus { + if ([self hasPermission]) return @"granted"; + EKAuthorizationStatus status = [EKEventStore authorizationStatusForEntityType:EKEntityTypeEvent]; + if (status == EKAuthorizationStatusDenied) return @"denied"; + if (status == EKAuthorizationStatusRestricted) return @"restricted"; + if (@available(iOS 17.0, *)) { + if (status == EKAuthorizationStatusWriteOnly) return @"write-only"; + } + return @"not-determined"; +} +- (void)calendarChanged:(NSNotification *)notification { + dispatch_async(dispatch_get_main_queue(), ^{ + if (self.changeHandler) self.changeHandler(); + }); +} +- (void)requestPermission:(void (^)(BOOL, NSString *))completion { + dispatch_async(self.queue, ^{ + if ([self hasPermission]) { + dispatch_async(dispatch_get_main_queue(), ^{ completion(YES, nil); }); + return; + } + void (^done)(BOOL, NSError *) = ^(BOOL granted, NSError *error) { + dispatch_async(self.queue, ^{ + // Discard objects fetched under the previous authorization. + [self.store reset]; + dispatch_async(dispatch_get_main_queue(), ^{ + if (self.changeHandler) self.changeHandler(); + completion(granted && [self hasPermission], error.localizedDescription); + }); + }); + }; + if (@available(iOS 17.0, *)) { + [self.store requestFullAccessToEventsWithCompletion:done]; + } else { + [self.store requestAccessToEntityType:EKEntityTypeEvent completion:done]; + } + }); +} +- (void)readUpcomingEvents:(NSInteger)maxEvents windowMs:(double)windowMs completion:(void (^)(NSString *, NSString *))completion { + // EventKit queries may block. Never query on the glasses render thread. + dispatch_async(self.queue, ^{ + if (![self hasPermission] || maxEvents <= 0 || !isfinite(windowMs) || windowMs <= 0) { + dispatch_async(dispatch_get_main_queue(), ^{ completion(@"[]", nil); }); + return; + } + @try { + NSDate *now = [NSDate date]; + // Bound the query well below EventKit's four-year predicate limit. + NSDate *end = [now dateByAddingTimeInterval:MIN(windowMs / 1000.0, 366 * 24 * 60 * 60)]; + NSPredicate *predicate = [self.store predicateForEventsWithStartDate:now endDate:end calendars:nil]; + // EventKit expands recurring events and includes overlapping events. + NSArray *events = [[self.store eventsMatchingPredicate:predicate] + sortedArrayUsingComparator:^NSComparisonResult(EKEvent *a, EKEvent *b) { + NSComparisonResult order = [a.startDate compare:b.startDate]; + return order == NSOrderedSame ? [(a.eventIdentifier ?: @"") compare:(b.eventIdentifier ?: @"")] : order; + }]; + NSMutableArray *rows = [NSMutableArray new]; + for (EKEvent *event in events) { + if (!event.startDate || !event.endDate || event.status == EKEventStatusCanceled || + [event.endDate compare:now] != NSOrderedDescending || [event.startDate compare:end] != NSOrderedAscending) continue; + [rows addObject:@{ + @"id": event.eventIdentifier ?: @"", + @"title": event.title ?: @"", + @"startMs": @(event.startDate.timeIntervalSince1970 * 1000.0), + @"endMs": @(event.endDate.timeIntervalSince1970 * 1000.0), + @"allDay": @(event.allDay), + @"location": event.location ?: @"", + @"calendarName": event.calendar.title ?: @"" + }]; + if (rows.count >= MIN(200, maxEvents)) break; + } + NSError *error = nil; + NSData *data = [NSJSONSerialization dataWithJSONObject:rows options:0 error:&error]; + NSString *json = data ? [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] : @"[]"; + dispatch_async(dispatch_get_main_queue(), ^{ completion(json, error.localizedDescription); }); + } @catch (NSException *exception) { + dispatch_async(dispatch_get_main_queue(), ^{ completion(@"[]", exception.reason ?: @"Calendar unavailable"); }); + } + }); +} +@end diff --git a/App_Resources/iOS/src/module.modulemap b/App_Resources/iOS/src/module.modulemap index 30f457d4..7287d6bf 100644 --- a/App_Resources/iOS/src/module.modulemap +++ b/App_Resources/iOS/src/module.modulemap @@ -7,6 +7,7 @@ module FaceclawGraphics { header "FaceclawSpeech.h" header "FaceclawSseRequest.h" header "FaceclawLocation.h" + header "FaceclawCalendar.h" header "FaceclawConfigPort.h" header "FaceclawEvenHubWebView.h" header "FaceclawCrypto.h" diff --git a/CHANGELOG b/CHANGELOG index 25cc9f8c..26f499e9 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,5 +1,9 @@ # Changelog +## 0.7.3 - Future + +* Add iOS calendar integration + ## 0.7.2 - 2026-09-19 * Rebase to firmware 2.3.0, fixing an issue with some R1 ring input events being lost diff --git a/app/apps/calendar/calendar-app.ts b/app/apps/calendar/calendar-app.ts index fddf39fd..80098e9b 100644 --- a/app/apps/calendar/calendar-app.ts +++ b/app/apps/calendar/calendar-app.ts @@ -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 | 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; diff --git a/app/apps/calendar/calendar.ts b/app/apps/calendar/calendar.ts index d2cc8629..4272cd97 100644 --- a/app/apps/calendar/calendar.ts +++ b/app/apps/calendar/calendar.ts @@ -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; } diff --git a/app/apps/glanceboard/widgets/calendar-widget.ts b/app/apps/glanceboard/widgets/calendar-widget.ts index 85f74ff4..4607cd55 100644 --- a/app/apps/glanceboard/widgets/calendar-widget.ts +++ b/app/apps/glanceboard/widgets/calendar-widget.ts @@ -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 | 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; } diff --git a/app/apps/ios-availability.ts b/app/apps/ios-availability.ts index e1eb7d24..c2f062c3 100644 --- a/app/apps/ios-availability.ts +++ b/app/apps/ios-availability.ts @@ -3,7 +3,6 @@ const unavailable: Record = { 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 diff --git a/app/assistant/system-tools.ts b/app/assistant/system-tools.ts index 206a9555..75309775 100644 --- a/app/assistant/system-tools.ts +++ b/app/assistant/system-tools.ts @@ -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", diff --git a/app/native/calendar-permissions.ios.ts b/app/native/calendar-permissions.ios.ts new file mode 100644 index 00000000..5758f457 --- /dev/null +++ b/app/native/calendar-permissions.ios.ts @@ -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 | null = null; + +export function ensureCalendarPermission(): Promise { + if (hasCalendarPermission()) return Promise.resolve(true); + if (!pending) pending = requestPermission().finally(() => { pending = null; }); + return pending; +} + +async function requestPermission(): Promise { + 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((resolve, reject) => { + calendar.requestPermission((granted: boolean, error: string | null) => { + if (error) reject(new Error(String(error))); + else resolve(granted); + }); + }); +} diff --git a/app/native/calendar-permissions.ts b/app/native/calendar-permissions.ts new file mode 100644 index 00000000..3a3b9625 --- /dev/null +++ b/app/native/calendar-permissions.ts @@ -0,0 +1 @@ +export { ensureCalendarPermission, hasCalendarPermission } from "../g2/android-permissions"; diff --git a/app/native/calendar-types.ts b/app/native/calendar-types.ts new file mode 100644 index 00000000..5b1381d7 --- /dev/null +++ b/app/native/calendar-types.ts @@ -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"; diff --git a/app/native/calendar.ios.ts b/app/native/calendar.ios.ts new file mode 100644 index 00000000..4b8b1c88 --- /dev/null +++ b/app/native/calendar.ios.ts @@ -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 { + 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 ?? ""), + }; +} diff --git a/app/native/calendar.ts b/app/native/calendar.ts index bd8e9e43..8768947b 100644 --- a/app/native/calendar.ts +++ b/app/native/calendar.ts @@ -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 { + return readUpcomingEvents(maxEvents, windowMs); +} + /** Drop the cached events so the next read re-queries the provider. */ export function invalidateCalendarCache(): void { cache = null; diff --git a/app/phone-ui/permissions-view-model.ts b/app/phone-ui/permissions-view-model.ts index 25195a94..a8f02e8d 100644 --- a/app/phone-ui/permissions-view-model.ts +++ b/app/phone-ui/permissions-view-model.ts @@ -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; diff --git a/tests/ios-calendar.test.cjs b/tests/ios-calendar.test.cjs new file mode 100644 index 00000000..7a8e93d6 --- /dev/null +++ b/tests/ios-calendar.test.cjs @@ -0,0 +1,265 @@ +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'); + +function load(file, modules = {}, globals = {}) { + const sandbox = { exports: {}, require: id => { + if (!(id in modules)) throw new Error(`Unstubbed import: ${id}`); + return modules[id]; + }, ...globals }; + vm.runInNewContext(ts.transpileModule(fs.readFileSync(path.join(__dirname, '..', file), 'utf8'), { + compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 }, + }).outputText, sandbox); + return sandbox.exports; +} +const flush = () => new Promise(resolve => setImmediate(resolve)); + +function provider() { + let now = 1000000, granted = true; + const reads = []; + const bridge = { readUpcomingEventsWindowMsCompletion: (max, window, done) => reads.push({ max, window, done }) }; + const permissions = { hasCalendarPermission: () => granted }; + const clock = { Date: class extends Date { static now() { return now; } } }; + const api = load('app/native/calendar.ios.ts', { './calendar-permissions': permissions }, { + FaceclawCalendar: { shared: () => bridge }, ...clock, + }); + const event = (id, extra = {}) => ({ id, title: 'Meeting', startMs: now + 10000, endMs: now + 60000, + allDay: false, location: 'Office', calendarName: 'Work', ...extra }); + return { api, bridge, reads, permissions, event, clock, advance: ms => { now += ms; }, permission: value => { granted = value; } }; +} + +test('iOS calendar reads asynchronously, shares pending work, caches, and expires ended events', () => { + const f = provider(); let changes = 0; + f.api.onCalendarChanged(() => changes++); + assert.equal(f.api.readUpcomingEvents().length, 0); + assert.equal(f.api.getCalendarReadState(), 'loading'); + f.api.readUpcomingEvents(); assert.equal(f.reads.length, 1); + assert.equal(f.reads[0].max, 50); assert.equal(f.reads[0].window, 14 * 86400000); + f.reads[0].done(JSON.stringify([f.event('one')]), null); + assert.equal(changes, 1); assert.equal(f.api.getCalendarReadState(), 'ready'); + assert.equal(f.api.readUpcomingEvents()[0].id, 'one'); assert.equal(f.reads.length, 1); + f.advance(30000); assert.equal(f.api.readUpcomingEvents()[0].id, 'one'); + f.api.readUpcomingEvents(); assert.equal(f.reads.length, 2); + f.advance(30001); assert.equal(f.api.readUpcomingEvents().length, 0, 'ended events disappear even during refresh'); +}); + +test('iOS calendar preserves recurrence occurrences, all-day fields and overlapping events, and sorts before limiting', () => { + const f = provider(); f.api.readUpcomingEvents(3, 100000); + f.reads[0].done(JSON.stringify([ + f.event('series', { startMs: 1080000, endMs: 1090000 }), + f.event('later', { startMs: 1090000, endMs: 1095000 }), + f.event('series', { startMs: 1030000, endMs: 1040000 }), + f.event('all-day', { startMs: 900000, allDay: true, location: '', calendarName: 'Personal' }), + f.event('ended', { startMs: 900000, endMs: 999999 }), + f.event('outside', { startMs: 1100000, endMs: 1110000 }), + f.event('bad', { startMs: null }), f.event('bad-end', { endMs: 'invalid' }), null, + ]), null); + const rows = f.api.readUpcomingEvents(3, 100000); + assert.deepEqual(Array.from(rows, e => e.id), ['all-day', 'series', 'series']); + assert.equal(rows[0].allDay, true); assert.equal(rows[0].calendarName, 'Personal'); + assert.equal(rows[0].startMs, 900000); assert.equal(rows[0].location, ''); +}); + +test('event-store changes invalidate pending reads and notify only active subscribers', () => { + const f = provider(); let changes = 0; + const off = f.api.onCalendarChanged(() => changes++); + f.api.readUpcomingEvents(); const old = f.reads[0]; + f.bridge.changeHandler(); assert.equal(changes, 1); + f.api.readUpcomingEvents(); old.done(JSON.stringify([f.event('stale')]), null); + assert.equal(f.api.getCalendarReadState(), 'loading'); assert.equal(changes, 1); + f.reads[1].done(JSON.stringify([f.event('fresh')]), null); + assert.equal(f.api.readUpcomingEvents()[0].id, 'fresh'); assert.equal(changes, 2); + off(); f.bridge.changeHandler(); assert.equal(changes, 2); +}); + +test('permission revocation prevents cached and in-flight calendar data from resurfacing', () => { + const f = provider(); f.api.readUpcomingEvents(); + f.reads[0].done(JSON.stringify([f.event('private')]), null); + f.permission(false); assert.equal(f.api.readUpcomingEvents().length, 0); + f.permission(true); f.api.readUpcomingEvents(); + f.permission(false); f.reads[1].done(JSON.stringify([f.event('private')]), null); + assert.equal(f.api.readUpcomingEvents().length, 0); + f.permission(true); assert.equal(f.api.readUpcomingEvents().length, 0); + assert.equal(f.reads.length, 3); +}); + +test('calendar read failures have a distinct state and retry after the cache interval', () => { + for (const [json, error] of [['[]', 'Unavailable'], ['bad json', null], ['{}', null]]) { + const f = provider(); f.api.readUpcomingEvents(); f.reads[0].done(json, error); + assert.equal(f.api.getCalendarReadState(), 'error'); + assert.equal(f.api.readUpcomingEvents().length, 0); assert.equal(f.reads.length, 1); + f.advance(30000); f.api.readUpcomingEvents(); + f.reads[1].done('[]', null); assert.equal(f.api.getCalendarReadState(), 'ready'); + } +}); + +test('calendar input bounds, query changes and force refresh do not reuse the wrong result', () => { + const f = provider(); + for (const value of [0, -1, NaN, Infinity]) assert.equal(f.api.readUpcomingEvents(value).length, 0); + f.api.readUpcomingEvents(5, 0); f.api.readUpcomingEvents(5, NaN); assert.equal(f.reads.length, 0); + f.api.readUpcomingEvents(999, Number.MAX_VALUE); + assert.equal(f.reads[0].max, 200); assert.equal(f.reads[0].window, 366 * 86400000); + f.api.readUpcomingEvents(); f.reads[0].done(JSON.stringify([f.event('wrong-query')]), null); + assert.equal(f.api.readUpcomingEvents().length, 0); + f.reads[1].done(JSON.stringify([f.event('right-query')]), null); + assert.equal(f.api.readUpcomingEvents(50, 14 * 86400000, true)[0].id, 'right-query'); + assert.equal(f.reads.length, 3); +}); + +function permissionFixture(initial = 'not-determined') { + let status = initial, confirm = true; + const requests = [], dialogs = [], opened = []; + const api = load('app/native/calendar-permissions.ios.ts', { + '@nativescript/core': { + Dialogs: { confirm: async options => { dialogs.push(options); return confirm; }, alert: async options => { dialogs.push(options); } }, + Utils: { openUrl: async url => opened.push(url) }, + }, + }, { FaceclawCalendar: { shared: () => ({ hasPermission: () => status === 'granted', + permissionStatus: () => status, requestPermission: done => requests.push(done) }) } }); + return { api, requests, dialogs, opened, status: value => { status = value; }, confirm: value => { confirm = value; } }; +} + +test('calendar permission requests coalesce, allow write-only upgrades, and propagate failures', async () => { + for (const status of ['not-determined', 'write-only']) { + const f = permissionFixture(status); + assert.equal(f.api.hasCalendarPermission(), false); + const first = f.api.ensureCalendarPermission(); assert.equal(f.api.ensureCalendarPermission(), first); + assert.equal(f.requests.length, 1); f.requests[0](false, null); assert.equal(await first, false); + const retry = f.api.ensureCalendarPermission(); f.requests[1](false, 'Native failure'); + await assert.rejects(retry, /Native failure/); + const grant = f.api.ensureCalendarPermission(); f.status('granted'); f.requests[2](true, null); + assert.equal(await grant, true); assert.equal(await f.api.ensureCalendarPermission(), true); + assert.equal(f.requests.length, 3); + } +}); + +test('denied calendar access offers Settings; restricted access explains the restriction', async () => { + const denied = permissionFixture('denied'); + denied.confirm(false); assert.equal(await denied.api.ensureCalendarPermission(), false); + assert.equal(denied.opened.length, 0); + denied.confirm(true); await denied.api.ensureCalendarPermission(); + assert.deepEqual(denied.opened, ['app-settings:']); assert.equal(denied.requests.length, 0); + const restricted = permissionFixture('restricted'); await restricted.api.ensureCalendarPermission(); + assert.match(restricted.dialogs[0].title, /Restricted/); + assert.equal(restricted.requests.length, 0); assert.equal(restricted.opened.length, 0); +}); + +function screenFixture() { + const f = provider(), timers = new Map(); let nextTimer = 0; + const font = { lineHeight: 12, measureText: text => text.length * 6 }; + class Image { + constructor(width = 300, height = 288) { this.width = width; this.height = height; this.text = []; } + drawText(_font, _x, _y, text) { this.text.push(text); } + fillRoundedRect() {} drawRoundedRect() {} + } + const common = { + 'graphics/image': { GrayImage: Image }, 'graphics/ui-fonts': { getDefaultSmallFont: () => font, getDefaultMediumFont: () => font }, + 'graphics/textwrap': { truncateText: (_font, text) => text, wrapText: (_font, text) => [text] }, + 'native/calendar': f.api, 'native/calendar-permissions': f.permissions, 'ui/metrics': { lineStep: () => 14 }, + 'ui/dashboard-settings': { timeFormatSetting: { get: () => '24h' } }, 'ui/gestures': { GESTURE_CLICK: 'Tap' }, + 'util/numeric-util': { clamp: (n, min, max) => Math.max(min, Math.min(max, n)) }, + }; + const modules = depth => Object.fromEntries(Object.entries(common).map(([key, value]) => [depth + key, value])); + const calendar = load('app/apps/calendar/calendar.ts', modules('../../')); + const widget = load('app/apps/glanceboard/widgets/calendar-widget.ts', { + ...modules('../../../'), '../../calendar/calendar': calendar, + }, { ...f.clock, setInterval: fn => { timers.set(++nextTimer, fn); return nextTimer; }, clearInterval: id => timers.delete(id) }); + return { ...f, ...calendar, ...widget, timers, Image }; +} + +test('Calendar and Glanceboard show permission, loading, error and event states with widget cleanup', () => { + const f = screenFixture(); let renders = 0, requests = 0; + const widget = new f.CalendarWidget(), layer = new f.CalendarLayer(() => requests++); + const ctx = { stack: { getBaseSize: () => ({ width: 300, height: 288 }) } }; + const paintWidget = () => { const image = new f.Image(); widget.paint(image); return image.text.join(' '); }; + widget.start(() => renders++); widget.start(() => renders++); assert.equal(f.timers.size, 1); + f.permission(false); assert.match(layer.paint(ctx).text.join(' '), /Grant calendar permission/); + assert.match(paintWidget(), /permission needed/); + layer.handleInput({ type: 'click' }); assert.equal(requests, 1); assert.equal(f.reads.length, 0); + f.permission(true); assert.match(layer.paint(ctx).text.join(' '), /Loading/); + assert.match(paintWidget(), /Loading/); + f.reads[0].done('[]', 'Unavailable'); assert.match(layer.paint(ctx).text.join(' '), /unavailable/); + assert.match(paintWidget(), /unavailable/); + f.api.invalidateCalendarCache(); layer.paint(ctx); + f.reads[1].done(JSON.stringify([f.event('event')]), null); + assert.match(layer.paint(ctx).text.join(' '), /Meeting/); + assert.match(paintWidget(), /Meeting/); + widget.stop(); const before = renders; f.bridge.changeHandler(); + assert.equal(renders, before); assert.equal(f.timers.size, 0); +}); + +test('Calendar window subscribes, refreshes periodically, and cleans up on close', async () => { + let options, listener, tick, unsubscribed = 0, cleared = 0, closed = 0, renders = 0; + const app = { requestRender: () => renders++ }; + const { createCalendarAppWindow } = load('app/apps/calendar/calendar-app.ts', { + '../../native/calendar-permissions': { hasCalendarPermission: () => true }, + '../../native/calendar': { onCalendarChanged: fn => { listener = fn; return () => unsubscribed++; } }, + '../../ui/shell/chrome-layer': { makeImageWindowIcon() {}, windowIcon() {} }, + './calendar': { CalendarLayer: class {} }, './calendar-icon': {}, + '../../ui/shell/in-process-window': { YieldAtRootLayer: class {}, createInProcessWindow: value => { options = value; return app; } }, + }, { setInterval: fn => { tick = fn; return 1; }, clearInterval: () => cleared++ }); + createCalendarAppWindow({ onClosed: () => closed++ }); + listener(); tick(); assert.equal(renders, 2); + options.onClosed(); assert.equal(unsubscribed, 1); assert.equal(cleared, 1); assert.equal(closed, 1); +}); + +test('iOS Calendar is launchable and its permission remains optional during onboarding', async () => { + const availability = load('app/apps/ios-availability.ts'); + assert.equal(availability.iosAppUnavailableReason('calendar'), null); + const f = permissionFixture(); let resumed; + const { PermissionsViewModel } = load('app/phone-ui/permissions-view-model.ts', { + '@nativescript/core': { Observable: class { notifyPropertyChange() {} }, + Application: { on: (_event, fn) => { resumed = fn; }, off() {} } }, + '../native/ios-bluetooth': { iosBluetooth: () => ({ state: 5 }) }, + '../native/calendar-permissions': f.api, + '../g2/android-permissions': {}, '../native/battery-optimization': {}, '../native/notification-access': {}, + }, { global: { isIOS: true } }); + const model = new PermissionsViewModel({ onboarding: true }); model.onPageLoaded(); + const card = () => model.cards.find(item => item.id === 'calendar'); + assert.equal(card().optionalVisibility, 'visible'); assert.equal(card().checkVisibility, 'collapse'); + assert.equal(model.primaryClass, '-primary'); + model.onCardTap({ object: { bindingContext: card() } }); assert.equal(f.requests.length, 1); + f.status('granted'); f.requests[0](true, null); await flush(); + assert.equal(card().checkVisibility, 'visible'); + f.status('denied'); resumed(); assert.equal(card().checkVisibility, 'collapse'); +}); + +test('awaited calendar reads do not replace the display cache and reject failures or revoked access', async () => { + const f = provider(); f.api.readUpcomingEvents(); + const awaited = f.api.readUpcomingEventsAsync(10, 3600000); + assert.equal(f.reads[1].max, 10); assert.equal(f.reads[1].window, 3600000); + f.reads[1].done(JSON.stringify([f.event('assistant')]), null); + assert.equal((await awaited)[0].id, 'assistant'); + assert.equal(f.api.getCalendarReadState(), 'loading'); + f.reads[0].done(JSON.stringify([f.event('display')]), null); + assert.equal(f.api.readUpcomingEvents()[0].id, 'display'); + const failed = f.api.readUpcomingEventsAsync(); f.reads[2].done('[]', 'Unavailable'); + await assert.rejects(failed, /Unavailable/); + const revoked = f.api.readUpcomingEventsAsync(); f.permission(false); + f.reads[3].done(JSON.stringify([f.event('private')]), null); + await assert.rejects(revoked, /permission/); + await assert.rejects(f.api.readUpcomingEventsAsync(), /permission/); + assert.equal(f.reads.length, 4); +}); + +test('iOS assistant calendar tool awaits events, reports denied access and failures, and leaves unsupported tools hidden', async () => { + const f = provider(), registered = new Map(); + const { registerSystemTools } = load('app/assistant/system-tools.ts', { + '../native/calendar': f.api, '../native/calendar-permissions': f.permissions, + '../native/media-controller': {}, '../native/notification-icons': {}, '../ui/shell/shell': {}, './tool-registry': {}, + }, { global: { isIOS: true } }); + registerSystemTools({ registerSystemTool: (definition, handler) => registered.set(definition.name, handler) }); + assert.deepEqual([...registered.keys()], ['glasses.get_state', 'glasses.show_alert', 'calendar.list_events']); + const list = registered.get('calendar.list_events'); + const result = list({ within_hours: 2, max_events: 3 }); + assert.equal(f.reads[0].max, 3); assert.equal(f.reads[0].window, 7200000); + f.reads[0].done(JSON.stringify([f.event('one')]), null); + assert.match((await result).content, /Meeting.*Office/); + const empty = list({}); f.reads[1].done('[]', null); + assert.match((await empty).content, /No upcoming/); + const failed = list({}); f.reads[2].done('[]', 'Failed'); assert.equal((await failed).ok, false); + f.permission(false); assert.equal((await list({})).ok, false); assert.equal(f.reads.length, 3); +});