Initial publishable release
No files matched your search
@@ -0,0 +1,19 @@
|
||||
root = true
|
||||
|
||||
[*]
|
||||
end_of_line = lf
|
||||
insert_final_newline = true
|
||||
trim_trailing_whitespace = true
|
||||
charset = utf-8
|
||||
|
||||
[*.json]
|
||||
indent_style = space
|
||||
indent_size = 2
|
||||
|
||||
[*.js]
|
||||
indent_style = space
|
||||
indent_size = 2
|
||||
|
||||
[*.ts]
|
||||
indent_style = space
|
||||
indent_size = 2
|
||||
@@ -0,0 +1,29 @@
|
||||
# NativeScript
|
||||
hooks/
|
||||
node_modules/
|
||||
platforms/
|
||||
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
|
||||
# General
|
||||
.DS_Store
|
||||
.AppleDouble
|
||||
.LSOverride
|
||||
.idea
|
||||
.cloud
|
||||
.project
|
||||
tmp/
|
||||
typings/
|
||||
.gradle-cursor
|
||||
|
||||
# Visual Studio Code
|
||||
.vscode/*
|
||||
!.vscode/settings.json
|
||||
!.vscode/tasks.json
|
||||
!.vscode/launch.json
|
||||
!.vscode/extensions.json
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"recommendations": ["nativescript.nativescript"]
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
// You can add your native dependencies here
|
||||
dependencies {
|
||||
// implementation 'androidx.multidex:multidex:2.0.1'
|
||||
}
|
||||
|
||||
android {
|
||||
compileSdkVersion 35
|
||||
buildToolsVersion "35"
|
||||
// ndkVersion ""
|
||||
|
||||
defaultConfig {
|
||||
minSdkVersion 24
|
||||
targetSdkVersion 35
|
||||
|
||||
// Version Information
|
||||
versionCode 1
|
||||
versionName "1.0.0"
|
||||
|
||||
generatedDensities = []
|
||||
}
|
||||
|
||||
aaptOptions {
|
||||
additionalParameters "--no-version-vectors"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
// this configurations is loaded before building plugins, as well as before building
|
||||
// the app - this is where you can apply global settings and overrides
|
||||
|
||||
project.ext {
|
||||
// androidXAppCompat = "1.4.1"
|
||||
// androidXExifInterface = "1.3.3"
|
||||
// androidXFragment = "1.4.1"
|
||||
// androidXMaterial = "1.5.0"
|
||||
// androidXMultidex = "2.0.1"
|
||||
// androidXTransition = "1.4.1"
|
||||
// androidXViewPager = "1.0.0"
|
||||
|
||||
// useKotlin = true
|
||||
// kotlinVersion = "1.6.0"
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
package="__PACKAGE__">
|
||||
|
||||
<supports-screens
|
||||
android:smallScreens="true"
|
||||
android:normalScreens="true"
|
||||
android:largeScreens="true"
|
||||
android:xlargeScreens="true"/>
|
||||
|
||||
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
|
||||
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
|
||||
<uses-permission android:name="android.permission.INTERNET"/>
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
|
||||
<uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30"/>
|
||||
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" android:maxSdkVersion="30"/>
|
||||
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" android:maxSdkVersion="30"/>
|
||||
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT"/>
|
||||
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" android:usesPermissionFlags="neverForLocation"/>
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_CONNECTED_DEVICE"/>
|
||||
|
||||
<application
|
||||
android:name="com.tns.NativeScriptApplication"
|
||||
android:allowBackup="true"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:label="@string/app_name"
|
||||
android:theme="@style/AppTheme"
|
||||
android:hardwareAccelerated="true">
|
||||
|
||||
<activity
|
||||
android:name="com.tns.NativeScriptActivity"
|
||||
android:label="@string/title_activity_kimera"
|
||||
android:configChanges="keyboard|keyboardHidden|orientation|screenSize|smallestScreenSize|screenLayout|locale|uiMode"
|
||||
android:theme="@style/LaunchScreenTheme"
|
||||
android:hardwareAccelerated="true"
|
||||
android:launchMode="singleTask"
|
||||
android:exported="true">
|
||||
|
||||
<meta-data android:name="SET_THEME_ON_LAUNCH" android:resource="@style/AppTheme" />
|
||||
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
<activity android:name="com.tns.ErrorReportActivity"/>
|
||||
<service
|
||||
android:name="com.faceclaw.app.FaceclawForegroundService"
|
||||
android:enabled="true"
|
||||
android:exported="false"
|
||||
android:foregroundServiceType="connectedDevice" />
|
||||
<service
|
||||
android:name="com.faceclaw.app.FaceclawMediaNotificationListenerService"
|
||||
android:enabled="true"
|
||||
android:exported="false"
|
||||
android:label="@string/app_name"
|
||||
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
|
||||
<intent-filter>
|
||||
<action android:name="android.service.notification.NotificationListenerService" />
|
||||
</intent-filter>
|
||||
</service>
|
||||
</application>
|
||||
</manifest>
|
||||
@@ -0,0 +1,70 @@
|
||||
package com.faceclaw.app;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import android.util.Log;
|
||||
|
||||
public final class BleImageOptimizer {
|
||||
private BleImageOptimizer() {}
|
||||
private static final String TAG = "BleImageOptimizer";
|
||||
|
||||
/**
|
||||
* Split an image into fragments (packets), taking advantage of the fact that each packet can declare
|
||||
* a logical size longer than its byte payload to get free trailing zero-padding.
|
||||
*
|
||||
* Each fragment's logical size stays within maxFragmentSize, while trailing zeros inside that span can
|
||||
* be omitted from the payload.
|
||||
*/
|
||||
public static List<BleProtocol.ImageFragment> planImageFragments(byte[] bmp, int maxFragmentSize) {
|
||||
return planImageFragments(bmp, maxFragmentSize, false);
|
||||
}
|
||||
|
||||
public static List<BleProtocol.ImageFragment> planImageFragments(
|
||||
byte[] bmp,
|
||||
int maxFragmentSize,
|
||||
boolean reserveFinalByte
|
||||
) {
|
||||
if (bmp == null || bmp.length == 0) {
|
||||
return Collections.singletonList(new BleProtocol.ImageFragment(0, new byte[0], 0));
|
||||
}
|
||||
if (maxFragmentSize <= 0) {
|
||||
throw new IllegalArgumentException("maxFragmentSize must be positive");
|
||||
}
|
||||
|
||||
final int bulkLength = reserveFinalByte ? bmp.length - 1 : bmp.length;
|
||||
final int fragmentCount = ((bulkLength + maxFragmentSize - 1) / maxFragmentSize)
|
||||
+ (bulkLength < bmp.length ? 1 : 0);
|
||||
final List<BleProtocol.ImageFragment> fragments = new ArrayList<>(fragmentCount);
|
||||
for (int index = 0; index * maxFragmentSize < bulkLength; index++) {
|
||||
int start = index * maxFragmentSize;
|
||||
int end = Math.min(start + maxFragmentSize, bulkLength);
|
||||
fragments.add(buildFragment(index, bmp, start, end));
|
||||
}
|
||||
if (bulkLength < bmp.length) {
|
||||
fragments.add(new BleProtocol.ImageFragment(
|
||||
fragments.size(),
|
||||
Arrays.copyOfRange(bmp, bulkLength, bmp.length),
|
||||
bmp.length - bulkLength
|
||||
));
|
||||
}
|
||||
Log.i(TAG, "planImageFragments: fragments=" + fragments.size() + ", bmp.length=" + bmp.length + ", maxFragmentSize=" + maxFragmentSize);
|
||||
return fragments;
|
||||
}
|
||||
|
||||
private static BleProtocol.ImageFragment buildFragment(int index, byte[] bmp, int start, int end) {
|
||||
int dataEnd = end;
|
||||
while (dataEnd > start && bmp[dataEnd - 1] == 0) {
|
||||
dataEnd -= 1;
|
||||
}
|
||||
if (dataEnd == start) {
|
||||
return new BleProtocol.ImageFragment(index, new byte[0], end - start);
|
||||
}
|
||||
return new BleProtocol.ImageFragment(
|
||||
index,
|
||||
Arrays.copyOfRange(bmp, start, dataEnd),
|
||||
end - start
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,480 @@
|
||||
package com.faceclaw.app;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* BleProtocol: Functions for generating and parsing messages when speaking to
|
||||
* the Even Realities G2. Does _not_ include code for actually sending anything;
|
||||
* for that, see FaceclawBleCommunicator.
|
||||
*
|
||||
* Most message formats are protobufs. For schemas, check g2-kit-unofficial.
|
||||
*/
|
||||
public class BleProtocol {
|
||||
public static final String WRITE_CHAR_UUID = "00002760-08c2-11e1-9073-0e8ac72e5401";
|
||||
public static final String NOTIFY_CHAR_UUID = "00002760-08c2-11e1-9073-0e8ac72e5402";
|
||||
public static final String RENDER_NOTIFY_UUID = "00002760-08c2-11e1-9073-0e8ac72e6402";
|
||||
|
||||
public static final byte[] PRELUDE_F5872 = new byte[] {
|
||||
(byte) 0xaa, 0x21, (byte) 0x92, 0x13, 0x01, 0x01, 0x01, 0x20,
|
||||
0x08, 0x02, 0x10, (byte) 0x9c, 0x01, 0x22, 0x0a, 0x1a,
|
||||
0x08, 0x12, 0x06, 0x12, 0x04, 0x08, 0x00, 0x10, 0x00,
|
||||
(byte) 0xa1, 0x42
|
||||
};
|
||||
|
||||
public static final int PRELUDE_ACK_SID = 0x01;
|
||||
public static final int PRELUDE_ACK_MAGIC = 156;
|
||||
public static final int SID_EVENHUB = 0xe0;
|
||||
public static final int SID_UI_SETTING = 0x09;
|
||||
public static final int FLAG_REQUEST = 0x20;
|
||||
public static final int FLAG_NOTIFY = 0x01;
|
||||
public static final int FLAG_NOTIFY_ALT = 0x06;
|
||||
|
||||
public static final int EVENT_CLICK = 0;
|
||||
public static final int EVENT_SCROLL_TOP = 1;
|
||||
public static final int EVENT_SCROLL_BOTTOM = 2;
|
||||
public static final int EVENT_DOUBLE_CLICK = 3;
|
||||
public static final int EVENT_FOREGROUND_ENTER = 4;
|
||||
public static final int EVENT_FOREGROUND_EXIT = 5;
|
||||
public static final int EVENT_ABNORMAL_EXIT = 6;
|
||||
public static final int EVENT_SYSTEM_EXIT = 7;
|
||||
|
||||
public static final UUID CCCD_UUID = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb");
|
||||
|
||||
public static List<byte[]> framePb(byte[] pb, int sid, int flag, int seq) {
|
||||
int chunkSize = 232;
|
||||
byte[] crc = crcBytesLe(pb);
|
||||
int totalWithCrc = pb.length + 2;
|
||||
int totalFrags = Math.max(1, (int) Math.ceil(totalWithCrc / (double) chunkSize));
|
||||
List<byte[]> frames = new ArrayList<>(totalFrags);
|
||||
int offset = 0;
|
||||
for (int i = 0; i < totalFrags; i++) {
|
||||
boolean isLast = i == totalFrags - 1;
|
||||
byte[] chunk;
|
||||
if (isLast) {
|
||||
int remaining = pb.length - offset;
|
||||
chunk = new byte[remaining + 2];
|
||||
System.arraycopy(pb, offset, chunk, 0, remaining);
|
||||
System.arraycopy(crc, 0, chunk, remaining, 2);
|
||||
} else {
|
||||
chunk = Arrays.copyOfRange(pb, offset, offset + chunkSize);
|
||||
offset += chunkSize;
|
||||
}
|
||||
if (isLast) {
|
||||
offset = pb.length;
|
||||
}
|
||||
byte[] frame = new byte[8 + chunk.length];
|
||||
frame[0] = (byte) 0xaa;
|
||||
frame[1] = 0x21;
|
||||
frame[2] = (byte) (seq & 0xff);
|
||||
frame[3] = (byte) (chunk.length & 0xff);
|
||||
frame[4] = (byte) (totalFrags & 0xff);
|
||||
frame[5] = (byte) ((i + 1) & 0xff);
|
||||
frame[6] = (byte) (sid & 0xff);
|
||||
frame[7] = (byte) (flag & 0xff);
|
||||
System.arraycopy(chunk, 0, frame, 8, chunk.length);
|
||||
frames.add(frame);
|
||||
}
|
||||
return frames;
|
||||
}
|
||||
|
||||
|
||||
public static byte[] buildCreateMixedImagePage(int magic, ImageTileOptions[] tiles) {
|
||||
List<byte[]> innerParts = new ArrayList<>();
|
||||
innerParts.add(encodeVarintField(1, 1 + tiles.length));
|
||||
innerParts.add(encodeMessageField(3, encodeTextObject("dashboard", 1, 0, 0, 576, 288, " ", true)));
|
||||
for (ImageTileOptions tile : tiles) {
|
||||
innerParts.add(encodeMessageField(4, encodeImageObject(tile)));
|
||||
}
|
||||
innerParts.add(encodeVarintField(5, 10000));
|
||||
byte[] inner = concat(innerParts);
|
||||
return wrapEvenHub(0, magic, 3, inner);
|
||||
}
|
||||
|
||||
public static byte[] buildDashboardTextUpgrade(int magic) {
|
||||
List<byte[]> inner = new ArrayList<>();
|
||||
inner.add(encodeVarintField(1, 1));
|
||||
inner.add(encodeStringField(2, "dashboard"));
|
||||
inner.add(encodeVarintField(3, 0));
|
||||
inner.add(encodeVarintField(4, 1));
|
||||
inner.add(encodeStringField(5, " "));
|
||||
return wrapEvenHub(5, magic, 9, concat(inner));
|
||||
}
|
||||
|
||||
public static byte[] buildImageRawData(ImageTileOptions tile, int sessionId, int totalSize, ImageFragment fragment, int magic) {
|
||||
List<byte[]> inner = new ArrayList<>();
|
||||
inner.add(encodeVarintField(1, tile.containerId));
|
||||
inner.add(encodeStringField(2, tile.name));
|
||||
inner.add(encodeVarintField(3, sessionId));
|
||||
inner.add(encodeVarintField(4, totalSize));
|
||||
inner.add(encodeVarintField(5, 0));
|
||||
inner.add(encodeVarintField(6, fragment.index));
|
||||
inner.add(encodeVarintField(7, fragment.size));
|
||||
inner.add(encodeBytesField(8, fragment.data));
|
||||
return wrapEvenHub(3, magic, 5, concat(inner));
|
||||
}
|
||||
|
||||
public static byte[] buildHeartbeat(int magic) {
|
||||
return wrapEvenHub(12, magic, 14, encodeVarintField(1, 0));
|
||||
}
|
||||
|
||||
public static byte[] buildShutdown(int magic, int exitMode) {
|
||||
return wrapEvenHub(9, magic, 11, encodeVarintField(1, exitMode));
|
||||
}
|
||||
|
||||
public static byte[] buildSettingsQuery(int magic) {
|
||||
byte[] request = encodeVarintField(1, 1);
|
||||
return concat(CollectionUtils.listOf(
|
||||
encodeVarintField(1, 2),
|
||||
encodeVarintField(2, magic),
|
||||
encodeMessageField(4, request)
|
||||
));
|
||||
}
|
||||
|
||||
public static BatterySnapshot parseSettingsBattery(byte[] pb) {
|
||||
byte[] root = stripTrailingCrc(pb);
|
||||
byte[] request = readFieldBytes(root, 4);
|
||||
if (request == null) {
|
||||
return null;
|
||||
}
|
||||
int battery = readVarintFieldValue(request, 12, -1);
|
||||
int charging = readVarintFieldValue(request, 13, -1);
|
||||
if (battery < 0) {
|
||||
return null;
|
||||
}
|
||||
return new BatterySnapshot(battery, charging);
|
||||
}
|
||||
|
||||
public static byte[] wrapEvenHub(int cmd, int magic, int innerFieldNumber, byte[] inner) {
|
||||
List<byte[]> parts = new ArrayList<>();
|
||||
parts.add(encodeVarintField(1, cmd));
|
||||
parts.add(encodeVarintField(2, magic));
|
||||
parts.add(encodeMessageField(innerFieldNumber, inner));
|
||||
return concat(parts);
|
||||
}
|
||||
|
||||
public static byte[] encodeTextObject(String name, int containerId, int x, int y, int width, int height, String text, boolean captureEvents) {
|
||||
List<byte[]> parts = new ArrayList<>();
|
||||
parts.add(encodeVarintField(1, x));
|
||||
parts.add(encodeVarintField(2, y));
|
||||
parts.add(encodeVarintField(3, width));
|
||||
parts.add(encodeVarintField(4, height));
|
||||
parts.add(encodeVarintField(9, containerId));
|
||||
parts.add(encodeStringField(10, name));
|
||||
if (captureEvents) {
|
||||
parts.add(encodeVarintField(11, 1));
|
||||
}
|
||||
parts.add(encodeStringField(12, text));
|
||||
return concat(parts);
|
||||
}
|
||||
|
||||
public static byte[] encodeImageObject(ImageTileOptions tile) {
|
||||
List<byte[]> parts = new ArrayList<>();
|
||||
parts.add(encodeVarintField(1, tile.x));
|
||||
parts.add(encodeVarintField(2, tile.y));
|
||||
parts.add(encodeVarintField(3, tile.width));
|
||||
parts.add(encodeVarintField(4, tile.height));
|
||||
parts.add(encodeVarintField(5, tile.containerId));
|
||||
parts.add(encodeStringField(6, tile.name));
|
||||
return concat(parts);
|
||||
}
|
||||
|
||||
private static byte[] concat(List<byte[]> parts) {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
for (byte[] part : parts) {
|
||||
if (part != null && part.length > 0) {
|
||||
out.write(part, 0, part.length);
|
||||
}
|
||||
}
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
private static byte[] encodeVarintField(int fieldNumber, int value) {
|
||||
return concat(CollectionUtils.listOf(encodeKey(fieldNumber, 0), encodeVarint(value)));
|
||||
}
|
||||
|
||||
private static byte[] encodeStringField(int fieldNumber, String value) {
|
||||
byte[] bytes = value == null ? new byte[0] : value.getBytes(StandardCharsets.UTF_8);
|
||||
return concat(CollectionUtils.listOf(encodeKey(fieldNumber, 2), encodeVarint(bytes.length), bytes));
|
||||
}
|
||||
|
||||
private static byte[] encodeBytesField(int fieldNumber, byte[] value) {
|
||||
byte[] bytes = value == null ? new byte[0] : value;
|
||||
return concat(CollectionUtils.listOf(encodeKey(fieldNumber, 2), encodeVarint(bytes.length), bytes));
|
||||
}
|
||||
|
||||
private static byte[] encodeMessageField(int fieldNumber, byte[] value) {
|
||||
byte[] bytes = value == null ? new byte[0] : value;
|
||||
return concat(CollectionUtils.listOf(encodeKey(fieldNumber, 2), encodeVarint(bytes.length), bytes));
|
||||
}
|
||||
|
||||
private static byte[] encodeKey(int fieldNumber, int wireType) {
|
||||
return encodeVarint((fieldNumber << 3) | wireType);
|
||||
}
|
||||
|
||||
private static byte[] encodeVarint(int value) {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
int v = value >>> 0;
|
||||
while (v >= 0x80) {
|
||||
out.write((v & 0x7f) | 0x80);
|
||||
v >>>= 7;
|
||||
}
|
||||
out.write(v);
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
private static byte[] crcBytesLe(byte[] data) {
|
||||
int crc = 0xffff;
|
||||
for (byte b : data) {
|
||||
crc ^= (b & 0xff) << 8;
|
||||
for (int i = 0; i < 8; i++) {
|
||||
if ((crc & 0x8000) != 0) {
|
||||
crc = ((crc << 1) ^ 0x1021) & 0xffff;
|
||||
} else {
|
||||
crc = (crc << 1) & 0xffff;
|
||||
}
|
||||
}
|
||||
}
|
||||
return new byte[] {(byte) (crc & 0xff), (byte) ((crc >>> 8) & 0xff)};
|
||||
}
|
||||
|
||||
|
||||
public static ParsedFrame parseFrame(byte[] buf) {
|
||||
if (buf == null || buf.length < 10 || buf[0] != (byte) 0xaa || (buf[1] != 0x21 && buf[1] != 0x12)) {
|
||||
return new ParsedFrame(false, 0, 0, new byte[0], -1, -1);
|
||||
}
|
||||
int sid = buf[6] & 0xff;
|
||||
int flag = buf[7] & 0xff;
|
||||
int len = buf[3] & 0xff;
|
||||
int end = Math.min(buf.length, 8 + len);
|
||||
byte[] pb = Arrays.copyOfRange(buf, 8, end);
|
||||
|
||||
int msgType = -1;
|
||||
int msgSeq = -1;
|
||||
int offset = 0;
|
||||
for (int i = 0; i < 8 && offset < pb.length; i++) {
|
||||
VarintResult key = readVarint(pb, offset);
|
||||
if (key == null) {
|
||||
break;
|
||||
}
|
||||
offset = key.next;
|
||||
int tag = key.value >> 3;
|
||||
int wire = key.value & 7;
|
||||
if (wire == 0) {
|
||||
VarintResult value = readVarint(pb, offset);
|
||||
if (value == null) {
|
||||
break;
|
||||
}
|
||||
if (tag == 1) {
|
||||
msgType = value.value;
|
||||
} else if (tag == 2) {
|
||||
msgSeq = value.value;
|
||||
}
|
||||
offset = value.next;
|
||||
} else if (wire == 2) {
|
||||
VarintResult length = readVarint(pb, offset);
|
||||
if (length == null) {
|
||||
break;
|
||||
}
|
||||
offset = length.next + length.value;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
if (msgType >= 0 && msgSeq >= 0) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return new ParsedFrame(true, sid, flag, pb, msgType, msgSeq);
|
||||
}
|
||||
|
||||
public static byte[] stripTrailingCrc(byte[] pb) {
|
||||
if (pb == null || pb.length < 2) {
|
||||
return pb == null ? new byte[0] : pb;
|
||||
}
|
||||
return Arrays.copyOf(pb, pb.length - 2);
|
||||
}
|
||||
|
||||
public static byte[] readFieldBytes(byte[] pb, int fieldNumber) {
|
||||
int offset = 0;
|
||||
while (offset < pb.length) {
|
||||
VarintResult key = readVarint(pb, offset);
|
||||
if (key == null) {
|
||||
return null;
|
||||
}
|
||||
offset = key.next;
|
||||
int field = key.value >> 3;
|
||||
int wire = key.value & 0x07;
|
||||
if (wire == 0) {
|
||||
VarintResult value = readVarint(pb, offset);
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
offset = value.next;
|
||||
continue;
|
||||
}
|
||||
if (wire == 1) {
|
||||
offset += 8;
|
||||
continue;
|
||||
}
|
||||
if (wire == 5) {
|
||||
offset += 4;
|
||||
continue;
|
||||
}
|
||||
if (wire != 2) {
|
||||
return null;
|
||||
}
|
||||
VarintResult length = readVarint(pb, offset);
|
||||
if (length == null) {
|
||||
return null;
|
||||
}
|
||||
offset = length.next;
|
||||
int end = offset + length.value;
|
||||
if (end > pb.length) {
|
||||
return null;
|
||||
}
|
||||
byte[] bytes = Arrays.copyOfRange(pb, offset, end);
|
||||
offset = end;
|
||||
if (field == fieldNumber) {
|
||||
return bytes;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static int readVarintFieldValue(byte[] pb, int fieldNumber, int defaultValue) {
|
||||
int offset = 0;
|
||||
while (offset < pb.length) {
|
||||
VarintResult key = readVarint(pb, offset);
|
||||
if (key == null) {
|
||||
return defaultValue;
|
||||
}
|
||||
offset = key.next;
|
||||
int field = key.value >> 3;
|
||||
int wire = key.value & 0x07;
|
||||
if (wire == 0) {
|
||||
VarintResult value = readVarint(pb, offset);
|
||||
if (value == null) {
|
||||
return defaultValue;
|
||||
}
|
||||
offset = value.next;
|
||||
if (field == fieldNumber) {
|
||||
return value.value;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (wire == 1) {
|
||||
offset += 8;
|
||||
continue;
|
||||
}
|
||||
if (wire == 5) {
|
||||
offset += 4;
|
||||
continue;
|
||||
}
|
||||
if (wire != 2) {
|
||||
return defaultValue;
|
||||
}
|
||||
VarintResult length = readVarint(pb, offset);
|
||||
if (length == null) {
|
||||
return defaultValue;
|
||||
}
|
||||
offset = length.next + length.value;
|
||||
}
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
public static String readStringFieldValue(byte[] pb, int fieldNumber) {
|
||||
byte[] bytes = readFieldBytes(pb, fieldNumber);
|
||||
if (bytes == null) {
|
||||
return "";
|
||||
}
|
||||
return new String(bytes, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
public static VarintResult readVarint(byte[] pb, int offset) {
|
||||
int value = 0;
|
||||
int shift = 0;
|
||||
int cursor = offset;
|
||||
while (cursor < pb.length) {
|
||||
int b = pb[cursor++] & 0xff;
|
||||
value |= (b & 0x7f) << shift;
|
||||
if ((b & 0x80) == 0) {
|
||||
return new VarintResult(value, cursor);
|
||||
}
|
||||
shift += 7;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
public static final class ParsedFrame {
|
||||
final boolean ok;
|
||||
final int sid;
|
||||
final int flag;
|
||||
final byte[] pb;
|
||||
final int msgType;
|
||||
final int msgSeq;
|
||||
|
||||
ParsedFrame(boolean ok, int sid, int flag, byte[] pb, int msgType, int msgSeq) {
|
||||
this.ok = ok;
|
||||
this.sid = sid;
|
||||
this.flag = flag;
|
||||
this.pb = pb;
|
||||
this.msgType = msgType;
|
||||
this.msgSeq = msgSeq;
|
||||
}
|
||||
}
|
||||
|
||||
private static final class VarintResult {
|
||||
final int value;
|
||||
final int next;
|
||||
|
||||
VarintResult(int value, int next) {
|
||||
this.value = value;
|
||||
this.next = next;
|
||||
}
|
||||
}
|
||||
|
||||
public static final class ImageTileOptions {
|
||||
final String name;
|
||||
final int containerId;
|
||||
final int x;
|
||||
final int y;
|
||||
final int width;
|
||||
final int height;
|
||||
|
||||
ImageTileOptions(String name, int containerId, int x, int y, int width, int height) {
|
||||
this.name = name;
|
||||
this.containerId = containerId;
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
}
|
||||
}
|
||||
|
||||
public static final class ImageFragment {
|
||||
final int index;
|
||||
final byte[] data;
|
||||
final int size;
|
||||
|
||||
ImageFragment(int index, byte[] data, int size) {
|
||||
this.index = index;
|
||||
this.data = data;
|
||||
this.size = size;
|
||||
}
|
||||
}
|
||||
|
||||
public static final class BatterySnapshot {
|
||||
final int battery;
|
||||
final int charging;
|
||||
|
||||
BatterySnapshot(int battery, int charging) {
|
||||
this.battery = battery;
|
||||
this.charging = charging;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.faceclaw.app;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class CollectionUtils {
|
||||
public static List<byte[]> singletonList(byte[] value) {
|
||||
List<byte[]> list = new ArrayList<>(1);
|
||||
list.add(value);
|
||||
return list;
|
||||
}
|
||||
|
||||
public static List<byte[]> listOf(byte[] a, byte[] b) {
|
||||
List<byte[]> list = new ArrayList<>(2);
|
||||
list.add(a);
|
||||
list.add(b);
|
||||
return list;
|
||||
}
|
||||
|
||||
public static List<byte[]> listOf(byte[] a, byte[] b, byte[] c) {
|
||||
List<byte[]> list = new ArrayList<>(3);
|
||||
list.add(a);
|
||||
list.add(b);
|
||||
list.add(c);
|
||||
return list;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.faceclaw.app;
|
||||
|
||||
public interface FaceclawBleCommunicatorListener {
|
||||
void onLog(String line);
|
||||
void onStateChange(String phase, String status);
|
||||
void onRingEvent(String kind, String containerName, int eventType, int eventSource, int systemExitReasonCode);
|
||||
void onBatteryState(int headsetBattery, int headsetCharging);
|
||||
void onEvenAppConflict(String message);
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.faceclaw.app;
|
||||
|
||||
public interface FaceclawBleListener {
|
||||
void onNotification(String address, String characteristicUuid, byte[] data);
|
||||
void onConnectionStateChange(String address, boolean connected);
|
||||
}
|
||||
@@ -0,0 +1,443 @@
|
||||
package com.faceclaw.app;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.bluetooth.BluetoothAdapter;
|
||||
import android.bluetooth.BluetoothDevice;
|
||||
import android.bluetooth.BluetoothGatt;
|
||||
import android.bluetooth.BluetoothGattCallback;
|
||||
import android.bluetooth.BluetoothGattCharacteristic;
|
||||
import android.bluetooth.BluetoothGattDescriptor;
|
||||
import android.bluetooth.BluetoothGattService;
|
||||
import android.bluetooth.BluetoothManager;
|
||||
import android.bluetooth.BluetoothProfile;
|
||||
import android.content.Context;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.os.SystemClock;
|
||||
import android.util.Log;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.RejectedExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
@SuppressLint("MissingPermission")
|
||||
public class FaceclawBleManager {
|
||||
private static final String TAG = "FaceclawBle";
|
||||
private static final int[] WRITE_RETRY_DELAYS_MS = new int[] {4, 8, 12, 20, 35, 100, 200};
|
||||
|
||||
private final Context context;
|
||||
private final BluetoothAdapter bluetoothAdapter;
|
||||
private final Handler mainHandler = new Handler(Looper.getMainLooper());
|
||||
|
||||
private final ConcurrentHashMap<String, BluetoothGatt> gattClients = new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<String, Object> writeLocks = new ConcurrentHashMap<>();
|
||||
|
||||
private final ConcurrentHashMap<String, CountDownLatch> connectLatches = new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<String, Boolean> connectResults = new ConcurrentHashMap<>();
|
||||
|
||||
private final ConcurrentHashMap<String, CountDownLatch> servicesLatches = new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<String, Integer> servicesStatuses = new ConcurrentHashMap<>();
|
||||
|
||||
private final ConcurrentHashMap<String, CountDownLatch> mtuLatches = new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<String, Integer> mtuStatuses = new ConcurrentHashMap<>();
|
||||
|
||||
private final ConcurrentHashMap<String, CountDownLatch> descriptorLatches = new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<String, Integer> descriptorStatuses = new ConcurrentHashMap<>();
|
||||
|
||||
private final ConcurrentHashMap<String, CountDownLatch> writeLatches = new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<String, Integer> writeStatuses = new ConcurrentHashMap<>();
|
||||
|
||||
private volatile FaceclawBleListener listener;
|
||||
|
||||
public FaceclawBleManager(Context context) {
|
||||
this.context = context.getApplicationContext();
|
||||
BluetoothManager bluetoothManager = (BluetoothManager) this.context.getSystemService(Context.BLUETOOTH_SERVICE);
|
||||
if (bluetoothManager == null || bluetoothManager.getAdapter() == null) {
|
||||
throw new IllegalStateException("Bluetooth adapter unavailable");
|
||||
}
|
||||
this.bluetoothAdapter = bluetoothManager.getAdapter();
|
||||
}
|
||||
|
||||
public void setListener(FaceclawBleListener listener) {
|
||||
this.listener = listener;
|
||||
}
|
||||
|
||||
public boolean connect(String address, int timeoutMs) {
|
||||
if (address == null || address.trim().isEmpty()) {
|
||||
throw new IllegalArgumentException("address is required");
|
||||
}
|
||||
BluetoothGatt existing = gattClients.get(address);
|
||||
if (existing != null) {
|
||||
return true;
|
||||
}
|
||||
|
||||
final BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address);
|
||||
if (device == null) {
|
||||
throw new IllegalArgumentException("remote device not found: " + address);
|
||||
}
|
||||
|
||||
CountDownLatch latch = new CountDownLatch(1);
|
||||
connectLatches.put(address, latch);
|
||||
connectResults.remove(address);
|
||||
|
||||
BluetoothGatt gatt = runOnMainSync(() -> device.connectGatt(
|
||||
context,
|
||||
false,
|
||||
gattCallback,
|
||||
BluetoothDevice.TRANSPORT_LE,
|
||||
BluetoothDevice.PHY_LE_2M|BluetoothDevice.PHY_LE_1M
|
||||
));
|
||||
if (gatt == null) {
|
||||
connectLatches.remove(address);
|
||||
return false;
|
||||
}
|
||||
gattClients.put(address, gatt);
|
||||
|
||||
if (!awaitLatch(latch, timeoutMs)) {
|
||||
connectLatches.remove(address);
|
||||
connectResults.remove(address);
|
||||
return false;
|
||||
}
|
||||
|
||||
gatt.readPhy();
|
||||
Boolean connected = connectResults.remove(address);
|
||||
connectLatches.remove(address);
|
||||
return Boolean.TRUE.equals(connected);
|
||||
}
|
||||
|
||||
public boolean requestConnectionPriority(String address, int priority) {
|
||||
BluetoothGatt gatt = requireGatt(address);
|
||||
return runOnMainSync(() -> gatt.requestConnectionPriority(priority));
|
||||
}
|
||||
|
||||
public boolean requestMtu(String address, int mtu, int timeoutMs) {
|
||||
BluetoothGatt gatt = requireGatt(address);
|
||||
CountDownLatch latch = new CountDownLatch(1);
|
||||
mtuLatches.put(address, latch);
|
||||
mtuStatuses.remove(address);
|
||||
|
||||
boolean started = runOnMainSync(() -> gatt.requestMtu(mtu));
|
||||
if (!started) {
|
||||
mtuLatches.remove(address);
|
||||
return false;
|
||||
}
|
||||
if (!awaitLatch(latch, timeoutMs)) {
|
||||
mtuLatches.remove(address);
|
||||
mtuStatuses.remove(address);
|
||||
return false;
|
||||
}
|
||||
Integer status = mtuStatuses.remove(address);
|
||||
mtuLatches.remove(address);
|
||||
return status != null && status == BluetoothGatt.GATT_SUCCESS;
|
||||
}
|
||||
|
||||
public boolean discoverServices(String address, int timeoutMs) {
|
||||
BluetoothGatt gatt = requireGatt(address);
|
||||
CountDownLatch latch = new CountDownLatch(1);
|
||||
servicesLatches.put(address, latch);
|
||||
servicesStatuses.remove(address);
|
||||
|
||||
boolean started = runOnMainSync(gatt::discoverServices);
|
||||
if (!started) {
|
||||
servicesLatches.remove(address);
|
||||
return false;
|
||||
}
|
||||
if (!awaitLatch(latch, timeoutMs)) {
|
||||
servicesLatches.remove(address);
|
||||
servicesStatuses.remove(address);
|
||||
return false;
|
||||
}
|
||||
Integer status = servicesStatuses.remove(address);
|
||||
servicesLatches.remove(address);
|
||||
return status != null && status == BluetoothGatt.GATT_SUCCESS;
|
||||
}
|
||||
|
||||
public boolean enableNotifications(String address, String characteristicUuid, boolean enable, int timeoutMs) {
|
||||
BluetoothGatt gatt = requireGatt(address);
|
||||
BluetoothGattCharacteristic characteristic = requireCharacteristic(gatt, characteristicUuid);
|
||||
|
||||
boolean notificationSet = runOnMainSync(() -> gatt.setCharacteristicNotification(characteristic, enable));
|
||||
if (!notificationSet) {
|
||||
return false;
|
||||
}
|
||||
|
||||
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(BleProtocol.CCCD_UUID);
|
||||
if (descriptor == null) {
|
||||
return true;
|
||||
}
|
||||
|
||||
CountDownLatch latch = new CountDownLatch(1);
|
||||
descriptorLatches.put(address, latch);
|
||||
descriptorStatuses.remove(address);
|
||||
|
||||
descriptor.setValue(enable
|
||||
? BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
|
||||
: BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
|
||||
boolean started = runOnMainSync(() -> gatt.writeDescriptor(descriptor));
|
||||
if (!started) {
|
||||
descriptorLatches.remove(address);
|
||||
return false;
|
||||
}
|
||||
if (!awaitLatch(latch, timeoutMs)) {
|
||||
descriptorLatches.remove(address);
|
||||
descriptorStatuses.remove(address);
|
||||
return false;
|
||||
}
|
||||
Integer status = descriptorStatuses.remove(address);
|
||||
descriptorLatches.remove(address);
|
||||
return status != null && status == BluetoothGatt.GATT_SUCCESS;
|
||||
}
|
||||
|
||||
public boolean writeFrames(
|
||||
String address,
|
||||
String characteristicUuid,
|
||||
List<byte[]> frames,
|
||||
int writeType,
|
||||
int timeoutMs
|
||||
) {
|
||||
if (frames == null || frames.isEmpty()) {
|
||||
return true;
|
||||
}
|
||||
Log.i(TAG, "Called writeFrames with writeType=" + writeType + ", " + frames.size() + " frames totaling " + frames.stream().mapToInt(frame -> frame != null ? frame.length : 0).sum() + " bytes");
|
||||
|
||||
BluetoothGatt gatt = requireGatt(address);
|
||||
BluetoothGattCharacteristic characteristic = requireCharacteristic(gatt, characteristicUuid);
|
||||
|
||||
for (int i = 0; i < frames.size(); i++) {
|
||||
Log.i(TAG, "writeFrames starting frame " + i);
|
||||
byte[] frame = frames.get(i);
|
||||
if (!startWrite(gatt, characteristic, address, frame, writeType, timeoutMs)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean startWrite(
|
||||
BluetoothGatt gatt,
|
||||
BluetoothGattCharacteristic characteristic,
|
||||
String address,
|
||||
byte[] data,
|
||||
int writeType,
|
||||
int timeoutMs
|
||||
) {
|
||||
boolean retry = false;
|
||||
int retryCount = 0;
|
||||
while (true) {
|
||||
long currentTime = System.currentTimeMillis();
|
||||
int result = gatt.writeCharacteristic(characteristic, data, writeType);
|
||||
long timeAsleep = System.currentTimeMillis() - currentTime;
|
||||
//Log.i(TAG, "writeCharacteristic: spent " + timeAsleep + "ms");
|
||||
|
||||
if (result == android.bluetooth.BluetoothStatusCodes.ERROR_GATT_WRITE_REQUEST_BUSY) {
|
||||
if (++retryCount < 25) {
|
||||
try {
|
||||
long currentTime2 = System.currentTimeMillis();
|
||||
Thread.sleep(1);
|
||||
long timeAsleep2 = System.currentTimeMillis() - currentTime2;
|
||||
//Log.i(TAG, "writeCharacteristic: slept for " + timeAsleep2 + "ms");
|
||||
} catch (InterruptedException e) {}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
//Log.i(TAG, "writeCharacteristic with writeType=" + writeType + " result=" + result + " retryCount=" + retryCount);
|
||||
return result == android.bluetooth.BluetoothStatusCodes.SUCCESS;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void disconnect(String address) {
|
||||
BluetoothGatt gatt = gattClients.remove(address);
|
||||
if (gatt == null) {
|
||||
return;
|
||||
}
|
||||
runOnMainAsync(() -> {
|
||||
gatt.disconnect();
|
||||
gatt.close();
|
||||
});
|
||||
}
|
||||
|
||||
public void close() {
|
||||
for (String address : gattClients.keySet()) {
|
||||
disconnect(address);
|
||||
}
|
||||
}
|
||||
|
||||
private BluetoothGatt requireGatt(String address) {
|
||||
BluetoothGatt gatt = gattClients.get(address);
|
||||
if (gatt == null) {
|
||||
throw new IllegalStateException("Not connected: " + address);
|
||||
}
|
||||
return gatt;
|
||||
}
|
||||
|
||||
private BluetoothGattCharacteristic requireCharacteristic(BluetoothGatt gatt, String characteristicUuid) {
|
||||
UUID target = UUID.fromString(characteristicUuid);
|
||||
for (BluetoothGattService service : gatt.getServices()) {
|
||||
BluetoothGattCharacteristic characteristic = service.getCharacteristic(target);
|
||||
if (characteristic != null) {
|
||||
return characteristic;
|
||||
}
|
||||
}
|
||||
throw new IllegalStateException("Characteristic not found: " + characteristicUuid);
|
||||
}
|
||||
|
||||
private boolean awaitLatch(CountDownLatch latch, int timeoutMs) {
|
||||
try {
|
||||
return latch.await(timeoutMs, TimeUnit.MILLISECONDS);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private void runOnMainAsync(Runnable runnable) {
|
||||
if (Looper.myLooper() == Looper.getMainLooper()) {
|
||||
runnable.run();
|
||||
} else {
|
||||
mainHandler.post(runnable);
|
||||
}
|
||||
}
|
||||
|
||||
private <T> T runOnMainSync(Callable<T> callable) {
|
||||
if (Looper.myLooper() == Looper.getMainLooper()) {
|
||||
try {
|
||||
return callable.call();
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
CountDownLatch latch = new CountDownLatch(1);
|
||||
AtomicReference<T> result = new AtomicReference<>();
|
||||
AtomicReference<RuntimeException> error = new AtomicReference<>();
|
||||
|
||||
mainHandler.post(() -> {
|
||||
try {
|
||||
result.set(callable.call());
|
||||
} catch (Exception e) {
|
||||
error.set(new RuntimeException(e));
|
||||
} finally {
|
||||
latch.countDown();
|
||||
}
|
||||
});
|
||||
|
||||
awaitLatch(latch, 10_000);
|
||||
if (error.get() != null) {
|
||||
throw error.get();
|
||||
}
|
||||
return result.get();
|
||||
}
|
||||
|
||||
private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
|
||||
@Override
|
||||
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
|
||||
String address = gatt.getDevice().getAddress();
|
||||
|
||||
if (newState == BluetoothProfile.STATE_CONNECTED && status == BluetoothGatt.GATT_SUCCESS) {
|
||||
connectResults.put(address, true);
|
||||
CountDownLatch latch = connectLatches.remove(address);
|
||||
if (latch != null) {
|
||||
latch.countDown();
|
||||
}
|
||||
dispatchConnectionState(address, true);
|
||||
return;
|
||||
}
|
||||
|
||||
if (newState == BluetoothProfile.STATE_DISCONNECTED) {
|
||||
connectResults.put(address, false);
|
||||
CountDownLatch latch = connectLatches.remove(address);
|
||||
if (latch != null) {
|
||||
latch.countDown();
|
||||
}
|
||||
gattClients.remove(address);
|
||||
writeLocks.remove(address);
|
||||
runOnMainAsync(gatt::close);
|
||||
dispatchConnectionState(address, false);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
|
||||
String address = gatt.getDevice().getAddress();
|
||||
servicesStatuses.put(address, status);
|
||||
CountDownLatch latch = servicesLatches.remove(address);
|
||||
if (latch != null) {
|
||||
latch.countDown();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {
|
||||
String address = gatt.getDevice().getAddress();
|
||||
mtuStatuses.put(address, status);
|
||||
CountDownLatch latch = mtuLatches.remove(address);
|
||||
if (latch != null) {
|
||||
latch.countDown();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPhyRead(BluetoothGatt gatt, int txPhy, int rxPhy, int status) {
|
||||
Log.i(TAG, "onPhyRead: txPhy=" + txPhy + " rxPhy=" + rxPhy + " status=" + status);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
|
||||
String address = gatt.getDevice().getAddress();
|
||||
descriptorStatuses.put(address, status);
|
||||
CountDownLatch latch = descriptorLatches.remove(address);
|
||||
if (latch != null) {
|
||||
latch.countDown();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
|
||||
String address = gatt.getDevice().getAddress();
|
||||
writeStatuses.put(address, status);
|
||||
CountDownLatch latch = writeLatches.remove(address);
|
||||
if (latch != null) {
|
||||
latch.countDown();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, byte[] value) {
|
||||
Log.i(TAG, "onCharacteristicChanged");
|
||||
dispatchNotification(gatt.getDevice().getAddress(), characteristic.getUuid().toString(), value);
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
@Override
|
||||
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
|
||||
dispatchNotification(gatt.getDevice().getAddress(), characteristic.getUuid().toString(), characteristic.getValue());
|
||||
}
|
||||
};
|
||||
|
||||
private void dispatchConnectionState(String address, boolean connected) {
|
||||
FaceclawBleListener current = listener;
|
||||
if (current == null) {
|
||||
return;
|
||||
}
|
||||
runOnMainAsync(() -> current.onConnectionStateChange(address, connected));
|
||||
}
|
||||
|
||||
private void dispatchNotification(String address, String characteristicUuid, byte[] data) {
|
||||
Log.i(TAG, "dispatchNotification");
|
||||
FaceclawBleListener current = listener;
|
||||
if (current == null) {
|
||||
return;
|
||||
}
|
||||
byte[] copy = data != null ? data.clone() : new byte[0];
|
||||
runOnMainAsync(() -> current.onNotification(address, characteristicUuid, copy));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.faceclaw.app;
|
||||
|
||||
import android.os.Looper;
|
||||
|
||||
public class FaceclawBridge {
|
||||
public static String ping(String value) {
|
||||
return "java-ping:" + value;
|
||||
}
|
||||
|
||||
public static String currentThreadName() {
|
||||
return Thread.currentThread().getName();
|
||||
}
|
||||
|
||||
public static boolean isMainThread() {
|
||||
return Looper.getMainLooper().isCurrentThread();
|
||||
}
|
||||
|
||||
public int add(int a, int b) {
|
||||
return a + b;
|
||||
}
|
||||
|
||||
public String describeEnvironment() {
|
||||
return "thread=" + currentThreadName() + " main=" + isMainThread();
|
||||
}
|
||||
|
||||
public String runCallback(String label, Runnable callback) {
|
||||
callback.run();
|
||||
return "java-callback-complete:" + label;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
package com.faceclaw.app;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.bluetooth.BluetoothAdapter;
|
||||
import android.bluetooth.BluetoothDevice;
|
||||
import android.bluetooth.BluetoothManager;
|
||||
import android.bluetooth.le.BluetoothLeScanner;
|
||||
import android.bluetooth.le.ScanCallback;
|
||||
import android.bluetooth.le.ScanResult;
|
||||
import android.bluetooth.le.ScanSettings;
|
||||
import android.content.Context;
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@SuppressLint("MissingPermission")
|
||||
public class FaceclawDeviceDiscovery {
|
||||
private static final Pattern RING_NAME = Pattern.compile("^EVEN R1_[0-9A-F]{6}$");
|
||||
private static final Pattern RIGHT_NAME = Pattern.compile("^Even G2_32_R_[0-9A-F]{6}$");
|
||||
private static final Pattern LEFT_NAME = Pattern.compile("^Even G2_32_L_[0-9A-F]{6}$");
|
||||
|
||||
private final Context appContext;
|
||||
private final BluetoothAdapter bluetoothAdapter;
|
||||
|
||||
public FaceclawDeviceDiscovery(Context context) {
|
||||
this.appContext = context.getApplicationContext();
|
||||
BluetoothManager bluetoothManager =
|
||||
(BluetoothManager) this.appContext.getSystemService(Context.BLUETOOTH_SERVICE);
|
||||
if (bluetoothManager == null || bluetoothManager.getAdapter() == null) {
|
||||
throw new IllegalStateException("Bluetooth adapter unavailable");
|
||||
}
|
||||
this.bluetoothAdapter = bluetoothManager.getAdapter();
|
||||
}
|
||||
|
||||
public String getBondedCandidatesJson() {
|
||||
LinkedHashMap<String, CandidateDevice> matches = new LinkedHashMap<>();
|
||||
Set<BluetoothDevice> bonded = bluetoothAdapter.getBondedDevices();
|
||||
if (bonded != null) {
|
||||
for (BluetoothDevice device : bonded) {
|
||||
maybeAddCandidate(matches, device, "paired");
|
||||
}
|
||||
}
|
||||
return encodeCandidates(matches);
|
||||
}
|
||||
|
||||
public String scanCandidatesJson(int timeoutMs) throws InterruptedException {
|
||||
LinkedHashMap<String, CandidateDevice> matches = new LinkedHashMap<>();
|
||||
BluetoothLeScanner scanner = bluetoothAdapter.getBluetoothLeScanner();
|
||||
if (scanner == null) {
|
||||
return encodeCandidates(matches);
|
||||
}
|
||||
final ScanCallback callback = new ScanCallback() {
|
||||
@Override
|
||||
public void onScanResult(int callbackType, ScanResult result) {
|
||||
if (result == null) {
|
||||
return;
|
||||
}
|
||||
maybeAddCandidate(matches, result.getDevice(), "scan");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onBatchScanResults(java.util.List<ScanResult> results) {
|
||||
if (results == null) {
|
||||
return;
|
||||
}
|
||||
for (ScanResult result : results) {
|
||||
if (result != null) {
|
||||
maybeAddCandidate(matches, result.getDevice(), "scan");
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
scanner.startScan(
|
||||
null,
|
||||
new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build(),
|
||||
callback
|
||||
);
|
||||
try {
|
||||
Thread.sleep(Math.max(500, timeoutMs));
|
||||
} finally {
|
||||
try {
|
||||
scanner.stopScan(callback);
|
||||
} catch (Throwable ignored) {
|
||||
}
|
||||
}
|
||||
return encodeCandidates(matches);
|
||||
}
|
||||
|
||||
private void maybeAddCandidate(Map<String, CandidateDevice> matches, BluetoothDevice device, String source) {
|
||||
if (device == null) {
|
||||
return;
|
||||
}
|
||||
String name = device.getName();
|
||||
String role = classifyRole(name);
|
||||
if (role == null) {
|
||||
return;
|
||||
}
|
||||
String address = device.getAddress();
|
||||
if (address == null || address.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
matches.put(address, new CandidateDevice(address, name == null ? "" : name, role, source));
|
||||
}
|
||||
|
||||
private String classifyRole(String name) {
|
||||
if (name == null) {
|
||||
return null;
|
||||
}
|
||||
if (RIGHT_NAME.matcher(name).matches()) {
|
||||
return "right";
|
||||
}
|
||||
if (LEFT_NAME.matcher(name).matches()) {
|
||||
return "left";
|
||||
}
|
||||
if (RING_NAME.matcher(name).matches()) {
|
||||
return "ring";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private String encodeCandidates(Map<String, CandidateDevice> matches) {
|
||||
JSONArray array = new JSONArray();
|
||||
for (CandidateDevice candidate : matches.values()) {
|
||||
JSONObject object = new JSONObject();
|
||||
try {
|
||||
object.put("address", candidate.address);
|
||||
object.put("name", candidate.name);
|
||||
object.put("role", candidate.role);
|
||||
object.put("source", candidate.source);
|
||||
array.put(object);
|
||||
} catch (JSONException ignored) {
|
||||
}
|
||||
}
|
||||
return array.toString();
|
||||
}
|
||||
|
||||
private static final class CandidateDevice {
|
||||
final String address;
|
||||
final String name;
|
||||
final String role;
|
||||
final String source;
|
||||
|
||||
CandidateDevice(String address, String name, String role, String source) {
|
||||
this.address = address;
|
||||
this.name = name;
|
||||
this.role = role;
|
||||
this.source = source;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.faceclaw.app;
|
||||
|
||||
import android.content.ComponentName;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.net.Uri;
|
||||
import android.provider.Settings;
|
||||
import android.util.Log;
|
||||
|
||||
public final class FaceclawEvenAppDetector {
|
||||
private static final String TAG = "FaceclawEvenApp";
|
||||
|
||||
public static final String EVEN_PACKAGE_NAME = "com.even.sg";
|
||||
public static final String EVEN_NOTIFICATION_TITLE = "Even Notification Service";
|
||||
|
||||
private FaceclawEvenAppDetector() {
|
||||
}
|
||||
|
||||
public static boolean isNotificationAccessEnabled(Context context) {
|
||||
if (context == null) {
|
||||
return false;
|
||||
}
|
||||
Context appContext = context.getApplicationContext();
|
||||
ComponentName listenerComponent = new ComponentName(appContext, FaceclawMediaNotificationListenerService.class);
|
||||
String enabledListeners = Settings.Secure.getString(
|
||||
appContext.getContentResolver(),
|
||||
"enabled_notification_listeners"
|
||||
);
|
||||
if (enabledListeners == null || enabledListeners.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
String fullName = listenerComponent.flattenToString();
|
||||
String shortName = listenerComponent.flattenToShortString();
|
||||
return enabledListeners.contains(fullName)
|
||||
|| enabledListeners.contains(shortName)
|
||||
|| enabledListeners.contains(appContext.getPackageName());
|
||||
}
|
||||
|
||||
public static boolean isEvenNotificationActive(Context context) {
|
||||
boolean hasAccess = isNotificationAccessEnabled(context);
|
||||
if (!hasAccess) {
|
||||
Log.i(TAG, "Can't check for Even Realities app notification, permission is not enabled");
|
||||
return false;
|
||||
}
|
||||
boolean hasNotfication = FaceclawMediaNotificationListenerService.hasActiveNotificationTitle(EVEN_NOTIFICATION_TITLE);
|
||||
Log.i(TAG, "isEvenNotificationActive: " + hasNotfication);
|
||||
return hasNotfication;
|
||||
}
|
||||
|
||||
public static void openEvenAppSettings(Context context) {
|
||||
if (context == null) {
|
||||
return;
|
||||
}
|
||||
Context appContext = context.getApplicationContext();
|
||||
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
|
||||
intent.setData(Uri.parse("package:" + EVEN_PACKAGE_NAME));
|
||||
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
|
||||
try {
|
||||
appContext.startActivity(intent);
|
||||
} catch (Throwable t) {
|
||||
Log.w(TAG, "failed to open Even app settings", t);
|
||||
openNotificationAccessSettings(appContext);
|
||||
}
|
||||
}
|
||||
|
||||
public static void openNotificationAccessSettings(Context context) {
|
||||
if (context == null) {
|
||||
return;
|
||||
}
|
||||
Context appContext = context.getApplicationContext();
|
||||
Intent intent = new Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS);
|
||||
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
|
||||
try {
|
||||
appContext.startActivity(intent);
|
||||
} catch (Throwable t) {
|
||||
Log.w(TAG, "failed to open notification access settings", t);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package com.faceclaw.app;
|
||||
|
||||
import android.app.Notification;
|
||||
import android.app.NotificationChannel;
|
||||
import android.app.NotificationManager;
|
||||
import android.app.PendingIntent;
|
||||
import android.app.Service;
|
||||
import android.content.Intent;
|
||||
import android.os.Build;
|
||||
import android.os.IBinder;
|
||||
|
||||
import com.tns.NativeScriptActivity;
|
||||
|
||||
public class FaceclawForegroundService extends Service {
|
||||
public static final String ACTION_START = "com.faceclaw.app.action.START";
|
||||
public static final String ACTION_UPDATE = "com.faceclaw.app.action.UPDATE";
|
||||
public static final String ACTION_STOP = "com.faceclaw.app.action.STOP";
|
||||
public static final String EXTRA_TEXT = "text";
|
||||
|
||||
private static final String CHANNEL_ID = "faceclaw-dashboard";
|
||||
private static final int NOTIFICATION_ID = 4201;
|
||||
|
||||
@Override
|
||||
public IBinder onBind(Intent intent) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int onStartCommand(Intent intent, int flags, int startId) {
|
||||
String action = intent != null ? intent.getAction() : ACTION_START;
|
||||
String text = intent != null ? intent.getStringExtra(EXTRA_TEXT) : null;
|
||||
|
||||
if (ACTION_STOP.equals(action)) {
|
||||
stopForeground(STOP_FOREGROUND_REMOVE);
|
||||
stopSelf();
|
||||
return START_NOT_STICKY;
|
||||
}
|
||||
|
||||
ensureNotificationChannel();
|
||||
Notification notification = buildNotification(
|
||||
text != null && !text.trim().isEmpty() ? text : "Keeping the dashboard connected"
|
||||
);
|
||||
|
||||
startForeground(NOTIFICATION_ID, notification);
|
||||
|
||||
if (ACTION_UPDATE.equals(action)) {
|
||||
NotificationManager manager = getSystemService(NotificationManager.class);
|
||||
if (manager != null) {
|
||||
manager.notify(NOTIFICATION_ID, notification);
|
||||
}
|
||||
}
|
||||
|
||||
return START_STICKY;
|
||||
}
|
||||
|
||||
private void ensureNotificationChannel() {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
|
||||
return;
|
||||
}
|
||||
|
||||
NotificationChannel channel = new NotificationChannel(
|
||||
CHANNEL_ID,
|
||||
"Faceclaw dashboard",
|
||||
NotificationManager.IMPORTANCE_LOW
|
||||
);
|
||||
channel.setDescription("Keeps the Faceclaw dashboard connected to the glasses.");
|
||||
|
||||
NotificationManager manager = getSystemService(NotificationManager.class);
|
||||
if (manager != null) {
|
||||
manager.createNotificationChannel(channel);
|
||||
}
|
||||
}
|
||||
|
||||
private Notification buildNotification(String text) {
|
||||
Intent launchIntent = new Intent(this, NativeScriptActivity.class);
|
||||
launchIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
|
||||
|
||||
int flags = PendingIntent.FLAG_UPDATE_CURRENT;
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
flags |= PendingIntent.FLAG_IMMUTABLE;
|
||||
}
|
||||
|
||||
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, launchIntent, flags);
|
||||
|
||||
Notification.Builder builder = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
|
||||
? new Notification.Builder(this, CHANNEL_ID)
|
||||
: new Notification.Builder(this);
|
||||
|
||||
return builder
|
||||
.setContentTitle("faceclaw dashboard")
|
||||
.setContentText(text)
|
||||
.setSmallIcon(getApplicationInfo().icon)
|
||||
.setContentIntent(contentIntent)
|
||||
.setOngoing(true)
|
||||
.setOnlyAlertOnce(true)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,320 @@
|
||||
package com.faceclaw.app;
|
||||
|
||||
import android.content.ComponentName;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.media.MediaMetadata;
|
||||
import android.media.session.MediaController;
|
||||
import android.media.session.MediaSessionManager;
|
||||
import android.media.session.PlaybackState;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.provider.Settings;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class FaceclawMediaController {
|
||||
private final Context appContext;
|
||||
private final Object lock = new Object();
|
||||
private final Handler mainHandler = new Handler(Looper.getMainLooper());
|
||||
private final ComponentName listenerComponent;
|
||||
private final MediaSessionManager sessionManager;
|
||||
|
||||
private final MediaController.Callback controllerCallback = new MediaController.Callback() {
|
||||
@Override
|
||||
public void onPlaybackStateChanged(PlaybackState state) {
|
||||
synchronized (lock) {
|
||||
emitStateLocked();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onMetadataChanged(MediaMetadata metadata) {
|
||||
synchronized (lock) {
|
||||
emitStateLocked();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSessionDestroyed() {
|
||||
synchronized (lock) {
|
||||
refreshActiveControllerLocked(null);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
private final MediaSessionManager.OnActiveSessionsChangedListener sessionsChangedListener = controllers -> {
|
||||
synchronized (lock) {
|
||||
refreshActiveControllerLocked(controllers);
|
||||
}
|
||||
};
|
||||
|
||||
private volatile FaceclawMediaControllerListener listener;
|
||||
private MediaController activeController;
|
||||
private boolean started;
|
||||
|
||||
public FaceclawMediaController(Context context) {
|
||||
this.appContext = context.getApplicationContext();
|
||||
this.listenerComponent = new ComponentName(appContext, FaceclawMediaNotificationListenerService.class);
|
||||
this.sessionManager = (MediaSessionManager) appContext.getSystemService(Context.MEDIA_SESSION_SERVICE);
|
||||
}
|
||||
|
||||
public void setListener(FaceclawMediaControllerListener listener) {
|
||||
synchronized (lock) {
|
||||
this.listener = listener;
|
||||
emitStateLocked();
|
||||
}
|
||||
}
|
||||
|
||||
public void start() {
|
||||
synchronized (lock) {
|
||||
if (started) {
|
||||
emitStateLocked();
|
||||
return;
|
||||
}
|
||||
started = true;
|
||||
if (!isNotificationAccessEnabled()) {
|
||||
emitStateLocked();
|
||||
return;
|
||||
}
|
||||
if (sessionManager != null) {
|
||||
try {
|
||||
sessionManager.addOnActiveSessionsChangedListener(
|
||||
sessionsChangedListener,
|
||||
listenerComponent,
|
||||
mainHandler
|
||||
);
|
||||
} catch (SecurityException ignored) {
|
||||
emitStateLocked();
|
||||
return;
|
||||
}
|
||||
}
|
||||
refreshActiveControllerLocked(null);
|
||||
}
|
||||
}
|
||||
|
||||
public void stop() {
|
||||
synchronized (lock) {
|
||||
if (!started) {
|
||||
return;
|
||||
}
|
||||
started = false;
|
||||
if (sessionManager != null) {
|
||||
try {
|
||||
sessionManager.removeOnActiveSessionsChangedListener(sessionsChangedListener);
|
||||
} catch (SecurityException ignored) {
|
||||
}
|
||||
}
|
||||
setActiveControllerLocked(null);
|
||||
emitStateLocked();
|
||||
}
|
||||
}
|
||||
|
||||
public void playPause() {
|
||||
synchronized (lock) {
|
||||
if (activeController == null) {
|
||||
return;
|
||||
}
|
||||
PlaybackState playbackState = activeController.getPlaybackState();
|
||||
MediaController.TransportControls controls = activeController.getTransportControls();
|
||||
if (playbackState == null) {
|
||||
controls.play();
|
||||
return;
|
||||
}
|
||||
switch (playbackState.getState()) {
|
||||
case PlaybackState.STATE_PLAYING:
|
||||
case PlaybackState.STATE_BUFFERING:
|
||||
case PlaybackState.STATE_CONNECTING:
|
||||
controls.pause();
|
||||
return;
|
||||
default:
|
||||
controls.play();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void skipNext() {
|
||||
synchronized (lock) {
|
||||
if (activeController != null) {
|
||||
activeController.getTransportControls().skipToNext();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void skipPrevious() {
|
||||
synchronized (lock) {
|
||||
if (activeController != null) {
|
||||
activeController.getTransportControls().skipToPrevious();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void openNotificationAccessSettings() {
|
||||
Intent intent = new Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS);
|
||||
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
|
||||
appContext.startActivity(intent);
|
||||
}
|
||||
|
||||
private void refreshActiveControllerLocked(List<MediaController> controllers) {
|
||||
if (!started) {
|
||||
setActiveControllerLocked(null);
|
||||
emitStateLocked();
|
||||
return;
|
||||
}
|
||||
if (!isNotificationAccessEnabled()) {
|
||||
setActiveControllerLocked(null);
|
||||
emitStateLocked();
|
||||
return;
|
||||
}
|
||||
if (controllers == null && sessionManager != null) {
|
||||
try {
|
||||
controllers = sessionManager.getActiveSessions(listenerComponent);
|
||||
} catch (SecurityException ignored) {
|
||||
controllers = null;
|
||||
}
|
||||
}
|
||||
setActiveControllerLocked(chooseController(controllers));
|
||||
emitStateLocked();
|
||||
}
|
||||
|
||||
private MediaController chooseController(List<MediaController> controllers) {
|
||||
if (controllers == null || controllers.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
MediaController first = controllers.get(0);
|
||||
for (MediaController controller : controllers) {
|
||||
PlaybackState playbackState = controller.getPlaybackState();
|
||||
if (playbackState != null && playbackState.getState() == PlaybackState.STATE_PLAYING) {
|
||||
return controller;
|
||||
}
|
||||
}
|
||||
return first;
|
||||
}
|
||||
|
||||
private void setActiveControllerLocked(MediaController controller) {
|
||||
if (sameController(activeController, controller)) {
|
||||
return;
|
||||
}
|
||||
if (activeController != null) {
|
||||
activeController.unregisterCallback(controllerCallback);
|
||||
}
|
||||
activeController = controller;
|
||||
if (activeController != null) {
|
||||
activeController.registerCallback(controllerCallback, mainHandler);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean sameController(MediaController a, MediaController b) {
|
||||
if (a == b) {
|
||||
return true;
|
||||
}
|
||||
if (a == null || b == null) {
|
||||
return false;
|
||||
}
|
||||
return a.getSessionToken().equals(b.getSessionToken());
|
||||
}
|
||||
|
||||
private boolean isNotificationAccessEnabled() {
|
||||
String enabledListeners = Settings.Secure.getString(
|
||||
appContext.getContentResolver(),
|
||||
"enabled_notification_listeners"
|
||||
);
|
||||
if (enabledListeners == null || enabledListeners.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
String fullName = listenerComponent.flattenToString();
|
||||
String shortName = listenerComponent.flattenToShortString();
|
||||
return enabledListeners.contains(fullName)
|
||||
|| enabledListeners.contains(shortName)
|
||||
|| enabledListeners.contains(appContext.getPackageName());
|
||||
}
|
||||
|
||||
private void emitStateLocked() {
|
||||
FaceclawMediaControllerListener currentListener = listener;
|
||||
if (currentListener == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
String playbackState = started ? "idle" : "stopped";
|
||||
String packageName = "";
|
||||
String title = "";
|
||||
String artist = "";
|
||||
String album = "";
|
||||
boolean canPlayPause = false;
|
||||
boolean canSkipNext = false;
|
||||
boolean canSkipPrevious = false;
|
||||
boolean accessEnabled = isNotificationAccessEnabled();
|
||||
String status;
|
||||
|
||||
if (!accessEnabled) {
|
||||
playbackState = "notification-access-required";
|
||||
status = "Notification access required.";
|
||||
} else if (activeController == null) {
|
||||
status = "No active media session.";
|
||||
} else {
|
||||
packageName = safe(activeController.getPackageName());
|
||||
PlaybackState state = activeController.getPlaybackState();
|
||||
MediaMetadata metadata = activeController.getMetadata();
|
||||
playbackState = playbackStateName(state);
|
||||
if (metadata != null) {
|
||||
title = safe(metadata.getString(MediaMetadata.METADATA_KEY_TITLE));
|
||||
artist = safe(metadata.getString(MediaMetadata.METADATA_KEY_ARTIST));
|
||||
album = safe(metadata.getString(MediaMetadata.METADATA_KEY_ALBUM));
|
||||
}
|
||||
long actions = state == null ? 0L : state.getActions();
|
||||
canPlayPause = (actions & PlaybackState.ACTION_PLAY_PAUSE) != 0
|
||||
|| (actions & PlaybackState.ACTION_PLAY) != 0
|
||||
|| (actions & PlaybackState.ACTION_PAUSE) != 0;
|
||||
canSkipNext = (actions & PlaybackState.ACTION_SKIP_TO_NEXT) != 0;
|
||||
canSkipPrevious = (actions & PlaybackState.ACTION_SKIP_TO_PREVIOUS) != 0;
|
||||
status = packageName.isEmpty() ? "Active media session." : "Active session: " + packageName;
|
||||
}
|
||||
|
||||
final String finalPlaybackState = playbackState;
|
||||
final String finalPackageName = packageName;
|
||||
final String finalTitle = title;
|
||||
final String finalArtist = artist;
|
||||
final String finalAlbum = album;
|
||||
final boolean finalCanPlayPause = canPlayPause;
|
||||
final boolean finalCanSkipNext = canSkipNext;
|
||||
final boolean finalCanSkipPrevious = canSkipPrevious;
|
||||
final boolean finalAccessEnabled = accessEnabled;
|
||||
final String finalStatus = status;
|
||||
|
||||
mainHandler.post(() -> currentListener.onStateChange(
|
||||
finalPlaybackState,
|
||||
finalPackageName,
|
||||
finalTitle,
|
||||
finalArtist,
|
||||
finalAlbum,
|
||||
finalCanPlayPause,
|
||||
finalCanSkipNext,
|
||||
finalCanSkipPrevious,
|
||||
finalAccessEnabled,
|
||||
finalStatus
|
||||
));
|
||||
}
|
||||
|
||||
private String playbackStateName(PlaybackState state) {
|
||||
if (state == null) {
|
||||
return "idle";
|
||||
}
|
||||
switch (state.getState()) {
|
||||
case PlaybackState.STATE_PLAYING:
|
||||
return "playing";
|
||||
case PlaybackState.STATE_PAUSED:
|
||||
return "paused";
|
||||
case PlaybackState.STATE_BUFFERING:
|
||||
case PlaybackState.STATE_CONNECTING:
|
||||
return "buffering";
|
||||
case PlaybackState.STATE_STOPPED:
|
||||
return "stopped";
|
||||
default:
|
||||
return "idle";
|
||||
}
|
||||
}
|
||||
|
||||
private String safe(String value) {
|
||||
return value == null ? "" : value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.faceclaw.app;
|
||||
|
||||
public interface FaceclawMediaControllerListener {
|
||||
void onStateChange(
|
||||
String playbackState,
|
||||
String packageName,
|
||||
String title,
|
||||
String artist,
|
||||
String album,
|
||||
boolean canPlayPause,
|
||||
boolean canSkipNext,
|
||||
boolean canSkipPrevious,
|
||||
boolean accessEnabled,
|
||||
String status
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
package com.faceclaw.app;
|
||||
|
||||
import android.app.Notification;
|
||||
import android.app.NotificationManager;
|
||||
import android.graphics.Bitmap;
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.Color;
|
||||
import android.graphics.drawable.Drawable;
|
||||
import android.graphics.drawable.Icon;
|
||||
import android.os.Bundle;
|
||||
import android.service.notification.NotificationListenerService;
|
||||
import android.service.notification.StatusBarNotification;
|
||||
import android.util.Log;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
|
||||
public class FaceclawMediaNotificationListenerService extends NotificationListenerService {
|
||||
private static final String TAG = "FaceclawNotify";
|
||||
private static final double NOTIFICATION_ICON_GAMMA = 1.6;
|
||||
|
||||
private static volatile FaceclawMediaNotificationListenerService activeService;
|
||||
|
||||
@Override
|
||||
public void onCreate() {
|
||||
super.onCreate();
|
||||
activeService = this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDestroy() {
|
||||
if (activeService == this) {
|
||||
activeService = null;
|
||||
}
|
||||
super.onDestroy();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onListenerConnected() {
|
||||
activeService = this;
|
||||
super.onListenerConnected();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onListenerDisconnected() {
|
||||
if (activeService == this) {
|
||||
activeService = null;
|
||||
}
|
||||
super.onListenerDisconnected();
|
||||
}
|
||||
|
||||
public static boolean hasActiveNotificationTitle(String expectedTitle) {
|
||||
FaceclawMediaNotificationListenerService service = activeService;
|
||||
if (service == null || expectedTitle == null || expectedTitle.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
StatusBarNotification[] notifications;
|
||||
try {
|
||||
notifications = service.getActiveNotifications();
|
||||
} catch (SecurityException e) {
|
||||
Log.w(TAG, "notification access denied while checking active notifications", e);
|
||||
return false;
|
||||
} catch (Throwable t) {
|
||||
Log.w(TAG, "failed to check active notifications", t);
|
||||
return false;
|
||||
}
|
||||
if (notifications == null || notifications.length == 0) {
|
||||
return false;
|
||||
}
|
||||
for (StatusBarNotification notification : notifications) {
|
||||
if (notification == null || notification.getNotification() == null) {
|
||||
continue;
|
||||
}
|
||||
Bundle extras = notification.getNotification().extras;
|
||||
if (extras == null) {
|
||||
continue;
|
||||
}
|
||||
CharSequence title = extras.getCharSequence(Notification.EXTRA_TITLE);
|
||||
if (expectedTitle.contentEquals(title)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static byte[] getActiveNotificationIconGrays(int iconSize, int maxIcons) {
|
||||
FaceclawMediaNotificationListenerService service = activeService;
|
||||
int size = Math.max(1, Math.min(96, iconSize));
|
||||
int limit = Math.max(0, maxIcons);
|
||||
if (service == null || limit == 0) {
|
||||
return new byte[0];
|
||||
}
|
||||
|
||||
StatusBarNotification[] notifications;
|
||||
try {
|
||||
notifications = service.getActiveNotifications();
|
||||
} catch (SecurityException e) {
|
||||
Log.w(TAG, "notification access denied while reading icons", e);
|
||||
return new byte[0];
|
||||
} catch (Throwable t) {
|
||||
Log.w(TAG, "failed to read notification icons", t);
|
||||
return new byte[0];
|
||||
}
|
||||
if (notifications == null || notifications.length == 0) {
|
||||
return new byte[0];
|
||||
}
|
||||
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream(size * size * Math.min(limit, notifications.length));
|
||||
int emitted = 0;
|
||||
for (StatusBarNotification statusBarNotification : notifications) {
|
||||
if (!shouldShowNotificationIcon(service, statusBarNotification)) {
|
||||
continue;
|
||||
}
|
||||
Drawable drawable = loadNotificationIcon(service, statusBarNotification.getNotification());
|
||||
if (drawable == null) {
|
||||
continue;
|
||||
}
|
||||
appendIconGrayBytes(drawable, size, out);
|
||||
emitted += 1;
|
||||
if (emitted >= limit) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
private static boolean shouldShowNotificationIcon(FaceclawMediaNotificationListenerService service, StatusBarNotification statusBarNotification) {
|
||||
if (statusBarNotification == null || statusBarNotification.getNotification() == null) {
|
||||
return false;
|
||||
}
|
||||
if (service.getPackageName().equals(statusBarNotification.getPackageName())) {
|
||||
return false;
|
||||
}
|
||||
Notification notification = statusBarNotification.getNotification();
|
||||
if ((notification.flags & Notification.FLAG_GROUP_SUMMARY) != 0) {
|
||||
return false;
|
||||
}
|
||||
if (Notification.CATEGORY_TRANSPORT.equals(notification.category)) {
|
||||
return false;
|
||||
}
|
||||
Bundle extras = notification.extras;
|
||||
if (extras != null && extras.containsKey("android.mediaSession")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
NotificationListenerService.RankingMap rankingMap = service.getCurrentRanking();
|
||||
if (rankingMap == null) {
|
||||
return true;
|
||||
}
|
||||
NotificationListenerService.Ranking ranking = new NotificationListenerService.Ranking();
|
||||
if (!rankingMap.getRanking(statusBarNotification.getKey(), ranking)) {
|
||||
return true;
|
||||
}
|
||||
int importance = ranking.getImportance();
|
||||
return importance > NotificationManager.IMPORTANCE_MIN;
|
||||
}
|
||||
|
||||
private static Drawable loadNotificationIcon(FaceclawMediaNotificationListenerService service, Notification notification) {
|
||||
try {
|
||||
Icon smallIcon = notification.getSmallIcon();
|
||||
if (smallIcon != null) {
|
||||
Drawable drawable = smallIcon.loadDrawable(service);
|
||||
if (drawable != null) {
|
||||
return drawable;
|
||||
}
|
||||
}
|
||||
} catch (Throwable t) {
|
||||
Log.w(TAG, "failed to load small notification icon", t);
|
||||
}
|
||||
try {
|
||||
Icon largeIcon = notification.getLargeIcon();
|
||||
if (largeIcon != null) {
|
||||
return largeIcon.loadDrawable(service);
|
||||
}
|
||||
} catch (Throwable t) {
|
||||
Log.w(TAG, "failed to load large notification icon", t);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static void appendIconGrayBytes(Drawable drawable, int size, ByteArrayOutputStream out) {
|
||||
Bitmap bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
|
||||
Canvas canvas = new Canvas(bitmap);
|
||||
drawable.setBounds(0, 0, size, size);
|
||||
drawable.draw(canvas);
|
||||
for (int y = 0; y < size; y++) {
|
||||
for (int x = 0; x < size; x++) {
|
||||
int color = bitmap.getPixel(x, y);
|
||||
int alpha = Color.alpha(color);
|
||||
double grayLinear = (0.2126 * Color.red(color) + 0.7152 * Color.green(color) + 0.0722 * Color.blue(color)) * alpha / (255.0 * 255.0);
|
||||
int gray = (int) Math.round(255.0 * Math.pow(Math.max(0.0, Math.min(1.0, grayLinear)), NOTIFICATION_ICON_GAMMA));
|
||||
out.write(gray & 0xff);
|
||||
}
|
||||
}
|
||||
bitmap.recycle();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.faceclaw.app;
|
||||
|
||||
import android.os.SystemClock;
|
||||
|
||||
final class InterruptibleSleep {
|
||||
private final Object lock = new Object();
|
||||
private boolean interrupted;
|
||||
|
||||
boolean sleep(long ms) {
|
||||
long delayMs = Math.max(1, ms);
|
||||
long deadline = SystemClock.elapsedRealtime() + delayMs;
|
||||
synchronized (lock) {
|
||||
interrupted = false;
|
||||
while (!interrupted) {
|
||||
long remaining = deadline - SystemClock.elapsedRealtime();
|
||||
if (remaining <= 0) {
|
||||
interrupted = false;
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
lock.wait(remaining);
|
||||
} catch (InterruptedException ignored) {
|
||||
interrupted = false;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
interrupted = false;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
void interrupt() {
|
||||
synchronized (lock) {
|
||||
interrupted = true;
|
||||
lock.notifyAll();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 3.6 KiB |
|
After Width: | Height: | Size: 5.0 KiB |
|
After Width: | Height: | Size: 1.6 KiB |
|
After Width: | Height: | Size: 2.5 KiB |
|
After Width: | Height: | Size: 2.2 KiB |
|
After Width: | Height: | Size: 3.4 KiB |
@@ -0,0 +1,8 @@
|
||||
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" android:gravity="fill">
|
||||
<item>
|
||||
<bitmap android:gravity="fill" android:src="@drawable/background" />
|
||||
</item>
|
||||
<item>
|
||||
<bitmap android:gravity="center" android:src="@drawable/logo" />
|
||||
</item>
|
||||
</layer-list>
|
||||
|
After Width: | Height: | Size: 5.3 KiB |
|
After Width: | Height: | Size: 6.7 KiB |
|
After Width: | Height: | Size: 9.7 KiB |
|
After Width: | Height: | Size: 10 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 14 KiB |
@@ -0,0 +1,15 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="108dp"
|
||||
android:height="108dp"
|
||||
android:viewportWidth="108"
|
||||
android:viewportHeight="108">
|
||||
<group android:scaleX="0.07382812"
|
||||
android:scaleY="0.07382812"
|
||||
android:translateX="16.2"
|
||||
android:translateY="16.2">
|
||||
<path
|
||||
android:pathData="M843,511.86L843,512.96C843,513.22 842.8,513.43 842.55,513.46C809.18,516.58 783.07,543.69 783.07,577.86L783.07,714.8C783.07,724.37 781.06,733.6 777.43,742.03C767.08,766.1 743.59,783.6 716.27,783.6L647.07,783.6L646.59,783L377.41,445.68L377.41,783.6L307.73,783.6C270.84,783.6 240.93,753.7 240.93,716.8L240.93,577.86C240.93,543.69 214.82,516.58 181.45,513.46C181.2,513.43 181,513.22 181,512.96L181,511.86C181,511.61 181.19,511.4 181.45,511.37C214.69,508.14 240.67,480.35 240.67,446.26L240.67,307.2C240.67,297.91 242.57,289.05 246,281.01C256.18,257.14 279.87,240.39 307.47,240.39L377.13,240.39L377.41,240.74L646.59,578.07L646.59,240.39L716.53,240.39C753.42,240.39 783.33,270.3 783.33,307.2L783.33,446.26C783.33,480.35 809.31,508.14 842.55,511.37C842.81,511.4 843,511.61 843,511.86"
|
||||
android:fillColor="#65ADF1"
|
||||
android:fillType="nonZero"/>
|
||||
</group>
|
||||
</vector>
|
||||
@@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<background android:drawable="@color/ic_launcher_background"/>
|
||||
<foreground android:drawable="@drawable/ic_launcher_foreground"/>
|
||||
</adaptive-icon>
|
||||
|
After Width: | Height: | Size: 3.0 KiB |
|
After Width: | Height: | Size: 1.9 KiB |
|
After Width: | Height: | Size: 4.4 KiB |
|
After Width: | Height: | Size: 7.0 KiB |
|
After Width: | Height: | Size: 10 KiB |
@@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<resources>
|
||||
<!-- You can override base colors from values/colors.xml here, for example: -->
|
||||
<!-- <color name="ns_accent">#65ADF1</color> -->
|
||||
</resources>
|
||||
@@ -0,0 +1,34 @@
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<resources xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
|
||||
<!-- Application theme -->
|
||||
<style name="AppThemeBase21" parent="AppThemeBase">
|
||||
<!-- Uncomment this to make the app show underneat the status bar -->
|
||||
<!-- <item name="android:windowTranslucentStatus">true</item> -->
|
||||
|
||||
<item name="android:datePickerStyle">@style/SpinnerDatePicker</item>
|
||||
<item name="android:timePickerStyle">@style/SpinnerTimePicker</item>
|
||||
</style>
|
||||
|
||||
<style name="AppTheme" parent="AppThemeBase21">
|
||||
</style>
|
||||
|
||||
<!-- Default style for DatePicker - in spinner mode -->
|
||||
<style name="SpinnerDatePicker" parent="android:Widget.Material.Light.DatePicker">
|
||||
<!-- set the default mode for the date picker (supported values: spinner, calendar) -->
|
||||
<item name="android:datePickerMode">spinner</item>
|
||||
</style>
|
||||
|
||||
<!-- Default style for TimePicker - in spinner mode -->
|
||||
<style name="SpinnerTimePicker" parent="android:Widget.Material.Light.TimePicker">
|
||||
<!-- set the default mode for the time picker (supported values: spinner, clock) -->
|
||||
<item name="android:timePickerMode">spinner</item>
|
||||
</style>
|
||||
|
||||
<style name="NativeScriptToolbarStyle" parent="NativeScriptToolbarStyleBase">
|
||||
<item name="android:elevation">4dp</item>
|
||||
|
||||
<!-- Add padding to the ActionBar - useful when android:windowTranslucentStatus is set to true -->
|
||||
<!-- <item name="android:paddingTop">24dp</item> -->
|
||||
</style>
|
||||
</resources>
|
||||
@@ -0,0 +1,18 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
|
||||
<!-- Application theme -->
|
||||
<style name="AppThemeBase29" parent="AppThemeBase21">
|
||||
|
||||
<!--
|
||||
Disable forced dark mode on newer devices.
|
||||
Enabling this will make your app appear in dark-mode,
|
||||
but the way the app is converted may lead to visual issues
|
||||
-->
|
||||
<item name="android:forceDarkAllowed">false</item>
|
||||
</style>
|
||||
|
||||
<style name="AppTheme" parent="AppThemeBase29">
|
||||
</style>
|
||||
|
||||
</resources>
|
||||
@@ -0,0 +1,14 @@
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<resources>
|
||||
<!-- The default color of the ActionBar -->
|
||||
<color name="ns_primary">#F5F5F5</color>
|
||||
|
||||
<!-- (API21+) The color of the status bar and contextual app bars; this is normally a dark version of colorPrimary. -->
|
||||
<color name="ns_primaryDark">#757575</color>
|
||||
|
||||
<!-- The color of UI controls such as check boxes, radio buttons, and edit text boxes. -->
|
||||
<color name="ns_accent">#65ADF1</color>
|
||||
|
||||
<!-- this is unused in the default themes, so we might want to remove it? -->
|
||||
<!-- <color name="ns_blue">#272734</color> -->
|
||||
</resources>
|
||||
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<color name="ic_launcher_background">#FFFFFF</color>
|
||||
</resources>
|
||||
@@ -0,0 +1,42 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
|
||||
<!-- theme to use FOR launch screen-->
|
||||
<style name="LaunchScreenThemeBase" parent="Theme.AppCompat.Light.NoActionBar">
|
||||
<item name="toolbarStyle">@style/NativeScriptToolbarStyle</item>
|
||||
|
||||
<item name="colorPrimary">@color/ns_primary</item>
|
||||
<item name="colorPrimaryDark">@color/ns_primaryDark</item>
|
||||
<item name="colorAccent">@color/ns_accent</item>
|
||||
|
||||
<item name="android:windowBackground">@drawable/splash_screen</item>
|
||||
|
||||
<item name="android:windowActionBarOverlay">true</item>
|
||||
<item name="android:windowTranslucentStatus">true</item>
|
||||
</style>
|
||||
|
||||
<style name="LaunchScreenTheme" parent="LaunchScreenThemeBase">
|
||||
</style>
|
||||
|
||||
<!-- theme to use AFTER launch screen is loaded-->
|
||||
<style name="AppThemeBase" parent="Theme.AppCompat.Light.NoActionBar">
|
||||
<item name="toolbarStyle">@style/NativeScriptToolbarStyle</item>
|
||||
|
||||
<item name="colorPrimary">@color/ns_primary</item>
|
||||
<item name="colorPrimaryDark">@color/ns_primaryDark</item>
|
||||
<item name="colorAccent">@color/ns_accent</item>
|
||||
</style>
|
||||
|
||||
<style name="AppTheme" parent="AppThemeBase">
|
||||
</style>
|
||||
|
||||
<!-- theme for action-bar -->
|
||||
<style name="NativeScriptToolbarStyleBase" parent="Widget.AppCompat.Toolbar">
|
||||
<item name="android:background">@color/ns_primary</item>
|
||||
<item name="theme">@style/ThemeOverlay.AppCompat.ActionBar</item>
|
||||
<item name="popupTheme">@style/ThemeOverlay.AppCompat</item>
|
||||
</style>
|
||||
|
||||
<style name="NativeScriptToolbarStyle" parent="NativeScriptToolbarStyleBase">
|
||||
</style>
|
||||
</resources>
|
||||
@@ -0,0 +1,14 @@
|
||||
This is Faceclaw, an Android program that provides user interface on the Even
|
||||
Realities G2 smart glasses. It is written in a mix of Typescript/NativeScript
|
||||
(for the user interface parts) and Java (for the low-level bluetooth parts and
|
||||
for interfacing with Android SDK).
|
||||
|
||||
Typescript parts are in app/. Java parts are in App_Resources/Android/src/main/java/com/faceclaw/app/.
|
||||
|
||||
If you are working on low-level communication bits, consider checking out
|
||||
https://github.com/Commute773/g2-kit-unofficial/ and referring to ble/docs/
|
||||
and ble/gen/ directories inside. That repository contains automatically
|
||||
extracted protobuf schemas, communication test scripts, and documentation of
|
||||
caveats that come up when communicating with the headset.
|
||||
|
||||
For instructions getting this to compile and install, refer to README.
|
||||
@@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
@@ -0,0 +1,35 @@
|
||||
# Faceclaw - An unofficial user interface for the Even Realities G2 smart glasses
|
||||
|
||||
This is an unofficial user interface for the Even Realities G2 smart glasses.
|
||||
It is entirely unofficial, and comes with no support or warranty from Even
|
||||
Realities or from anyone. If this damages your glasses somehow, this void your
|
||||
warranty.
|
||||
|
||||
THIS IS AN UNFINISHED DEVELOPMENT PROTOTYPE; IF YOU DON'T HAVE ANY PROGRAMMING
|
||||
EXPERIENCE, OR YOU AREN'T COMFORTABLE EDITING, COMPILING, AND SIDELOADING AN
|
||||
ANDROID APPLICATION YOURSELF, OR YOU DON'T HAVE AN ANDROID DEVICE TO RUN IT
|
||||
ON, THIS IS NOT FOR YOU.
|
||||
|
||||
In its current state, it's more of a demo/research project than something you
|
||||
could actually use, mainly because it's extremely slow: updating the display
|
||||
on the headset takes multiple seconds. This is because it's entirely designed
|
||||
around sending images to the headset, which is slow, rather than updating text
|
||||
containers that use the builtin font, which is fast but very limiting. Hopefully
|
||||
a future firmware update or reverse-engineering discovery will speed this up
|
||||
enough to be fully usable. In the mean time, you can use it as a dashboard
|
||||
(which doesn't require fast updates), and you can operate the UI via the phone
|
||||
screen, which shows the same UI but more quickly.
|
||||
|
||||
The name Faceclaw implies plans to integrate this with OpenClaw. These plans
|
||||
have not yet been iplemented. If you want to use OpenClaw with Even Realities G2
|
||||
smart glasses today, consider using OcuClaw (which is an Even Hub app) instead.
|
||||
|
||||
|
||||
## Compiling and Installing
|
||||
|
||||
To compile this, you will need an Android SDK environment, with SDK version 35
|
||||
installed and licenses accepted, and the ANDROID_HOME pointing to the install.
|
||||
You will need a JDK environment (v21), with the JAVA_HOME environment variable
|
||||
pointed at it. You will also need a reasonably up to date npm and nodejs
|
||||
installed.
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
<Frame defaultPage="launch-page">
|
||||
</Frame>
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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.
|
||||
*/
|
||||
@@ -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();
|
||||
}
|
||||
@@ -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>
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
Dimitar Zhekov <dimitar.zhekov@gmail.com>
|
||||
@@ -0,0 +1 @@
|
||||
See OFL.TXT
|
||||
@@ -0,0 +1 @@
|
||||
See CHANGES
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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,
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -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();
|
||||
@@ -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));
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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)}`);
|
||||
}
|
||||
@@ -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 === ":";
|
||||
}
|
||||
|
After Width: | Height: | Size: 7.6 KiB |
@@ -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,
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
<Page xmlns="http://schemas.nativescript.org/tns.xsd" navigatingTo="navigatingTo" actionBarHidden="true">
|
||||
<GridLayout />
|
||||
</Page>
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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>
|
||||
@@ -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)}...`;
|
||||
}
|
||||
}
|
||||
@@ -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"));
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
@@ -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))));
|
||||
}
|
||||