# Appearance API

A theme is no longer a separate plugin kind. Any signed code plugin that declares
`ui.appearance` can apply a complete color theme at runtime through `AppearanceHost`.
There is no `kind: "theme"`, no `theme/theme.json`, no theme package preview and no
theme catalog.

Status: **delivered for code plugins**. The appearance API supports semantic palette
tokens, raw upstream color keys, plugin-scoped custom colors, apply, reset, persistence,
safe mode, and removal on disable, uninstall or revocation. Fonts, wallpapers, in-app
icons and layout-style overrides are not part of this milestone.

## 1. Declaring the capability

```json
{
  "kind": "code",
  "platforms": ["android"],
  "entrypoints": {
    "android": "dev.example.midnight.MidnightPlugin"
  },
  "permissions": ["ui.appearance"]
}
```

Rules:

- The plugin must be a normal code plugin with DEX and `entrypoints.android`.
- `ui.appearance` is required for every appearance method. Without it, the host throws
  `PermissionDeniedException`.
- A package with `kind: "theme"` is rejected with `E_UNSUPPORTED_KIND` and the message
  `Theme packages are no longer supported. Ship a code plugin with the ui.appearance permission.`
- One code plugin can combine appearance, settings, actions and screen replacement.

## 2. `AppearanceTheme`

`AppearanceTheme` is an immutable value built with a fluent builder:

```java
public final class AppearanceTheme {
    public enum Base { LIGHT, DARK, AMOLED }

    public static Builder builder(Base base);
    public Base base();
    public Map<String, Integer> colors();       // semantic palette tokens
    public Map<String, Integer> rawColors();    // upstream Theme.key_* values
    public Map<String, Integer> customColors(); // plugin-scoped, not applied upstream

    public static final class Builder {
        public Builder color(String token, int color);
        public Builder rawColor(String upstreamKey, int color);
        public Builder customColor(String key, int color);
        public AppearanceTheme build();
    }
}
```

A `null` base falls back to `LIGHT`. Colors are ARGB integers, for example
`0xFF16121C`. The host maps the base to a coherent default palette, then applies the
semantic colors, then the raw colors.

### 2.1 Base

| Base | Meaning |
| --- | --- |
| `LIGHT` | Light app palette, light dialogs and light default chat bubbles |
| `DARK` | Dark app palette with dark surfaces |
| `AMOLED` | Dark palette with black window and chat backgrounds |

The base supplies defaults for every token the theme does not override. It is a palette
overlay, not a full copy of the Telegram theme engine.

## 3. Semantic tokens

Semantic tokens are stable SDK names exposed as constants in `AppearancePalette`.
`AppearanceTheme.Builder.color(...)` validates them; an unknown token throws
`IllegalArgumentException` and no partial theme is created.

| Constant | Token | Used for |
| --- | --- | --- |
| `WINDOW_BACKGROUND` | `window.background` | Main window, list and message panel background |
| `WINDOW_BACKGROUND_GRAY` | `window.backgroundGray` | Grouped settings and secondary surfaces |
| `ACTION_BAR_BACKGROUND` | `actionBar.background` | Action bar and toolbar |
| `ACTION_BAR_TEXT` | `actionBar.text` | Action bar title and icons |
| `CHAT_BACKGROUND` | `chat.background` | Chat canvas behind bubbles |
| `CHAT_BUBBLE_IN` | `chat.bubbleIn` | Incoming bubble |
| `CHAT_BUBBLE_OUT` | `chat.bubbleOut` | Outgoing bubble |
| `CHAT_BUBBLE_TEXT_IN` | `chat.bubbleTextIn` | Incoming bubble text |
| `CHAT_BUBBLE_TEXT_OUT` | `chat.bubbleTextOut` | Outgoing bubble text |
| `CHAT_SERVICE` | `chat.service` | Service message background |
| `TEXT_PRIMARY` | `text.primary` | Primary text |
| `TEXT_SECONDARY` | `text.secondary` | Secondary text and subtitles |
| `TEXT_DISABLED` | `text.disabled` | Disabled text |
| `ACCENT` | `accent` | Accent, selected state and primary action |
| `DIVIDER` | `divider` | Dividers and separators |
| `LINK` | `link` | Links in messages and profiles |
| `BUTTON_BACKGROUND` | `button.background` | Primary button fill |
| `BUTTON_TEXT` | `button.text` | Primary button text |
| `BADGE` | `badge` | Unread and mention badges |
| `DIALOG_BACKGROUND` | `dialog.background` | Dialogs and bottom sheets |
| `DIALOG_TEXT` | `dialog.text` | Dialog text |
| `NOTIFICATION_BACKGROUND` | `notification.background` | Reserved for compatibility; currently accepted with a warning and not applied |
| `SELECTION_BACKGROUND` | `selection.background` | Text selection and list selection |
| `DANGER` | `danger` | Destructive actions |
| `WARNING` | `warning` | Warnings |
| `SUCCESS` | `success` | Success states |

