forked from Blendman974/faceclaw
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9e6bb8473a
|
No files matched your search
@@ -54,7 +54,8 @@ class FaceclawCalendarProvider private constructor() {
|
|||||||
* boundaries the provider stores them as.
|
* boundaries the provider stores them as.
|
||||||
*/
|
*/
|
||||||
@JvmStatic
|
@JvmStatic
|
||||||
fun getUpcomingEventsJson(context: Context?, maxEvents: Int, windowMs: Long): String {
|
@JvmOverloads
|
||||||
|
fun getUpcomingEventsJson(context: Context?, maxEvents: Int, windowMs: Long, selectedCalendarIdsJson: String = "null"): String {
|
||||||
if (context == null || maxEvents <= 0) {
|
if (context == null || maxEvents <= 0) {
|
||||||
return "[]"
|
return "[]"
|
||||||
}
|
}
|
||||||
@@ -73,11 +74,21 @@ class FaceclawCalendarProvider private constructor() {
|
|||||||
val events = ArrayList<Event>()
|
val events = ArrayList<Event>()
|
||||||
var cursor: Cursor? = null
|
var cursor: Cursor? = null
|
||||||
try {
|
try {
|
||||||
|
// Filter instances before the cutoff/limit so excluded calendars
|
||||||
|
// cannot crowd out selected calendars, including recurrences.
|
||||||
|
val ids = if (selectedCalendarIdsJson == "null") null else JSONArray(selectedCalendarIdsJson)
|
||||||
|
if (ids != null && ids.length() == 0) return "[]"
|
||||||
|
val args = ids?.let { values -> Array(values.length()) { index ->
|
||||||
|
values.getString(index).also { require(it.matches(Regex("[0-9]+"))) }
|
||||||
|
} }
|
||||||
|
val selection = args?.let {
|
||||||
|
CalendarContract.Instances.CALENDAR_ID + " IN (" + it.joinToString(",") { "?" } + ")"
|
||||||
|
}
|
||||||
cursor = context.contentResolver.query(
|
cursor = context.contentResolver.query(
|
||||||
uri,
|
uri,
|
||||||
PROJECTION,
|
PROJECTION,
|
||||||
null,
|
selection,
|
||||||
null,
|
args,
|
||||||
CalendarContract.Instances.BEGIN + " ASC")
|
CalendarContract.Instances.BEGIN + " ASC")
|
||||||
if (cursor != null) {
|
if (cursor != null) {
|
||||||
val utc = Calendar.getInstance(TimeZone.getTimeZone("UTC"))
|
val utc = Calendar.getInstance(TimeZone.getTimeZone("UTC"))
|
||||||
@@ -118,6 +129,33 @@ class FaceclawCalendarProvider private constructor() {
|
|||||||
return out.toString()
|
return out.toString()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@JvmStatic
|
||||||
|
fun getCalendarsJson(context: Context?): String {
|
||||||
|
if (context == null) return "[]"
|
||||||
|
val out = JSONArray()
|
||||||
|
try {
|
||||||
|
context.contentResolver.query(
|
||||||
|
CalendarContract.Calendars.CONTENT_URI,
|
||||||
|
arrayOf(CalendarContract.Calendars._ID, CalendarContract.Calendars.CALENDAR_DISPLAY_NAME,
|
||||||
|
CalendarContract.Calendars.ACCOUNT_NAME, CalendarContract.Calendars.ACCOUNT_TYPE),
|
||||||
|
null, null, CalendarContract.Calendars.CALENDAR_DISPLAY_NAME + " ASC",
|
||||||
|
)?.use { cursor ->
|
||||||
|
while (cursor.moveToNext()) {
|
||||||
|
out.put(JSONObject().apply {
|
||||||
|
put("id", cursor.getLong(0).toString())
|
||||||
|
put("name", cursor.getString(1) ?: "")
|
||||||
|
put("accountName", cursor.getString(2) ?: "")
|
||||||
|
put("accountType", cursor.getString(3) ?: "")
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (t: Throwable) {
|
||||||
|
Log.w(TAG, "failed to read calendars", t)
|
||||||
|
return "[]"
|
||||||
|
}
|
||||||
|
return out.toString()
|
||||||
|
}
|
||||||
|
|
||||||
private fun readEvent(cursor: Cursor, utc: Calendar, local: Calendar): Event {
|
private fun readEvent(cursor: Cursor, utc: Calendar, local: Calendar): Event {
|
||||||
val allDay = cursor.getInt(4) != 0
|
val allDay = cursor.getInt(4) != 0
|
||||||
var startMs = cursor.getLong(2)
|
var startMs = cursor.getLong(2)
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { invalidateCalendarCache, onCalendarChanged } from "../../native/calenda
|
|||||||
import { makeImageWindowIcon, windowIcon } from "../../ui/shell/chrome-layer";
|
import { makeImageWindowIcon, windowIcon } from "../../ui/shell/chrome-layer";
|
||||||
import { CalendarLayer } from "./calendar";
|
import { CalendarLayer } from "./calendar";
|
||||||
import { renderCalendarDateIcon } from "./calendar-icon";
|
import { renderCalendarDateIcon } from "./calendar-icon";
|
||||||
|
import { calendarSelectionMenuItems } from "./calendar-filter";
|
||||||
import {
|
import {
|
||||||
createInProcessWindow,
|
createInProcessWindow,
|
||||||
YieldAtRootLayer,
|
YieldAtRootLayer,
|
||||||
@@ -44,6 +45,10 @@ export function createCalendarAppWindow(options: InProcessAppOptions): InProcess
|
|||||||
icon: "calendar",
|
icon: "calendar",
|
||||||
drawIcon: makeImageWindowIcon(renderCalendarDateIcon, windowIcon("calendar", "Ca")),
|
drawIcon: makeImageWindowIcon(renderCalendarDateIcon, windowIcon("calendar", "Ca")),
|
||||||
closeable: true,
|
closeable: true,
|
||||||
|
menuItems: () => calendarSelectionMenuItems().map(item => ({ ...item, onSelect: (ctx, menu) => {
|
||||||
|
ctx.stack.pop();
|
||||||
|
return item.onSelect(ctx, menu);
|
||||||
|
} })),
|
||||||
actions: options.actions,
|
actions: options.actions,
|
||||||
baseLayer: new YieldAtRootLayer(new CalendarLayer(requestPermission)),
|
baseLayer: new YieldAtRootLayer(new CalendarLayer(requestPermission)),
|
||||||
submitFrame: options.submitFrame,
|
submitFrame: options.submitFrame,
|
||||||
|
|||||||
@@ -0,0 +1,94 @@
|
|||||||
|
import { getDefaultSmallFont } from "../../graphics/ui-fonts";
|
||||||
|
import { type GrayImage } from "../../graphics/image";
|
||||||
|
import { truncateText } from "../../graphics/textwrap";
|
||||||
|
import { readCalendarSelection, setCalendarSelection } from "../../native/calendar-selection";
|
||||||
|
import { readAvailableCalendars } from "../../native/calendar-sources";
|
||||||
|
import { hasCalendarPermission } from "../../native/calendar-permissions";
|
||||||
|
import { type InputEvent } from "../../ui/gestures";
|
||||||
|
import { type Layer, type LayerContext, type PaintBelow } from "../../ui/layers";
|
||||||
|
import { drawToggleMenuItem, MenuLayer, type MenuItem } from "../../ui/menu";
|
||||||
|
|
||||||
|
/** Shared preference for every Android calendar reader. */
|
||||||
|
export class CalendarFilterLayer implements Layer {
|
||||||
|
private menu: MenuLayer | null = null;
|
||||||
|
private width = 0;
|
||||||
|
private keys: string[] = [];
|
||||||
|
|
||||||
|
private currentMenu(ctx: LayerContext): MenuLayer {
|
||||||
|
const calendars = readAvailableCalendars().sort((a, b) =>
|
||||||
|
a.name.localeCompare(b.name) || a.accountName.localeCompare(b.accountName) || a.id.localeCompare(b.id));
|
||||||
|
const selection = readCalendarSelection();
|
||||||
|
const known = new Set(calendars.map(calendar => calendar.id));
|
||||||
|
const keys = ["all", "none"];
|
||||||
|
const toggle = (id: string) => {
|
||||||
|
// Leaving all mode snapshots the current calendars. Newly added calendars
|
||||||
|
// then stay excluded until selected individually or all mode is restored.
|
||||||
|
const ids = new Set(readCalendarSelection() ?? calendars.map(calendar => calendar.id));
|
||||||
|
if (ids.has(id)) ids.delete(id); else ids.add(id);
|
||||||
|
setCalendarSelection(Array.from(ids));
|
||||||
|
};
|
||||||
|
const items: MenuItem[] = [{
|
||||||
|
label: "All calendars",
|
||||||
|
description: "Include all calendars, including calendars added later.",
|
||||||
|
onSelect: () => setCalendarSelection(null),
|
||||||
|
render: ({ image, x, y, width, selected }) => drawToggleMenuItem(image, getDefaultSmallFont(), x, y, width,
|
||||||
|
"All calendars", readCalendarSelection() === null, selected),
|
||||||
|
}, {
|
||||||
|
label: "No calendars",
|
||||||
|
onSelect: () => setCalendarSelection([]),
|
||||||
|
render: ({ image, x, y, width, selected }) => drawToggleMenuItem(image, getDefaultSmallFont(), x, y, width,
|
||||||
|
"No calendars", readCalendarSelection()?.length === 0, selected),
|
||||||
|
}];
|
||||||
|
const rows = [
|
||||||
|
...calendars.map(calendar => ({ id: calendar.id,
|
||||||
|
label: `${calendar.name || "(unnamed)"} / ${calendar.accountName || "Local"} (${calendar.accountType || "local"}) #${calendar.id}` })),
|
||||||
|
...(selection ?? []).filter(id => !known.has(id)).map(id => ({ id, label: `Unavailable calendar #${id}` })),
|
||||||
|
];
|
||||||
|
for (const row of rows) {
|
||||||
|
keys.push(`calendar:${row.id}`);
|
||||||
|
items.push({
|
||||||
|
label: row.label,
|
||||||
|
description: row.label,
|
||||||
|
onSelect: () => toggle(row.id),
|
||||||
|
render: ({ image, x, y, width, selected }) => {
|
||||||
|
const font = getDefaultSmallFont();
|
||||||
|
const ids = readCalendarSelection();
|
||||||
|
drawToggleMenuItem(image, font, x, y, width, truncateText(font, row.label, width - 48),
|
||||||
|
ids === null || ids.includes(row.id), selected);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (!calendars.length) items.push({
|
||||||
|
label: hasCalendarPermission() ? "No calendars available" : "Grant calendar permission on your phone",
|
||||||
|
disabled: true, onSelect: () => {},
|
||||||
|
});
|
||||||
|
const key = this.menu?.selectedIndex != null ? this.keys[this.menu.selectedIndex] : "all";
|
||||||
|
const index = Math.max(0, keys.indexOf(key ?? "all"));
|
||||||
|
this.keys = keys;
|
||||||
|
const width = ctx.stack.getBaseSize().width;
|
||||||
|
if (!this.menu || this.width !== width) {
|
||||||
|
this.width = width;
|
||||||
|
this.menu = new MenuLayer("Calendars displayed", items, {
|
||||||
|
x: 8, y: 8, width: width - 16, opaque: true, showBorder: false,
|
||||||
|
footer: "Shared by Calendar and Glanceboard",
|
||||||
|
}).selectItem(index);
|
||||||
|
} else this.menu.setItems(items, index);
|
||||||
|
return this.menu;
|
||||||
|
}
|
||||||
|
|
||||||
|
paint(ctx: LayerContext, paintBelow: PaintBelow): GrayImage {
|
||||||
|
return this.currentMenu(ctx).paint(ctx, paintBelow);
|
||||||
|
}
|
||||||
|
|
||||||
|
async handleInput(event: InputEvent, ctx: LayerContext): Promise<void> {
|
||||||
|
await this.currentMenu(ctx).handleInput(event, ctx);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function calendarSelectionMenuItems(): MenuItem[] {
|
||||||
|
return global.isAndroid ? [{
|
||||||
|
label: "Calendars displayed",
|
||||||
|
description: "Choose the calendars used by Calendar, Glanceboard and other calendar views.",
|
||||||
|
onSelect: ctx => ctx.stack.push(new CalendarFilterLayer()),
|
||||||
|
}] : [];
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import { type GlanceWidgetDefinition, type GlanceWidgetId } from "../widget";
|
import { type GlanceWidgetDefinition, type GlanceWidgetId } from "../widget";
|
||||||
import { CalendarWidget } from "./calendar-widget";
|
import { CalendarWidget } from "./calendar-widget";
|
||||||
|
import { calendarSelectionMenuItems } from "../../calendar/calendar-filter";
|
||||||
import { CompassWidget } from "./compass-widget";
|
import { CompassWidget } from "./compass-widget";
|
||||||
import { MusicWidget, musicSettingsMenuItems } from "./music-widget";
|
import { MusicWidget, musicSettingsMenuItems } from "./music-widget";
|
||||||
import { NightscoutWidget } from "./nightscout-widget";
|
import { NightscoutWidget } from "./nightscout-widget";
|
||||||
@@ -11,7 +12,7 @@ import { HealthWidget } from "./health-widget";
|
|||||||
/** Every widget a board slot can hold. */
|
/** Every widget a board slot can hold. */
|
||||||
export const GLANCE_WIDGETS: readonly GlanceWidgetDefinition[] = [
|
export const GLANCE_WIDGETS: readonly GlanceWidgetDefinition[] = [
|
||||||
{ id: "system-card", label: "System card", settingsMenuItems: systemCardSettingsMenuItems, create: () => new SystemCardWidget() },
|
{ id: "system-card", label: "System card", settingsMenuItems: systemCardSettingsMenuItems, create: () => new SystemCardWidget() },
|
||||||
{ id: "calendar", label: "Calendar", tall: true, create: () => new CalendarWidget() },
|
{ id: "calendar", label: "Calendar", tall: true, settingsMenuItems: calendarSelectionMenuItems, create: () => new CalendarWidget() },
|
||||||
{ id: "terminal", label: "Terminal", tall: true, create: () => new TerminalWidget() },
|
{ id: "terminal", label: "Terminal", tall: true, create: () => new TerminalWidget() },
|
||||||
{ id: "t3code", label: "T3 Code", tall: true, create: () => new T3CodeWidget() },
|
{ id: "t3code", label: "T3 Code", tall: true, create: () => new T3CodeWidget() },
|
||||||
{ id: "nightscout", label: "Nightscout", create: () => new NightscoutWidget() },
|
{ id: "nightscout", label: "Nightscout", create: () => new NightscoutWidget() },
|
||||||
|
|||||||
@@ -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 { Layer, LayerActions, LayerContext } from "../../ui/layers";
|
||||||
import { MenuLayer, type MenuItem } from "../../ui/menu";
|
import { MenuLayer, type MenuItem } from "../../ui/menu";
|
||||||
import { WINDOW_MENU_LAYOUT } from "../../ui/window-menu";
|
import { WINDOW_MENU_LAYOUT } from "../../ui/window-menu";
|
||||||
import {
|
import { onAnySettingChanged } from "../../ui/dashboard-settings";
|
||||||
onAnySettingChanged, launcherLayoutSetting, enumSettingMenuItem,
|
|
||||||
ConfigSettingString, EditTextSettingLayer,
|
|
||||||
} from "../../ui/dashboard-settings";
|
|
||||||
import { getLauncherLayoutFingerprint, orderLauncherEntries, moveLauncherEntry } from "./launcher-layout";
|
|
||||||
import { createInProcessWindow } from "../../ui/shell/in-process-window";
|
import { createInProcessWindow } from "../../ui/shell/in-process-window";
|
||||||
import {
|
import {
|
||||||
getFolderAssignments,
|
getFolderAssignments,
|
||||||
@@ -20,7 +16,6 @@ import {
|
|||||||
getFolderStateFingerprint,
|
getFolderStateFingerprint,
|
||||||
setAppFolder,
|
setAppFolder,
|
||||||
unusedNewFolderName,
|
unusedNewFolderName,
|
||||||
getExplicitFolderNames, createFolder, renameFolder, folderNameError, disbandFolder,
|
|
||||||
} from "./launcher-folders";
|
} from "./launcher-folders";
|
||||||
import { shell, type ShellWindow } from "../../ui/shell/shell";
|
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
|
* and is re-read every paint, so assistant folder tools take effect without
|
||||||
* the layer holding any copy of the state.
|
* 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 {
|
class LauncherGridLayer implements Layer {
|
||||||
// Watch swipes are spatial: up/down move between rows, left/right between
|
// Watch swipes are spatial: up/down move between rows, left/right between
|
||||||
// columns. From the leftmost column, left keeps going out: it leaves the
|
// columns. From the leftmost column, left keeps going out: it leaves the
|
||||||
@@ -87,12 +74,6 @@ class LauncherGridLayer implements Layer {
|
|||||||
readonly acceptsDirectional = true;
|
readonly acceptsDirectional = true;
|
||||||
/** Folder whose contents the grid is showing, or null for the top grid. */
|
/** Folder whose contents the grid is showing, or null for the top grid. */
|
||||||
private currentFolder: string | null = null;
|
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>({
|
private readonly grid = new IconGrid<LauncherGridEntry>({
|
||||||
items: () => this.entries(),
|
items: () => this.entries(),
|
||||||
describe: (entry) => ({
|
describe: (entry) => ({
|
||||||
@@ -123,23 +104,25 @@ class LauncherGridLayer implements Layer {
|
|||||||
const members = (getFolders().get(this.currentFolder) ?? [])
|
const members = (getFolders().get(this.currentFolder) ?? [])
|
||||||
.map((appId) => byAppId.get(appId))
|
.map((appId) => byAppId.get(appId))
|
||||||
.filter(Boolean) as LauncherAppEntry[];
|
.filter(Boolean) as LauncherAppEntry[];
|
||||||
if (members.length > 0 || getExplicitFolderNames().includes(this.currentFolder)) {
|
if (members.length > 0) {
|
||||||
return this.sortEntries(members.map((app): LauncherGridEntry => ({
|
return members
|
||||||
|
.map((app): LauncherGridEntry => ({
|
||||||
kind: "app",
|
kind: "app",
|
||||||
label: app.label,
|
label: app.label,
|
||||||
icon: app.icon,
|
icon: app.icon,
|
||||||
appId: app.appId,
|
appId: app.appId,
|
||||||
renderIcon: app.renderIcon,
|
renderIcon: app.renderIcon,
|
||||||
})));
|
}))
|
||||||
|
.sort((a, b) => a.label.localeCompare(b.label));
|
||||||
}
|
}
|
||||||
this.currentFolder = null;
|
this.currentFolder = null;
|
||||||
}
|
}
|
||||||
const assignments = getFolderAssignments();
|
const assignments = getFolderAssignments();
|
||||||
const entries: LauncherGridEntry[] = [];
|
const entries: LauncherGridEntry[] = [];
|
||||||
// Legacy folders need a known member; explicitly created folders may be empty.
|
// A folder cell appears only when it holds at least one known app; stale
|
||||||
const explicit = new Set(getExplicitFolderNames());
|
// assignments to removed apps are ignored.
|
||||||
for (const [name, members] of getFolders()) {
|
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 });
|
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. */
|
/** 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). */
|
/** Enter a folder or launch an app; true when that left the grid (a launch). */
|
||||||
private async openEntry(entry: LauncherGridEntry): Promise<boolean> {
|
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") {
|
if (entry.kind === "folder") {
|
||||||
this.currentFolder = entry.name;
|
this.currentFolder = entry.name;
|
||||||
this.grid.resetSelection();
|
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. */
|
/** Leave the open folder, else yield to the sidebar; true when that left the grid. */
|
||||||
private back(): boolean {
|
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) {
|
if (this.currentFolder !== null) {
|
||||||
this.exitFolder();
|
this.exitFolder();
|
||||||
return false;
|
return false;
|
||||||
@@ -209,54 +175,14 @@ class LauncherGridLayer implements Layer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Layout and folder creation are always available. Per-icon actions need
|
* App-specific entries for the window's context menu. Only item mode
|
||||||
* item mode so row navigation never edits an ambiguous selection.
|
* 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[] {
|
menuItems(): MenuItem[] {
|
||||||
if (this.editingFolder) return [];
|
|
||||||
const entry = this.grid.selectedItem;
|
const entry = this.grid.selectedItem;
|
||||||
const items: MenuItem[] = [
|
if (!entry || entry.kind !== "app") return [];
|
||||||
enumSettingMenuItem(launcherLayoutSetting, { onChange: () => { this.moving = null; this.grid.resetSelection(); } }),
|
return [
|
||||||
{
|
|
||||||
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,
|
|
||||||
{
|
{
|
||||||
label: "Move to folder",
|
label: "Move to folder",
|
||||||
onSelect: (ctx) => {
|
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,
|
* 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,
|
* plus a generated-name "New folder" (ring input has no text entry) and,
|
||||||
@@ -342,9 +242,7 @@ class LauncherGridLayer implements Layer {
|
|||||||
items.push({
|
items.push({
|
||||||
label: "New folder",
|
label: "New folder",
|
||||||
onSelect: (ctx) => {
|
onSelect: (ctx) => {
|
||||||
const name = unusedNewFolderName();
|
setAppFolder(appId, unusedNewFolderName());
|
||||||
createFolder(name);
|
|
||||||
setAppFolder(appId, name);
|
|
||||||
ctx.stack.pop();
|
ctx.stack.pop();
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -365,16 +263,8 @@ class LauncherGridLayer implements Layer {
|
|||||||
const { width, height } = ctx.stack.getBaseSize();
|
const { width, height } = ctx.stack.getBaseSize();
|
||||||
const image = new GrayImage(width, height, 0);
|
const image = new GrayImage(width, height, 0);
|
||||||
// The folder-name header band scales with the font.
|
// The folder-name header band scales with the font.
|
||||||
const entries = this.entries();
|
const gridTop = this.currentFolder !== null ? GRID_TOP + font.lineHeight + 4 : ROOT_GRID_TOP;
|
||||||
if (this.moving && (launcherLayoutSetting.get() !== "custom" || this.moving.folder !== this.currentFolder ||
|
if (this.currentFolder !== null) {
|
||||||
!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) {
|
|
||||||
image.drawText(font, 8, GRID_TOP - 2, truncateText(font, this.currentFolder, width - 16), 160);
|
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
|
// 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> {
|
async handleInput(event: InputEvent, ctx: LayerContext): Promise<void> {
|
||||||
if (this.moving && event.type === "double-click") { this.back(); return; }
|
|
||||||
await this.grid.handleInput(event, ctx);
|
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
|
// keeps every unrelated setting change from repainting the launcher. The
|
||||||
// launcher is pinned for the app's lifetime, so the subscription never needs
|
// launcher is pinned for the app's lifetime, so the subscription never needs
|
||||||
// tearing down.
|
// tearing down.
|
||||||
let lastState = `${getFolderStateFingerprint()}\n${getLauncherLayoutFingerprint()}\n${launcherAppsFingerprint(options.apps())}`;
|
let lastState = `${getFolderStateFingerprint()}\n${launcherAppsFingerprint(options.apps())}`;
|
||||||
onAnySettingChanged(() => {
|
onAnySettingChanged(() => {
|
||||||
const state = `${getFolderStateFingerprint()}\n${getLauncherLayoutFingerprint()}\n${launcherAppsFingerprint(options.apps())}`;
|
const state = `${getFolderStateFingerprint()}\n${launcherAppsFingerprint(options.apps())}`;
|
||||||
if (state === lastState) return;
|
if (state === lastState) return;
|
||||||
lastState = state;
|
lastState = state;
|
||||||
created.requestRender();
|
created.requestRender();
|
||||||
|
|||||||
@@ -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 { getStringSetting, setStringSetting } from "../../native/settings-store";
|
||||||
|
|
||||||
import { renameLauncherFolderOrder, removeLauncherFolderOrder } from "./launcher-layout";
|
|
||||||
|
|
||||||
const STORAGE_KEY = "launcher.folders";
|
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. */
|
/** The out-of-the-box grouping, applied only while the setting is unset. */
|
||||||
const DEFAULT_ASSIGNMENTS: Record<string, string> = {
|
const DEFAULT_ASSIGNMENTS: Record<string, string> = {
|
||||||
@@ -68,7 +32,7 @@ export function getFolderAssignments(): Record<string, string> {
|
|||||||
try {
|
try {
|
||||||
const parsed = JSON.parse(raw);
|
const parsed = JSON.parse(raw);
|
||||||
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};
|
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)) {
|
for (const appId of Object.keys(parsed)) {
|
||||||
const folder = parsed[appId];
|
const folder = parsed[appId];
|
||||||
if (typeof folder === "string" && folder.trim()) {
|
if (typeof folder === "string" && folder.trim()) {
|
||||||
@@ -94,7 +58,6 @@ export function getFolders(): Map<string, string[]> {
|
|||||||
unsorted.set(folder, [appId]);
|
unsorted.set(folder, [appId]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for (const name of getExplicitFolderNames()) if (!unsorted.has(name)) unsorted.set(name, []);
|
|
||||||
const folders = new Map<string, string[]>();
|
const folders = new Map<string, string[]>();
|
||||||
for (const name of Array.from(unsorted.keys()).sort((a, b) => a.localeCompare(b))) {
|
for (const name of Array.from(unsorted.keys()).sort((a, b) => a.localeCompare(b))) {
|
||||||
folders.set(name, unsorted.get(name)!);
|
folders.set(name, unsorted.get(name)!);
|
||||||
@@ -123,8 +86,6 @@ export function disbandFolder(folder: string): number {
|
|||||||
moved++;
|
moved++;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
setStringSetting(NAMES_KEY, JSON.stringify(getExplicitFolderNames().filter(name => name !== folder)));
|
|
||||||
removeLauncherFolderOrder(folder);
|
|
||||||
if (moved > 0) {
|
if (moved > 0) {
|
||||||
setStringSetting(STORAGE_KEY, JSON.stringify(assignments));
|
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", …).
|
* 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;
|
* 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 {
|
export function unusedNewFolderName(): string {
|
||||||
const existing = new Set(Array.from(getFolders().keys()).map((name) => name.toLowerCase()));
|
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. */
|
/** Raw stored value, for cheap change detection by the launcher window. */
|
||||||
export function getFolderStateFingerprint(): string {
|
export function getFolderStateFingerprint(): string {
|
||||||
return JSON.stringify([getStringSetting(STORAGE_KEY, ""), getStringSetting(NAMES_KEY, ""),
|
return getStringSetting(STORAGE_KEY, "");
|
||||||
getStringSetting("launcher.folderNameDraft", "")]);
|
|
||||||
}
|
}
|
||||||
@@ -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, "")]);
|
|
||||||
}
|
|
||||||
@@ -191,7 +191,7 @@ function registerTools(options: WindowToolsOptions, registry: ToolRegistry): voi
|
|||||||
const lines: string[] = [];
|
const lines: string[] = [];
|
||||||
for (const [name, members] of getFolders()) {
|
for (const [name, members] of getFolders()) {
|
||||||
const known = members.filter((appId) => appIds.indexOf(appId) >= 0).sort();
|
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 assignments = getFolderAssignments();
|
||||||
const ungrouped = appIds.filter((appId) => !assignments[appId]);
|
const ungrouped = appIds.filter((appId) => !assignments[appId]);
|
||||||
@@ -237,7 +237,7 @@ function registerTools(options: WindowToolsOptions, registry: ToolRegistry): voi
|
|||||||
{
|
{
|
||||||
name: "apps.remove_from_folder",
|
name: "apps.remove_from_folder",
|
||||||
description:
|
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: {
|
inputSchema: {
|
||||||
type: "object",
|
type: "object",
|
||||||
properties: {
|
properties: {
|
||||||
@@ -276,9 +276,8 @@ function registerTools(options: WindowToolsOptions, registry: ToolRegistry): voi
|
|||||||
(args) => {
|
(args) => {
|
||||||
const folder = resolveFolderName(String(args?.folder ?? ""));
|
const folder = resolveFolderName(String(args?.folder ?? ""));
|
||||||
if (!folder) return err("folder must be a non-empty name");
|
if (!folder) return err("folder must be a non-empty name");
|
||||||
const existed = getFolders().has(folder);
|
|
||||||
const moved = disbandFolder(folder);
|
const moved = disbandFolder(folder);
|
||||||
if (moved === 0 && !existed) {
|
if (moved === 0) {
|
||||||
const names = Array.from(getFolders().keys());
|
const names = Array.from(getFolders().keys());
|
||||||
return err(
|
return err(
|
||||||
names.length
|
names.length
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
import { getStringSetting, setStringSetting } from "./settings-store";
|
||||||
|
|
||||||
|
export const CALENDAR_SELECTION_KEY = "calendar.selectedIds";
|
||||||
|
/** null means all calendars (including future ones); [] explicitly means none. */
|
||||||
|
export function readCalendarSelection(): string[] | null {
|
||||||
|
try {
|
||||||
|
const value = JSON.parse(getStringSetting(CALENDAR_SELECTION_KEY, "null"));
|
||||||
|
if (value === null) return null;
|
||||||
|
if (!Array.isArray(value) || !value.every(id => typeof id === "string" && /^\d+$/.test(id))) return null;
|
||||||
|
return Array.from(new Set<string>(value));
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setCalendarSelection(ids: readonly string[] | null): void {
|
||||||
|
if (ids !== null && !ids.every(id => /^\d+$/.test(id))) throw new Error("Invalid calendar ID");
|
||||||
|
setStringSetting(CALENDAR_SELECTION_KEY, JSON.stringify(ids === null ? null : Array.from(new Set(ids))));
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import { Utils } from "@nativescript/core";
|
||||||
|
import { hasCalendarPermission } from "./calendar-permissions";
|
||||||
|
|
||||||
|
declare const com: any;
|
||||||
|
|
||||||
|
export type CalendarSource = { id: string; name: string; accountName: string; accountType: string };
|
||||||
|
|
||||||
|
/** Android calendar IDs survive renames and distinguish equal display names. */
|
||||||
|
export function readAvailableCalendars(): CalendarSource[] {
|
||||||
|
if (!global.isAndroid || !hasCalendarPermission()) return [];
|
||||||
|
try {
|
||||||
|
const context = Utils.android.getApplicationContext();
|
||||||
|
if (!context) return [];
|
||||||
|
const parsed = JSON.parse(String(com.faceclaw.app.FaceclawCalendarProvider.getCalendarsJson(context)));
|
||||||
|
if (!Array.isArray(parsed)) return [];
|
||||||
|
return parsed.filter(row => row && typeof row.id === "string" && /^\d+$/.test(row.id))
|
||||||
|
.map(row => ({ id: row.id, name: String(row.name ?? ""),
|
||||||
|
accountName: String(row.accountName ?? ""), accountType: String(row.accountType ?? "") }));
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
+15
-3
@@ -2,6 +2,8 @@ import { Utils } from "@nativescript/core";
|
|||||||
import { hasCalendarPermission } from "../g2/android-permissions";
|
import { hasCalendarPermission } from "../g2/android-permissions";
|
||||||
import { spanCurrent } from "./frame-timings";
|
import { spanCurrent } from "./frame-timings";
|
||||||
import { type CalendarEvent, type CalendarReadState } from "./calendar-types";
|
import { type CalendarEvent, type CalendarReadState } from "./calendar-types";
|
||||||
|
import { CALENDAR_SELECTION_KEY, readCalendarSelection } from "./calendar-selection";
|
||||||
|
import { onSettingsStoreChanged } from "./settings-store";
|
||||||
export type { CalendarEvent } from "./calendar-types";
|
export type { CalendarEvent } from "./calendar-types";
|
||||||
|
|
||||||
declare const com: any;
|
declare const com: any;
|
||||||
@@ -13,14 +15,21 @@ declare const com: any;
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
// Android reads synchronously; iOS notifies subscribers after background reads.
|
// Android reads synchronously; iOS notifies subscribers after background reads.
|
||||||
export function onCalendarChanged(_listener: () => void): () => void { return () => {}; }
|
export function onCalendarChanged(listener: () => void): () => void {
|
||||||
|
return onSettingsStoreChanged(key => {
|
||||||
|
if (key === CALENDAR_SELECTION_KEY || key == null) {
|
||||||
|
invalidateCalendarCache();
|
||||||
|
listener();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
export function getCalendarReadState(): CalendarReadState { return "ready"; }
|
export function getCalendarReadState(): CalendarReadState { return "ready"; }
|
||||||
|
|
||||||
const DEFAULT_MAX_EVENTS = 50;
|
const DEFAULT_MAX_EVENTS = 50;
|
||||||
const DEFAULT_WINDOW_MS = 14 * 24 * 60 * 60 * 1000;
|
const DEFAULT_WINDOW_MS = 14 * 24 * 60 * 60 * 1000;
|
||||||
const CACHE_MS = 30_000;
|
const CACHE_MS = 30_000;
|
||||||
|
|
||||||
let cache: { events: CalendarEvent[]; atMs: number; maxEvents: number; windowMs: number } | null = null;
|
let cache: { events: CalendarEvent[]; atMs: number; maxEvents: number; windowMs: number; selection: string } | null = null;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Upcoming events from now through the given window, ordered by start time.
|
* Upcoming events from now through the given window, ordered by start time.
|
||||||
@@ -35,9 +44,11 @@ export function readUpcomingEvents(
|
|||||||
if (!global.isAndroid || !hasCalendarPermission()) return [];
|
if (!global.isAndroid || !hasCalendarPermission()) return [];
|
||||||
|
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
|
const selection = JSON.stringify(readCalendarSelection());
|
||||||
if (
|
if (
|
||||||
!forceRefresh &&
|
!forceRefresh &&
|
||||||
cache &&
|
cache &&
|
||||||
|
cache.selection === selection &&
|
||||||
cache.maxEvents === maxEvents &&
|
cache.maxEvents === maxEvents &&
|
||||||
cache.windowMs === windowMs &&
|
cache.windowMs === windowMs &&
|
||||||
now - cache.atMs < CACHE_MS
|
now - cache.atMs < CACHE_MS
|
||||||
@@ -55,6 +66,7 @@ export function readUpcomingEvents(
|
|||||||
context,
|
context,
|
||||||
Math.max(0, Math.round(maxEvents)),
|
Math.max(0, Math.round(maxEvents)),
|
||||||
Math.max(0, Math.round(windowMs)),
|
Math.max(0, Math.round(windowMs)),
|
||||||
|
selection,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
@@ -62,7 +74,7 @@ export function readUpcomingEvents(
|
|||||||
const events = Array.isArray(parsed)
|
const events = Array.isArray(parsed)
|
||||||
? parsed.map(normalizeEvent).filter((event): event is CalendarEvent => Boolean(event))
|
? parsed.map(normalizeEvent).filter((event): event is CalendarEvent => Boolean(event))
|
||||||
: [];
|
: [];
|
||||||
cache = { events, atMs: now, maxEvents, windowMs };
|
cache = { events, atMs: now, maxEvents, windowMs, selection };
|
||||||
return events;
|
return events;
|
||||||
} catch {
|
} catch {
|
||||||
return [];
|
return [];
|
||||||
|
|||||||
@@ -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> & {
|
type ConfigSettingStringOptions<TId extends string> = ConfigSettingOptions<string, TId> & {
|
||||||
editorTitle?: string;
|
editorTitle?: string;
|
||||||
glassesEditTitle?: string;
|
glassesEditTitle?: string;
|
||||||
|
|||||||
+2
-50
@@ -326,7 +326,7 @@ class ShellOverlayMenuLayer extends MenuLayer {
|
|||||||
*/
|
*/
|
||||||
keepWindowFocus = false;
|
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
|
// Aligned to the min-height window band (like the sidebar), wherever the
|
||||||
// vertical position setting currently puts it; centered over the
|
// vertical position setting currently puts it; centered over the
|
||||||
// application area, i.e. the part of the screen beside a side strip
|
// application area, i.e. the part of the screen beside a side strip
|
||||||
@@ -334,7 +334,7 @@ class ShellOverlayMenuLayer extends MenuLayer {
|
|||||||
// the strip overlays).
|
// the strip overlays).
|
||||||
const width = 272;
|
const width = 272;
|
||||||
const area = appViewportRect("min");
|
const area = appViewportRect("min");
|
||||||
super(title, items, {
|
super("System", items, {
|
||||||
x: area.x + (((area.width - width) / 2) | 0),
|
x: area.x + (((area.width - width) / 2) | 0),
|
||||||
y: area.y + 8,
|
y: area.y + 8,
|
||||||
width,
|
width,
|
||||||
@@ -1304,43 +1304,6 @@ class Shell {
|
|||||||
return hidden ? this.windows.filter((window) => window !== hidden) : this.windows;
|
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:
|
* The status bar items the switcher's selection can move onto, in order:
|
||||||
* with a bottom switcher (the selection reaches them past the last
|
* 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") {
|
if (brightnessSetting.get() !== "auto") {
|
||||||
items.push({
|
items.push({
|
||||||
label: "Brightness",
|
label: "Brightness",
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
# Android calendar selection validation
|
||||||
|
|
||||||
|
Software: `npm test` and `bash lint.sh` for changed TypeScript files.
|
||||||
|
`tests/calendar-selection.test.cjs` covers preference reloads, all versus none,
|
||||||
|
duplicate names/accounts, selection changes with cached readers, deleted IDs,
|
||||||
|
recurrence occurrences and forwarding the selection to the provider before its
|
||||||
|
limit. Provider SQL structure is checked statically; the mocked bridge does not
|
||||||
|
replace an Android CalendarContract integration test.
|
||||||
|
|
||||||
|
On an Android device (pending):
|
||||||
|
|
||||||
|
1. With no saved preference, compare events with the current release.
|
||||||
|
2. Open Calendar's window menu > Calendars displayed (also available through
|
||||||
|
Glanceboard's Calendar widget settings). Select between two equal-named
|
||||||
|
calendars belonging to different accounts. Check ID/account labels.
|
||||||
|
3. Create more than 50 early events in an excluded calendar and later recurring
|
||||||
|
events in a selected calendar. Check those later occurrences still appear.
|
||||||
|
4. Select “No calendars”: Calendar, Glanceboard and any other readers must be
|
||||||
|
empty immediately. Restart and confirm the selection persists.
|
||||||
|
5. Select individual calendars, rename one, then delete one. Remaining selections
|
||||||
|
must stay unchanged. A missing selected ID is shown as unavailable and may be
|
||||||
|
removed; it never causes a fallback to all calendars.
|
||||||
|
6. Select “All calendars”, add a calendar, and check it is included. In individual
|
||||||
|
mode, newly added calendars stay excluded. Check all-day and timed recurring
|
||||||
|
events in both Calendar and Glanceboard, including timezone/DST boundaries.
|
||||||
|
|
||||||
|
IDs are Android CalendarContract IDs, stable across display-name changes within
|
||||||
|
an installation. Removing/re-adding an account can create new calendar IDs.
|
||||||
|
The iOS calendar reader and its behavior are unchanged; iOS selection is deferred.
|
||||||
@@ -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.
|
|
||||||
@@ -0,0 +1,150 @@
|
|||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const fs = require('node:fs');
|
||||||
|
const path = require('node:path');
|
||||||
|
const vm = require('node:vm');
|
||||||
|
const ts = require('typescript');
|
||||||
|
const source = file => fs.readFileSync(path.join(__dirname, '..', file), 'utf8');
|
||||||
|
function load(file, modules, globals = {}) {
|
||||||
|
const context = { exports: {}, require: name => {
|
||||||
|
assert.ok(name in modules, `Unexpected import ${name}`);
|
||||||
|
return modules[name];
|
||||||
|
}, ...globals };
|
||||||
|
vm.runInNewContext(ts.transpileModule(source(file), {
|
||||||
|
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
|
||||||
|
}).outputText, context);
|
||||||
|
return context.exports;
|
||||||
|
}
|
||||||
|
function fixture(settings = new Map()) {
|
||||||
|
const listeners = new Set();
|
||||||
|
const storage = {
|
||||||
|
getStringSetting: (key, fallback) => settings.get(key) ?? fallback,
|
||||||
|
setStringSetting: (key, value) => { settings.set(key, value); for (const fn of listeners) fn(key); },
|
||||||
|
onSettingsStoreChanged: fn => { listeners.add(fn); return () => listeners.delete(fn); },
|
||||||
|
};
|
||||||
|
const prefs = load('app/native/calendar-selection.ts', { './settings-store': storage });
|
||||||
|
let permitted = true;
|
||||||
|
const calls = [];
|
||||||
|
const calendars = [
|
||||||
|
{ id: '1', name: 'Work', accountName: 'one@example.com', accountType: 'google' },
|
||||||
|
{ id: '2', name: 'Work', accountName: 'two@example.com', accountType: 'google' },
|
||||||
|
];
|
||||||
|
const events = [
|
||||||
|
{ id: 1, calendarId: '1', startMs: 10000, endMs: 20000, title: 'Excluded early' },
|
||||||
|
{ id: 9, calendarId: '2', startMs: 30000, endMs: 40000, title: 'Recurrence one' },
|
||||||
|
{ id: 9, calendarId: '2', startMs: 50000, endMs: 60000, title: 'Recurrence two' },
|
||||||
|
];
|
||||||
|
const modules = {
|
||||||
|
'@nativescript/core': { Utils: { android: { getApplicationContext: () => ({}) } } },
|
||||||
|
'../g2/android-permissions': { hasCalendarPermission: () => permitted },
|
||||||
|
'./calendar-permissions': { hasCalendarPermission: () => permitted },
|
||||||
|
'./frame-timings': { spanCurrent: (_name, fn) => fn() },
|
||||||
|
'./calendar-selection': prefs,
|
||||||
|
'./settings-store': storage,
|
||||||
|
};
|
||||||
|
const globals = { global: { isAndroid: true }, com: { faceclaw: { app: { FaceclawCalendarProvider: {
|
||||||
|
getCalendarsJson: () => JSON.stringify(calendars),
|
||||||
|
getUpcomingEventsJson: (_ctx, max, window, selection) => {
|
||||||
|
calls.push({ max, window, selection });
|
||||||
|
const ids = JSON.parse(selection);
|
||||||
|
return JSON.stringify(events.filter(event => ids === null || ids.includes(event.calendarId)).slice(0, max));
|
||||||
|
},
|
||||||
|
} } } } };
|
||||||
|
const api = load('app/native/calendar.ts', modules, globals);
|
||||||
|
const sources = load('app/native/calendar-sources.ts', modules, globals);
|
||||||
|
return { api, prefs, sources, modules, globals, settings, calls, calendars,
|
||||||
|
permissions: value => { permitted = value; } };
|
||||||
|
}
|
||||||
|
|
||||||
|
test('calendar selection distinguishes all and none, survives restart and rejects invalid data', () => {
|
||||||
|
const f = fixture();
|
||||||
|
assert.equal(f.prefs.readCalendarSelection(), null);
|
||||||
|
f.prefs.setCalendarSelection([]);
|
||||||
|
assert.deepEqual(Array.from(fixture(f.settings).prefs.readCalendarSelection()), []);
|
||||||
|
f.prefs.setCalendarSelection(['2', '2', '1']);
|
||||||
|
assert.deepEqual(Array.from(fixture(f.settings).prefs.readCalendarSelection()), ['2', '1']);
|
||||||
|
f.prefs.setCalendarSelection(null);
|
||||||
|
assert.equal(fixture(f.settings).prefs.readCalendarSelection(), null);
|
||||||
|
assert.throws(() => f.prefs.setCalendarSelection(['1 OR 1=1']));
|
||||||
|
for (const value of ['oops', '{}', '[false]', '["bad"]']) {
|
||||||
|
f.settings.set(f.prefs.CALENDAR_SELECTION_KEY, value);
|
||||||
|
assert.equal(f.prefs.readCalendarSelection(), null);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('shared reader forwards IDs before limiting, preserves recurrence occurrences and invalidates all cached query variants', async () => {
|
||||||
|
const f = fixture();
|
||||||
|
assert.equal(f.api.readUpcomingEvents(1)[0].title, 'Excluded early');
|
||||||
|
f.api.readUpcomingEvents(1);
|
||||||
|
assert.equal(f.calls.length, 1);
|
||||||
|
let notifications = 0;
|
||||||
|
const off = f.api.onCalendarChanged(() => notifications++);
|
||||||
|
f.prefs.setCalendarSelection(['2']);
|
||||||
|
const rows = f.api.readUpcomingEvents(2);
|
||||||
|
assert.deepEqual(Array.from(rows, event => event.id), [9, 9]);
|
||||||
|
assert.equal(f.calls.at(-1).selection, '["2"]');
|
||||||
|
assert.equal(notifications, 1);
|
||||||
|
assert.equal((await f.api.readUpcomingEventsAsync(1))[0].title, 'Recurrence one');
|
||||||
|
off();
|
||||||
|
f.prefs.setCalendarSelection([]);
|
||||||
|
assert.equal(notifications, 1);
|
||||||
|
assert.equal(f.api.readUpcomingEvents(1).length, 0, 'selection cache key works even without subscriptions');
|
||||||
|
assert.equal(fixture(f.settings).api.readUpcomingEvents().length, 0);
|
||||||
|
f.prefs.setCalendarSelection(['999']);
|
||||||
|
assert.equal(f.api.readUpcomingEvents().length, 0, 'deleted calendar does not revert to all');
|
||||||
|
f.permissions(false);
|
||||||
|
assert.equal(f.api.readUpcomingEvents().length, 0);
|
||||||
|
assert.equal(f.sources.readAvailableCalendars().length, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('calendar menu distinguishes equal names by account and ID; all, none, deleted and individual selections share preferences', () => {
|
||||||
|
const f = fixture();
|
||||||
|
const { CalendarFilterLayer } = load('app/apps/calendar/calendar-filter.ts', {
|
||||||
|
'../../graphics/ui-fonts': { getDefaultSmallFont: () => ({}) },
|
||||||
|
'../../graphics/textwrap': { truncateText: (_font, text) => text },
|
||||||
|
'../../native/calendar-selection': f.prefs,
|
||||||
|
'../../native/calendar-sources': f.sources,
|
||||||
|
'../../native/calendar-permissions': { hasCalendarPermission: () => true },
|
||||||
|
'../../ui/menu': {
|
||||||
|
drawToggleMenuItem: () => {},
|
||||||
|
MenuLayer: class {
|
||||||
|
constructor(_title, items) { this.items = items; this.selectedIndex = 0; }
|
||||||
|
selectItem(index) { this.selectedIndex = index; return this; }
|
||||||
|
setItems(items, index) { this.items = items; this.selectedIndex = index; }
|
||||||
|
paint() { return this.items; }
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}, f.globals);
|
||||||
|
const layer = new CalendarFilterLayer();
|
||||||
|
const ctx = { stack: { getBaseSize: () => ({ width: 576 }) } };
|
||||||
|
const rows = () => layer.paint(ctx, () => {});
|
||||||
|
assert.ok(rows()[2].label.includes('one@example.com'));
|
||||||
|
assert.ok(rows()[3].label.includes('two@example.com'));
|
||||||
|
rows()[2].onSelect();
|
||||||
|
assert.deepEqual(Array.from(f.prefs.readCalendarSelection()), ['2']);
|
||||||
|
rows()[1].onSelect();
|
||||||
|
assert.equal(f.api.readUpcomingEvents().length, 0);
|
||||||
|
rows()[3].onSelect();
|
||||||
|
assert.deepEqual(Array.from(f.prefs.readCalendarSelection()), ['2']);
|
||||||
|
f.calendars.pop();
|
||||||
|
const missing = rows().find(row => row.label === 'Unavailable calendar #2');
|
||||||
|
assert.ok(missing);
|
||||||
|
missing.onSelect();
|
||||||
|
assert.equal(f.prefs.readCalendarSelection().length, 0);
|
||||||
|
rows()[0].onSelect();
|
||||||
|
assert.equal(f.prefs.readCalendarSelection(), null);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Android provider restricts Instances with bound calendar IDs before cutoff and limit', () => {
|
||||||
|
const kotlin = source('App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawCalendarProvider.kt');
|
||||||
|
assert.match(kotlin, /Instances\.CALENDAR_ID/);
|
||||||
|
assert.match(kotlin, /if \(ids != null && ids.length\(\) == 0\) return "\[\]"/);
|
||||||
|
assert.match(kotlin, /PROJECTION,\s+selection,\s+args,/);
|
||||||
|
assert.ok(kotlin.indexOf('selection,\n args,') < kotlin.indexOf('events.take(limit)'));
|
||||||
|
assert.match(kotlin, /CalendarContract\.Calendars\._ID/);
|
||||||
|
assert.match(kotlin, /CalendarContract\.Calendars\.ACCOUNT_NAME/);
|
||||||
|
for (const file of ['app/apps/calendar/calendar.ts', 'app/apps/glanceboard/widgets/calendar-widget.ts']) {
|
||||||
|
assert.match(source(file), /readUpcomingEvents/);
|
||||||
|
assert.match(source(file), /native\/calendar"/);
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -199,6 +199,7 @@ test('Calendar window subscribes, refreshes periodically, and cleans up on close
|
|||||||
'../../native/calendar': { onCalendarChanged: fn => { listener = fn; return () => unsubscribed++; } },
|
'../../native/calendar': { onCalendarChanged: fn => { listener = fn; return () => unsubscribed++; } },
|
||||||
'../../ui/shell/chrome-layer': { makeImageWindowIcon() {}, windowIcon() {} },
|
'../../ui/shell/chrome-layer': { makeImageWindowIcon() {}, windowIcon() {} },
|
||||||
'./calendar': { CalendarLayer: class {} }, './calendar-icon': {},
|
'./calendar': { CalendarLayer: class {} }, './calendar-icon': {},
|
||||||
|
'./calendar-filter': { calendarSelectionMenuItems: () => [] },
|
||||||
'../../ui/shell/in-process-window': { YieldAtRootLayer: class {}, createInProcessWindow: value => { options = value; return app; } },
|
'../../ui/shell/in-process-window': { YieldAtRootLayer: class {}, createInProcessWindow: value => { options = value; return app; } },
|
||||||
}, { setInterval: fn => { tick = fn; return 1; }, clearInterval: () => cleared++ });
|
}, { setInterval: fn => { tick = fn; return 1; }, clearInterval: () => cleared++ });
|
||||||
createCalendarAppWindow({ onClosed: () => closed++ });
|
createCalendarAppWindow({ onClosed: () => closed++ });
|
||||||
|
|||||||
@@ -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']);
|
|
||||||
});
|
|
||||||
@@ -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'));
|
|
||||||
});
|
|
||||||
Reference in new issue
Block a user