Compare commits

Author SHA1 Message Date
Blendman974 75bceb3b92 fix: support Android 16 KiB pages in native llama library 2026-11-06 04:21:43 +01:00
13 changed files with 171 additions and 719 deletions

No files matched your search

@@ -29,3 +29,8 @@ add_subdirectory(${LLAMA_CPP_SOURCE_DIR} llama.cpp-build EXCLUDE_FROM_ALL)
add_library(faceclaw_llama SHARED faceclaw_llama.cpp)
target_link_libraries(faceclaw_llama PRIVATE llama android log)
# NDK r27 defaults to 4 KiB. Align both LOAD segments and RELRO boundaries
# for Android devices using 16 KiB pages, including debug APKs.
target_link_options(faceclaw_llama PRIVATE
"-Wl,-z,max-page-size=16384"
"-Wl,-z,common-page-size=16384")
+20 -131
View File
@@ -8,11 +8,7 @@ import { IconGrid, ICON_GRID_BAND_INSET_X, ICON_GRID_HIGHLIGHT_INSET_Y, ICON_GRI
import { Layer, LayerActions, LayerContext } from "../../ui/layers";
import { MenuLayer, type MenuItem } from "../../ui/menu";
import { WINDOW_MENU_LAYOUT } from "../../ui/window-menu";
import {
onAnySettingChanged, launcherLayoutSetting, enumSettingMenuItem,
ConfigSettingString, EditTextSettingLayer,
} from "../../ui/dashboard-settings";
import { getLauncherLayoutFingerprint, orderLauncherEntries, moveLauncherEntry } from "./launcher-layout";
import { onAnySettingChanged } from "../../ui/dashboard-settings";
import { createInProcessWindow } from "../../ui/shell/in-process-window";
import {
getFolderAssignments,
@@ -20,7 +16,6 @@ import {
getFolderStateFingerprint,
setAppFolder,
unusedNewFolderName,
getExplicitFolderNames, createFolder, renameFolder, folderNameError, disbandFolder,
} from "./launcher-folders";
import { shell, type ShellWindow } from "../../ui/shell/shell";
@@ -71,14 +66,6 @@ type LauncherGridEntry =
* and is re-read every paint, so assistant folder tools take effect without
* the layer holding any copy of the state.
*/
const entryKey = (entry: LauncherGridEntry) => entry.kind === "app" ? `app:${entry.appId}` : `folder:${entry.name}`;
/** Reuse the phone text editor; dismiss it if the glasses leave this page. */
class FolderNameEditorLayer extends EditTextSettingLayer {
constructor(setting: ConfigSettingString, private readonly actions: LayerActions) { super(setting); }
onRemoved(): void { void this.actions.endTextSettingEdit(); }
}
class LauncherGridLayer implements Layer {
// Watch swipes are spatial: up/down move between rows, left/right between
// columns. From the leftmost column, left keeps going out: it leaves the
@@ -87,12 +74,6 @@ class LauncherGridLayer implements Layer {
readonly acceptsDirectional = true;
/** Folder whose contents the grid is showing, or null for the top grid. */
private currentFolder: string | null = null;
private editingFolder = false;
private moving: { key: string; label: string; folder: string | null } | null = null;
private sortEntries(entries: LauncherGridEntry[]): LauncherGridEntry[] {
return orderLauncherEntries(entries, entryKey, this.currentFolder, launcherLayoutSetting.get() === "custom");
}
private readonly grid = new IconGrid<LauncherGridEntry>({
items: () => this.entries(),
describe: (entry) => ({
@@ -123,23 +104,25 @@ class LauncherGridLayer implements Layer {
const members = (getFolders().get(this.currentFolder) ?? [])
.map((appId) => byAppId.get(appId))
.filter(Boolean) as LauncherAppEntry[];
if (members.length > 0 || getExplicitFolderNames().includes(this.currentFolder)) {
return this.sortEntries(members.map((app): LauncherGridEntry => ({
if (members.length > 0) {
return members
.map((app): LauncherGridEntry => ({
kind: "app",
label: app.label,
icon: app.icon,
appId: app.appId,
renderIcon: app.renderIcon,
})));
}))
.sort((a, b) => a.label.localeCompare(b.label));
}
this.currentFolder = null;
}
const assignments = getFolderAssignments();
const entries: LauncherGridEntry[] = [];
// Legacy folders need a known member; explicitly created folders may be empty.
const explicit = new Set(getExplicitFolderNames());
// A folder cell appears only when it holds at least one known app; stale
// assignments to removed apps are ignored.
for (const [name, members] of getFolders()) {
if (explicit.has(name) || members.some((appId) => byAppId.has(appId))) {
if (members.some((appId) => byAppId.has(appId))) {
entries.push({ kind: "folder", label: name, name });
}
}
@@ -154,7 +137,7 @@ class LauncherGridLayer implements Layer {
});
}
}
return this.sortEntries(entries);
return entries.sort((a, b) => a.label.localeCompare(b.label));
}
/** Leave the current folder, putting the selection back on its cell. */
@@ -168,16 +151,6 @@ class LauncherGridLayer implements Layer {
/** Enter a folder or launch an app; true when that left the grid (a launch). */
private async openEntry(entry: LauncherGridEntry): Promise<boolean> {
if (this.moving) {
const moving = this.moving;
this.moving = null;
if (launcherLayoutSetting.get() === "custom" && moving.folder === this.currentFolder) {
moveLauncherEntry(this.currentFolder, this.entries().map(entryKey), moving.key, entryKey(entry));
const index = this.entries().findIndex(item => entryKey(item) === moving.key);
if (index >= 0) this.grid.selectIndex(index);
}
return false;
}
if (entry.kind === "folder") {
this.currentFolder = entry.name;
this.grid.resetSelection();
@@ -193,13 +166,6 @@ class LauncherGridLayer implements Layer {
/** Leave the open folder, else yield to the sidebar; true when that left the grid. */
private back(): boolean {
if (this.moving) {
const key = this.moving.key;
this.moving = null;
const index = this.entries().findIndex(entry => entryKey(entry) === key);
if (index >= 0) this.grid.selectIndex(index);
return false;
}
if (this.currentFolder !== null) {
this.exitFolder();
return false;
@@ -209,54 +175,14 @@ class LauncherGridLayer implements Layer {
}
/**
* Layout and folder creation are always available. Per-icon actions need
* item mode so row navigation never edits an ambiguous selection.
* App-specific entries for the window's context menu. Only item mode
* pins the selection to a single cell, and only apps can move to folders,
* so anywhere else the menu falls back to just the defaults.
*/
menuItems(): MenuItem[] {
if (this.editingFolder) return [];
const entry = this.grid.selectedItem;
const items: MenuItem[] = [
enumSettingMenuItem(launcherLayoutSetting, { onChange: () => { this.moving = null; this.grid.resetSelection(); } }),
{
label: "New folder",
onSelect: ctx => {
const name = unusedNewFolderName();
if (createFolder(name)) {
this.currentFolder = null;
this.moving = null;
this.grid.resetSelection();
this.grid.selectIndex(this.entries().findIndex(item => item.kind === "folder" && item.name === name));
}
ctx.stack.pop();
},
},
];
const folder = entry?.kind === "folder" ? entry.name : this.currentFolder;
if (folder !== null) {
items.push({ label: "Rename folder", onSelect: ctx => this.editFolderName(folder, ctx) }, {
label: "Delete folder",
onSelect: ctx => {
ctx.stack.pop();
ctx.stack.push(new MenuLayer("Delete folder? Apps stay installed.", [
{ label: "Delete folder", onSelect: confirm => {
disbandFolder(folder);
if (this.currentFolder === folder) this.currentFolder = null;
this.moving = null;
this.grid.resetSelection();
confirm.stack.pop();
} },
{ label: "Cancel", onSelect: confirm => confirm.stack.pop() },
], WINDOW_MENU_LAYOUT));
},
});
}
if (this.moving) items.push({ label: "Cancel move", onSelect: ctx => { this.back(); ctx.stack.pop(); } });
else if (entry && launcherLayoutSetting.get() === "custom") items.push({
label: "Move icon",
onSelect: ctx => { this.moving = { key: entryKey(entry), label: entry.label, folder: this.currentFolder }; ctx.stack.pop(); },
});
if (!entry || entry.kind !== "app") return items;
return [...items,
if (!entry || entry.kind !== "app") return [];
return [
{
label: "Move to folder",
onSelect: (ctx) => {
@@ -295,32 +221,6 @@ class LauncherGridLayer implements Layer {
];
}
private editFolderName(folder: string, ctx: LayerContext): void {
ctx.stack.pop();
const setting = new ConfigSettingString({
id: "launcher-folder-name", label: "Folder name", storageKey: "launcher.folderNameDraft",
defaultValue: folder, normalize: value => value ?? "",
validate: value => folderNameError(value, folder), reportInAnalytics: false,
});
setting.set(folder);
this.editingFolder = true;
const editor = new FolderNameEditorLayer(setting, ctx.actions);
ctx.stack.push(editor);
void ctx.actions.startTextSettingsEdit([setting], "Rename folder", () => {
this.editingFolder = false;
if (renameFolder(folder, setting.get())) {
if (this.currentFolder === folder) this.currentFolder = setting.get().trim();
this.moving = null;
}
ctx.stack.popIfTop(layer => layer === editor);
ctx.actions.requestRender();
}, undefined, () => {
this.editingFolder = false;
ctx.stack.popIfTop(layer => layer === editor);
ctx.actions.requestRender();
});
}
/**
* The folder-picker submenu: every existing folder except the app's own,
* plus a generated-name "New folder" (ring input has no text entry) and,
@@ -342,9 +242,7 @@ class LauncherGridLayer implements Layer {
items.push({
label: "New folder",
onSelect: (ctx) => {
const name = unusedNewFolderName();
createFolder(name);
setAppFolder(appId, name);
setAppFolder(appId, unusedNewFolderName());
ctx.stack.pop();
},
});
@@ -365,16 +263,8 @@ class LauncherGridLayer implements Layer {
const { width, height } = ctx.stack.getBaseSize();
const image = new GrayImage(width, height, 0);
// The folder-name header band scales with the font.
const entries = this.entries();
if (this.moving && (launcherLayoutSetting.get() !== "custom" || this.moving.folder !== this.currentFolder ||
!entries.some(entry => entryKey(entry) === this.moving!.key))) this.moving = null;
const gridTop = this.moving ? GRID_TOP + 2 * (font.lineHeight + 2)
: this.currentFolder !== null ? GRID_TOP + font.lineHeight + 4 : ROOT_GRID_TOP;
if (this.moving) {
image.drawText(font, 8, GRID_TOP - 2, truncateText(font, `Move ${this.moving.label}`, width - 16), 220);
image.drawText(font, 8, GRID_TOP + font.lineHeight, "Select position; double tap cancels", 160);
}
if (this.currentFolder !== null && !this.moving) {
const gridTop = this.currentFolder !== null ? GRID_TOP + font.lineHeight + 4 : ROOT_GRID_TOP;
if (this.currentFolder !== null) {
image.drawText(font, 8, GRID_TOP - 2, truncateText(font, this.currentFolder, width - 16), 160);
}
// The grid runs to the window's bottom edge, so a row cut off there for
@@ -384,7 +274,6 @@ class LauncherGridLayer implements Layer {
}
async handleInput(event: InputEvent, ctx: LayerContext): Promise<void> {
if (this.moving && event.type === "double-click") { this.back(); return; }
await this.grid.handleInput(event, ctx);
}
@@ -422,9 +311,9 @@ export function createLauncherWindow(options: LauncherOptions): ShellWindow {
// keeps every unrelated setting change from repainting the launcher. The
// launcher is pinned for the app's lifetime, so the subscription never needs
// tearing down.
let lastState = `${getFolderStateFingerprint()}\n${getLauncherLayoutFingerprint()}\n${launcherAppsFingerprint(options.apps())}`;
let lastState = `${getFolderStateFingerprint()}\n${launcherAppsFingerprint(options.apps())}`;
onAnySettingChanged(() => {
const state = `${getFolderStateFingerprint()}\n${getLauncherLayoutFingerprint()}\n${launcherAppsFingerprint(options.apps())}`;
const state = `${getFolderStateFingerprint()}\n${launcherAppsFingerprint(options.apps())}`;
if (state === lastState) return;
lastState = state;
created.requestRender();
+11 -51
View File
@@ -1,50 +1,14 @@
/** Launcher assignments keep their legacy format; explicitly created folders may be empty. */
/**
* Launcher folder state: which apps are grouped into which named folder.
* Stored as one JSON string (appId -> folder name) in the settings store, so
* it persists and its changes broadcast to every isolate. An unset value means
* the default grouping; any edit persists the whole map, so clearing out the
* defaults sticks. Folders exist only while at least one app is assigned to
* them — there is no separate create/delete step.
*/
import { getStringSetting, setStringSetting } from "../../native/settings-store";
import { renameLauncherFolderOrder, removeLauncherFolderOrder } from "./launcher-layout";
const STORAGE_KEY = "launcher.folders";
const NAMES_KEY = "launcher.folderNames";
/** Only user-created/renamed folders persist after their last member leaves. */
export function getExplicitFolderNames(): string[] {
try {
const value = JSON.parse(getStringSetting(NAMES_KEY, "[]"));
return Array.isArray(value) ? [...new Set(value.filter((name): name is string =>
typeof name === "string" && !!name.trim()).map(name => name.trim()))] : [];
} catch { return []; }
}
export function folderNameError(input: string, previous?: string): string | null {
const name = input.trim();
if (!name) return "Enter a folder name.";
if (name.length > FOLDER_NAME_MAX_LENGTH) return `Use at most ${FOLDER_NAME_MAX_LENGTH} characters.`;
if (/[\u0000-\u001f\u007f]/.test(name)) return "Use a single-line folder name.";
if (previous !== undefined && !getFolders().has(previous)) return "This folder no longer exists.";
for (const existing of getFolders().keys()) {
if (existing !== previous && existing.toLowerCase() === name.toLowerCase()) return "A folder with this name already exists.";
}
return null;
}
export function createFolder(input: string): boolean {
if (folderNameError(input)) return false;
setStringSetting(NAMES_KEY, JSON.stringify([...getExplicitFolderNames(), input.trim()]));
return true;
}
export function renameFolder(previous: string, input: string): boolean {
if (folderNameError(input, previous)) return false;
const name = input.trim();
if (name === previous) return true;
const assignments = getFolderAssignments();
for (const appId of Object.keys(assignments)) if (assignments[appId] === previous) assignments[appId] = name;
// Preserve position and per-folder order when the visible name changes.
renameLauncherFolderOrder(previous, name);
setStringSetting(NAMES_KEY, JSON.stringify([...getExplicitFolderNames().filter(n => n !== previous), name]));
setStringSetting(STORAGE_KEY, JSON.stringify(assignments));
return true;
}
/** The out-of-the-box grouping, applied only while the setting is unset. */
const DEFAULT_ASSIGNMENTS: Record<string, string> = {
@@ -68,7 +32,7 @@ export function getFolderAssignments(): Record<string, string> {
try {
const parsed = JSON.parse(raw);
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};
const assignments: Record<string, string> = Object.create(null);
const assignments: Record<string, string> = {};
for (const appId of Object.keys(parsed)) {
const folder = parsed[appId];
if (typeof folder === "string" && folder.trim()) {
@@ -94,7 +58,6 @@ export function getFolders(): Map<string, string[]> {
unsorted.set(folder, [appId]);
}
}
for (const name of getExplicitFolderNames()) if (!unsorted.has(name)) unsorted.set(name, []);
const folders = new Map<string, string[]>();
for (const name of Array.from(unsorted.keys()).sort((a, b) => a.localeCompare(b))) {
folders.set(name, unsorted.get(name)!);
@@ -123,8 +86,6 @@ export function disbandFolder(folder: string): number {
moved++;
}
}
setStringSetting(NAMES_KEY, JSON.stringify(getExplicitFolderNames().filter(name => name !== folder)));
removeLauncherFolderOrder(folder);
if (moved > 0) {
setStringSetting(STORAGE_KEY, JSON.stringify(assignments));
}
@@ -134,7 +95,7 @@ export function disbandFolder(folder: string): number {
/**
* An unused name for a ring-created folder ("New folder", "New folder 2", …).
* Ring input has no text entry, so new folders start with a generated name;
* Rename folder uses the existing phone text editor for a custom name.
* the assistant's folder tools can regroup the apps under a better one.
*/
export function unusedNewFolderName(): string {
const existing = new Set(Array.from(getFolders().keys()).map((name) => name.toLowerCase()));
@@ -158,6 +119,5 @@ export function resolveFolderName(input: string): string {
/** Raw stored value, for cheap change detection by the launcher window. */
export function getFolderStateFingerprint(): string {
return JSON.stringify([getStringSetting(STORAGE_KEY, ""), getStringSetting(NAMES_KEY, ""),
getStringSetting("launcher.folderNameDraft", "")]);
return getStringSetting(STORAGE_KEY, "");
}
-60
View File
@@ -1,60 +0,0 @@
import { getStringSetting, setStringSetting } from "../../native/settings-store";
const ORDER_KEY = "launcher.order";
const scopeKey = (folder: string | null) => folder === null ? "root" : `folder:${folder}`;
function readOrders(): Record<string, string[]> {
try {
const value = JSON.parse(getStringSetting(ORDER_KEY, "{}"));
if (!value || typeof value !== "object" || Array.isArray(value)) return {};
return Object.fromEntries(Object.entries(value).filter(([, order]) => Array.isArray(order))
.map(([scope, order]) => [scope, [...new Set((order as unknown[]).filter((id): id is string => typeof id === "string"))]]));
} catch { return {}; }
}
export function setLauncherOrder(folder: string | null, ids: readonly string[]): void {
const orders = readOrders();
orders[scopeKey(folder)] = [...new Set(ids)];
setStringSetting(ORDER_KEY, JSON.stringify(orders));
}
/** Unseen apps append alphabetically; changing sort modes never destroys saved order. */
export function orderLauncherEntries<T extends { label: string }>(
entries: T[], key: (entry: T) => string, folder: string | null, custom: boolean,
): T[] {
const order = custom ? readOrders()[scopeKey(folder)] ?? [] : [];
const rank = new Map(order.map((id, index) => [id, index]));
return entries.sort((a, b) => (rank.get(key(a)) ?? Infinity) - (rank.get(key(b)) ?? Infinity) ||
a.label.localeCompare(b.label) || key(a).localeCompare(key(b)));
}
/** Move into the target's position, without moving apps across folders. */
export function moveLauncherEntry(folder: string | null, ids: string[], source: string, target: string): boolean {
const from = ids.indexOf(source), to = ids.indexOf(target);
if (from < 0 || to < 0) return false;
const next = ids.slice();
next.splice(from, 1);
next.splice(to, 0, source);
setLauncherOrder(folder, next);
return true;
}
export function renameLauncherFolderOrder(previous: string, next: string): void {
const orders = readOrders();
const oldScope = scopeKey(previous), newScope = scopeKey(next);
if (orders[oldScope]) orders[newScope] = orders[oldScope];
delete orders[oldScope];
if (orders.root) orders.root = orders.root.map(id => id === `folder:${previous}` ? `folder:${next}` : id);
setStringSetting(ORDER_KEY, JSON.stringify(orders));
}
export function removeLauncherFolderOrder(folder: string): void {
const orders = readOrders();
delete orders[scopeKey(folder)];
if (orders.root) orders.root = orders.root.filter(id => id !== `folder:${folder}`);
setStringSetting(ORDER_KEY, JSON.stringify(orders));
}
export function getLauncherLayoutFingerprint(): string {
return JSON.stringify([getStringSetting("launcher.layout", "alphabetical"), getStringSetting(ORDER_KEY, "")]);
}
+3 -4
View File
@@ -191,7 +191,7 @@ function registerTools(options: WindowToolsOptions, registry: ToolRegistry): voi
const lines: string[] = [];
for (const [name, members] of getFolders()) {
const known = members.filter((appId) => appIds.indexOf(appId) >= 0).sort();
if (known.length || members.length === 0) lines.push(`${name}: ${known.length ? known.map(describeApp).join(", ") : "(empty)"}`);
if (known.length) lines.push(`${name}: ${known.map(describeApp).join(", ")}`);
}
const assignments = getFolderAssignments();
const ungrouped = appIds.filter((appId) => !assignments[appId]);
@@ -237,7 +237,7 @@ function registerTools(options: WindowToolsOptions, registry: ToolRegistry): voi
{
name: "apps.remove_from_folder",
description:
"Move an app out of its launcher folder back to the top-level grid. Default folders disappear when their last app is removed; user-created folders can stay empty.",
"Move an app out of its launcher folder back to the top-level grid. A folder disappears when its last app is removed.",
inputSchema: {
type: "object",
properties: {
@@ -276,9 +276,8 @@ function registerTools(options: WindowToolsOptions, registry: ToolRegistry): voi
(args) => {
const folder = resolveFolderName(String(args?.folder ?? ""));
if (!folder) return err("folder must be a non-empty name");
const existed = getFolders().has(folder);
const moved = disbandFolder(folder);
if (moved === 0 && !existed) {
if (moved === 0) {
const names = Array.from(getFolders().keys());
return err(
names.length
-7
View File
@@ -200,13 +200,6 @@ export class ConfigSettingEnum<TValue extends string, TId extends string = strin
}
}
export const launcherLayoutSetting = new ConfigSettingEnum({
id: "launcher-layout", label: "Layout", storageKey: "launcher.layout",
defaultValue: "alphabetical", values: ["alphabetical", "custom"] as const,
formatValue: value => value === "custom" ? "Custom" : "Alphabetical",
description: "Sort apps and folders alphabetically, or arrange icons yourself. Custom positions are remembered when switching layouts.",
});
type ConfigSettingStringOptions<TId extends string> = ConfigSettingOptions<string, TId> & {
editorTitle?: string;
glassesEditTitle?: string;
+2 -50
View File
@@ -326,7 +326,7 @@ class ShellOverlayMenuLayer extends MenuLayer {
*/
keepWindowFocus = false;
constructor(items: MenuItem[], footer: string | undefined, private readonly onClosed: () => void, title = "System") {
constructor(items: MenuItem[], footer: string | undefined, private readonly onClosed: () => void) {
// Aligned to the min-height window band (like the sidebar), wherever the
// vertical position setting currently puts it; centered over the
// application area, i.e. the part of the screen beside a side strip
@@ -334,7 +334,7 @@ class ShellOverlayMenuLayer extends MenuLayer {
// the strip overlays).
const width = 272;
const area = appViewportRect("min");
super(title, items, {
super("System", items, {
x: area.x + (((area.width - width) / 2) | 0),
y: area.y + 8,
width,
@@ -1304,43 +1304,6 @@ class Shell {
return hidden ? this.windows.filter((window) => window !== hidden) : this.windows;
}
/** Reorder visible app windows while keeping pinned/temporary slots and foreground stable. */
private moveSwitcherWindow(windowId: string, targetId: string): boolean {
const movable = this.switcherWindows().filter(window => window.closeable);
const from = movable.findIndex(window => window.windowId === windowId);
const to = movable.findIndex(window => window.windowId === targetId);
if (from < 0 || to < 0 || from === to) return false;
const foreground = this.foregroundWindow();
const ids = new Set(movable.map(window => window.windowId));
const [moved] = movable.splice(from, 1);
movable.splice(to, 0, moved!);
let index = 0;
this.windows = this.windows.map(window => ids.has(window.windowId) ? movable[index++]! : window);
if (foreground) this.selectedIndex = this.windows.indexOf(foreground);
this.config.onWindowsChanged?.();
this.config.requestShellRender();
return true;
}
/** Capture window IDs: changing titles or closing windows cannot redirect a pending move. */
private openSwitcherMoveMenu(windowId: string): void {
if (!this.screenOn || this.activeVoiceLayer || !this.stack.isAtBase()) return;
const movable = this.switcherWindows().filter(window => window.closeable);
const selected = movable.findIndex(window => window.windowId === windowId);
if (selected < 0 || movable.length < 2) return;
const items: MenuItem[] = movable.map((window, index) => ({
label: `${index + 1}. ${window.title}`,
onSelect: ctx => {
ctx.stack.pop();
this.moveSwitcherWindow(windowId, window.windowId);
},
}));
const layer = new ShellOverlayMenuLayer(items, undefined, () => this.yieldFocusToSidebar(), "Move app to position");
layer.selectItem(selected);
this.stack.push(layer);
this.config.requestShellRender();
}
/**
* The status bar items the switcher's selection can move onto, in order:
* with a bottom switcher (the selection reaches them past the last
@@ -1996,17 +1959,6 @@ class Shell {
},
}]),
);
const movableWindows = this.switcherWindows().filter(window => window.closeable);
if (movableWindows.length > 1 && movableWindows.includes(foreground)) {
items.push({
label: "Move in app switcher",
description: "Choose this open window's position in the app switcher.",
onSelect: ctx => {
ctx.stack.pop();
this.openSwitcherMoveMenu(foreground.windowId);
},
});
}
if (brightnessSetting.get() !== "auto") {
items.push({
label: "Brightness",
+33
View File
@@ -0,0 +1,33 @@
# Android 16 KiB page compatibility
The initial debug APK triggered Android's page-size compatibility warning.
Its `libfaceclaw_llama.so` LOAD segments were aligned to 4096 bytes. The other
six packaged arm64 libraries were aligned to 16384 bytes, and APK ZIP alignment
already passed `zipalign -c -P 16 4`.
The llama JNI shared library now links with both `max-page-size=16384` and
`common-page-size=16384`, matching the LC3 JNI library. This changes the native
binary layout rather than hiding the compatibility warning or disabling debug.
Gradle already tracks CMakeLists.txt as an input, and Ninja reconfigures and
relinks existing builds after this change.
Reproduce the regression and artifact checks inside `devenv shell`:
```sh
python3 -m unittest discover -s tests -p test_apk_pages.py
bash build.sh
python3 scripts/check-apk-pages.py platforms/android/app/build/outputs/apk/debug/app-debug.apk
"$ANDROID_HOME/build-tools/35.0.1/zipalign" -c -P 16 4 platforms/android/app/build/outputs/apk/debug/app-debug.apk
```
The checker rejects the initial APK and reports its misaligned llama library.
Five unit tests cover 4 KiB rejection, 16 KiB acceptance, RELRO boundaries and
invalid ELF program headers. APK checks inspect all arm64/x86_64 shared libraries.
Reference: [Android's 16 KiB guidance](https://developer.android.com/guide/practices/page-sizes).
Static alignment and successful installation do not prove every native code
path works on-device; voice/LLM features still require functional testing.
The rebuilt APK passes all seven native-library checks, ZIP alignment and APK
signature verification. The connected Pixel 10 Pro Fold reports `getconf
PAGE_SIZE` = 4096; actual execution with 16 KiB pages remains untested.
-23
View File
@@ -1,23 +0,0 @@
# Launcher folders and layouts
Open the Apps window's app menu (tap then hold by default). Layout and New folder are available even without a single icon selected. New folder creates a persistent empty folder with an unused generated name. Select a folder, or enter it, to rename it through the existing phone text editor. Rename commits on Submit; Cancel leaves the folder unchanged. Names must be non-empty, single-line, at most 24 characters, and unique ignoring case. Delete folder requires confirmation and returns its apps to the root without uninstalling them.
Layout offers Alphabetical (the existing default) and Custom. In Custom, select an app or folder icon and choose Move icon, navigate to its destination and click to place it at that position. Double tap cancels; the watch's back from the left edge also cancels. The phone mirror can select the destination too. Moves stay within the root or current folder; Move to folder and Remove from folder remain available for changing membership. Renaming a folder preserves its root position and internal order. New apps append alphabetically after saved icons. Switching to Alphabetical retains saved custom positions for later use.
Persistence uses the existing shared settings store. The legacy launcher.folders assignment map stays compatible; new launcher.folderNames metadata preserves explicitly created/renamed empty folders. Untouched legacy folders keep disappearing when their last app is removed. launcher.layout stores the mode, and launcher.order stores root and per-folder order. Assistant folder tools remain consistent with empty folders. Existing installations retain their grouping and alphabetical layout.
Software checks cover defaults, restart, existing assignments, empty folder creation/deletion, duplicate and invalid names, rename commit/cancel, independent root/folder positions, layout toggling, new/removed apps, malformed metadata, move cancellation and deletion confirmation. TypeScript and changed-source lint are checked separately.
Hardware validation remains pending: ring row/item selection, watch directional navigation and back, moving across scroll rows, phone-mirror placement, phone rename Submit/Cancel, reopening folders and app restart. No firmware was flashed.
Independent branch validation: 1073 JavaScript tests passed, 2 skipped, 0 failed; TypeScript and changed-source lint passed.
## Open app switcher order
The system menu adds Move in app switcher when the selected window can be moved and at least two app windows are open. Its numbered position picker shows the currently open app windows in switcher order, preselects the current position, and uses window IDs internally to distinguish windows with identical titles. Choose a destination to move there, or double tap to cancel.
This arranges existing open windows independently of the launcher's Alphabetical/Custom preference. Pinned windows keep their slots and temporary status-item windows do not participate. Reordering retains the same foreground window, attention state and most-recently-used history; closing a window still returns to the most recently viewed one. New windows append as before. Open-window order lasts for those windows' lifetime; reopening the app does not restore previously closed windows or write ephemeral window IDs to settings.
Software tests cover both directions, menu integration, duplicate titles, captured source IDs, cancellation, removed source/destination, temporary and pinned windows, appending/replacing windows, foreground identity and MRU close behavior. Hardware checks remain pending for ring/watch navigation in the position picker and left/right/bottom/popup switcher placements.
Independent branch after adding open-window ordering: 1080 JavaScript tests passed, 2 skipped; TypeScript and changed-source lint passed.
+57
View File
@@ -0,0 +1,57 @@
#!/usr/bin/env python3
"""Check ELF64 LOAD/RELRO alignment in an APK; pair with zipalign -c -P 16 4."""
import argparse
import struct
import zipfile
PAGE = 16384
def alignment_errors(data):
if len(data) < 64 or data[:4] != b"\x7fELF" or data[4] != 2 or data[5] not in (1, 2):
return ["expected an ELF64 library"]
endian = "<" if data[5] == 1 else ">"
offset = struct.unpack_from(endian + "Q", data, 32)[0]
size, count = struct.unpack_from(endian + "HH", data, 54)
if size < 56 or offset + size * count > len(data):
return ["invalid program headers"]
headers = [struct.unpack_from(endian + "IIQQQQQQ", data, offset + i * size) for i in range(count)]
errors = []
loads = [h for h in headers if h[0] == 1]
if not loads:
errors.append("no LOAD segments")
for h in loads:
if h[7] < PAGE or h[7] % PAGE or (h[3] - h[2]) % PAGE:
errors.append(f"LOAD alignment {h[7]} is incompatible with 16 KiB pages")
for h in headers:
if h[0] != 0x6474E552:
continue
end = h[3] + h[6]
# A RELRO ending within a writable LOAD may protect unrelated writable
# data on a 16 KiB device. A separate LOAD after RELRO is also safe.
if end % PAGE and any(p[1] & 2 and p[3] <= h[3] and end < p[3] + p[6] for p in loads):
errors.append("RELRO ends inside writable LOAD without 16 KiB alignment")
return errors
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("apk")
args = parser.parse_args()
checked = 0
failed = False
with zipfile.ZipFile(args.apk) as archive:
for name in archive.namelist():
if not name.startswith(("lib/arm64-v8a/", "lib/x86_64/")) or not name.endswith(".so"):
continue
checked += 1
errors = alignment_errors(archive.read(name))
failed |= bool(errors)
print(f"{'FAIL' if errors else 'OK'} {name}" + (": " + "; ".join(errors) if errors else ""))
if not checked:
parser.error("no 64-bit native libraries found")
return int(failed)
if __name__ == "__main__":
raise SystemExit(main())
-239
View File
@@ -1,239 +0,0 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const vm = require('node:vm');
const ts = require('typescript');
function fixture(store = new Map()) {
const storage = { getStringSetting: (key, fallback) => store.get(key) ?? fallback,
setStringSetting: (key, value) => store.set(key, value), onSettingsStoreChanged() {},
getBooleanSetting: (_key, fallback) => fallback, setBooleanSetting() {} };
function load(file, deps, suffix = '') {
const context = { exports: {}, global: { isIOS: false }, console,
require: id => deps(id) };
vm.runInNewContext(ts.transpileModule(fs.readFileSync(file, 'utf8') + suffix, {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
}).outputText, context);
return context.exports;
}
const layout = load('app/apps/launcher/launcher-layout.ts', () => storage);
const folders = load('app/apps/launcher/launcher-folders.ts', id => id === './launcher-layout' ? layout : storage);
const settings = load('app/ui/dashboard-settings.ts', id => {
if (id.includes('settings-store')) return storage;
if (id.includes('brightness-curve')) return require('../.test-build/app/g2/brightness-curve.js');
if (id.includes('animation-speed')) return require('../.test-build/app/ui/animation-speed.js');
return { Layer: class {}, ASSISTANT_MODEL_CHOICES: [] };
});
return { store, layout, folders, settings, load };
}
const plain = value => JSON.parse(JSON.stringify(value));
test('legacy assignments and alphabetical default survive creation, rename and restart', () => {
const f = fixture();
const original = plain(f.folders.getFolderAssignments());
assert.equal(f.settings.launcherLayoutSetting.get(), 'alphabetical');
assert.equal(f.folders.createFolder(' Français '), true);
assert.deepEqual(plain(f.folders.getFolders().get('Français')), []);
assert.deepEqual(plain(f.folders.getFolderAssignments()), original);
assert.equal(f.folders.renameFolder('Games', 'Jeux'), true);
const again = fixture(f.store);
assert.equal(again.folders.getFolderAssignments().blocks, 'Jeux');
assert.equal(again.folders.getFolderAssignments().calculator, 'Prototypes');
assert.equal(again.folders.getFolders().has('Français'), true);
assert.equal(again.folders.getFolders().has('Games'), false);
});
test('folder names reject blank, multiline, long and case-insensitive duplicate names', () => {
const f = fixture();
for (const name of ['', ' ', 'games', 'GAMES', 'x'.repeat(25), 'Two\nlines']) {
assert.equal(f.folders.createFolder(name), false, name);
assert.equal(f.folders.renameFolder('Prototypes', name), false, name);
}
assert.equal(f.folders.renameFolder('Games', 'games'), true);
assert.equal(f.folders.renameFolder('missing', 'New name'), false);
});
test('explicit empty folders persist, can be deleted and never reintroduce default assignments', () => {
const f = fixture(new Map([['launcher.folders', '{}']]));
assert.equal(f.folders.createFolder('Empty'), true);
f.folders.setAppFolder('test', 'Empty');
f.folders.setAppFolder('test', null);
assert.equal(fixture(f.store).folders.getFolders().has('Empty'), true);
assert.equal(f.folders.disbandFolder('Empty'), 0);
assert.equal(f.folders.getFolders().size, 0);
assert.equal(f.folders.unusedNewFolderName(), 'New folder');
f.folders.createFolder('New folder');
assert.equal(f.folders.unusedNewFolderName(), 'New folder 2');
});
test('deleting a non-empty folder ungroups all members without losing other assignments', () => {
const f = fixture();
assert.equal(f.folders.disbandFolder('Games'), 5);
assert.equal(f.folders.getFolderAssignments().blocks, undefined);
assert.equal(f.folders.getFolderAssignments().calculator, 'Prototypes');
assert.equal(fixture(f.store).folders.getFolders().has('Games'), false);
});
test('custom root and folder orders persist independently, survive renames and append new apps', () => {
const f = fixture();
const entries = [{ label: 'Alpha', id: 'app:a' }, { label: 'Beta', id: 'app:b' }, { label: 'Games', id: 'folder:Games' }];
const sort = (scope, custom = true) => plain(f.layout.orderLauncherEntries(entries.slice(), e => e.id, scope, custom)).map(e => e.id);
f.settings.launcherLayoutSetting.set('custom');
f.layout.moveLauncherEntry(null, entries.map(e => e.id), 'folder:Games', 'app:a');
f.layout.setLauncherOrder('Games', ['app:b', 'app:a']);
assert.deepEqual(sort(null), ['folder:Games', 'app:a', 'app:b']);
assert.deepEqual(sort('Games'), ['app:b', 'app:a', 'folder:Games']);
assert.deepEqual(sort(null, false), ['app:a', 'app:b', 'folder:Games']);
f.settings.launcherLayoutSetting.set('alphabetical');
f.settings.launcherLayoutSetting.set('custom');
assert.deepEqual(sort(null), ['folder:Games', 'app:a', 'app:b']);
f.folders.renameFolder('Games', 'Jeux');
const again = fixture(f.store);
assert.equal(again.settings.launcherLayoutSetting.get(), 'custom');
entries[2] = { label: 'Jeux', id: 'folder:Jeux' };
assert.deepEqual(sort(null), ['folder:Jeux', 'app:a', 'app:b']);
assert.deepEqual(sort('Jeux'), ['app:b', 'app:a', 'folder:Jeux']);
entries.push({ label: 'A newly installed app', id: 'app:new' });
assert.deepEqual(sort(null), ['folder:Jeux', 'app:a', 'app:b', 'app:new']);
f.folders.disbandFolder('Jeux');
f.folders.createFolder('Jeux');
assert.deepEqual(sort('Jeux'), ['app:new', 'app:a', 'app:b', 'folder:Jeux']);
});
test('malformed metadata is safe; moves tolerate removed apps and stale IDs', () => {
const f = fixture(new Map([['launcher.folderNames', '{bad'], ['launcher.order', '{bad']]));
assert.equal(f.folders.getExplicitFolderNames().length, 0);
assert.equal(f.layout.moveLauncherEntry(null, ['a', 'b'], 'missing', 'a'), false);
assert.equal(f.layout.moveLauncherEntry(null, ['a', 'b'], 'a', 'missing'), false);
assert.equal(f.layout.moveLauncherEntry(null, ['a', 'b'], 'a', 'b'), true);
assert.deepEqual(JSON.parse(f.store.get('launcher.order')).root, ['b', 'a']);
});
function launcherFixture() {
const f = fixture(new Map([['launcher.folders', '{}']]));
const layers = [], launches = [], deleted = [];
class IconGrid {
constructor(options) { this.options = options; this.index = null; }
get selectedItem() { return this.index === null ? null : this.options.items()[this.index] ?? null; }
resetSelection() { this.index = null; }
selectIndex(index) { this.index = index; }
enterRowMode() { this.index = null; }
async handleInput(event, ctx) {
if (event.type === 'click') await this.options.onActivate(this.selectedItem, ctx);
if (event.type === 'double-click' || event.type === 'swipe-left') this.options.onBack(ctx);
}
}
class MenuLayer { constructor(title, items) { this.title = title; this.items = items; } }
class EditTextSettingLayer { constructor(setting) { this.setting = setting; } }
let edit;
const ctx = { stack: {
push: layer => layers.push(layer), pop() { const layer = layers.pop(); layer?.onRemoved?.(); },
popIfTop(test) { if (layers.length && test(layers.at(-1))) { this.pop(); return true; } return false; },
}, actions: { requestRender() {}, endTextSettingEdit() {}, startTextSettingsEdit(settings, title, submit, toggle, cancel) {
edit = { setting: settings[0], submit, cancel };
} } };
const api = f.load('app/apps/launcher/launcher-app.ts', id => {
if (id === './launcher-folders') return f.folders;
if (id === './launcher-layout') return f.layout;
if (id.endsWith('/dashboard-settings')) return { ...f.settings, EditTextSettingLayer,
enumSettingMenuItem: setting => ({ label: setting.label }) };
if (id.endsWith('/icon-grid')) return { IconGrid, ICON_GRID_BAND_INSET_X: 0, ICON_GRID_HIGHLIGHT_INSET_Y: 0 };
if (id.endsWith('/menu')) return { MenuLayer };
if (id.endsWith('/shell/shell')) return { shell: { yieldFocusToSidebar() {} } };
return {};
}, '\nexport { LauncherGridLayer };');
const apps = [{ appId: 'a', label: 'Alpha', icon: 'a' }, { appId: 'b', label: 'Beta', icon: 'b' }, { appId: 'c', label: 'Gamma', icon: 'c' }];
const layer = new api.LauncherGridLayer({ apps: () => apps, launchApp: id => launches.push(id), uninstallApp: id => deleted.push(id) });
return { ...f, layer, ctx, layers, launches, deleted, apps, edit: () => edit,
choose(label) { const item = layer.menuItems().find(item => item.label === label); assert.ok(item, label); item.onSelect(ctx); } };
}
test('launcher menu is available in row mode and supports empty folder creation and entry', async () => {
const h = launcherFixture();
assert.deepEqual(plain(h.layer.menuItems().map(item => item.label)), ['Layout', 'New folder']);
h.choose('New folder');
const folder = h.layer.entries().find(entry => entry.kind === 'folder');
assert.equal(folder.name, 'New folder');
await h.layer.openEntry(folder);
assert.equal(h.layer.currentFolder, 'New folder');
assert.equal(h.layer.entries().length, 0);
assert.ok(h.layer.menuItems().some(item => item.label === 'Rename folder'));
});
test('folder rename uses the existing editor, commits on submit only, and preserves open folder', async () => {
const h = launcherFixture(); h.choose('New folder');
await h.layer.openEntry(h.layer.entries().find(entry => entry.kind === 'folder'));
h.choose('Rename folder');
h.edit().setting.set('Renommé');
assert.equal(h.layer.menuItems().length, 0);
assert.equal(h.folders.getFolders().has('New folder'), true);
h.edit().cancel();
assert.equal(h.folders.getFolders().has('Renommé'), false);
h.choose('Rename folder');
h.edit().setting.set('Renommé');
h.edit().submit();
assert.equal(h.layer.currentFolder, 'Renommé');
assert.equal(h.folders.getFolders().has('New folder'), false);
assert.equal(h.layers.length, 0);
});
test('moving icons reorders without launching; cancellation and alphabetical mode preserve order', async () => {
const h = launcherFixture();
h.layer.grid.selectIndex(0);
assert.equal(h.layer.menuItems().some(item => item.label === 'Move icon'), false);
h.settings.launcherLayoutSetting.set('custom');
h.choose('Move icon');
h.layer.grid.selectIndex(2);
await h.layer.handleInput({ type: 'click' }, h.ctx);
assert.deepEqual(plain(h.layer.entries().map(entry => entry.appId)), ['b', 'c', 'a']);
assert.equal(h.launches.length, 0);
h.choose('Move icon');
h.layer.grid.selectIndex(0);
await h.layer.handleInput({ type: 'double-click' }, h.ctx);
assert.equal(h.layer.moving, null);
assert.deepEqual(plain(h.layer.entries().map(entry => entry.appId)), ['b', 'c', 'a']);
h.settings.launcherLayoutSetting.set('alphabetical');
assert.deepEqual(plain(h.layer.entries().map(entry => entry.appId)), ['a', 'b', 'c']);
h.settings.launcherLayoutSetting.set('custom');
assert.deepEqual(plain(h.layer.entries().map(entry => entry.appId)), ['b', 'c', 'a']);
});
test('folder moves stay inside their scope, folder deletion is confirmed and apps are not uninstalled', async () => {
const h = launcherFixture(); h.folders.createFolder('Dossier');
h.folders.setAppFolder('a', 'Dossier'); h.folders.setAppFolder('b', 'Dossier');
await h.layer.openEntry(h.layer.entries().find(entry => entry.kind === 'folder'));
h.settings.launcherLayoutSetting.set('custom'); h.layer.grid.selectIndex(0);
h.choose('Move icon'); await h.layer.openEntry(h.layer.entries()[1]);
assert.deepEqual(plain(h.layer.entries().map(entry => entry.appId)), ['b', 'a']);
h.choose('Delete folder');
assert.equal(h.folders.getFolders().has('Dossier'), true);
h.layers.at(-1).items[0].onSelect(h.ctx);
assert.equal(h.folders.getFolders().has('Dossier'), false);
assert.equal(h.layer.currentFolder, null);
assert.equal(h.layer.entries().length, 3);
assert.equal(h.deleted.length, 0);
});
test('legacy folders with removed apps disappear while explicit empty folders remain', async () => {
const h = launcherFixture();
h.folders.setAppFolder('a', 'Legacy');
await h.layer.openEntry(h.layer.entries().find(entry => entry.kind === 'folder'));
h.apps.splice(0, 1);
assert.deepEqual(plain(h.layer.entries().map(entry => entry.appId)), ['b', 'c']);
assert.equal(h.layer.currentFolder, null);
h.folders.createFolder('Empty');
await h.layer.openEntry(h.layer.entries().find(entry => entry.kind === 'folder'));
assert.equal(h.layer.entries().length, 0);
assert.equal(h.layer.currentFolder, 'Empty');
});
test('removing the source during a move cancels without launching or corrupting order', async () => {
const h = launcherFixture(); h.settings.launcherLayoutSetting.set('custom');
h.layer.grid.selectIndex(0); h.choose('Move icon');
h.apps.splice(0, 1);
await h.layer.openEntry(h.layer.entries()[0]);
assert.equal(h.layer.moving, null);
assert.equal(h.launches.length, 0);
assert.deepEqual(plain(h.layer.entries().map(entry => entry.appId)), ['b', 'c']);
});
-154
View File
@@ -1,154 +0,0 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const vm = require('node:vm');
const ts = require('typescript');
function fixture() {
const source = ts.createSourceFile('shell.ts', fs.readFileSync('app/ui/shell/shell.ts', 'utf8'), ts.ScriptTarget.Latest, true);
const cls = source.statements.find(n => ts.isClassDeclaration(n) && n.name.text === 'Shell');
const names = new Set(['moveSwitcherWindow', 'openSwitcherMoveMenu', 'switcherWindows', 'foregroundWindow',
'openEscapeMenu', 'registerWindow', 'removeWindow', 'noteWindowVisible', 'mostRecentWindowIndex']);
const methods = cls.members.filter(n => names.has(n.name?.getText(source)));
assert.equal(methods.length, names.size);
const overlay = source.statements.find(n => ts.isClassDeclaration(n) && n.name.text === 'ShellOverlayMenuLayer');
class MenuLayer {
constructor(title, items) { this.title = title; this.items = items; }
selectItem(index) { this.selectedIndex = index; }
}
const context = { exports: {}, MenuLayer, appViewportRect: () => ({ x: 0, y: 0, width: 576 }),
CONTEXT_MENU_DIM: 0.5, brightnessSetting: { get: () => 'auto' }, makeInputEvent: e => e,
appFullscreenSetting: () => ({ get: () => false }), appKeepAwakeSetting: () => ({ label: 'Keep screen awake' }),
toggleSettingMenuItem: setting => ({ label: setting.label }),
swapMenuGesturesSetting: { get: () => false }, GESTURE_SHORT_THEN_LONG_PRESS: 'tap-hold',
};
vm.runInNewContext(ts.transpileModule(`${overlay.getText(source)}\nexport class Shell { ${methods.map(n => n.getText(source)).join('\n')} }`, {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
}).outputText, context);
const s = new context.exports.Shell();
const foregroundCalls = [], closed = [], input = [];
const window = (windowId, appId = windowId, closeable = true, title = windowId) => ({
windowId, appId, closeable, title, requestRender() {},
setForeground: value => foregroundCalls.push([windowId, value]),
close: () => closed.push(windowId), handleInput: event => input.push([windowId, event.type]),
});
const launcher = window('launcher', 'launcher', false, 'Apps');
const first = window('terminal:one', 'terminal', true, 'Terminal');
const second = window('terminal:two', 'terminal', true, 'Terminal');
const third = window('calendar', 'calendar', true, 'Calendar');
const layers = [];
let changed = 0, renders = 0;
Object.assign(s, {
windows: [launcher, first, second, third], selectedIndex: 1, focus: 'sidebar', screenOn: true,
attention: new Map(), mruWindowIds: ['terminal:one', 'calendar', 'terminal:two', 'launcher'],
config: { voiceInputEnabled: false, onWindowsChanged: () => changed++, requestShellRender: () => renders++ },
yieldFocusToSidebar() { this.focus = 'sidebar'; },
stack: { isAtBase: () => !layers.length, push: layer => layers.push(layer),
pop: () => layers.pop()?.onRemoved?.() },
});
return { s, launcher, first, second, third, window, foregroundCalls, closed, input,
ids: () => Array.from(s.windows, w => w.windowId), changed: () => changed, renders: () => renders,
menu: () => layers.at(-1), choose(label) {
const item = layers.at(-1).items.find(item => item.label === label);
assert.ok(item, label); item.onSelect({ stack: s.stack });
} };
}
test('moving open windows in either direction keeps foreground, MRU and pinned launcher stable', () => {
const h = fixture(); h.s.focus = 'window';
const mru = Array.from(h.s.mruWindowIds);
assert.equal(h.s.moveSwitcherWindow(h.first.windowId, h.third.windowId), true);
assert.deepEqual(h.ids(), ['launcher', 'terminal:two', 'calendar', 'terminal:one']);
assert.equal(h.s.foregroundWindow(), h.first);
assert.equal(h.s.selectedIndex, 3);
assert.equal(h.s.focus, 'window');
assert.deepEqual(Array.from(h.s.mruWindowIds), mru);
assert.deepEqual(h.foregroundCalls, []);
assert.deepEqual(h.closed, []);
assert.equal(h.changed(), 1); assert.equal(h.renders(), 1);
assert.equal(h.s.moveSwitcherWindow(h.first.windowId, h.second.windowId), true);
assert.deepEqual(h.ids(), ['launcher', 'terminal:one', 'terminal:two', 'calendar']);
assert.equal(h.s.foregroundWindow(), h.first);
});
test('system menu opens a numbered position picker and moves the captured window, even with duplicate titles', () => {
const h = fixture();
h.s.openEscapeMenu(); h.choose('Move in app switcher');
assert.equal(h.menu().title, 'Move app to position');
assert.deepEqual(Array.from(h.menu().items, item => item.label), ['1. Terminal', '2. Terminal', '3. Calendar']);
assert.equal(h.menu().selectedIndex, 0);
// A delayed focus change must not move a different app than the menu captured.
h.s.selectedIndex = 2;
h.choose('3. Calendar');
assert.deepEqual(h.ids(), ['launcher', 'terminal:two', 'calendar', 'terminal:one']);
assert.equal(h.s.foregroundWindow(), h.second);
assert.equal(h.menu(), undefined);
assert.equal(h.s.focus, 'sidebar');
});
test('cancelling the picker and choosing the current slot leave ordering unchanged', () => {
const h = fixture(); const before = h.ids();
h.s.openSwitcherMoveMenu(h.first.windowId); h.s.stack.pop();
assert.deepEqual(h.ids(), before);
h.s.openSwitcherMoveMenu(h.first.windowId); h.choose('1. Terminal');
assert.deepEqual(h.ids(), before);
assert.equal(h.changed(), 0);
});
test('closing the pending source or destination prevents a stale move from affecting another window', () => {
for (const removed of ['terminal:one', 'calendar']) {
const h = fixture(); h.s.openSwitcherMoveMenu(h.first.windowId);
h.s.removeWindow(removed);
const afterClose = h.ids();
h.choose('3. Calendar');
assert.deepEqual(h.ids(), afterClose);
assert.equal(h.menu(), undefined);
}
});
test('temporary status windows and pinned slots stay fixed, including selected status foreground', () => {
const h = fixture();
const hidden = h.window('notifications:temporary');
const pinned = h.window('another-pinned', 'pinned', false);
h.s.windows.splice(2, 0, hidden, pinned);
h.s.selectedIndex = 2;
h.s.selectedStatus = { transient: true, host: hidden, item: { key: 'notification' } };
assert.equal(h.s.moveSwitcherWindow(hidden.windowId, h.first.windowId), false);
h.s.moveSwitcherWindow(h.first.windowId, h.third.windowId);
assert.deepEqual(h.ids(), ['launcher', 'terminal:two', 'notifications:temporary', 'another-pinned', 'calendar', 'terminal:one']);
assert.equal(h.s.foregroundWindow(), hidden);
assert.equal(h.s.selectedStatus.host, hidden);
h.s.openEscapeMenu();
assert.ok(!h.menu().items.some(item => item.label === 'Move in app switcher'));
h.s.stack.pop();
h.s.openSwitcherMoveMenu(h.first.windowId);
assert.deepEqual(Array.from(h.menu().items, item => item.label), ['1. Terminal', '2. Calendar', '3. Terminal']);
});
test('new windows append, replacements keep their slot, and closing uses unchanged recency after a move', () => {
const h = fixture(); h.s.moveSwitcherWindow(h.first.windowId, h.third.windowId);
h.s.registerWindow(h.window('new'));
assert.equal(h.ids().at(-1), 'new');
const replacement = h.window(h.second.windowId, 'terminal', true, 'Renamed session');
h.s.registerWindow(replacement);
assert.equal(h.s.windows[1], replacement);
assert.equal(h.s.foregroundWindow(), h.first);
h.s.removeWindow(h.first.windowId);
assert.equal(h.s.foregroundWindow(), h.third);
});
test('pinned, missing, single-window, screen-off and overlay cases cannot start a reorder', () => {
const h = fixture(); const before = h.ids();
for (const [from, to] of [['launcher', 'calendar'], ['calendar', 'launcher'], ['missing', 'calendar']]) {
assert.equal(h.s.moveSwitcherWindow(from, to), false);
}
h.s.openSwitcherMoveMenu('missing'); assert.equal(h.menu(), undefined);
h.s.screenOn = false; h.s.openSwitcherMoveMenu(h.first.windowId); assert.equal(h.menu(), undefined);
h.s.screenOn = true; h.s.stack.push({});
h.s.openSwitcherMoveMenu(h.first.windowId); assert.equal(h.menu().title, undefined); h.s.stack.pop();
assert.deepEqual(h.ids(), before);
h.s.selectedIndex = 0; h.s.openEscapeMenu();
assert.ok(!h.menu().items.some(item => item.label === 'Move in app switcher')); h.s.stack.pop();
h.s.windows = [h.launcher, h.first]; h.s.selectedIndex = 1; h.s.openEscapeMenu();
assert.ok(!h.menu().items.some(item => item.label === 'Move in app switcher'));
});
+40
View File
@@ -0,0 +1,40 @@
import importlib.util
from pathlib import Path
import struct
import unittest
spec = importlib.util.spec_from_file_location("apk_pages", Path(__file__).parents[1] / "scripts/check-apk-pages.py")
checker = importlib.util.module_from_spec(spec)
spec.loader.exec_module(checker)
def elf(alignment=16384, relro_end=16384, writable_end=32768):
data = bytearray(64 + 2 * 56)
data[:6] = b"\x7fELF\x02\x01"
struct.pack_into("<Q", data, 32, 64)
struct.pack_into("<HH", data, 54, 56, 2)
struct.pack_into("<IIQQQQQQ", data, 64, 1, 6, 0, 0, 0, writable_end, writable_end, alignment)
struct.pack_into("<IIQQQQQQ", data, 120, 0x6474E552, 4, 0, 0, 0, relro_end, relro_end, 1)
return data
class AlignmentTests(unittest.TestCase):
def test_rejects_4k_loads(self):
self.assertTrue(checker.alignment_errors(elf(alignment=4096)))
def test_accepts_16k_loads_and_relro(self):
self.assertEqual([], checker.alignment_errors(elf()))
def test_rejects_relro_protecting_writable_data(self):
self.assertTrue(checker.alignment_errors(elf(relro_end=4096)))
def test_accepts_relro_at_end_of_writable_load(self):
self.assertEqual([], checker.alignment_errors(elf(relro_end=4096, writable_end=4096)))
def test_rejects_invalid_headers(self):
self.assertTrue(checker.alignment_errors(b"not ELF"))
self.assertTrue(checker.alignment_errors(elf()[:70]))
if __name__ == "__main__":
unittest.main()