`AppearancePalette.tokens()` returns the current set and `AppearancePalette.isKnown`
checks a name. Adding a token is an additive SDK change.

`NOTIFICATION_BACKGROUND` has no stable upstream key in this host build. It is accepted
for source compatibility, logged as unsupported during apply, and `themeColor` returns the
fallback until a notification surface is mapped.

## 4. Raw upstream colors

Some surfaces do not have a semantic token. `rawColor` accepts the string value of an
upstream `Theme.key_*` constant:

```java
AppearanceTheme.builder(AppearanceTheme.Base.DARK)
    .color(AppearancePalette.WINDOW_BACKGROUND, 0xFF101318)
    // Theme.key_windowBackgroundWhite
    .rawColor("windowBackgroundWhite", 0xFF101318)
    // Theme.key_chat_inBubbleSelected
    .rawColor("chat_inBubbleSelected", 0xFF1C2530)
    .build();
```

Rules:

- The key is the bare `Theme.key_*` name, not a Java expression. Pass
  `windowBackgroundWhite` for `Theme.key_windowBackgroundWhite`.
- Builder validation accepts `[A-Za-z0-9_]+` keys up to 128 characters.
- The host validates the key against the theme keys of the current Telegram version.
  Unknown keys are dropped with a warning; they never crash the app.
- Raw colors are applied after semantic colors, so a raw key overrides the semantic
  mapping for the same upstream key.
- Low-contrast text/background pairs are logged as warnings, not rejected.
- Raw keys are not a stable cross-version contract. Prefer semantic tokens where one
  exists.

## 5. Custom colors

Custom colors are plugin-scoped values that are not written to upstream `Theme` keys:

```java
AppearanceTheme.builder(AppearanceTheme.Base.DARK)
    .customColor("surfaceRaised", 0xFF1B1E24)
    .customColor("onSurfaceMuted", 0xFFA8B0BD)
    .build();
```

- Keys match `[a-zA-Z0-9._-]{1,128}`.
- The host prefixes the key internally with the plugin id, so two plugins can use the
  same key without collision.
- The values are persisted with the active appearance and cleared on reset.
- Read them with `AppearanceHost.customColor(key, fallback)`.
- They are intended for plugin views and slots; they do not recolor Telegram by
  themselves.

## 6. Limits and validation

| Rule | Behavior |
| --- | --- |
| At most 256 entries in `colors()`, `rawColors()` and `customColors()` | Builder throws `IllegalArgumentException` at 257 |
| Key length at most 128 characters | Builder throws `IllegalArgumentException` |
| Empty or null semantic, raw or custom key | Builder throws `IllegalArgumentException` |
| Unknown semantic token | Builder throws `IllegalArgumentException` |
| Raw key outside `[A-Za-z0-9_]+` | Builder throws `IllegalArgumentException` |
| Custom key outside `[a-zA-Z0-9._-]{1,128}` | Builder throws `IllegalArgumentException` |
| Raw key unknown to the current host | Dropped with a warning |
| Low contrast text pair | Warning in the host log |
| Color value | ARGB `int`; alpha is preserved |

Applying an empty theme is valid: it applies the base palette only.

## 7. Host API

`AppearanceHost` is resolved through the plugin context and requires `ui.appearance`:

