Initial publishable release

This commit is contained in:
James Babcock committed 2026-04-26 23:07:54 -07:00
commit 6e442e7faa
120 files changed
+750769

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
<Frame defaultPage="launch-page">
</Frame>
+15
View File
@@ -0,0 +1,15 @@
@import '@nativescript/theme/css/core.css';
@import '@nativescript/theme/css/default.css';
Button.-primary {
font-size: 18;
}
.system-name-modal {
margin: 16;
padding: 16;
background-color: #f6f6f6;
border-color: #222222;
border-width: 1;
border-radius: 8;
}
+14
View File
@@ -0,0 +1,14 @@
/*
In NativeScript, the app.ts file is the entry point to your application.
You can use this file to perform app-level initialization, but the primary
purpose of the file is to pass control to the app’s first module.
*/
import { Application } from '@nativescript/core'
Application.run({ moduleName: 'app-root' })
/*
Do not place any code after the application has been started as it will not
be executed on iOS.
*/
+8
View File
@@ -0,0 +1,8 @@
import { EventData, Page } from "@nativescript/core";
import { ConfigViewModel } from "./config-view-model";
export function navigatingTo(args: EventData): void {
const page = args.object as Page;
page.bindingContext = new ConfigViewModel();
}
+38
View File
@@ -0,0 +1,38 @@
<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" />
<StackLayout row="1" 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">
<Label text="Left arm MAC" />
<TextField text="{{ leftAddress }}" textChange="{{ onLeftAddressTextChange }}" autocorrect="false" autocapitalizationType="none" />
</StackLayout>
<StackLayout row="3" 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">
<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 }}" />
</GridLayout>
<Label row="5" text="{{ status }}" class="m-t-16" textWrap="true" />
<GridLayout row="6" columns="*,*" class="m-t-16">
<Button col="0" text="Save" tap="{{ onSaveTap }}" class="-primary" />
<Button col="1" text="Back" tap="{{ onBackTap }}" />
</GridLayout>
<ScrollView row="7" class="m-t-16">
<Label text="{{ discoveryLog }}" textWrap="true" verticalAlignment="top" />
</ScrollView>
</GridLayout>
</Page>
+174
View File
@@ -0,0 +1,174 @@
import { Frame, Observable } from "@nativescript/core";
import { ensureBlePermissions } from "./g2/android-permissions";
import { isValidMacAddress, loadDeviceAddresses, normalizeMacAddress, saveDeviceAddresses } from "./g2/device-addresses";
import { buildAddressSet, DeviceDiscoveryBridge } from "./native/device-discovery";
type TextChangeArgs = { value?: string; object?: { text?: string } };
export class ConfigViewModel extends Observable {
private readonly discovery = new DeviceDiscoveryBridge();
private _rightAddress = "";
private _leftAddress = "";
private _ringAddress = "";
private _status = "";
private _discoveryLog = "";
private _discovering = false;
constructor() {
super();
const stored = loadDeviceAddresses();
this.rightAddress = stored.right;
this.leftAddress = stored.left;
this.ringAddress = stored.ring;
this.status = "Edit addresses manually, or load them from paired devices or a scan.";
}
get rightAddress(): string {
return this._rightAddress;
}
set rightAddress(value: string) {
if (this._rightAddress !== value) {
this._rightAddress = value;
this.notifyPropertyChange("rightAddress", value);
}
}
get leftAddress(): string {
return this._leftAddress;
}
set leftAddress(value: string) {
if (this._leftAddress !== value) {
this._leftAddress = value;
this.notifyPropertyChange("leftAddress", value);
}
}
get ringAddress(): string {
return this._ringAddress;
}
set ringAddress(value: string) {
if (this._ringAddress !== value) {
this._ringAddress = value;
this.notifyPropertyChange("ringAddress", value);
}
}
get status(): string {
return this._status;
}
set status(value: string) {
if (this._status !== value) {
this._status = value;
this.notifyPropertyChange("status", value);
}
}
get discoveryLog(): string {
return this._discoveryLog;
}
set discoveryLog(value: string) {
if (this._discoveryLog !== value) {
this._discoveryLog = value;
this.notifyPropertyChange("discoveryLog", value);
}
}
get canDiscover(): boolean {
return !this._discovering;
}
private setDiscovering(value: boolean): void {
if (this._discovering !== value) {
this._discovering = value;
this.notifyPropertyChange("canDiscover", this.canDiscover);
}
}
onRightAddressTextChange(args: TextChangeArgs): void {
this.rightAddress = args.object?.text ?? args.value ?? "";
}
onLeftAddressTextChange(args: TextChangeArgs): void {
this.leftAddress = args.object?.text ?? args.value ?? "";
}
onRingAddressTextChange(args: TextChangeArgs): void {
this.ringAddress = args.object?.text ?? args.value ?? "";
}
async onLoadPairedTap(): Promise<void> {
await this.populateFromDiscovery(async () => this.discovery.getBondedCandidates(), "Loaded paired devices.");
}
async onScanTap(): Promise<void> {
await this.populateFromDiscovery(async () => this.discovery.scanCandidates(6000), "Scanned nearby devices.");
}
onBackTap(): void {
Frame.topmost()?.navigate({
moduleName: "main-page",
clearHistory: true,
});
}
onSaveTap(): void {
const right = normalizeMacAddress(this.rightAddress);
const left = normalizeMacAddress(this.leftAddress);
const ring = normalizeMacAddress(this.ringAddress);
if (!isValidMacAddress(right)) {
this.status = "Right arm MAC address is invalid.";
return;
}
if (!isValidMacAddress(left)) {
this.status = "Left arm MAC address is invalid.";
return;
}
if (!isValidMacAddress(ring, true)) {
this.status = "Ring MAC address is invalid.";
return;
}
saveDeviceAddresses({ right, left, ring });
this.rightAddress = right;
this.leftAddress = left;
this.ringAddress = ring;
this.status = "Saved device addresses.";
}
private async populateFromDiscovery(
load: () => Promise<Parameters<typeof buildAddressSet>[0]>,
successMessage: string,
): Promise<void> {
if (!global.isAndroid) {
this.status = "Discovery is only available on Android.";
return;
}
this.setDiscovering(true);
try {
await ensureBlePermissions();
const candidates = await load();
const selection = buildAddressSet(candidates);
if (selection.right) this.rightAddress = selection.right;
if (selection.left) this.leftAddress = selection.left;
if (selection.ring) this.ringAddress = selection.ring;
this.discoveryLog = selection.summary;
this.status = successMessage;
} catch (error) {
this.status = this.formatError(error);
} finally {
this.setDiscovering(false);
}
}
private formatError(error: unknown): string {
const raw = (error as Error)?.message ?? String(error);
return raw.replace(/[\x00-\x1f]+/g, " ").replace(/\s+/g, " ").trim();
}
}
+1
View File
@@ -0,0 +1 @@
Dimitar Zhekov <dimitar.zhekov@gmail.com>
+1
View File
@@ -0,0 +1 @@
See OFL.TXT
+1
View File
@@ -0,0 +1 @@
See CHANGES
+94
View File
@@ -0,0 +1,94 @@
Copyright (C) 2020 Dimitar Toshkov Zhekov,
with Reserved Font Name "Terminus Font".
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
+395
View File
@@ -0,0 +1,395 @@
Contents:
1. About.
1.1. Build requitements.
1.2. Quick installation.
1.3. Legend.
1.4. Variants.
1.5. Notes.
1.6. Alternative tools.
2. Linux console.
2.1. Installation.
2.2. Usage.
2.3. Quick reference.
2.4. Legend.
2.5. Notes.
3. X11 Window System.
3.1. Installation.
3.2. Notes.
4. Open Type Bitmap.
4.1. Installation.
4.2. Notes.
5. Microsoft Windows.
5.1. Installation package.
5.2. Font file only.
5.3. Notes.
6. Frequently Asked Questions.
7. Legal information.
7.1. Licenses.
7.2. Copyright.
--
1. About.
This archive contains source code for generating and installing Terminus
Font for Linux console, X11 Window System, Microsoft Windows and Open Type
Bitmap capable systems.
- version 4.49.1
- sizes 6x12, 8x14, 8x16, 10x18, 10x20, 11x22, 12x24, 14x28, 16x32
- weights normal, bold, CRT VGA bold
- characters 1356
- format Bitmap Distribution Format (BDF) version 2.1
The character set covers about 120 language sets and supports ISO8859-1/2/5/
7/9/13/15/16, Paratype-PT154/PT254, KOI8-R/U/E/F, Esperanto and many IBM,
Windows and Macintosh code pages, as well as the IBM VGA, vt100 and xterm
pseudographic characters.
1.1. Build requirements.
- GNU make
- Python 3.5.0+ (or node.js 6.9.0+ as alternative)
- for X11 only: bdftopcf
- for Windows only: GCC for Win32/i686
- for the Windows installer only: NSIS and patch(1).
1.2. Quick installation.
The commands:
$ ./configure [--prefix=PREFIX]
$ make -j8
# make install fontdir
compile and install the Linux console and X11 Window System fonts.
The default PREFIX is /usr/local.
1.3. Legend.
The file names are structured as follows:
ter-u<SIZE><STYLE>.bdf
<SIZE> is the font height. <STYLE> is n for normal (all sizes), b for bold
(all sizes except 6x12), and v for CRT VGA bold (8x14 and 8x16 only, uses
the eight character matrix column).
1.4. Variants.
Some characters are implemented in two variants. To use the alternate
variant, execute:
$ patch -p1 -i alt/<NAME>.diff
before making the font. See the font WEB page for examples. If you want to
combine hi2 with dv1 and/or ka2, apply hi2 and then hi2-dv1 and/or hi2-ka2.
The default variant for unicode range 2800-28FF is oriented towards
pseudographics.
1.5. Notes.
The commands marked with $ can be executed by a regular user.
The configure commands are optional.
"make -j8" runs 8 jobs in parallel.
Sizes 6x12, 11x22, 14x28-bold and 16x32-normal are worse than the others.
Avoid them.
210E and 210F are not italic.
226A, 226B and the double struck letters are not very good.
2135 may be wrong.
The hebrew letters and sheqel are uppercase height, which is an attempt to
compensate for the missing width.
1.6. Alternative tools.
If your Python 3 executable is named python instead if python3:
$ ./configure INT=python
To use node.js instead of python:
$ ./configure INT=node EXT=js
--
2. Linux console.
- weights normal, bold, CRT VGA-bold
- code pages ISO8859-1/ISO8859-15/Windows-1252, ISO8859-2/Windows-1250,
Windows-1251/ISO8859-5, ISO8859-9/Windows-1254, ISO8859-16,
ISO8859-7/Windows-1253, ISO8859-13/Windows-1257, IBM-437,
Bulgarian-MIK, KOI8-R, KOI8-U, Paratype-PT154, combined
- format PC Screen Font (PSF) with unicode data
2.1. Installation.
$ ./configure [--prefix=PREFIX | --psfdir=DIRECTORY]
$ make -j8 psf
# make install-psf
The files are compressed with gzip and installed in DIRECTORY. The default
DIRECTORY is PREFIX/share/consolefonts. For kbd, you may need to change it
to PREFIX/lib/kbd/consolefonts or PREFIX/share/kbd/consolefonts, depending
on the kbd version.
The CRT VGA bold weight fonts, suitable for real CRT text modes only, are
not installed by default. To install them, execute:
$ make -j8 psf-vgaw
# make install-psf-vgaw
2.2. Usage.
To load a cont in consoletools:
$ consolechars [-m MAPPING] -f ter-<X><SIZE><STYLE>
To load a font in kbd:
$ setfont [-m MAPPING] ter-<X><SIZE><STYLE>
where <X> is a character identifying the code page as listed in p.2.4.
2.3. Quick reference.
The commands:
$ ./configure [--prefix=PREFIX | --psfdir=DIRECTORY | --psfref=FILENAME]
# make install-psf-ref
install the text from p.2.4 as FILENAME (the default is README.terminus)
in DIRECTORY.
2.4. Legend.
names mappings covered codepage(s)
ter-1* iso01, iso15, cp1252 ISO8859-1, ISO8859-15, Windows-1252
ter-2* iso02, cp1250 ISO8859-2, Windows-1250
ter-7* iso07, cp1253 ISO8859-7, Windows-1253
ter-9* iso09, cp1254 ISO8859-9, Windows-1254
ter-c* cp1251, iso05 Windows-1251, ISO8859-5
ter-d* iso13, cp1257 ISO8859-13, Windows-1257
ter-g* iso16 ISO8859-16
ter-h* cp1255, iso08 Windows-1258, ISO8859-8
ter-i* cp437 IBM-437
ter-k* koi8r KOI8-R
ter-m* mik Bulgarian-MIK
ter-p* pt154 Paratype-PT154
ter-u* koi8u KOI8-U
ter-v* all mappings / code pages listed above and many others, about 110
language sets, 8 or 16 foreground colors depending on the kernel and
console driver versions
names weight
ter-*n normal
ter-*b bold
ter-*v CRT VGA bold
2.5. Notes.
The combined code page is based on IBM-437 (character 0xFF is ogonek).
The ISO8859-16 font also includes all letters and accents from Windows-1250.
--
3. X11 Window System.
- weights normal, bold
- code pages ISO8859-1/Windows-1252, ISO8859-2, ISO8859-5, ISO8859-7,
ISO8859-9/Windows-1254, ISO8859-13, ISO8859-15, ISO8859-16,
Windows-1251, IBM-437, KOI8-R, KOI8-U, Paratype-PT154 and
ISO10646-1 (unicode)
- format Portable Compiled Font (PCF)
3.1. Installation.
$ ./configure [--prefix=PREFIX | --x11dir=DIRECTORY]
$ make -j8 pcf
# make install-pcf
The files are compressed with gzip and installed in DIRECTORY. The default
DIRECTORY is PREFIX/share/fonts/terminus. Requires bdftopcf.
A copy of the normal 6x12 font is installed as "bold", because some X11
libraries and applications substitute the missing bold fonts by shifting the
normal fonts, and others do not recognize the bold weight at all if the
lowest font size lacks it.
To update the font cache in DIRECTORY after (un)installation, run:
# make fontdir
The configuration file which lists the font directories must contain
DIRECTORY. The X11 server may need to be restarted so the font list can be
updated.
By default, only the unicode (ISO10646-1) font is installed. To install the
other code pages:
$ make -j8 pcf-8bit
# make install-pcf-8bit
3.2. Notes.
The ISO8859-1 and ISO8859-9 fonts contain the Windows Western characters and
can be used as Windows-1252 and Windows-1254 respectively.
--
4. Open Type Bitmap.
- weights normal, bold
- code pages ISO10646-1 (unicode)
- format Linux/UNIX bitmap-only TrueType
4.1. Installation.
$ ./configure [--prefix=PREFIX | --otbdir=DIRECTORY]
$ make otb
# make install-otb
The files are installed in DIRECTORY.
The default DIRECTORY is PREFIX/share/fonts/terminus.
4.2. Notes
An OTB file is generated for each BDF file, instead of combining sizes by
weight, for the following reasons:
- KDE compatibility. With combined files, only the first size is available.
- Correct global font metrics. For example, the base line and character
width for 8x14 and 8x16 (relative to height) may never be identical.
otb1cli is NOT a full-featured BDF to sfnt convertor. It expands the bitmaps
first, uses the expanded widths, does not support overlapping characters,
and targets Linux/UNIX only.
--
5. Microsoft Windows.
- weights normal, bold
- code pages Windows-1252, 1250, 1253, 1254, 1251 and 1257
- format Font File Format version 2.0, compiled into FON
5.1. Installation package.
Make sure that no variant patches are applied to the font (p.1.4).
> cd win32
> build
Be patient, the process may take several minutes.
After that, open terminus.nsi and compile it.
5.2. Font file only.
> copy *.bdf win32
> cd win32
> make -j8
You can install terminus.fon via the regular means.
5.3. Notes.
The Windows code pages contain a total of 384 characters. All other
characters (math, pseudographics etc.) are not currently available.
--
6. Frequently Asked Questions.
Q. Italic version?
A. No. The quality is significantly lower, and preserving the font width
requires overlapping characters, which are not handled very well by X11/Xft.
You can try mkitalic from FreeBSD or bdfslant from Debian.
Q. Scalable version?
A. Probably not. The font uses a lot of straight horizontal and vertical
lines, which is good for a bitmap, but not so much for a vector font. A
bitmap font packaged as TTF seems possible.
Q. How about some new characters?
A. Contact me and be ready to help.
Q. The bold 6x12 font...
A. ...does not exist, there is no space for a bold font in a 6x12 matrix.
However, the "normal" font is somewhere between.
Q. The font works in X11/Motif, but not in GNOME/KDE/Xfce.
A. Try adding 75-yes-terminus.conf to the Fontconfig configuration files.
For some Fontconfig versions, you may need to replace the text "Terminus"
in 75-yes-terminus.conf with "xos4 Terminus", though that is unlikely.
See also mkfontscale(1), mkfontdir(1), fc-cache(1), xorg.conf(5), xfs(1),
xlsfonts(1), fonts-conf(5) etc.
Q. My terminal emulator does not display cyrillic/pseudographics/...
A. If you have the 8-bit X11 code pages installed, and your emulator uses
"XLFD" font names, make sure that the font name ends with "-10616-1" instead
of "-*-*".
--
7. Legal information.
7.1. Licenses.
Terminus Font is licensed under the SIL Open Font License, Version 1.1.
The license is included as OFL.TXT, and is also available with a FAQ at:
http://scripts.sil.org/OFL
The font includes two variants of unicode range 2800-28FF, but does not
support Braille in any way.
The configure files, python and javascript sources are distributed under
the GNU General Public License version 2.0 or (at your choice) any later
version.
7.2. Copyright.
Terminus Font 4.49.1, Copyright (C) 2020 Dimitar Toshkov Zhekov.
Report bugs to <dimitar.zhekov@gmail.com>
Thanks to Anton Zinoviev, Tim Allen, Kir Koliushkin, Antonios Galanopoulos
and everyone else who helped.
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+88
View File
@@ -0,0 +1,88 @@
import { Application, Utils } from "@nativescript/core";
const PERMISSION_REQUEST_CODE = 4242;
const POST_NOTIFICATIONS_PERMISSION = "android.permission.POST_NOTIFICATIONS";
function getActivity(): androidx.appcompat.app.AppCompatActivity {
const activity = Application.android.foregroundActivity ?? Application.android.startActivity;
if (!activity) throw new Error("No Android activity is available");
return activity;
}
function getContext(): android.content.Context {
const context = Utils.android.getApplicationContext();
if (!context) throw new Error("No Android application context is available");
return context;
}
function toJavaStringArray(values: string[]): string[] {
const result = Array.create("java.lang.String", values.length) as string[];
for (let i = 0; i < values.length; i++) {
result[i] = values[i]!;
}
return result;
}
function getRequiredPermissions(): string[] {
const sdk = android.os.Build.VERSION.SDK_INT;
const permissions: string[] = [];
if (sdk >= 31) {
permissions.push(
android.Manifest.permission.BLUETOOTH_SCAN,
android.Manifest.permission.BLUETOOTH_CONNECT,
);
} else {
permissions.push(android.Manifest.permission.ACCESS_FINE_LOCATION);
}
if (sdk >= 33) {
permissions.push(POST_NOTIFICATIONS_PERMISSION);
}
return permissions;
}
export async function ensureBlePermissions(): Promise<void> {
if (!global.isAndroid) return;
const context = getContext();
const activity = getActivity();
const required = getRequiredPermissions();
const missing = required.filter(
(permission) =>
androidx.core.content.ContextCompat.checkSelfPermission(context, permission) !==
android.content.pm.PackageManager.PERMISSION_GRANTED,
);
if (missing.length === 0) return;
await new Promise<void>((resolve, reject) => {
const callback = (args: {
requestCode: number;
permissions: string[];
grantResults: number[];
}) => {
if (args.requestCode !== PERMISSION_REQUEST_CODE) return;
Application.android.off(Application.android.activityRequestPermissionsEvent, callback);
const denied = missing.filter(
(_permission, index) =>
args.grantResults[index] !== android.content.pm.PackageManager.PERMISSION_GRANTED,
);
if (denied.length > 0) {
reject(new Error(`Bluetooth permissions denied: ${denied.join(", ")}`));
return;
}
resolve();
};
Application.android.on(Application.android.activityRequestPermissionsEvent, callback);
androidx.core.app.ActivityCompat.requestPermissions(
activity,
toJavaStringArray(missing),
PERMISSION_REQUEST_CODE,
);
});
}
+645
View File
@@ -0,0 +1,645 @@
import { G2_LENS_HEIGHT, G2_LENS_WIDTH, GrayImage } from "../graphics/image";
import { EventSourceType, EventSourceTypeName, OsEventTypeList, OsEventTypeName, } from "g2-kit/lite";
import { ImageSource } from "@nativescript/core";
import { loadDeviceAddresses } from "./device-addresses";
import { ensureBlePermissions } from "./android-permissions";
import { FaceclawCommunicatorBridge, type RawInputEvent } from "../native/faceclaw-communicator";
import { startForegroundNotification, stopForegroundNotification, updateForegroundNotification } from "../native/foreground-service";
import { mediaControllerBridge } from "../native/media-controller";
import { nightscoutBridge } from "../native/nightscout";
import { openEvenAppSettings, readEvenAppNotificationState } from "../native/even-app-conflict";
import { grayImageToPreviewSource } from "../native/gray-image-preview";
import {
drawDashboard,
getDashboardNightscoutSettings,
getDashboardSystemCardName,
receiveInput,
setDashboardBatteryLevels,
setDashboardActions,
setDashboardNightscoutApiToken,
setDashboardNightscoutSiteUrl,
setDashboardSystemCardName,
} from "../ui/dashboard";
type ConnectionPhase = "disconnected" | "connecting" | "connected" | "disconnecting";
export type TextSettingEditorKind = "dashboard-name" | "nightscout-site-url" | "nightscout-api-token";
export type DashboardSnapshot = {
phase: ConnectionPhase;
status: string;
log: string;
displayPreview: ImageSource | null;
systemCardName: string;
editingSystemCardName: boolean;
activeTextSettingEditorKind: TextSettingEditorKind | null;
activeTextSettingTitle: string;
activeTextSettingValue: string;
evenAppConflictMessage: string;
evenAppConflictWarningVisible: boolean;
};
type DashboardListener = (snapshot: DashboardSnapshot) => void;
type LogLevel = "debug"|"info"|"warn"|"error";
const CONTAINER_NAME = "dashboard";
const DASHBOARD_INTERVAL_MS = 60_000;
const EVEN_APP_DETECTED_MESSAGE =
"The Even Realities app appears to be running. If Faceclaw has trouble connecting, open its app settings and force stop it.";
function formatTimestamp(date: Date): string {
return date.toISOString().slice(11, 23);
}
function pad2(value: number): string {
return String(value).padStart(2, "0");
}
function formatTime24h(date: Date, includeSeconds: boolean): string {
const hours = date.getHours();
const minutes = pad2(date.getMinutes());
const seconds = pad2(date.getSeconds());
return includeSeconds
? `${hours}:${minutes}:${seconds}`
: `${hours}:${minutes}`;
}
function formatUtcOffset(date: Date): string {
const offsetMinutes = -date.getTimezoneOffset();
const sign = offsetMinutes >= 0 ? "+" : "-";
const absoluteMinutes = Math.abs(offsetMinutes);
const hours = Math.floor(absoluteMinutes / 60);
const minutes = absoluteMinutes % 60;
return `UTC${sign}${pad2(hours)}:${pad2(minutes)}`;
}
function formatForStatus(date: Date): string {
return formatTime24h(date, true);
}
function eventName(eventType: number): string {
return OsEventTypeName[eventType] ?? `UNKNOWN_${eventType}`;
}
function sourceName(eventSource: number): string {
return EventSourceTypeName[eventSource] ?? `SOURCE_${eventSource}`;
}
function normalizeContainerName(name: string): string {
return name.replace(/[^\x20-\x7e]+/g, "");
}
function isDashboardContainerName(name: string): boolean {
const normalized = normalizeContainerName(name);
return normalized === CONTAINER_NAME || normalized.includes(CONTAINER_NAME);
}
class DashboardController {
private phase: ConnectionPhase = "disconnected";
private status = "Disconnected.";
private log = "";
private editingSystemCardName = false;
private activeTextSettingEditorKind: TextSettingEditorKind | null = null;
private evenNotificationActive = false;
private evenAppConflictMessage = "";
private displayPreview: ImageSource | null = grayImageToPreviewSource(
new GrayImage(G2_LENS_WIDTH, G2_LENS_HEIGHT, 0),
);
private readonly listeners = new Set<DashboardListener>();
private communicator: FaceclawCommunicatorBridge | null = null;
private dashboardTimer: ReturnType<typeof setInterval> | null = null;
private offState: (() => void) | null = null;
private offLog: (() => void) | null = null;
private offRing: (() => void) | null = null;
private offBattery: (() => void) | null = null;
private offEvenAppConflict: (() => void) | null = null;
private offMedia: (() => void) | null = null;
private offNightscout: (() => void) | null = null;
private lastInput = "waiting...";
private lastSys = "none yet";
private renderInProgress = false;
private renderQueued = false;
private queuedRenderReason: "initial" | "interval" = "interval";
constructor() {
setDashboardActions({
disconnect: () => this.disconnect(),
startSystemNameEdit: () => this.startSystemNameEdit(),
endSystemNameEdit: () => this.endSystemNameEdit(),
startNightscoutSiteUrlEdit: () => this.startNightscoutSiteUrlEdit(),
startNightscoutApiTokenEdit: () => this.startNightscoutApiTokenEdit(),
endTextSettingEdit: () => this.endTextSettingEdit(),
});
}
subscribe(listener: DashboardListener): () => void {
this.listeners.add(listener);
listener(this.snapshot());
return () => {
this.listeners.delete(listener);
};
}
snapshot(): DashboardSnapshot {
return {
phase: this.phase,
status: this.status,
log: this.log,
displayPreview: this.displayPreview,
systemCardName: getDashboardSystemCardName(),
editingSystemCardName: this.editingSystemCardName,
activeTextSettingEditorKind: this.activeTextSettingEditorKind,
activeTextSettingTitle: this.getActiveTextSettingTitle(),
activeTextSettingValue: this.getActiveTextSettingValue(),
evenAppConflictMessage: this.evenAppConflictMessage,
evenAppConflictWarningVisible: this.evenAppConflictMessage.length > 0,
};
}
refreshEvenAppStatus(): void {
const state = readEvenAppNotificationState();
const wasActive = this.evenNotificationActive;
this.evenNotificationActive = state.evenNotificationActive;
if (state.evenNotificationActive && !wasActive) {
this.appendLog("Even app notification is active.");
}
if (state.evenNotificationActive && !this.evenAppConflictMessage) {
this.evenAppConflictMessage = EVEN_APP_DETECTED_MESSAGE;
this.emit();
}
if (!state.evenNotificationActive && this.evenAppConflictMessage) {
this.evenAppConflictMessage = "";
this.emit();
}
}
openEvenAppSettings(): void {
openEvenAppSettings();
}
setSystemCardName(name: string): void {
const savedName = setDashboardSystemCardName(name);
this.emit();
if (this.phase === "connected" && this.communicator) {
void this.requestRender("interval").catch((error) => {
this.appendLog(`dashboard name update failed: ${this.formatError(error)}`);
});
} else {
const image = drawDashboard();
this.setDisplayPreview(grayImageToPreviewSource(image));
}
if (savedName !== name) {
this.emit();
}
}
setActiveTextSettingValue(value: string): void {
switch (this.activeTextSettingEditorKind) {
case "dashboard-name":
this.setSystemCardName(value);
return;
case "nightscout-site-url":
setDashboardNightscoutSiteUrl(value);
this.emit();
this.previewOrRenderAfterTextSettingChange("nightscout site URL");
return;
case "nightscout-api-token":
setDashboardNightscoutApiToken(value);
this.emit();
this.previewOrRenderAfterTextSettingChange("nightscout API token");
return;
default:
return;
}
}
endSystemNameEdit(): void {
if (!this.editingSystemCardName) return;
this.editingSystemCardName = false;
if (this.activeTextSettingEditorKind === "dashboard-name") {
this.activeTextSettingEditorKind = null;
}
this.emit();
}
async connect(): Promise<void> {
if (this.phase !== "disconnected") return;
const addresses = loadDeviceAddresses();
if (!addresses.right || !addresses.left) {
const message = "Configure both left and right arm MAC addresses before connecting.";
this.setPhase("disconnected");
this.setStatus(`Failed: ${message}`);
this.appendLog(`error: ${message}`);
throw new Error(message);
}
this.log = "";
this.lastInput = "waiting...";
this.lastSys = "none yet";
this.refreshEvenAppStatus();
this.setPhase("connecting");
this.setStatus("Connecting to the glasses...");
this.appendLog(
`Using configured arms: R=${addresses.right} L=${addresses.left}${addresses.ring ? ` ring=${addresses.ring}` : ""}`,
);
startForegroundNotification("Connecting to the glasses");
let communicator: FaceclawCommunicatorBridge | null = null;
try {
await ensureBlePermissions();
communicator = new FaceclawCommunicatorBridge({
right: addresses.right,
left: addresses.left,
ring: addresses.ring,
});
this.communicator = communicator;
this.offLog = communicator.onLog((line) => {
this.appendLog(line);
});
this.offState = communicator.onStateChange((state) => {
const mappedPhase =
state.phase === "connected"
? "connected"
: state.phase === "disconnecting"
? "disconnecting"
: state.phase === "disconnected"
? "disconnected"
: "connecting";
this.setPhase(mappedPhase);
this.setStatus(state.status);
});
this.offRing = communicator.onRingEvent((event) => {
void this.handleInputEvent(event).catch((error) => {
const message = this.formatError(error);
this.appendLog(`input handler failed: ${message}`);
});
});
this.offBattery = communicator.onBatteryState((state) => {
setDashboardBatteryLevels({
headset: state.battery,
headsetCharging: state.chargingStatus > 0,
});
if (this.phase === "connected" && this.communicator) {
void this.requestRender("interval").catch((error) => {
const message = this.formatError(error);
this.appendLog(`battery update failed: ${message}`);
});
}
});
this.offEvenAppConflict = communicator.onEvenAppConflict((message) => {
this.refreshEvenAppStatus();
if (!this.evenNotificationActive) {
this.appendLog(`Even app conflict suspected, but notification was not active: ${message}`);
return;
}
this.evenAppConflictMessage = message;
this.appendLog(message);
this.emit();
});
this.offMedia = mediaControllerBridge.onStateChange(() => {
if (this.phase === "connected" && this.communicator) {
void this.requestRender("interval").catch((error) => {
const message = this.formatError(error);
this.appendLog(`media update failed: ${message}`);
});
}
});
this.offNightscout = nightscoutBridge.onStateChange(() => {
if (this.phase === "connected" && this.communicator) {
void this.requestRender("interval").catch((error) => {
const message = this.formatError(error);
this.appendLog(`nightscout update failed: ${message}`);
});
}
});
await mediaControllerBridge.start();
await nightscoutBridge.start();
await communicator.start();
await this.requestRender("initial");
this.dashboardTimer = setInterval(() => {
void this.requestRender("interval").catch((error) => {
const message = this.formatError(error);
this.setStatus(`Dashboard update failed: ${message}`);
this.appendLog(`dashboard update failed: ${message}`);
});
}, DASHBOARD_INTERVAL_MS);
} catch (error) {
const message = this.formatError(error);
this.offState?.();
this.offState = null;
this.offLog?.();
this.offLog = null;
this.offRing?.();
this.offRing = null;
this.offBattery?.();
this.offBattery = null;
this.offEvenAppConflict?.();
this.offEvenAppConflict = null;
this.offMedia?.();
this.offMedia = null;
this.offNightscout?.();
this.offNightscout = null;
await mediaControllerBridge.stop().catch(() => {});
await nightscoutBridge.stop().catch(() => {});
if (communicator) {
await communicator.close().catch(() => {});
}
this.communicator = null;
this.clearDashboardTimer();
stopForegroundNotification();
this.setPhase("disconnected");
this.setStatus(`Failed: ${message}`);
this.appendLog(`error: ${message}`);
throw error;
}
}
async disconnect(): Promise<void> {
if (this.phase === "disconnected" || this.phase === "disconnecting") return;
this.setPhase("disconnecting");
this.setStatus("Disconnecting...");
this.clearDashboardTimer();
this.offState?.();
this.offState = null;
this.offLog?.();
this.offLog = null;
this.offRing?.();
this.offRing = null;
this.offBattery?.();
this.offBattery = null;
this.offEvenAppConflict?.();
this.offEvenAppConflict = null;
this.offMedia?.();
this.offMedia = null;
this.offNightscout?.();
this.offNightscout = null;
const communicator = this.communicator;
this.communicator = null;
try {
const shutdownAcked = await communicator?.sendShutdown(0).catch((error) => {
this.appendLog(`shutdown command failed: ${this.formatError(error)}`);
return false;
});
if (shutdownAcked === true) {
this.appendLog("Shutdown command completed.");
} else if (communicator) {
this.appendLog("Shutdown command did not complete before disconnect.");
}
await mediaControllerBridge.stop().catch(() => {});
await nightscoutBridge.stop().catch(() => {});
await communicator?.close().catch(() => {});
} finally {
stopForegroundNotification();
this.setPhase("disconnected");
this.setStatus("Disconnected.");
this.appendLog("Disconnected from the glasses.");
}
}
async injectSyntheticRingInput(kind: "click" | "double-click" | "scroll-up" | "scroll-down"): Promise<void> {
const event = this.buildSyntheticRingInput(kind);
await this.handleInputEvent(event);
}
private startSystemNameEdit(): void {
this.editingSystemCardName = true;
this.activeTextSettingEditorKind = "dashboard-name";
this.emit();
}
private startNightscoutSiteUrlEdit(): void {
this.editingSystemCardName = false;
this.activeTextSettingEditorKind = "nightscout-site-url";
this.emit();
}
private startNightscoutApiTokenEdit(): void {
this.editingSystemCardName = false;
this.activeTextSettingEditorKind = "nightscout-api-token";
this.emit();
}
private endTextSettingEdit(): void {
const finishedKind = this.activeTextSettingEditorKind;
this.editingSystemCardName = false;
this.activeTextSettingEditorKind = null;
this.emit();
if (finishedKind === "nightscout-site-url" || finishedKind === "nightscout-api-token") {
void this.refreshNightscoutAfterSettingsChange();
}
}
private getActiveTextSettingTitle(): string {
switch (this.activeTextSettingEditorKind) {
case "dashboard-name":
return "Dashboard name";
case "nightscout-site-url":
return "Nightscout site URL";
case "nightscout-api-token":
return "Nightscout API token";
default:
return "";
}
}
private getActiveTextSettingValue(): string {
const nightscoutSettings = getDashboardNightscoutSettings();
switch (this.activeTextSettingEditorKind) {
case "dashboard-name":
return getDashboardSystemCardName();
case "nightscout-site-url":
return nightscoutSettings.siteUrl;
case "nightscout-api-token":
return nightscoutSettings.apiToken;
default:
return "";
}
}
private async refreshNightscoutAfterSettingsChange(): Promise<void> {
await nightscoutBridge.refreshNow().catch((error) => {
this.appendLog(`nightscout settings refresh failed: ${this.formatError(error)}`);
});
if (this.phase === "connected" && this.communicator) {
await this.requestRender("interval").catch((error) => {
this.appendLog(`nightscout settings render failed: ${this.formatError(error)}`);
});
} else {
const image = drawDashboard();
this.setDisplayPreview(grayImageToPreviewSource(image));
}
}
private previewOrRenderAfterTextSettingChange(label: string): void {
if (this.phase === "connected" && this.communicator) {
void this.requestRender("interval").catch((error) => {
this.appendLog(`${label} update failed: ${this.formatError(error)}`);
});
return;
}
const image = drawDashboard();
this.setDisplayPreview(grayImageToPreviewSource(image));
}
private async requestRender(reason: "initial" | "interval"): Promise<void> {
this.queuedRenderReason = this.queuedRenderReason === "initial" ? "initial" : reason;
if (this.renderInProgress) {
this.renderQueued = true;
return;
}
this.renderInProgress = true;
try {
do {
const nextReason = this.queuedRenderReason;
this.renderQueued = false;
this.queuedRenderReason = "interval";
await this.renderDashboard(nextReason);
} while (this.renderQueued);
} finally {
this.renderInProgress = false;
}
}
private async renderDashboard(reason: "initial" | "interval"): Promise<void> {
const now = new Date();
const image = drawDashboard();
this.setDisplayPreview(grayImageToPreviewSource(image));
if (!this.communicator) return;
const fingerprint = image.fingerprint();
const tiles = image.toEvenHubTiles().map((tile) => tile.bmp);
await this.communicator.submitDashboardImage(tiles, fingerprint);
const renderedAt = formatForStatus(now);
if (this.phase === "connected") {
this.setStatus(`Connected. Dashboard queued at ${renderedAt}.`);
updateForegroundNotification(`Connected`);
}
this.appendLog(`${reason === "initial" ? "initial" : "scheduled"} dashboard image queued`);
}
private async handleInputEvent(event: RawInputEvent): Promise<void> {
await receiveInput(event);
if (event.kind === "sys-event") {
this.lastSys = `${sourceName(event.eventSource)}/${eventName(event.eventType)}`;
this.appendLog(`sys-event ${this.lastSys}`);
if (
event.eventType === OsEventTypeList.FOREGROUND_EXIT_EVENT ||
event.eventType === OsEventTypeList.ABNORMAL_EXIT_EVENT ||
event.eventType === OsEventTypeList.SYSTEM_EXIT_EVENT
) {
this.appendLog("display state invalidated by firmware exit event");
}
if (event.eventSource === EventSourceType.TOUCH_EVENT_FROM_RING) {
this.lastInput = eventName(event.eventType);
}
await this.requestRender("interval");
return;
}
if (event.kind === "text-click" && isDashboardContainerName(event.containerName)) {
if (
event.eventType === OsEventTypeList.SCROLL_TOP_EVENT ||
event.eventType === OsEventTypeList.SCROLL_BOTTOM_EVENT
) {
this.lastSys = `TEXT/${eventName(event.eventType)}`;
this.lastInput = `TEXT_${eventName(event.eventType)}`;
this.appendLog(`text-event ${this.lastSys}`);
await this.requestRender("interval");
}
}
}
private clearDashboardTimer(): void {
if (!this.dashboardTimer) return;
clearInterval(this.dashboardTimer);
this.dashboardTimer = null;
}
private setPhase(phase: ConnectionPhase): void {
if (this.phase === phase) return;
this.phase = phase;
this.emit();
}
private setStatus(status: string): void {
if (this.status === status) return;
this.status = status;
this.emit();
}
private appendLog(line: string): void {
const stamped = `[${formatTimestamp(new Date())}] ${line}`;
this.log = this.log ? `${this.log}\n${stamped}` : stamped;
console.log(stamped);
this.emit();
}
private setDisplayPreview(preview: ImageSource | null): void {
if (this.displayPreview === preview) return;
this.displayPreview = preview;
this.emit();
}
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)}...`;
}
private buildSyntheticRingInput(kind: "click" | "double-click" | "scroll-up" | "scroll-down"): RawInputEvent {
switch (kind) {
case "click":
return {
kind: "sys-event",
containerName: CONTAINER_NAME,
eventType: OsEventTypeList.CLICK_EVENT,
eventSource: EventSourceType.TOUCH_EVENT_FROM_RING,
systemExitReasonCode: 0,
};
case "double-click":
return {
kind: "sys-event",
containerName: CONTAINER_NAME,
eventType: OsEventTypeList.DOUBLE_CLICK_EVENT,
eventSource: EventSourceType.TOUCH_EVENT_FROM_RING,
systemExitReasonCode: 0,
};
case "scroll-up":
return {
kind: "text-click",
containerName: CONTAINER_NAME,
eventType: OsEventTypeList.SCROLL_TOP_EVENT,
eventSource: EventSourceType.TOUCH_EVENT_FROM_RING,
systemExitReasonCode: 0,
};
case "scroll-down":
default:
return {
kind: "text-click",
containerName: CONTAINER_NAME,
eventType: OsEventTypeList.SCROLL_BOTTOM_EVENT,
eventSource: EventSourceType.TOUCH_EVENT_FROM_RING,
systemExitReasonCode: 0,
};
}
}
private emit(): void {
const snapshot = this.snapshot();
for (const listener of this.listeners) {
listener(snapshot);
}
}
}
export const dashboardController = new DashboardController();
+52
View File
@@ -0,0 +1,52 @@
import { ApplicationSettings } from "@nativescript/core";
export type DeviceAddresses = {
right: string;
left: string;
ring: string;
};
const ADDRESS_KEYS = {
right: "deviceAddress.right",
left: "deviceAddress.left",
ring: "deviceAddress.ring",
} as const;
const DEFAULT_DEVICE_ADDRESSES: DeviceAddresses = {
right: "",
left: "",
ring: "",
};
export function loadDeviceAddresses(): DeviceAddresses {
return {
right: normalizeMacAddress(ApplicationSettings.getString(ADDRESS_KEYS.right, DEFAULT_DEVICE_ADDRESSES.right)),
left: normalizeMacAddress(ApplicationSettings.getString(ADDRESS_KEYS.left, DEFAULT_DEVICE_ADDRESSES.left)),
ring: normalizeMacAddress(ApplicationSettings.getString(ADDRESS_KEYS.ring, DEFAULT_DEVICE_ADDRESSES.ring)),
};
}
export function saveDeviceAddresses(addresses: DeviceAddresses): void {
ApplicationSettings.setString(ADDRESS_KEYS.right, normalizeMacAddress(addresses.right));
ApplicationSettings.setString(ADDRESS_KEYS.left, normalizeMacAddress(addresses.left));
ApplicationSettings.setString(ADDRESS_KEYS.ring, normalizeMacAddress(addresses.ring));
}
export function normalizeMacAddress(value: string | null | undefined): string {
const compact = (value ?? "")
.trim()
.replace(/[^0-9a-fA-F]/g, "")
.toUpperCase();
if (compact.length !== 12) {
return (value ?? "").trim().toUpperCase();
}
return compact.match(/.{1,2}/g)?.join(":") ?? compact;
}
export function isValidMacAddress(value: string, allowEmpty = false): boolean {
const trimmed = value.trim();
if (!trimmed) {
return allowEmpty;
}
return /^[0-9A-F]{2}(?::[0-9A-F]{2}){5}$/.test(normalizeMacAddress(trimmed));
}
+155
View File
@@ -0,0 +1,155 @@
import { knownFolders } from "@nativescript/core";
export type Glyph = {
encoding: number;
dwidthX: number;
bbxWidth: number;
bbxHeight: number;
bbxX: number;
bbxY: number;
bitmapRows: number[];
};
export class BdfFont {
readonly ascent: number;
readonly descent: number;
readonly lineHeight: number;
readonly defaultChar: number;
private readonly glyphs: Map<number, Glyph>;
constructor(opts: {
ascent: number;
descent: number;
defaultChar: number;
glyphs: Map<number, Glyph>;
}) {
this.ascent = opts.ascent;
this.descent = opts.descent;
this.lineHeight = opts.ascent + opts.descent;
this.defaultChar = opts.defaultChar;
this.glyphs = opts.glyphs;
}
static parse(source: string): BdfFont {
const lines = source.replace(/\r/g, "").split("\n");
let ascent = 10;
let descent = 2;
let defaultChar = 63;
const glyphs = new Map<number, Glyph>();
for (let i = 0; i < lines.length; i++) {
const line = lines[i]!;
if (line.startsWith("FONT_ASCENT ")) {
ascent = parseInt(line.slice("FONT_ASCENT ".length), 10);
continue;
}
if (line.startsWith("FONT_DESCENT ")) {
descent = parseInt(line.slice("FONT_DESCENT ".length), 10);
continue;
}
if (line.startsWith("DEFAULT_CHAR ")) {
defaultChar = parseInt(line.slice("DEFAULT_CHAR ".length), 10);
continue;
}
if (!line.startsWith("STARTCHAR ")) {
continue;
}
let encoding = -1;
let dwidthX = 0;
let bbxWidth = 0;
let bbxHeight = 0;
let bbxX = 0;
let bbxY = 0;
const bitmapRows: number[] = [];
for (i = i + 1; i < lines.length; i++) {
const inner = lines[i]!;
if (inner.startsWith("ENCODING ")) {
encoding = parseInt(inner.slice("ENCODING ".length), 10);
continue;
}
if (inner.startsWith("DWIDTH ")) {
dwidthX = parseInt(inner.slice("DWIDTH ".length).split(/\s+/)[0]!, 10);
continue;
}
if (inner.startsWith("BBX ")) {
const [w, h, x, y] = inner
.slice("BBX ".length)
.split(/\s+/)
.map((value) => parseInt(value, 10));
bbxWidth = w!;
bbxHeight = h!;
bbxX = x!;
bbxY = y!;
continue;
}
if (inner === "BITMAP") {
for (let row = 0; row < bbxHeight && i + 1 < lines.length; row++) {
const bitmapLine = lines[++i]!;
bitmapRows.push(parseInt(bitmapLine || "0", 16) || 0);
}
continue;
}
if (inner === "ENDCHAR") {
if (encoding >= 0) {
glyphs.set(encoding, {
encoding,
dwidthX: dwidthX || bbxWidth,
bbxWidth,
bbxHeight,
bbxX,
bbxY,
bitmapRows,
});
}
break;
}
}
}
return new BdfFont({ ascent, descent, defaultChar, glyphs });
}
getGlyph(codePoint: number): Glyph | undefined {
return this.glyphs.get(codePoint) ?? this.glyphs.get(this.defaultChar) ?? this.glyphs.get(63);
}
hasGlyph(codePoint: number): boolean {
return this.glyphs.has(codePoint);
}
measureText(text: string): number {
let width = 0;
for (const char of text) {
width += this.getGlyph(char.codePointAt(0) ?? 32)?.dwidthX ?? 0;
}
return width;
}
}
const cachedEmbeddedFonts = new Map<string, BdfFont>();
export function loadEmbeddedTerminus12(): BdfFont {
return loadEmbeddedFont("fonts/terminus/ter-u12n.bdf");
}
export function loadEmbeddedTerminus16(): BdfFont {
return loadEmbeddedFont("fonts/terminus/ter-u16n.bdf");
}
export function loadEmbeddedTerminus24(): BdfFont {
return loadEmbeddedFont("fonts/terminus/ter-u24n.bdf");
}
function loadEmbeddedFont(path: string): BdfFont {
const cached = cachedEmbeddedFonts.get(path);
if (cached) {
return cached;
}
const file = knownFolders.currentApp().getFile(path);
const text = file.readTextSync();
const font = BdfFont.parse(text);
cachedEmbeddedFonts.set(path, font);
return font;
}
+354
View File
@@ -0,0 +1,354 @@
import { BdfFont, Glyph } from "./bdffont";
export const G2_LENS_WIDTH = 576;
export const G2_LENS_HEIGHT = 288;
export const G2_TILE_WIDTH = 288;
export const G2_TILE_HEIGHT = 144;
const DEFAULT_CORNER_RADIUS = 8;
export type ImageTile = {
x: number;
y: number;
width: number;
height: number;
bmp: Uint8Array;
};
export function imageFromAsciiArt(lines: readonly string[], value = 255): GrayImage {
const width = Math.max(0, ...lines.map((line) => line.length));
const image = new GrayImage(width, lines.length, 0);
const fill = clampByte(value);
for (let y = 0; y < lines.length; y++) {
const line = lines[y]!;
for (let x = 0; x < line.length; x++) {
const pixel = line[x];
if (pixel && pixel !== " " && pixel !== ".") {
image.pixels[y * width + x] = fill;
}
}
}
return image;
}
export class GrayImage {
readonly width: number;
readonly height: number;
readonly pixels: Uint8Array;
constructor(width: number, height: number, fill = 0) {
this.width = width;
this.height = height;
this.pixels = new Uint8Array(width * height);
this.clear(fill);
}
clear(value = 0): void {
this.pixels.fill(clampByte(value));
}
setPixel(x: number, y: number, value: number): void {
this.setPixelUnchecked(x, y, clampByte(value));
}
private setPixelUnchecked(x: number, y: number, value: number): void {
if (x < 0 || y < 0 || x >= this.width || y >= this.height) return;
this.pixels[y * this.width + x] = value;
}
getPixel(x: number, y: number): number {
if (x < 0 || y < 0 || x >= this.width || y >= this.height) return 0;
return this.pixels[y * this.width + x] ?? 0;
}
fillRect(x: number, y: number, width: number, height: number, value: number): void {
const left = Math.max(0, x | 0);
const top = Math.max(0, y | 0);
const right = Math.min(this.width, (x + width) | 0);
const bottom = Math.min(this.height, (y + height) | 0);
const fill = clampByte(value);
for (let row = top; row < bottom; row++) {
const offset = row * this.width;
for (let col = left; col < right; col++) {
this.pixels[offset + col] = fill;
}
}
}
drawRect(x: number, y: number, width: number, height: number, value: number): void {
this.drawLine(x, y, x + width - 1, y, value);
this.drawLine(x, y, x, y + height - 1, value);
this.drawLine(x + width - 1, y, x + width - 1, y + height - 1, value);
this.drawLine(x, y + height - 1, x + width - 1, y + height - 1, value);
}
drawLine(x0: number, y0: number, x1: number, y1: number, value: number): void {
let ax = Math.round(x0);
let ay = Math.round(y0);
const bx = Math.round(x1);
const by = Math.round(y1);
const stroke = clampByte(value);
const dx = Math.abs(bx - ax);
const sx = ax < bx ? 1 : -1;
const dy = -Math.abs(by - ay);
const sy = ay < by ? 1 : -1;
let err = dx + dy;
while (true) {
this.setPixelUnchecked(ax, ay, stroke);
if (ax === bx && ay === by) break;
const e2 = 2 * err;
if (e2 >= dy) {
err += dy;
ax += sx;
}
if (e2 <= dx) {
err += dx;
ay += sy;
}
}
}
drawText(font: BdfFont, x: number, y: number, text: string, value: number): void {
let cursorX = x;
const fill = clampByte(value);
for (const char of text) {
if (char === "\n") {
cursorX = x;
y += font.lineHeight;
continue;
}
const glyph = font.getGlyph(char.codePointAt(0) ?? 32);
if (!glyph) continue;
this.drawGlyph(font, glyph, cursorX, y, fill);
cursorX += glyph.dwidthX;
}
}
bitBlt(
source: GrayImage,
dx: number,
dy: number,
opts: { sx?: number; sy?: number; width?: number; height?: number } = {},
): void {
const srcX = Math.max(0, (opts.sx ?? 0) | 0);
const srcY = Math.max(0, (opts.sy ?? 0) | 0);
const copyWidth = Math.max(0, (opts.width ?? (source.width - srcX)) | 0);
const copyHeight = Math.max(0, (opts.height ?? (source.height - srcY)) | 0);
const destX = dx | 0;
const destY = dy | 0;
for (let row = 0; row < copyHeight; row++) {
const sy = srcY + row;
const ty = destY + row;
if (sy < 0 || sy >= source.height || ty < 0 || ty >= this.height) continue;
for (let col = 0; col < copyWidth; col++) {
const sx = srcX + col;
const tx = destX + col;
if (sx < 0 || sx >= source.width || tx < 0 || tx >= this.width) continue;
this.pixels[ty * this.width + tx] = source.pixels[sy * source.width + sx] ?? 0;
}
}
}
fillRoundedRect(
x: number,
y: number,
width: number,
height: number,
value: number,
radius = DEFAULT_CORNER_RADIUS,
): void {
const left = x | 0;
const top = y | 0;
const rectWidth = width | 0;
const rectHeight = height | 0;
const bottom = top + rectHeight;
const fill = clampByte(value);
for (let row = top; row < bottom; row++) {
if (row < 0 || row >= this.height) continue;
const span = roundedRectRowSpan(row, left, top, rectWidth, rectHeight, radius);
if (!span) continue;
const start = Math.max(0, span.left);
const end = Math.min(this.width, span.right);
const offset = row * this.width;
for (let col = start; col < end; col++) {
this.pixels[offset + col] = fill;
}
}
}
drawRoundedRect(
x: number,
y: number,
width: number,
height: number,
value: number,
radius = DEFAULT_CORNER_RADIUS,
): void {
const left = x | 0;
const top = y | 0;
const rectWidth = width | 0;
const rectHeight = height | 0;
const bottom = top + rectHeight;
const stroke = clampByte(value);
const innerLeft = left + 1;
const innerTop = top + 1;
const innerWidth = rectWidth - 2;
const innerHeight = rectHeight - 2;
for (let row = top; row < bottom; row++) {
if (row < 0 || row >= this.height) continue;
const outer = roundedRectRowSpan(row, left, top, rectWidth, rectHeight, radius);
if (!outer) continue;
const inner =
innerWidth > 0 && innerHeight > 0
? roundedRectRowSpan(row, innerLeft, innerTop, innerWidth, innerHeight, Math.max(0, radius - 1))
: undefined;
const offset = row * this.width;
const outerLeft = Math.max(0, outer.left);
const outerRight = Math.min(this.width, outer.right);
if (!inner) {
for (let col = outerLeft; col < outerRight; col++) {
this.pixels[offset + col] = stroke;
}
continue;
}
const innerLeftClamped = Math.max(outerLeft, Math.min(outerRight, inner.left));
const innerRightClamped = Math.max(outerLeft, Math.min(outerRight, inner.right));
for (let col = outerLeft; col < innerLeftClamped; col++) {
this.pixels[offset + col] = stroke;
}
for (let col = innerRightClamped; col < outerRight; col++) {
this.pixels[offset + col] = stroke;
}
}
}
fingerprint(): string {
let hash = 2166136261;
for (let i = 0; i < this.pixels.length; i++) {
hash ^= this.pixels[i]!;
hash = Math.imul(hash, 16777619);
}
return `fnv:${(hash >>> 0).toString(16)}`;
}
toEvenHubTiles(): ImageTile[] {
const tiles: ImageTile[] = [];
for (let ty = 0; ty < this.height; ty += G2_TILE_HEIGHT) {
for (let tx = 0; tx < this.width; tx += G2_TILE_WIDTH) {
const width = Math.min(G2_TILE_WIDTH, this.width - tx);
const height = Math.min(G2_TILE_HEIGHT, this.height - ty);
tiles.push({
x: tx,
y: ty,
width,
height,
bmp: buildEvenHubBmp(width, height, (x, y) => this.getPixel(tx + x, ty + y) >> 4),
});
}
}
return tiles;
}
private drawGlyph(font: BdfFont, glyph: Glyph, x: number, y: number, value: number): void {
const baselineY = y + font.ascent;
const top = baselineY - (glyph.bbxHeight + glyph.bbxY);
const left = x + glyph.bbxX;
const rowBitWidth = ((glyph.bbxWidth + 7) >> 3) << 3;
for (let row = 0; row < glyph.bbxHeight; row++) {
const bits = glyph.bitmapRows[row] ?? 0;
for (let col = 0; col < glyph.bbxWidth; col++) {
const shift = rowBitWidth - 1 - col;
if (((bits >> shift) & 1) !== 0) {
this.setPixelUnchecked(left + col, top + row, value);
}
}
}
}
}
function buildEvenHubBmp(
width: number,
height: number,
pixel: (x: number, y: number) => number,
): Uint8Array {
const bytesPerPixelRow = (width + 1) >> 1;
const rowStride = (bytesPerPixelRow + 3) & ~3;
const pixelDataSize = rowStride * height;
const fileHeaderSize = 14;
const dibHeaderSize = 40;
const paletteSize = 16 * 4;
const pixelOffset = fileHeaderSize + dibHeaderSize + paletteSize;
const fileSize = pixelOffset + pixelDataSize;
const buf = new Uint8Array(fileSize);
const view = new DataView(buf.buffer);
buf[0] = 0x42;
buf[1] = 0x4d;
view.setUint32(2, fileSize, true);
view.setUint32(10, pixelOffset, true);
view.setUint32(14, dibHeaderSize, true);
view.setInt32(18, width, true);
view.setInt32(22, height, true);
view.setUint16(26, 1, true);
view.setUint16(28, 4, true);
view.setUint32(30, 0, true);
view.setUint32(34, pixelDataSize, true);
view.setUint32(46, 16, true);
for (let i = 0; i < 16; i++) {
const v = i * 17;
const base = fileHeaderSize + dibHeaderSize + i * 4;
buf[base + 0] = v;
buf[base + 1] = v;
buf[base + 2] = v;
buf[base + 3] = 0;
}
for (let bmpRow = 0; bmpRow < height; bmpRow++) {
const srcY = height - 1 - bmpRow;
const rowOffset = pixelOffset + bmpRow * rowStride;
for (let x = 0; x < width; x += 2) {
const hi = pixel(x, srcY) & 0x0f;
const lo = (x + 1 < width ? pixel(x + 1, srcY) : 0) & 0x0f;
buf[rowOffset + (x >> 1)] = (hi << 4) | lo;
}
}
return buf;
}
function clampByte(value: number): number {
return Math.max(0, Math.min(255, Math.round(value)));
}
function roundedRectRowSpan(
row: number,
x: number,
y: number,
width: number,
height: number,
radius: number,
): { left: number; right: number } | undefined {
if (width <= 0 || height <= 0 || row < y || row >= y + height) return undefined;
const r = Math.max(0, Math.min(radius | 0, (width / 2) | 0, (height / 2) | 0));
if (r === 0) return { left: x, right: x + width };
const cy = row + 0.5;
const topCornerBottom = y + r;
const bottomCornerTop = y + height - r;
if (cy >= topCornerBottom && cy < bottomCornerTop) {
return { left: x, right: x + width };
}
const cornerY = cy < topCornerBottom ? topCornerBottom : bottomCornerTop;
const dy = cy - cornerY;
const dxSquared = r * r - dy * dy;
if (dxSquared < 0) return undefined;
const inset = (r - Math.sqrt(dxSquared) + 0.5) | 0;
return { left: x + inset, right: x + width - inset };
}
+61
View File
@@ -0,0 +1,61 @@
import { File, knownFolders } from "@nativescript/core";
import { GrayImage } from "./image";
declare const interop: any;
const UPNG = require("upng-js");
export function loadPngAsGrayImage(path: string): GrayImage {
const file = resolveFile(path);
const raw = file.readSync();
const pngBuffer = toArrayBuffer(raw);
const decoded = UPNG.decode(pngBuffer);
const frames = UPNG.toRGBA8(decoded) as ArrayBuffer[];
if (!frames.length) {
throw new Error(`PNG contains no frames: ${path}`);
}
const rgba = new Uint8Array(frames[0]!);
const image = new GrayImage(decoded.width, decoded.height, 0);
for (let y = 0; y < decoded.height; y++) {
for (let x = 0; x < decoded.width; x++) {
const offset = (y * decoded.width + x) * 4;
const r = rgba[offset] ?? 0;
const g = rgba[offset + 1] ?? 0;
const b = rgba[offset + 2] ?? 0;
const a = (rgba[offset + 3] ?? 0) / 255;
const gray = Math.round((0.2126 * r + 0.7152 * g + 0.0722 * b) * a);
image.pixels[y * decoded.width + x] = gray;
}
}
return image;
}
function resolveFile(path: string): File {
if (!path) {
throw new Error("PNG path is required");
}
return path.startsWith("/") ? File.fromPath(path) : knownFolders.currentApp().getFile(path);
}
function toArrayBuffer(raw: unknown): ArrayBuffer {
if (raw instanceof ArrayBuffer) {
return raw.slice(0);
}
if (raw instanceof Uint8Array) {
return raw.buffer.slice(raw.byteOffset, raw.byteOffset + raw.byteLength) as ArrayBuffer;
}
if (global.isAndroid && raw && typeof (raw as { length?: unknown }).length === "number") {
const bytes = raw as ArrayLike<number>;
const out = new Uint8Array(bytes.length);
for (let i = 0; i < bytes.length; i++) {
out[i] = bytes[i]! & 0xff;
}
return out.buffer;
}
if (global.isIOS && raw) {
return interop.bufferFromData(raw);
}
throw new Error(`Unsupported PNG byte source: ${String(raw)}`);
}
+139
View File
@@ -0,0 +1,139 @@
import { BdfFont } from "./bdffont";
export function findWrapOpportunities(text: string): number[] {
const offsets: number[] = [];
for (let i = 0; i < text.length; ) {
const codePoint = text.codePointAt(i) ?? 0;
const char = String.fromCodePoint(codePoint);
const next = i + char.length;
if (isWhitespace(char)) {
let end = next;
while (end < text.length) {
const innerCodePoint = text.codePointAt(end) ?? 0;
const innerChar = String.fromCodePoint(innerCodePoint);
if (!isWhitespace(innerChar) || innerChar === "\n") break;
end += innerChar.length;
}
offsets.push(end);
i = end;
continue;
}
if (isBreakAfter(char)) {
offsets.push(next);
}
i = next;
}
return offsets;
}
export function wrapText(font: BdfFont, text: string, targetWidth: number): string[] {
if (targetWidth <= 0) {
return text.length ? text.split("\n") : [""];
}
const paragraphs = text.replace(/\r/g, "").split("\n");
const lines: string[] = [];
for (const paragraph of paragraphs) {
lines.push(...wrapParagraph(font, paragraph, targetWidth));
}
return lines.length ? lines : [""];
}
function wrapParagraph(font: BdfFont, paragraph: string, targetWidth: number): string[] {
if (paragraph.length === 0) {
return [""];
}
const widths = measureOffsets(font, paragraph);
const wrapOffsets = findWrapOpportunities(paragraph);
const lines: string[] = [];
let start = skipLeadingWhitespace(paragraph, 0);
while (start < paragraph.length) {
let best = -1;
for (const candidate of wrapOffsets) {
if (candidate <= start) continue;
if (measureSpan(widths, candidate) - measureSpan(widths, start) <= targetWidth) {
best = candidate;
continue;
}
break;
}
if (best < 0) {
best = furthestFittingOffset(widths, start, targetWidth);
}
if (best <= start) {
best = nextOffset(widths, start);
}
const line = paragraph.slice(start, best).trimEnd();
lines.push(line);
start = skipLeadingWhitespace(paragraph, best);
}
return lines.length ? lines : [""];
}
function measureOffsets(font: BdfFont, text: string): Map<number, number> {
const widths = new Map<number, number>();
let total = 0;
widths.set(0, 0);
for (let i = 0; i < text.length; ) {
const codePoint = text.codePointAt(i) ?? 32;
const char = String.fromCodePoint(codePoint);
i += char.length;
total += font.getGlyph(codePoint)?.dwidthX ?? 0;
widths.set(i, total);
}
return widths;
}
function furthestFittingOffset(widths: Map<number, number>, start: number, targetWidth: number): number {
const startWidth = measureSpan(widths, start);
let best = start;
for (const offset of widths.keys()) {
if (offset <= start) continue;
if (measureSpan(widths, offset) - startWidth <= targetWidth) {
best = offset;
continue;
}
break;
}
return best;
}
function nextOffset(widths: Map<number, number>, start: number): number {
for (const offset of widths.keys()) {
if (offset > start) return offset;
}
return start;
}
function measureSpan(widths: Map<number, number>, offset: number): number {
return widths.get(offset) ?? 0;
}
function skipLeadingWhitespace(text: string, offset: number): number {
let cursor = offset;
while (cursor < text.length) {
const codePoint = text.codePointAt(cursor) ?? 0;
const char = String.fromCodePoint(codePoint);
if (!isWhitespace(char) || char === "\n") {
break;
}
cursor += char.length;
}
return cursor;
}
function isWhitespace(char: string): boolean {
return /\s/.test(char);
}
function isBreakAfter(char: string): boolean {
return char === "-" || char === "/" || char === "," || char === ";" || char === ":";
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 7.6 KiB

+14
View File
@@ -0,0 +1,14 @@
import { EventData, Frame, Page } from "@nativescript/core";
import { hasCompletedOnboarding } from "./onboarding-state";
export function navigatingTo(args: EventData): void {
const page = args.object as Page;
page.on(Page.loadedEvent, () => {
Frame.topmost()?.navigate({
moduleName: hasCompletedOnboarding() ? "main-page" : "onboarding-page",
clearHistory: true,
animated: false,
});
});
}
+3
View File
@@ -0,0 +1,3 @@
<Page xmlns="http://schemas.nativescript.org/tns.xsd" navigatingTo="navigatingTo" actionBarHidden="true">
<GridLayout />
</Page>
+104
View File
@@ -0,0 +1,104 @@
import { EventData, Observable, Page, ScrollView, TextField } from '@nativescript/core'
import { MainViewModel } from './main-view-model'
import { dashboardController } from './g2/dashboard-controller'
export function navigatingTo(args: EventData) {
const page = <Page>args.object
page.bindingContext = new MainViewModel()
}
type MainPageState = {
isPinnedToBottom: boolean
scrollHandler: () => void
propertyChangeHandler: (args: EventData & { propertyName?: string }) => void
}
function getPageState(page: Page): MainPageState | undefined {
return (page as Page & { __mainPageState?: MainPageState }).__mainPageState
}
function setPageState(page: Page, state?: MainPageState): void {
;(page as Page & { __mainPageState?: MainPageState }).__mainPageState = state
}
function cleanupPage(page: Page): void {
const state = getPageState(page)
const model = page.bindingContext as MainViewModel | null
const scrollView = page.getViewById<ScrollView>('logScrollView')
if (!state || !model || !scrollView) {
setPageState(page, undefined)
return
}
scrollView.off(ScrollView.scrollEvent, state.scrollHandler)
model.off(Observable.propertyChangeEvent, state.propertyChangeHandler)
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 focusSystemNameField(page: Page): void {
setTimeout(() => {
const textField = page.getViewById<TextField>('settingsTextField')
textField?.focus()
}, 0)
}
export function loaded(args: EventData) {
const page = args.object as Page
cleanupPage(page)
dashboardController.refreshEvenAppStatus()
const model = page.bindingContext as MainViewModel | null
const scrollView = page.getViewById<ScrollView>('logScrollView')
if (!model || !scrollView) {
return
}
const state: MainPageState = {
isPinnedToBottom: true,
scrollHandler: () => {
state.isPinnedToBottom = isAtBottom(scrollView)
},
propertyChangeHandler: (propertyArgs) => {
if (propertyArgs.propertyName === 'showLog') {
if (model.showLog) {
state.isPinnedToBottom = true
scrollToBottom(scrollView)
}
return
}
if (propertyArgs.propertyName === 'activeTextSettingEditorKind') {
if (model.isTextSettingEditorActive) {
focusSystemNameField(page)
}
return
}
if (propertyArgs.propertyName !== 'log') {
return
}
if (state.isPinnedToBottom) {
scrollToBottom(scrollView)
}
},
}
scrollView.on(ScrollView.scrollEvent, state.scrollHandler)
model.on(Observable.propertyChangeEvent, state.propertyChangeHandler)
setPageState(page, state)
scrollToBottom(scrollView)
if (model.isTextSettingEditorActive) {
focusSystemNameField(page)
}
}
export function unloaded(args: EventData) {
cleanupPage(args.object as Page)
}
+46
View File
@@ -0,0 +1,46 @@
<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" />
<ActionItem text="Configure devices" tap="{{ onConfigureTap }}" isEnabled="{{ canRun }}" android.position="popup" />
<ActionItem text="{{ showLogMenuLabel }}" tap="{{ onToggleLogTap }}" android.position="popup" />
</ActionBar>
<GridLayout rows="auto,*">
<StackLayout row="0" visibility="{{ displayPreviewVisibility }}">
<Image src="{{ displayPreview }}" stretch="fill" height="{{ displayPreviewHeight }}" />
</StackLayout>
<GridLayout row="1" rows="auto,auto,auto,*" class="p-20">
<StackLayout row="0" class="m-b-8" visibility="{{ evenAppConflictWarningVisibility }}">
<Label text="{{ evenAppConflictMessage }}" textWrap="true" />
<Button text="Open Even app settings" tap="{{ onOpenEvenAppSettingsTap }}" class="-primary" />
</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="2" text="Click" tap="{{ onSyntheticRightTap }}" />
<Button row="2" col="1" text="Swipe down" tap="{{ onSyntheticDownTap }}" />
</GridLayout>
</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>
</GridLayout>
<StackLayout
row="0"
class="system-name-modal"
visibility="{{ textSettingEditorVisibility }}"
horizontalAlignment="stretch"
verticalAlignment="top">
<Label text="{{ activeTextSettingTitle }}" />
<TextField
id="settingsTextField"
text="{{ activeTextSettingValue }}"
textChange="{{ onTextSettingTextChange }}"
autocorrect="false"
autocapitalizationType="words"
returnKeyType="done" />
</StackLayout>
</GridLayout>
</Page>
+296
View File
@@ -0,0 +1,296 @@
import { Frame, ImageSource, Observable, Screen } from "@nativescript/core";
import { dashboardController, type TextSettingEditorKind } from "./g2/dashboard-controller";
export class MainViewModel extends Observable {
private _status = "Disconnected.";
private _log = "";
private _displayPreview: ImageSource | null = null;
private _systemCardName = "Faceclaw";
private _editingSystemCardName = false;
private _activeTextSettingEditorKind: TextSettingEditorKind | null = null;
private _activeTextSettingTitle = "";
private _activeTextSettingValue = "";
private _evenAppConflictMessage = "";
private _evenAppConflictWarningVisible = false;
private _showLog = false;
private _phase: "disconnected" | "connecting" | "connected" | "disconnecting" = "disconnected";
constructor() {
super();
dashboardController.subscribe((snapshot) => {
this.status = snapshot.status;
this.log = snapshot.log;
this.displayPreview = snapshot.displayPreview;
this.phase = snapshot.phase;
this.systemCardName = snapshot.systemCardName;
this.editingSystemCardName = snapshot.editingSystemCardName;
this.activeTextSettingEditorKind = snapshot.activeTextSettingEditorKind;
this.activeTextSettingTitle = snapshot.activeTextSettingTitle;
this.activeTextSettingValue = snapshot.activeTextSettingValue;
this.evenAppConflictMessage = snapshot.evenAppConflictMessage;
this.evenAppConflictWarningVisible = snapshot.evenAppConflictWarningVisible;
});
}
get status(): string {
return this._status;
}
set status(value: string) {
if (this._status !== value) {
this._status = value;
this.notifyPropertyChange("status", value);
}
}
get log(): string {
return this._log;
}
set log(value: string) {
if (this._log !== value) {
this._log = value;
this.notifyPropertyChange("log", value);
}
}
get displayPreview(): ImageSource | null {
return this._displayPreview;
}
set displayPreview(value: ImageSource | null) {
if (this._displayPreview !== value) {
this._displayPreview = value;
this.notifyPropertyChange("displayPreview", value);
this.notifyPropertyChange("hasDisplayPreview", this.hasDisplayPreview);
this.notifyPropertyChange("displayPreviewVisibility", this.displayPreviewVisibility);
}
}
get hasDisplayPreview(): boolean {
return this._displayPreview !== null;
}
get displayPreviewVisibility(): "visible" | "collapse" {
return this.hasDisplayPreview ? "visible" : "collapse";
}
get displayPreviewHeight(): number {
return Screen.mainScreen.widthDIPs / 2;
}
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";
}
get systemCardName(): string {
return this._systemCardName;
}
set systemCardName(value: string) {
if (this._systemCardName !== value) {
this._systemCardName = value;
this.notifyPropertyChange("systemCardName", value);
}
}
get editingSystemCardName(): boolean {
return this._editingSystemCardName;
}
set editingSystemCardName(value: boolean) {
if (this._editingSystemCardName !== value) {
this._editingSystemCardName = value;
this.notifyPropertyChange("editingSystemCardName", value);
this.notifyPropertyChange("systemCardNameEditorVisibility", this.systemCardNameEditorVisibility);
}
}
get systemCardNameEditorVisibility(): "visible" | "collapse" {
return this._editingSystemCardName ? "visible" : "collapse";
}
get activeTextSettingEditorKind(): TextSettingEditorKind | null {
return this._activeTextSettingEditorKind;
}
set activeTextSettingEditorKind(value: TextSettingEditorKind | null) {
if (this._activeTextSettingEditorKind !== value) {
this._activeTextSettingEditorKind = value;
this.notifyPropertyChange("activeTextSettingEditorKind", value);
this.notifyPropertyChange("textSettingEditorVisibility", this.textSettingEditorVisibility);
this.notifyPropertyChange("isTextSettingEditorActive", this.isTextSettingEditorActive);
}
}
get activeTextSettingTitle(): string {
return this._activeTextSettingTitle;
}
set activeTextSettingTitle(value: string) {
if (this._activeTextSettingTitle !== value) {
this._activeTextSettingTitle = value;
this.notifyPropertyChange("activeTextSettingTitle", value);
}
}
get activeTextSettingValue(): string {
return this._activeTextSettingValue;
}
set activeTextSettingValue(value: string) {
if (this._activeTextSettingValue !== value) {
this._activeTextSettingValue = value;
this.notifyPropertyChange("activeTextSettingValue", value);
}
}
get isTextSettingEditorActive(): boolean {
return this._activeTextSettingEditorKind !== null;
}
get textSettingEditorVisibility(): "visible" | "collapse" {
return this.isTextSettingEditorActive ? "visible" : "collapse";
}
get evenAppConflictMessage(): string {
return this._evenAppConflictMessage;
}
set evenAppConflictMessage(value: string) {
if (this._evenAppConflictMessage !== value) {
this._evenAppConflictMessage = value;
this.notifyPropertyChange("evenAppConflictMessage", value);
}
}
get evenAppConflictWarningVisible(): boolean {
return this._evenAppConflictWarningVisible;
}
set evenAppConflictWarningVisible(value: boolean) {
if (this._evenAppConflictWarningVisible !== value) {
this._evenAppConflictWarningVisible = value;
this.notifyPropertyChange("evenAppConflictWarningVisible", value);
this.notifyPropertyChange("evenAppConflictWarningVisibility", this.evenAppConflictWarningVisibility);
}
}
get evenAppConflictWarningVisibility(): "visible" | "collapse" {
return this._evenAppConflictWarningVisible ? "visible" : "collapse";
}
get phase(): "disconnected" | "connecting" | "connected" | "disconnecting" {
return this._phase;
}
set phase(value: "disconnected" | "connecting" | "connected" | "disconnecting") {
if (this._phase !== value) {
this._phase = value;
this.notifyPropertyChange("phase", value);
this.notifyPropertyChange("buttonLabel", this.buttonLabel);
this.notifyPropertyChange("canRun", this.canRun);
}
}
get buttonLabel(): string {
switch (this.phase) {
case "connecting":
return "Connecting...";
case "connected":
return "Disconnect";
case "disconnecting":
return "Disconnecting...";
default:
return "Connect";
}
}
get canRun(): boolean {
return this.phase !== "connecting" && this.phase !== "disconnecting";
}
async onTap(): Promise<void> {
if (!this.canRun) return;
try {
if (this.phase === "connected") {
await dashboardController.disconnect();
} else {
await dashboardController.connect();
}
} catch (error) {
const message = this.formatError(error);
if (!this.status.startsWith("Failed:")) {
this.status = `Failed: ${message}`;
this.appendLog(`error: ${message}`);
}
}
}
onConfigureTap(): void {
if (!this.canRun) return;
Frame.topmost()?.navigate("config-page");
}
onToggleLogTap(): void {
this.showLog = !this.showLog;
}
onSystemCardNameTextChange(args: { value?: string; object?: { text?: string } }): void {
dashboardController.setSystemCardName(args.object?.text ?? args.value ?? "");
}
onTextSettingTextChange(args: { value?: string; object?: { text?: string } }): void {
dashboardController.setActiveTextSettingValue(args.object?.text ?? args.value ?? "");
}
onOpenEvenAppSettingsTap(): void {
dashboardController.openEvenAppSettings();
}
async onSyntheticUpTap(): Promise<void> {
await dashboardController.injectSyntheticRingInput("scroll-up");
}
async onSyntheticDownTap(): Promise<void> {
await dashboardController.injectSyntheticRingInput("scroll-down");
}
async onSyntheticLeftTap(): Promise<void> {
await dashboardController.injectSyntheticRingInput("double-click");
}
async onSyntheticRightTap(): Promise<void> {
await dashboardController.injectSyntheticRingInput("click");
}
private appendLog(line: string): void {
const stamp = new Date().toISOString().slice(11, 19);
this.log = this.log ? `${this.log}\n[${stamp}] ${line}` : `[${stamp}] ${line}`;
}
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)}...`;
}
}
+64
View File
@@ -0,0 +1,64 @@
import { Utils } from "@nativescript/core";
declare const com: any;
export type DiscoveredDevice = {
address: string;
name: string;
role: "left" | "right" | "ring";
source: "paired" | "scan";
};
export type DiscoveredAddressSet = {
left: string;
right: string;
ring: string;
summary: string;
};
export class DeviceDiscoveryBridge {
private readonly discovery: any;
constructor() {
const context = Utils.android.getApplicationContext();
if (!context) throw new Error("Android application context unavailable");
this.discovery = new com.faceclaw.app.FaceclawDeviceDiscovery(context);
}
async getBondedCandidates(): Promise<DiscoveredDevice[]> {
return parseCandidates(String(this.discovery.getBondedCandidatesJson()));
}
async scanCandidates(timeoutMs = 6000): Promise<DiscoveredDevice[]> {
return parseCandidates(String(this.discovery.scanCandidatesJson(timeoutMs)));
}
}
export function buildAddressSet(candidates: DiscoveredDevice[]): DiscoveredAddressSet {
const latestForRole = new Map<DiscoveredDevice["role"], DiscoveredDevice>();
for (const candidate of candidates) {
latestForRole.set(candidate.role, candidate);
}
const selected = {
left: latestForRole.get("left")?.address ?? "",
right: latestForRole.get("right")?.address ?? "",
ring: latestForRole.get("ring")?.address ?? "",
};
const lines = candidates.map((candidate) => `${candidate.role}: ${candidate.name} ${candidate.address}`);
return {
...selected,
summary: lines.length ? lines.join("\n") : "No matching devices found.",
};
}
function parseCandidates(json: string): DiscoveredDevice[] {
const raw = JSON.parse(json) as Array<Record<string, unknown>>;
return raw
.map((item) => ({
address: String(item.address ?? ""),
name: String(item.name ?? ""),
role: String(item.role ?? "") as DiscoveredDevice["role"],
source: String(item.source ?? "") as DiscoveredDevice["source"],
}))
.filter((item) => !!item.address && (item.role === "left" || item.role === "right" || item.role === "ring"));
}
+39
View File
@@ -0,0 +1,39 @@
import { Utils } from "@nativescript/core";
declare const com: any;
export type EvenAppNotificationState = {
notificationAccessEnabled: boolean;
evenNotificationActive: boolean;
};
export function readEvenAppNotificationState(): EvenAppNotificationState {
if (!global.isAndroid) {
return { notificationAccessEnabled: false, evenNotificationActive: false };
}
const context = Utils.android.getApplicationContext();
if (!context) {
return { notificationAccessEnabled: false, evenNotificationActive: false };
}
const detector = com.faceclaw.app.FaceclawEvenAppDetector;
return {
notificationAccessEnabled: Boolean(detector.isNotificationAccessEnabled(context)),
evenNotificationActive: Boolean(detector.isEvenNotificationActive(context)),
};
}
export function openEvenAppSettings(): void {
if (!global.isAndroid) return;
const context = Utils.android.getApplicationContext();
if (context) {
com.faceclaw.app.FaceclawEvenAppDetector.openEvenAppSettings(context);
}
}
export function openNotificationAccessSettings(): void {
if (!global.isAndroid) return;
const context = Utils.android.getApplicationContext();
if (context) {
com.faceclaw.app.FaceclawEvenAppDetector.openNotificationAccessSettings(context);
}
}
+177
View File
@@ -0,0 +1,177 @@
import { Utils } from "@nativescript/core";
declare const com: any;
type NotificationListener = (address: string, characteristicUuid: string, data: Uint8Array) => void;
type ConnectionListener = (address: string, connected: boolean) => void;
function toUint8Array(bytes: ArrayLike<number> | null | undefined): Uint8Array {
if (!bytes) return new Uint8Array(0);
const out = new Uint8Array(bytes.length);
for (let i = 0; i < bytes.length; i++) {
out[i] = bytes[i]! & 0xff;
}
return out;
}
function toJavaByteArray(bytes: Uint8Array): number[] {
const out = Array.create("byte", bytes.length) as number[];
for (let i = 0; i < bytes.length; i++) {
const value = bytes[i]!;
out[i] = value > 127 ? value - 256 : value;
}
return out;
}
function toJavaByteList(frames: Uint8Array[]): any {
const list = new java.util.ArrayList();
for (const frame of frames) {
list.add(toJavaByteArray(frame));
}
return list;
}
export class FaceclawBleBridge {
private readonly manager: any;
private readonly notificationListeners = new Set<NotificationListener>();
private readonly connectionListeners = new Set<ConnectionListener>();
private readonly listenerProxy: any;
constructor() {
const context = Utils.android.getApplicationContext();
if (!context) throw new Error("Android application context unavailable");
this.manager = new com.faceclaw.app.FaceclawBleManager(context);
this.listenerProxy = new com.faceclaw.app.FaceclawBleListener({
onNotification: (address: string, characteristicUuid: string, data: ArrayLike<number>) => {
const bytes = toUint8Array(data);
for (const listener of this.notificationListeners) {
listener(String(address), String(characteristicUuid), bytes);
}
},
onConnectionStateChange: (address: string, connected: boolean) => {
for (const listener of this.connectionListeners) {
listener(String(address), Boolean(connected));
}
},
});
this.manager.setListener(this.listenerProxy);
}
onNotification(listener: NotificationListener): () => void {
this.notificationListeners.add(listener);
return () => {
this.notificationListeners.delete(listener);
};
}
onConnectionStateChange(listener: ConnectionListener): () => void {
this.connectionListeners.add(listener);
return () => {
this.connectionListeners.delete(listener);
};
}
async connect(address: string, timeoutMs: number): Promise<void> {
if (!this.manager.connect(address, timeoutMs)) {
throw new Error(`connect failed: ${address}`);
}
}
async requestMtu(address: string, mtu: number, timeoutMs: number): Promise<void> {
if (!this.manager.requestMtu(address, mtu, timeoutMs)) {
throw new Error(`requestMtu failed: ${address}`);
}
}
async requestConnectionPriority(address: string, priority: number): Promise<void> {
if (!this.manager.requestConnectionPriority(address, priority)) {
throw new Error(`requestConnectionPriority failed: ${address} ${priority}`);
}
}
async discoverServices(address: string, timeoutMs: number): Promise<void> {
if (!this.manager.discoverServices(address, timeoutMs)) {
throw new Error(`discoverServices failed: ${address}`);
}
}
async enableNotifications(
address: string,
characteristicUuid: string,
enable: boolean,
timeoutMs: number,
): Promise<void> {
if (!this.manager.enableNotifications(address, characteristicUuid, enable, timeoutMs)) {
throw new Error(`enableNotifications failed: ${address} ${characteristicUuid}`);
}
}
async writeCharacteristic(
address: string,
characteristicUuid: string,
data: Uint8Array,
writeType: number,
timeoutMs: number,
): Promise<void> {
if (!this.manager.write(address, characteristicUuid, toJavaByteArray(data), writeType, timeoutMs)) {
throw new Error(`write failed: ${address} ${characteristicUuid}`);
}
}
async writeCharacteristicFrames(
address: string,
characteristicUuid: string,
frames: Uint8Array[],
writeType: number,
timeoutMs: number,
allowFallback: boolean,
interFrameDelayMs: number,
): Promise<void> {
if (
!this.manager.writeFrames(
address,
characteristicUuid,
toJavaByteList(frames),
writeType,
timeoutMs,
allowFallback,
interFrameDelayMs,
)
) {
throw new Error(`write frames failed: ${address} ${characteristicUuid}`);
}
}
async queueCharacteristicFrames(
address: string,
characteristicUuid: string,
frames: Uint8Array[],
writeType: number,
timeoutMs: number,
allowFallback: boolean,
interFrameDelayMs: number,
): Promise<void> {
if (
!this.manager.queueWriteFrames(
address,
characteristicUuid,
toJavaByteList(frames),
writeType,
timeoutMs,
allowFallback,
interFrameDelayMs,
)
) {
throw new Error(`queue write frames failed: ${address} ${characteristicUuid}`);
}
}
async disconnect(address: string): Promise<void> {
this.manager.disconnect(address);
}
async close(): Promise<void> {
this.manager.close();
}
}
+177
View File
@@ -0,0 +1,177 @@
import { Utils } from "@nativescript/core";
declare const com: any;
export type CommunicatorPhase =
| "disconnected"
| "connecting"
| "connected"
| "retrying"
| "disconnecting";
export type CommunicatorState = {
phase: CommunicatorPhase;
status: string;
};
export type HeadsetBatteryState = {
battery: number;
chargingStatus: number;
};
export type RawInputEvent =
| {
kind: "list-click";
containerName: string;
eventType: number;
eventSource: number;
systemExitReasonCode: number;
}
| {
kind: "text-click";
containerName: string;
eventType: number;
eventSource: number;
systemExitReasonCode: number;
}
| {
kind: "sys-event";
containerName: string;
eventType: number;
eventSource: number;
systemExitReasonCode: number;
};
function toJavaByteArray(bytes: Uint8Array): number[] {
const out = Array.create("byte", bytes.length) as number[];
for (let i = 0; i < bytes.length; i++) {
const value = bytes[i]!;
out[i] = value > 127 ? value - 256 : value;
}
return out;
}
export class FaceclawCommunicatorBridge {
private readonly communicator: any;
private readonly listenerProxy: any;
private readonly logListeners = new Set<(line: string) => void>();
private readonly stateListeners = new Set<(state: CommunicatorState) => void>();
private readonly ringListeners = new Set<(event: RawInputEvent) => void>();
private readonly batteryListeners = new Set<(state: HeadsetBatteryState) => void>();
private readonly evenAppConflictListeners = new Set<(message: string) => void>();
constructor(addresses: { right: string; left: string; ring?: string }) {
const context = Utils.android.getApplicationContext();
if (!context) throw new Error("Android application context unavailable");
this.communicator = new com.faceclaw.app.FaceclawBleCommunicator(
context,
addresses.right,
addresses.left,
addresses.ring ?? "",
);
this.listenerProxy = new com.faceclaw.app.FaceclawBleCommunicatorListener({
onLog: (line: string) => {
for (const listener of this.logListeners) {
listener(String(line));
}
},
onStateChange: (phase: string, status: string) => {
const state = {
phase: String(phase) as CommunicatorPhase,
status: String(status),
};
for (const listener of this.stateListeners) {
listener(state);
}
},
onRingEvent: (
kind: string,
containerName: string,
eventType: number,
eventSource: number,
systemExitReasonCode: number,
) => {
const event = {
kind: String(kind) as RawInputEvent["kind"],
containerName: String(containerName),
eventType: Number(eventType),
eventSource: Number(eventSource),
systemExitReasonCode: Number(systemExitReasonCode),
};
for (const listener of this.ringListeners) {
listener(event);
}
},
onBatteryState: (headsetBattery: number, headsetCharging: number) => {
const state = {
battery: Number(headsetBattery),
chargingStatus: Number(headsetCharging),
};
for (const listener of this.batteryListeners) {
listener(state);
}
},
onEvenAppConflict: (message: string) => {
for (const listener of this.evenAppConflictListeners) {
listener(String(message));
}
},
});
this.communicator.setListener(this.listenerProxy);
}
onLog(listener: (line: string) => void): () => void {
this.logListeners.add(listener);
return () => this.logListeners.delete(listener);
}
onStateChange(listener: (state: CommunicatorState) => void): () => void {
this.stateListeners.add(listener);
return () => this.stateListeners.delete(listener);
}
onRingEvent(listener: (event: RawInputEvent) => void): () => void {
this.ringListeners.add(listener);
return () => this.ringListeners.delete(listener);
}
onBatteryState(listener: (state: HeadsetBatteryState) => void): () => void {
this.batteryListeners.add(listener);
return () => this.batteryListeners.delete(listener);
}
onEvenAppConflict(listener: (message: string) => void): () => void {
this.evenAppConflictListeners.add(listener);
return () => this.evenAppConflictListeners.delete(listener);
}
async start(): Promise<void> {
this.communicator.start();
}
async submitDashboardImage(tileBmps: Uint8Array[], fingerprint: string): Promise<void> {
if (tileBmps.length !== 4) {
throw new Error(`expected 4 dashboard tiles, got ${tileBmps.length}`);
}
this.communicator.submitDashboardImage4(
toJavaByteArray(tileBmps[0]!),
toJavaByteArray(tileBmps[1]!),
toJavaByteArray(tileBmps[2]!),
toJavaByteArray(tileBmps[3]!),
fingerprint,
);
}
async disconnect(): Promise<void> {
this.communicator.disconnect();
}
async sendShutdown(exitMode = 0): Promise<boolean> {
return Boolean(this.communicator.sendShutdown(exitMode));
}
async close(): Promise<void> {
this.communicator.close();
}
}
+38
View File
@@ -0,0 +1,38 @@
import { Utils } from "@nativescript/core";
declare const com: any;
function getContext(): android.content.Context {
const context = Utils.android.getApplicationContext();
if (!context) throw new Error("Android application context unavailable");
return context;
}
function createIntent(action: string, text?: string): android.content.Intent {
const context = getContext();
const intent = new android.content.Intent(context, com.faceclaw.app.FaceclawForegroundService.class);
intent.setAction(action);
if (text) {
intent.putExtra(com.faceclaw.app.FaceclawForegroundService.EXTRA_TEXT, text);
}
return intent;
}
export function startForegroundNotification(text: string): void {
if (!global.isAndroid) return;
const context = getContext();
const intent = createIntent(com.faceclaw.app.FaceclawForegroundService.ACTION_START, text);
androidx.core.content.ContextCompat.startForegroundService(context, intent);
}
export function updateForegroundNotification(text: string): void {
if (!global.isAndroid) return;
const context = getContext();
context.startService(createIntent(com.faceclaw.app.FaceclawForegroundService.ACTION_UPDATE, text));
}
export function stopForegroundNotification(): void {
if (!global.isAndroid) return;
const context = getContext();
context.startService(createIntent(com.faceclaw.app.FaceclawForegroundService.ACTION_STOP));
}
+36
View File
@@ -0,0 +1,36 @@
import { ImageSource, Screen, Utils } from "@nativescript/core";
import { type GrayImage } from "../graphics/image";
const PREVIEW_BRIGHTEN_GAMMA = 0.7;
export function grayImageToPreviewSource(image: GrayImage): ImageSource | null {
if (!global.isAndroid) {
return null;
}
const colors = Array.create("int", image.width * image.height) as number[];
for (let i = 0; i < image.pixels.length; i++) {
const gray = brightenForPreview(image.pixels[i] ?? 0);
colors[i] = (255 << 24) | (gray << 16) | (gray << 8) | gray;
}
const bitmap = android.graphics.Bitmap.createBitmap(
colors,
image.width,
image.height,
android.graphics.Bitmap.Config.ARGB_8888,
);
const targetWidth = Math.max(1, Math.round(Utils.layout.toDevicePixels(Screen.mainScreen.widthDIPs)));
const targetHeight = Math.max(1, Math.round((targetWidth * image.height) / image.width));
const scaledBitmap =
bitmap.getWidth() === targetWidth && bitmap.getHeight() === targetHeight
? bitmap
: android.graphics.Bitmap.createScaledBitmap(bitmap, targetWidth, targetHeight, false);
return new ImageSource(scaledBitmap);
}
function brightenForPreview(gray: number): number {
const normalized = Math.max(0, Math.min(255, gray)) / 255;
return Math.max(0, Math.min(255, Math.round(255 * Math.pow(normalized, PREVIEW_BRIGHTEN_GAMMA))));
}
+148
View File
@@ -0,0 +1,148 @@
import { Utils } from "@nativescript/core";
declare const com: any;
export type MediaPlaybackState =
| "notification-access-required"
| "idle"
| "playing"
| "paused"
| "buffering"
| "stopped"
| "unknown";
export type MediaControllerState = {
available: boolean;
accessEnabled: boolean;
packageName: string;
playbackState: MediaPlaybackState;
title: string;
artist: string;
album: string;
status: string;
canPlayPause: boolean;
canSkipNext: boolean;
canSkipPrevious: boolean;
};
const DEFAULT_MEDIA_STATE: MediaControllerState = {
available: false,
accessEnabled: false,
packageName: "",
playbackState: "idle",
title: "",
artist: "",
album: "",
status: "Media controller unavailable.",
canPlayPause: false,
canSkipNext: false,
canSkipPrevious: false,
};
export class FaceclawMediaControllerBridge {
private readonly stateListeners = new Set<(state: MediaControllerState) => void>();
private controller: any | null = null;
private listenerProxy: any | null = null;
private state: MediaControllerState = { ...DEFAULT_MEDIA_STATE };
private started = false;
onStateChange(listener: (state: MediaControllerState) => void): () => void {
this.stateListeners.add(listener);
listener(this.snapshot());
return () => this.stateListeners.delete(listener);
}
snapshot(): MediaControllerState {
return { ...this.state };
}
async start(): Promise<void> {
if (this.started || !global.isAndroid) return;
this.ensureController();
this.started = true;
this.controller?.start();
}
async stop(): Promise<void> {
if (!this.started || !global.isAndroid) return;
this.started = false;
this.controller?.stop();
}
async playPause(): Promise<void> {
this.ensureController();
this.controller?.playPause();
}
async skipNext(): Promise<void> {
this.ensureController();
this.controller?.skipNext();
}
async skipPrevious(): Promise<void> {
this.ensureController();
this.controller?.skipPrevious();
}
openNotificationAccessSettings(): void {
this.ensureController();
this.controller?.openNotificationAccessSettings();
}
private ensureController(): void {
if (!global.isAndroid || this.controller) return;
const context = Utils.android.getApplicationContext();
if (!context) {
throw new Error("Android application context unavailable");
}
this.controller = new com.faceclaw.app.FaceclawMediaController(context);
this.listenerProxy = new com.faceclaw.app.FaceclawMediaControllerListener({
onStateChange: (
playbackState: string,
packageName: string,
title: string,
artist: string,
album: string,
canPlayPause: boolean,
canSkipNext: boolean,
canSkipPrevious: boolean,
accessEnabled: boolean,
status: string,
) => {
this.state = {
available: Boolean(title || artist || album || packageName) || String(playbackState) !== "idle",
accessEnabled: Boolean(accessEnabled),
packageName: String(packageName),
playbackState: normalizePlaybackState(String(playbackState)),
title: String(title),
artist: String(artist),
album: String(album),
status: String(status),
canPlayPause: Boolean(canPlayPause),
canSkipNext: Boolean(canSkipNext),
canSkipPrevious: Boolean(canSkipPrevious),
};
for (const listener of this.stateListeners) {
listener(this.snapshot());
}
},
});
this.controller.setListener(this.listenerProxy);
}
}
function normalizePlaybackState(value: string): MediaPlaybackState {
switch (value) {
case "notification-access-required":
case "idle":
case "playing":
case "paused":
case "buffering":
case "stopped":
return value;
default:
return "unknown";
}
}
export const mediaControllerBridge = new FaceclawMediaControllerBridge();
+411
View File
@@ -0,0 +1,411 @@
import { loadNightscoutSettings } from "../ui/dashboard-settings";
export type NightscoutPoint = {
timestampMs: number;
sgv: number;
};
export type NightscoutCarbEvent = {
timestampMs: number;
carbs: number;
};
export type NightscoutBolusEvent = {
timestampMs: number;
insulin: number;
};
export type NightscoutBasalEvent = {
timestampMs: number;
durationMinutes: number;
rate: number;
};
export type NightscoutState = {
available: boolean;
status: string;
units: string;
history: NightscoutPoint[];
latest: NightscoutPoint | null;
delta: number | null;
direction: string;
iob: number | null;
cob: number | null;
cageTimestampMs: number | null;
pumpStatus: string;
openapsStatusShort: string;
carbs: NightscoutCarbEvent[];
boluses: NightscoutBolusEvent[];
basal: NightscoutBasalEvent[];
lastUpdatedMs: number | null;
configurationMissing: boolean;
};
type NightscoutEntryResponse = {
sgv?: unknown;
date?: unknown;
direction?: unknown;
};
type NightscoutDeviceStatusResponse = {
openaps?: {
iob?: {
iob?: unknown;
timestamp?: unknown;
mills?: unknown;
};
suggested?: {
COB?: unknown;
timestamp?: unknown;
mills?: unknown;
};
enacted?: {
COB?: unknown;
timestamp?: unknown;
mills?: unknown;
};
};
pump?: {
clock?: unknown;
reservoir?: unknown;
battery?: {
voltage?: unknown;
status?: unknown;
};
status?: {
status?: unknown;
bolusing?: unknown;
suspended?: unknown;
timestamp?: unknown;
};
};
created_at?: unknown;
};
type NightscoutStatusResponse = {
settings?: {
units?: unknown;
};
};
type NightscoutTreatmentResponse = {
created_at?: unknown;
timestamp?: unknown;
eventType?: unknown;
carbs?: unknown;
insulin?: unknown;
absolute?: unknown;
rate?: unknown;
duration?: unknown;
};
const NIGHTSCOUT_REFRESH_MS = 60_000;
const NIGHTSCOUT_HISTORY_COUNT = 30;
const NIGHTSCOUT_GRAPH_WINDOW_MS = 2 * 60 * 60 * 1000;
const NIGHTSCOUT_TREATMENT_LOOKBACK_MS = 3 * 60 * 60 * 1000;
const DEFAULT_NIGHTSCOUT_STATE: NightscoutState = {
available: false,
status: "Nightscout unavailable.",
units: "mg/dL",
history: [],
latest: null,
delta: null,
direction: "",
iob: null,
cob: null,
cageTimestampMs: null,
pumpStatus: "",
openapsStatusShort: "--",
carbs: [],
boluses: [],
basal: [],
lastUpdatedMs: null,
configurationMissing: true,
};
export class NightscoutBridge {
private readonly listeners = new Set<(state: NightscoutState) => void>();
private state: NightscoutState = { ...DEFAULT_NIGHTSCOUT_STATE };
private refreshHandle: ReturnType<typeof setInterval> | null = null;
private refreshInFlight: Promise<void> | null = null;
onStateChange(listener: (state: NightscoutState) => void): () => void {
this.listeners.add(listener);
listener(this.snapshot());
return () => this.listeners.delete(listener);
}
snapshot(): NightscoutState {
return {
...this.state,
history: this.state.history.map((point) => ({ ...point })),
latest: this.state.latest ? { ...this.state.latest } : null,
carbs: this.state.carbs.map((event) => ({ ...event })),
boluses: this.state.boluses.map((event) => ({ ...event })),
basal: this.state.basal.map((event) => ({ ...event })),
};
}
async start(): Promise<void> {
if (this.refreshHandle) {
await this.refreshNow();
return;
}
await this.refreshNow();
this.refreshHandle = setInterval(() => {
void this.refreshNow();
}, NIGHTSCOUT_REFRESH_MS);
}
async stop(): Promise<void> {
if (this.refreshHandle) {
clearInterval(this.refreshHandle);
this.refreshHandle = null;
}
await this.refreshInFlight?.catch(() => {});
}
async refreshNow(): Promise<void> {
if (this.refreshInFlight) {
return this.refreshInFlight;
}
this.refreshInFlight = this.refresh();
try {
await this.refreshInFlight;
} finally {
this.refreshInFlight = null;
}
}
private async refresh(): Promise<void> {
try {
const nowMs = Date.now();
const settings = loadNightscoutSettings();
if (!settings.siteUrl || !settings.apiToken) {
this.state = {
...DEFAULT_NIGHTSCOUT_STATE,
status: "Configure Nightscout site URL and API token.",
configurationMissing: true,
};
this.emit();
return;
}
const treatmentStartIso = new Date(nowMs - NIGHTSCOUT_TREATMENT_LOOKBACK_MS).toISOString();
const tokenQuery = `token=${encodeURIComponent(settings.apiToken)}`;
const [entries, deviceStatus, status, treatments, siteChanges] = await Promise.all([
fetchJson<NightscoutEntryResponse[]>(
`${settings.siteUrl}/api/v1/entries.json?count=${NIGHTSCOUT_HISTORY_COUNT}&${tokenQuery}`,
),
fetchJson<NightscoutDeviceStatusResponse[]>(
`${settings.siteUrl}/api/v1/devicestatus.json?count=1&${tokenQuery}`,
),
fetchJson<NightscoutStatusResponse>(
`${settings.siteUrl}/api/v1/status.json?${tokenQuery}`,
),
fetchJson<NightscoutTreatmentResponse[]>(
`${settings.siteUrl}/api/v1/treatments.json?find%5Bcreated_at%5D%5B%24gte%5D=${encodeURIComponent(treatmentStartIso)}&${tokenQuery}`,
),
fetchJson<NightscoutTreatmentResponse[]>(
`${settings.siteUrl}/api/v1/treatments.json?find%5BeventType%5D=Site%20Change&count=1&${tokenQuery}`,
),
]);
const history = (entries ?? [])
.map((entry) => ({
timestampMs: Number(entry.date ?? 0),
sgv: Number(entry.sgv ?? NaN),
direction: typeof entry.direction === "string" ? entry.direction : "",
}))
.filter((entry) => Number.isFinite(entry.timestampMs) && Number.isFinite(entry.sgv))
.sort((a, b) => a.timestampMs - b.timestampMs);
const latest = history.at(-1) ?? null;
const previous = history.length >= 2 ? history[history.length - 2]! : null;
const latestDirection = latest ? (entries?.[0]?.direction as string | undefined) ?? "" : "";
const latestDeviceStatus = deviceStatus?.[0];
const iob = Number((latestDeviceStatus?.openaps?.iob?.iob as number | undefined) ?? NaN);
const cob = firstFiniteNumber(
latestDeviceStatus?.openaps?.suggested?.COB,
latestDeviceStatus?.openaps?.enacted?.COB,
);
const loopTimestampMs = Math.max(
parseTimestampMs(latestDeviceStatus?.openaps?.suggested?.mills ?? latestDeviceStatus?.openaps?.suggested?.timestamp),
parseTimestampMs(latestDeviceStatus?.openaps?.enacted?.mills ?? latestDeviceStatus?.openaps?.enacted?.timestamp),
parseTimestampMs(latestDeviceStatus?.openaps?.iob?.mills ?? latestDeviceStatus?.openaps?.iob?.timestamp),
);
const pumpStatus = formatPumpStatus(latestDeviceStatus, nowMs);
const parsedTreatments = parseTreatments(treatments ?? [], nowMs);
const latestSiteChange = parseTimestampMs(siteChanges?.[0]?.created_at ?? siteChanges?.[0]?.timestamp);
this.state = {
available: latest !== null,
status: latest ? "Nightscout updated." : "No Nightscout glucose entries.",
units: typeof status?.settings?.units === "string" ? status.settings.units : "mg/dL",
history: history.map(({ timestampMs, sgv }) => ({ timestampMs, sgv })),
latest: latest ? { timestampMs: latest.timestampMs, sgv: latest.sgv } : null,
delta: latest && previous ? latest.sgv - previous.sgv : null,
direction: latestDirection,
iob: Number.isFinite(iob) ? iob : null,
cob,
cageTimestampMs: latestSiteChange > 0 ? latestSiteChange : null,
pumpStatus,
openapsStatusShort: loopTimestampMs > 0 ? formatElapsedShort(nowMs - loopTimestampMs) : "--",
carbs: parsedTreatments.carbs,
boluses: parsedTreatments.boluses,
basal: parsedTreatments.basal,
lastUpdatedMs: nowMs,
configurationMissing: false,
};
this.emit();
} catch (error) {
const message = (error as Error)?.message ?? String(error);
this.state = {
...this.state,
available: this.state.latest !== null,
status: `Nightscout refresh failed: ${message}`,
};
this.emit();
}
}
private emit(): void {
const snapshot = this.snapshot();
for (const listener of this.listeners) {
listener(snapshot);
}
}
}
async function fetchJson<T>(url: string): Promise<T> {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return (await response.json()) as T;
}
function parseTreatments(treatments: NightscoutTreatmentResponse[], nowMs: number): {
carbs: NightscoutCarbEvent[];
boluses: NightscoutBolusEvent[];
basal: NightscoutBasalEvent[];
} {
const windowStartMs = nowMs - NIGHTSCOUT_TREATMENT_LOOKBACK_MS;
const carbs: NightscoutCarbEvent[] = [];
const boluses: NightscoutBolusEvent[] = [];
const basal: NightscoutBasalEvent[] = [];
for (const treatment of treatments) {
const timestampMs = parseTimestampMs(treatment.created_at ?? treatment.timestamp);
if (timestampMs <= 0 || timestampMs < windowStartMs || timestampMs > nowMs) {
continue;
}
const carbValue = firstFiniteNumber(treatment.carbs);
if (carbValue !== null && carbValue > 0) {
carbs.push({ timestampMs, carbs: carbValue });
}
const insulinValue = firstFiniteNumber(treatment.insulin);
if (insulinValue !== null && insulinValue > 0) {
boluses.push({ timestampMs, insulin: insulinValue });
}
const eventType = typeof treatment.eventType === "string" ? treatment.eventType : "";
const basalRate = firstFiniteNumber(treatment.absolute, treatment.rate);
const durationMinutes = firstFiniteNumber(treatment.duration);
if ((eventType === "Temp Basal" || basalRate !== null) && basalRate !== null && durationMinutes !== null && durationMinutes > 0) {
basal.push({ timestampMs, rate: basalRate, durationMinutes });
}
}
carbs.sort((a, b) => a.timestampMs - b.timestampMs);
boluses.sort((a, b) => a.timestampMs - b.timestampMs);
basal.sort((a, b) => a.timestampMs - b.timestampMs);
return { carbs, boluses, basal };
}
function parseTimestampMs(value: unknown): number {
if (typeof value === "number" && Number.isFinite(value)) {
return value;
}
if (typeof value === "string") {
const asNumber = Number(value);
if (Number.isFinite(asNumber) && asNumber > 0) {
return asNumber;
}
const parsed = Date.parse(value);
if (Number.isFinite(parsed)) {
return parsed;
}
}
return 0;
}
function firstFiniteNumber(...values: unknown[]): number | null {
for (const value of values) {
const numeric = Number(value);
if (Number.isFinite(numeric)) {
return numeric;
}
}
return null;
}
function formatPumpStatus(status: NightscoutDeviceStatusResponse | undefined, nowMs: number): string {
if (!status?.pump) {
return "--";
}
const reservoir = firstFiniteNumber(status.pump.reservoir);
const voltage = firstFiniteNumber(status.pump.battery?.voltage);
const commTimestampMs = Math.max(
parseTimestampMs(status.pump.status?.timestamp),
parseTimestampMs(status.pump.clock),
parseTimestampMs(status.created_at),
);
const stateLabel = summarizePumpState(status);
const parts: string[] = [];
if (reservoir !== null) {
parts.push(`${Math.round(reservoir)}U`);
}
if (voltage !== null) {
parts.push(`${voltage.toFixed(2)}v`);
}
if (commTimestampMs > 0) {
parts.push(`${formatElapsedShort(nowMs - commTimestampMs)} ago`);
}
if (stateLabel) {
parts.push(stateLabel);
}
return parts.join(" ") || "--";
}
function summarizePumpState(status: NightscoutDeviceStatusResponse): string {
if (status.pump?.status?.suspended === true) {
return "suspended";
}
if (status.pump?.status?.bolusing === true) {
return "bolusing";
}
if (typeof status.pump?.status?.status === "string" && status.pump.status.status.trim()) {
return status.pump.status.status.trim();
}
if (typeof status.pump?.battery?.status === "string" && status.pump.battery.status.trim()) {
return status.pump.battery.status.trim();
}
return "";
}
function formatElapsedShort(elapsedMs: number): string {
const minutes = Math.max(0, Math.round(elapsedMs / 60_000));
if (minutes < 60) {
return `${minutes}m`;
}
const hours = Math.round(minutes / 60);
if (hours < 48) {
return `${hours}h`;
}
return `${Math.round(hours / 24)}d`;
}
export const nightscoutBridge = new NightscoutBridge();
+52
View File
@@ -0,0 +1,52 @@
import { GrayImage } from "../graphics/image";
declare const com: any;
const ICON_SIZE = 24;
const ICON_CACHE_MS = 5_000;
let cachedIcons: GrayImage[] = [];
let cachedAtMs = 0;
export function readActiveNotificationIcons(maxIcons: number): GrayImage[] {
if (!global.isAndroid || maxIcons <= 0) return [];
const now = Date.now();
if (now - cachedAtMs < ICON_CACHE_MS) {
return cachedIcons.map(cloneGrayImage);
}
const bytes = toUint8Array(
com.faceclaw.app.FaceclawMediaNotificationListenerService.getActiveNotificationIconGrays(
ICON_SIZE,
maxIcons,
),
);
const iconByteLength = ICON_SIZE * ICON_SIZE;
const iconCount = Math.floor(bytes.length / iconByteLength);
const icons: GrayImage[] = [];
for (let index = 0; index < iconCount; index++) {
const icon = new GrayImage(ICON_SIZE, ICON_SIZE, 0);
icon.pixels.set(bytes.subarray(index * iconByteLength, (index + 1) * iconByteLength));
icons.push(icon);
}
cachedIcons = icons;
cachedAtMs = now;
return icons.map(cloneGrayImage);
}
function toUint8Array(bytes: ArrayLike<number> | null | undefined): Uint8Array {
if (!bytes) return new Uint8Array(0);
const out = new Uint8Array(bytes.length);
for (let i = 0; i < bytes.length; i++) {
out[i] = bytes[i]! & 0xff;
}
return out;
}
function cloneGrayImage(image: GrayImage): GrayImage {
const clone = new GrayImage(image.width, image.height, 0);
clone.pixels.set(image.pixels);
return clone;
}
+36
View File
@@ -0,0 +1,36 @@
import { Utils } from "@nativescript/core";
declare const android: any;
export type PhoneBatteryState = {
battery: number | null;
charging: boolean | null;
};
export function readPhoneBatteryState(): PhoneBatteryState {
if (!global.isAndroid) {
return { battery: null, charging: null };
}
const context = Utils.android.getApplicationContext();
if (!context) {
return { battery: null, charging: null };
}
const filter = new android.content.IntentFilter(android.content.Intent.ACTION_BATTERY_CHANGED);
const intent = context.registerReceiver(null, filter);
if (!intent) {
return { battery: null, charging: null };
}
const level = Number(intent.getIntExtra(android.os.BatteryManager.EXTRA_LEVEL, -1));
const scale = Number(intent.getIntExtra(android.os.BatteryManager.EXTRA_SCALE, -1));
const status = Number(intent.getIntExtra(android.os.BatteryManager.EXTRA_STATUS, -1));
const charging =
status === android.os.BatteryManager.BATTERY_STATUS_CHARGING ||
status === android.os.BatteryManager.BATTERY_STATUS_FULL;
return {
battery: level >= 0 && scale > 0 ? Math.round((level * 100) / scale) : null,
charging,
};
}
+8
View File
@@ -0,0 +1,8 @@
import { EventData, Page } from "@nativescript/core";
import { OnboardingViewModel } from "./onboarding-view-model";
export function navigatingTo(args: EventData): void {
const page = args.object as Page;
page.bindingContext = new OnboardingViewModel();
}
+17
View File
@@ -0,0 +1,17 @@
<Page xmlns="http://schemas.nativescript.org/tns.xsd" navigatingTo="navigatingTo" actionBarHidden="true">
<GridLayout rows="*,auto" class="p-20">
<ScrollView row="0">
<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" />
</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 }}" class="-primary" />
</GridLayout>
</GridLayout>
</Page>
+11
View File
@@ -0,0 +1,11 @@
import { ApplicationSettings } from "@nativescript/core";
const ONBOARDING_COMPLETE_KEY = "onboarding.complete";
export function hasCompletedOnboarding(): boolean {
return ApplicationSettings.getBoolean(ONBOARDING_COMPLETE_KEY, false);
}
export function setOnboardingCompleted(completed: boolean): void {
ApplicationSettings.setBoolean(ONBOARDING_COMPLETE_KEY, completed);
}
+150
View File
@@ -0,0 +1,150 @@
import { Frame, Observable } from "@nativescript/core";
import { setOnboardingCompleted } from "./onboarding-state";
type OnboardingStep = 1 | 2 | 3;
type StepContent = {
headline: string;
tagline: string;
body: string;
primaryLabel: string;
secondaryLabel: string;
showLogo: boolean;
showTagline: boolean;
showSecondary: boolean;
};
const STEP_CONTENT: Record<OnboardingStep, StepContent> = {
1: {
headline: "Faceclaw",
tagline: "Perching on the faces of giants",
body: "",
primaryLabel: "Next",
secondaryLabel: "",
showLogo: true,
showTagline: true,
showSecondary: false,
},
2: {
headline: "Before You Continue",
tagline: "",
body:
"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,
showSecondary: true,
},
3: {
headline: "Disconnect Even First",
tagline: "",
body:
"You can switch back and forth between Faceclaw and the official Even Realities application at any time. However, they can't both be connected to the headset simultaneously. The Even app will reconnect to the glasses whenever you launch it. To disconnect the official Even app, open it, go to the Home tab, select your glasses, open the Connection submenu, and press Disconnect.",
primaryLabel: "Configure",
secondaryLabel: "Back",
showLogo: false,
showTagline: false,
showSecondary: true,
},
};
export class OnboardingViewModel extends Observable {
private _step: OnboardingStep = 1;
constructor() {
super();
this.publish();
}
onPrimaryTap(): void {
if (this._step === 1) {
this.setStep(2);
return;
}
if (this._step === 2) {
this.setStep(3);
return;
}
setOnboardingCompleted(true);
Frame.topmost()?.navigate({
moduleName: "config-page",
clearHistory: true,
});
}
onSecondaryTap(): void {
if (this._step === 2) {
this.setStep(1);
return;
}
if (this._step === 3) {
this.setStep(2);
}
}
get headline(): string {
return STEP_CONTENT[this._step].headline;
}
get tagline(): string {
return STEP_CONTENT[this._step].tagline;
}
get body(): string {
return STEP_CONTENT[this._step].body;
}
get primaryLabel(): string {
return STEP_CONTENT[this._step].primaryLabel;
}
get secondaryLabel(): string {
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 taglineVisibility(): "visible" | "collapse" {
return this.showTagline ? "visible" : "collapse";
}
get secondaryVisibility(): "visible" | "collapse" {
return this.showSecondary ? "visible" : "collapse";
}
private setStep(step: OnboardingStep): void {
if (this._step === step) return;
this._step = step;
this.publish();
}
private publish(): void {
this.notifyPropertyChange("headline", this.headline);
this.notifyPropertyChange("tagline", this.tagline);
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("secondaryVisibility", this.secondaryVisibility);
}
}
+664
View File
@@ -0,0 +1,664 @@
import takeRight from "lodash/takeRight";
import { BdfFont, loadEmbeddedTerminus24 } from "../graphics/bdffont";
import { GrayImage, imageFromAsciiArt } from "../graphics/image";
import { wrapText } from "../graphics/textwrap";
import { mediaControllerBridge, type MediaControllerState } from "../native/media-controller";
import { nightscoutBridge, type NightscoutState } from "../native/nightscout";
import { type DashboardPluginId } from "./dashboard-settings";
import { Layer, type DashboardInputEvent, type LayerContext } from "./layers";
export type DashboardPluginState = {
logLines: string[];
media: MediaControllerState;
nightscout: NightscoutState;
nightscoutConfigured: boolean;
};
export type DashboardPluginCardBounds = {
x: number;
y: number;
width: number;
height: number;
};
export type DashboardPluginCardRenderArgs = {
image: GrayImage;
bounds: DashboardPluginCardBounds;
selected: boolean;
font: BdfFont;
state: DashboardPluginState;
};
export interface DashboardPlugin {
readonly id: DashboardPluginId;
readonly label: string;
renderCard(args: DashboardPluginCardRenderArgs): void;
createFullscreenLayer?(getState: () => DashboardPluginState): Layer | null;
}
const DASHBOARD_PLUGINS: DashboardPlugin[] = [
{
id: "blank",
label: "Blank",
renderCard: () => {},
createFullscreenLayer: () => null,
},
{
id: "input-debug-log",
label: "Input debug log",
renderCard: ({ image, bounds, font, state }) => {
image.drawText(font, bounds.x + 10, bounds.y + 14, "Input log", 180);
const lineHeight = 14;
const visibleLineCount = Math.max(1, Math.floor((bounds.height - 28) / lineHeight));
const visibleLines = takeRight(state.logLines, visibleLineCount);
for (let i = 0; i < visibleLines.length; i++) {
image.drawText(font, bounds.x + 8, bounds.y + 26 + i * lineHeight, visibleLines[i]!, 190);
}
},
createFullscreenLayer: (getState) => new DebugLogLayer(getState),
},
{
id: "music-controller",
label: "Music controller",
renderCard: ({ image, bounds, font, state }) => {
const media = state.media;
image.drawText(font, bounds.x + 10, bounds.y + 14, "Now playing", 180);
if (!media.accessEnabled) {
image.drawText(font, bounds.x + 10, bounds.y + 30, "Enable notification", 150);
image.drawText(font, bounds.x + 10, bounds.y + 44, "access for media", 150);
return;
}
if (!media.available) {
image.drawText(font, bounds.x + 10, bounds.y + 30, "No active session", 150);
return;
}
const titleLines = wrapText(font, media.title || "Unknown title", bounds.width - 20).slice(0, 2);
const artistLine = media.artist || media.album || media.packageName || "Unknown source";
image.drawText(font, bounds.x + 10, bounds.y + 30, titleLines[0] ?? "", 210);
if (titleLines[1]) {
image.drawText(font, bounds.x + 10, bounds.y + 44, titleLines[1], 210);
}
image.drawText(font, bounds.x + 10, bounds.y + 62, artistLine, 160);
image.drawText(font, bounds.x + 10, bounds.y + bounds.height - 18, playbackLabel(media), 130);
},
createFullscreenLayer: (getState) => new MusicControllerLayer(getState),
},
{
id: "nightscout",
label: "Nightscout",
renderCard: ({ image, bounds, font, state }) => {
const nightscout = state.nightscout;
const nowMs = Date.now();
image.drawText(font, bounds.x + 10, bounds.y + 10, "Nightscout", 180);
if (!state.nightscoutConfigured || nightscout.configurationMissing) {
image.drawText(font, bounds.x + 10, bounds.y + 30, "Needs setup", 170);
image.drawText(font, bounds.x + 10, bounds.y + 44, "Click to configure", 140);
return;
}
if (!nightscout.available || !nightscout.latest) {
image.drawText(font, bounds.x + 10, bounds.y + 30, "No glucose data", 150);
image.drawText(font, bounds.x + 10, bounds.y + 44, truncateLine(nightscout.status, 26), 120);
return;
}
const latest = nightscout.latest;
const deltaLabel = formatDelta(nightscout.delta);
const glucoseText = `${latest.sgv}`;
const glucoseX = bounds.x + bounds.width - 92;
image.drawText(nightscoutLargeFont, glucoseX, bounds.y + 10, glucoseText, 230);
if (isNightscoutPointStale(latest, nowMs)) {
drawNightscoutValueStrikeThrough(image, glucoseX, bounds.y + 22, nightscoutLargeFont.measureText(glucoseText));
}
drawNightscoutDelta(image, font, bounds.x + bounds.width - 92, bounds.y + 30, deltaLabel, nightscout.direction, 160);
image.drawText(
font,
bounds.x + 10,
bounds.y + 30,
`IOB ${nightscout.iob === null ? "--" : nightscout.iob.toFixed(1)} COB ${nightscout.cob === null ? "--" : formatWholeNumber(nightscout.cob)}`,
160,
);
image.drawText(
font,
bounds.x + 10,
bounds.y + 44,
`Loop ${nightscout.openapsStatusShort} CAGE ${formatAgeShortFromTimestamp(nightscout.cageTimestampMs, nowMs)}`,
138,
);
drawNightscoutGraph(
image,
{
x: bounds.x + 10,
y: bounds.y + 60,
width: bounds.width - 20,
height: Math.max(16, bounds.height - 82),
},
nightscout,
nowMs,
font,
);
},
createFullscreenLayer: (getState) => new NightscoutLayer(getState),
},
];
const PLUGIN_MAP = new Map<DashboardPluginId, DashboardPlugin>(
DASHBOARD_PLUGINS.map((plugin) => [plugin.id, plugin]),
);
const nightscoutLargeFont = loadEmbeddedTerminus24();
const NIGHTSCOUT_STALE_MS = 15 * 60 * 1000;
const NIGHTSCOUT_GRAPH_WINDOW_MS = 2 * 60 * 60 * 1000;
export function listDashboardPlugins(): DashboardPlugin[] {
return [...DASHBOARD_PLUGINS];
}
export function getDashboardPlugin(pluginId: DashboardPluginId): DashboardPlugin {
return PLUGIN_MAP.get(pluginId) ?? PLUGIN_MAP.get("blank")!;
}
export function isBlankDashboardPlugin(pluginId: DashboardPluginId): boolean {
return pluginId === "blank";
}
function playbackLabel(media: MediaControllerState): string {
switch (media.playbackState) {
case "playing":
return "Playing";
case "paused":
return "Paused";
case "buffering":
return "Buffering";
case "stopped":
return "Stopped";
case "notification-access-required":
return "Access required";
default:
return media.status || "Idle";
}
}
function formatDelta(delta: number | null): string {
if (delta === null) return "--";
return `${delta >= 0 ? "+" : ""}${Math.round(delta)}`;
}
function drawNightscoutDelta(
image: GrayImage,
font: BdfFont,
x: number,
y: number,
deltaLabel: string,
direction: string,
shade: number,
): void {
const text = direction ? `${deltaLabel} ` : deltaLabel;
image.drawText(font, x, y, text, shade);
drawDirectionIndicator(image, font, x + font.measureText(text), y, direction, shade);
}
function drawDirectionIndicator(
image: GrayImage,
font: BdfFont,
x: number,
y: number,
direction: string,
shade: number,
): void {
const label = directionGlyphLabel(font, direction);
if (label) {
image.drawText(font, x, y, label, shade);
return;
}
const art = directionAsciiArt(direction);
if (art) {
image.bitBlt(imageFromAsciiArt(art, shade), x, y + 1);
return;
}
if (direction) {
image.drawText(font, x, y, truncateLine(direction, 10), shade);
}
}
function directionGlyphLabel(font: BdfFont, direction: string): string {
switch (direction) {
case "DoubleUp":
return font.hasGlyph("↑".codePointAt(0)!) ? "↑↑" : "";
case "SingleUp":
return font.hasGlyph("↑".codePointAt(0)!) ? "↑" : "";
case "FortyFiveUp":
return font.hasGlyph("↗".codePointAt(0)!) ? "↗" : "";
case "Flat":
return font.hasGlyph("→".codePointAt(0)!) ? "→" : "";
case "FortyFiveDown":
return font.hasGlyph("↘".codePointAt(0)!) ? "↘" : "";
case "SingleDown":
return font.hasGlyph("↓".codePointAt(0)!) ? "↓" : "";
case "DoubleDown":
return font.hasGlyph("↓".codePointAt(0)!) ? "↓↓" : "";
default:
return "";
}
}
function directionAsciiArt(direction: string): readonly string[] | undefined {
switch (direction) {
case "FortyFiveUp":
return [" ##", " ###", " # ##", "# ##", " ##"];
case "FortyFiveDown":
return [" ##", "# ##", " # ##", " ###", " ##"];
default:
return undefined;
}
}
function truncateLine(text: string, maxChars: number): string {
if (text.length <= maxChars) return text;
return `${text.slice(0, Math.max(0, maxChars - 3))}...`;
}
function formatWholeNumber(value: number): string {
return `${Math.round(value)}`;
}
function formatBolusLabel(value: number): string {
return Number.isInteger(value) ? `${value}` : value.toFixed(1);
}
function formatAgeShortFromTimestamp(timestampMs: number | null, nowMs: number): string {
if (!timestampMs) {
return "--";
}
const elapsedMinutes = Math.max(0, Math.round((nowMs - timestampMs) / 60_000));
if (elapsedMinutes < 60) {
return `${elapsedMinutes}m`;
}
const elapsedHours = Math.round(elapsedMinutes / 60);
if (elapsedHours < 48) {
return `${elapsedHours}h`;
}
return `${Math.round(elapsedHours / 24)}d`;
}
function drawNightscoutGraph(
image: GrayImage,
bounds: { x: number; y: number; width: number; height: number },
nightscout: NightscoutState,
nowMs: number,
font: BdfFont,
): void {
if (bounds.width <= 2 || bounds.height <= 2) {
return;
}
const windowStartMs = nowMs - NIGHTSCOUT_GRAPH_WINDOW_MS;
const visibleHistory = nightscout.history.filter((point) => point.timestampMs >= windowStartMs && point.timestampMs <= nowMs);
if (visibleHistory.length === 0) {
return;
}
const values = visibleHistory.map((point) => point.sgv);
const min = Math.min(...values, 60);
const max = Math.max(...values, 200);
const range = Math.max(20, max - min);
const paddedMin = min - range * 0.1;
const paddedMax = max + range * 0.1;
image.drawRect(bounds.x, bounds.y, bounds.width, bounds.height, 56);
drawNightscoutBasalOverlay(image, bounds, nightscout.basal, nowMs);
drawNightscoutReferenceLine(image, bounds, paddedMin, paddedMax, 60, 40);
drawNightscoutReferenceLine(image, bounds, paddedMin, paddedMax, 100, 40);
drawNightscoutReferenceLine(image, bounds, paddedMin, paddedMax, 180, 40);
const plotted = visibleHistory.map((point) => ({
point,
x:
bounds.x +
Math.round(
((point.timestampMs - windowStartMs) / Math.max(1, NIGHTSCOUT_GRAPH_WINDOW_MS)) * Math.max(1, bounds.width - 1),
),
y:
bounds.y +
bounds.height -
1 -
Math.round(((point.sgv - paddedMin) / Math.max(1, paddedMax - paddedMin)) * Math.max(1, bounds.height - 1)),
}));
for (let i = 0; i < plotted.length; i++) {
const current = plotted[i]!;
const previous = i > 0 ? plotted[i - 1]! : null;
const next = i + 1 < plotted.length ? plotted[i + 1]! : null;
const connectedToPrevious =
previous !== null && current.point.timestampMs - previous.point.timestampMs <= NIGHTSCOUT_STALE_MS;
const connectedToNext =
next !== null && next.point.timestampMs - current.point.timestampMs <= NIGHTSCOUT_STALE_MS;
if (connectedToPrevious && previous) {
image.drawLine(previous.x, previous.y, current.x, current.y, 220);
}
if (!connectedToPrevious && !connectedToNext) {
image.fillRect(current.x - 1, current.y - 1, 2, 2, 220);
}
}
drawNightscoutCarbMarkers(image, bounds, font, nightscout.carbs, nowMs);
drawNightscoutBolusMarkers(image, bounds, font, nightscout.boluses, nowMs);
}
function drawNightscoutBasalOverlay(
image: GrayImage,
bounds: { x: number; y: number; width: number; height: number },
basalEvents: NightscoutState["basal"],
nowMs: number,
): void {
const windowStartMs = nowMs - NIGHTSCOUT_GRAPH_WINDOW_MS;
const visibleEvents = basalEvents.filter(
(event) => event.timestampMs + event.durationMinutes * 60_000 >= windowStartMs && event.timestampMs <= nowMs,
);
if (visibleEvents.length === 0) {
return;
}
const maxRate = Math.max(...visibleEvents.map((event) => event.rate), 0);
if (maxRate <= 0) {
return;
}
const overlayHeight = Math.max(8, Math.min(18, Math.floor(bounds.height * 0.22)));
const bottomY = bounds.y + bounds.height - 2;
for (const event of visibleEvents) {
const startMs = Math.max(windowStartMs, event.timestampMs);
const endMs = Math.min(nowMs, event.timestampMs + event.durationMinutes * 60_000);
if (endMs <= startMs) {
continue;
}
const leftX = timeToGraphX(bounds, windowStartMs, startMs);
const rightX = timeToGraphX(bounds, windowStartMs, endMs);
const height = Math.max(1, Math.round((event.rate / maxRate) * overlayHeight));
image.fillRect(leftX, bottomY - height + 1, Math.max(1, rightX - leftX + 1), height, 18);
}
}
function drawNightscoutCarbMarkers(
image: GrayImage,
bounds: { x: number; y: number; width: number; height: number },
font: BdfFont,
carbEvents: NightscoutState["carbs"],
nowMs: number,
): void {
const windowStartMs = nowMs - NIGHTSCOUT_GRAPH_WINDOW_MS;
const baselineY = bounds.y + bounds.height - 2;
for (const event of carbEvents) {
if (event.timestampMs < windowStartMs || event.timestampMs > nowMs) {
continue;
}
const x = timeToGraphX(bounds, windowStartMs, event.timestampMs);
image.drawLine(x, baselineY, x, baselineY - 6, 150);
drawTextCentered(image, font, x, Math.max(bounds.y + 2, baselineY - 18), `${Math.round(event.carbs)}`, 150, bounds);
}
}
function drawNightscoutBolusMarkers(
image: GrayImage,
bounds: { x: number; y: number; width: number; height: number },
font: BdfFont,
bolusEvents: NightscoutState["boluses"],
nowMs: number,
): void {
const windowStartMs = nowMs - NIGHTSCOUT_GRAPH_WINDOW_MS;
const topY = bounds.y + 1;
for (const event of bolusEvents) {
if (event.timestampMs < windowStartMs || event.timestampMs > nowMs) {
continue;
}
const x = timeToGraphX(bounds, windowStartMs, event.timestampMs);
image.drawLine(x, topY, x, topY + 6, 144);
if (event.insulin >= 1) {
drawTextCentered(
image,
font,
x,
Math.min(bounds.y + bounds.height - font.lineHeight - 1, topY + 8),
formatBolusLabel(event.insulin),
144,
bounds,
);
}
}
}
function drawTextCentered(
image: GrayImage,
font: BdfFont,
centerX: number,
y: number,
text: string,
shade: number,
bounds: { x: number; y: number; width: number; height: number },
): void {
const textWidth = font.measureText(text);
const x = Math.max(bounds.x + 1, Math.min(bounds.x + bounds.width - textWidth - 1, centerX - Math.round(textWidth / 2)));
image.drawText(font, x, y, text, shade);
}
function timeToGraphX(
bounds: { x: number; y: number; width: number; height: number },
windowStartMs: number,
timestampMs: number,
): number {
return (
bounds.x +
Math.round(((timestampMs - windowStartMs) / Math.max(1, NIGHTSCOUT_GRAPH_WINDOW_MS)) * Math.max(1, bounds.width - 1))
);
}
function drawNightscoutReferenceLine(
image: GrayImage,
bounds: { x: number; y: number; width: number; height: number },
minValue: number,
maxValue: number,
value: number,
shade: number,
): void {
const y =
bounds.y +
bounds.height -
1 -
Math.round(((value - minValue) / Math.max(1, maxValue - minValue)) * Math.max(1, bounds.height - 1));
image.drawLine(bounds.x + 1, y, bounds.x + bounds.width - 2, y, shade);
}
class DebugLogLayer implements Layer {
private scrollOffset = 0;
constructor(private readonly getState: () => DashboardPluginState) {}
paint(ctx: LayerContext): GrayImage {
const image = new GrayImage(576, 288, 0);
image.drawRect(12, 12, 552, 264, 52);
image.drawText(ctx.font, 22, 16, "Input debug log", 220);
const logs = this.getState().logLines;
const lineHeight = 14;
const visibleCount = Math.max(1, Math.floor((288 - 64) / lineHeight));
const maxOffset = Math.max(0, logs.length - visibleCount);
this.scrollOffset = Math.max(0, Math.min(this.scrollOffset, maxOffset));
const start = Math.max(0, maxOffset - this.scrollOffset);
const visible = logs.slice(start, start + visibleCount);
for (let index = 0; index < visible.length; index++) {
image.drawText(ctx.font, 22, 42 + index * lineHeight, visible[index]!, 180);
}
image.drawText(ctx.font, 22, 252, "Scroll: browse Double-click: back", 110);
return image;
}
handleInput(event: DashboardInputEvent, ctx: LayerContext): void {
switch (event.type) {
case "scroll-up":
this.scrollOffset += 1;
return;
case "scroll-down":
this.scrollOffset = Math.max(0, this.scrollOffset - 1);
return;
case "double-click":
ctx.stack.pop();
return;
default:
return;
}
}
}
class MusicControllerLayer implements Layer {
constructor(private readonly getState: () => DashboardPluginState) {}
paint(ctx: LayerContext): GrayImage {
const image = new GrayImage(576, 288, 0);
const media = this.getState().media;
image.drawRect(12, 12, 552, 264, 52);
image.drawText(ctx.font, 22, 16, "Music controller", 220);
if (!media.accessEnabled) {
const lines = wrapText(
ctx.font,
"Notification access is required before Android will expose active media sessions to Faceclaw. Click to open settings.",
520,
);
for (let i = 0; i < lines.length; i++) {
image.drawText(ctx.font, 22, 44 + i * 14, lines[i]!, 180);
}
image.drawText(ctx.font, 22, 252, "Click: open settings Double-click: back", 110);
return image;
}
if (!media.available) {
image.drawText(ctx.font, 22, 44, "No active media session.", 180);
image.drawText(ctx.font, 22, 58, "Start playback in another app,", 180);
image.drawText(ctx.font, 22, 72, "then reopen this card.", 180);
image.drawText(ctx.font, 22, 252, "Double-click: back", 110);
return image;
}
image.drawText(ctx.font, 22, 44, media.title || "Unknown title", 220);
image.drawText(ctx.font, 22, 60, media.artist || media.album || "Unknown artist", 180);
image.drawText(ctx.font, 22, 76, media.packageName, 130);
image.drawText(ctx.font, 22, 104, `State: ${playbackLabel(media)}`, 180);
image.drawText(ctx.font, 22, 132, "Click: play/pause", 180);
image.drawText(ctx.font, 22, 146, "Scroll up: previous", 180);
image.drawText(ctx.font, 22, 160, "Scroll down: next", 180);
image.drawText(ctx.font, 22, 252, "Double-click: back", 110);
return image;
}
async handleInput(event: DashboardInputEvent, ctx: LayerContext): Promise<void> {
const media = this.getState().media;
switch (event.type) {
case "click":
if (!media.accessEnabled) {
mediaControllerBridge.openNotificationAccessSettings();
} else if (media.canPlayPause) {
await mediaControllerBridge.playPause();
}
return;
case "scroll-up":
if (media.canSkipPrevious) {
await mediaControllerBridge.skipPrevious();
}
return;
case "scroll-down":
if (media.canSkipNext) {
await mediaControllerBridge.skipNext();
}
return;
case "double-click":
ctx.stack.pop();
return;
default:
return;
}
}
}
class NightscoutLayer implements Layer {
constructor(private readonly getState: () => DashboardPluginState) {}
paint(ctx: LayerContext): GrayImage {
const image = new GrayImage(576, 288, 0);
const nightscout = this.getState().nightscout;
const nowMs = Date.now();
image.drawRect(12, 12, 552, 264, 52);
image.drawText(ctx.font, 22, 16, "Nightscout", 220);
if (!this.getState().nightscoutConfigured || nightscout.configurationMissing) {
image.drawText(ctx.font, 22, 44, "Nightscout needs configuration.", 180);
image.drawText(ctx.font, 22, 62, "Double-click and use Settings", 140);
image.drawText(ctx.font, 22, 78, "Integrations > Nightscout.", 140);
return image;
}
if (!nightscout.available || !nightscout.latest) {
image.drawText(ctx.font, 22, 44, "No Nightscout data available.", 180);
image.drawText(ctx.font, 22, 58, truncateLine(nightscout.status, 60), 140);
image.drawText(ctx.font, 22, 252, "Click: refresh Double-click: back", 110);
return image;
}
const latest = nightscout.latest;
const glucoseText = `${latest.sgv}`;
const glucoseX = 22;
const glucoseWidth = nightscoutLargeFont.measureText(glucoseText);
image.drawText(nightscoutLargeFont, glucoseX, 28, glucoseText, 230);
if (isNightscoutPointStale(latest, nowMs)) {
drawNightscoutValueStrikeThrough(image, glucoseX, 40, glucoseWidth);
}
image.drawText(ctx.font, glucoseX + glucoseWidth + 8, 36, nightscout.units, 140);
const trendText = `Delta ${formatDelta(nightscout.delta)} Trend `;
image.drawText(ctx.font, 22, 62, trendText, 180);
drawDirectionIndicator(image, ctx.font, 22 + ctx.font.measureText(trendText), 62, nightscout.direction, 180);
image.drawText(
ctx.font,
22,
78,
`IOB ${nightscout.iob === null ? "--" : nightscout.iob.toFixed(2)} COB ${nightscout.cob === null ? "--" : formatWholeNumber(nightscout.cob)} Updated ${formatTimestamp(latest.timestampMs)}`,
160,
);
image.drawText(
ctx.font,
22,
94,
`CAGE ${formatAgeShortFromTimestamp(nightscout.cageTimestampMs, nowMs)} Loop ${nightscout.openapsStatusShort}`,
160,
);
image.drawText(ctx.font, 22, 110, `Pump ${truncateLine(nightscout.pumpStatus || "--", 56)}`, 150);
drawNightscoutGraph(image, { x: 22, y: 128, width: 532, height: 96 }, nightscout, nowMs, ctx.font);
image.drawText(ctx.font, 22, 234, "2-hour glucose history with basal / carbs / boluses", 130);
image.drawText(ctx.font, 22, 252, "Click: refresh Double-click: back", 110);
return image;
}
async handleInput(event: DashboardInputEvent, ctx: LayerContext): Promise<void> {
switch (event.type) {
case "click":
await nightscoutBridge.refreshNow();
return;
case "double-click":
ctx.stack.pop();
return;
default:
return;
}
}
}
function formatTimestamp(timestampMs: number): string {
const date = new Date(timestampMs);
return `${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`;
}
function isNightscoutPointStale(point: NightscoutState["latest"], nowMs: number): boolean {
return point !== null && nowMs - point.timestampMs > NIGHTSCOUT_STALE_MS;
}
function drawNightscoutValueStrikeThrough(image: GrayImage, x: number, y: number, width: number): void {
image.drawLine(x, y, x + width, y, 180);
}
+154
View File
@@ -0,0 +1,154 @@
import { ApplicationSettings } from "@nativescript/core";
export type DashboardSlotId = "top-right" | "bottom-left" | "bottom-right";
export type DashboardPluginId = "blank" | "input-debug-log" | "music-controller" | "nightscout";
export type DashboardSlotConfig = Record<DashboardSlotId, DashboardPluginId>;
export type NightscoutSettings = {
siteUrl: string;
apiToken: string;
};
export type SystemCardSettings = {
showFaceclawLogo: boolean;
showBatteryIndicators: boolean;
showAndroidNotifications: boolean;
};
export type SystemCardSettingKey = keyof SystemCardSettings;
export const DEFAULT_SYSTEM_CARD_NAME = "Faceclaw";
const SYSTEM_CARD_NAME_KEY = "dashboard.systemCardName";
const SYSTEM_CARD_SETTING_KEYS: Record<SystemCardSettingKey, string> = {
showFaceclawLogo: "dashboard.systemCard.showFaceclawLogo",
showBatteryIndicators: "dashboard.systemCard.showBatteryIndicators",
showAndroidNotifications: "dashboard.systemCard.showAndroidNotifications",
};
const NIGHTSCOUT_SITE_URL_KEY = "integrations.nightscout.siteUrl";
const NIGHTSCOUT_API_TOKEN_KEY = "integrations.nightscout.apiToken";
const SLOT_KEYS: Record<DashboardSlotId, string> = {
"top-right": "dashboard.slot.topRight",
"bottom-left": "dashboard.slot.bottomLeft",
"bottom-right": "dashboard.slot.bottomRight",
};
const KNOWN_PLUGIN_IDS = new Set<DashboardPluginId>([
"blank",
"input-debug-log",
"music-controller",
"nightscout",
]);
const DEFAULT_SLOT_CONFIG: DashboardSlotConfig = {
"top-right": "input-debug-log",
"bottom-left": "blank",
"bottom-right": "blank",
};
const DEFAULT_SYSTEM_CARD_SETTINGS: SystemCardSettings = {
showFaceclawLogo: true,
showBatteryIndicators: true,
showAndroidNotifications: true,
};
export function getDashboardSlotIds(): DashboardSlotId[] {
return ["top-right", "bottom-left", "bottom-right"];
}
export function getDefaultDashboardSlotConfig(): DashboardSlotConfig {
return { ...DEFAULT_SLOT_CONFIG };
}
export function loadDashboardSlotConfig(): DashboardSlotConfig {
const config = getDefaultDashboardSlotConfig();
for (const slot of getDashboardSlotIds()) {
const stored = ApplicationSettings.getString(SLOT_KEYS[slot], config[slot]);
config[slot] = normalizePluginId(stored, config[slot]);
}
return config;
}
export function saveDashboardSlotPlugin(slot: DashboardSlotId, pluginId: DashboardPluginId): void {
ApplicationSettings.setString(SLOT_KEYS[slot], pluginId);
}
export function saveDashboardSlotConfig(config: DashboardSlotConfig): void {
for (const slot of getDashboardSlotIds()) {
saveDashboardSlotPlugin(slot, config[slot]);
}
}
export function loadSystemCardName(): string {
return normalizeSystemCardName(ApplicationSettings.getString(SYSTEM_CARD_NAME_KEY, DEFAULT_SYSTEM_CARD_NAME));
}
export function saveSystemCardName(name: string): string {
const normalized = normalizeSystemCardName(name);
ApplicationSettings.setString(SYSTEM_CARD_NAME_KEY, normalized);
return normalized;
}
export function loadSystemCardSettings(): SystemCardSettings {
return {
showFaceclawLogo: ApplicationSettings.getBoolean(
SYSTEM_CARD_SETTING_KEYS.showFaceclawLogo,
DEFAULT_SYSTEM_CARD_SETTINGS.showFaceclawLogo,
),
showBatteryIndicators: ApplicationSettings.getBoolean(
SYSTEM_CARD_SETTING_KEYS.showBatteryIndicators,
DEFAULT_SYSTEM_CARD_SETTINGS.showBatteryIndicators,
),
showAndroidNotifications: ApplicationSettings.getBoolean(
SYSTEM_CARD_SETTING_KEYS.showAndroidNotifications,
DEFAULT_SYSTEM_CARD_SETTINGS.showAndroidNotifications,
),
};
}
export function saveSystemCardSetting(key: SystemCardSettingKey, value: boolean): void {
ApplicationSettings.setBoolean(SYSTEM_CARD_SETTING_KEYS[key], value);
}
export function loadNightscoutSettings(): NightscoutSettings {
return {
siteUrl: normalizeNightscoutSiteUrl(ApplicationSettings.getString(NIGHTSCOUT_SITE_URL_KEY, "")),
apiToken: normalizeNightscoutApiToken(ApplicationSettings.getString(NIGHTSCOUT_API_TOKEN_KEY, "")),
};
}
export function saveNightscoutSiteUrl(siteUrl: string): string {
const normalized = normalizeNightscoutSiteUrl(siteUrl);
ApplicationSettings.setString(NIGHTSCOUT_SITE_URL_KEY, normalized);
return normalized;
}
export function saveNightscoutApiToken(apiToken: string): string {
const normalized = normalizeNightscoutApiToken(apiToken);
ApplicationSettings.setString(NIGHTSCOUT_API_TOKEN_KEY, normalized);
return normalized;
}
export function isNightscoutSettingsConfigured(settings = loadNightscoutSettings()): boolean {
return settings.siteUrl.length > 0 && settings.apiToken.length > 0;
}
export function normalizePluginId(
value: string | null | undefined,
fallback: DashboardPluginId = "blank",
): DashboardPluginId {
if (value && KNOWN_PLUGIN_IDS.has(value as DashboardPluginId)) {
return value as DashboardPluginId;
}
return fallback;
}
function normalizeSystemCardName(name: string | null | undefined): string {
const normalized = (name ?? "").replace(/[\x00-\x1f]+/g, " ").replace(/\s+/g, " ").trim();
return normalized;
}
function normalizeNightscoutSiteUrl(siteUrl: string | null | undefined): string {
return (siteUrl ?? "").replace(/[\x00-\x1f]+/g, "").trim().replace(/\/+$/, "");
}
function normalizeNightscoutApiToken(apiToken: string | null | undefined): string {
return (apiToken ?? "").replace(/[\x00-\x1f]+/g, "").trim();
}
+823
View File
@@ -0,0 +1,823 @@
import { G2_LENS_HEIGHT, G2_LENS_WIDTH, GrayImage, imageFromAsciiArt } from "../graphics/image";
import { loadEmbeddedTerminus12, loadEmbeddedTerminus16 } from "../graphics/bdffont";
import { loadPngAsGrayImage } from "../graphics/imagefile";
import { type RawInputEvent } from "../native/faceclaw-communicator";
import { mediaControllerBridge } from "../native/media-controller";
import { nightscoutBridge } from "../native/nightscout";
import { readActiveNotificationIcons } from "../native/notification-icons";
import { readPhoneBatteryState } from "../native/phone-battery";
import { OsEventTypeList, EventSourceType } from "g2-kit/lite";
import {
getDashboardPlugin,
isBlankDashboardPlugin,
listDashboardPlugins,
type DashboardPluginCardBounds,
type DashboardPluginState,
} from "./dashboard-plugins";
import {
DEFAULT_SYSTEM_CARD_NAME,
getDashboardSlotIds,
isNightscoutSettingsConfigured,
loadDashboardSlotConfig,
loadNightscoutSettings,
loadSystemCardSettings,
loadSystemCardName,
saveDashboardSlotPlugin,
saveNightscoutApiToken,
saveNightscoutSiteUrl,
saveSystemCardSetting,
saveSystemCardName,
type DashboardSlotId,
type NightscoutSettings,
type SystemCardSettingKey,
} from "./dashboard-settings";
import { Layer, LayerActions, LayerStack, type DashboardInputEvent, type LayerContext } from "./layers";
import { MenuLayer } from "./menu";
type DashboardCardId = "system" | DashboardSlotId;
export type DashboardBatteryLevels = {
headset: number | null;
headsetCharging: boolean | null;
ring: number | null;
};
let dashboardState = {
logLines: [] as string[],
screenOn: true,
selectedCard: "system" as DashboardCardId,
slotConfig: loadDashboardSlotConfig(),
systemCardName: loadSystemCardName(),
systemCardSettings: loadSystemCardSettings(),
nightscoutSettings: loadNightscoutSettings(),
battery: {
headset: null,
headsetCharging: null,
ring: null,
} as DashboardBatteryLevels,
};
let cachedDashboardLogo: GrayImage | null | undefined;
const dashboardActions: LayerActions = {
disconnect: () => {},
startSystemNameEdit: () => {},
endSystemNameEdit: () => {},
startNightscoutSiteUrlEdit: () => {},
startNightscoutApiTokenEdit: () => {},
endTextSettingEdit: () => {},
};
const dashboardFont = loadEmbeddedTerminus12();
const dashboardSystemFont = loadEmbeddedTerminus16();
const NOTIFICATION_ICON_SIZE = 24;
const SYSTEM_CARD_ITEM_HEIGHT = 38;
const SYSTEM_CARD_ITEM_GAP = 2;
const BATTERY_ITEM_Y_OFFSET = 4;
const EMPTY_BATTERY_ICON = imageFromAsciiArt(
[
" ################## ",
" #................# ",
" #................###",
" #................###",
" #................###",
" #................###",
" #................###",
" #................###",
" #................# ",
" ################## ",
],
120,
);
const BATTERY_BOLT_ICON = imageFromAsciiArt(
[
"....#..",
"...##..",
"..##...",
".######",
"...##..",
"..##...",
"..#....",
],
255,
);
const BATTERY_FILL_X = 3;
const BATTERY_FILL_Y = 2;
const BATTERY_FILL_WIDTH = 14;
const BATTERY_FILL_HEIGHT = 6;
function rawInputEventToInputEvent(event: RawInputEvent): DashboardInputEvent {
if (event.kind === "sys-event") {
if (event.eventType === OsEventTypeList.CLICK_EVENT) {
return {
type: "click",
source: eventSourceToString(event.eventSource),
};
} else if (event.eventType === OsEventTypeList.DOUBLE_CLICK_EVENT) {
return {
type: "double-click",
source: eventSourceToString(event.eventSource),
};
}
} else if (event.kind === "text-click") {
if (event.eventType === OsEventTypeList.SCROLL_BOTTOM_EVENT) {
return { type: "scroll-down" };
} else if (event.eventType === OsEventTypeList.SCROLL_TOP_EVENT) {
return { type: "scroll-up" };
}
}
return {
type: "unknown",
kind: event.kind,
eventSource: event.eventSource,
eventType: event.eventType,
};
}
function eventSourceToString(eventSource: number): "ring" | "left-arm" | "right-arm" {
if (eventSource === EventSourceType.TOUCH_EVENT_FROM_RING) {
return "ring";
} else if (eventSource === EventSourceType.TOUCH_EVENT_FROM_GLASSES_L) {
return "left-arm";
} else if (eventSource === EventSourceType.TOUCH_EVENT_FROM_GLASSES_R) {
return "right-arm";
}
return "ring";
}
export async function receiveInput(event: RawInputEvent): Promise<void> {
const inputEvent = rawInputEventToInputEvent(event);
dashboardState.logLines.push(eventToString(inputEvent));
await dashboardLayers.handleInput(inputEvent);
}
function eventToString(event: DashboardInputEvent): string {
switch (event.type) {
case "click":
return `Click from ${event.source}`;
case "double-click":
return `Double click from ${event.source}`;
case "scroll-up":
return `Scroll up`;
case "scroll-down":
return `Scroll down`;
default:
case "unknown":
return `Unknown event: ${event.kind} ${event.eventSource} ${event.eventType}`;
}
}
export function logToDashboard(message: string): void {
dashboardState.logLines.push(message);
}
export function setDashboardActions(actions: Partial<LayerActions>): void {
dashboardLayers.setActions(actions);
}
export function drawDashboard(): GrayImage {
return dashboardLayers.paint();
}
export function setDashboardSystemCardName(name: string): string {
const savedName = saveSystemCardName(name);
dashboardState.systemCardName = savedName;
return savedName;
}
export function getDashboardSystemCardName(): string {
return dashboardState.systemCardName;
}
export function setDashboardNightscoutSiteUrl(siteUrl: string): string {
const savedUrl = saveNightscoutSiteUrl(siteUrl);
dashboardState.nightscoutSettings = {
...dashboardState.nightscoutSettings,
siteUrl: savedUrl,
};
return savedUrl;
}
export function setDashboardNightscoutApiToken(apiToken: string): string {
const savedToken = saveNightscoutApiToken(apiToken);
dashboardState.nightscoutSettings = {
...dashboardState.nightscoutSettings,
apiToken: savedToken,
};
return savedToken;
}
export function getDashboardNightscoutSettings(): NightscoutSettings {
return { ...dashboardState.nightscoutSettings };
}
export function setDashboardSystemCardSetting(key: SystemCardSettingKey, value: boolean): void {
dashboardState.systemCardSettings = {
...dashboardState.systemCardSettings,
[key]: value,
};
saveSystemCardSetting(key, value);
}
export function setDashboardBatteryLevels(levels: Partial<DashboardBatteryLevels>): void {
dashboardState.battery = {
...dashboardState.battery,
...levels,
};
}
function getDisplayedSystemCardName(): string {
return dashboardState.systemCardName || DEFAULT_SYSTEM_CARD_NAME;
}
type SystemCardFlowItem =
| { type: "battery"; label: string; percentCharge: number; isCharging: boolean }
| { type: "notification"; icon: GrayImage };
function collectBatteryItems(): SystemCardFlowItem[] {
if (!dashboardState.systemCardSettings.showBatteryIndicators) return [];
const phone = readPhoneBatteryState();
const items: SystemCardFlowItem[] = [];
addBatteryItem(items, "Phone", phone.battery, phone.charging);
addBatteryItem(items, "G2", dashboardState.battery.headset, dashboardState.battery.headsetCharging);
addBatteryItem(items, "R1", dashboardState.battery.ring, null);
return items;
}
function addBatteryItem(
items: SystemCardFlowItem[],
label: string,
percentCharge: number | null,
isCharging: boolean | null,
): void {
if (percentCharge === null || !Number.isFinite(percentCharge)) return;
items.push({
type: "battery",
label,
percentCharge,
isCharging: Boolean(isCharging),
});
}
function drawBatteryFlowItem(image: GrayImage, x: number, y: number, item: Extract<SystemCardFlowItem, { type: "battery" }>): void {
const itemWidth = systemCardFlowItemWidth(item);
const labelX = x + Math.max(0, ((itemWidth - dashboardFont.measureText(item.label)) / 2) | 0);
image.drawText(dashboardFont, labelX, y + BATTERY_ITEM_Y_OFFSET, item.label, 150);
const battery = drawBattery(item.percentCharge, item.isCharging);
image.bitBlt(battery, x + ((itemWidth - battery.width) / 2) | 0, y + 16 + BATTERY_ITEM_Y_OFFSET);
}
function drawBattery(percentCharge: number, isCharging: boolean): GrayImage {
const icon = new GrayImage(EMPTY_BATTERY_ICON.width, EMPTY_BATTERY_ICON.height, 0);
icon.bitBlt(EMPTY_BATTERY_ICON, 0, 0);
const clamped = Math.max(0, Math.min(100, percentCharge));
const fillWidth = Math.round((BATTERY_FILL_WIDTH * clamped) / 100);
icon.fillRect(BATTERY_FILL_X, BATTERY_FILL_Y, fillWidth, BATTERY_FILL_HEIGHT, 190);
if (isCharging) {
overlayImage(icon, BATTERY_BOLT_ICON, 7, 1);
}
return icon;
}
function overlayImage(target: GrayImage, source: GrayImage, dx: number, dy: number): void {
for (let y = 0; y < source.height; y++) {
for (let x = 0; x < source.width; x++) {
const value = source.pixels[y * source.width + x] ?? 0;
if (value > 0) {
target.setPixel(dx + x, dy + y, value);
}
}
}
}
const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
const WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
function formatDashboardDate(now: Date): string {
return `${WEEKDAYS[now.getDay()]} ${MONTHS[now.getMonth()]} ${now.getDate()} ${pad2(now.getHours())}:${pad2(now.getMinutes())}`;
}
function pad2(value: number): string {
return String(value).padStart(2, "0");
}
function getDashboardLogo(): GrayImage | null {
if (cachedDashboardLogo !== undefined) {
return cachedDashboardLogo;
}
try {
cachedDashboardLogo = loadPngAsGrayImage("images/faceclaw-logo-dashboard.png");
} catch {
cachedDashboardLogo = null;
}
return cachedDashboardLogo;
}
function drawSystemCardFlowItems(image: GrayImage, bounds: DashboardPluginCardBounds): void {
const left = bounds.x + 10;
const top = bounds.y + 84;
const right = bounds.x + bounds.width - 10;
const bottom = bounds.y + bounds.height - 6;
const items = collectBatteryItems();
if (dashboardState.systemCardSettings.showAndroidNotifications) {
const maxNotificationIcons = Math.max(0, ((right - left) / Math.max(1, NOTIFICATION_ICON_SIZE + SYSTEM_CARD_ITEM_GAP)) | 0) * 2;
for (const icon of readActiveNotificationIcons(maxNotificationIcons)) {
items.push({ type: "notification", icon });
}
}
let itemX = left;
let itemY = top;
for (const item of items) {
const itemWidth = systemCardFlowItemWidth(item);
if (itemX > left && itemX + itemWidth > right) {
itemX = left;
itemY += SYSTEM_CARD_ITEM_HEIGHT + SYSTEM_CARD_ITEM_GAP;
}
if (itemY + SYSTEM_CARD_ITEM_HEIGHT > bottom) {
break;
}
if (item.type === "battery") {
drawBatteryFlowItem(image, itemX, itemY, item);
} else {
image.bitBlt(
item.icon,
itemX,
itemY + ((SYSTEM_CARD_ITEM_HEIGHT - NOTIFICATION_ICON_SIZE) / 2) | 0,
);
}
itemX += itemWidth + SYSTEM_CARD_ITEM_GAP;
}
}
function systemCardFlowItemWidth(item: SystemCardFlowItem): number {
if (item.type === "notification") {
return NOTIFICATION_ICON_SIZE;
}
return Math.max(EMPTY_BATTERY_ICON.width, dashboardFont.measureText(item.label));
}
class DashboardLayer implements Layer {
paint(): GrayImage {
if (!dashboardState.screenOn) {
return new GrayImage(G2_LENS_WIDTH, G2_LENS_HEIGHT, 0);
}
const image = new GrayImage(G2_LENS_WIDTH, G2_LENS_HEIGHT, 0);
const now = new Date();
const logo = getDashboardLogo();
const pluginState = getPluginState();
const systemBounds = getCardBounds("system");
this.drawCardBorder(image, systemBounds, dashboardState.selectedCard === "system");
if (logo && dashboardState.systemCardSettings.showFaceclawLogo) {
image.bitBlt(logo, systemBounds.x + 10, systemBounds.y + 10);
}
const infoX = logo && dashboardState.systemCardSettings.showFaceclawLogo ? systemBounds.x + 92 : systemBounds.x + 10;
image.drawText(dashboardSystemFont, infoX, systemBounds.y + 10, getDisplayedSystemCardName(), 200);
image.drawText(dashboardSystemFont, infoX, systemBounds.y + 32, formatDashboardDate(now), 200);
drawSystemCardFlowItems(image, systemBounds);
for (const slot of getDashboardSlotIds()) {
const bounds = getCardBounds(slot);
const pluginId = dashboardState.slotConfig[slot];
if (!isBlankDashboardPlugin(pluginId)) {
this.drawCardBorder(image, bounds, dashboardState.selectedCard === slot);
}
getDashboardPlugin(pluginId).renderCard({
image,
bounds,
selected: dashboardState.selectedCard === slot,
font: dashboardFont,
state: pluginState,
});
}
return image;
}
handleInput(event: DashboardInputEvent, ctx: { stack: LayerStack }): void {
if (!dashboardState.screenOn) {
if (event.type === "double-click") {
dashboardState.selectedCard = "system";
dashboardState.screenOn = true;
}
return;
}
if (event.type === "scroll-up") {
cycleSelection(-1);
return;
}
if (event.type === "scroll-down") {
cycleSelection(1);
return;
}
if (event.type === "click") {
if (dashboardState.selectedCard === "system") {
ctx.stack.push(createRootMenuLayer());
} else {
const pluginId = dashboardState.slotConfig[dashboardState.selectedCard];
if (pluginId === "nightscout" && !isNightscoutSettingsConfigured(dashboardState.nightscoutSettings)) {
ctx.stack.push(createNightscoutSettingsMenuLayer());
return;
}
const layer = getDashboardPlugin(pluginId).createFullscreenLayer?.(
getPluginState,
);
if (layer) {
ctx.stack.push(layer);
}
}
return;
}
if (event.type === "double-click") {
dashboardState.selectedCard = "system";
dashboardState.screenOn = false;
}
}
private drawCardBorder(image: GrayImage, bounds: DashboardPluginCardBounds, selected: boolean): void {
if (selected) {
image.drawRect(bounds.x, bounds.y, bounds.width, bounds.height, 60);
}
}
}
function createRootMenuLayer(): MenuLayer {
return new MenuLayer(
"Menu",
[
{
label: "About",
onSelect: (ctx) => {
ctx.stack.push(new AboutLayer());
},
},
{
label: "Settings",
onSelect: (ctx) => {
ctx.stack.push(createSettingsMenuLayer());
},
},
{
label: "Quit / Disconnect",
onSelect: async (ctx) => {
ctx.stack.clearToBase();
await ctx.actions.disconnect();
},
},
],
{
x: 16,
y: 24,
width: 252,
height: 180,
},
);
}
function createSettingsMenuLayer(): MenuLayer {
return new MenuLayer(
"Settings",
[
{
label: "Dashboard",
onSelect: (ctx) => {
ctx.stack.push(createDashboardSettingsMenuLayer());
},
},
{
label: "Integrations",
onSelect: (ctx) => {
ctx.stack.push(createIntegrationsMenuLayer());
},
},
],
{
x: 16,
y: 24,
width: 252,
height: 180,
},
);
}
function createDashboardSettingsMenuLayer(): MenuLayer {
return new MenuLayer(
"Dashboard",
[
{
label: "System Card",
onSelect: (ctx) => {
ctx.stack.push(createSystemCardSettingsMenuLayer());
},
},
...getDashboardSlotIds().map((slot) => ({
label: slotMenuLabel(slot),
onSelect: (ctx) => {
ctx.stack.push(createSlotPickerMenu(slot));
},
render: ({ image, x, y }) => {
image.drawText(dashboardFont, x, y + 4, `${slotMenuLabel(slot)}: ${pluginLabelForSlot(slot)}`, 200);
},
})),
],
{
x: 16,
y: 24,
width: 252,
height: 180,
},
);
}
function createSystemCardSettingsMenuLayer(): MenuLayer {
return new MenuLayer(
"System Card",
[
{
label: "Name",
onSelect: (ctx) => {
void ctx.actions.startSystemNameEdit();
ctx.stack.push(new EditSystemNameLayer());
},
render: ({ image, x, y }) => {
image.drawText(dashboardFont, x, y + 4, `Name: ${getDisplayedSystemCardName()}`, 200);
},
},
createSystemCardToggleItem("Show Faceclaw Logo", "showFaceclawLogo"),
createSystemCardToggleItem("Show Battery Indicators", "showBatteryIndicators"),
createSystemCardToggleItem("Show Android Notifications", "showAndroidNotifications"),
],
{
x: 308,
y: 24,
width: 252,
height: 180,
},
true,
);
}
function createSystemCardToggleItem(label: string, key: SystemCardSettingKey) {
return {
label,
onSelect: () => {
setDashboardSystemCardSetting(key, !dashboardState.systemCardSettings[key]);
},
render: ({ image, x, y, width, selected }: { image: GrayImage; x: number; y: number; width: number; selected: boolean }) => {
drawToggleMenuItem(image, x, y, width, label, dashboardState.systemCardSettings[key], selected);
},
};
}
function drawToggleMenuItem(image: GrayImage, x: number, y: number, width: number, label: string, enabled: boolean, selected: boolean): void {
const switchWidth = 34;
const switchHeight = 16;
const switchX = x + width - switchWidth - 2;
const switchY = y + 2;
image.drawText(dashboardFont, x, y + 4, label, 200);
const offFill = selected ? 0 : 18;
image.fillRoundedRect(switchX, switchY, switchWidth, switchHeight, enabled ? 70 : offFill, 8);
image.drawRoundedRect(switchX, switchY, switchWidth, switchHeight, enabled ? 130 : 55, 8);
const knobSize = 12;
const knobX = enabled ? switchX + switchWidth - knobSize - 2 : switchX + 2;
image.fillRoundedRect(knobX, switchY + 2, knobSize, knobSize, enabled ? 230 : selected ? 170 : 90, 6);
}
function createIntegrationsMenuLayer(): MenuLayer {
return new MenuLayer(
"Integrations",
[
{
label: "Nightscout",
onSelect: (ctx) => {
ctx.stack.push(createNightscoutSettingsMenuLayer());
},
},
],
{
x: 16,
y: 24,
width: 252,
height: 180,
},
);
}
function createNightscoutSettingsMenuLayer(): MenuLayer {
return new MenuLayer(
"Nightscout",
[
{
label: "Site URL",
onSelect: (ctx) => {
void ctx.actions.startNightscoutSiteUrlEdit();
ctx.stack.push(new EditTextSettingLayer("Edit Nightscout URL", () => dashboardState.nightscoutSettings.siteUrl || "(empty)"));
},
render: ({ image, x, y }) => {
image.drawText(dashboardFont, x, y + 4, `URL: ${truncateSetting(dashboardState.nightscoutSettings.siteUrl)}`, 200);
},
},
{
label: "API token",
onSelect: (ctx) => {
void ctx.actions.startNightscoutApiTokenEdit();
ctx.stack.push(new EditTextSettingLayer("Edit API token", () => maskToken(dashboardState.nightscoutSettings.apiToken)));
},
render: ({ image, x, y }) => {
image.drawText(dashboardFont, x, y + 4, `Token: ${maskToken(dashboardState.nightscoutSettings.apiToken)}`, 200);
},
},
],
{
x: 16,
y: 24,
width: 252,
height: 180,
},
);
}
class EditSystemNameLayer implements Layer {
paint(): GrayImage {
const image = new GrayImage(G2_LENS_WIDTH, G2_LENS_HEIGHT, 0);
image.drawRect(12, 12, G2_LENS_WIDTH - 24, G2_LENS_HEIGHT - 24, 52);
image.drawText(dashboardFont, 22, 16, "Edit dashboard name", 220);
image.drawText(dashboardFont, 22, 52, "Look at the phone app", 200);
image.drawText(dashboardFont, 22, 70, "to type a new name.", 200);
image.drawText(dashboardSystemFont, 22, 110, getDisplayedSystemCardName(), 220);
image.drawText(dashboardFont, 22, 252, "Double-click to go back", 110);
return image;
}
handleInput(event: DashboardInputEvent, ctx: LayerContext): void {
if (event.type === "double-click") {
void ctx.actions.endSystemNameEdit();
void ctx.actions.endTextSettingEdit();
ctx.stack.pop();
}
}
}
class EditTextSettingLayer implements Layer {
constructor(
private readonly title: string,
private readonly value: () => string,
) {}
paint(): GrayImage {
const image = new GrayImage(G2_LENS_WIDTH, G2_LENS_HEIGHT, 0);
image.drawRect(12, 12, G2_LENS_WIDTH - 24, G2_LENS_HEIGHT - 24, 52);
image.drawText(dashboardFont, 22, 16, this.title, 220);
image.drawText(dashboardFont, 22, 52, "Look at the phone app", 200);
image.drawText(dashboardFont, 22, 70, "to type a value.", 200);
image.drawText(dashboardFont, 22, 110, truncateSetting(this.value(), 52), 220);
image.drawText(dashboardFont, 22, 252, "Double-click to go back", 110);
return image;
}
handleInput(event: DashboardInputEvent, ctx: LayerContext): void {
if (event.type === "double-click") {
void ctx.actions.endTextSettingEdit();
ctx.stack.pop();
}
}
}
function createSlotPickerMenu(slot: DashboardSlotId): MenuLayer {
return new MenuLayer(
slotMenuLabel(slot),
listDashboardPlugins().map((plugin) => ({
label: plugin.label,
onSelect: (ctx) => {
dashboardState.slotConfig[slot] = plugin.id;
saveDashboardSlotPlugin(slot, plugin.id);
if (dashboardState.selectedCard === slot && isBlankDashboardPlugin(plugin.id)) {
dashboardState.selectedCard = "system";
}
ctx.stack.pop();
},
render: ({ image, x, y }) => {
const selected = dashboardState.slotConfig[slot] === plugin.id ? " *" : "";
image.drawText(dashboardFont, x, y + 4, `${plugin.label}${selected}`, 200);
},
})),
{
x: 16,
y: 24,
width: 252,
height: 180,
},
);
}
class AboutLayer implements Layer {
paint(): GrayImage {
const image = new GrayImage(G2_LENS_WIDTH, G2_LENS_HEIGHT, 0);
const logo = getDashboardLogo();
image.drawRect(12, 12, G2_LENS_WIDTH - 24, G2_LENS_HEIGHT - 24, 52);
image.drawText(dashboardFont, 22, 16, "About Faceclaw", 220);
if (logo) {
image.bitBlt(logo, 22, 42);
}
image.drawText(dashboardFont, 108, 48, "Faceclaw", 220);
image.drawText(dashboardFont, 108, 64, "Dashboard prototype", 180);
const aboutLines = [
"A lobster on top of a smiley face.",
"Perching on the faces of giants.",
"",
"System card opens menus.",
"Swipe cycles dashboard cards.",
"Plugin cards open fullscreen views.",
];
for (let index = 0; index < aboutLines.length; index++) {
image.drawText(dashboardFont, 22, 128 + index * 14, aboutLines[index]!, 180);
}
image.drawText(dashboardFont, 22, 252, "Double-click to go back", 110);
return image;
}
handleInput(event: DashboardInputEvent, ctx: { stack: LayerStack }): void {
if (event.type === "double-click") {
ctx.stack.pop();
}
}
}
function getPluginState(): DashboardPluginState {
return {
logLines: dashboardState.logLines,
media: mediaControllerBridge.snapshot(),
nightscout: nightscoutBridge.snapshot(),
nightscoutConfigured: isNightscoutSettingsConfigured(dashboardState.nightscoutSettings),
};
}
function getCardBounds(card: DashboardCardId): DashboardPluginCardBounds {
switch (card) {
case "system":
return { x: 0, y: 0, width: G2_LENS_WIDTH / 2 - 2, height: G2_LENS_HEIGHT / 2 - 2 };
case "top-right":
return {
x: G2_LENS_WIDTH / 2 + 2,
y: 0,
width: G2_LENS_WIDTH / 2 - 2,
height: G2_LENS_HEIGHT / 2 - 2,
};
case "bottom-left":
return {
x: 0,
y: G2_LENS_HEIGHT / 2 + 2,
width: G2_LENS_WIDTH / 2 - 2,
height: G2_LENS_HEIGHT / 2 - 2,
};
case "bottom-right":
return {
x: G2_LENS_WIDTH / 2 + 2,
y: G2_LENS_HEIGHT / 2 + 2,
width: G2_LENS_WIDTH / 2 - 2,
height: G2_LENS_HEIGHT / 2 - 2,
};
}
}
function cycleSelection(direction: -1 | 1): void {
const order: DashboardCardId[] = [
"system",
...getDashboardSlotIds().filter((slot) => !isBlankDashboardPlugin(dashboardState.slotConfig[slot])),
];
const index = order.indexOf(dashboardState.selectedCard);
const currentIndex = index >= 0 ? index : 0;
dashboardState.selectedCard = order[(currentIndex + direction + order.length) % order.length]!;
}
function slotMenuLabel(slot: DashboardSlotId): string {
switch (slot) {
case "top-right":
return "Top-right slot";
case "bottom-left":
return "Bottom-left slot";
case "bottom-right":
return "Bottom-right slot";
}
}
function pluginLabelForSlot(slot: DashboardSlotId): string {
return getDashboardPlugin(dashboardState.slotConfig[slot]).label;
}
function truncateSetting(value: string, maxLength = 22): string {
const text = value || "(empty)";
return text.length <= maxLength ? text : `${text.slice(0, Math.max(0, maxLength - 3))}...`;
}
function maskToken(token: string): string {
if (!token) return "(empty)";
return token.length <= 6 ? "******" : `${token.slice(0, 2)}...${token.slice(-4)}`;
}
const dashboardLayers = new LayerStack(new DashboardLayer(), dashboardFont, dashboardActions);
+90
View File
@@ -0,0 +1,90 @@
import { G2_LENS_HEIGHT, G2_LENS_WIDTH, GrayImage } from "../graphics/image";
import { BdfFont } from "../graphics/bdffont";
export type DashboardInputEvent =
| { type: "click"; source: "ring" | "left-arm" | "right-arm" }
| { type: "double-click"; source: "ring" | "left-arm" | "right-arm" }
| { type: "scroll-up" }
| { type: "scroll-down" }
| { type: "unknown"; kind: string; eventSource: number; eventType: number };
export type LayerActions = {
disconnect: () => Promise<void> | void;
startSystemNameEdit: () => Promise<void> | void;
endSystemNameEdit: () => Promise<void> | void;
startNightscoutSiteUrlEdit: () => Promise<void> | void;
startNightscoutApiTokenEdit: () => Promise<void> | void;
endTextSettingEdit: () => Promise<void> | void;
};
export type PaintBelow = () => GrayImage;
export interface LayerContext {
readonly stack: LayerStack;
readonly font: BdfFont;
readonly actions: LayerActions;
}
export interface Layer {
readonly paintOverBase?: boolean;
paint(ctx: LayerContext, paintBelow: PaintBelow): GrayImage;
handleInput(event: DashboardInputEvent, ctx: LayerContext): Promise<void> | void;
}
export class LayerStack {
private readonly layers: Layer[];
private readonly ctx: LayerContext;
constructor(baseLayer: Layer, font: BdfFont, actions: LayerActions) {
this.layers = [baseLayer];
this.ctx = {
stack: this,
font,
actions,
};
}
push(layer: Layer): void {
this.layers.push(layer);
}
pop(): void {
if (this.layers.length > 1) {
this.layers.pop();
}
}
clearToBase(): void {
this.layers.splice(1);
}
setActions(actions: Partial<LayerActions>): void {
Object.assign(this.ctx.actions, actions);
}
paint(): GrayImage {
return this.paintLayer(this.layers.length - 1);
}
async handleInput(event: DashboardInputEvent): Promise<void> {
await this.layers[this.layers.length - 1]!.handleInput(event, this.ctx);
}
private paintLayer(index: number): GrayImage {
const layer = this.layers[index]!;
let cachedBelow: GrayImage | null = null;
return layer.paint(this.ctx, () => {
if (cachedBelow) {
return cachedBelow;
}
if (index <= 0) {
cachedBelow = new GrayImage(G2_LENS_WIDTH, G2_LENS_HEIGHT, 0);
} else if (layer.paintOverBase) {
cachedBelow = this.paintLayer(0);
} else {
cachedBelow = this.paintLayer(index - 1);
}
return cachedBelow;
});
}
}
+136
View File
@@ -0,0 +1,136 @@
import { GrayImage } from "../graphics/image";
import { wrapText } from "../graphics/textwrap";
import { DashboardInputEvent, Layer, LayerContext, PaintBelow } from "./layers";
const DEFAULT_MENU_X = 48;
const DEFAULT_MENU_Y = 24;
const DEFAULT_MENU_WIDTH = 480;
const DEFAULT_MENU_HEIGHT = 240;
const MENU_TITLE_HEIGHT = 24;
const MENU_ROW_HEIGHT = 28;
export type MenuLayout = {
x: number;
y: number;
width: number;
height: number;
};
export type MenuItemRenderArgs = {
image: GrayImage;
x: number;
y: number;
width: number;
height: number;
selected: boolean;
text: string;
ctx: LayerContext;
};
export type MenuItem = {
label: string;
onSelect: (ctx: LayerContext, menu: MenuLayer) => Promise<void> | void;
render?: (args: MenuItemRenderArgs) => void;
};
export class MenuLayer implements Layer {
private selectedIndex = 0;
constructor(
private readonly title: string,
private readonly items: MenuItem[],
private readonly layout: MenuLayout = {
x: DEFAULT_MENU_X,
y: DEFAULT_MENU_Y,
width: DEFAULT_MENU_WIDTH,
height: DEFAULT_MENU_HEIGHT,
},
public readonly paintOverBase = false,
) {}
paint(ctx: LayerContext, paintBelow: PaintBelow): GrayImage {
const { x, y, width, height } = this.layout;
const image = paintBelow();
image.fillRoundedRect(x, y, width, height, 0);
image.drawRoundedRect(x, y, width, height, 72);
image.drawText(ctx.font, x + 18, y + 10, this.title, 220);
const bodyY = y + MENU_TITLE_HEIGHT + 12;
for (let index = 0; index < this.items.length; index++) {
const item = this.items[index]!;
const y = bodyY + index * MENU_ROW_HEIGHT;
const selected = index === this.selectedIndex;
if (selected) {
image.fillRoundedRect(x + 12, y - 2, width - 24, MENU_ROW_HEIGHT - 4, 18);
image.drawRoundedRect(x + 12, y - 2, width - 24, MENU_ROW_HEIGHT - 4, 45);
}
if (item.render) {
item.render({
image,
x: x + 22,
y,
width: width - 44,
height: MENU_ROW_HEIGHT - 4,
selected,
text: item.label,
ctx,
});
} else {
image.drawText(ctx.font, x + 22, y + 4, item.label, selected ? 255 : 200);
}
}
return image;
}
async handleInput(event: DashboardInputEvent, ctx: LayerContext): Promise<void> {
if (!this.items.length) {
if (event.type === "double-click") {
ctx.stack.pop();
}
return;
}
switch (event.type) {
case "scroll-up":
this.selectedIndex = (this.selectedIndex + this.items.length - 1) % this.items.length;
return;
case "scroll-down":
this.selectedIndex = (this.selectedIndex + 1) % this.items.length;
return;
case "double-click":
ctx.stack.pop();
return;
case "click":
await this.items[this.selectedIndex]!.onSelect(ctx, this);
return;
default:
return;
}
}
}
export class TextPageLayer implements Layer {
constructor(
private readonly title: string,
private readonly body: string,
) {}
paint(ctx: LayerContext): GrayImage {
const image = new GrayImage(576, 288, 0);
image.drawText(ctx.font, 18, 14, this.title, 220);
image.drawRect(12, 12, 552, 264, 52);
const wrapped = wrapText(ctx.font, this.body, 520);
for (let index = 0; index < wrapped.length; index++) {
image.drawText(ctx.font, 24, 42 + index * 14, wrapped[index]!, 190);
}
image.drawText(ctx.font, 24, 252, "Double-click to go back", 110);
return image;
}
handleInput(event: DashboardInputEvent, ctx: LayerContext): void {
if (event.type === "double-click") {
ctx.stack.pop();
}
}
}