Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package com.callstack.agentdevice.snapshothelper;

import android.content.res.Configuration;
import android.os.LocaleList;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
* Sets the system locale list. It runs through {@code app_process} as the shell user, which holds
* CHANGE_CONFIGURATION and WRITE_SETTINGS; no installed app can hold the first. This is the same
* persistent configuration update the Settings language picker makes, so it survives a reboot and
* running apps receive a configuration change.
*
* <p>Usage: {@code app_process /system/bin <this class> <language tags>}. It prints {@code
* previous=<tags>} and {@code current=<tags>}, or {@code error=<message>} and exits 1.
*/
public final class SystemLocaleCommand {
private SystemLocaleCommand() {}

public static void main(String[] args) {
try {
if (args.length != 1 || args[0].isEmpty()) {
throw new IllegalArgumentException("Pass one comma-separated list of language tags");
}
LocaleList requested = LocaleList.forLanguageTags(args[0]);
Object activityManager =
Class.forName("android.app.ActivityManager").getMethod("getService").invoke(null);
Class<?> service = Class.forName("android.app.IActivityManager");
Method getConfiguration = service.getMethod("getConfiguration");
Configuration previous = (Configuration) getConfiguration.invoke(activityManager);
Configuration update = new Configuration();
update.setLocales(requested);
Configuration.class.getField("userSetLocale").setBoolean(update, true);
service
.getMethod("updatePersistentConfiguration", Configuration.class)
.invoke(activityManager, update);
Configuration current = (Configuration) getConfiguration.invoke(activityManager);
System.out.println("previous=" + previous.getLocales().toLanguageTags());
System.out.println("current=" + current.getLocales().toLanguageTags());
} catch (Throwable error) {
Throwable cause = error instanceof InvocationTargetException ? error.getCause() : error;
System.out.println("error=" + cause);
System.exit(1);
}
}
}
14 changes: 14 additions & 0 deletions packages/command-surface/src/capture/settings.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,20 @@ describe('settings CLI permission', () => {
);
});

test('reads locale as a written value the daemon parses again', () => {
const locale = settingsCliReader(['locale', 'en_IN'], {
targetApp: 'com.example.app',
} as CliFlags);
expect(locale).toEqual({ setting: 'locale', state: 'en-IN', app: 'com.example.app' });
expect(settingsDaemonWriter(locale)).toMatchObject({
positionals: ['locale', 'en-IN'],
input: { app: 'com.example.app' },
});
expect(() => settingsCliReader(['locale', 'english'], flags())).toThrow(
expect.objectContaining({ code: 'INVALID_ARGS' }),
);
});