```java
AppearanceHost host = context.require(AppearanceHost.class);

CompletableFuture<Void> applyTheme(AppearanceTheme theme);
void resetTheme();
boolean hasTheme();
int themeColor(String token, int fallback);
int customColor(String key, int fallback);
```

| Method | Behavior |
| --- | --- |
| `applyTheme` | Validates and applies the theme; completes when the theme is active, completes exceptionally when apply fails |
| `resetTheme` | Removes the calling plugin's active theme and restores the previous theme |
| `hasTheme` | Whether the calling plugin currently owns the active appearance |
| `themeColor` | Effective color from the active plugin theme, then the current host theme, then `fallback` |
| `customColor` | The calling plugin's custom color, or `fallback` |

Blur and avatar shape remain part of the same host:

```java
int blur = host.blurStrength();
host.setBlurStrength(60);
host.resetBlurStrength();

int shape = host.avatarShape();
host.setAvatarShape(AppearanceHost.AVATAR_SHAPE_SQUIRCLE);
host.resetAvatarShape();
```

### 7.1 Palette compatibility

Existing code plugins that call the semantic palette API keep working:

```java
void applyPalette(AppearancePalette palette);
void resetPalette();
boolean hasPalette();
```

`applyPalette` copies `AppearancePalette.colors()` into a semantic-only
`AppearanceTheme` and applies it through the same appearance runtime. `resetPalette`
and `hasPalette` are wrappers around `resetTheme` and `hasTheme`. A palette and a full
theme are the same active provider; the most recent successful apply wins.

`dev.nextgram.betterblur` 1.0.1 and `dev.nextgram.md3` continue to load without a
rebuild. `betterblur` only uses blur controls.

## 8. Apply and reset semantics

- `applyTheme` is marshalled onto the main thread. The returned future completes when the
  theme is active and completes exceptionally when apply fails.
- Only one appearance provider is active at a time. The most recent successful apply
  wins, even when it comes from another plugin.
- The runtime writes an `.attheme` file into the app cache, calls the existing
  `Theme.applyThemeFile` path, and remembers the previous theme key.
- A successful apply persists the active plugin id, the previous theme key and the
  plugin's custom colors.
- A failed apply restores the previous theme, keeps the previous active state and
  completes the future exceptionally. The app is never left half-themed.
- `resetTheme` clears the active state, restores the theme that was active before the
  plugin applied, and falls back to `Theme.applyPreviousTheme()` when that theme is no
  longer available.
- Applying from `onLoad` is allowed but discouraged. Use `onStart` or a settings action
  so the UI exists and the user can see the result.
- Apply emits `ThemeChangedEvent`; attached plugin screens receive `onThemeChanged`.

## 9. Persistence and the Reset appearance action

Appearance state is stored in the kernel preference file `nextgram_plugin_runtime`:

- `active_appearance_plugin_id`;
- `previous_appearance_theme_key`;
- `appearance_base_theme_key`;
- `appearance_custom_<safePluginId>`;
- `screen_overrides_enabled` for the screen kill switch.

The plugin manager has an **Appearance** section. It shows the active provider name or
**Stock theme** and a kernel-owned **Reset appearance** action. The reset action works
without the plugin being loaded and is the supported recovery path when a plugin's
settings screen is unusable.

There is no theme catalog, preview or apply/revert screen for theme packages.

## 10. Disable, uninstall, revocation and safe mode

- Disabling or uninstalling the active appearance plugin resets its theme immediately.
- A critical revocation resets the appearance if the revoked plugin owns it.
- Safe mode unloads external plugins, resets the active appearance and starts with the
  stock theme. Safe mode never applies a plugin theme.
- At boot, a persisted appearance whose plugin is missing, disabled or revoked is
  cleared before the first frame.
- Disabling, uninstalling, a critical revocation, safe mode and turning off external code
  reset the active appearance.
- The theme persists across app restarts while the plugin stays installed and enabled.

## 11. Complete example

