This commit is contained in:
James Babcock committed 2026-08-30 00:42:27 -07:00
commit d542acb891
315 files changed
+35117 -2087

No files matched your search

+15
View File
@@ -0,0 +1,15 @@
import { NavigatedData, Page } from "@nativescript/core";
import { AskViewModel } from "./ask-view-model";
export function navigatingTo(args: NavigatedData): void {
const page = args.object as Page;
if (!page.bindingContext) {
page.bindingContext = new AskViewModel();
}
}
export function unloaded(args: NavigatedData): void {
const page = args.object as Page;
(page.bindingContext as AskViewModel | undefined)?.cancel();
}
+20
View File
@@ -0,0 +1,20 @@
<Page xmlns="http://schemas.nativescript.org/tns.xsd" navigatingTo="navigatingTo" unloaded="unloaded">
<ActionBar title="Ask about conversations" />
<GridLayout rows="auto,auto,auto,*" class="p-8">
<TextField
row="0"
hint="e.g. What did Alice say about the budget last week?"
text="{{ question }}"
returnKeyType="go"
returnPress="{{ onAskTap }}" />
<Button row="1" text="{{ askLabel }}" tap="{{ onAskTap }}" isEnabled="{{ askEnabled }}" class="m-t-4" />
<Label row="2" text="{{ statusText }}" class="conversation-meta m-t-4" textWrap="true" visibility="{{ statusVisibility }}" />
<ScrollView row="3" class="m-t-8">
<StackLayout>
<Label text="{{ answer }}" class="ask-answer" textWrap="true" visibility="{{ answerVisibility }}" />
<Label text="{{ contextNote }}" class="conversation-meta m-t-8" textWrap="true" visibility="{{ noteVisibility }}" />
</StackLayout>
</ScrollView>
</GridLayout>
</Page>
+84
View File
@@ -0,0 +1,84 @@
import { Observable } from "@nativescript/core";
import {
askConversations,
conversationQaAvailable,
} from "../apps/microphones/conversation-qa";
import type { LlmStreamHandle } from "../assistant/llm-protocol";
/**
* "Ask about conversations": free-form questions over the saved transcripts,
* speakers, tags, and metadata, answered entirely on-device by the local
* assistant model. The answer streams in as it generates.
*/
export class AskViewModel extends Observable {
private stream: LlmStreamHandle | null = null;
private busy = false;
constructor() {
super();
this.set("question", "");
this.set("answer", "");
this.set("contextNote", "");
this.set("askLabel", "Ask");
this.set("askEnabled", true);
this.set("answerVisibility", "collapsed");
this.set("noteVisibility", "collapsed");
if (!conversationQaAvailable()) {
this.set(
"statusText",
"The on-phone model isn't downloaded yet. Enable it on the glasses under Settings > Assistant, then come back — questions are answered entirely on-device.",
);
this.set("statusVisibility", "visible");
} else {
this.set("statusText", "");
this.set("statusVisibility", "collapsed");
}
}
onAskTap = (): void => {
const question = String(this.get("question") ?? "").trim();
if (!question || this.busy) return;
this.cancel();
this.busy = true;
this.set("askLabel", "Thinking...");
this.set("askEnabled", false);
this.set("answer", "");
this.set("answerVisibility", "collapsed");
this.set("noteVisibility", "collapsed");
this.set("statusText", "Reading your conversations...");
this.set("statusVisibility", "visible");
this.stream = askConversations(question, {
onDelta: (textSoFar) => {
this.set("answer", textSoFar);
this.set("answerVisibility", "visible");
this.set("statusVisibility", "collapsed");
},
onDone: (answer, contextNote) => {
this.finish();
this.set("answer", answer || "(no answer)");
this.set("answerVisibility", "visible");
this.set("contextNote", contextNote);
this.set("noteVisibility", "visible");
},
onError: (message) => {
this.finish();
this.set("statusText", message);
this.set("statusVisibility", "visible");
},
});
};
cancel(): void {
this.stream?.cancel();
this.stream = null;
if (this.busy) this.finish();
}
private finish(): void {
this.busy = false;
this.stream = null;
this.set("askLabel", "Ask");
this.set("askEnabled", true);
}
}
+2 -2
View File
@@ -4,8 +4,8 @@ import { ConfigViewModel } from "./config-view-model";
export function navigatingTo(args: NavigatedData): void {
const page = args.object as Page;
// Preserve the model across back-navigation (returning from the unpair page)
// so the onboarding "Continue" flow isn't lost.
// Preserve the model across back-navigation (returning from the firmware
// check page) so the onboarding "Continue" flow isn't lost.
if (!page.bindingContext) {
const context = (args.context as { onboarding?: boolean } | undefined) ?? undefined;
page.bindingContext = new ConfigViewModel({ onboarding: context?.onboarding ?? false });
+22 -12
View File
@@ -1,37 +1,47 @@
<Page xmlns="http://schemas.nativescript.org/tns.xsd" navigatingTo="navigatingTo">
<ActionBar title="Configure Devices" />
<GridLayout rows="auto,auto,auto,auto,auto,auto,auto,*" class="p-20">
<Label row="0" text="Configure the MAC addresses for the G2 headset arms and optional R1 ring. This page does not test a connection." textWrap="true" />
<GridLayout rows="auto,auto,auto,auto,auto,auto,auto,auto,*" class="p-20">
<Label row="0" text="Configure the MAC addresses for the G2 headset arms and optional R1 ring. This page does not test a connection." class="body-text" textWrap="true" />
<StackLayout row="1" class="m-t-16">
<GridLayout row="1" columns="96,*" class="pairing-row m-t-12" visibility="{{ identityVisibility }}">
<Image col="0" src="{{ identityImagePath }}" stretch="aspectFit" width="90" height="34" />
<StackLayout col="1" class="m-l-8">
<Label text="{{ identityTitle }}" class="pairing-title" />
<Label text="{{ identityVariant }}" class="pairing-variant" visibility="{{ identityVariantVisibility }}" />
<Label text="{{ identitySerial }}" class="pairing-serial" />
<Label text="{{ identityDetail }}" class="pairing-arms" textWrap="true" />
</StackLayout>
</GridLayout>
<StackLayout row="2" class="m-t-16">
<Label text="Right arm MAC" />
<TextField text="{{ rightAddress }}" textChange="{{ onRightAddressTextChange }}" autocorrect="false" autocapitalizationType="none" />
</StackLayout>
<StackLayout row="2" class="m-t-12">
<StackLayout row="3" class="m-t-12">
<Label text="Left arm MAC" />
<TextField text="{{ leftAddress }}" textChange="{{ onLeftAddressTextChange }}" autocorrect="false" autocapitalizationType="none" />
</StackLayout>
<StackLayout row="3" class="m-t-12">
<StackLayout row="4" class="m-t-12">
<Label text="R1 ring MAC (optional)" />
<TextField text="{{ ringAddress }}" textChange="{{ onRingAddressTextChange }}" autocorrect="false" autocapitalizationType="none" />
</StackLayout>
<GridLayout row="4" columns="*,*" class="m-t-16">
<GridLayout row="5" columns="*,*" class="m-t-16">
<Button col="0" text="Load paired devices" tap="{{ onLoadPairedTap }}" class="-primary" isEnabled="{{ canDiscover }}" />
<Button col="1" text="Scan nearby" tap="{{ onScanTap }}" class="-primary" isEnabled="{{ canDiscover }}" />
<Button col="1" text="Scan for glasses" tap="{{ onScanTap }}" class="-primary" isEnabled="{{ canDiscover }}" />
</GridLayout>
<Label row="5" text="{{ status }}" class="m-t-16" textWrap="true" />
<Label row="6" text="{{ status }}" class="body-text m-t-16" textWrap="true" />
<GridLayout row="6" columns="*,*" class="m-t-16">
<Button col="0" text="{{ saveLabel }}" tap="{{ onSaveTap }}" class="-primary" />
<Button col="1" text="Back" tap="{{ onBackTap }}" />
<GridLayout row="7" columns="*,*" class="m-t-16">
<Button col="0" text="Back" tap="{{ onBackTap }}" />
<Button col="1" text="{{ saveLabel }}" tap="{{ onSaveTap }}" class="-primary" />
</GridLayout>
<ScrollView row="7" class="m-t-16">
<ScrollView row="8" class="m-t-16">
<Label text="{{ discoveryLog }}" textWrap="true" verticalAlignment="top" />
</ScrollView>
</GridLayout>
+101 -8
View File
@@ -1,8 +1,18 @@
import { Frame, Observable } from "@nativescript/core";
import { ensureBlePermissions } from "../g2/android-permissions";
import { isValidMacAddress, loadDeviceAddresses, normalizeMacAddress, saveDeviceAddresses } from "../g2/device-addresses";
import {
isValidMacAddress,
loadDeviceAddresses,
loadPairedGlassesIdentityForAddresses,
normalizeMacAddress,
saveDeviceAddresses,
type PairedGlassesIdentity,
} from "../g2/device-addresses";
import { glassesImagePath } from "../g2/glasses-artwork";
import { GlassesHardwareIdentity } from "../g2/glasses-hardware-identity";
import { buildAddressSet, DeviceDiscoveryBridge } from "../native/device-discovery";
import { formatErrorMessage } from "../util/format-error";
type TextChangeArgs = { value?: string; object?: { text?: string } };
@@ -15,6 +25,7 @@ export class ConfigViewModel extends Observable {
private _status = "";
private _discoveryLog = "";
private _discovering = false;
private pairedIdentity: PairedGlassesIdentity | null = null;
constructor(options?: { onboarding?: boolean }) {
super();
@@ -23,9 +34,69 @@ export class ConfigViewModel extends Observable {
this.rightAddress = stored.right;
this.leftAddress = stored.left;
this.ringAddress = stored.ring;
this.refreshIdentity();
this.status = this.onboarding
? "Load the addresses from the glasses you paired with the official Even app, or scan / enter them, then Continue."
: "Edit addresses manually, or load them from paired devices or a scan.";
? "Scan for glasses to pick yours by model and serial, load the addresses of devices paired with this phone, or enter them by hand, then Continue."
: "Edit addresses manually, scan for glasses, or load them from paired devices.";
}
// --- paired identity card --------------------------------------------------
/** The identity saved by the pairing scan, shown only while it still describes the entered addresses. */
private refreshIdentity(): void {
this.pairedIdentity = loadPairedGlassesIdentityForAddresses({
right: this._rightAddress,
left: this._leftAddress,
ring: this._ringAddress,
});
for (const property of [
"identityVisibility",
"identityImagePath",
"identityTitle",
"identityVariant",
"identityVariantVisibility",
"identitySerial",
"identityDetail",
] as const) {
this.notifyPropertyChange(property, this[property]);
}
}
private get decodedIdentity(): GlassesHardwareIdentity | null {
return GlassesHardwareIdentity.decode(this.pairedIdentity?.serial);
}
get identityVisibility(): "visible" | "collapse" {
return this.pairedIdentity ? "visible" : "collapse";
}
get identityImagePath(): string {
return glassesImagePath(this.decodedIdentity);
}
get identityTitle(): string {
return this.decodedIdentity?.productName ?? "Even Realities G2";
}
get identityVariant(): string {
return this.decodedIdentity?.variantSummary ?? "";
}
get identityVariantVisibility(): "visible" | "collapse" {
return this.identityVariant ? "visible" : "collapse";
}
get identitySerial(): string {
return this.pairedIdentity ? `Serial ${this.pairedIdentity.serial}` : "";
}
get identityDetail(): string {
const identity = this.pairedIdentity;
if (!identity) return "";
const parts = [`Left ${identity.leftName || identity.leftAddress}`, `Right ${identity.rightName || identity.rightAddress}`];
if (identity.ringName) parts.push(`Ring ${identity.ringName}`);
if (identity.pairedAtMs) parts.push(`paired ${new Date(identity.pairedAtMs).toLocaleDateString()}`);
return parts.join(" · ");
}
get saveLabel(): string {
@@ -100,10 +171,12 @@ export class ConfigViewModel extends Observable {
onRightAddressTextChange(args: TextChangeArgs): void {
this.rightAddress = args.object?.text ?? args.value ?? "";
this.refreshIdentity();
}
onLeftAddressTextChange(args: TextChangeArgs): void {
this.leftAddress = args.object?.text ?? args.value ?? "";
this.refreshIdentity();
}
onRingAddressTextChange(args: TextChangeArgs): void {
@@ -114,8 +187,28 @@ export class ConfigViewModel extends Observable {
await this.populateFromDiscovery(async () => this.discovery.getBondedCandidates(), "Loaded paired devices.");
}
/** The live scan page identifies pairs by serial, model, and distance; hand off to it. */
async onScanTap(): Promise<void> {
await this.populateFromDiscovery(async () => this.discovery.scanCandidates(6000), "Scanned nearby devices.");
if (!this.onboarding) {
// A connected arm stops advertising, so drop the link before scanning.
// Required lazily: a module-scope import would instantiate the dashboard
// controller singleton during onboarding, which this page is part of.
// Outside onboarding the main page has already loaded it.
const { dashboardController } = require("../g2/dashboard-controller") as typeof import("../g2/dashboard-controller");
const { resumeAutoReconnect } = require("../g2/reconnect-policy") as typeof import("../g2/reconnect-policy");
try {
await dashboardController.disconnect();
} catch {
// proceed anyway; the pairing page reports what it hears
}
// disconnect() enters the manual-disconnected state; pairing is a
// detour, so let the main page reconnect afterwards.
resumeAutoReconnect();
}
Frame.topmost()?.navigate({
moduleName: "phone-ui/pairing-page",
context: { onboarding: this.onboarding },
});
}
onBackTap(): void {
@@ -139,8 +232,8 @@ export class ConfigViewModel extends Observable {
return;
}
if (this.onboarding) {
// Continue the onboarding chain: unpair the official app next.
Frame.topmost()?.navigate({ moduleName: "phone-ui/onboarding-unpair-page" });
// Continue the onboarding chain: check the glasses' firmware next.
Frame.topmost()?.navigate({ moduleName: "phone-ui/onboarding-firmware-check-page" });
}
}
@@ -186,6 +279,7 @@ export class ConfigViewModel extends Observable {
if (selection.right) this.rightAddress = selection.right;
if (selection.left) this.leftAddress = selection.left;
if (selection.ring) this.ringAddress = selection.ring;
this.refreshIdentity();
this.discoveryLog = selection.summary;
this.status = successMessage;
} catch (error) {
@@ -196,7 +290,6 @@ export class ConfigViewModel extends Observable {
}
private formatError(error: unknown): string {
const raw = (error as Error)?.message ?? String(error);
return raw.replace(/[\x00-\x1f]+/g, " ").replace(/\s+/g, " ").trim();
return formatErrorMessage(error);
}
}
+100
View File
@@ -0,0 +1,100 @@
import { Utils } from "@nativescript/core";
import type { EmotionLabel, SentimentBucket } from "../apps/microphones/sentiment";
declare const com: any;
/**
* Shared plumbing for the conversation review pages: access to the Java
* conversation store, the row shapes it returns, and the small formatting/
* color helpers every page needs. Callers must guard store access with
* `global.isAndroid`.
*/
export type SessionSpeakerRef = { id: number; name: string; color: string };
export type SessionRow = {
id: number;
startedAt: number;
endedAt: number;
title: string;
audioPath: string;
audioCodec: string;
avgSentiment: number;
segmentCount: number;
speakers: SessionSpeakerRef[];
};
export type SegmentRow = {
id: number;
speakerId: number | null;
startedAt: number;
endedAt: number;
audioOffsetMs: number | null;
text: string;
lang: string;
translation: string;
translationLang: string;
sentiment: number;
emotion: string;
angle: number | null;
};
export function conversationStore(): any {
const context = Utils.android.getApplicationContext();
return com.faceclaw.app.FaceclawConversationStore.getInstance(context);
}
export const NO_CONVERSATIONS_MESSAGE =
"No conversations yet — enable Captions + Save captions in the Microphones app on the glasses.";
/** "Mar 4, 2026, 2:15 PM" in the phone's locale. */
export function formatDateTime(ms: number): string {
if (!Number.isFinite(ms) || ms <= 0) return "";
const date = new Date(ms);
return `${date.toLocaleDateString()} ${date.toLocaleTimeString([], { hour: "numeric", minute: "2-digit" })}`;
}
/** Time-of-day only, e.g. "2:15 PM" — used for per-line timestamps. */
export function formatTime(ms: number): string {
if (!Number.isFinite(ms) || ms <= 0) return "";
return new Date(ms).toLocaleTimeString([], { hour: "numeric", minute: "2-digit", second: "2-digit" });
}
/** mm:ss (hours spill into minutes: 90 min -> "90:00"). */
export function formatDuration(ms: number): string {
const totalSeconds = Math.max(0, Math.round(ms / 1000));
const minutes = Math.floor(totalSeconds / 60);
const seconds = totalSeconds % 60;
return `${minutes}:${seconds < 10 ? "0" : ""}${seconds}`;
}
export const SENTIMENT_BUCKET_COLORS: Record<SentimentBucket, string> = {
veryPositive: "#2E7D32",
positive: "#66BB6A",
neutral: "#9E9E9E",
negative: "#EF6C00",
veryNegative: "#C62828",
};
export const EMOTION_COLORS: Record<EmotionLabel, string> = {
happy: "#81C784",
excited: "#AED581",
calm: "#4DB6AC",
relieved: "#66BB6A",
confident: "#4FC3F7",
surprised: "#BA68C8",
confused: "#FFB74D",
bored: "#90A4AE",
anxious: "#FFA726",
embarrassed: "#F06292",
frustrated: "#FF8A65",
sad: "#7986CB",
angry: "#E57373",
disgusted: "#A1887F",
neutral: "#BDBDBD",
};
export function emotionColor(emotion: string): string {
return EMOTION_COLORS[emotion as EmotionLabel] ?? EMOTION_COLORS.neutral;
}
+24
View File
@@ -0,0 +1,24 @@
import { EventData, NavigatedData, Page } from "@nativescript/core";
import { ConversationViewModel } from "./conversation-view-model";
type ConversationContext = { sessionId?: number } | undefined;
export function navigatingTo(args: NavigatedData): void {
const page = args.object as Page;
let model = page.bindingContext as ConversationViewModel | undefined;
if (!model) {
const context = args.context as ConversationContext;
model = new ConversationViewModel(context?.sessionId ?? 0);
page.bindingContext = model;
}
model.reload();
}
export function unloaded(args: EventData): void {
const page = args.object as Page;
const model = page.bindingContext as ConversationViewModel | undefined;
// The page has no forward navigation, so unloaded means it's going away:
// stop playback and release the MediaPlayer.
model?.dispose();
}
+49
View File
@@ -0,0 +1,49 @@
<Page xmlns="http://schemas.nativescript.org/tns.xsd" navigatingTo="navigatingTo" unloaded="unloaded">
<ActionBar title="{{ pageTitle }}">
<ActionItem text="Re-diarize" tap="{{ onRediarizeTap }}" android.position="popup" />
<ActionItem text="Split speaker..." tap="{{ onSplitSpeakerTap }}" android.position="popup" />
<ActionItem text="Delete conversation" tap="{{ onDeleteTap }}" android.position="popup" />
</ActionBar>
<GridLayout rows="auto,auto,auto,*" class="p-8">
<StackLayout row="0">
<Label text="{{ headerDate }}" class="conversation-meta" />
<Label text="{{ headerMeta }}" class="conversation-meta" textWrap="true" />
</StackLayout>
<Image row="1" src="{{ graphSource }}" height="120" stretch="fill" class="m-t-8" visibility="{{ graphVisibility }}" />
<Label row="2" text="{{ status }}" class="conversation-status m-t-4" textWrap="true" visibility="{{ statusVisibility }}" />
<ScrollView row="3" class="m-t-8">
<StackLayout>
<Label text="{{ emptyMessage }}" class="conversation-empty" textWrap="true" visibility="{{ emptyVisibility }}" />
<Repeater items="{{ transcriptRows }}">
<Repeater.itemsLayout>
<StackLayout />
</Repeater.itemsLayout>
<Repeater.itemTemplate>
<StackLayout class="{{ rowClass }}" tap="{{ onRowTap }}" longPress="{{ onRowLongPress }}">
<GridLayout columns="*,auto">
<Label col="0" textWrap="true">
<Label.formattedText>
<FormattedString>
<Span text="{{ speakerPrefix }}" color="{{ speakerColor }}" fontWeight="bold" />
<Span text="{{ text }}" />
</FormattedString>
</Label.formattedText>
</Label>
<Label col="1" text="{{ playIndicator }}" class="transcript-play" verticalAlignment="top" />
</GridLayout>
<Label text="{{ translation }}" class="transcript-translation" textWrap="true" visibility="{{ translationVisibility }}" />
<StackLayout orientation="horizontal" class="m-t-4">
<Label text="{{ timeLabel }}" class="transcript-time" />
<Label text="{{ emotionLabel }}" class="transcript-emotion m-l-6" backgroundColor="{{ emotionColor }}" visibility="{{ emotionVisibility }}" />
</StackLayout>
</StackLayout>
</Repeater.itemTemplate>
</Repeater>
</StackLayout>
</ScrollView>
</GridLayout>
</Page>
+159
View File
@@ -0,0 +1,159 @@
import { inferredEmotionFilter, type EmotionLabel } from "../apps/microphones/sentiment";
import { NON_WORD_RUN } from "../util/unicode-class";
/**
* Natural-language search parsing for the conversations list. The grammar is
* deliberately small and lossy-safe: recognized phrases become structured
* filters and are stripped from the query; everything left over is passed on
* as a plain text query.
*
* Recognized date phrases (case-insensitive):
* - "past/last N hours/days/weeks/months" (N as digits, "one".."twelve",
* "a"/"an", "couple (of)", "few"; N omitted means 1), with optional
* leading "in/over/during/from" and "the" -> sinceMs
* - "today", "this week", "this month" -> sinceMs at the period start
* - "yesterday" -> sinceMs/untilMs bracketing
* that day (untilMs is dropped when combined with an open-ended phrase)
*
* Emotion: `inferredEmotionFilter` over the date-stripped query; when it
* names exactly one emotion, that becomes the filter and the tokens that
* triggered it (checked as unigrams and bigrams, so "fed up" works) are
* stripped. When any filter was recognized, connective filler words
* ("conversations where the speaker was ...") are stripped too, so the
* residual text query is only the meaningful content words.
*/
export type ParsedConversationQuery = {
sinceMs: number | null;
untilMs: number | null;
emotion: EmotionLabel | null;
text: string;
};
const NUMBER_WORDS: Record<string, number> = {
a: 1,
an: 1,
one: 1,
two: 2,
three: 3,
four: 4,
five: 5,
six: 6,
seven: 7,
eight: 8,
nine: 9,
ten: 10,
eleven: 11,
twelve: 12,
couple: 2,
few: 3,
};
const UNIT_MS: Record<string, number> = {
hour: 3_600_000,
day: 86_400_000,
week: 7 * 86_400_000,
month: 30 * 86_400_000,
};
const RELATIVE_RANGE_PATTERN =
/\b(?:(?:in|over|during|from)\s+)?(?:the\s+)?(?:past|last)\s+(?:(\d+|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|couple(?:\s+of)?|few|a|an)\s+)?(hour|day|week|month)s?\b/g;
/**
* Filler words that carry no search content once the query has been
* understood as a filter request ("conversations where the speaker was
* angry"). Only stripped when an emotion or date filter matched, so ordinary
* text queries pass through untouched.
*/
const FILLER_WORDS = new Set<string>([
"conversations", "conversation", "chats", "chat", "sessions", "session",
"where", "when", "which", "who", "that", "whose",
"the", "a", "an", "was", "were", "is", "are", "be", "being", "been",
"speaker", "speakers", "someone", "anybody", "anyone", "people", "person",
"sounded", "sounds", "felt", "feels", "feeling", "seemed", "seems",
"show", "me", "find", "search", "list", "get", "all", "any",
"i", "we", "they", "he", "she", "it", "you",
"in", "of", "with", "about", "on", "at", "and", "or", "to",
"talked", "talking", "talks", "said", "saying",
]);
function parseCount(word: string | undefined): number {
if (!word) return 1;
const normalized = word.replace(/\s+of$/, "").trim();
if (/^\d+$/.test(normalized)) return Math.max(1, parseInt(normalized, 10));
return NUMBER_WORDS[normalized] ?? 1;
}
function startOfDay(nowMs: number): number {
const date = new Date(nowMs);
date.setHours(0, 0, 0, 0);
return date.getTime();
}
function tokenize(text: string): string[] {
return text.split(NON_WORD_RUN).filter((token) => token.length > 0);
}
export function parseConversationQuery(raw: string, nowMs: number = Date.now()): ParsedConversationQuery {
let working = raw.toLowerCase();
const sinceCandidates: number[] = [];
let untilMs: number | null = null;
let openEndedRange = false;
working = working.replace(RELATIVE_RANGE_PATTERN, (_match, count: string | undefined, unit: string) => {
sinceCandidates.push(nowMs - parseCount(count) * UNIT_MS[unit]!);
openEndedRange = true;
return " ";
});
if (/\byesterday\b/.test(working)) {
const todayStart = startOfDay(nowMs);
sinceCandidates.push(todayStart - UNIT_MS.day!);
untilMs = todayStart;
working = working.replace(/\byesterday\b/g, " ");
}
if (/\btoday\b/.test(working)) {
sinceCandidates.push(startOfDay(nowMs));
openEndedRange = true;
working = working.replace(/\btoday\b/g, " ");
}
if (/\bthis\s+week\b/.test(working)) {
const now = new Date(nowMs);
sinceCandidates.push(startOfDay(nowMs) - now.getDay() * UNIT_MS.day!);
openEndedRange = true;
working = working.replace(/\bthis\s+week\b/g, " ");
}
if (/\bthis\s+month\b/.test(working)) {
const now = new Date(nowMs);
sinceCandidates.push(new Date(now.getFullYear(), now.getMonth(), 1).getTime());
openEndedRange = true;
working = working.replace(/\bthis\s+month\b/g, " ");
}
// "yesterday" alone brackets that day, but combined with an open-ended
// phrase ("yesterday and the past week") the upper bound would silently
// hide results the other phrase asked for.
if (openEndedRange) untilMs = null;
const sinceMs = sinceCandidates.length > 0 ? Math.min(...sinceCandidates) : null;
const emotion = inferredEmotionFilter(working);
let tokens = tokenize(working);
if (emotion) {
const kept: string[] = [];
for (let i = 0; i < tokens.length; i++) {
if (i + 1 < tokens.length && inferredEmotionFilter(`${tokens[i]} ${tokens[i + 1]}`) === emotion) {
i++;
continue;
}
if (inferredEmotionFilter(tokens[i]!) === emotion) continue;
kept.push(tokens[i]!);
}
tokens = kept;
}
if (emotion || sinceMs !== null) {
tokens = tokens.filter((token) => !FILLER_WORDS.has(token));
}
return { sinceMs, untilMs, emotion, text: tokens.join(" ") };
}
+467
View File
@@ -0,0 +1,467 @@
import { Frame, ImageSource, Observable, Screen, Utils, action, confirm, fromObject } from "@nativescript/core";
import { rediarizeSession } from "../apps/microphones/rediarize";
import { summarize, type AnalyzedLine, type EmotionLabel } from "../apps/microphones/sentiment";
import { speakerRegistry } from "../apps/microphones/speakers";
import {
conversationStore,
emotionColor,
formatDateTime,
formatDuration,
formatTime,
type SegmentRow,
type SessionRow,
} from "./conversation-format";
declare const android: any;
/**
* One transcript line. Rows are Observables so playback highlighting can
* update just the affected rows instead of rebuilding the whole Repeater.
*/
export type TranscriptRow = Observable;
const UNKNOWN_SPEAKER_COLOR = "#90A4AE";
const GRAPH_HEIGHT_DIP = 120;
export class ConversationViewModel extends Observable {
private readonly sessionId: number;
private session: SessionRow | null = null;
private segments: SegmentRow[] = [];
private rows: TranscriptRow[] = [];
private player: any = null; // android.media.MediaPlayer
private activeRowIndex = -1;
private playing = false;
private rediarizeRunning = false;
private _pageTitle = "Conversation";
private _headerDate = "";
private _headerMeta = "";
private _status = "";
private _emptyMessage = "";
private _graphSource: ImageSource | null = null;
constructor(sessionId: number) {
super();
this.sessionId = sessionId;
}
// --- bound properties ------------------------------------------------------
get pageTitle(): string {
return this._pageTitle;
}
get headerDate(): string {
return this._headerDate;
}
get headerMeta(): string {
return this._headerMeta;
}
get status(): string {
return this._status;
}
set status(value: string) {
if (this._status !== value) {
this._status = value;
this.notifyPropertyChange("status", value);
this.notifyPropertyChange("statusVisibility", this.statusVisibility);
}
}
get statusVisibility(): "visible" | "collapse" {
return this._status ? "visible" : "collapse";
}
get emptyMessage(): string {
return this._emptyMessage;
}
get emptyVisibility(): "visible" | "collapse" {
return this._emptyMessage ? "visible" : "collapse";
}
get graphSource(): ImageSource | null {
return this._graphSource;
}
get graphVisibility(): "visible" | "collapse" {
return this._graphSource ? "visible" : "collapse";
}
get transcriptRows(): TranscriptRow[] {
return this.rows;
}
// --- lifecycle -------------------------------------------------------------
reload(): void {
if (!global.isAndroid) {
this._emptyMessage = "Conversation review is only available on Android.";
this.notifyPropertyChange("emptyMessage", this._emptyMessage);
this.notifyPropertyChange("emptyVisibility", this.emptyVisibility);
return;
}
this.stopPlaybackHighlight();
try {
const sessions = JSON.parse(String(conversationStore().querySessions("{}"))) as SessionRow[];
this.session = sessions.find((row) => row.id === this.sessionId) ?? null;
this.segments = JSON.parse(String(conversationStore().querySegments(this.sessionId))) as SegmentRow[];
} catch (error) {
console.error(`conversation load failed: ${String(error)}`);
this.session = null;
this.segments = [];
}
this.refreshHeader();
this.rebuildRows();
this.rebuildGraph();
}
/** Release the MediaPlayer when the page goes away. */
dispose(): void {
this.stopPlaybackHighlight();
if (this.player) {
try {
this.player.release();
} catch {
// already released
}
this.player = null;
}
}
// --- header / rows ---------------------------------------------------------
private refreshHeader(): void {
const session = this.session;
this._pageTitle = session?.title || (session ? formatDateTime(session.startedAt) : "Conversation");
this._headerDate = session ? formatDateTime(session.startedAt) : "";
if (session) {
const durationMs = session.endedAt > session.startedAt ? session.endedAt - session.startedAt : 0;
const speakerNames = (session.speakers ?? []).map((speaker) => speaker.name).join(", ");
const parts = [formatDuration(durationMs), `${session.segmentCount} lines`];
if (speakerNames) parts.push(speakerNames);
if (!session.audioPath) parts.push("no recording");
this._headerMeta = parts.join(" · ");
} else {
this._headerMeta = "";
}
this._emptyMessage = !session
? "This conversation is no longer in the store."
: this.segments.length === 0
? "No transcript lines were saved for this conversation."
: "";
this.notifyPropertyChange("pageTitle", this._pageTitle);
this.notifyPropertyChange("headerDate", this._headerDate);
this.notifyPropertyChange("headerMeta", this._headerMeta);
this.notifyPropertyChange("emptyMessage", this._emptyMessage);
this.notifyPropertyChange("emptyVisibility", this.emptyVisibility);
}
private rebuildRows(): void {
const speakerById = new Map<number, { name: string; color: string }>();
for (const speaker of this.session?.speakers ?? []) {
speakerById.set(speaker.id, speaker);
}
// Session speakers only cover voices heard in this session; a reassignment
// to a brand-new speaker still needs a name, so fall back to the registry.
for (const profile of speakerRegistry.all()) {
if (!speakerById.has(profile.id)) {
speakerById.set(profile.id, { name: profile.name, color: profile.color });
}
}
this.rows = this.segments.map((segment, index) => {
const speaker = segment.speakerId !== null ? speakerById.get(segment.speakerId) : undefined;
const emotion = (segment.emotion || "neutral") as string;
const row = fromObject({
speakerPrefix: `${speaker?.name ?? "Unknown"}: `,
speakerColor: speaker?.color || UNKNOWN_SPEAKER_COLOR,
text: segment.text ?? "",
translation: segment.translation ?? "",
translationVisibility: segment.translation ? "visible" : "collapse",
emotionLabel: emotion,
emotionColor: emotionColor(emotion),
emotionVisibility: emotion !== "neutral" ? "visible" : "collapse",
timeLabel: formatTime(segment.startedAt),
playIndicator: "",
rowClass: "transcript-row",
onRowTap: () => this.onRowTapped(index),
onRowLongPress: () => {
void this.onRowLongPressed(index);
},
});
return row;
});
this.notifyPropertyChange("transcriptRows", this.rows);
}
// --- sentiment graph -------------------------------------------------------
/**
* Renders the per-line sentiment trend into a Bitmap: a horizontal zero
* line, a polyline of scores over the conversation, and a dot per trend
* point colored by the dominant emotion of that stretch.
*/
private rebuildGraph(): void {
this._graphSource = null;
if (global.isAndroid && this.segments.length > 1) {
try {
this._graphSource = this.drawGraph();
} catch (error) {
console.error(`sentiment graph failed: ${String(error)}`);
}
}
this.notifyPropertyChange("graphSource", this._graphSource);
this.notifyPropertyChange("graphVisibility", this.graphVisibility);
}
private drawGraph(): ImageSource | null {
const lines: AnalyzedLine[] = this.segments.map((segment) => ({
score: segment.sentiment ?? 0,
emotion: (segment.emotion || "neutral") as EmotionLabel,
emotionConfidence: 1,
}));
const trend = summarize(lines).trend;
if (trend.length < 2) return null;
const scale = Screen.mainScreen.scale;
const width = Math.max(320, Math.round(Screen.mainScreen.widthDIPs * scale));
const height = Math.round(GRAPH_HEIGHT_DIP * scale);
const padding = Math.round(10 * scale);
const bitmap = android.graphics.Bitmap.createBitmap(width, height, android.graphics.Bitmap.Config.ARGB_8888);
const canvas = new android.graphics.Canvas(bitmap);
canvas.drawColor(android.graphics.Color.parseColor("#26909090"));
const xAt = (i: number): number => padding + (i / (trend.length - 1)) * (width - 2 * padding);
const yAt = (score: number): number => {
const clamped = Math.max(-1, Math.min(1, score));
return height / 2 - clamped * (height / 2 - padding);
};
const paint = new android.graphics.Paint(android.graphics.Paint.ANTI_ALIAS_FLAG);
// Zero line.
paint.setStyle(android.graphics.Paint.Style.STROKE);
paint.setStrokeWidth(1 * scale);
paint.setColor(android.graphics.Color.parseColor("#80909090"));
canvas.drawLine(padding, height / 2, width - padding, height / 2, paint);
// Score polyline.
const path = new android.graphics.Path();
path.moveTo(xAt(0), yAt(trend[0].score));
for (let i = 1; i < trend.length; i++) {
path.lineTo(xAt(i), yAt(trend[i].score));
}
paint.setStrokeWidth(2 * scale);
paint.setColor(android.graphics.Color.parseColor("#78909C"));
canvas.drawPath(path, paint);
// Emotion dots.
paint.setStyle(android.graphics.Paint.Style.FILL);
for (let i = 0; i < trend.length; i++) {
paint.setColor(android.graphics.Color.parseColor(emotionColor(trend[i].emotion)));
canvas.drawCircle(xAt(i), yAt(trend[i].score), 3.5 * scale, paint);
}
return new ImageSource(bitmap);
}
// --- playback --------------------------------------------------------------
private onRowTapped(index: number): void {
if (!global.isAndroid) return;
const session = this.session;
const segment = this.segments[index];
if (!session?.audioPath || !segment) return;
// Lines predating the recording (or a mid-session codec restart) may miss
// an offset; fall back to the wall-clock delta from the session start.
const offsetMs =
segment.audioOffsetMs !== null && segment.audioOffsetMs !== undefined
? segment.audioOffsetMs
: Math.max(0, segment.startedAt - session.startedAt);
if (index === this.activeRowIndex && this.player) {
if (this.playing) {
try {
this.player.pause();
} catch {
// fall through to state update; a dead player just loses the toggle
}
this.playing = false;
} else {
try {
this.player.start();
this.playing = true;
} catch {
this.playing = false;
}
}
this.updateRowPlayback();
return;
}
if (!this.ensurePlayer(session.audioPath)) return;
try {
this.player.seekTo(offsetMs);
this.player.start();
this.playing = true;
this.activeRowIndex = index;
} catch (error) {
this.status = `Playback failed: ${String(error)}`;
this.playing = false;
this.activeRowIndex = -1;
}
this.updateRowPlayback();
}
private ensurePlayer(audioPath: string): boolean {
if (this.player) return true;
try {
const player = new android.media.MediaPlayer();
player.setDataSource(audioPath);
player.prepare();
player.setOnCompletionListener(
new android.media.MediaPlayer.OnCompletionListener({
onCompletion: () => {
Utils.executeOnMainThread(() => {
this.playing = false;
this.updateRowPlayback();
});
},
}),
);
this.player = player;
return true;
} catch (error) {
this.status = `Could not open the recording: ${String(error)}`;
return false;
}
}
private stopPlaybackHighlight(): void {
if (this.player && this.playing) {
try {
this.player.pause();
} catch {
// ignore; the player may already be gone
}
}
this.playing = false;
this.activeRowIndex = -1;
}
private updateRowPlayback(): void {
for (let i = 0; i < this.rows.length; i++) {
const row = this.rows[i];
const isActive = i === this.activeRowIndex;
const rowClass = isActive ? "transcript-row transcript-row-playing" : "transcript-row";
const indicator = isActive ? (this.playing ? "⏸" : "▶") : "";
if (row.get("rowClass") !== rowClass) row.set("rowClass", rowClass);
if (row.get("playIndicator") !== indicator) row.set("playIndicator", indicator);
}
}
// --- actions ---------------------------------------------------------------
onRediarizeTap(): void {
if (!global.isAndroid || this.rediarizeRunning) return;
this.rediarizeRunning = true;
this.status = "Re-diarizing… 0%";
rediarizeSession(this.sessionId, {}, {
onProgress: (fraction) => {
Utils.executeOnMainThread(() => {
this.status = `Re-diarizing… ${Math.round(fraction * 100)}%`;
});
},
onDone: (result) => {
Utils.executeOnMainThread(() => {
this.rediarizeRunning = false;
this.status =
`Re-diarization done: ${result.clusters} voices, ` +
`${result.reassignedSegments} lines reassigned, ${result.newSpeakers} new speakers.`;
this.reload();
});
},
onError: (message) => {
Utils.executeOnMainThread(() => {
this.rediarizeRunning = false;
this.status = message;
});
},
});
}
async onSplitSpeakerTap(): Promise<void> {
if (!global.isAndroid) return;
const speakers = this.session?.speakers ?? [];
if (speakers.length === 0) {
this.status = "This conversation has no speakers to split.";
return;
}
const picked = await action({
title: "Split speaker",
message: "Move one speaker's lines in this conversation to a new profile.",
cancelButtonText: "Cancel",
actions: speakers.map((speaker) => speaker.name),
});
const chosen = speakers.find((speaker) => speaker.name === picked);
if (!chosen) return;
const confirmed = await confirm({
title: "Split speaker",
message: `Move ${chosen.name}'s lines in this conversation to a new speaker?`,
okButtonText: "Split",
cancelButtonText: "Cancel",
});
if (!confirmed) return;
speakerRegistry.splitFromSession(this.sessionId, chosen.id);
this.status = "";
this.reload();
}
async onDeleteTap(): Promise<void> {
if (!global.isAndroid) return;
const confirmed = await confirm({
title: "Delete conversation",
message: "Delete this conversation, its transcript, and its recording link? This cannot be undone.",
okButtonText: "Delete",
cancelButtonText: "Cancel",
});
if (!confirmed) return;
this.dispose();
try {
conversationStore().deleteSession(this.sessionId);
} catch (error) {
this.status = `Delete failed: ${String(error)}`;
return;
}
Frame.topmost()?.goBack();
}
private async onRowLongPressed(index: number): Promise<void> {
if (!global.isAndroid) return;
const segment = this.segments[index];
if (!segment) return;
const profiles = speakerRegistry.all();
if (profiles.length === 0) return;
const picked = await action({
title: "Reassign speaker",
message: "Whose line is this?",
cancelButtonText: "Cancel",
actions: profiles.map((profile) => profile.name),
});
const chosen = profiles.find((profile) => profile.name === picked);
if (!chosen || chosen.id === segment.speakerId) return;
try {
conversationStore().reassignSegmentSpeaker(segment.id, chosen.id);
} catch (error) {
this.status = `Reassign failed: ${String(error)}`;
return;
}
speakerRegistry.reload();
this.reload();
}
}
+19
View File
@@ -0,0 +1,19 @@
import { NavigatedData, Page } from "@nativescript/core";
import { ConversationsViewModel } from "./conversations-view-model";
type ConversationsContext = { speakerId?: number } | undefined;
export function navigatingTo(args: NavigatedData): void {
const page = args.object as Page;
// Preserve the model across back-navigation (returning from a conversation
// or the speakers page) so the search and filters aren't lost; reload every
// time so deletions, merges, and renames made elsewhere show up.
let model = page.bindingContext as ConversationsViewModel | undefined;
if (!model) {
const context = args.context as ConversationsContext;
model = new ConversationsViewModel({ speakerId: context?.speakerId });
page.bindingContext = model;
}
model.reload();
}
+56
View File
@@ -0,0 +1,56 @@
<Page xmlns="http://schemas.nativescript.org/tns.xsd" navigatingTo="navigatingTo">
<ActionBar title="Conversations">
<ActionItem text="Ask AI" tap="{{ onAskTap }}" android.position="actionBar" />
<ActionItem text="Speakers" tap="{{ onSpeakersTap }}" android.position="actionBar" />
</ActionBar>
<GridLayout rows="auto,auto,*" class="p-8">
<SearchBar
row="0"
hint="Search (e.g. lunch past 2 days, angry)"
text="{{ searchText }}"
submit="{{ onSearchSubmit }}"
clear="{{ onSearchClear }}" />
<ScrollView row="1" orientation="horizontal" class="m-t-8" visibility="{{ filterChipsVisibility }}">
<StackLayout orientation="horizontal">
<Repeater items="{{ speakerChips }}">
<Repeater.itemsLayout>
<StackLayout orientation="horizontal" />
</Repeater.itemsLayout>
<Repeater.itemTemplate>
<Label text="{{ name }}" class="{{ chipClass }}" backgroundColor="{{ chipBackground }}" tap="{{ onChipTap }}" />
</Repeater.itemTemplate>
</Repeater>
</StackLayout>
</ScrollView>
<ScrollView row="2" class="m-t-8">
<StackLayout>
<Label text="{{ emptyMessage }}" class="conversation-empty" textWrap="true" visibility="{{ emptyVisibility }}" />
<Repeater items="{{ sessionRows }}">
<Repeater.itemsLayout>
<StackLayout />
</Repeater.itemsLayout>
<Repeater.itemTemplate>
<StackLayout class="conversation-row" tap="{{ onRowTap }}">
<GridLayout columns="*,auto">
<Label col="0" text="{{ title }}" class="conversation-title" textWrap="true" />
<Label col="1" text="" width="12" height="12" borderRadius="6" backgroundColor="{{ sentimentColor }}" verticalAlignment="center" />
</GridLayout>
<Label text="{{ meta }}" class="conversation-meta" />
<Repeater items="{{ speakerChips }}" visibility="{{ chipsVisibility }}" class="m-t-4">
<Repeater.itemsLayout>
<WrapLayout />
</Repeater.itemsLayout>
<Repeater.itemTemplate>
<Label text="{{ name }}" class="speaker-chip" backgroundColor="{{ chipBackground }}" />
</Repeater.itemTemplate>
</Repeater>
</StackLayout>
</Repeater.itemTemplate>
</Repeater>
</StackLayout>
</ScrollView>
</GridLayout>
</Page>
+175
View File
@@ -0,0 +1,175 @@
import { EventData, Frame, Observable, SearchBar } from "@nativescript/core";
import { sentimentBucket } from "../apps/microphones/sentiment";
import { speakerRegistry } from "../apps/microphones/speakers";
import {
conversationStore,
formatDateTime,
formatDuration,
NO_CONVERSATIONS_MESSAGE,
SENTIMENT_BUCKET_COLORS,
type SessionRow,
} from "./conversation-format";
import { parseConversationQuery } from "./conversation-search";
/** One session row in the Repeater; tap handler rides on the item itself (see pairing-view-model). */
export type SessionRowItem = {
title: string;
meta: string;
sentimentColor: string;
speakerChips: Array<{ name: string; chipBackground: string }>;
chipsVisibility: "visible" | "collapse";
onRowTap: () => void;
};
export type SpeakerChipItem = {
name: string;
chipBackground: string;
chipClass: string;
onChipTap: () => void;
};
export class ConversationsViewModel extends Observable {
private _searchText = "";
private _sessionRows: SessionRowItem[] = [];
private _speakerChips: SpeakerChipItem[] = [];
private _emptyMessage = "";
private selectedSpeakerId: number | null = null;
constructor(options?: { speakerId?: number }) {
super();
this.selectedSpeakerId = options?.speakerId ?? null;
}
get searchText(): string {
return this._searchText;
}
set searchText(value: string) {
if (this._searchText !== value) {
this._searchText = value;
this.notifyPropertyChange("searchText", value);
}
}
get sessionRows(): SessionRowItem[] {
return this._sessionRows;
}
get speakerChips(): SpeakerChipItem[] {
return this._speakerChips;
}
get emptyMessage(): string {
return this._emptyMessage;
}
get emptyVisibility(): "visible" | "collapse" {
return this._emptyMessage ? "visible" : "collapse";
}
get filterChipsVisibility(): "visible" | "collapse" {
return this._speakerChips.length > 0 ? "visible" : "collapse";
}
/** Called on every navigatingTo so edits made on other pages show up on the way back. */
reload(): void {
this.refreshSpeakerChips();
this.refreshSessions();
}
onSpeakersTap(): void {
Frame.topmost()?.navigate("phone-ui/speakers-page");
}
onAskTap(): void {
Frame.topmost()?.navigate("phone-ui/ask-page");
}
onSearchSubmit(args: EventData): void {
const bar = args.object as SearchBar;
this._searchText = bar.text ?? "";
this.refreshSessions();
}
onSearchClear(): void {
if (!this._searchText) return;
this._searchText = "";
this.notifyPropertyChange("searchText", "");
this.refreshSessions();
}
private refreshSpeakerChips(): void {
const profiles = global.isAndroid ? speakerRegistry.all() : [];
this._speakerChips = profiles.map((profile) => ({
name: profile.name,
chipBackground: profile.color || "#90A4AE",
chipClass: profile.id === this.selectedSpeakerId ? "speaker-chip speaker-chip-selected" : "speaker-chip",
onChipTap: () => {
this.selectedSpeakerId = this.selectedSpeakerId === profile.id ? null : profile.id;
this.refreshSpeakerChips();
this.refreshSessions();
},
}));
this.notifyPropertyChange("speakerChips", this._speakerChips);
this.notifyPropertyChange("filterChipsVisibility", this.filterChipsVisibility);
}
private refreshSessions(): void {
if (!global.isAndroid) {
this.setSessions([], "Conversation review is only available on Android.");
return;
}
const parsed = parseConversationQuery(this._searchText);
const filter: Record<string, unknown> = {};
if (parsed.sinceMs !== null) filter.sinceMs = parsed.sinceMs;
if (parsed.untilMs !== null) filter.untilMs = parsed.untilMs;
if (parsed.emotion !== null) filter.emotion = parsed.emotion;
if (parsed.text) filter.query = parsed.text;
if (this.selectedSpeakerId !== null) filter.speakerId = this.selectedSpeakerId;
const filtered = Object.keys(filter).length > 0;
let rows: SessionRow[] = [];
try {
rows = JSON.parse(String(conversationStore().querySessions(JSON.stringify(filter)))) as SessionRow[];
} catch (error) {
console.error(`conversations query failed: ${String(error)}`);
this.setSessions([], "Could not read saved conversations.");
return;
}
this.setSessions(
rows.map((row) => this.toRowItem(row)),
rows.length > 0 ? "" : filtered ? "No conversations match this search." : NO_CONVERSATIONS_MESSAGE,
);
}
private setSessions(rows: SessionRowItem[], emptyMessage: string): void {
this._sessionRows = rows;
this._emptyMessage = emptyMessage;
this.notifyPropertyChange("sessionRows", rows);
this.notifyPropertyChange("emptyMessage", emptyMessage);
this.notifyPropertyChange("emptyVisibility", this.emptyVisibility);
}
private toRowItem(row: SessionRow): SessionRowItem {
const durationMs = row.endedAt > row.startedAt ? row.endedAt - row.startedAt : 0;
const metaParts = [formatDateTime(row.startedAt), formatDuration(durationMs), `${row.segmentCount} lines`];
const chips = (row.speakers ?? []).map((speaker) => ({
name: speaker.name,
chipBackground: speaker.color || "#90A4AE",
}));
return {
title: row.title || formatDateTime(row.startedAt),
meta: metaParts.filter((part) => part.length > 0).join(" · "),
sentimentColor: SENTIMENT_BUCKET_COLORS[sentimentBucket(row.avgSentiment ?? 0)],
speakerChips: chips,
chipsVisibility: chips.length > 0 ? "visible" : "collapse",
onRowTap: () => {
Frame.topmost()?.navigate({
moduleName: "phone-ui/conversation-page",
context: { sessionId: row.id },
});
},
};
}
}
+26
View File
@@ -0,0 +1,26 @@
import { Frame, NavigatedData, Page, knownFolders } from "@nativescript/core";
/** Phone-side viewer for the project docs that webpack.config.js copies into
* the bundle under about/ (LICENSE, PRIVACY, ...). The glasses-side
* equivalent lives in ui/dashboard/settings-menus.ts. */
type DocumentContext = { fileName?: string; title?: string } | undefined;
export function navigatingTo(args: NavigatedData): void {
const page = args.object as Page;
const context = args.context as DocumentContext;
const fileName = context?.fileName ?? "";
page.bindingContext = {
title: context?.title ?? fileName,
text: readBundledDoc(fileName),
onBackTap: () => Frame.topmost()?.goBack(),
};
}
function readBundledDoc(fileName: string): string {
try {
const text = knownFolders.currentApp().getFile(`about/${fileName}`).readTextSync();
return text || `(${fileName} is missing from this build)`;
} catch {
return `(${fileName} is missing from this build)`;
}
}
+9
View File
@@ -0,0 +1,9 @@
<Page xmlns="http://schemas.nativescript.org/tns.xsd" navigatingTo="navigatingTo">
<ActionBar title="{{ title }}">
<NavigationButton android.systemIcon="ic_menu_back" tap="{{ onBackTap }}" />
</ActionBar>
<ScrollView>
<Label text="{{ text }}" textWrap="true" class="document-text p-16" />
</ScrollView>
</Page>
+19 -54
View File
@@ -1,4 +1,4 @@
import { Application, Color, EventData, isAndroid, Observable, Page, ScrollView, TextField } from '@nativescript/core'
import { Application, Color, EventData, isAndroid, Observable, Page, TextField } from '@nativescript/core'
import { MainViewModel } from './main-view-model'
import { dashboardController } from '../g2/dashboard-controller'
@@ -13,9 +13,6 @@ export function navigatingTo(args: EventData) {
type MainPageState = {
model: MainViewModel
isPinnedToBottom: boolean
scrollViews: ScrollView[]
scrollHandler: (args: EventData) => void
propertyChangeHandler: (args: EventData & { propertyName?: string }) => void
orientationHandler: () => void
}
@@ -34,30 +31,14 @@ function cleanupPage(page: Page): void {
setPageState(page, undefined)
return
}
for (const scrollView of state.scrollViews) {
scrollView.off(ScrollView.scrollEvent, state.scrollHandler)
}
state.model.off(Observable.propertyChangeEvent, state.propertyChangeHandler)
Application.off(Application.orientationChangedEvent, state.orientationHandler)
// navigatingTo builds a fresh model each visit; drop the old one's
// controller/settings subscriptions or every navigation leaks a listener.
state.model.dispose()
setPageState(page, undefined)
}
function isAtBottom(scrollView: ScrollView): boolean {
return scrollView.scrollableHeight <= 0 || scrollView.verticalOffset >= scrollView.scrollableHeight - 8
}
function scrollToBottom(scrollView: ScrollView): void {
setTimeout(() => {
scrollView.scrollToVerticalOffset(scrollView.scrollableHeight, false)
}, 0)
}
function scrollLogsToBottom(scrollViews: ScrollView[]): void {
for (const scrollView of scrollViews) {
scrollToBottom(scrollView)
}
}
function applySettingsTextFieldContrast(textField: TextField): void {
textField.color = SETTINGS_TEXT_COLOR
textField.backgroundColor = SETTINGS_BACKGROUND_COLOR
@@ -79,6 +60,15 @@ function applySettingsTextFieldContrast(textField: TextField): void {
nativeTextField.setSelectAllOnFocus(true)
}
/**
* Leaving keyboard-input mode: the glasses navigated away from the text
* setting, so the phone's keyboard has nothing to type into any more.
*/
function dismissTextEditorKeyboard(page: Page): void {
page.getViewById<TextField>('settingsTextField')?.dismissSoftInput()
page.getViewById<TextField>('secondarySettingsTextField')?.dismissSoftInput()
}
function focusTextEditor(page: Page): void {
setTimeout(() => {
const textField = page.getViewById<TextField>('settingsTextField')
@@ -99,70 +89,45 @@ export function loaded(args: EventData) {
dashboardController.refreshEvenAppStatus()
const model = page.bindingContext as MainViewModel | null
// Re-subscribe after a suspend/resume cycle (unloaded disposed the model);
// a no-op on the first load after construction.
model?.attach()
// Automatically connect on reaching the main page (no-op if already
// connected or if no glasses are configured).
void model?.autoConnect()
// Reopen the apps that were open before the last restart (no-op after the
// first load).
void dashboardController.restoreOpenApps()
const scrollViews = [
page.getViewById<ScrollView>('logScrollView'),
page.getViewById<ScrollView>('logScrollViewLandscape'),
].filter((scrollView): scrollView is ScrollView => !!scrollView)
const settingsTextField = page.getViewById<TextField>('settingsTextField')
model?.refreshLayoutMetrics()
if (settingsTextField) {
applySettingsTextFieldContrast(settingsTextField)
}
if (!model || scrollViews.length === 0) {
if (!model) {
return
}
const state: MainPageState = {
model,
isPinnedToBottom: true,
scrollViews,
scrollHandler: (scrollArgs) => {
state.isPinnedToBottom = isAtBottom(scrollArgs.object as ScrollView)
},
orientationHandler: () => {
setTimeout(() => {
model.refreshLayoutMetrics()
if (state.isPinnedToBottom) {
scrollLogsToBottom(scrollViews)
}
}, 0)
},
propertyChangeHandler: (propertyArgs) => {
if (propertyArgs.propertyName === 'showLog') {
if (model.showLog) {
state.isPinnedToBottom = true
scrollLogsToBottom(scrollViews)
}
return
}
if (propertyArgs.propertyName === 'activeTextSettingId') {
if (model.isTextSettingEditorActive) {
focusTextEditor(page)
} else {
dismissTextEditorKeyboard(page)
}
return
}
if (propertyArgs.propertyName !== 'log') {
return
}
if (state.isPinnedToBottom) {
scrollLogsToBottom(scrollViews)
}
},
}
for (const scrollView of scrollViews) {
scrollView.on(ScrollView.scrollEvent, state.scrollHandler)
}
model.on(Observable.propertyChangeEvent, state.propertyChangeHandler)
Application.on(Application.orientationChangedEvent, state.orientationHandler)
setPageState(page, state)
scrollLogsToBottom(scrollViews)
if (model.isTextSettingEditorActive) {
focusTextEditor(page)
}
+56 -63
View File
@@ -1,17 +1,27 @@
<Page xmlns="http://schemas.nativescript.org/tns.xsd" navigatingTo="navigatingTo" loaded="loaded" unloaded="unloaded">
<ActionBar title="Faceclaw">
<ActionItem text="{{ buttonLabel }}" tap="{{ onTap }}" isEnabled="{{ canRun }}" android.position="popup" />
<Page xmlns="http://schemas.nativescript.org/tns.xsd" xmlns:rc="phone-ui" navigatingTo="navigatingTo" loaded="loaded" unloaded="unloaded">
<ActionBar>
<!-- Custom titleView: app title on the left; connection status and the
warning-triangle indicator right-aligned beside the overflow menu. -->
<GridLayout columns="auto,*,auto,auto" width="100%" verticalAlignment="center">
<Label col="0" text="Faceclaw" class="action-bar-title" />
<Label col="2" text="{{ connectionStatusLabel }}" tap="{{ onConnectionStatusTap }}" class="action-bar-status" />
<Label col="3" text="&#x26A0;&#xFE0F;" tap="{{ onWarningIconTap }}" visibility="{{ warningIconVisibility }}" class="action-bar-warning" />
</GridLayout>
<ActionItem text="{{ buttonLabel }}" tap="{{ onTap }}" isEnabled="{{ connectItemEnabled }}" android.position="popup" />
<ActionItem text="Pair glasses" tap="{{ onPairGlassesTap }}" isEnabled="{{ canRun }}" android.position="popup" />
<ActionItem text="Configure devices" tap="{{ onConfigureTap }}" isEnabled="{{ canRun }}" android.position="popup" />
<ActionItem text="Permissions" tap="{{ onPermissionsTap }}" android.position="popup" />
<ActionItem text="Conversations" tap="{{ onConversationsTap }}" android.position="popup" />
<ActionItem text="Take screenshot" tap="{{ onTakeScreenshotTap }}" android.position="popup" />
<ActionItem text="Record screen" tap="{{ onRecordScreenTap }}" android.position="popup" />
<ActionItem text="Uninstall custom firmware" tap="{{ onUninstallFirmwareTap }}" isEnabled="{{ canRun }}" android.position="popup" />
<ActionItem text="{{ showLogMenuLabel }}" tap="{{ onToggleLogTap }}" android.position="popup" />
</ActionBar>
<GridLayout>
<GridLayout rows="auto,*" visibility="{{ portraitLayoutVisibility }}">
<StackLayout row="0" visibility="{{ displayPreviewVisibility }}">
<Image src="{{ displayPreview }}" stretch="fill" height="{{ displayPreviewHeight }}" />
<Image src="{{ displayPreview }}" stretch="fill" height="{{ displayPreviewHeight }}"
tap="{{ onMirrorTap }}" doubleTap="{{ onMirrorDoubleTap }}" longPress="{{ onMirrorLongPress }}" swipe="{{ onMirrorSwipe }}" />
</StackLayout>
<GridLayout
row="0"
@@ -20,58 +30,23 @@
visibility="{{ displayPreviewMessageVisibility }}">
<Label text="{{ displayPreviewMessage }}" textWrap="true" horizontalAlignment="center" verticalAlignment="center" />
</GridLayout>
<GridLayout row="1" rows="auto,auto,auto,*" class="p-20">
<StackLayout row="0" class="m-b-8">
<StackLayout visibility="{{ evenAppConflictWarningVisibility }}">
<Label text="{{ evenAppConflictMessage }}" textWrap="true" />
<Button text="Open Even app settings" tap="{{ onOpenEvenAppSettingsTap }}" class="-primary" />
</StackLayout>
<StackLayout visibility="{{ firmwareWarningVisibility }}">
<Label text="{{ firmwareWarningMessage }}" textWrap="true" />
<Button text="Install custom firmware" tap="{{ onInstallFirmwareTap }}" class="-primary" />
</StackLayout>
<StackLayout visibility="{{ batteryOptimizationWarningVisibility }}">
<Label text="Android will slow Faceclaw to a crawl when the phone screen is off unless it is exempt from battery optimization." textWrap="true" />
<Button text="Allow unrestricted background usage" tap="{{ onAllowBackgroundUsageTap }}" class="-primary" />
</StackLayout>
</StackLayout>
<StackLayout row="1">
<GridLayout rows="auto,auto,auto" columns="*,*,*" class="m-t-8">
<Button row="0" col="1" text="Swipe up" tap="{{ onSyntheticUpTap }}" />
<Button row="1" col="0" text="Double-click" tap="{{ onSyntheticLeftTap }}" />
<Button row="1" col="1" text="Long press" tap="{{ onSyntheticLongPressTap }}" />
<Button row="1" col="2" text="Click" tap="{{ onSyntheticRightTap }}" />
<Button row="0" col="2" text="Microphone" tap="{{ onSyntheticMicTap }}" />
<Button row="2" col="1" text="Swipe down" tap="{{ onSyntheticDownTap }}" />
</GridLayout>
<Button text="Stop recording" tap="{{ onStopRecordingTap }}" visibility="{{ stopRecordingButtonVisibility }}" />
</StackLayout>
<Label row="2" text="{{ status }}" class="m-t-16" textWrap="true" />
<ScrollView id="logScrollView" row="3" class="m-t-16" visibility="{{ showLogVisibility }}">
<Label text="{{ log }}" textWrap="true" verticalAlignment="top" />
</ScrollView>
<!-- The controls get the whole star row so the active tab's
content can center in the leftover height. -->
<GridLayout row="1" rows="*,auto" class="p-20">
<rc:remote-controls row="0" visibility="{{ controlsVisibility }}" />
<Button row="1" text="Stop recording" tap="{{ onStopRecordingTap }}" visibility="{{ stopRecordingButtonVisibility }}" />
</GridLayout>
</GridLayout>
<GridLayout rows="auto,*" class="p-20" visibility="{{ landscapeLayoutVisibility }}">
<StackLayout row="0" class="m-b-8">
<StackLayout visibility="{{ evenAppConflictWarningVisibility }}">
<Label text="{{ evenAppConflictMessage }}" textWrap="true" />
<Button text="Open Even app settings" tap="{{ onOpenEvenAppSettingsTap }}" class="-primary" />
</StackLayout>
<Label text="{{ firmwareWarningMessage }}" textWrap="true" visibility="{{ firmwareWarningVisibility }}" />
<StackLayout visibility="{{ batteryOptimizationWarningVisibility }}">
<Label text="Android will slow Faceclaw to a crawl when the phone screen is off unless it is exempt from battery optimization." textWrap="true" />
<Button text="Allow unrestricted background usage" tap="{{ onAllowBackgroundUsageTap }}" class="-primary" />
</StackLayout>
</StackLayout>
<GridLayout row="1" rows="auto,auto,*" columns="*,260">
<GridLayout class="p-20" visibility="{{ landscapeLayoutVisibility }}">
<GridLayout rows="auto" columns="*,360">
<StackLayout row="0" col="0" visibility="{{ displayPreviewVisibility }}" horizontalAlignment="left">
<Image
src="{{ displayPreview }}"
stretch="fill"
width="{{ landscapeDisplayPreviewWidth }}"
height="{{ landscapeDisplayPreviewHeight }}" />
height="{{ landscapeDisplayPreviewHeight }}"
tap="{{ onMirrorTap }}" doubleTap="{{ onMirrorDoubleTap }}" longPress="{{ onMirrorLongPress }}" swipe="{{ onMirrorSwipe }}" />
</StackLayout>
<GridLayout
row="0"
@@ -84,29 +59,47 @@
<Label text="{{ displayPreviewMessage }}" textWrap="true" horizontalAlignment="center" verticalAlignment="center" />
</GridLayout>
<StackLayout row="0" col="1" class="m-l-16">
<GridLayout rows="auto,auto,auto" columns="*,*,*">
<Button row="0" col="1" text="Swipe up" tap="{{ onSyntheticUpTap }}" />
<Button row="1" col="0" text="Double-click" tap="{{ onSyntheticLeftTap }}" />
<Button row="1" col="1" text="Long press" tap="{{ onSyntheticLongPressTap }}" />
<Button row="1" col="2" text="Click" tap="{{ onSyntheticRightTap }}" />
<Button row="0" col="2" text="Microphone" tap="{{ onSyntheticMicTap }}" />
<Button row="2" col="1" text="Swipe down" tap="{{ onSyntheticDownTap }}" />
</GridLayout>
<rc:remote-controls visibility="{{ controlsVisibility }}" />
<Button text="Stop recording" tap="{{ onStopRecordingTap }}" visibility="{{ stopRecordingButtonVisibility }}" />
</StackLayout>
<Label row="1" col="0" colSpan="2" text="{{ status }}" class="m-t-16" textWrap="true" />
<ScrollView id="logScrollViewLandscape" row="2" col="0" colSpan="2" class="m-t-16" visibility="{{ showLogVisibility }}">
<Label text="{{ log }}" textWrap="true" verticalAlignment="top" />
</ScrollView>
</GridLayout>
</GridLayout>
<ScrollView
class="warnings-modal"
visibility="{{ warningsModalVisibility }}"
width="{{ warningsModalWidth }}"
horizontalAlignment="center"
verticalAlignment="center">
<StackLayout class="warnings-modal-content">
<Label text="Attention needed" class="h2" />
<StackLayout visibility="{{ evenAppConflictWarningVisibility }}" class="warnings-modal-item">
<Label text="{{ evenAppConflictMessage }}" textWrap="true" />
<Button text="Open Even app settings" tap="{{ onOpenEvenAppSettingsTap }}" class="-primary" />
</StackLayout>
<StackLayout visibility="{{ firmwareWarningVisibility }}" class="warnings-modal-item">
<Label text="{{ firmwareWarningMessage }}" textWrap="true" />
<Button text="Install custom firmware" tap="{{ onInstallFirmwareTap }}" class="-primary" />
</StackLayout>
<StackLayout visibility="{{ batteryOptimizationWarningVisibility }}" class="warnings-modal-item">
<Label text="Android will slow Faceclaw to a crawl when the phone screen is off unless it is exempt from battery optimization." textWrap="true" />
<Button text="Allow unrestricted background usage" tap="{{ onAllowBackgroundUsageTap }}" class="-primary" />
</StackLayout>
<Button text="Close" tap="{{ onWarningsModalCloseTap }}" />
</StackLayout>
</ScrollView>
<!-- Keyboard-input mode: anchored to the bottom of the (keyboard-
shrunk) page, so it sits in the space below the mirror and only
overlaps the mirror when the open keyboard leaves too little
room. The tabbed controls are collapsed while it is up. -->
<StackLayout
class="system-name-modal"
visibility="{{ textSettingEditorVisibility }}"
horizontalAlignment="stretch"
verticalAlignment="top">
verticalAlignment="bottom">
<Label text="{{ activeTextEditorTitle }}" class="h2" />
<Label text="{{ activeTextSettingTitle }}" />
<!-- Per-field labels only matter with two fields; a single-field
edit's field title is the same string as the editor title. -->
<Label text="{{ activeTextSettingTitle }}" visibility="{{ secondaryTextSettingVisibility }}" />
<TextField
id="settingsTextField"
text="{{ activeTextSettingValue }}"
+483 -54
View File
@@ -1,16 +1,45 @@
import { Application, Frame, ImageSource, Observable, Screen } from "@nativescript/core";
import { dashboardController } from "../g2/dashboard-controller";
import {
Application,
Dialogs,
Frame,
ImageSource,
Observable,
Screen,
SwipeDirection,
type GestureEventData,
type SwipeGestureEventData,
type TouchGestureEventData,
type View,
} from "@nativescript/core";
import { dashboardController, type MirrorTouchKind } from "../g2/dashboard-controller";
import { shell } from "../ui/shell/shell";
import {
brightnessSetting,
DISPLAY_MODE_VALUES,
displayModeLabel,
displayModeSetting,
mirrorTouchSetting,
onAnySettingChanged,
type BrightnessSetting,
type DisplayModeSetting,
} from "../ui/dashboard-settings";
import { isValidMacAddress, loadDeviceAddresses } from "../g2/device-addresses";
import { isAutoReconnectSuppressed } from "../g2/reconnect-policy";
import { isAutoReconnectSuppressed, resumeAutoReconnect } from "../g2/reconnect-policy";
import { formatErrorMessage } from "../util/format-error";
import { G2_LENS_HEIGHT, G2_LENS_WIDTH } from "../graphics/image";
const LENS_ASPECT_RATIO = G2_LENS_WIDTH / G2_LENS_HEIGHT;
type LayoutOrientation = "portrait" | "landscape";
type ControlsTab = "settings" | "watch" | "ring";
// Survives navigation round-trips (a fresh view model is built per visit) but
// not process restarts.
let lastControlsTab: ControlsTab = "watch";
export class MainViewModel extends Observable {
private _status = "Disconnected.";
private _log = "";
private _displayPreview: ImageSource | null = null;
private _displayPreviewMessage = "";
private _layoutOrientation: LayoutOrientation = this.readLayoutOrientation();
@@ -32,14 +61,29 @@ export class MainViewModel extends Observable {
private _firmwareWarningVisible = false;
private _screenRecordingActive = false;
private _batteryOptimizationWarningVisible = false;
private _showLog = false;
private _warningsModalVisible = false;
private _phase: "disconnected" | "connecting" | "connected" | "charging" | "disconnecting" = "disconnected";
// A new view model is built on every navigation to the main page; these
// module-level subscriptions must die with it (see dispose) or each
// round-trip to another page leaks a listener that pins the dead model.
private readonly unsubscribers: Array<() => void> = [];
constructor() {
super();
dashboardController.subscribe((snapshot) => {
this.attach();
}
/**
* Subscribe to the controller and settings. Idempotent; the page calls it
* again from `loaded` because an app suspend fires unloaded/loaded (which
* dispose the model) without a navigation building a fresh one. Subscribing
* delivers the current snapshot, so a re-attached model catches up.
*/
attach(): void {
if (this.unsubscribers.length > 0) return;
this.unsubscribers.push(dashboardController.subscribe((snapshot) => {
this.status = snapshot.status;
this.log = snapshot.log;
this.displayPreview = snapshot.displayPreview;
this.displayPreviewMessage = snapshot.displayPreviewMessage;
this.phase = snapshot.phase;
@@ -61,7 +105,17 @@ export class MainViewModel extends Observable {
this.firmwareWarningVisible = snapshot.firmwareWarningVisible;
this.screenRecordingActive = snapshot.screenRecordingActive;
this.batteryOptimizationWarningVisible = snapshot.batteryOptimizationWarningVisible;
});
this.refreshPadFocusLine();
}));
// Brightness / display mode can change from the glasses' Settings app too.
this.unsubscribers.push(onAnySettingChanged(() => this.refreshDisplayControls()));
}
/** Detach from the controller and settings; the page calls this when it lets go of the model. */
dispose(): void {
for (const unsubscribe of this.unsubscribers.splice(0)) {
unsubscribe();
}
}
get status(): string {
@@ -72,18 +126,34 @@ export class MainViewModel extends Observable {
if (this._status !== value) {
this._status = value;
this.notifyPropertyChange("status", value);
this.notifyPropertyChange("connectionStatusLabel", this.connectionStatusLabel);
}
}
get log(): string {
return this._log;
/**
* Short connection indicator for the action bar. The full status string
* (which can be a sentence, e.g. a failure reason) stays available by
* tapping the indicator.
*/
get connectionStatusLabel(): string {
switch (this._phase) {
case "connected":
return "Connected";
case "charging":
return "Charging";
case "disconnecting":
return "Disconnecting";
case "connecting":
// The transport reports retry loops as "Reconnecting..." with the
// phase still "connecting"; keep that distinction visible.
return this._status.startsWith("Reconnecting") ? "Reconnecting" : "Connecting";
default:
return this._status.startsWith("Failed") ? "Failed" : "Disconnected";
}
}
set log(value: string) {
if (this._log !== value) {
this._log = value;
this.notifyPropertyChange("log", value);
}
onConnectionStatusTap(): void {
void Dialogs.alert({ title: "Connection status", message: this._status, okButtonText: "OK" });
}
get displayPreview(): ImageSource | null {
@@ -141,11 +211,33 @@ export class MainViewModel extends Observable {
// aspect; the width is derived from it, so a wider lens aspect can't
// grow the preview past the side panel.
const screenWidth = Screen.mainScreen.widthDIPs;
const sidePanelWidth = 260;
// Must match the landscape grid's fixed side-panel column in main-page.xml.
const sidePanelWidth = 360;
const availableWidth = Math.max(240, Math.floor(screenWidth - sidePanelWidth - 56));
return Math.floor(availableWidth / 2);
}
/** Near-full-width on phones, capped on tablets (the 32 clears the 16 margins). */
get warningsModalWidth(): number {
return Math.min(Screen.mainScreen.widthDIPs - 32, 480);
}
/**
* The simulated watch face (and the Back/Menu row under it) is capped at a
* 1.5:1 face aspect; on narrow phones the available width governs instead.
*/
get watchFaceWidth(): number {
// Must match .touchpad height in app.css.
const faceHeight = 230;
const available =
this._layoutOrientation === "landscape"
? // The landscape side panel column (see main-page.xml) minus its
// m-l-16 margin and the controls' own 8+8 margins.
360 - 32
: Screen.mainScreen.widthDIPs - 56; // p-20 padding + controls margins
return Math.min(available, Math.round(faceHeight * 1.5));
}
get portraitLayoutVisibility(): "visible" | "collapse" {
return this._layoutOrientation === "portrait" ? "visible" : "collapse";
}
@@ -164,27 +256,8 @@ export class MainViewModel extends Observable {
this.notifyPropertyChange("displayPreviewHeight", this.displayPreviewHeight);
this.notifyPropertyChange("landscapeDisplayPreviewWidth", this.landscapeDisplayPreviewWidth);
this.notifyPropertyChange("landscapeDisplayPreviewHeight", this.landscapeDisplayPreviewHeight);
}
get showLog(): boolean {
return this._showLog;
}
set showLog(value: boolean) {
if (this._showLog !== value) {
this._showLog = value;
this.notifyPropertyChange("showLog", value);
this.notifyPropertyChange("showLogVisibility", this.showLogVisibility);
this.notifyPropertyChange("showLogMenuLabel", this.showLogMenuLabel);
}
}
get showLogVisibility(): "visible" | "collapse" {
return this._showLog ? "visible" : "collapse";
}
get showLogMenuLabel(): string {
return this._showLog ? "Hide Log" : "Show Log";
this.notifyPropertyChange("warningsModalWidth", this.warningsModalWidth);
this.notifyPropertyChange("watchFaceWidth", this.watchFaceWidth);
}
get activeTextSettingId(): string | null {
@@ -197,6 +270,8 @@ export class MainViewModel extends Observable {
this.notifyPropertyChange("activeTextSettingId", value);
this.notifyPropertyChange("textSettingEditorVisibility", this.textSettingEditorVisibility);
this.notifyPropertyChange("isTextSettingEditorActive", this.isTextSettingEditorActive);
// Keyboard-input mode: the tabbed controls make way for the editor.
this.notifyPropertyChange("controlsVisibility", this.controlsVisibility);
}
}
@@ -386,6 +461,7 @@ export class MainViewModel extends Observable {
this._evenAppConflictWarningVisible = value;
this.notifyPropertyChange("evenAppConflictWarningVisible", value);
this.notifyPropertyChange("evenAppConflictWarningVisibility", this.evenAppConflictWarningVisibility);
this.refreshWarningIndicator();
}
}
@@ -413,6 +489,7 @@ export class MainViewModel extends Observable {
this._firmwareWarningVisible = value;
this.notifyPropertyChange("firmwareWarningVisible", value);
this.notifyPropertyChange("firmwareWarningVisibility", this.firmwareWarningVisibility);
this.refreshWarningIndicator();
}
}
@@ -469,6 +546,7 @@ export class MainViewModel extends Observable {
this._batteryOptimizationWarningVisible = value;
this.notifyPropertyChange("batteryOptimizationWarningVisible", value);
this.notifyPropertyChange("batteryOptimizationWarningVisibility", this.batteryOptimizationWarningVisibility);
this.refreshWarningIndicator();
}
}
@@ -477,9 +555,51 @@ export class MainViewModel extends Observable {
}
onAllowBackgroundUsageTap(): void {
this.setWarningsModalVisible(false);
dashboardController.requestBatteryOptimizationExemption();
}
// ---- the action bar's warning triangle and the modal behind it ----
get anyWarningVisible(): boolean {
return (
this._evenAppConflictWarningVisible ||
this._firmwareWarningVisible ||
this._batteryOptimizationWarningVisible
);
}
get warningIconVisibility(): "visible" | "collapse" {
return this.anyWarningVisible ? "visible" : "collapse";
}
get warningsModalVisibility(): "visible" | "collapse" {
return this._warningsModalVisible ? "visible" : "collapse";
}
onWarningIconTap(): void {
this.setWarningsModalVisible(true);
}
onWarningsModalCloseTap(): void {
this.setWarningsModalVisible(false);
}
private setWarningsModalVisible(value: boolean): void {
if (this._warningsModalVisible !== value) {
this._warningsModalVisible = value;
this.notifyPropertyChange("warningsModalVisibility", this.warningsModalVisibility);
}
}
private refreshWarningIndicator(): void {
this.notifyPropertyChange("warningIconVisibility", this.warningIconVisibility);
// Don't leave the modal open showing nothing once the last warning clears.
if (!this.anyWarningVisible) {
this.setWarningsModalVisible(false);
}
}
get phase(): "disconnected" | "connecting" | "connected" | "charging" | "disconnecting" {
return this._phase;
}
@@ -490,13 +610,14 @@ export class MainViewModel extends Observable {
this.notifyPropertyChange("phase", value);
this.notifyPropertyChange("buttonLabel", this.buttonLabel);
this.notifyPropertyChange("canRun", this.canRun);
this.notifyPropertyChange("connectItemEnabled", this.connectItemEnabled);
this.notifyPropertyChange("connectionStatusLabel", this.connectionStatusLabel);
}
}
get buttonLabel(): string {
switch (this.phase) {
case "connecting":
return "Connecting...";
case "connected":
case "charging":
return "Disconnect";
@@ -511,20 +632,28 @@ export class MainViewModel extends Observable {
return this.phase !== "connecting" && this.phase !== "disconnecting";
}
/**
* Unlike the other canRun-gated menu items, Connect/Disconnect stays live
* while connecting: Disconnect is the only way out of a reconnection-attempt
* loop short of force-stopping the app.
*/
get connectItemEnabled(): boolean {
return this.phase !== "disconnecting";
}
async onTap(): Promise<void> {
if (!this.canRun) return;
if (!this.connectItemEnabled) return;
try {
if (this.phase === "connected" || this.phase === "charging") {
await dashboardController.disconnect();
} else {
if (this.phase === "disconnected") {
await dashboardController.connect();
} else {
await dashboardController.disconnect();
}
} catch (error) {
const message = this.formatError(error);
if (!this.status.startsWith("Failed:")) {
this.status = `Failed: ${message}`;
this.appendLog(`error: ${message}`);
}
}
}
@@ -553,7 +682,41 @@ export class MainViewModel extends Observable {
Frame.topmost()?.navigate("phone-ui/config-page");
}
onPermissionsTap(): void {
Frame.topmost()?.navigate({
moduleName: "phone-ui/permissions-page",
context: { onboarding: false },
});
}
/** Review saved caption sessions; works without a glasses connection. */
onConversationsTap(): void {
Frame.topmost()?.navigate("phone-ui/conversations-page");
}
/**
* Live scan that names each nearby pair by model, colour, and serial and
* checks both arms belong together. A connected arm stops advertising, so
* drop the current link first. disconnect() enters the manual-disconnected
* state; pairing is a detour, not a Disconnect, so lift the suppression
* right away — nothing dials the glasses until the main page's autoConnect
* runs again on the way back.
*/
async onPairGlassesTap(): Promise<void> {
if (!this.canRun) return;
if (this.phase === "connected" || this.phase === "charging" || this.phase === "connecting") {
try {
await dashboardController.disconnect();
} catch {
// proceed anyway; the pairing page reports what it hears
}
resumeAutoReconnect();
}
Frame.topmost()?.navigate({ moduleName: "phone-ui/pairing-page", context: { onboarding: false } });
}
async onInstallFirmwareTap(): Promise<void> {
this.setWarningsModalVisible(false);
await this.openFlashPage("install");
}
@@ -576,10 +739,6 @@ export class MainViewModel extends Observable {
});
}
onToggleLogTap(): void {
this.showLog = !this.showLog;
}
onTextSettingTextChange(args: { value?: string; object?: { text?: string } }): void {
dashboardController.setActiveTextSettingValue(
args.object?.text ?? args.value ?? "",
@@ -623,6 +782,7 @@ export class MainViewModel extends Observable {
}
onOpenEvenAppSettingsTap(): void {
this.setWarningsModalVisible(false);
dashboardController.openEvenAppSettings();
}
@@ -650,9 +810,267 @@ export class MainViewModel extends Observable {
await dashboardController.injectSyntheticRingInput("wakeword");
}
private appendLog(line: string): void {
const stamp = new Date().toISOString().slice(11, 19);
this.log = this.log ? `${this.log}\n[${stamp}] ${line}` : `[${stamp}] ${line}`;
// ---- the phone's own controller: touchpad, d-pad, mirror touch ----
//
// Everything here is the watch scheme (origin "watch"): spatial swipes,
// tap = select, double-tap / two fingers = back, hold = menu. The ring row
// above stays on the ring's own scheme.
private padTwoFingerDown = false;
/** What the next gesture lands on, as the watch pad shows it. */
get padFocusLine(): string {
return dashboardController.glassesDisplayLabel();
}
private refreshPadFocusLine(): void {
this.notifyPropertyChange("padFocusLine", this.padFocusLine);
}
async onPadTap(): Promise<void> {
if (this.padTwoFingerDown) return;
await dashboardController.injectSyntheticRingInput("click", "watch");
this.refreshPadFocusLine();
}
async onPadDoubleTap(): Promise<void> {
await dashboardController.injectSyntheticRingInput("double-click", "watch");
this.refreshPadFocusLine();
}
async onPadLongPress(): Promise<void> {
await dashboardController.injectSyntheticRingInput("long-press", "watch");
this.refreshPadFocusLine();
}
async onPadSwipe(args: SwipeGestureEventData): Promise<void> {
await dashboardController.injectSyntheticRingInput(swipeKind(args.direction), "watch");
this.refreshPadFocusLine();
}
/** Two fingers down and up without moving: back (the watch's two-finger tap). */
async onPadTouch(args: TouchGestureEventData): Promise<void> {
const count = args.getPointerCount();
if (args.action === "down" || args.action === "move") {
if (count >= 2) this.padTwoFingerDown = true;
return;
}
if (args.action === "up" || args.action === "cancel") {
const twoFinger = this.padTwoFingerDown;
if (twoFinger) {
// Let the single-tap recognizer's delayed tap see the flag first.
setTimeout(() => {
this.padTwoFingerDown = false;
}, 400);
if (args.action === "up") {
await dashboardController.injectSyntheticRingInput("double-click", "watch");
this.refreshPadFocusLine();
}
}
}
}
async onDpadUp(): Promise<void> {
await dashboardController.injectSyntheticRingInput("swipe-up", "watch");
this.refreshPadFocusLine();
}
async onDpadDown(): Promise<void> {
await dashboardController.injectSyntheticRingInput("swipe-down", "watch");
this.refreshPadFocusLine();
}
async onDpadLeft(): Promise<void> {
await dashboardController.injectSyntheticRingInput("swipe-left", "watch");
this.refreshPadFocusLine();
}
async onDpadRight(): Promise<void> {
await dashboardController.injectSyntheticRingInput("swipe-right", "watch");
this.refreshPadFocusLine();
}
async onDpadSelect(): Promise<void> {
await dashboardController.injectSyntheticRingInput("click", "watch");
this.refreshPadFocusLine();
}
async onBackTap(): Promise<void> {
await dashboardController.injectSyntheticRingInput("double-click", "watch");
this.refreshPadFocusLine();
}
async onMenuTap(): Promise<void> {
await dashboardController.injectSyntheticRingInput("long-press", "watch");
this.refreshPadFocusLine();
}
// ---- touching the mirror itself ----
// Toggled from Settings > Phone display > Touch mirror; read per gesture,
// so no change notification is needed.
get mirrorTouchEnabled(): boolean {
return mirrorTouchSetting.get();
}
private mirrorFraction(args: GestureEventData & { getX?: () => number; getY?: () => number }): { nx: number; ny: number } | null {
const view = args.object as View | undefined;
const size = view?.getActualSize?.();
if (!view || !size || !size.width || !size.height || !args.getX || !args.getY) return null;
// NativeScript's gesture getX/getY are view-local DIPs (the view's own
// MotionEvent coordinates), so they divide straight into the view's size.
return { nx: args.getX() / size.width, ny: args.getY() / size.height };
}
private async mirrorGesture(kind: MirrorTouchKind, args: GestureEventData): Promise<void> {
if (!this.mirrorTouchEnabled) return;
const at = this.mirrorFraction(args) ?? { nx: 0.5, ny: 0.5 };
await dashboardController.handleMirrorTouch(kind, at.nx, at.ny);
this.refreshPadFocusLine();
}
onMirrorTap(args: GestureEventData): Promise<void> {
return this.mirrorGesture("tap", args);
}
onMirrorDoubleTap(args: GestureEventData): Promise<void> {
return this.mirrorGesture("double-tap", args);
}
onMirrorLongPress(args: GestureEventData): Promise<void> {
return this.mirrorGesture("long-press", args);
}
onMirrorSwipe(args: SwipeGestureEventData): Promise<void> {
return this.mirrorGesture(swipeKind(args.direction), args);
}
// ---- the tabbed controls area below the mirror ----
//
// Three tabs: Settings (screen size + brightness), Watch (the simulated
// watch face), Ring (simulated R1 inputs). The whole area collapses while a
// text setting is being edited so the editor gets the space instead.
private _controlsTab: ControlsTab = lastControlsTab;
get controlsVisibility(): "visible" | "collapse" {
return this.isTextSettingEditorActive ? "collapse" : "visible";
}
get settingsTabVisibility(): "visible" | "collapse" {
return this._controlsTab === "settings" ? "visible" : "collapse";
}
get watchTabVisibility(): "visible" | "collapse" {
return this._controlsTab === "watch" ? "visible" : "collapse";
}
get ringTabVisibility(): "visible" | "collapse" {
return this._controlsTab === "ring" ? "visible" : "collapse";
}
get settingsTabClass(): string {
return this._controlsTab === "settings" ? "tab-button tab-button-selected" : "tab-button";
}
get watchTabClass(): string {
return this._controlsTab === "watch" ? "tab-button tab-button-selected" : "tab-button";
}
get ringTabClass(): string {
return this._controlsTab === "ring" ? "tab-button tab-button-selected" : "tab-button";
}
onSettingsTabTap(): void {
this.setControlsTab("settings");
}
onWatchTabTap(): void {
this.setControlsTab("watch");
}
onRingTabTap(): void {
this.setControlsTab("ring");
}
private setControlsTab(tab: ControlsTab): void {
if (this._controlsTab === tab) return;
this._controlsTab = tab;
// Remembered across navigations (module-level) so the page comes back on
// the tab it left on; deliberately not persisted to disk.
lastControlsTab = tab;
this.notifyPropertyChange("settingsTabVisibility", this.settingsTabVisibility);
this.notifyPropertyChange("watchTabVisibility", this.watchTabVisibility);
this.notifyPropertyChange("ringTabVisibility", this.ringTabVisibility);
this.notifyPropertyChange("settingsTabClass", this.settingsTabClass);
this.notifyPropertyChange("watchTabClass", this.watchTabClass);
this.notifyPropertyChange("ringTabClass", this.ringTabClass);
}
// ---- display mode and brightness, on the Settings tab ----
get displayModeLabel(): string {
return displayModeLabel(displayModeSetting.get()) + " ▾";
}
async onDisplayModeTap(): Promise<void> {
const current = displayModeSetting.get();
const options = DISPLAY_MODE_VALUES.map((value) => displayModeLabel(value) + (value === current ? " ✓" : ""));
const picked = await Dialogs.action({ title: "Display mode", cancelButtonText: "Cancel", actions: options });
const index = options.indexOf(picked);
if (index < 0) return;
const value = DISPLAY_MODE_VALUES[index] as DisplayModeSetting;
if (value !== current) displayModeSetting.set(value);
this.notifyPropertyChange("displayModeLabel", this.displayModeLabel);
}
get brightnessAuto(): boolean {
return brightnessSetting.get() === "auto";
}
get brightnessSliderEnabled(): boolean {
return !this.brightnessAuto;
}
/** The slider's position; while Auto, the last manual level (or 50). */
get brightnessPercent(): number {
const value = brightnessSetting.get();
if (value === "auto") return this.lastManualBrightness;
const numeric = parseInt(value, 10);
return Number.isFinite(numeric) ? numeric : 50;
}
private lastManualBrightness = 50;
onBrightnessChange(args: { value?: number; object?: { value?: number } }): void {
if (this.brightnessAuto) return;
const raw = typeof args.value === "number" ? args.value : Number(args.object?.value ?? NaN);
if (!Number.isFinite(raw)) return;
// The setting only has every tenth level; snap to the nearest.
const level = Math.min(100, Math.max(0, Math.round(raw / 10) * 10));
this.lastManualBrightness = level;
const value = String(level) as BrightnessSetting;
if (brightnessSetting.get() !== value) brightnessSetting.set(value);
}
onBrightnessAutoChange(args: { value?: boolean; object?: { checked?: boolean } }): void {
const on = typeof args.value === "boolean" ? args.value : Boolean(args.object?.checked);
if (on) {
if (brightnessSetting.get() !== "auto") {
this.lastManualBrightness = this.brightnessPercent;
brightnessSetting.set("auto");
}
} else if (brightnessSetting.get() === "auto") {
brightnessSetting.set(String(this.lastManualBrightness) as BrightnessSetting);
}
this.refreshDisplayControls();
}
private refreshDisplayControls(): void {
this.notifyPropertyChange("brightnessAuto", this.brightnessAuto);
this.notifyPropertyChange("brightnessSliderEnabled", this.brightnessSliderEnabled);
this.notifyPropertyChange("brightnessPercent", this.brightnessPercent);
this.notifyPropertyChange("displayModeLabel", this.displayModeLabel);
}
private readLayoutOrientation(): LayoutOrientation {
@@ -664,9 +1082,20 @@ export class MainViewModel extends Observable {
}
private formatError(error: unknown): string {
const raw = (error as Error)?.message ?? String(error);
const sanitized = raw.replace(/[\x00-\x1f]+/g, " ").replace(/\s+/g, " ").trim();
if (sanitized.length <= 240) return sanitized;
return `${sanitized.slice(0, 237)}...`;
return formatErrorMessage(error, 240);
}
}
/** NativeScript swipe direction -> the watch-scheme directional gesture. */
function swipeKind(direction: SwipeDirection): "swipe-up" | "swipe-down" | "swipe-left" | "swipe-right" {
switch (direction) {
case SwipeDirection.up:
return "swipe-up";
case SwipeDirection.down:
return "swipe-down";
case SwipeDirection.left:
return "swipe-left";
default:
return "swipe-right";
}
}
@@ -4,13 +4,20 @@
<StackLayout>
<Label text="{{ headline }}" class="h1 text-center m-t-24" textWrap="true" />
<ActivityIndicator busy="{{ busy }}" visibility="{{ busyVisibility }}" class="m-t-16" />
<Label text="{{ status }}" class="m-t-16 text-center" textWrap="true" />
<Label text="{{ status }}" class="body-text m-t-16 text-center" textWrap="true" />
</StackLayout>
</ScrollView>
<GridLayout row="1" columns="*,*" class="m-t-20">
<Button col="0" text="{{ secondaryLabel }}" tap="{{ onSecondaryTap }}" visibility="{{ secondaryVisibility }}" />
<Button col="1" text="{{ primaryLabel }}" tap="{{ onPrimaryTap }}" visibility="{{ primaryVisibility }}" class="-primary" />
</GridLayout>
<StackLayout row="1" class="m-t-20">
<!-- Error-only escape hatches: flash anyway, or trust that the custom firmware is present. -->
<GridLayout columns="*,*" visibility="{{ errorActionsVisibility }}">
<Button col="0" text="Install" tap="{{ onInstallTap }}" />
<Button col="1" text="Skip" tap="{{ onSkipTap }}" />
</GridLayout>
<GridLayout columns="*,*">
<Button col="0" text="{{ secondaryLabel }}" tap="{{ onSecondaryTap }}" visibility="{{ secondaryVisibility }}" />
<Button col="1" text="{{ primaryLabel }}" tap="{{ onPrimaryTap }}" visibility="{{ primaryVisibility }}" class="-primary" />
</GridLayout>
</StackLayout>
</GridLayout>
</Page>
@@ -10,6 +10,7 @@ import {
import { classifyOnboardingFirmware, FLASHABLE_STOCK_VERSION_TEXT } from "../g2/firmware-compat";
import { DeviceInfoProbe, DeviceInfoState } from "../native/device-info-probe";
import { setOnboardingCompleted, setPreviewOnlyMode } from "./onboarding-state";
import { formatErrorMessage } from "../util/format-error";
type CheckPhase = "checking" | "fonts" | "custom" | "flashable" | "newer" | "error";
@@ -94,6 +95,10 @@ export class OnboardingFirmwareCheckViewModel extends Observable {
return this._phase === "custom" || this._phase === "fonts" ? "collapse" : "visible";
}
get errorActionsVisibility(): "visible" | "collapse" {
return this._phase === "error" ? "visible" : "collapse";
}
// --- button handlers -------------------------------------------------------
onPrimaryTap(): void {
@@ -120,7 +125,25 @@ export class OnboardingFirmwareCheckViewModel extends Observable {
frame.goBack();
return;
}
frame?.navigate({ moduleName: "phone-ui/onboarding-unpair-page", clearHistory: true });
frame?.navigate({
moduleName: "phone-ui/pairing-page",
context: { onboarding: true },
clearHistory: true,
});
}
/** Escape hatch when the check itself fails: flash as if stock firmware had been detected. */
onInstallTap(): void {
if (this._phase !== "error") return;
this.goToFlashing();
}
/** Escape hatch when the check itself fails: continue as if compatible custom firmware had been detected. */
onSkipTap(): void {
if (this._phase !== "error") return;
// Same path as a real "custom" classification, so the phone-side G2 fonts
// still get extracted when they're missing.
this.applyClassification("custom", "", "");
}
// --- probe flow ------------------------------------------------------------
@@ -144,7 +167,7 @@ export class OnboardingFirmwareCheckViewModel extends Observable {
}
this.disposeProbe();
const probe = new DeviceInfoProbe(stored.right);
const probe = new DeviceInfoProbe(stored.right, stored.left);
this.probeInstance = probe;
probe.onStateChange((state) => this.reportProbeState(state));
@@ -162,6 +185,9 @@ export class OnboardingFirmwareCheckViewModel extends Observable {
private reportProbeState(state: DeviceInfoState): void {
if (state === "connecting") {
this.status = "Connecting to your glasses...";
} else if (state === "authenticating") {
// First-time connections pair here; the OS may show a Bluetooth dialog.
this.status = "Authenticating with your glasses... If Android asks to pair, tap Pair.";
} else if (state === "querying") {
this.status = "Reading the firmware version...";
}
@@ -285,6 +311,7 @@ export class OnboardingFirmwareCheckViewModel extends Observable {
this.notifyPropertyChange("secondaryLabel", this.secondaryLabel);
this.notifyPropertyChange("primaryVisibility", this.primaryVisibility);
this.notifyPropertyChange("secondaryVisibility", this.secondaryVisibility);
this.notifyPropertyChange("errorActionsVisibility", this.errorActionsVisibility);
}
private disposeProbe(): void {
@@ -299,7 +326,6 @@ export class OnboardingFirmwareCheckViewModel extends Observable {
}
private formatError(error: unknown): string {
const raw = (error as Error)?.message ?? String(error);
return raw.replace(/[\x00-\x1f]+/g, " ").replace(/\s+/g, " ").trim();
return formatErrorMessage(error);
}
}
+1 -1
View File
@@ -5,7 +5,7 @@
<Label text="{{ headline }}" class="h1 text-center m-t-24" textWrap="true" />
<ActivityIndicator busy="{{ busy }}" visibility="{{ busyVisibility }}" class="m-t-16" />
<Progress value="{{ progress }}" maxValue="100" visibility="{{ progressVisibility }}" class="m-t-16" />
<Label text="{{ status }}" class="m-t-16 text-center" textWrap="true" />
<Label text="{{ status }}" class="body-text m-t-16 text-center" textWrap="true" />
<Label text="{{ log }}" class="m-t-24" textWrap="true" fontSize="12" visibility="{{ logVisibility }}" />
</StackLayout>
</ScrollView>
+6 -8
View File
@@ -17,6 +17,7 @@ import { FirmwareFlasher, FlashProgress, FlashState } from "../native/firmware-f
import { FlashPromptCommunicator, FlashPromptState } from "../native/flash-prompt-communicator";
import { resumeAutoReconnect, suppressAutoReconnect } from "../g2/reconnect-policy";
import { setOnboardingCompleted, setPreviewOnlyMode } from "./onboarding-state";
import { formatErrorMessage } from "../util/format-error";
type FlashPhase = "intro" | "prompt" | "building" | "ready" | "flashing" | "flashed" | "error";
@@ -252,7 +253,7 @@ export class OnboardingFlashViewModel extends Observable {
private startCommunicator(addresses: { right: string; left: string }): void {
this.disposePrompt();
const prompt = new FlashPromptCommunicator(addresses, this.glassesWarning);
const prompt = new FlashPromptCommunicator(addresses.right, this.glassesWarning);
this.prompt = prompt;
this.promptUnsubscribers.push(
@@ -421,11 +422,9 @@ export class OnboardingFlashViewModel extends Observable {
private handleFlashProgress(progress: FlashProgress): void {
const lensIndex = progress.lens === "right" ? 1 : 0;
const withinLens =
progress.componentCount > 0
? (progress.componentIndex - 1 + (progress.blockCount > 0 ? progress.blockIndex / progress.blockCount : 0)) /
progress.componentCount
: 0;
// Weight by bytes, not by component index: the image is one large segment
// plus several small ones, so per-component steps move wildly unevenly.
const withinLens = progress.bytesTotal > 0 ? Math.min(1, progress.bytesSent / progress.bytesTotal) : 0;
this.progress = ((lensIndex + withinLens) / 2) * 100;
this.status =
`Flashing ${progress.lens} lens — part ${progress.componentIndex}/${progress.componentCount}, ` +
@@ -566,7 +565,6 @@ export class OnboardingFlashViewModel extends Observable {
}
private formatError(error: unknown): string {
const raw = (error as Error)?.message ?? String(error);
return raw.replace(/[\x00-\x1f]+/g, " ").replace(/\s+/g, " ").trim();
return formatErrorMessage(error);
}
}
+8 -4
View File
@@ -1,12 +1,16 @@
import { EventData, Page } from "@nativescript/core";
import { NavigatedData, Page } from "@nativescript/core";
import { OnboardingViewModel } from "./onboarding-view-model";
export function navigatingTo(args: EventData): void {
type OnboardingContext = { step?: number } | undefined;
export function navigatingTo(args: NavigatedData): void {
const page = args.object as Page;
// Preserve the step when returning from the flashing page (back navigation
// re-fires navigatingTo); only build a fresh model on first entry.
// re-fires navigatingTo); only build a fresh model on first entry. The
// permissions page navigates here with { step: 3 } to continue the flow.
if (!page.bindingContext) {
page.bindingContext = new OnboardingViewModel();
const context = args.context as OnboardingContext;
page.bindingContext = new OnboardingViewModel(context?.step);
}
}
+16 -6
View File
@@ -1,15 +1,25 @@
<Page xmlns="http://schemas.nativescript.org/tns.xsd" navigatingTo="navigatingTo" actionBarHidden="true">
<GridLayout rows="*,auto" class="p-20">
<ScrollView row="0">
<GridLayout rows="*,auto,auto" class="p-20">
<StackLayout row="0" verticalAlignment="middle" visibility="{{ splashVisibility }}">
<Label text="{{ headline }}" class="h1 text-center" textWrap="true" />
<Label text="{{ tagline }}" class="body-text text-center m-t-8" textWrap="true" />
<Image src="~/images/faceclaw-logo.png" stretch="aspectFit" height="{{ logoHeight }}" horizontalAlignment="center" class="onboarding-logo m-t-24" />
</StackLayout>
<ScrollView row="0" visibility="{{ contentVisibility }}">
<StackLayout>
<Image src="res://logo" stretch="aspectFit" height="140" horizontalAlignment="center" visibility="{{ logoVisibility }}" class="m-t-24" />
<Label text="{{ headline }}" class="h1 text-center m-t-24" textWrap="true" />
<Label text="{{ tagline }}" class="text-center m-t-8" textWrap="true" visibility="{{ taglineVisibility }}" />
<Label text="{{ body }}" class="m-t-24" textWrap="true" />
<Label text="{{ body }}" class="body-text m-t-24" textWrap="true" />
</StackLayout>
</ScrollView>
<GridLayout row="1" columns="*,*" class="m-t-20">
<StackLayout row="1" orientation="horizontal" horizontalAlignment="center" class="m-t-16" visibility="{{ footerVisibility }}">
<Label text="License (GPLv3)" class="footer-link" tap="{{ onLicenseTap }}" />
<Label text="·" class="footer-link-separator" />
<Label text="Privacy Policy" class="footer-link" tap="{{ onPrivacyTap }}" />
</StackLayout>
<GridLayout row="2" columns="*,*" class="m-t-20">
<Button col="0" text="{{ secondaryLabel }}" tap="{{ onSecondaryTap }}" visibility="{{ secondaryVisibility }}" />
<Button col="1" text="{{ primaryLabel }}" tap="{{ onPrimaryTap }}" class="-primary" />
</GridLayout>
+4 -4
View File
@@ -2,11 +2,11 @@
<GridLayout rows="*,auto" class="p-20">
<ScrollView row="0">
<StackLayout>
<Label text="Disconnect the Even App" class="h1 text-center m-t-24" textWrap="true" />
<Label text="Disconnect Other Apps" class="h1 text-center m-t-24" textWrap="true" />
<Label
text="Faceclaw and the official Even Realities app can't both be connected to the glasses at once. Before continuing, open the Even app, go to Home, select your glasses, open the Connection submenu, and press Disconnect (or turn off the Even app's Bluetooth)."
class="m-t-24" textWrap="true" />
<Button text="Open Even App Settings" tap="{{ onOpenEvenAppSettingsTap }}" class="-primary m-t-24" />
text="Faceclaw and the official Even Realities app can't both be connected to the glasses at once. Before continuing, open the Even app, go to Home, select your glasses, open the Connection submenu, and press Disconnect (or turn off the Even app's Bluetooth). If any other glasses app is installed (such as Mentra), disconnect it too."
class="body-text m-t-24" textWrap="true" />
<Button text="Open Even App Settings" tap="{{ onOpenEvenAppSettingsTap }}" width="{{ settingsButtonWidth }}" horizontalAlignment="center" class="-primary m-t-24" />
</StackLayout>
</ScrollView>
+15 -4
View File
@@ -1,4 +1,4 @@
import { Frame, Observable } from "@nativescript/core";
import { Frame, Observable, Screen } from "@nativescript/core";
import { openEvenAppSettings } from "../native/even-app-conflict";
@@ -8,7 +8,10 @@ export class OnboardingUnpairViewModel extends Observable {
}
onContinueTap(): void {
Frame.topmost()?.navigate({ moduleName: "phone-ui/onboarding-firmware-check-page" });
Frame.topmost()?.navigate({
moduleName: "phone-ui/pairing-page",
context: { onboarding: true },
});
}
onBackTap(): void {
@@ -18,9 +21,17 @@ export class OnboardingUnpairViewModel extends Observable {
return;
}
frame?.navigate({
moduleName: "phone-ui/config-page",
context: { onboarding: true },
moduleName: "phone-ui/onboarding-page",
context: { step: 3 },
clearHistory: true,
});
}
/**
* The settings button fills the page's width on phones but is capped so it
* doesn't stretch edge-to-edge on tablets.
*/
get settingsButtonWidth(): number {
return Math.min(320, Math.round(Screen.mainScreen.widthDIPs) - 40);
}
}
+54 -32
View File
@@ -1,4 +1,4 @@
import { Frame, Observable } from "@nativescript/core";
import { Frame, Observable, Screen } from "@nativescript/core";
import { setOnboardingCompleted, setPreviewOnlyMode } from "./onboarding-state";
@@ -10,8 +10,8 @@ type StepContent = {
body: string;
primaryLabel: string;
secondaryLabel: string;
showLogo: boolean;
showTagline: boolean;
/** Step 1 renders as the vertically-centered splash (headline + tagline + logo) instead of the scrolling body. */
splash: boolean;
showSecondary: boolean;
};
@@ -22,8 +22,7 @@ const STEP_CONTENT: Record<OnboardingStep, StepContent> = {
body: "",
primaryLabel: "Next",
secondaryLabel: "",
showLogo: true,
showTagline: true,
splash: true,
showSecondary: false,
},
2: {
@@ -33,19 +32,17 @@ const STEP_CONTENT: Record<OnboardingStep, StepContent> = {
"This unofficial software provides a custom user interface and functionality for the Even Realities G2 smart glasses. It is not created or supported by Even Realities. If this software somehow breaks my headset, this is not Even's fault and is not covered by the hardware's warranty. If this software doesn't break my headset, using this software may void the hardware's warranty anyways, at the sole discretion of Even Realities. This software is a development prototype and may not be relied on for anything important. This software may be broken at any time by software or firmware updates created by Even, and this will not be Even's fault.",
primaryLabel: "Agree",
secondaryLabel: "Back",
showLogo: false,
showTagline: false,
splash: false,
showSecondary: true,
},
3: {
headline: "Custom Firmware Required",
tagline: "",
body:
"Faceclaw only runs on Even Realities G2 glasses that have Faceclaw's custom firmware installed. You have two choices:\n\n• Preview Only — explore Faceclaw's interface on your phone's screen without pairing any glasses. Nothing is written to a headset.\n\n• Flash Firmware — install the custom firmware on your glasses now, then use Faceclaw for real. This connects to your glasses, asks for confirmation on the lens, then downloads and prepares the firmware.\n\nFlashing replaces the official firmware. It may void your warranty and, like any firmware update, carries a risk of bricking the device. You can only be connected to one app at a time, so disconnect the official Even app before flashing (open it, go to Home, select your glasses, open Connection, and press Disconnect).",
"Faceclaw only runs on Even Realities G2 glasses that have Faceclaw's custom firmware installed. You have two choices:\n\n• Preview Only — explore Faceclaw's interface on your phone's screen without pairing any glasses. Nothing is written to a headset.\n\n• Flash Firmware — install the custom firmware on your glasses now, then use Faceclaw for real. Faceclaw scans for nearby glasses so you can pick yours by model, colour, and serial, then connects, asks for confirmation on the lens, and downloads and prepares the firmware.\n\nFlashing replaces the official firmware. It may void your warranty and, like any firmware update, carries a risk of bricking the device. The glasses can only be connected to one app at a time, so the next step will walk you through disconnecting the official Even app (and any other glasses apps) first.",
primaryLabel: "Flash Firmware",
secondaryLabel: "Preview Only",
showLogo: false,
showTagline: false,
splash: false,
showSecondary: true,
},
};
@@ -53,8 +50,9 @@ const STEP_CONTENT: Record<OnboardingStep, StepContent> = {
export class OnboardingViewModel extends Observable {
private _step: OnboardingStep = 1;
constructor() {
constructor(initialStep?: number) {
super();
if (initialStep === 2 || initialStep === 3) this._step = initialStep;
this.publish();
}
@@ -64,14 +62,33 @@ export class OnboardingViewModel extends Observable {
return;
}
if (this._step === 2) {
this.setStep(3);
// The Permissions screen sits between the disclaimer and the firmware
// step; it navigates forward to a fresh onboarding page at step 3.
Frame.topmost()?.navigate({
moduleName: "phone-ui/permissions-page",
context: { onboarding: true },
});
return;
}
// Step 3 primary: begin the flashing setup — configure device addresses,
// then unpair the official app, then check firmware and flash.
// Step 3 primary: begin the flashing setup — disconnect other glasses apps
// first (a connected app blocks our BLE access, including pairing), then
// scan for and pick the glasses (manual address entry is offered from that
// page), then check firmware and flash.
Frame.topmost()?.navigate({ moduleName: "phone-ui/onboarding-unpair-page" });
}
onLicenseTap(): void {
this.openDocument("LICENSE", "License (GPLv3)");
}
onPrivacyTap(): void {
this.openDocument("PRIVACY", "Privacy Policy");
}
private openDocument(fileName: string, title: string): void {
Frame.topmost()?.navigate({
moduleName: "phone-ui/config-page",
context: { onboarding: true },
moduleName: "phone-ui/document-page",
context: { fileName, title },
});
}
@@ -111,30 +128,36 @@ export class OnboardingViewModel extends Observable {
return STEP_CONTENT[this._step].secondaryLabel;
}
get showLogo(): boolean {
return STEP_CONTENT[this._step].showLogo;
}
get showTagline(): boolean {
return STEP_CONTENT[this._step].showTagline;
}
get showSecondary(): boolean {
return STEP_CONTENT[this._step].showSecondary;
}
get logoVisibility(): "visible" | "collapse" {
return this.showLogo ? "visible" : "collapse";
get splashVisibility(): "visible" | "collapse" {
return STEP_CONTENT[this._step].splash ? "visible" : "collapse";
}
get taglineVisibility(): "visible" | "collapse" {
return this.showTagline ? "visible" : "collapse";
get contentVisibility(): "visible" | "collapse" {
return STEP_CONTENT[this._step].splash ? "collapse" : "visible";
}
/**
* The logo scales with the screen (~40% of its height) so it reads as a
* splash on tablets too, capped near the source PNG's height so it doesn't
* upscale into mush.
*/
get logoHeight(): number {
return Math.min(480, Math.round(Screen.mainScreen.heightDIPs * 0.4));
}
get secondaryVisibility(): "visible" | "collapse" {
return this.showSecondary ? "visible" : "collapse";
}
/** License and privacy-policy links, shown only under the disclaimer step. */
get footerVisibility(): "visible" | "collapse" {
return this._step === 2 ? "visible" : "collapse";
}
private setStep(step: OnboardingStep): void {
if (this._step === step) return;
this._step = step;
@@ -147,11 +170,10 @@ export class OnboardingViewModel extends Observable {
this.notifyPropertyChange("body", this.body);
this.notifyPropertyChange("primaryLabel", this.primaryLabel);
this.notifyPropertyChange("secondaryLabel", this.secondaryLabel);
this.notifyPropertyChange("showLogo", this.showLogo);
this.notifyPropertyChange("showTagline", this.showTagline);
this.notifyPropertyChange("showSecondary", this.showSecondary);
this.notifyPropertyChange("logoVisibility", this.logoVisibility);
this.notifyPropertyChange("taglineVisibility", this.taglineVisibility);
this.notifyPropertyChange("splashVisibility", this.splashVisibility);
this.notifyPropertyChange("contentVisibility", this.contentVisibility);
this.notifyPropertyChange("secondaryVisibility", this.secondaryVisibility);
this.notifyPropertyChange("footerVisibility", this.footerVisibility);
}
}
+32
View File
@@ -0,0 +1,32 @@
import { NavigatedData, Page } from "@nativescript/core";
import { PairingViewModel } from "./pairing-view-model";
type PairingContext = { onboarding?: boolean } | undefined;
export function navigatingTo(args: NavigatedData): void {
const page = args.object as Page;
// Preserve the model across back-navigation (returning from the firmware
// check or manual-entry pages) so the selection isn't lost; the model
// restarts its scan on re-entry.
let model = page.bindingContext as PairingViewModel | undefined;
if (!model) {
const context = args.context as PairingContext;
model = new PairingViewModel({ onboarding: context?.onboarding ?? false });
page.bindingContext = model;
}
void model.start();
}
export function navigatingFrom(args: NavigatedData): void {
const page = args.object as Page;
const model = page.bindingContext as PairingViewModel | undefined;
// Backing out destroys the page; a forward navigation (manual entry) keeps
// it on the stack, so only pause the scan and keep the model's app-lifecycle
// hooks for the return trip.
if (args.isBackNavigation) {
model?.dispose();
} else {
model?.stop();
}
}
+90
View File
@@ -0,0 +1,90 @@
<Page xmlns="http://schemas.nativescript.org/tns.xsd" navigatingTo="navigatingTo" navigatingFrom="navigatingFrom" actionBarHidden="{{ actionBarHidden }}">
<ActionBar title="Pair Glasses" />
<GridLayout rows="auto,auto,*,auto" class="p-16">
<StackLayout row="0">
<Label text="{{ headline }}" class="h1 text-center" textWrap="true" />
<Label text="{{ instructions }}" class="m-t-8 pairing-instructions" textWrap="true" />
</StackLayout>
<GridLayout row="1" columns="auto,*" class="m-t-12 pairing-status-row">
<ActivityIndicator col="0" busy="{{ scanning }}" visibility="{{ scanningVisibility }}" width="22" height="22" />
<Label col="1" text="{{ status }}" textWrap="true" class="pairing-status" />
</GridLayout>
<ScrollView row="2" class="m-t-12">
<StackLayout>
<Label text="Glasses" class="h2 pairing-section" />
<Label text="{{ emptyGlassesMessage }}" class="pairing-empty" textWrap="true" visibility="{{ emptyGlassesVisibility }}" />
<Repeater items="{{ glassesRows }}">
<Repeater.itemsLayout>
<StackLayout />
</Repeater.itemsLayout>
<Repeater.itemTemplate>
<GridLayout columns="84,*,auto" rows="auto" class="{{ rowClass }}" tap="{{ onRowTap }}">
<GridLayout col="0" rows="auto,auto" class="pairing-art">
<Image row="0" src="{{ imagePath }}" stretch="aspectFit" width="80" height="30" />
<GridLayout row="1" columns="auto,auto" horizontalAlignment="center" class="m-t-4" visibility="{{ swatchVisibility }}">
<Label col="0" text="" width="12" height="12" borderRadius="6" backgroundColor="{{ swatchHex }}" />
<Label col="1" text="{{ colorwayLabel }}" class="pairing-swatch-label m-l-4" />
</GridLayout>
</GridLayout>
<StackLayout col="1" class="m-l-8">
<GridLayout columns="auto,auto">
<Label col="0" text="{{ modelTitle }}" class="pairing-title" />
<Label col="1" text="{{ badge }}" class="pairing-badge m-l-6" visibility="{{ badgeVisibility }}" />
</GridLayout>
<Label text="{{ variantSummary }}" class="pairing-variant" visibility="{{ variantVisibility }}" />
<Label text="{{ proximityLine }}" class="{{ proximityClass }}" />
<Label text="{{ deviceName }}" class="pairing-serial" />
<Label text="{{ armsSummary }}" class="pairing-arms" textWrap="true" visibility="{{ armsVisibility }}" />
<Label text="{{ warning }}" class="pairing-warning" textWrap="true" visibility="{{ warningVisibility }}" />
</StackLayout>
<Label col="2" text="{{ chevron }}" class="pairing-chevron" verticalAlignment="center" />
</GridLayout>
</Repeater.itemTemplate>
</Repeater>
<Label text="Ring (optional)" class="h2 pairing-section m-t-16" />
<Label text="{{ emptyRingMessage }}" class="pairing-empty" textWrap="true" visibility="{{ emptyRingVisibility }}" />
<Repeater items="{{ ringRows }}">
<Repeater.itemsLayout>
<StackLayout />
</Repeater.itemsLayout>
<Repeater.itemTemplate>
<GridLayout columns="84,*,auto" rows="auto" class="{{ rowClass }}" tap="{{ onRowTap }}">
<Image col="0" src="{{ imagePath }}" stretch="aspectFit" width="56" height="30" class="pairing-art" />
<StackLayout col="1" class="m-l-8">
<GridLayout columns="auto,auto">
<Label col="0" text="{{ modelTitle }}" class="pairing-title" />
<Label col="1" text="{{ badge }}" class="pairing-badge m-l-6" visibility="{{ badgeVisibility }}" />
</GridLayout>
<Label text="{{ proximityLine }}" class="{{ proximityClass }}" />
<Label text="{{ deviceName }}" class="pairing-serial" />
<Label text="{{ armsSummary }}" class="pairing-arms" textWrap="true" visibility="{{ armsVisibility }}" />
<Label text="{{ warning }}" class="pairing-warning" textWrap="true" visibility="{{ warningVisibility }}" />
</StackLayout>
<Label col="2" text="{{ chevron }}" class="pairing-chevron" verticalAlignment="center" />
</GridLayout>
</Repeater.itemTemplate>
</Repeater>
<StackLayout class="pairing-selection m-t-16" visibility="{{ selectionVisibility }}">
<Label text="Selected" class="h2 pairing-section" />
<Label text="{{ selectionSummary }}" textWrap="true" />
</StackLayout>
</StackLayout>
</ScrollView>
<StackLayout row="3" class="m-t-12">
<GridLayout columns="*,*">
<Button col="0" text="{{ secondaryLabel }}" tap="{{ onSecondaryTap }}" />
<Button col="1" text="{{ primaryLabel }}" tap="{{ onPrimaryTap }}" class="-primary" isEnabled="{{ primaryEnabled }}" />
</GridLayout>
<GridLayout columns="*,*" class="m-t-4">
<Button col="0" text="{{ scanToggleLabel }}" tap="{{ onScanToggleTap }}" class="pairing-link" />
<Button col="1" text="Enter addresses manually" tap="{{ onManualTap }}" class="pairing-link" />
</GridLayout>
</StackLayout>
</GridLayout>
</Page>
+466
View File
@@ -0,0 +1,466 @@
import { Application, EventData, Frame, Observable, View } from "@nativescript/core";
import { ensureBlePermissions } from "../g2/android-permissions";
import { loadDeviceAddresses, loadPairedGlassesIdentity, saveDeviceAddresses, savePairedGlassesIdentity } from "../g2/device-addresses";
import { formatErrorMessage } from "../util/format-error";
import {
colorwayLabel,
DEFAULT_STALE_AFTER_MS,
DiscoveryAggregator,
glassesRow,
nearestCandidateId,
ringRow,
type GlassesPairCandidate,
type PairingRowPresentation,
type RingCandidate,
} from "../g2/pairing-candidates";
import { DeviceDiscoveryBridge } from "../native/device-discovery";
import { setPreviewOnlyMode } from "./onboarding-state";
/** One Repeater row: the presentation plus the display-only fields the XML binds. */
export type PairingRowItem = PairingRowPresentation & {
rowClass: string;
swatchVisibility: "visible" | "collapse";
colorwayLabel: string;
badgeVisibility: "visible" | "collapse";
variantVisibility: "visible" | "collapse";
proximityLine: string;
proximityClass: string;
armsVisibility: "visible" | "collapse";
warningVisibility: "visible" | "collapse";
chevron: string;
/**
* Tap handler carried on the row itself. The Repeater assigns a row's
* bindingContext before attaching it to the tree, so a `$parents['Page']`
* binding cannot resolve on first bind and logs an error every refresh;
* binding `tap="{{ onRowTap }}"` against the item avoids the walk entirely.
*/
onRowTap: (args: EventData) => void;
};
const REFRESH_INTERVAL_MS = 500;
const NO_RESULTS_HINT_AFTER_MS = 10_000;
/**
* Live pairing scan. Streams advertisements into a `DiscoveryAggregator`,
* re-renders the pair/ring lists at a calm cadence, and saves the chosen
* addresses plus the decoded identity when the user continues.
*
* Selection is always a deliberate tap (no auto-select on a single result):
* a strong signal is a hint, not consent.
*/
export class PairingViewModel extends Observable {
private readonly onboarding: boolean;
private readonly aggregator = new DiscoveryAggregator();
private discovery: DeviceDiscoveryBridge | null = null;
private refreshTimer: ReturnType<typeof setInterval> | null = null;
private startedAtMs = 0;
private advertisementCount = 0;
private scanFailure = "";
private _scanning = false;
private _status = "";
private _glassesRows: PairingRowItem[] = [];
private _ringRows: PairingRowItem[] = [];
private selectedPair: GlassesPairCandidate | null = null;
private selectedRing: RingCandidate | null = null;
private readonly previouslyPairedSerial: string | null;
private readonly previouslyPairedRing: string;
constructor(options?: { onboarding?: boolean }) {
super();
this.onboarding = options?.onboarding ?? false;
this.previouslyPairedSerial = loadPairedGlassesIdentity()?.serial ?? null;
this.previouslyPairedRing = loadDeviceAddresses().ring;
// A backgrounded phone (Home, screen lock, a call) must not keep the
// low-latency scan and the refresh timer burning; pick both back up when
// the app returns.
Application.on(Application.suspendEvent, this.onAppSuspend);
Application.on(Application.resumeEvent, this.onAppResume);
}
// --- lifecycle -------------------------------------------------------------
private resumeScanAfterSuspend = false;
private readonly onAppSuspend = (): void => {
if (this._scanning) {
this.resumeScanAfterSuspend = true;
this.stop();
}
};
private readonly onAppResume = (): void => {
if (this.resumeScanAfterSuspend) {
this.resumeScanAfterSuspend = false;
void this.start();
}
};
/** Final teardown when the page is left for good (not a detour to manual entry). */
dispose(): void {
this.stop();
Application.off(Application.suspendEvent, this.onAppSuspend);
Application.off(Application.resumeEvent, this.onAppResume);
}
async start(): Promise<void> {
if (this._scanning) return;
if (!global.isAndroid) {
this.status = "Pairing is only available on Android.";
return;
}
try {
await ensureBlePermissions();
} catch (error) {
this.status = this.formatError(error);
return;
}
try {
this.discovery ??= new DeviceDiscoveryBridge();
} catch (error) {
this.status = this.formatError(error);
return;
}
if (!this.discovery.bluetoothEnabled) {
this.status = "Bluetooth is off. Turn it on, then tap Scan.";
return;
}
this.scanFailure = "";
this.startedAtMs = Date.now();
const started = this.discovery.startScan({
onAdvertisement: (raw) => {
if (this.aggregator.ingest(raw)) this.advertisementCount += 1;
},
onScanFailed: (_code, message) => {
this.scanFailure = message;
this.scanning = false;
this.refresh();
},
});
if (!started) {
this.status = "Could not start the Bluetooth scan. Check that Bluetooth is on.";
return;
}
// Bonded arms show up immediately (no signal) and gain a serial once heard.
this.discovery.emitBondedDevices();
this.scanning = true;
this.refreshTimer ??= setInterval(() => this.refresh(), REFRESH_INTERVAL_MS);
this.refresh();
}
stop(): void {
if (this.refreshTimer) {
clearInterval(this.refreshTimer);
this.refreshTimer = null;
}
this.discovery?.stopScan();
this.scanning = false;
this.refresh();
}
// --- observable properties -------------------------------------------------
get actionBarHidden(): boolean {
return this.onboarding;
}
get headline(): string {
return this.onboarding ? "Pair Your Glasses" : "Pair Glasses";
}
get instructions(): string {
return (
"Take the glasses out of their case (or open the lid) and keep them next to the phone. " +
"Each arm advertises its serial; a pair is ready when both arms report the same one. " +
"An arm connected to the official Even app stops advertising — disconnect it there first."
);
}
get scanning(): boolean {
return this._scanning;
}
set scanning(value: boolean) {
if (this._scanning === value) return;
this._scanning = value;
this.notifyPropertyChange("scanning", value);
this.notifyPropertyChange("scanningVisibility", this.scanningVisibility);
this.notifyPropertyChange("scanToggleLabel", this.scanToggleLabel);
}
get scanningVisibility(): "visible" | "collapse" {
return this._scanning ? "visible" : "collapse";
}
get scanToggleLabel(): string {
return this._scanning ? "Pause scan" : "Scan again";
}
get status(): string {
return this._status;
}
set status(value: string) {
if (this._status === value) return;
this._status = value;
this.notifyPropertyChange("status", value);
}
get glassesRows(): PairingRowItem[] {
return this._glassesRows;
}
get ringRows(): PairingRowItem[] {
return this._ringRows;
}
get emptyGlassesVisibility(): "visible" | "collapse" {
return this._glassesRows.length ? "collapse" : "visible";
}
get emptyGlassesMessage(): string {
if (this.scanFailure) return `Scan failed: ${this.scanFailure}`;
if (!this._scanning) return "Scan paused. Tap Scan again to look for glasses.";
const elapsed = Date.now() - this.startedAtMs;
if (elapsed < NO_RESULTS_HINT_AFTER_MS) return "Listening for glasses…";
return (
"No glasses heard yet. Make sure they are out of the case and not connected to another app. " +
"On Android 11 and older, Location must also be switched on for Bluetooth scanning to return results."
);
}
get emptyRingVisibility(): "visible" | "collapse" {
return this._ringRows.length ? "collapse" : "visible";
}
get emptyRingMessage(): string {
return this._scanning ? "No ring heard yet. Tap the ring to wake it if you have one." : "";
}
get selectionVisibility(): "visible" | "collapse" {
return this.selectedPair || this.selectedRing ? "visible" : "collapse";
}
get selectionSummary(): string {
const parts: string[] = [];
if (this.selectedPair) {
const identity = this.selectedPair.identity;
const label = identity ? identity.displayName : "Even Realities G2";
parts.push(
`${label} · serial ${this.selectedPair.serial ?? "unknown"}\n` +
`Left ${this.selectedPair.left?.address ?? "?"} · Right ${this.selectedPair.right?.address ?? "?"}`,
);
}
if (this.selectedRing) {
parts.push(`Ring ${this.selectedRing.advertisement.name} · ${this.selectedRing.advertisement.address}`);
}
return parts.join("\n");
}
get primaryLabel(): string {
return this.onboarding ? "Continue" : "Save";
}
get primaryEnabled(): boolean {
return !!this.selectedPair || (!this.onboarding && !!this.selectedRing);
}
get secondaryLabel(): string {
return this.onboarding ? "Back" : "Cancel";
}
// --- actions ---------------------------------------------------------------
// Arrow property: NativeScript fires XML event handlers with `this` bound to the
// tapped view's bindingContext (the row item), not the view model.
readonly onRowTap = (args: EventData): void => {
const row = (args.object as View).bindingContext as PairingRowItem | undefined;
if (!row) return;
if (row.kind === "glasses") {
const pair = this.aggregator.pairs().find((candidate) => candidate.id === row.id) ?? null;
if (!pair) return;
if (!row.canSelect) {
this.status = row.warning || `${row.modelTitle}: ${row.armsSummary}. Both arms must be heard before pairing.`;
return;
}
this.selectedPair = this.selectedPair?.id === pair.id ? null : pair;
} else {
const ring = this.aggregator.rings().find((candidate) => candidate.id === row.id) ?? null;
this.selectedRing = this.selectedRing?.id === ring?.id ? null : ring;
}
this.refresh();
};
onPrimaryTap(): void {
const pair = this.selectedPair;
const ring = this.selectedRing;
if (!pair && !ring) return;
// refresh() drops a selection whose pair regressed below complete, but the
// tap can race a prune: never fall back to previously stored addresses for
// a missing arm — that silently welds together arms of two different pairs.
if (pair && (!pair.left || !pair.right)) return;
const existing = loadDeviceAddresses();
const addresses = {
right: pair ? pair.right!.address : existing.right,
left: pair ? pair.left!.address : existing.left,
ring: ring?.advertisement.address ?? existing.ring,
};
saveDeviceAddresses(addresses);
if (pair) {
savePairedGlassesIdentity({
serial: pair.serial ?? "",
leftName: pair.left!.name,
rightName: pair.right!.name,
leftAddress: pair.left!.address,
rightAddress: pair.right!.address,
ringName: ring?.advertisement.name ?? (addresses.ring === existing.ring ? (loadPairedGlassesIdentity()?.ringName ?? "") : ""),
ringAddress: addresses.ring,
pairedAtMs: Date.now(),
});
} else if (ring) {
// Replacing just the ring: keep the stored glasses identity current so
// the config page doesn't keep naming the old ring.
const identity = loadPairedGlassesIdentity();
if (identity) {
savePairedGlassesIdentity({
...identity,
ringName: ring.advertisement.name,
ringAddress: ring.advertisement.address,
});
}
}
this.dispose();
if (this.onboarding) {
setPreviewOnlyMode(false);
// Continue the onboarding chain: check the glasses' firmware next.
Frame.topmost()?.navigate({ moduleName: "phone-ui/onboarding-firmware-check-page" });
return;
}
Frame.topmost()?.navigate({ moduleName: "phone-ui/main-page", clearHistory: true });
}
onSecondaryTap(): void {
this.dispose();
const frame = Frame.topmost();
if (frame?.canGoBack()) {
frame.goBack();
return;
}
frame?.navigate({
moduleName: this.onboarding ? "phone-ui/onboarding-unpair-page" : "phone-ui/main-page",
clearHistory: true,
});
}
onManualTap(): void {
this.stop();
Frame.topmost()?.navigate({
moduleName: "phone-ui/config-page",
context: { onboarding: this.onboarding },
});
}
onScanToggleTap(): void {
if (this._scanning) {
this.stop();
return;
}
this.aggregator.clear();
this.advertisementCount = 0;
void this.start();
}
// --- rendering -------------------------------------------------------------
private refresh(): void {
this.aggregator.prune(Date.now(), DEFAULT_STALE_AFTER_MS);
const pairs = this.aggregator.pairs();
const rings = this.aggregator.rings();
// Keep the selection pointing at live data (addresses can only change if a
// side was replaced); drop it if the pair disappeared — or if it degraded
// below complete (an arm went back in the case), so Save can never write a
// one-armed selection padded with stale addresses.
if (this.selectedPair) {
const live = pairs.find((pair) => pair.id === this.selectedPair!.id) ?? null;
this.selectedPair = live?.completeness === "complete" ? live : null;
}
if (this.selectedRing) {
this.selectedRing = rings.find((ring) => ring.id === this.selectedRing!.id) ?? null;
}
const nearestPair = nearestCandidateId(pairs);
const nearestRing = nearestCandidateId(rings);
this._glassesRows = pairs.map((pair) =>
toRowItem(
glassesRow(pair, { pairedSerial: this.previouslyPairedSerial, nearestId: nearestPair }),
this.selectedPair?.id === pair.id,
this.onRowTap,
),
);
this._ringRows = rings.map((ring) =>
toRowItem(
ringRow(ring, { pairedRingAddress: this.previouslyPairedRing, nearestId: nearestRing }),
this.selectedRing?.id === ring.id,
this.onRowTap,
),
);
const complete = pairs.filter((pair) => pair.completeness === "complete").length;
const partial = pairs.length - complete;
if (this.scanFailure) {
this.status = `Scan failed: ${this.scanFailure}`;
} else if (!this._scanning) {
this.status = "Scan paused.";
} else if (!pairs.length && !rings.length) {
this.status = "Scanning…";
} else {
const bits = [
complete ? `${complete} ${complete === 1 ? "pair" : "pairs"} ready` : null,
partial ? `${partial} with one arm heard` : null,
rings.length ? `${rings.length} ${rings.length === 1 ? "ring" : "rings"}` : null,
].filter(Boolean);
this.status = `Scanning… ${bits.join(" · ")}. Tap a pair to select it.`;
}
for (const property of [
"glassesRows",
"ringRows",
"emptyGlassesVisibility",
"emptyGlassesMessage",
"emptyRingVisibility",
"emptyRingMessage",
"selectionVisibility",
"selectionSummary",
"primaryEnabled",
] as const) {
this.notifyPropertyChange(property, this[property]);
}
}
private formatError(error: unknown): string {
return formatErrorMessage(error);
}
}
function toRowItem(row: PairingRowPresentation, selected: boolean, onRowTap: (args: EventData) => void): PairingRowItem {
const classes = ["pairing-row"];
if (selected) classes.push("pairing-row-selected");
if (!row.canSelect) classes.push("pairing-row-incomplete");
return {
...row,
rowClass: classes.join(" "),
// The swatch is redundant when the variant photo already shows the finish.
swatchVisibility: row.swatchHex && !row.hasVariantImage ? "visible" : "collapse",
colorwayLabel: colorwayLabel(row.colorway),
badgeVisibility: row.badge ? "visible" : "collapse",
variantVisibility: row.variantSummary ? "visible" : "collapse",
proximityLine: `${row.proximityGlyph} ${row.proximitySummary}`,
proximityClass: row.zone === "immediate" ? "pairing-proximity pairing-proximity-immediate" : "pairing-proximity",
armsVisibility: row.armsSummary ? "visible" : "collapse",
warningVisibility: row.warning ? "visible" : "collapse",
chevron: selected ? "✓" : row.canSelect ? "›" : "…",
onRowTap,
};
}
+25
View File
@@ -0,0 +1,25 @@
import { EventData, NavigatedData, Page } from "@nativescript/core";
import { PermissionsViewModel } from "./permissions-view-model";
type PermissionsContext = { onboarding?: boolean } | undefined;
export function navigatingTo(args: NavigatedData): void {
const page = args.object as Page;
// Preserve the model when returning via back navigation (from the step-3
// onboarding page); statuses are re-checked in the loaded handler.
if (!page.bindingContext) {
const context = args.context as PermissionsContext;
page.bindingContext = new PermissionsViewModel({ onboarding: context?.onboarding ?? false });
}
}
export function loaded(args: EventData): void {
const page = args.object as Page;
(page.bindingContext as PermissionsViewModel | undefined)?.onPageLoaded();
}
export function unloaded(args: EventData): void {
const page = args.object as Page;
(page.bindingContext as PermissionsViewModel | undefined)?.onPageUnloaded();
}
+37
View File
@@ -0,0 +1,37 @@
<Page xmlns="http://schemas.nativescript.org/tns.xsd" navigatingTo="navigatingTo" loaded="loaded" unloaded="unloaded" actionBarHidden="{{ actionBarHidden }}">
<ActionBar title="Permissions" />
<GridLayout rows="auto,*,auto" class="p-16">
<StackLayout row="0">
<Label text="Permissions" class="h1 text-center" textWrap="true" visibility="{{ headlineVisibility }}" />
<Label text="{{ instructions }}" class="m-t-8 pairing-instructions" textWrap="true" />
</StackLayout>
<ScrollView row="1" class="m-t-12">
<StackLayout>
<Repeater items="{{ cards }}">
<Repeater.itemsLayout>
<StackLayout />
</Repeater.itemsLayout>
<Repeater.itemTemplate>
<GridLayout columns="*,auto" rows="auto" class="pairing-row" tap="{{ onCardTap }}">
<StackLayout col="0">
<GridLayout columns="auto,auto">
<Label col="0" text="{{ title }}" class="pairing-title" />
<Label col="1" text="Optional" class="pairing-badge" marginLeft="14" visibility="{{ optionalVisibility }}" />
</GridLayout>
<Label text="{{ description }}" class="permissions-description" textWrap="true" />
</StackLayout>
<Label col="1" text="✓" class="permissions-check" verticalAlignment="center" visibility="{{ checkVisibility }}" />
</GridLayout>
</Repeater.itemTemplate>
</Repeater>
</StackLayout>
</ScrollView>
<GridLayout row="2" columns="*,*" class="m-t-12">
<Button col="0" text="Back" tap="{{ onSecondaryTap }}" visibility="{{ secondaryVisibility }}" />
<Button col="1" text="{{ primaryLabel }}" tap="{{ onPrimaryTap }}" class="{{ primaryClass }}" />
</GridLayout>
</GridLayout>
</Page>
+243
View File
@@ -0,0 +1,243 @@
import { Application, Dialogs, EventData, Frame, Observable, View } from "@nativescript/core";
import {
ensureCalendarPermission,
ensureFineLocationPermission,
hasBlePermissions,
hasCalendarPermission,
hasFineLocationPermission,
hasMicrophonePermission,
hasPostNotificationsPermission,
requestBlePermissions,
requestMicrophonePermission,
requestPostNotificationsPermission,
} from "../g2/android-permissions";
import { isIgnoringBatteryOptimizations, requestIgnoreBatteryOptimizations } from "../native/battery-optimization";
import { isNotificationListenerEnabled, requestNotificationListenerAccess } from "../native/notification-access";
type PermissionDefinition = {
id: string;
title: string;
description: string;
optional: boolean;
isGranted: () => boolean;
/** Show the grant UI: a runtime-permission dialog or a system settings screen. */
request: () => void | Promise<unknown>;
};
/**
* Battery Optimization and Read Notifications are not runtime permissions:
* their request() opens a system screen, so the granted state can only be
* re-checked when the app resumes (the page refreshes on Application.resume).
*/
const PERMISSIONS: PermissionDefinition[] = [
{
id: "nearby-devices",
title: "Nearby Devices",
description: "Needed to communicate with your smart glasses over Bluetooth.",
optional: false,
isGranted: hasBlePermissions,
request: requestBlePermissions,
},
{
id: "post-notifications",
title: "Send Notifications",
description: "A notification will be pinned, to keep Faceclaw running while your phone screen is off.",
optional: false,
isGranted: hasPostNotificationsPermission,
request: requestPostNotificationsPermission,
},
{
id: "battery-optimization",
title: "Battery Optimization",
description: "Needed to keep running while your phone screen is off.",
optional: false,
isGranted: isIgnoringBatteryOptimizations,
request: requestIgnoreBatteryOptimizations,
},
{
id: "read-notifications",
title: "Read Notifications",
description: "Needed to display your Android notifications on the glasses.",
optional: true,
isGranted: isNotificationListenerEnabled,
request: requestNotificationListenerAccess,
},
{
id: "microphone",
title: "Microphone",
description: "Needed to use voice input.",
optional: true,
isGranted: hasMicrophonePermission,
request: requestMicrophonePermission,
},
{
id: "location",
title: "Location",
description: "Needed to use location-based features like navigation inside glasses apps.",
optional: true,
// Navigation needs precise fixes, so the checkmark tracks fine location;
// "approximate only" leaves the card unchecked and re-tappable.
isGranted: hasFineLocationPermission,
request: ensureFineLocationPermission,
},
{
id: "calendar",
title: "Calendar",
description: "Needed to display your calendar on the glasses.",
optional: true,
isGranted: hasCalendarPermission,
request: ensureCalendarPermission,
},
];
/** One Repeater card: the permission's copy plus the display-only fields the XML binds. */
export type PermissionCardItem = {
id: string;
title: string;
description: string;
optionalVisibility: "visible" | "collapse";
checkVisibility: "visible" | "collapse";
onCardTap: (args: EventData) => void;
};
/**
* The Permissions screen: one card per Android 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.
*/
export class PermissionsViewModel extends Observable {
private readonly onboarding: boolean;
private _cards: PermissionCardItem[] = [];
private requesting = false;
constructor(options?: { onboarding?: boolean }) {
super();
this.onboarding = options?.onboarding ?? false;
this.refresh();
}
/**
* Battery Optimization and Read Notifications grant flows leave the app for
* a system screen; re-check everything whenever the app comes back.
*/
private readonly onAppResume = (): void => this.refresh();
onPageLoaded(): void {
Application.on(Application.resumeEvent, this.onAppResume);
this.refresh();
}
onPageUnloaded(): void {
Application.off(Application.resumeEvent, this.onAppResume);
}
// --- observable properties -------------------------------------------------
get actionBarHidden(): boolean {
return this.onboarding;
}
get headlineVisibility(): "visible" | "collapse" {
return this.onboarding ? "visible" : "collapse";
}
get instructions(): string {
return this.onboarding
? "Faceclaw uses these 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."
: "Tap a card to grant a permission; a checkmark means it is already granted.";
}
get cards(): PermissionCardItem[] {
return this._cards;
}
get primaryLabel(): string {
return this.onboarding ? "Continue" : "Done";
}
/**
* Continue looks grayed out (but stays tappable — tapping it asks for
* confirmation instead) while a required permission is missing. Done, in
* menu mode, never dims: there is nothing to warn about when closing.
*/
get primaryClass(): string {
return this.onboarding && !this.requiredPermissionsGranted()
? "-primary permissions-primary-dimmed"
: "-primary";
}
get secondaryVisibility(): "visible" | "collapse" {
return this.onboarding ? "visible" : "collapse";
}
// --- actions ---------------------------------------------------------------
// Arrow property: NativeScript fires XML event handlers with `this` bound to
// the tapped view's bindingContext (the card item), not the view model.
readonly onCardTap = (args: EventData): void => {
const item = (args.object as View).bindingContext as PermissionCardItem | undefined;
if (!item || this.requesting) return;
const definition = PERMISSIONS.find((permission) => permission.id === item.id);
if (!definition || definition.isGranted()) return;
void this.requestPermission(definition);
};
async onPrimaryTap(): Promise<void> {
if (this.onboarding) {
if (!this.requiredPermissionsGranted()) {
const proceed = await Dialogs.confirm({
title: "Missing Permissions",
message: "You haven't enabled all of the necessary permissions. Are you sure you want to continue?",
okButtonText: "Continue",
cancelButtonText: "Go Back",
});
if (!proceed) return;
}
// Continue the onboarding chain at the Custom Firmware Required step.
Frame.topmost()?.navigate({
moduleName: "phone-ui/onboarding-page",
context: { step: 3 },
});
return;
}
Frame.topmost()?.goBack();
}
onSecondaryTap(): void {
Frame.topmost()?.goBack();
}
// --- rendering -------------------------------------------------------------
private async requestPermission(definition: PermissionDefinition): Promise<void> {
this.requesting = true;
try {
await definition.request();
} catch {
// A denial simply leaves the card unchecked; the user can tap again.
} finally {
this.requesting = false;
this.refresh();
}
}
private requiredPermissionsGranted(): boolean {
return PERMISSIONS.every((definition) => definition.optional || definition.isGranted());
}
refresh(): void {
this._cards = PERMISSIONS.map((definition) => ({
id: definition.id,
title: definition.title,
description: definition.description,
optionalVisibility: definition.optional ? "visible" : "collapse",
checkVisibility: definition.isGranted() ? "visible" : "collapse",
onCardTap: this.onCardTap,
}));
this.notifyPropertyChange("cards", this._cards);
this.notifyPropertyChange("primaryClass", this.primaryClass);
}
}
+72
View File
@@ -0,0 +1,72 @@
<!--
The phone's controller for the glasses, as a three-tab area below the mirror:
Settings (screen size + brightness), Watch (the simulated watch face: same
scheme as the watch pad - tap = select, double-tap or two fingers = back,
hold = menu, swipes navigate), and Ring (simulated R1 inputs on the ring's
own scheme). The narrow mic button at the tab bar's right edge fires the
wakeword without changing the selected tab. Used by main-page.xml in both
orientations; binds to the page's MainViewModel, which collapses the whole
area while a text setting is being edited (keyboard-input mode).
The root is a rows="auto,*" grid so the active section can use the leftover
height (the Watch face centers in it); the three sections share the star
cell, only one visible at a time.
-->
<GridLayout xmlns="http://schemas.nativescript.org/tns.xsd" rows="auto,*" class="remote-controls">
<!-- rows="auto" everywhere below: a rows-less GridLayout's implicit row
acts as star, and this component sits in a bounded (star-row) parent,
where that would balloon the first grid to fill all remaining height. -->
<GridLayout row="0" rows="auto" columns="*,*,*,auto" class="controls-tab-bar">
<Button col="0" text="Settings" tap="{{ onSettingsTabTap }}" class="{{ settingsTabClass }}" />
<Button col="1" text="Watch" tap="{{ onWatchTabTap }}" class="{{ watchTabClass }}" />
<Button col="2" text="Ring" tap="{{ onRingTabTap }}" class="{{ ringTabClass }}" />
<!-- A Button can't hold an image, so this is a button-styled tile. The
explicit star row makes the cell fill the tile's height so the icon's
center alignment has room to work in. -->
<GridLayout col="3" rows="*" tap="{{ onSyntheticMicTap }}" class="tab-button tab-mic-button">
<Image src="res://ic_tab_mic" class="tab-mic-icon" verticalAlignment="center" horizontalAlignment="center" />
</GridLayout>
</GridLayout>
<!-- Settings tab -->
<StackLayout row="1" visibility="{{ settingsTabVisibility }}">
<GridLayout rows="auto" columns="auto,*" class="settings-row">
<Label col="0" text="Screen size" class="settings-row-label" verticalAlignment="center" />
<Button col="1" text="{{ displayModeLabel }}" tap="{{ onDisplayModeTap }}" class="mode-button" horizontalAlignment="left" />
</GridLayout>
<GridLayout rows="auto" columns="auto,*,auto" class="settings-row">
<Label col="0" text="☀" class="brightness-icon" verticalAlignment="center" />
<Slider col="1" width="100%" minValue="0" maxValue="100" value="{{ brightnessPercent }}" valueChange="{{ onBrightnessChange }}" isEnabled="{{ brightnessSliderEnabled }}" />
<StackLayout col="2" orientation="horizontal" verticalAlignment="center" class="auto-toggle">
<Label text="Auto" verticalAlignment="center" />
<Switch checked="{{ brightnessAuto }}" checkedChange="{{ onBrightnessAutoChange }}" />
</StackLayout>
</GridLayout>
</StackLayout>
<!-- Watch tab: centered in the leftover height, capped at the 1.5:1 face
aspect (watchFaceWidth = min(available, 1.5 x face height). -->
<StackLayout row="1" visibility="{{ watchTabVisibility }}" width="{{ watchFaceWidth }}" horizontalAlignment="center" verticalAlignment="center">
<GridLayout class="touchpad" tap="{{ onPadTap }}" doubleTap="{{ onPadDoubleTap }}" longPress="{{ onPadLongPress }}" swipe="{{ onPadSwipe }}" touch="{{ onPadTouch }}">
<Label text="{{ padFocusLine }}" class="pad-focus" horizontalAlignment="center" verticalAlignment="center" />
<Label text="● select ●● back ‒ menu" class="pad-legend" horizontalAlignment="center" verticalAlignment="bottom" />
<Button text="▲" tap="{{ onDpadUp }}" class="pad-dpad-button" horizontalAlignment="center" verticalAlignment="top" />
<Button text="▼" tap="{{ onDpadDown }}" class="pad-dpad-button pad-dpad-down" horizontalAlignment="center" verticalAlignment="bottom" />
<Button text="◀" tap="{{ onDpadLeft }}" class="pad-dpad-button" horizontalAlignment="left" verticalAlignment="center" />
<Button text="▶" tap="{{ onDpadRight }}" class="pad-dpad-button" horizontalAlignment="right" verticalAlignment="center" />
</GridLayout>
<GridLayout rows="auto" columns="*,*" class="action-row">
<Button col="0" text="Back" tap="{{ onBackTap }}" class="action-button" />
<Button col="1" text="Menu" tap="{{ onMenuTap }}" class="action-button" />
</GridLayout>
</StackLayout>
<!-- Ring tab -->
<GridLayout row="1" rows="auto,auto" columns="*,*,*" visibility="{{ ringTabVisibility }}" class="ring-grid">
<Button row="0" col="0" text="▲ Up" tap="{{ onSyntheticUpTap }}" class="ring-pad-button" />
<Button row="0" col="1" text="▼ Down" tap="{{ onSyntheticDownTap }}" class="ring-pad-button" />
<Button row="0" col="2" text="● Click" tap="{{ onSyntheticRightTap }}" class="ring-pad-button" />
<Button row="1" col="0" text="●● Double" tap="{{ onSyntheticLeftTap }}" class="ring-pad-button" />
<Button row="1" col="1" text="‒ Hold" tap="{{ onSyntheticLongPressTap }}" class="ring-pad-button" />
</GridLayout>
</GridLayout>
+15
View File
@@ -0,0 +1,15 @@
import { NavigatedData, Page } from "@nativescript/core";
import { SpeakersViewModel } from "./speakers-view-model";
export function navigatingTo(args: NavigatedData): void {
const page = args.object as Page;
let model = page.bindingContext as SpeakersViewModel | undefined;
if (!model) {
model = new SpeakersViewModel();
page.bindingContext = model;
}
// Reload every time so edits made from a conversation page (re-diarize,
// split, reassign) show up on the way back.
model.reload();
}
+27
View File
@@ -0,0 +1,27 @@
<Page xmlns="http://schemas.nativescript.org/tns.xsd" navigatingTo="navigatingTo">
<ActionBar title="Speakers" />
<ScrollView class="p-8">
<StackLayout>
<Label text="{{ emptyMessage }}" class="conversation-empty" textWrap="true" visibility="{{ emptyVisibility }}" />
<Repeater items="{{ speakerRows }}">
<Repeater.itemsLayout>
<StackLayout />
</Repeater.itemsLayout>
<Repeater.itemTemplate>
<GridLayout columns="auto,*" class="conversation-row" tap="{{ onRowTap }}">
<Label col="0" text="" width="18" height="18" borderRadius="9" backgroundColor="{{ swatchColor }}" verticalAlignment="center" />
<StackLayout col="1" class="m-l-8">
<StackLayout orientation="horizontal">
<Label text="{{ name }}" class="conversation-title" />
<Label text="{{ tag }}" class="speaker-tag m-l-6" visibility="{{ tagVisibility }}" />
<Label text="my voice" class="speaker-wearer-badge m-l-6" visibility="{{ wearerVisibility }}" />
</StackLayout>
<Label text="{{ meta }}" class="conversation-meta" />
</StackLayout>
</GridLayout>
</Repeater.itemTemplate>
</Repeater>
</StackLayout>
</ScrollView>
</Page>
+230
View File
@@ -0,0 +1,230 @@
import { Frame, Observable, action, alert, confirm, prompt } from "@nativescript/core";
import { speakerRegistry, type SpeakerProfile } from "../apps/microphones/speakers";
import { formatDateTime } from "./conversation-format";
/** One speaker row; tap handler rides on the item itself (see pairing-view-model). */
export type SpeakerRowItem = {
name: string;
tag: string;
tagVisibility: "visible" | "collapse";
wearerVisibility: "visible" | "collapse";
swatchColor: string;
meta: string;
onRowTap: () => void;
};
const PRESET_COLORS: Array<{ label: string; hex: string }> = [
{ label: "Sky", hex: "#4FC3F7" },
{ label: "Amber", hex: "#FFB74D" },
{ label: "Green", hex: "#81C784" },
{ label: "Red", hex: "#E57373" },
{ label: "Purple", hex: "#BA68C8" },
{ label: "Yellow", hex: "#FFD54F" },
{ label: "Teal", hex: "#4DB6AC" },
{ label: "Pink", hex: "#F06292" },
{ label: "Brown", hex: "#A1887F" },
{ label: "Gray", hex: "#90A4AE" },
];
export class SpeakersViewModel extends Observable {
private _speakerRows: SpeakerRowItem[] = [];
private _emptyMessage = "";
get speakerRows(): SpeakerRowItem[] {
return this._speakerRows;
}
get emptyMessage(): string {
return this._emptyMessage;
}
get emptyVisibility(): "visible" | "collapse" {
return this._emptyMessage ? "visible" : "collapse";
}
reload(): void {
if (!global.isAndroid) {
this.setRows([], "Speaker management is only available on Android.");
return;
}
speakerRegistry.reload();
const profiles = speakerRegistry.all();
this.setRows(
profiles.map((profile) => this.toRowItem(profile)),
profiles.length > 0
? ""
: "No speakers yet — voices are enrolled automatically while Captions + Save captions run in the Microphones app on the glasses.",
);
}
private setRows(rows: SpeakerRowItem[], emptyMessage: string): void {
this._speakerRows = rows;
this._emptyMessage = emptyMessage;
this.notifyPropertyChange("speakerRows", rows);
this.notifyPropertyChange("emptyMessage", emptyMessage);
this.notifyPropertyChange("emptyVisibility", this.emptyVisibility);
}
private toRowItem(profile: SpeakerProfile): SpeakerRowItem {
const metaParts: string[] = [];
if (profile.lastHeardAt > 0) metaParts.push(`Last heard ${formatDateTime(profile.lastHeardAt)}`);
metaParts.push(`${profile.segmentCount} lines`);
return {
name: profile.name,
tag: profile.tag,
tagVisibility: profile.tag ? "visible" : "collapse",
wearerVisibility: profile.isWearer ? "visible" : "collapse",
swatchColor: profile.color || "#90A4AE",
meta: metaParts.join(" · "),
onRowTap: () => {
void this.onSpeakerTap(profile.id);
},
};
}
private async onSpeakerTap(speakerId: number): Promise<void> {
const profile = speakerRegistry.byId(speakerId);
if (!profile) return;
const choice = await action({
title: profile.name,
cancelButtonText: "Cancel",
actions: [
"View insights",
"Rename",
"Set tag",
"Set color",
"Set as my voice",
"Merge into...",
"View conversations",
"Delete",
],
});
switch (choice) {
case "View insights":
await this.viewInsights(profile);
break;
case "Rename":
await this.renameSpeaker(profile);
break;
case "Set tag":
await this.setSpeakerTag(profile);
break;
case "Set color":
await this.setSpeakerColor(profile);
break;
case "Set as my voice":
speakerRegistry.setWearer(profile.id, true);
this.reload();
break;
case "Merge into...":
await this.mergeSpeaker(profile);
break;
case "View conversations":
Frame.topmost()?.navigate({
moduleName: "phone-ui/conversations-page",
context: { speakerId: profile.id },
});
break;
case "Delete":
await this.deleteSpeaker(profile);
break;
}
}
/** The contact's conversation memory: last heard, recap, action items, facts. */
private async viewInsights(profile: SpeakerProfile): Promise<void> {
const parts: string[] = [];
if (profile.lastHeardAt > 0) parts.push(`Last heard ${formatDateTime(profile.lastHeardAt)}.`);
if (profile.lastRecap) parts.push(`Last conversation: ${profile.lastRecap}`);
if (profile.actionItems.length) {
parts.push(`Action items:\n${profile.actionItems.map((item) => `• ${item}`).join("\n")}`);
}
if (profile.facts.length) {
parts.push(`Facts:\n${profile.facts.map((fact) => `• ${fact}`).join("\n")}`);
}
if (!profile.lastRecap && !profile.actionItems.length && !profile.facts.length) {
parts.push(
"No conversation insights yet — they are generated on-device when a captioned " +
"conversation with this person ends (requires the downloaded assistant model).",
);
}
await alert({
title: profile.name,
message: parts.join("\n\n"),
okButtonText: "Close",
});
}
private async renameSpeaker(profile: SpeakerProfile): Promise<void> {
const result = await prompt({
title: "Rename speaker",
defaultText: profile.name,
okButtonText: "Rename",
cancelButtonText: "Cancel",
});
const name = result.result ? result.text.trim() : "";
if (!name || name === profile.name) return;
speakerRegistry.rename(profile.id, name);
this.reload();
}
private async setSpeakerTag(profile: SpeakerProfile): Promise<void> {
const result = await prompt({
title: "Set tag",
message: "A short label like \"work\", \"family\", or \"neighbor\".",
defaultText: profile.tag,
okButtonText: "Save",
cancelButtonText: "Cancel",
});
if (!result.result) return;
speakerRegistry.setTag(profile.id, result.text.trim());
this.reload();
}
private async setSpeakerColor(profile: SpeakerProfile): Promise<void> {
const picked = await action({
title: "Set color",
cancelButtonText: "Cancel",
actions: PRESET_COLORS.map((color) => `${color.label} (${color.hex})`),
});
const chosen = PRESET_COLORS.find((color) => `${color.label} (${color.hex})` === picked);
if (!chosen) return;
speakerRegistry.setColor(profile.id, chosen.hex);
this.reload();
}
private async mergeSpeaker(profile: SpeakerProfile): Promise<void> {
const others = speakerRegistry.all().filter((candidate) => candidate.id !== profile.id);
if (others.length === 0) return;
const picked = await action({
title: "Merge into...",
message: `${profile.name}'s lines and voice-print will move to the speaker you pick.`,
cancelButtonText: "Cancel",
actions: others.map((candidate) => candidate.name),
});
const target = others.find((candidate) => candidate.name === picked);
if (!target) return;
const confirmed = await confirm({
title: "Merge speakers",
message: `Merge ${profile.name} into ${target.name}? This cannot be undone.`,
okButtonText: "Merge",
cancelButtonText: "Cancel",
});
if (!confirmed) return;
speakerRegistry.merge(profile.id, target.id);
this.reload();
}
private async deleteSpeaker(profile: SpeakerProfile): Promise<void> {
const confirmed = await confirm({
title: "Delete speaker",
message: `Delete ${profile.name}? Their transcript lines stay but lose the speaker label.`,
okButtonText: "Delete",
cancelButtonText: "Cancel",
});
if (!confirmed) return;
speakerRegistry.remove(profile.id);
this.reload();
}
}