test.each(['mobile-data', 'bluetooth'])(
'forwards --app on %s so the daemon refuses it instead of dropping it',
(setting) => {
Expand Down
6 changes: 3 additions & 3 deletions packages/command-surface/src/capture/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import { defineFieldCommandMetadata } from '../field-command-contract.ts';

const SETTINGS_COMMAND_NAME = 'settings';
const settingsCommandDescription =
'Read or change supported operating-system settings, animation scales, appearance, time zone, or app permissions on the selected target. Platform support varies by setting and action.';
'Read or change supported operating-system settings, animation scales, appearance, locale, time zone, or app permissions on the selected target. Platform support varies by setting and action.';

const settingsCommandMetadata = defineFieldCommandMetadata(
SETTINGS_COMMAND_NAME,
Expand All @@ -35,7 +35,7 @@ const settingsCommandMetadata = defineFieldCommandMetadata(
// A readable setting answers with no state; the parse decides per setting.
state: stringField(),
app: stringField(
'App the change targets, by bundle id, package name, or app name: the app `clear-app-state` clears, or the app a `permission` change (or an iOS-simulator `location on|off` privacy change) lands on. A name resolves to the installed app as `open` resolves it: an iOS simulator, local or Limrun, matches display names and accepts only an installed bundle id, and Android accepts only an installed package and refuses a name that resolves to an intent with `setting_app_not_package`. One that resolves to nothing is refused with `app_not_installed` before anything changes. The app need not be running. Without it the session app is used; a device-wide change (`location set` on any target, the Android `location on|off` toggle, `mobile-data`, `keep-awake`, `bluetooth`, `timezone`, macOS permissions) refuses one with `setting_app_not_consumed`. The CLI reads it only from this invocation, never from `AGENT_DEVICE_TARGET_APP` or config `targetApp`.',
'App the change targets, by bundle id, package name, or app name: the app `clear-app-state` clears, or the app a `permission` change (or an iOS-simulator `location on|off` privacy change) lands on. A name resolves to the installed app as `open` resolves it: an iOS simulator, local or Limrun, matches display names and accepts only an installed bundle id, and Android accepts only an installed package and refuses a name that resolves to an intent with `setting_app_not_package`. One that resolves to nothing is refused with `app_not_installed` before anything changes. The app need not be running. Without it the session app is used; a device-wide change (`location set` on any target, the Android `location on|off` toggle, `mobile-data`, `keep-awake`, `bluetooth`, `locale`, `timezone`, macOS permissions) refuses one with `setting_app_not_consumed`. The CLI reads it only from this invocation, never from `AGENT_DEVICE_TARGET_APP` or config `targetApp`.',
),
latitude: numberField(),
longitude: numberField(),
Expand Down Expand Up @@ -101,7 +101,7 @@ export const settingsCommandFacet = defineCommandFacet({
effect: 'destructive',
text: {
summary: 'Change OS settings and app permissions',
searchHint: 'wifi airplane location dark mode permission grant revoke timezone',
searchHint: 'wifi airplane location dark mode permission grant revoke language timezone',
cliDetail: [
'A bare readable setting reads the value the target holds. A target that does not serve a setting refuses it with UNSUPPORTED_OPERATION before anything changes.',
'',
Expand Down
8 changes: 8 additions & 0 deletions packages/contracts/src/client-settings.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,14 @@ describe('public client settings cover the catalog', () => {
expectTypeOf<{ setting: 'timezone' }>().not.toExtend<SettingsUpdateOptions>();
expectTypeOf<Value['app']>().toEqualTypeOf<string | undefined>();
});

test('locale takes a value or reset, and an app to refuse', () => {
type Value = Extract<SettingsUpdateOptions, { setting: 'locale' }>;
expectTypeOf<{ setting: 'locale'; state: 'en_IN' }>().toExtend<SettingsUpdateOptions>();
expectTypeOf<{ setting: 'locale'; state: 'reset' }>().toExtend<SettingsUpdateOptions>();
expectTypeOf<{ setting: 'locale' }>().not.toExtend<SettingsUpdateOptions>();
expectTypeOf<Value['app']>().toEqualTypeOf<string | undefined>();
});
});

/**
Expand Down
6 changes: 6 additions & 0 deletions packages/contracts/src/settings-catalog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,12 @@ export const SETTINGS = {
appScope: { apple: 'device-level', mobile: 'device-level' },
help: 'Sets the device time zone from an IANA name, such as Asia/Kolkata, on iPhone and iPad simulators (sets TZ in simulator launchd; applies only to apps launched afterwards and is lost when the simulator reboots; the status bar keeps the host time) and Android (the system time zone, with automatic time zone turned off). reset hands it back to the device default: the host Mac time zone on a simulator, and automatic time zone on Android, which applies the network zone a moment later. The response reports the time zone held before. --app is refused.',
},
locale: {
forms: [{ kind: 'value', placeholder: 'locale-id' }],
app: 'input',
appScope: { apple: 'device-level', mobile: 'device-level' },
help: 'Sets the device language and region from one locale id, such as en_IN or fr-CA, on iPhone and iPad simulators (AppleLanguages and AppleLocale) and Android (the system locale list). reset removes the simulator override, which leaves English with no region, and applies the system image default on Android. The response reports the locale held before. An iOS app reads the locale at launch, so relaunch it; Android applies it to running apps at once. --app is refused.',
},
faceid: {
forms: [{ kind: 'choice', states: ['match', 'nonmatch', 'enroll', 'unenroll'] }],
help: 'Simulates Face ID on iPhone and iPad simulators.',
Expand Down
49 changes: 49 additions & 0 deletions packages/contracts/src/settings.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
describeSettingRead,
describeSettingWrite,
parseAppearanceAction,
parseLocaleId,
parsePermissionAction,
parsePermissionTarget,
parseSettingsMutation,
Expand Down Expand Up @@ -46,6 +47,7 @@ describe('settings usage', () => {
'settings appearance <light|dark|toggle>',
`settings text-size [${TEXT_SIZE_CATEGORIES.join('|')}]`,
'settings timezone <iana-zone|reset>',
'settings locale <locale-id|reset>',
'settings <faceid|touchid> <match|nonmatch|enroll|unenroll>',
'settings fingerprint <match|nonmatch>',
'settings clear-app-state [app-id]',
Expand Down Expand Up @@ -276,6 +278,47 @@ describe('timezone', () => {
});
});

describe('locale', () => {
test('a locale id is carried as its BCP 47 tag whichever separator and casing it uses', () => {
expect(parseSettingsMutation(['Locale', 'en_in'])).toEqual({
setting: 'locale',
state: 'en-IN',
});
expect(parseLocaleId('fr-CA')).toBe('fr-CA');
expect(parseLocaleId(' zh_hans_cn ')).toBe('zh-Hans-CN');
expect(parseLocaleId('es_419')).toBe('es-419');
expect(parseLocaleId('EN')).toBe('en');
});

test('a locale with an extension or variant, or no language, is refused before dispatch', () => {
for (const value of ['en-US-u-ca-buddhist', 'en_US_POSIX', 'english', 'x', '']) {
expectInvalidArgs(() => parseLocaleId(value), `Invalid locale id: ${value}.`);
}
});

test('reset is a state of its own, and locale takes exactly one value', () => {
expect(parseSettingsMutation(['locale', 'RESET'])).toEqual({
setting: 'locale',
state: 'reset',
});
expectInvalidArgs(
() => parseSettingsMutation(['locale']),
'settings locale requires a state: <locale-id|reset>.',
);
expectInvalidArgs(
() => parseSettingsMutation(['locale', 'en_IN', 'extra']),
SETTINGS_INVALID_ARGS_MESSAGE,
);
});

test('locale writes answer with the locale set or the reset', () => {
expect(describeSettingWrite('locale', 'en-IN', undefined)).toBe('Locale set to en-IN');
expect(describeSettingWrite('locale', 'reset', undefined)).toBe(
'Locale reset to the device default',
);
});
});

describe('owner parsers', () => {
test('parsePermissionTarget accepts the mobile targets only', () => {
expect(parsePermissionTarget(' Camera ')).toBe('camera');
Expand Down Expand Up @@ -335,6 +378,12 @@ describe('settingsAppScope device-wide settings', () => {
expect(settingsAppScope('macos-host', 'timezone', 'reset')).toBe('unknown');
});

test('locale changes the whole device on every mobile family', () => {
expect(settingsAppScope('apple', 'locale', 'reset')).toBe('device-level');
expect(settingsAppScope('mobile', 'locale', 'en-IN')).toBe('device-level');
expect(settingsAppScope('macos-host', 'locale', 'reset')).toBe('unknown');
});

test.each(['mobile-data', 'keep-awake', 'bluetooth'])(
'%s switches the whole device wherever it is served',
(setting) => {
Expand Down
30 changes: 30 additions & 0 deletions packages/contracts/src/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,11 @@ export function describeSettingWrite(
? 'Time zone reset to the device default'
: `Time zone set to ${state}`;
}
if (setting === 'locale') {
return state === SETTING_RESET_STATE
? 'Locale reset to the device default'
: `Locale set to ${state}`;
}
return `Updated setting: ${setting}`;
}

Expand Down Expand Up @@ -419,6 +424,7 @@ type ValueSetting = {
}[SettingName];

const VALUE_PARSERS = {
locale: parseLocaleId,
timezone: parseTimeZoneId,
} as const satisfies Record<ValueSetting, (value: string) => string>;

Expand Down Expand Up @@ -453,6 +459,30 @@ function isKnownTimeZone(name: string): boolean {
}
}

/** A language, an optional script, and an optional region: the parts every owner can write. */
const LOCALE_ID_PATTERN = /^[a-z]{2,3}(-[A-Z][a-z]{3})?(-([A-Z]{2}|\d{3}))?$/;

/**
* The BCP 47 tag of a locale id written with `-` or `_` in any casing, such as `en-IN` for `en_in`.
* Extensions and variants are refused: neither owner can apply them.
*/
export function parseLocaleId(value: string): string {
const canonical = canonicalLocale(value.trim().replaceAll('_', '-'));
if (canonical !== undefined && LOCALE_ID_PATTERN.test(canonical)) return canonical;
throw new AppError(
'INVALID_ARGS',
`Invalid locale id: ${value}. Use a language with an optional script and region, such as en_IN, fr-CA, or zh-Hans-CN.`,
);
}

function canonicalLocale(tag: string): string | undefined {
try {
return Intl.getCanonicalLocales(tag)[0];
} catch {
return undefined;
}
}

function normalizeName(value: string | undefined): string | undefined {
return value?.trim().toLowerCase();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,7 @@ function settingsFacts(device: DeviceInfo) {
appearance: available,
'text-size': available,
timezone: available,
locale: available,
fingerprint: available,
'clear-app-state': available,
permission: available,
Expand Down Expand Up @@ -229,6 +230,7 @@ function settingsFacts(device: DeviceInfo) {
permission: available,
'text-size': handheld,
timezone: handheld,
locale: handheld,
faceid: handheld,
touchid: handheld,
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -751,6 +751,63 @@ test('settings timezone refuses an invalid zone and a tvOS leaf before reaching
expect(fixtureSettingsMutations).toHaveLength(0);
});

test.each([
{ positionals: ['locale', 'fr_ca'], state: 'fr-CA', message: 'Locale set to fr-CA' },
{
positionals: ['locale', 'RESET'],
state: 'reset',
message: 'Locale reset to the device default',
},
])('settings $positionals reaches the owner as the parsed value', async (row) => {
const sessionStore = makeSessionStore();
const sessionName = `ios-${row.positionals[0]}-${row.state}`;
sessionStore.publish(sessionName, makeSession(sessionName, iosSimulatorDevice));

const response = await handleSnapshotCommands({
createCommandSurface: fakeCreateCommandSurface,
platformServices: daemonPlatformServicesFixture(),
req: snapshotRequest(sessionName, 'settings', { positionals: row.positionals }),
sessionName,
logPath: '/tmp/daemon.log',
sessionStore,
});

expect(response?.ok && response.data).toMatchObject({ state: row.state, message: row.message });
expect(fixtureSettingsMutations.at(-1)).toMatchObject({
setting: row.positionals[0],
state: row.state,
});
});

test('settings locale refuses an invalid id and a tvOS leaf before reaching the owner', async () => {
const sessionStore = makeSessionStore();
sessionStore.publish('ios-locale-invalid', makeSession('ios-locale-invalid', iosSimulatorDevice));
sessionStore.publish('tvos-locale', makeSession('tvos-locale', tvOsSimulatorDevice));

const invalid = await handleSnapshotCommands({
createCommandSurface: fakeCreateCommandSurface,
platformServices: daemonPlatformServicesFixture(),
req: snapshotRequest('ios-locale-invalid', 'settings', {
positionals: ['locale', 'en-u-nu-thai'],
}),
sessionName: 'ios-locale-invalid',
logPath: '/tmp/daemon.log',
sessionStore,
});
const tvos = await handleSnapshotCommands({
createCommandSurface: fakeCreateCommandSurface,
platformServices: daemonPlatformServicesFixture(),
req: snapshotRequest('tvos-locale', 'settings', { positionals: ['locale', 'en_IN'] }),
sessionName: 'tvos-locale',
logPath: '/tmp/daemon.log',
sessionStore,
});

expect(invalid?.ok === false && invalid.error.code).toBe('INVALID_ARGS');
expect(tvos?.ok === false && tvos.error.code).toBe('UNSUPPORTED_OPERATION');
expect(fixtureSettingsMutations).toHaveLength(0);
});

// A macOS permission is a host-level TCC grant, so naming an app is refused rather than dropped.
test('settings mobile-data reaches the Android owner as an on/off mutation', async () => {
const sessionStore = makeSessionStore();
Expand All @@ -774,6 +831,7 @@ test.each([
['mobile-data', 'off'],
['keep-awake', 'off'],
['bluetooth', 'off'],
['locale', 'en_IN'],
['timezone', 'Asia/Kolkata'],
])('settings Android %s refuses a named app before reaching the owner', async (setting, state) => {
const sessionStore = makeSessionStore();
Expand Down
Loading
Loading