```java
package dev.example.midnight;

import dev.nextgram.plugin.v1.AbstractNextGramPlugin;
import dev.nextgram.plugin.v1.PluginContext;
import dev.nextgram.plugin.v1.Permissions;
import dev.nextgram.plugin.v1.host.AppearanceHost;
import dev.nextgram.plugin.v1.host.AppearancePalette;
import dev.nextgram.plugin.v1.host.AppearanceTheme;
import dev.nextgram.plugin.v1.ui.IconRef;
import dev.nextgram.plugin.v1.ui.LocalizedText;
import dev.nextgram.plugin.v1.ui.SettingsEntry;

public final class MidnightPlugin extends AbstractNextGramPlugin {

    private AppearanceHost appearance;

    @Override
    public void onLoad(PluginContext context) {
        appearance = context.require(AppearanceHost.class);

        context.contributions().addSettingsEntry(
                SettingsEntry.builder("appearance")
                        .title(LocalizedText.of("Midnight"))
                        .subtitle(LocalizedText.of("Apply the Midnight palette"))
                        .icon(IconRef.asset("assets/icon.png"))
                        .action(ctx -> apply())
                        .build()
        );
    }

    @Override
    public void onStart() {
        if (!appearance.hasTheme()) {
            apply();
        }
    }

    private void apply() {
        appearance.applyTheme(
                AppearanceTheme.builder(AppearanceTheme.Base.DARK)
                        .color(AppearancePalette.WINDOW_BACKGROUND, 0xFF0E1117)
                        .color(AppearancePalette.WINDOW_BACKGROUND_GRAY, 0xFF0A0D12)
                        .color(AppearancePalette.ACTION_BAR_BACKGROUND, 0xFF0E1117)
                        .color(AppearancePalette.ACTION_BAR_TEXT, 0xFFF5F7FA)
                        .color(AppearancePalette.CHAT_BACKGROUND, 0xFF0A0D12)
                        .color(AppearancePalette.CHAT_BUBBLE_IN, 0xFF1A1F27)
                        .color(AppearancePalette.CHAT_BUBBLE_OUT, 0xFF2B5CFF)
                        .color(AppearancePalette.CHAT_BUBBLE_TEXT_IN, 0xFFF5F7FA)
                        .color(AppearancePalette.CHAT_BUBBLE_TEXT_OUT, 0xFFFFFFFF)
                        .color(AppearancePalette.TEXT_PRIMARY, 0xFFF5F7FA)
                        .color(AppearancePalette.TEXT_SECONDARY, 0xFF8B93A1)
                        .color(AppearancePalette.ACCENT, 0xFF6D8BFF)
                        .color(AppearancePalette.DIVIDER, 0xFF1F2630)
                        .color(AppearancePalette.LINK, 0xFF6D8BFF)
                        .color(AppearancePalette.BUTTON_BACKGROUND, 0xFF2B5CFF)
                        .color(AppearancePalette.BUTTON_TEXT, 0xFFFFFFFF)
                        .color(AppearancePalette.BADGE, 0xFFFF5C5C)
                        .color(AppearancePalette.DIALOG_BACKGROUND, 0xFF151A22)
                        .color(AppearancePalette.DIALOG_TEXT, 0xFFF5F7FA)
                        .rawColor("windowBackgroundWhite", 0xFF0E1117)
                        .rawColor("chat_inBubbleSelected", 0xFF222A36)
                        .customColor("surfaceRaised", 0xFF1B1E24)
                        .customColor("onSurfaceMuted", 0xFFA8B0BD)
                        .build()
        ).exceptionally(error -> null);
    }
}
```

The complete manifest adds `"permissions": ["ui.settings", "ui.appearance"]` and the
appearance icon.

## 12. Not in this milestone

- Font overrides.
- Wallpapers and chat backgrounds from assets.
- In-app icon packs and global drawable overrides.
- Layout-style overrides.
- Per-screen or per-chat theme isolation: an applied theme is global and tints every
  surface, including login, passcode and payment screens. Those surfaces never receive
  plugin views, contexts or data; see [security.md](/security/).
- Declarative theme packages, `theme/theme.json`, theme preview and a theme catalog.

Screen replacement and view-local styling are the supported way to redesign the app
beyond colors. See [screens.md](/screens/).
