forked from Blendman974/faceclaw
iOS porting: Battery indicators, app icon, add the rest of the apps
This commit is contained in:
1 parent
00a5e38f75
commit
e5ba7abc18
31 files changed
+501
-65
No files matched your search
@@ -0,0 +1,8 @@
|
||||
/** Workers send baked grayscale frames to the main-thread iOS compositor. */
|
||||
const display = {
|
||||
submitSurfaceFrame(buffer: ArrayBuffer, surfaceId: string, _x: number, _y: number, width: number, height: number): void {
|
||||
const data = NSData.dataWithBytesLength(interop.handleof(buffer), buffer.byteLength)
|
||||
global.postMessage({ type: 'surface-frame', surfaceId, width, height, pixels: data.base64EncodedStringWithOptions(0 as NSDataBase64EncodingOptions) })
|
||||
},
|
||||
}
|
||||
export function getActiveDisplay(): typeof display { return display }
|
||||
@@ -124,6 +124,7 @@ export function drainPhoneAlarmJournal(): PhoneAlarmAction[] {
|
||||
|
||||
/** Conditions under which the phone may fail to ring, most serious first. */
|
||||
export function checkPhoneAlarmReliability(): AlarmReliabilityIssue[] {
|
||||
if (global.isIOS) return [{ code: "ios-foreground-only", message: "Keep Faceclaw open: background timer and alarm alerts are not available on iOS yet.", fixable: false }];
|
||||
const context = getContext();
|
||||
if (!context) return [];
|
||||
let parsed: any;
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { knownFolders, path as paths } from '@nativescript/core'
|
||||
export type DirectoryEntry = { name: string; path: string; isDirectory: boolean; sizeBytes: number; modifiedMs: number }
|
||||
const fm = NSFileManager.defaultManager
|
||||
// The iOS Files app exposes Documents; access is limited to Faceclaw's container.
|
||||
export function hasAllFilesAccess(): boolean { return true }
|
||||
export function requestAllFilesAccess(): void {}
|
||||
export function externalStorageRootPath(): string { return knownFolders.documents().path }
|
||||
export function appFilesDirPath(): string { return knownFolders.documents().path }
|
||||
export function statPath(path: string): DirectoryEntry | null {
|
||||
try {
|
||||
const attrs = fm.attributesOfItemAtPathError(path)
|
||||
if (!attrs) return null
|
||||
const modified: any = attrs.objectForKey(NSFileModificationDate)
|
||||
return { name: path.slice(path.lastIndexOf('/') + 1), path, isDirectory: attrs.objectForKey(NSFileType) === NSFileTypeDirectory,
|
||||
sizeBytes: Number(attrs.objectForKey(NSFileSize)) || 0,
|
||||
modifiedMs: modified instanceof Date ? modified.getTime() : Number(modified?.timeIntervalSince1970 ?? 0) * 1000 }
|
||||
} catch { return null }
|
||||
}
|
||||
export function listDirectory(path: string): DirectoryEntry[] | null {
|
||||
try {
|
||||
const names = fm.contentsOfDirectoryAtPathError(path), entries: DirectoryEntry[] = []
|
||||
for (let i = 0; i < names.count; i++) { const entry = statPath(paths.join(path, names.objectAtIndex(i))); if (entry) entries.push(entry) }
|
||||
return entries.sort((a, b) => Number(b.isDirectory) - Number(a.isDirectory) || a.name.localeCompare(b.name))
|
||||
} catch { return null }
|
||||
}
|
||||
export function readBinaryFile(path: string): Uint8Array | null {
|
||||
const data = NSData.dataWithContentsOfFile(path)
|
||||
return data ? new Uint8Array(interop.bufferFromData(data)).slice() : null
|
||||
}
|
||||
export function writeBinaryFile(path: string, bytes: Uint8Array): boolean {
|
||||
try {
|
||||
fm.createDirectoryAtPathWithIntermediateDirectoriesAttributesError(path.slice(0, path.lastIndexOf('/')), true, null)
|
||||
const copy = bytes.slice(), data = NSData.dataWithBytesLength(interop.handleof(copy.buffer), copy.byteLength)
|
||||
return data.writeToFileAtomically(path, true)
|
||||
} catch { return false }
|
||||
}
|
||||
export function readTextFile(path: string): string | null {
|
||||
const entry = statPath(path)
|
||||
if (!entry || entry.isDirectory || entry.sizeBytes > 2_000_000) return null
|
||||
const data = NSData.dataWithContentsOfFile(path)
|
||||
const text = data ? NSString.alloc().initWithDataEncoding(data, NSUTF8StringEncoding) : null
|
||||
return text == null ? null : String(text).slice(0, 500_000)
|
||||
}
|
||||
export function writeTextToDownloads(filename: string, text: string): string | null {
|
||||
const path = paths.join(knownFolders.documents().path, 'Downloads', filename.slice(filename.lastIndexOf('/') + 1))
|
||||
const data = NSString.stringWithString(text).dataUsingEncoding(NSUTF8StringEncoding)
|
||||
return writeBinaryFile(path, new Uint8Array(interop.bufferFromData(data))) ? path : null
|
||||
}
|
||||
export function deletePathRecursively(path: string): void {
|
||||
try { if (fm.fileExistsAtPath(path)) fm.removeItemAtPathError(path) } catch (error) { console.warn(`Delete failed: ${error}`) }
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { openSocket } from "./socket";
|
||||
import { toUint8Array } from "../util/array-util";
|
||||
|
||||
declare const com: any;
|
||||
@@ -181,7 +182,7 @@ export class G2MirrorClient {
|
||||
const generation = ++this.connectionGeneration;
|
||||
const url = `${this.options.secure ? "wss" : "ws"}://${this.options.host}:${this.options.port}`;
|
||||
this.setState("connecting", `Connecting to ${this.options.host}:${this.options.port}...`);
|
||||
this.listenerProxy = new com.faceclaw.app.FaceclawWebSocketListener({
|
||||
this.listenerProxy = {
|
||||
onOpen: () => {
|
||||
if (this.stopped || generation !== this.connectionGeneration) return;
|
||||
this.setState("connecting", "Authenticating...");
|
||||
@@ -206,9 +207,9 @@ export class G2MirrorClient {
|
||||
if (this.stopped || generation !== this.connectionGeneration) return;
|
||||
this.handleConnectionLost(`Connection failed: ${shortenError(String(message))}`);
|
||||
},
|
||||
});
|
||||
};
|
||||
try {
|
||||
this.ws = new com.faceclaw.app.FaceclawWebSocket(url, this.listenerProxy, null, null);
|
||||
this.ws = openSocket(url, this.listenerProxy);
|
||||
} catch (error) {
|
||||
this.ws = null;
|
||||
this.handleConnectionLost(`Connection failed: ${shortenError(String((error as Error)?.message ?? error))}`);
|
||||
@@ -571,11 +572,19 @@ export class G2MirrorClient {
|
||||
|
||||
function decodeBase64(data: string): Uint8Array {
|
||||
if (!data) return new Uint8Array(0);
|
||||
if (global.isIOS) {
|
||||
const decoded = NSData.alloc().initWithBase64EncodedStringOptions(data, 0 as NSDataBase64DecodingOptions);
|
||||
return decoded ? new Uint8Array(interop.bufferFromData(decoded)).slice() : new Uint8Array();
|
||||
}
|
||||
return toUint8Array(android.util.Base64.decode(data, android.util.Base64.DEFAULT));
|
||||
}
|
||||
|
||||
function decodeBase64Utf8(data: string): string {
|
||||
if (!data) return "";
|
||||
if (global.isIOS) {
|
||||
const decoded = NSData.alloc().initWithBase64EncodedStringOptions(data, 0 as NSDataBase64DecodingOptions);
|
||||
return decoded ? String(NSString.alloc().initWithDataEncoding(decoded, NSUTF8StringEncoding) ?? "") : "";
|
||||
}
|
||||
const bytes = android.util.Base64.decode(data, android.util.Base64.DEFAULT);
|
||||
return String(new java.lang.String(bytes, "UTF-8"));
|
||||
}
|
||||
@@ -587,6 +596,7 @@ function stripAnsi(text: string): string {
|
||||
}
|
||||
|
||||
function encodeBase64Utf8(text: string): string {
|
||||
if (global.isIOS) return NSString.stringWithString(text).dataUsingEncoding(NSUTF8StringEncoding).base64EncodedStringWithOptions(0 as NSDataBase64EncodingOptions);
|
||||
const bytes = new java.lang.String(text).getBytes("UTF-8");
|
||||
return String(android.util.Base64.encodeToString(bytes, android.util.Base64.NO_WRAP));
|
||||
}
|
||||
|
||||
@@ -8,6 +8,15 @@ export type PhoneBatteryState = {
|
||||
};
|
||||
|
||||
export function readPhoneBatteryState(): PhoneBatteryState {
|
||||
if (global.isIOS) {
|
||||
const device = UIDevice.currentDevice
|
||||
const level = device.batteryLevel
|
||||
const state = device.batteryState
|
||||
return {
|
||||
battery: level >= 0 ? Math.round(level * 100) : null,
|
||||
charging: state === UIDeviceBatteryState.Unknown ? null : state === UIDeviceBatteryState.Charging || state === UIDeviceBatteryState.Full,
|
||||
}
|
||||
}
|
||||
if (!global.isAndroid) {
|
||||
return { battery: null, charging: null };
|
||||
}
|
||||
|
||||
@@ -1,28 +1,56 @@
|
||||
import { ApplicationSettings } from '@nativescript/core'
|
||||
|
||||
// Main-isolate settings for the initial iOS port. Worker synchronization will
|
||||
// be added when worker-hosted apps are enabled on iOS.
|
||||
// NSUserDefaults is shared by all NativeScript isolates. Each isolate polls
|
||||
// just its observed keys so callbacks always execute on the owning JS thread.
|
||||
const CHANGE_TOKEN = 'ios.settings.changeToken'
|
||||
let lastToken = ApplicationSettings.getString(CHANGE_TOKEN, '')
|
||||
const observed = new Map<string, { read: () => string; value: string }>()
|
||||
function observe(key: string, read: () => string): void {
|
||||
if (!observed.has(key)) observed.set(key, { read, value: read() })
|
||||
}
|
||||
function markChanged(key: string): void {
|
||||
// A unique token lets other isolates check one key while idle. It does not
|
||||
// depend on a read/increment/write counter that concurrent writers could lose.
|
||||
ApplicationSettings.setString(CHANGE_TOKEN, `${Date.now()}:${Math.random()}`)
|
||||
const item = observed.get(key)
|
||||
if (item) item.value = item.read()
|
||||
changed(key)
|
||||
}
|
||||
let pollTimer: ReturnType<typeof setInterval> | null = null
|
||||
const listeners = new Set<(key: string) => void>()
|
||||
function changed(key: string): void {
|
||||
setTimeout(() => { for (const listener of [...listeners]) listener(key) }, 0)
|
||||
}
|
||||
export function getStringSetting(key: string, fallback: string): string {
|
||||
return ApplicationSettings.getString(key, fallback)
|
||||
const value = ApplicationSettings.getString(key, fallback)
|
||||
observe(key, () => JSON.stringify(ApplicationSettings.getString(key, fallback)))
|
||||
return value
|
||||
}
|
||||
export function setStringSetting(key: string, value: string): void {
|
||||
if (getStringSetting(key, '') === value && ApplicationSettings.hasKey(key)) return
|
||||
ApplicationSettings.setString(key, value)
|
||||
changed(key)
|
||||
markChanged(key)
|
||||
}
|
||||
export function getBooleanSetting(key: string, fallback: boolean): boolean {
|
||||
return ApplicationSettings.getBoolean(key, fallback)
|
||||
const value = ApplicationSettings.getBoolean(key, fallback)
|
||||
observe(key, () => JSON.stringify(ApplicationSettings.getBoolean(key, fallback)))
|
||||
return value
|
||||
}
|
||||
export function setBooleanSetting(key: string, value: boolean): void {
|
||||
if (getBooleanSetting(key, false) === value && ApplicationSettings.hasKey(key)) return
|
||||
ApplicationSettings.setBoolean(key, value)
|
||||
changed(key)
|
||||
markChanged(key)
|
||||
}
|
||||
export function onSettingsStoreChanged(listener: (key: string) => void): () => void {
|
||||
listeners.add(listener)
|
||||
return () => { listeners.delete(listener) }
|
||||
if (!pollTimer) pollTimer = setInterval(() => {
|
||||
const token = ApplicationSettings.getString(CHANGE_TOKEN, '')
|
||||
if (token === lastToken) return
|
||||
lastToken = token
|
||||
for (const [key, item] of observed) {
|
||||
const value = item.read()
|
||||
if (value !== item.value) { item.value = value; changed(key) }
|
||||
}
|
||||
}, 250)
|
||||
return () => { listeners.delete(listener); if (!listeners.size && pollTimer) { clearInterval(pollTimer); pollTimer = null } }
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
export type SocketListener = { onOpen(): void; onTextMessage(message: string): void; onClosed(code: number, reason: string): void; onFailure(message: string): void }
|
||||
declare const FaceclawSocket: any
|
||||
export function openSocket(url: string, listener: SocketListener): { sendText(text: string): void; close(code: number, reason: string): void } {
|
||||
const native = FaceclawSocket.alloc().initWithURL(url)
|
||||
let ended = false
|
||||
const close = () => { if (ended) return; ended = true; clearInterval(timer); native.close() }
|
||||
const timer = setInterval(() => {
|
||||
for (const event of JSON.parse(native.takeEvents())) {
|
||||
if (ended) break
|
||||
if (event.kind === 'open') listener.onOpen()
|
||||
else if (event.kind === 'text') listener.onTextMessage(event.text)
|
||||
else { close(); if (event.kind === 'closed') listener.onClosed(event.code, event.text); else listener.onFailure(event.text) }
|
||||
}
|
||||
}, 25)
|
||||
return { sendText: text => { if (!ended) native.sendText(text) }, close }
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
declare const com: any
|
||||
export type SocketListener = { onOpen(): void; onTextMessage(message: string): void; onClosed(code: number, reason: string): void; onFailure(message: string): void }
|
||||
export function openSocket(url: string, listener: SocketListener): { sendText(text: string): void; close(code: number, reason: string): void } {
|
||||
const proxy = new com.faceclaw.app.FaceclawWebSocketListener(listener)
|
||||
const native = new com.faceclaw.app.FaceclawWebSocket(url, proxy, null, null)
|
||||
const connection = { listenerProxy: proxy, sendText: (text: string) => native.sendText(text),
|
||||
close: (code: number, reason: string) => native.close(code, reason) }
|
||||
return connection
|
||||
}
|
||||
Reference in new issue
Block a user