From 8b7fa5ff5798e430d82239de680ed82fd0631065 Mon Sep 17 00:00:00 2001 From: cheb0chik Date: Mon, 2 Nov 2026 12:32:37 +0300 Subject: [PATCH] LihonT 2 Serena alpha Themes as data: the settings and the rest of TikTok take a look (Stickers, Windows 95, or a theme a plugin brings with the right ui.theme); the DEBUG recovery mode (Clear cache in Android resets the look and puts the plugins in safe mode); new plugin functions (name.style, confetti and buzz on a tap); a few memory trims in the chat bubbles; the person list for bubbles no longer shows screen labels. Co-Authored-By: Claude Sonnet 5.5 --- docs/plugins.md | 45 ++ plugins/lihont.fun-names/plugin.json | 19 + plugins/lihont.theme-sunset/plugin.json | 25 + plugins/lihont.theme-win95/plugin.json | 27 + scripts/make_ltp.py | 2 +- scripts/make_luna_cards.py | 29 + scripts/make_serena_promo.py | 364 +++++++++ scripts/stage_site.py | 1 + sdk/lihont-ltp/examples/07_theme.py | 9 + sdk/lihont-ltp/examples/08_fun.py | 10 + sdk/lihont-ltp/lihont_ltp/__init__.py | 5 +- sdk/lihont-ltp/lihont_ltp/core.py | 42 +- sdk/lihont-ltp/lihont_ltp/guard.py | 37 +- sdk/lihont-ltp/lihont_ltp/ru.py | 2 +- sdk/lihont-ltp/lihont_ltp/validate.py | 97 ++- skills/lihont-ltp/SKILL.md | 4 + src/lihont/two/bar/BarStyle.java | 2 + src/lihont/two/bar/NavPill.java | 9 +- src/lihont/two/bar/PlusPill.java | 7 +- src/lihont/two/bar/ProfileMenu.java | 2 +- src/lihont/two/chat/BubbleDrawable.java | 15 +- src/lihont/two/chat/BubbleStore.java | 38 +- src/lihont/two/chat/Bubbles.java | 18 +- src/lihont/two/comments/CommentPanel.java | 4 +- src/lihont/two/comments/Fill.java | 13 +- src/lihont/two/look/DebugMode.java | 99 +++ src/lihont/two/look/Windows.java | 2 + src/lihont/two/plugin/Act.java | 46 ++ src/lihont/two/plugin/Confetti.java | 90 +++ src/lihont/two/plugin/Defender.java | 28 + src/lihont/two/plugin/Evaluator.java | 1 + src/lihont/two/plugin/OverlaySpec.java | 6 +- src/lihont/two/plugin/Permission.java | 3 + src/lihont/two/plugin/Plugin.java | 23 +- src/lihont/two/plugin/PluginRegistry.java | 5 + src/lihont/two/plugin/PluginScreen.java | 8 + src/lihont/two/plugin/ThemeData.java | 149 ++++ src/lihont/two/profile/ProfilePanel.java | 6 +- src/lihont/two/profile/Tone.java | 13 +- src/lihont/two/settings/BevelDrawable.java | 63 ++ .../two/settings/LihonTSettingsActivity.java | 97 ++- src/lihont/two/settings/Md3.java | 65 +- src/lihont/two/settings/Md3Switch.java | 49 +- src/lihont/two/settings/PluginSettings.java | 2 +- src/lihont/two/settings/ThemeEngine.java | 122 +++ src/lihont/two/settings/ThemeSpec.java | 93 +++ src/web/assets/site/plugin_howto.svg | 10 + src/web/index.html | 695 ++++++++++-------- src/web/pay_index.html | 150 ++-- tests/java/lihont/two/plugin/PluginTest.java | 26 +- tests/test_debug_mode.py | 58 ++ tests/test_ltp_sdk.py | 73 +- tests/test_manifest_activity.py | 2 +- tests/test_plugins.py | 23 +- 54 files changed, 2392 insertions(+), 441 deletions(-) create mode 100644 plugins/lihont.fun-names/plugin.json create mode 100644 plugins/lihont.theme-sunset/plugin.json create mode 100644 plugins/lihont.theme-win95/plugin.json create mode 100644 scripts/make_luna_cards.py create mode 100644 scripts/make_serena_promo.py create mode 100644 sdk/lihont-ltp/examples/07_theme.py create mode 100644 sdk/lihont-ltp/examples/08_fun.py create mode 100644 src/lihont/two/look/DebugMode.java create mode 100644 src/lihont/two/plugin/Confetti.java create mode 100644 src/lihont/two/plugin/ThemeData.java create mode 100644 src/lihont/two/settings/BevelDrawable.java create mode 100644 src/lihont/two/settings/ThemeEngine.java create mode 100644 src/lihont/two/settings/ThemeSpec.java create mode 100644 src/web/assets/site/plugin_howto.svg create mode 100644 tests/test_debug_mode.py diff --git a/docs/plugins.md b/docs/plugins.md index 1d797bc..66abd28 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -80,6 +80,7 @@ python scripts/make_ltp.py plugins/my.plugin | `ui.sound` | Проигрывать звук плагина, когда вы нажимаете на его картинку. | | `feed.like` | Ставить лайк видео на главной ленте, когда вы нажимаете на картинку плагина. | | `net.download` | Скачивать картинки и звуки с сайтов, названных в `net` (см. ниже). Нужен ещё переключатель «Интернет» у плагина. | +| `ui.theme` | Менять оформление экранов мода и TikTok: цвета, формы, рамки (см. «Тема»). Ничего не скрывает и не двигает. | ## Правило @@ -199,6 +200,34 @@ python scripts/make_ltp.py plugins/my.plugin предупреждение, что сайт может его подменить. Вместо «Плагин не может: выходить в интернет» он пишет, что плагин ходит только на названные сайты и только за файлами. +## Тема (`theme`) + +Плагин с правом `ui.theme` может принести тему оформления. Это только цвета и несколько чисел, поэтому тема красит, но +не прячет и не двигает ничего на экране. Правила в таком плагине можно не писать вовсе. + +```json +"permissions": ["ui.theme"], +"theme": {"name": "Закат", "dark": true, "page": "#2b1d3a", "card": "#3d2b52", "text": "#fbe9ff", + "accent": "#ff8a5b", "on_accent": "#2b1d3a", "radius": 20, "outline": 2, "shadow": 4} +``` + +| Поле | Что это | +| --- | --- | +| `name` | Название темы, до 24 знаков (обязательно). | +| `page`, `card`, `text`, `accent` | Цвета страницы, карточек, текста и акцента (обязательно). Пишутся `#rrggbb` маленькими буквами. | +| `muted`, `on_accent`, `line`, `title_from`, `title_to` | Второй текст, текст на акценте (по умолчанию `#ffffff`), линии, начало и конец полосы заголовка. По умолчанию: `text`, `#ffffff`, `text`, `accent`, `accent`. | +| `dark` | Тёмная тема (`true`/`false`). | +| `radius` | Скругление углов, 0–40. 0 даёт квадратные углы везде. | +| `outline`, `shadow` | Толщина контура 0–6 и смещение жёсткой тени 0–12. | +| `bevel` | Объёмные рамки, как у окон Windows 95. | +| `tick_box` | Переключатели рисуются квадратной галочкой. | +| `title_bars` | Заголовки разделов становятся цветной полосой. | + +Защитник проверяет контраст текста на карточках и на акценте. Если он ниже 3.0, он честно напишет, что текст будет плохо +читаться, но тему не запретит. Если тема всё-таки сломала экран, вернуть вид можно режимом DEBUG (Настройки мода → +«Восстановление»): включите его заранее, потом очистите кэш приложения в настройках Android. Выбирается тема в настройках +мода, строка «Оформление». В SDK: `plugin.theme("Закат", page="#2b1d3a", card="#3d2b52", text="#fbe9ff", accent="#ff8a5b")`. + ## Как установить В настройках мода откройте раздел «Плагины» → «Установить плагин» → выберите `.ltp`. Мод покажет, кто автор, какие @@ -210,3 +239,19 @@ python scripts/make_ltp.py plugins/my.plugin Не читают чаты и личные данные, не запускают код, не пишут сообщения от вашего имени, не меняют файлы. В сеть выходит только плагин с правом `net.download`: он скачивает файлы с названных сайтов, когда вы включили ему интернет и подтвердили адрес, и ничего не отправляет. Картинка плагина может поставить лайк только вашим нажатием на неё и только на главной ленте. Если захочется такого, это будет отдельным правом, которое вы увидите и одобрите при установке. + +## Что плагинам закрыто навсегда + +Это не настройка, а граница формата. Права на это нет в списке, поэтому плагин не может его запросить, а файл, где такое +право названо, мод отклоняет как неизвестное. Если ограничение когда-нибудь пересматривать, то только отдельным решением, +которое видно в этом документе, а не тихим добавлением поля. + +- пароли, коды входа и данные для входа; +- токены, ключи и любые секреты приложения; +- **куки** и сохранённые сессии (по ним можно войти в аккаунт без пароля); +- тексты сообщений и содержимое чатов, комментариев и личных данных; +- запуск кода и изменение файлов. + +Что плагин видит сейчас: описание, хэштеги и автора видео, имена на экране и время. Любое новое поле данных появляется +только вместе с отдельным правом, которое защитник показывает, и с тестом, который проверяет, что в этом поле нет ничего +из списка выше. diff --git a/plugins/lihont.fun-names/plugin.json b/plugins/lihont.fun-names/plugin.json new file mode 100644 index 0000000..2a9185b --- /dev/null +++ b/plugins/lihont.fun-names/plugin.json @@ -0,0 +1,19 @@ +{ + "ltp": 1, + "id": "lihont.fun-names", + "name": "Весёлые имена", + "version": "1.0", + "author": "LihonT", + "description": "Твоё имя на твоём экране волной, а у друзей из списка с пробелами между буквами. Только у вас на экране.", + "license": "VCBFU-2", + "ai": ["Claude Sonnet 5.5 (Claude Code)"], + "permissions": ["names"], + "rules": [ + { + "title": "Моё имя волной", + "when": "name.show", + "if": {"uid": ["self"]}, + "do": [{"name.style": "wave"}] + } + ] +} diff --git a/plugins/lihont.theme-sunset/plugin.json b/plugins/lihont.theme-sunset/plugin.json new file mode 100644 index 0000000..f3da1e2 --- /dev/null +++ b/plugins/lihont.theme-sunset/plugin.json @@ -0,0 +1,25 @@ +{ + "ltp": 1, + "id": "lihont.theme-sunset", + "name": "Закат", + "version": "1.0", + "author": "LihonT", + "description": "Тёмно-лиловый фон, тёплый оранжевый акцент, толстые контуры и мягкие тени.", + "license": "VCBFU-2", + "ai": ["Claude Sonnet 5.5 (Claude Code)"], + "permissions": ["ui.theme"], + "theme": { + "name": "Закат", + "dark": true, + "page": "#2b1d3a", + "card": "#3d2b52", + "text": "#fbe9ff", + "muted": "#cdb4e0", + "accent": "#ff8a5b", + "on_accent": "#2b1d3a", + "line": "#fbe9ff", + "radius": 20, + "outline": 2, + "shadow": 4 + } +} diff --git a/plugins/lihont.theme-win95/plugin.json b/plugins/lihont.theme-win95/plugin.json new file mode 100644 index 0000000..d3dcfe3 --- /dev/null +++ b/plugins/lihont.theme-win95/plugin.json @@ -0,0 +1,27 @@ +{ + "ltp": 1, + "id": "lihont.theme-win95", + "name": "Windows 95", + "version": "1.0", + "author": "LihonT", + "description": "Серые окна на бирюзовом рабочем столе, объёмные рамки, синие заголовки и квадратные галочки.", + "license": "VCBFU-2", + "ai": ["Claude Sonnet 5.5 (Claude Code)"], + "permissions": ["ui.theme"], + "theme": { + "name": "Windows 95", + "page": "#008080", + "card": "#c0c0c0", + "text": "#000000", + "muted": "#404040", + "accent": "#000080", + "on_accent": "#ffffff", + "line": "#808080", + "title_from": "#000080", + "title_to": "#1084d0", + "radius": 0, + "bevel": true, + "tick_box": true, + "title_bars": true + } +} diff --git a/scripts/make_ltp.py b/scripts/make_ltp.py index 6840a3a..a5d091b 100644 --- a/scripts/make_ltp.py +++ b/scripts/make_ltp.py @@ -80,7 +80,7 @@ def main(argv) -> int: parser.add_argument("folders", nargs="*", help="plugin folders (default: every folder of plugins/)") parser.add_argument("-o", "--out", default=str(ROOT / "ComplectAPK" / "plugins")) args = parser.parse_args(argv) - folders = [Path(f) for f in args.folders] or sorted(p for p in (ROOT / "plugins").iterdir() if p.is_dir()) + folders = [Path(f) for f in args.folders] or sorted(p for p in (ROOT / "plugins").iterdir() if p.is_dir() and (p / "plugin.json").is_file()) for folder in folders: out = pack(folder, Path(args.out)) print("%s %d bytes" % (out, out.stat().st_size)) diff --git a/scripts/make_luna_cards.py b/scripts/make_luna_cards.py new file mode 100644 index 0000000..6f49ac1 --- /dev/null +++ b/scripts/make_luna_cards.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Cards for the Telegram post about LihonT 2 Luna: the settled frames of the sticker-style promo video +(make_luna_promo2.py), 1080x1920, one per scene, no screenshots. + +usage: py -X utf8 -B scripts/make_luna_cards.py # writes work/luna-cards/card_01.png ... +""" +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import make_luna_promo2 as V # noqa: E402 + +OUT = V.ROOT / "work" / "luna-cards" +# the moment of each scene when everything has landed and nothing is half-way +MOMENTS = [("intro", 2.9), ("flame", 7.4), ("keeper", 12.2), ("bubbles", 17.4), ("ghost", 21.8), + ("photos", 26.4), ("plugins", 31.4), ("shapes", 35.4), ("settings", 40.0), ("outro", 44.2)] + + +def main() -> None: + OUT.mkdir(parents=True, exist_ok=True) + for n, (name, t) in enumerate(MOMENTS, 1): + path = OUT / ("card_%02d_%s.png" % (n, name)) + V.frame_at(t).convert("RGB").save(path) + print(path.name) + + +if __name__ == "__main__": + main() diff --git a/scripts/make_serena_promo.py b/scripts/make_serena_promo.py new file mode 100644 index 0000000..ccb03a9 --- /dev/null +++ b/scripts/make_serena_promo.py @@ -0,0 +1,364 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +LihonT 2 «Serena alpha» promo in the sticker style of make_luna_promo2.py: 1080x1920, 30 fps, about 36 seconds. + +Everything is drawn here (no screenshots): the settings card that changes theme, the Windows 95 windows, the plugin code that +types itself, the wave name, the confetti and the recovery mode. The look helpers come from make_luna_promo2.py. + +usage (from the repository root): + py -X utf8 -B scripts/make_serena_promo.py # work/serena-promo/serena_promo.mp4 + py -X utf8 -B scripts/make_serena_promo.py --still 9.0 # one frame +""" + +from __future__ import annotations + +import argparse +import math +import shutil +import subprocess +import sys +from multiprocessing import Pool +from pathlib import Path + +from PIL import Image, ImageDraw + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import make_luna_promo2 as V # noqa: E402 +import make_lihont_promo as P # noqa: E402 + +W, H, FPS = V.W, V.H, V.FPS +ROOT = V.ROOT +OUT = ROOT / "work" / "serena-promo" / "serena_promo.mp4" +AUDIO = ROOT / "work" / "serena-promo" / "serena_audio.wav" +INK, CREAM, CORAL, YELLOW, MINT, VIOLET, SKY, PINK, WHITE = V.INK, V.CREAM, V.CORAL, V.YELLOW, V.MINT, V.VIOLET, V.SKY, V.PINK, V.WHITE +clamp, ease_out_cubic, ease_out_back, pop = V.clamp, V.ease_out_cubic, V.ease_out_back, V.pop + +SCENES = [ + ("intro", 0.0, 3.6, CREAM), + ("themes", 3.6, 9.6, (255, 226, 200)), + ("win95", 9.6, 14.4, (0, 128, 128)), + ("plugin", 14.4, 20.4, (255, 236, 150)), + ("fun", 20.4, 25.6, (215, 200, 255)), + ("debug", 25.6, 31.0, (190, 240, 220)), + ("outro", 31.0, 35.4, (255, 196, 176)), +] +DURATION = SCENES[-1][2] +FRAMES = int(round(DURATION * FPS)) +WIPE = V.WIPE + +# the looks a settings card can have: (page, card, ink, radius, outline, shadow, bevel, tick box, title bars, accent, on accent) +LOOKS = { + "md3": dict(page=(254, 247, 255), card=(243, 237, 247), ink=(29, 27, 32), radius=34, outline=0, shadow=0, bevel=False, + tick=False, bars=False, accent=(103, 80, 164), on=(255, 255, 255), name="Material 3"), + "sticker": dict(page=(255, 244, 224), card=(255, 255, 255), ink=INK, radius=30, outline=6, shadow=10, bevel=False, + tick=False, bars=False, accent=VIOLET, on=WHITE, name="Стикеры"), + "win95": dict(page=(0, 128, 128), card=(192, 192, 192), ink=(0, 0, 0), radius=0, outline=0, shadow=0, bevel=True, + tick=True, bars=True, accent=(0, 0, 128), on=WHITE, name="Windows 95"), + "sunset": dict(page=(43, 29, 58), card=(61, 43, 82), ink=(251, 233, 255), radius=34, outline=5, shadow=8, bevel=False, + tick=False, bars=False, accent=(255, 138, 91), on=(43, 29, 58), name="Закат (плагин)"), +} + + +def bevel(d, box, raised=True, edge=3, face=(192, 192, 192)): + x0, y0, x1, y1 = [int(v) for v in box] + d.rectangle([x0, y0, x1, y1], fill=face + (255,)) + light, mid, dark, black = (255, 255, 255), (223, 223, 223), (128, 128, 128), (0, 0, 0) + tl1, br1, tl2, br2 = (light, black, mid, dark) if raised else (dark, light, black, mid) + for k, (tl, br) in enumerate(((tl1, br1), (tl2, br2))): + o = k * edge + d.rectangle([x0 + o, y0 + o, x1 - o - edge, y0 + o + edge - 1], fill=tl + (255,)) + d.rectangle([x0 + o, y0 + o, x0 + o + edge - 1, y1 - o - edge], fill=tl + (255,)) + d.rectangle([x0 + o + edge, y1 - o - edge + 1, x1 - o, y1 - o], fill=br + (255,)) + d.rectangle([x1 - o - edge + 1, y0 + o + edge, x1 - o, y1 - o], fill=br + (255,)) + + +def settings_card(layer, look, box, lt=0.0, rows=None): + """A mock of the mod's settings screen in a given look: a page, a title strip and four rows with switches.""" + L = LOOKS[look] if isinstance(look, str) else look + x0, y0, x1, y1 = box + d = ImageDraw.Draw(layer, "RGBA") + d.rectangle([x0 - 30, y0 - 30, x1 + 30, y1 + 30], fill=L["page"] + (255,)) + inner = (x0, y0 + 70, x1 - L["shadow"], y1 - L["shadow"]) + if L["shadow"]: + d.rounded_rectangle([inner[0] + L["shadow"], inner[1] + L["shadow"], inner[2] + L["shadow"], inner[3] + L["shadow"]], + radius=L["radius"], fill=(0, 0, 0, 255) if look == "sunset" else INK + (255,)) + if L["bevel"]: + bevel(d, inner, True) + else: + d.rounded_rectangle(inner, radius=L["radius"], fill=L["card"] + (255,), + outline=L["ink"] + (255,) if L["outline"] else None, width=L["outline"] or 0) + # section title + if L["bars"]: + for i in range(x1 - x0): + k = i / max(1, x1 - x0) + d.line([(x0 + i, y0 + 8), (x0 + i, y0 + 62)], fill=(int(0 + 16 * k), int(0 + 132 * k), int(128 + 80 * k), 255)) + P.draw_text(layer, (x0 + 24, y0 + 35), "Функции", 36, L["on"] + (255,), anchor="lm") + else: + P.draw_text(layer, (x0 + 28, y0 + 35), "Функции", 38, (L["accent"] if look != "sticker" else L["ink"]) + (255,), anchor="lm") + names = rows or ["Призрак: истории", "Свои пузыри", "Несколько фото", "Автопродление"] + step = (inner[3] - inner[1]) / len(names) + for n, text in enumerate(names): + cy = inner[1] + step * (n + 0.5) + P.draw_text(layer, (x0 + 40, cy), text, 40, L["ink"] + (255,), anchor="lm") + on = clamp((lt - 0.2 - n * 0.25) / 0.3) if lt >= 0 else 1.0 + cx = x1 - 90 - L["shadow"] + if L["tick"]: + bevel(d, (cx - 24, cy - 24, cx + 24, cy + 24), False, 3, (255, 255, 255)) + if on > 0.5: + d.line([(cx - 13, cy), (cx - 4, cy + 11), (cx + 14, cy - 12)], fill=(0, 0, 0, 255), width=7) + else: + track = tuple(int(L["card"][i] * (1 - on) + L["accent"][i] * on) for i in range(3)) + d.rounded_rectangle([cx - 56, cy - 30, cx + 56, cy + 30], radius=30, fill=track + (255,), outline=L["ink"] + (255,), + width=4 if L["outline"] else 2) + kx = cx - 26 + 52 * on + d.ellipse([kx - 20, cy - 20, kx + 20, cy + 20], fill=(L["on"] if on > 0.5 else L["ink"]) + (255,)) + + +def scene_intro(layer, lt): + k = ease_out_back(lt / 0.9) + V.place(layer, V.ASSETS["logo"], W / 2, 760, 0.5 * k * (1 + 0.04 * math.sin(lt * 5)), math.sin(lt * 2.4) * 8 + (1 - k) * 360) + V.burst(layer, W / 2, 760, lt, 0.6, seed=14) + V.title(layer, max(0.0, lt - 0.9), "LihonT 2", "Serena alpha", y=1230) + V.label(layer, W / 2, 1480, "темы · приколы · восстановление", pop(lt, 1.8), size=44, fill=YELLOW) + + +def scene_themes(layer, lt): + V.title(layer, lt, "Темы оформления", "Выбери вид, как хочешь") + order = ["md3", "sticker", "win95"] + idx = min(len(order) - 1, int(lt / 1.55)) + part = (lt % 1.55) / 1.55 + look = order[idx] + settings_card(layer, look, (150, 620, 930, 1240), lt=lt - idx * 1.55) + # the name of the look flies in on a sticker + V.label(layer, W / 2, 1400, LOOKS[look]["name"], pop(part, 0.0, 0.4), size=64, fill=YELLOW) + for n, key in enumerate(order): + V.label(layer, 220 + n * 320, 1560, LOOKS[key]["name"], pop(lt, 4.2 + n * 0.2), size=32, + fill=WHITE if key != look else MINT) + V.label(layer, W / 2, 1700, "И свои темы из плагинов", pop(lt, 4.8), size=40, fill=PINK) + if part < 0.08: + V.ring(layer, W / 2, 930, part, 0.0, color=INK, size=420) + + +def scene_win95(layer, lt): + d = ImageDraw.Draw(layer, "RGBA") + P.draw_text(layer, (W / 2, 190), "Windows 95 везде", 100, WHITE + (255,)) + P.draw_text(layer, (W / 2, 290), "не только в настройках", 46, (230, 255, 255, 255), bold=False) + # a phone-ish screen: windows with navy title bars + px0, py0, px1, py1 = 170, 400, 910, 1700 + d.rectangle([px0 - 14, py0 - 14, px1 + 14, py1 + 14], fill=(20, 20, 20, 255)) + d.rectangle([px0, py0, px1, py1], fill=(0, 128, 128, 255)) + for n, (title, lines) in enumerate((("Комментарии", ["anna: смотрите, вайб!", "luna: нашёл своих"]), + ("Профиль", ["подписчики: 5 095", "лайки: 21,2 тыс."]))): + k = ease_out_back((lt - 0.3 - n * 0.4) / 0.5) + if k <= 0.02: + continue + y0 = py0 + 50 + n * 480 + (1 - k) * 300 + bevel(d, (px0 + 40, y0, px1 - 40, y0 + 420), True, 4) + for i in range(px1 - px0 - 100): + kk = i / max(1, px1 - px0 - 100) + d.line([(px0 + 52 + i, y0 + 12), (px0 + 52 + i, y0 + 62)], fill=(int(16 * kk), int(132 * kk), int(128 + 80 * kk), 255)) + P.draw_text(layer, (px0 + 70, y0 + 38), title, 36, WHITE + (255,), anchor="lm") + bevel(d, (px1 - 130, y0 + 16, px1 - 100, y0 + 58), True, 2) + for i, text in enumerate(lines): + bevel(d, (px0 + 66, y0 + 96 + i * 150, px1 - 66, y0 + 216 + i * 150), False, 3, (255, 255, 255)) + P.draw_text(layer, (px0 + 90, y0 + 156 + i * 150), text, 34, (0, 0, 0, 255), anchor="lm") + # the bottom bar: square tabs, the chosen one pressed in + by = py1 - 170 + bevel(d, (px0, by, px1, py1), True, 4) + for i in range(5): + x = px0 + 20 + i * 140 + pressed = i == 1 + bevel(d, (x, by + 22, x + 120, by + 130), not pressed, 3) + d.rectangle([x + 40, by + 52, x + 80, by + 92], outline=(0, 0, 0, 255), width=5) + V.label(layer, W / 2, 1810, "Панель, комментарии, профиль, меню", pop(lt, 1.8), size=36, fill=YELLOW) + + +TYPED = [ + 'plugin = Plugin("Закат", author="Вася")', + "plugin.theme(", + ' page="#2b1d3a", card="#3d2b52",', + ' text="#fbe9ff", accent="#ff8a5b",', + " radius=20, outline=2, shadow=4)", + "plugin.save()", +] + + +def scene_plugin(layer, lt): + V.title(layer, lt, "Тема из плагина", "Пять строк на Python") + d = ImageDraw.Draw(layer, "RGBA") + box = (90, 470, 990, 1010) + d.rounded_rectangle([box[0] + 10, box[1] + 10, box[2] + 10, box[3] + 10], radius=36, fill=INK + (255,)) + d.rounded_rectangle(box, radius=36, fill=(34, 28, 46, 255), outline=INK + (255,), width=6) + for i, c in enumerate((CORAL, YELLOW, MINT)): + d.ellipse([130 + i * 44, 505, 160 + i * 44, 535], fill=c + (255,)) + total = sum(len(t) + 1 for t in TYPED) + shown = int(clamp((lt - 0.5) / 3.0) * total) + y = 580 + for line in TYPED: + part = line[:max(0, shown)] + shown -= len(line) + 1 + color = (255, 205, 60, 255) if line.startswith("plugin.") else (251, 233, 255, 255) + P.draw_text(layer, (130, y), part, 36, color, bold=False, anchor="lm") + y += 64 + if shown < 0: + break + # the result appears as a card in the new theme + k = pop(lt, 3.8, 0.6) + if k > 0.02: + V.place(layer, _card_image("sunset", 780, 520), W / 2, 1380 + (1 - k) * 200, 0.85 * k) + V.label(layer, W / 2, 1720, "Защитник проверит контраст", pop(lt, 4.4), size=36, fill=WHITE) + + +_cache = {} + + +def _card_image(look, w, h): + key = (look, w, h) + if key not in _cache: + img = Image.new("RGBA", (w + 80, h + 80), (0, 0, 0, 0)) + settings_card(img, look, (40, 40, 40 + w, 40 + h), lt=-1) + _cache[key] = img + return _cache[key] + + +def scene_fun(layer, lt): + V.title(layer, lt, "Приколы", "Имя, конфетти, вибрация") + d = ImageDraw.Draw(layer, "RGBA") + # a name that turns into a wave, letter by letter + word = "Привет, мир" + f = P.font(110) + total = d.textlength(word, font=f) + x = W / 2 - total / 2 + done = int(clamp((lt - 0.6) / 1.4) * len(word)) + for n, ch in enumerate(word): + shown = ch.upper() if (n % 2 == 1 and n < done) else ch.lower() + w = d.textlength(ch, font=f) + bob = math.sin(lt * 5 + n * 0.7) * 10 if n < done else 0 + P.draw_text(layer, (x + w / 2, 700 + bob), shown, 110, INK + (255,)) + x += w + V.label(layer, W / 2, 840, "name.style: wave", pop(lt, 1.0), size=40, fill=YELLOW) + # a star sticker that is tapped and throws confetti + cx, cy = W / 2, 1230 + k = pop(lt, 2.4) + pts = [] + for i in range(10): + r = 130 if i % 2 == 0 else 58 + a = -math.pi / 2 + i * math.pi / 5 + pts.append((cx + math.cos(a) * r * k, cy + math.sin(a) * r * k)) + if k > 0.02: + d.polygon([(x + 8, y + 8) for x, y in pts], fill=INK + (255,)) + d.polygon(pts, fill=YELLOW + (255,), outline=INK + (255,)) + d.line(pts + [pts[0]], fill=INK + (255,), width=6) + tap = 3.4 + if lt > tap: + V.burst(layer, cx, cy, lt, tap, seed=3, count=60, power=1100) + V.ring(layer, cx, cy, lt, tap, color=INK, size=260) + for i in range(3): # little buzz marks beside the star + off = 170 + i * 26 + a = int(255 * clamp(1 - (lt - tap) / 0.8)) + d.arc([cx - off, cy - off, cx + off, cy + off], 150, 210, fill=INK + (a,), width=6) + d.arc([cx - off, cy - off, cx + off, cy + off], -30, 30, fill=INK + (a,), width=6) + V.label(layer, W / 2, 1480, "tap: confetti + buzz", pop(lt, 2.8), size=40, fill=PINK) + V.label(layer, W / 2, 1620, "Всё безопасно: только у вас на экране", pop(lt, 3.6), size=34, fill=WHITE) + + +def scene_debug(layer, lt): + V.title(layer, lt, "Режим DEBUG", "Если тема всё сломала") + d = ImageDraw.Draw(layer, "RGBA") + # the switch + V.sticker(layer, (110, 480, 970, 640), WHITE, radius=44) + P.draw_text(layer, (160, 560), "Режим DEBUG", 48, INK + (255,), anchor="lm") + V.switch(layer, 850, 560, ease_out_cubic((lt - 0.6) / 0.4)) + # Android: Clear cache + pressed = clamp((lt - 2.2) / 0.3) + V.sticker(layer, (110, 740, 970, 900), (230, 230, 240), radius=44, shadow=int(10 * (1 - pressed))) + P.draw_text(layer, (160, 820), "Android → TikTok → Очистить кэш", 38, INK + (255,), anchor="lm") + d.ellipse([850 - 36, 820 - 36, 850 + 36, 820 + 36], fill=CORAL + (255,), outline=INK + (255,), width=5) + # the card: Windows 95 for a moment, then back to Material 3 with a burst + back = lt > 3.0 + look = "md3" if back else "win95" + if lt > 1.0: + settings_card(layer, look, (150, 1030, 930, 1560), lt=-1) + if back: + V.burst(layer, W / 2, 1300, lt, 3.0, seed=9, count=50, power=900) + V.ring(layer, W / 2, 1300, lt, 3.0, color=INK, size=380) + V.label(layer, W / 2, 1690, "Оформление и плагины сброшены", pop(lt, 3.3), size=38, fill=YELLOW) + V.label(layer, W / 2, 1790, "Файлы плагинов остаются", pop(lt, 3.8), size=34, fill=WHITE) + + +def scene_outro(layer, lt): + k = ease_out_back(lt / 0.8) + V.place(layer, V.ASSETS["logo"], W / 2, 620, 0.46 * k * (1 + 0.04 * math.sin(lt * 5)), math.sin(lt * 2.4) * 8 + (1 - k) * 300) + V.burst(layer, W / 2, 620, lt, 0.5, seed=19, count=60, power=1000) + V.title(layer, max(0.0, lt - 0.5), "Serena alpha", "Открытый код · лицензия VCBFU v2", y=1000) + bounce = lambda t0: abs(math.sin((lt - t0) * 3)) * 14 if lt > t0 else 0 # noqa: E731 + V.label(layer, W / 2, 1290 - bounce(1.2), "git.lihont.space", pop(lt, 1.2), size=60, fill=YELLOW) + V.label(layer, W / 2, 1440 - bounce(1.5), "Telegram · @lihont", pop(lt, 1.5), size=60, fill=WHITE) + V.label(layer, W / 2, 1580, "Это альфа: может быть шероховато", pop(lt, 2.2), size=34, fill=PINK) + + +SCENE_DRAW = {name: globals()["scene_" + name] for name, _, _, _ in SCENES} + + +def frame_at(t: float) -> Image.Image: + V.init_assets() + index = 0 + for n, (name, start, end, color) in enumerate(SCENES): + if t >= start: + index = n + name, start, end, color = SCENES[index] + img = Image.new("RGBA", (W, H), color + (255,)) + if index > 0 and t - start < WIPE: + prev = SCENES[index - 1][3] + img = Image.new("RGBA", (W, H), prev + (255,)) + r = 1700 * ease_out_cubic((t - start) / WIPE) + mask = Image.new("L", (W, H), 0) + ImageDraw.Draw(mask).ellipse([W / 2 - r, H / 2 - r, W / 2 + r, H / 2 + r], fill=255) + img.paste(Image.new("RGBA", (W, H), color + (255,)), (0, 0), mask) + if name != "win95": + ox, oy = int(t * 30) % 80, int(t * 18) % 80 + img.alpha_composite(V.ASSETS["dots"], (-ox, -oy)) + layer = Image.new("RGBA", (W, H), (0, 0, 0, 0)) + SCENE_DRAW[name](layer, t - start) + out = clamp((end - t) / 0.25) if index < len(SCENES) - 1 else 1.0 + if out < 1.0: + layer.putalpha(layer.getchannel("A").point(lambda v, a=out: int(v * a))) + img.alpha_composite(layer) + return img + + +def render_frame(index: int) -> bytes: + return frame_at(index / FPS).convert("RGB").tobytes() + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--still", type=float) + parser.add_argument("--out", default=str(OUT)) + parser.add_argument("--jobs", type=int, default=6) + args = parser.parse_args() + OUT.parent.mkdir(parents=True, exist_ok=True) + if args.still is not None: + path = OUT.parent / ("still_%.2f.png" % args.still) + frame_at(args.still).convert("RGB").save(path) + print(path) + return + import make_lihont_music + make_lihont_music.generate(AUDIO, DURATION, tuple(s[1] for s in SCENES[1:])) + command = [shutil.which("ffmpeg") or "ffmpeg", "-y", "-loglevel", "error", "-f", "rawvideo", "-pix_fmt", "rgb24", + "-s", "%dx%d" % (W, H), "-r", str(FPS), "-i", "-", "-i", str(AUDIO), "-c:v", "libx264", "-preset", "medium", + "-crf", "18", "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "160k", "-shortest", args.out] + proc = subprocess.Popen(command, stdin=subprocess.PIPE) + with Pool(args.jobs, initializer=V.init_assets) as pool: + for n, data in enumerate(pool.imap(render_frame, range(FRAMES), chunksize=4)): + proc.stdin.write(data) + if n % 60 == 0: + print("frame %d/%d" % (n, FRAMES), flush=True) + proc.stdin.close() + proc.wait() + print("done:", args.out) + + +if __name__ == "__main__": + main() diff --git a/scripts/stage_site.py b/scripts/stage_site.py index aefe266..3e1cd07 100644 --- a/scripts/stage_site.py +++ b/scripts/stage_site.py @@ -27,6 +27,7 @@ PAYLOAD = [ ("src/web/assets/site/md3.css", "assets/site/md3.css"), ("src/web/assets/site/md3.js", "assets/site/md3.js"), ("src/web/assets/site/icons.svg", "assets/site/icons.svg"), + ("src/web/assets/site/plugin_howto.svg", "assets/site/plugin_howto.svg"), ] diff --git a/sdk/lihont-ltp/examples/07_theme.py b/sdk/lihont-ltp/examples/07_theme.py new file mode 100644 index 0000000..731eea2 --- /dev/null +++ b/sdk/lihont-ltp/examples/07_theme.py @@ -0,0 +1,9 @@ +# Пример 7: тема оформления. Тема только красит экраны мода и TikTok: она ничего не прячет и не двигает. +from lihont_ltp import * + +plugin = Plugin("Закат", author="Вася", description="Тёмно-лиловый фон и тёплый акцент", license="MIT") + +plugin.theme("Закат", page="#2b1d3a", card="#3d2b52", text="#fbe9ff", accent="#ff8a5b", + on_accent="#2b1d3a", dark=True, radius=20, outline=2, shadow=4) + +plugin.save() diff --git a/sdk/lihont-ltp/examples/08_fun.py b/sdk/lihont-ltp/examples/08_fun.py new file mode 100644 index 0000000..5aefaf1 --- /dev/null +++ b/sdk/lihont-ltp/examples/08_fun.py @@ -0,0 +1,10 @@ +# Пример 8: приколы. Твоё имя волной (только у тебя на экране) и картинка, которая сыплет конфетти и жужжит по нажатию. +from lihont_ltp import * + +plugin = Plugin("Приколы", author="Вася", description="Имя волной и конфетти из картинки", license="MIT") + +plugin.name(me, style("wave"), title="Моё имя волной") +plugin.screen(picture("star.png", size=100, right=16, bottom=120, on_tap=[wiggle, confetti, buzz]), + title="Звезда с конфетти") + +plugin.save() diff --git a/sdk/lihont-ltp/lihont_ltp/__init__.py b/sdk/lihont-ltp/lihont_ltp/__init__.py index 540eaa5..4b1163f 100644 --- a/sdk/lihont-ltp/lihont_ltp/__init__.py +++ b/sdk/lihont-ltp/lihont_ltp/__init__.py @@ -9,7 +9,7 @@ from .core import (Plugin, account, after, all_of, always, any_of, author, before, between, bounce, day, download, evening, friday, hashtag, hide, like, me, morning, night, person, picture, rename, say, sound, wander, weekday, - weekend, wiggle, word) + weekend, wiggle, word, style, confetti, buzz) from .errors import LtpError __version__ = "0.1.0" @@ -18,5 +18,6 @@ __all__ = [ "Plugin", "LtpError", "word", "hashtag", "author", "person", "account", "between", "weekday", "all_of", "any_of", "me", "always", "morning", "day", "evening", "night", "friday", "weekend", - "hide", "say", "before", "after", "rename", "picture", "sound", "like", "wiggle", "download", "bounce", "wander", + "hide", "say", "before", "after", "rename", "style", "picture", "sound", "like", "wiggle", "confetti", "buzz", + "download", "bounce", "wander", ] diff --git a/sdk/lihont-ltp/lihont_ltp/core.py b/sdk/lihont-ltp/lihont_ltp/core.py index 52091e7..b1e9f2d 100644 --- a/sdk/lihont-ltp/lihont_ltp/core.py +++ b/sdk/lihont-ltp/lihont_ltp/core.py @@ -219,6 +219,8 @@ class Tap: hide = Action("feed.hide", True, "hide") wiggle = Tap("animate") like = Tap("like") +confetti = Tap("confetti") +buzz = Tap("buzz") def say(text): @@ -241,6 +243,12 @@ def rename(text): return Action("name.replace", text, "rename") +def style(kind): + """Вид имени на твоём экране: style("upper") — ЗАГЛАВНЫМИ, "lower" — строчными, "reverse" — наоборот, + "wave" — пРиВеТ, "spaced" — п р и в е т. Только у тебя на экране; лучше с условием (me, person(...)).""" + return Action("name.style", kind, "style") + + def sound(file): """Играть звук при нажатии на картинку: picture("cat.gif", on_tap=[sound("meow.ogg")]).""" return Tap("sound", file) @@ -275,7 +283,7 @@ def picture(file, size=140, right=16, bottom=16, opacity=100, movable=True, on_t walk=None): """Картинка в углу приложения. Файл лежит рядом со скриптом (png, gif или webp). - on_tap=[wiggle, sound("мяу.ogg"), like] — что делать, когда на неё нажали. + on_tap=[wiggle, sound("мяу.ogg"), like] — что делать, когда на неё нажали (ещё confetti — конфетти и buzz — вибрация). pet="погладили.gif" — вторая картинка, когда водишь пальцем по верхней половине. walk=bounce(speed=40) или wander() — картинка сама ходит по экрану (двигать её пальцем тогда нельзя). """ @@ -284,7 +292,7 @@ def picture(file, size=140, right=16, bottom=16, opacity=100, movable=True, on_t keys = [] for tap in taps: if not isinstance(tap, Tap): - raise LtpError("picture(..., on_tap=[...]): внутри можно wiggle, sound(\"файл.ogg\") и like") + raise LtpError("picture(..., on_tap=[...]): внутри можно wiggle, sound(\"файл.ogg\"), like, confetti и buzz") keys.append(tap.key) if tap.sound_file: sound_file = tap.sound_file @@ -343,6 +351,7 @@ class Plugin: self.icon = icon self.id = id or "%s.%s" % (_slug(author) or "me", _slug(name) or "plugin") self._rules = [] + self._theme = None self._base = _caller_folder() # правила ---------------------------------------------------------------------------------------------------- @@ -361,6 +370,28 @@ class Plugin: actions = actions[1:] return self._add("screen", "screen.show", when, actions, title, limit) + def theme(self, name=None, *, page, card, text, accent, muted=None, on_accent=None, line=None, title_from=None, + title_to=None, dark=False, radius=None, outline=None, shadow=None, bevel=False, tick_box=False, + title_bars=False): + """Тема оформления: цвета и пара чисел. Тема только красит: она ничего не прячет и не двигает. + + plugin.theme("Закат", page="#2b1d3a", card="#3d2b52", text="#fbe9ff", accent="#ff8a5b", radius=20) + + Цвета пишутся как #rrggbb маленькими буквами. radius 0–40, outline 0–6, shadow 0–12. + bevel даёт объёмные рамки (как Windows 95), tick_box рисует переключатель галочкой, title_bars делает + заголовки разделов полосой. + """ + theme = {"name": name or self.title, "page": page, "card": card, "text": text, "accent": accent} + for key, value in (("muted", muted), ("on_accent", on_accent), ("line", line), ("title_from", title_from), + ("title_to", title_to), ("radius", radius), ("outline", outline), ("shadow", shadow)): + if value is not None: + theme[key] = value + for key, value in (("dark", dark), ("bevel", bevel), ("tick_box", tick_box), ("title_bars", title_bars)): + if value: + theme[key] = True + self._theme = theme + return self + def _add(self, kind, trigger, when, actions, title, limit): if isinstance(when, Action): # забыли условие: plugin.video(hide) значит «всегда» actions = (when,) + tuple(actions) @@ -404,6 +435,8 @@ class Plugin: manifest["license"] = self.license if self.ai: manifest["ai"] = self.ai + if self._theme is not None: + rights.append("ui.theme") manifest["permissions"] = rights if "net.download" in rights: # сайты берутся из адресов скачиваний: писать их отдельно не нужно @@ -416,7 +449,10 @@ class Plugin: if host and host not in hosts: hosts.append(host) manifest["net"] = {"hosts": hosts} - manifest["rules"] = rules + if self._theme is not None: + manifest["theme"] = self._theme + if rules or self._theme is None: + manifest["rules"] = rules if not self.description: del manifest["description"] return manifest diff --git a/sdk/lihont-ltp/lihont_ltp/guard.py b/sdk/lihont-ltp/lihont_ltp/guard.py index 1740de8..710117d 100644 --- a/sdk/lihont-ltp/lihont_ltp/guard.py +++ b/sdk/lihont-ltp/lihont_ltp/guard.py @@ -4,6 +4,8 @@ Тест репозитория сравнивает его вывод с настоящим Java-защитником на всех готовых плагинах, так что они совпадают. """ +from . import validate + CALM = 0 WATCH = 1 CAREFUL = 2 @@ -15,6 +17,8 @@ CANNOT_NET = ("Плагин не может: ходить куда-либо, к "и только после вашего подтверждения.") DEFAULT_LIMIT = 3 +STYLE_WORDS = {"upper": "заглавными буквами", "lower": "строчными буквами", "reverse": "задом наперёд", + "wave": "волной (пРиВеТ)", "spaced": "с пробелами между буквами"} DAYS = ["", "пн", "вт", "ср", "чт", "пт", "сб", "вс"] @@ -89,6 +93,8 @@ def says_action(action): return "дописать «%s» после имени" % value if key == "name.replace": return "показать вместо имени «%s»" % value + if key == "name.style": + return "показывать имя " + STYLE_WORDS[value] if key == "notice": return "показать подсказку «%s»" % value if key == "download": @@ -106,6 +112,10 @@ def says_action(action): taps.append("звук") if "like" in spec["tap"]: taps.append("лайк видео") + if "confetti" in spec["tap"]: + taps.append("конфетти") + if "buzz" in spec["tap"]: + taps.append("вибрация") if taps: out += "; по нажатию: " + ", ".join(taps) if spec["pet"]: @@ -168,6 +178,10 @@ class Report: return out + "\n" + (CANNOT_NET if self.net else CANNOT) +def _tenths(value): + return "%d.%d" % (value // 10, value % 10) + + def check(manifest, asset_names=()): careful, watch, calm, rules, seen = [], [], [], [], set() @@ -177,7 +191,7 @@ def check(manifest, asset_names=()): seen.add(key) return True - for index, rule in enumerate(manifest["rules"]): + for index, rule in enumerate(manifest.get("rules", [])): title = _title(rule, index) rules.append("%s: %s" % (title, says_rule(rule))) cond = rule.get("if") @@ -203,6 +217,12 @@ def check(manifest, asset_names=()): elif key in ("name.prefix", "name.suffix"): if once("affix"): calm.append("Дописывает текст к именам, только на вашем экране.") + elif key == "name.style": + if not picks: + watch.append("Правило «%s» меняет вид всех имён на экране (%s): читать их труднее." + % (title, STYLE_WORDS[value])) + elif once("style"): + calm.append("Меняет вид имён у выбранных аккаунтов, только на вашем экране.") elif key == "notice": if limit > 10 and once("notice"): watch.append("Показывает подсказки до %d раз в день." % limit) @@ -229,11 +249,26 @@ def check(manifest, asset_names=()): "она закрывает часть экрана." % spec["image"]) elif spec["size"] >= 300 and once("big"): watch.append("Большая картинка закрывает часть экрана.") + if ("confetti" in spec["tap"] or "buzz" in spec["tap"]) and once("fun"): + calm.append("Конфетти или лёгкая вибрация по нажатию на картинку.") if "sound" in spec["tap"] and once("sound"): watch.append("Играет звук, когда вы нажимаете на картинку.") if "like" in spec["tap"] and once("like"): careful.append("Ставит лайк видео на главной ленте, когда вы нажимаете на картинку плагина. " "Это действие аккаунта: случайное нажатие тоже поставит лайк.") + theme = manifest.get("theme") + if theme is not None: + rules.append("Тема «%s»: меняет цвета и вид экранов мода и TikTok" % theme["name"].strip()) + calm.append("Меняет оформление: цвета, формы и рамки. Ничего не скрывает и не двигает. " + "Вернуть как было можно в «Оформление» или режимом DEBUG.") + text, card, accent, on_accent = validate.theme_values(theme) + text_tenths = validate.contrast_tenths(text, card) + if text_tenths < 30: + watch.append("Текст на карточках темы плохо читается: контраст %s при нужных 3.0." % _tenths(text_tenths)) + accent_tenths = validate.contrast_tenths(on_accent, accent) + if accent_tenths < 30: + watch.append("Текст на кнопках и заголовках темы плохо читается: контраст %s при нужных 3.0." + % _tenths(accent_tenths)) if asset_names: calm.append("Файлов внутри: %d. Тип каждого проверен по первым байтам, они входят в хэш." % len(set(asset_names))) if not (manifest.get("license") or "").strip(): diff --git a/sdk/lihont-ltp/lihont_ltp/ru.py b/sdk/lihont-ltp/lihont_ltp/ru.py index 395ad77..ac7d40c 100644 --- a/sdk/lihont-ltp/lihont_ltp/ru.py +++ b/sdk/lihont-ltp/lihont_ltp/ru.py @@ -9,7 +9,7 @@ from . import core from .core import (account as аккаунт, after as после, all_of as все_условия, always as всегда, any_of as любое_условие, author as автор, before as перед, between as между, bounce as туда_сюда, wander as бродит, day as день, download as скачать, evening as вечер, - friday as пятница, hashtag as хэштег, hide as скрыть, like as лайк, me as я, morning as утро, + friday as пятница, style as вид_имени, confetti as конфетти, buzz as вибро, hashtag as хэштег, hide as скрыть, like as лайк, me as я, morning as утро, night as ночь, person as человек, picture as картинка, rename as переименовать, say as сказать, sound as звук, weekday as день_недели, weekend as выходные, wiggle as качнуться, word as слово) diff --git a/sdk/lihont-ltp/lihont_ltp/validate.py b/sdk/lihont-ltp/lihont_ltp/validate.py index cfdbe2a..bc89d0a 100644 --- a/sdk/lihont-ltp/lihont_ltp/validate.py +++ b/sdk/lihont-ltp/lihont_ltp/validate.py @@ -24,14 +24,25 @@ MAX_ICON = 64 * 1024 MAX_FILE = 1024 * 1024 TRIGGERS = ("feed.item", "name.show", "screen.show") -RIGHTS = ("feed.hide", "names", "ui.notice", "ui.overlay", "ui.sound", "feed.like", "net.download") -ACTIONS = ("feed.hide", "name.prefix", "name.suffix", "name.replace", "notice", "overlay", "download") +RIGHTS = ("feed.hide", "names", "ui.notice", "ui.overlay", "ui.sound", "feed.like", "net.download", "ui.theme") +ACTIONS = ("feed.hide", "name.prefix", "name.suffix", "name.replace", "name.style", "notice", "overlay", "download") +NAME_STYLES = ("upper", "lower", "reverse", "wave", "spaced") +TAPS = ("animate", "sound", "like", "confetti", "buzz") OVERLAY_KEYS = ("image", "size", "alpha", "right", "bottom", "movable", "tap", "sound", "pet", "animate_ms", "walk") WALK_MODES = ("bounce", "wander") WALK_KEYS = ("mode", "speed", "flip") DOWNLOAD_KEYS = ("url", "as", "sha256") MAX_LICENSE = 40 +MAX_THEME_NAME = 24 +MAX_RADIUS = 40 +MAX_OUTLINE = 6 +MAX_SHADOW = 12 +THEME_KEYS = ("name", "dark", "page", "card", "text", "muted", "accent", "on_accent", "line", "title_from", "title_to", + "radius", "outline", "shadow", "bevel", "tick_box", "title_bars") +THEME_COLOURS = ("page", "card", "text", "muted", "accent", "on_accent", "line", "title_from", "title_to") +THEME_FLAGS = ("dark", "bevel", "tick_box", "title_bars") +COLOUR = re.compile(r"#[0-9a-f]{6}") MAX_AI = 4 MAX_AI_TEXT = 60 MAX_URL = 200 @@ -137,6 +148,12 @@ def check_action(node, trigger, where): raise LtpError("«скрыть» работает только в правилах про видео: %s" % where) if value is not True: raise LtpError("%s: нужно true" % here) + elif key == "name.style": + if trigger != "name.show": + raise LtpError("«вид имени» работает только в правилах про имена: %s" % where) + _text(value, 12, here) + if value not in NAME_STYLES: + raise LtpError("%s: вид имени — upper, lower, reverse, wave или spaced, а не «%s»" % (here, value)) elif key == "notice": _text(value, 80, here) elif key == "overlay": @@ -205,8 +222,8 @@ def check_overlay(node, where): if not isinstance(taps, list): raise LtpError("%s, «tap»: нужен список" % where) for tap in taps: - if tap not in ("animate", "sound", "like"): - raise LtpError("%s, «tap»: можно wiggle, sound(...) и like" % where) + if tap not in TAPS: + raise LtpError("%s, «tap»: можно wiggle, sound(...), like, confetti и buzz" % where) if len(set(taps)) != len(taps): raise LtpError("%s, «tap»: одно и то же действие названо дважды" % where) else: @@ -279,6 +296,65 @@ def rights_of(action): return ["names"] +def theme_colour(theme, key, default): + """Цвет темы как число 0xRRGGBB; если поля нет — значение по умолчанию (те же, что в приложении).""" + value = theme.get(key) + return default if value is None else int(value[1:], 16) + + +def theme_values(theme): + """Цвета темы с теми же умолчаниями, что в ThemeData.java: (текст, карточка, акцент, текст на акценте).""" + text = theme_colour(theme, "text", 0) + card = theme_colour(theme, "card", 0) + accent = theme_colour(theme, "accent", 0) + on_accent = theme_colour(theme, "on_accent", 0xFFFFFF) + return text, card, accent, on_accent + + +def _linear(channel): + c = channel / 255.0 + return c / 12.92 if c <= 0.03928 else ((c + 0.055) / 1.055) ** 2.4 + + +def _luminance(rgb): + return 0.2126 * _linear((rgb >> 16) & 0xFF) + 0.7152 * _linear((rgb >> 8) & 0xFF) + 0.0722 * _linear(rgb & 0xFF) + + +def contrast_tenths(a, b): + """Контраст WCAG в десятых (21.0 это 210), отбрасывая лишнее, как в Java: так проверки совпадают.""" + one = _luminance(a) + 0.05 + two = _luminance(b) + 0.05 + ratio = one / two if one > two else two / one + return int(ratio * 10) + + +def check_theme(theme, where="plugin.json, «theme»"): + """Тема: цвета и несколько чисел, ничего больше. Те же поля и границы, что в ThemeData.java.""" + if not isinstance(theme, dict): + raise LtpError("%s: нужен объект {…}" % where) + for key in theme: + if key not in THEME_KEYS: + raise LtpError("%s: нет поля «%s»" % (where, key)) + name = _text(theme.get("name"), MAX_THEME_NAME, where + ", поле «name»").strip() + if not name: + raise LtpError("%s: название темы не может быть пустым" % where) + for key in ("page", "card", "text", "accent"): + if theme.get(key) is None: + raise LtpError("%s: нет поля «%s»" % (where, key)) + for key in THEME_COLOURS: + value = theme.get(key) + if value is not None: + _text(value, 7, where + ", поле «%s»" % key) + if not COLOUR.fullmatch(value): + raise LtpError("%s, поле «%s»: цвет пишут как #rrggbb, например #2b1d3a (маленькими буквами)" % (where, key)) + for key, high in (("radius", MAX_RADIUS), ("outline", MAX_OUTLINE), ("shadow", MAX_SHADOW)): + if theme.get(key) is not None: + _integer(theme[key], 0, high, where + ", поле «%s»" % key) + for key in THEME_FLAGS: + if theme.get(key) is not None and not isinstance(theme[key], bool): + raise LtpError("%s, поле «%s»: нужно true или false" % (where, key)) + + def check_manifest(manifest, assets=None): """`assets` — словарь «имя файла → байты» (или None, если файлы тут неизвестны).""" if not isinstance(manifest, dict): @@ -317,8 +393,17 @@ def check_manifest(manifest, assets=None): raise LtpError("Неизвестное право «%s»" % right) if len(set(permissions)) != len(permissions): raise LtpError("Одно право названо дважды") + theme = manifest.get("theme") + if theme is not None: + if "ui.theme" not in permissions: + raise LtpError("plugin.json: есть «theme», но нет права «ui.theme»") + check_theme(theme) + elif "ui.theme" in permissions: + raise LtpError("plugin.json: право «ui.theme» требует поле «theme»") rules = manifest.get("rules") - if not isinstance(rules, list) or not rules: + if rules is None and theme is not None: + rules = [] # a plugin that only brings a theme has no rules + if not isinstance(rules, list) or (not rules and theme is None): raise LtpError("В плагине нет правил: добавь хотя бы одно, например plugin.video(hashtag(\"fyp\"), hide)") if len(rules) > MAX_RULES: raise LtpError("В плагине больше %d правил" % MAX_RULES) @@ -352,7 +437,7 @@ def check_manifest(manifest, assets=None): if rule.get("limit") is not None: _integer(rule["limit"], 1, MAX_LIMIT, where + ", «limit»") for right in permissions: - if right not in used: + if right != "ui.theme" and right not in used: raise LtpError("Плагин просит право «%s», но не использует его" % right) check_net(manifest.get("net"), permissions, downloads, assets) if assets is not None: diff --git a/skills/lihont-ltp/SKILL.md b/skills/lihont-ltp/SKILL.md index 65610c8..cd1d70f 100644 --- a/skills/lihont-ltp/SKILL.md +++ b/skills/lihont-ltp/SKILL.md @@ -36,6 +36,7 @@ plugin.save() - **Про что**: `plugin.video(...)`, `plugin.name(...)`, `plugin.screen(...)`. - **Если** (необязательно, без него «всегда»): `word("слово")`, `hashtag("тег")`, `author("ник")`, `person("id")`, `account("ник")`, `me`, `between("22:00","07:00")`, `weekday("fri")`, `morning/day/evening/night`, `friday/weekend`; сочетания `a & b` (и), `a | b` (или), `~a` (не). Несколько слов в одном условии значат «или»: `hashtag("fyp","foryou")`. +- **Тема оформления**: `plugin.theme("Закат", page="#2b1d3a", card="#3d2b52", text="#fbe9ff", accent="#ff8a5b", on_accent="#2b1d3a", radius=20)`. Цвета `#rrggbb` маленькими буквами; radius 0–40, outline 0–6, shadow 0–12; `bevel`, `tick_box`, `title_bars` для вида Windows 95. Тема только красит (ничего не прячет и не двигает), правила в таком плагине не нужны. Следи за контрастом: текст на карточках и на акценте не ниже 3.0, иначе защитник предупредит. - **Что сделать**: `hide` (только в `video`), `say("текст")` (подсказка, `limit=1` чтобы не чаще раза в день), `before("…")`, `after("…")`, `rename("…")` (только в `name`), `picture("файл", size=…, right=…, bottom=…, opacity=…, movable=True, on_tap=[wiggle, sound("x.ogg"), like], pet="…")`, `download("https://…", "имя.png")` (только в `screen`). - В `picture`: `like` ставит лайк по нажатию, поэтому добавляй его, только если человек прямо попросил. - Лицензия и ИИ: всегда ставь `license="MIT"` (или `"VCBFU-2"`) и `ai="<какая модель написала>"`. Без лицензии защитник отметит замечание, а для полки «проверенные» нужна MIT или VCBFU-2. @@ -52,12 +53,15 @@ plugin.save() | Короткая подсказка (до 80 знаков, не чаще лимита) | Читать чаты, комментарии, пароли, личные данные | | Картинка поверх приложения с анимацией, звуком, перетаскиванием, лайком по нажатию | Запускать код, вызывать любые функции | | Скачать картинку или звук (https, до 400 КБ, названный сайт, два согласия человека) | Ходить в интернет иначе; скачивать другое; отправлять данные | +| Тема оформления: цвета, радиус, контур, тень, объёмные рамки, галочки, полосы заголовков | Прятать, двигать и добавлять элементы экрана | | Лимиты: до 32 правил, до 8 действий в правиле, до 8 файлов по 400 КБ, всего 1 МБ | Темы, виджеты, кнопки: этого вида плагинов пока нет | Если просят то, чего в левой колонке нет, скажи прямо: это пока невозможно. Не изобретай несуществующие функции и не предлагай обходные пути через код. ## Осторожность +- **Закрыто навсегда** (этого нет и не будет у плагинов, не обещай и не придумывай обходов): пароли и коды входа, токены и ключи, **куки** и сессии, тексты сообщений и чатов, запуск кода. Если просят такое, скажи прямо, что формат этого не даёт. + - Не делай плагин «скрыть все видео» или «поменять все имена» без условия: защитник пометит его красным. Спроси, не нужно ли сузить условие. - Не клади в плагин чужие картинки, звуки и мемы без разрешения автора. Свои или свободные (CC0, MIT) файлы можно, и об источнике надо сказать. - `download` пиши только с адресом, который дал человек. Если можешь, добавь `sha256="…"`, иначе защитник предупредит, что сайт может подменить файл. diff --git a/src/lihont/two/bar/BarStyle.java b/src/lihont/two/bar/BarStyle.java index 71484f5..719b48d 100644 --- a/src/lihont/two/bar/BarStyle.java +++ b/src/lihont/two/bar/BarStyle.java @@ -85,6 +85,7 @@ final class BarStyle implements ViewTreeObserver.OnPreDrawListener, View.OnAttac create = bar.getChildAt(CREATE); if (create != null) { plus = new PlusPill(density, palette.primary, palette.onPrimary); + plus.setSquare(lihont.two.settings.ThemeEngine.square(activity)); android.util.Log.i("LihonT", "bar-style create button: " + describe(create)); } int styled = 0; @@ -101,6 +102,7 @@ final class BarStyle implements ViewTreeObserver.OnPreDrawListener, View.OnAttac Drawable existing = item.getBackground(); if (existing != null && !(existing instanceof NavPill)) continue; NavPill pill = new NavPill(icon, density, palette.secondaryContainer); + pill.setSquare(lihont.two.settings.ThemeEngine.square(activity)); item.setBackground(pill); pill.snapTo(item.isSelected()); pills[i] = pill; diff --git a/src/lihont/two/bar/NavPill.java b/src/lihont/two/bar/NavPill.java index 9303814..e0cff46 100644 --- a/src/lihont/two/bar/NavPill.java +++ b/src/lihont/two/bar/NavPill.java @@ -28,6 +28,12 @@ final class NavPill extends Drawable { private boolean selected; private ValueAnimator animator; + private boolean square; + + void setSquare(boolean value) { + square = value; + } + NavPill(View icon, float density, int color) { this.icon = icon; this.density = density; @@ -100,7 +106,8 @@ final class NavPill extends Drawable { rect.set(cx - width / 2f, cy - height / 2f, cx + width / 2f, cy + height / 2f); int alpha = paint.getAlpha(); paint.setAlpha(Math.round(alpha * progress)); - canvas.drawRoundRect(rect, height / 2f, height / 2f, paint); + if (square) canvas.drawRect(rect, paint); + else canvas.drawRoundRect(rect, height / 2f, height / 2f, paint); paint.setAlpha(alpha); } diff --git a/src/lihont/two/bar/PlusPill.java b/src/lihont/two/bar/PlusPill.java index 77a3dec..d99f9d9 100644 --- a/src/lihont/two/bar/PlusPill.java +++ b/src/lihont/two/bar/PlusPill.java @@ -14,6 +14,11 @@ final class PlusPill extends Drawable { private final Paint glyph = new Paint(Paint.ANTI_ALIAS_FLAG); private final RectF body = new RectF(); private final float density; + private boolean square; + + void setSquare(boolean value) { + square = value; + } PlusPill(float density, int fillColor, int glyphColor) { this.density = density; @@ -33,7 +38,7 @@ final class PlusPill extends Drawable { float cx = bounds.exactCenterX(); float cy = bounds.exactCenterY(); body.set(cx - width / 2f, cy - height / 2f, cx + width / 2f, cy + height / 2f); - float radius = height / 2.4f; + float radius = square ? 0f : height / 2.4f; canvas.drawRoundRect(body, radius, radius, fill); float arm = 9f * density; float thick = 1.6f * density; diff --git a/src/lihont/two/bar/ProfileMenu.java b/src/lihont/two/bar/ProfileMenu.java index 81f3d35..b2b025e 100644 --- a/src/lihont/two/bar/ProfileMenu.java +++ b/src/lihont/two/bar/ProfileMenu.java @@ -108,7 +108,7 @@ final class ProfileMenu { int gap = Math.round(1 * density); GradientDrawable tile = new GradientDrawable(); tile.setColor(palette.surfaceContainerHigh); - tile.setCornerRadius(24 * density); + tile.setCornerRadius(lihont.two.settings.ThemeEngine.square(row.getContext()) ? 0f : 24 * density); row.setBackground(new InsetDrawable(tile, side, gap, side, gap)); View name = cell.findViewById(title); diff --git a/src/lihont/two/chat/BubbleDrawable.java b/src/lihont/two/chat/BubbleDrawable.java index 4b47b31..391d3be 100644 --- a/src/lihont/two/chat/BubbleDrawable.java +++ b/src/lihont/two/chat/BubbleDrawable.java @@ -20,6 +20,9 @@ public final class BubbleDrawable extends Drawable { private final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG); private final Rect from = new Rect(); private final Path clip = new Path(); + private final RectF clipBox = new RectF(); + private int clipWidth = -1; + private int clipHeight = -1; /** @param corner the radius of the rounded corners, in pixels */ public BubbleDrawable(Bitmap bitmap, int corner) { @@ -40,8 +43,16 @@ public final class BubbleDrawable extends Drawable { int left = (bitmap.getWidth() - w) / 2; int top = (bitmap.getHeight() - h) / 2; from.set(left, top, left + w, top + h); - clip.reset(); - clip.addRoundRect(new RectF(box), corner, corner, Path.Direction.CW); + if (clipWidth != box.width() || clipHeight != box.height()) { + clipWidth = box.width(); + clipHeight = box.height(); + clip.reset(); + clipBox.set(box); + clip.addRoundRect(clipBox, corner, corner, Path.Direction.CW); + } else if (clipBox.left != box.left || clipBox.top != box.top) { + clip.offset(box.left - clipBox.left, box.top - clipBox.top); + clipBox.set(box); + } int saved = canvas.save(); canvas.clipPath(clip); canvas.drawBitmap(bitmap, from, box, paint); diff --git a/src/lihont/two/chat/BubbleStore.java b/src/lihont/two/chat/BubbleStore.java index 66be4e2..5fe675a 100644 --- a/src/lihont/two/chat/BubbleStore.java +++ b/src/lihont/two/chat/BubbleStore.java @@ -25,7 +25,13 @@ public final class BubbleStore { private static final String PEOPLE = "people"; private static final int MAX_PEOPLE = 60; - private static final Map CACHE = new HashMap(); + /** At most this many pictures stay decoded in memory; the one used least recently leaves first. */ + private static final int MAX_CACHED = 6; + private static final Map CACHE = new java.util.LinkedHashMap(8, 0.75f, true) { + @Override protected boolean removeEldestEntry(Map.Entry eldest) { + return size() > MAX_CACHED; + } + }; private static String lastSeen; private BubbleStore() {} @@ -57,7 +63,7 @@ public final class BubbleStore { /** Remembers the name of a person whose chat was opened, so that a picture can be chosen for them from a list. */ public static void seen(Context context, String person) { - if (person == null || person.length() == 0 || person.length() > 40 || person.equals(lastSeen)) return; + if (!plausible(person) || person.equals(lastSeen)) return; lastSeen = person; SharedPreferences prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE); java.util.Set known = new java.util.HashSet(prefs.getStringSet(PEOPLE, new java.util.HashSet())); @@ -68,11 +74,37 @@ public final class BubbleStore { public static java.util.List people(Context context) { SharedPreferences prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE); - java.util.List list = new java.util.ArrayList(prefs.getStringSet(PEOPLE, new java.util.HashSet())); + java.util.List list = new java.util.ArrayList(); + for (String name : prefs.getStringSet(PEOPLE, new java.util.HashSet())) { + if (plausible(name)) list.add(name); // names kept by earlier builds that were really screen labels are hidden + } java.util.Collections.sort(list, String.CASE_INSENSITIVE_ORDER); return list; } + private static final String[] LABELS = {"репост", "репосты", "входящие", "сообщения", "чат", "чаты", "активность", "уведомления", + "запросы", "новые подписчики", "inbox", "reposts", "messages", "notifications", "activity", "chat"}; + + /** True when the text can be a person's name: not a number, not a one-letter mark and not a label of the app's own screens. */ + static boolean plausible(String name) { + if (name == null) return false; + String text = name.trim(); + if (text.length() < 2 || text.length() > 40) return false; + boolean digitsOnly = true; + for (int i = 0; i < text.length(); i++) { + if (!Character.isDigit(text.charAt(i))) { + digitsOnly = false; + break; + } + } + if (digitsOnly) return false; + String lower = text.toLowerCase(java.util.Locale.ROOT); + for (String label : LABELS) { + if (lower.equals(label)) return false; + } + return true; + } + /** The picture for a slot: OWN, GENERAL or "p:" + person; a person without one gets the general picture. */ public static synchronized Bitmap forSlot(Context context, String slot, boolean fallbackToGeneral) { Bitmap own = load(context, slot); diff --git a/src/lihont/two/chat/Bubbles.java b/src/lihont/two/chat/Bubbles.java index f97effd..3793c40 100644 --- a/src/lihont/two/chat/Bubbles.java +++ b/src/lihont/two/chat/Bubbles.java @@ -51,14 +51,24 @@ public final class Bubbles { }); } + /** The ids of the chat views never change while the app runs: they are looked up once instead of three times a frame. */ + private static int listIdCache; + private static int rowIdCache; + private static int bubbleIdCache; + private static int id(Activity activity, String name) { return activity.getResources().getIdentifier(name, "id", activity.getPackageName()); } private static void apply(Activity activity, View decor) { - int listId = id(activity, LIST); - int rowId = id(activity, ROW); - int bubbleId = id(activity, BUBBLE); + if (listIdCache == 0) { + listIdCache = id(activity, LIST); + rowIdCache = id(activity, ROW); + bubbleIdCache = id(activity, BUBBLE); + } + int listId = listIdCache; + int rowId = rowIdCache; + int bubbleId = bubbleIdCache; if (listId == 0 || rowId == 0 || bubbleId == 0) return; View found = decor.findViewById(listId); if (!(found instanceof ViewGroup)) return; @@ -122,6 +132,7 @@ public final class Bubbles { int h = picture.getHeight(); Bitmap middle = Bitmap.createBitmap(picture, w / 4, h / 4, Math.max(1, w / 2), Math.max(1, h / 2)); Bitmap tiny = Bitmap.createScaledBitmap(middle, 8, 8, true); + if (middle != picture && middle != tiny) middle.recycle(); float sum = 0f; float weight = 0f; for (int y = 0; y < 8; y++) { @@ -133,6 +144,7 @@ public final class Bubbles { weight += a; } } + if (tiny != picture) tiny.recycle(); int color = weight == 0f || sum / weight < 0.55f ? 0xFFFFFFFF : 0xFF111111; TEXT.put(picture, Integer.valueOf(color)); return color; diff --git a/src/lihont/two/comments/CommentPanel.java b/src/lihont/two/comments/CommentPanel.java index 69d10bb..bf2c547 100644 --- a/src/lihont/two/comments/CommentPanel.java +++ b/src/lihont/two/comments/CommentPanel.java @@ -107,7 +107,7 @@ final class CommentPanel { this.palette = Md3.palette(activity, dark ? ModSettings.Theme.DARK : ModSettings.Theme.LIGHT); this.sheetBackground = new SheetBackground(density); this.sheetBackground.setColors(palette.surfaceContainerLow, palette.onSurfaceVariant); - this.pill = new Fill(palette.surfaceContainerHigh, PILL_RADIUS_DP * density); + this.pill = new Fill(activity, palette.surfaceContainerHigh, PILL_RADIUS_DP * density); this.mutedIcon = new PorterDuffColorFilter(palette.onSurfaceVariant, PorterDuff.Mode.SRC_IN); this.strongIcon = new PorterDuffColorFilter(palette.onSurface, PorterDuff.Mode.SRC_IN); this.accentIcon = new PorterDuffColorFilter(palette.primary, PorterDuff.Mode.SRC_IN); @@ -295,7 +295,7 @@ final class CommentPanel { private boolean card(View card) { CardState state = CARDS.get(card); if (state == null) { - state = new CardState(new Fill(palette.surfaceContainer, CARD_RADIUS_DP * density)); + state = new CardState(new Fill(activity, palette.surfaceContainer, CARD_RADIUS_DP * density)); state.color = palette.surfaceContainer; CARDS.put(card, state); note("card " + describe(card) + " " + card.getClass().getSuperclass().getSimpleName() diff --git a/src/lihont/two/comments/Fill.java b/src/lihont/two/comments/Fill.java index 9f835b6..2541dc3 100644 --- a/src/lihont/two/comments/Fill.java +++ b/src/lihont/two/comments/Fill.java @@ -1,11 +1,20 @@ package lihont.two.comments; +import android.content.Context; import android.graphics.drawable.GradientDrawable; +import lihont.two.settings.ThemeEngine; + /** A rounded tonal fill of the comment skin; the type tells the skin which backgrounds are its own. */ final class Fill extends GradientDrawable { - Fill(int color, float radiusPx) { + Fill(Context context, int color, float radiusPx) { setColor(color); - setCornerRadius(radiusPx); + if (ThemeEngine.square(context)) { + // a square theme: no rounding, a thin edge so the fill reads as a panel + setCornerRadius(0f); + setStroke(Math.max(1, Math.round(context.getResources().getDisplayMetrics().density)), ThemeEngine.edge(context)); + } else { + setCornerRadius(radiusPx); + } } } diff --git a/src/lihont/two/look/DebugMode.java b/src/lihont/two/look/DebugMode.java new file mode 100644 index 0000000..c3eefd7 --- /dev/null +++ b/src/lihont/two/look/DebugMode.java @@ -0,0 +1,99 @@ +package lihont.two.look; + +import android.content.Context; +import android.content.SharedPreferences; +import android.util.Log; + +import java.io.File; +import java.io.IOException; + +import lihont.two.plugin.PluginRegistry; +import lihont.two.settings.ModSettings; +import lihont.two.settings.SettingsHost; +import lihont.two.settings.ThemeEngine; + +/** + * The way back when a look or a plugin has made the screen hard to use. + * + * With DEBUG on, the app keeps a small marker file in its cache folder. Android's own "Clear cache" (App info, outside the + * app, so it works even when our screens cannot be read) removes the marker; the next time a screen opens, the missing marker + * tells the mod that the cache was cleared on purpose, and it resets the look (theme, colours, shape of the bar) and the + * plugins (safe mode on, internet off for every plugin). The plugin files stay, so nothing is lost: the person can switch + * them on again. DEBUG then turns itself off, so a cache that the system trims by itself later cannot reset anything twice. + */ +public final class DebugMode { + private static final String TAG = "LIHONT"; + private static final String PREFS = "lihont_debug"; + private static final String KEY = "enabled"; + private static final String MARKER = "lihont_debug.marker"; + + private DebugMode() {} + + public static boolean enabled(Context context) { + return context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getBoolean(KEY, false); + } + + /** Switches DEBUG on (and puts the marker in the cache) or off (and takes it out). */ + public static void set(Context context, boolean on) { + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putBoolean(KEY, on).apply(); + File marker = new File(context.getCacheDir(), MARKER); + if (on) { + try { + if (!marker.exists() && !marker.createNewFile()) Log.w(TAG, "debug: marker not created"); + } catch (IOException cannot) { + Log.w(TAG, "debug: marker not created: " + cannot); + } + } else if (marker.exists() && !marker.delete()) { + Log.w(TAG, "debug: marker not removed"); + } + } + + /** Puts the marker back when DEBUG is on: used after the app clears its own cache, which is not the way to a reset. */ + public static void keepMarker(Context context) { + try { + if (enabled(context)) set(context, true); + } catch (RuntimeException ignored) { + // The marker is a convenience for recovery; never let it stop a restart. + } + } + + /** Called when a screen opens: if DEBUG is on and the marker is gone, the cache was cleared, so reset. */ + public static void check(Context context) { + try { + if (!enabled(context)) return; + if (new File(context.getCacheDir(), MARKER).exists()) return; + Log.i(TAG, "debug: the cache was cleared with DEBUG on, resetting the look and the plugins"); + resetLook(context); + resetPlugins(context); + set(context, false); + } catch (Throwable ignored) { + // A recovery tool must never take a screen down. + } + } + + private static void resetLook(Context context) { + ThemeEngine.reset(context); + ModSettings now = SettingsHost.active(); + if (now == null) return; + ModSettings fresh = ModSettings.defaults(); + ModSettings next = now.withMd3(fresh.md3()).withTheme(fresh.theme()).withAccent(fresh.accent()) + .withAccentHue(fresh.accentHue()).withAmoled(fresh.amoled()).withCompactBar(fresh.compactBar()); + try { + SettingsHost.repository(context).save(next); + } catch (IOException | RuntimeException cannot) { + Log.w(TAG, "debug: the look settings were not saved: " + cannot); + } + } + + private static void resetPlugins(Context context) { + PluginRegistry.enterSafeMode(context); + for (PluginRegistry.Entry entry : PluginRegistry.entries(context)) { + PluginRegistry.setNetOn(context, entry.id, false); + } + } + + /** The SharedPreferences file name, for the tests and for a person who wants to check it. */ + static SharedPreferences prefs(Context context) { + return context.getSharedPreferences(PREFS, Context.MODE_PRIVATE); + } +} diff --git a/src/lihont/two/look/Windows.java b/src/lihont/two/look/Windows.java index 6c152e4..af17a4c 100644 --- a/src/lihont/two/look/Windows.java +++ b/src/lihont/two/look/Windows.java @@ -33,6 +33,8 @@ public final class Windows implements Application.ActivityLifecycleCallbacks { /** Watchers for a screen that has just come to the front; also called by the main screen itself. */ public static void attach(Activity activity) { + // the recovery mode first: it may reset the look and the plugins before any skin reads them + DebugMode.check(activity); try { lihont.two.plugin.PluginScreen.attach(activity); } catch (Throwable ignored) { diff --git a/src/lihont/two/plugin/Act.java b/src/lihont/two/plugin/Act.java index 6932fe2..a939d66 100644 --- a/src/lihont/two/plugin/Act.java +++ b/src/lihont/two/plugin/Act.java @@ -11,6 +11,7 @@ import java.util.Map; * {"name.prefix": "text"} text before the name (right names, trigger name.show) * {"name.suffix": "text"} text after the name (right names, trigger name.show) * {"name.replace": "text"} another name (right names, trigger name.show) + * {"name.style": "upper"} the look of the name: upper, lower, reverse, wave or spaced (right names, trigger name.show) * {"notice": "text"} a short hint on the screen (right ui.notice, any trigger) * {"overlay": {...}} a picture over the app, see OverlaySpec (right ui.overlay, plus ui.sound and * feed.like for a tap that plays a sound or likes; trigger screen.show) @@ -26,6 +27,40 @@ final class Act { static final int NOTICE = 4; static final int OVERLAY = 5; static final int DOWNLOAD = 6; + static final int STYLE = 7; + + /** The looks a name can be given, with the words the defender uses for each. */ + static final String[] STYLES = {"upper", "lower", "reverse", "wave", "spaced"}; + private static final String[] STYLE_WORDS = {"заглавными буквами", "строчными буквами", "задом наперёд", + "волной (пРиВеТ)", "с пробелами между буквами"}; + + static String styleWords(String style) { + for (int i = 0; i < STYLES.length; i++) { + if (STYLES[i].equals(style)) return STYLE_WORDS[i]; + } + return style; + } + + /** The name in the given look; a name that is longer than the screen can show is cut by the app, not here. */ + static String restyle(String style, String name) { + if (style.equals("upper")) return name.toUpperCase(java.util.Locale.ROOT); + if (style.equals("lower")) return name.toLowerCase(java.util.Locale.ROOT); + if (style.equals("reverse")) return new StringBuilder(name).reverse().toString(); + StringBuilder out = new StringBuilder(); + int index = 0; + for (int i = 0; i < name.length(); ) { + int point = name.codePointAt(i); + i += Character.charCount(point); + if (style.equals("wave")) { + out.appendCodePoint(index % 2 == 0 ? Character.toLowerCase(point) : Character.toUpperCase(point)); + } else { + if (index > 0) out.append(' '); + out.appendCodePoint(point); + } + index++; + } + return out.toString(); + } final int kind; final String text; @@ -71,6 +106,7 @@ final class Act { if (kind == SUFFIX) return "дописать «" + text + "» после имени"; if (kind == REPLACE) return "показать вместо имени «" + text + "»"; if (kind == NOTICE) return "показать подсказку «" + text + "»"; + if (kind == STYLE) return "показывать имя " + styleWords(text); if (kind == DOWNLOAD) { return "скачать файл " + download.as + " с сайта " + download.host + " (после вашего подтверждения)"; } @@ -83,6 +119,8 @@ final class Act { if (overlay.tap.contains(OverlaySpec.TAP_ANIMATE)) taps.add("играет анимация"); if (overlay.tap.contains(OverlaySpec.TAP_SOUND)) taps.add("звук"); if (overlay.tap.contains(OverlaySpec.TAP_LIKE)) taps.add("лайк видео"); + if (overlay.tap.contains(OverlaySpec.TAP_CONFETTI)) taps.add("конфетти"); + if (overlay.tap.contains(OverlaySpec.TAP_BUZZ)) taps.add("вибрация"); if (!taps.isEmpty()) { out.append("; по нажатию: "); for (int i = 0; i < taps.size(); i++) out.append(i > 0 ? ", " : "").append(taps.get(i)); @@ -111,6 +149,14 @@ final class Act { if (!Rule.SCREEN.equals(trigger)) throw new LtpException(here + ": работает только в правиле screen.show"); return new Act(DOWNLOAD, "", null, DownloadSpec.parse(value, here)); } + if (key.equals("name.style")) { + if (!Rule.NAME.equals(trigger)) throw new LtpException(here + ": работает только в правиле name.show"); + String style = Fields.text(value, 12, here); + if (!Fields.in(style, STYLES)) { + throw new LtpException(here + ": вид имени — upper, lower, reverse, wave или spaced, а не «" + style + "»"); + } + return new Act(STYLE, style, null); + } int kind = key.equals("name.prefix") ? PREFIX : key.equals("name.suffix") ? SUFFIX : key.equals("name.replace") ? REPLACE : -1; diff --git a/src/lihont/two/plugin/Confetti.java b/src/lihont/two/plugin/Confetti.java new file mode 100644 index 0000000..07bf59c --- /dev/null +++ b/src/lihont/two/plugin/Confetti.java @@ -0,0 +1,90 @@ +package lihont.two.plugin; + +import android.app.Activity; +import android.content.Context; +import android.graphics.Canvas; +import android.graphics.Paint; +import android.os.SystemClock; +import android.view.View; +import android.view.ViewGroup; +import android.widget.FrameLayout; + +import java.util.Random; + +/** + * A short burst of confetti thrown up from a point of the screen, for a tap on a plugin's picture. It draws on its own view + * that is put over the screen for a second and a half and then removed, never takes a touch, and holds no pictures: a few + * dozen small coloured shapes, so it costs almost no memory. + */ +final class Confetti extends View { + private static final int COUNT = 36; + private static final long LIFE_MS = 1500L; + private static final int[] COLOURS = {0xFFFF6B6B, 0xFFFFCD3C, 0xFF5ED6AA, 0xFF9670FF, 0xFF5AB4FF, 0xFFFF96C8}; + + private final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); + private final float[] vx = new float[COUNT]; + private final float[] vy = new float[COUNT]; + private final float[] spin = new float[COUNT]; + private final float[] size = new float[COUNT]; + private final float originX; + private final float originY; + private final float gravity; + private final long start = SystemClock.uptimeMillis(); + + private Confetti(Context context, float x, float y) { + super(context); + float density = context.getResources().getDisplayMetrics().density; + originX = x; + originY = y; + gravity = 900f * density; + Random random = new Random(start); + for (int i = 0; i < COUNT; i++) { + double angle = -Math.PI * (0.05 + random.nextDouble() * 0.9); + float speed = (180f + random.nextFloat() * 320f) * density; + vx[i] = (float) Math.cos(angle) * speed; + vy[i] = (float) Math.sin(angle) * speed; + spin[i] = (random.nextFloat() - 0.5f) * 16f; + size[i] = (4f + random.nextFloat() * 5f) * density; + } + setClickable(false); + setFocusable(false); + } + + /** Throws confetti from the middle of `from`, over the whole screen of the activity. */ + static void burst(Activity activity, View from) { + try { + ViewGroup decor = (ViewGroup) activity.getWindow().getDecorView(); + int[] at = new int[2]; + from.getLocationInWindow(at); + final Confetti view = new Confetti(activity, at[0] + from.getWidth() / 2f, at[1] + from.getHeight() / 2f); + decor.addView(view, new FrameLayout.LayoutParams(-1, -1)); + view.postDelayed(new Runnable() { + @Override public void run() { + ViewGroup parent = (ViewGroup) view.getParent(); + if (parent != null) parent.removeView(view); + } + }, LIFE_MS + 100L); + } catch (RuntimeException ignored) { + // A flourish: never worth taking a screen down. + } + } + + @Override protected void onDraw(Canvas canvas) { + float t = (SystemClock.uptimeMillis() - start) / 1000f; + float fade = Math.max(0f, 1f - (t * 1000f) / LIFE_MS); + if (fade <= 0f) return; + paint.setStyle(Paint.Style.FILL); + for (int i = 0; i < COUNT; i++) { + float x = originX + vx[i] * t; + float y = originY + vy[i] * t + 0.5f * gravity * t * t; + paint.setColor(COLOURS[i % COLOURS.length]); + paint.setAlpha((int) (255 * fade)); + canvas.save(); + canvas.translate(x, y); + canvas.rotate(spin[i] * t * 57.3f); + canvas.drawRect(-size[i], -size[i] / 2f, size[i], size[i] / 2f, paint); + canvas.restore(); + } + postInvalidateOnAnimation(); + } +} diff --git a/src/lihont/two/plugin/Defender.java b/src/lihont/two/plugin/Defender.java index 9c0fdc6..596d0a3 100644 --- a/src/lihont/two/plugin/Defender.java +++ b/src/lihont/two/plugin/Defender.java @@ -86,6 +86,13 @@ public final class Defender { } } else if (act.kind == Act.PREFIX || act.kind == Act.SUFFIX) { if (seen.add("affix")) calm.add("Дописывает текст к именам, только на вашем экране."); + } else if (act.kind == Act.STYLE) { + if (!selects) { + watch.add("Правило «" + rule.title + "» меняет вид всех имён на экране (" + Act.styleWords(act.text) + + "): читать их труднее."); + } else if (seen.add("style")) { + calm.add("Меняет вид имён у выбранных аккаунтов, только на вашем экране."); + } } else if (act.kind == Act.NOTICE) { if (rule.limit > 10 && seen.add("notice")) { watch.add("Показывает подсказки до " + rule.limit + " раз в день."); @@ -112,6 +119,10 @@ public final class Defender { } else if (spec.size >= 300 && seen.add("big")) { watch.add("Большая картинка закрывает часть экрана."); } + if ((spec.tap.contains(OverlaySpec.TAP_CONFETTI) || spec.tap.contains(OverlaySpec.TAP_BUZZ)) + && seen.add("fun")) { + calm.add("Конфетти или лёгкая вибрация по нажатию на картинку."); + } if (spec.tap.contains(OverlaySpec.TAP_SOUND) && seen.add("sound")) { watch.add("Играет звук, когда вы нажимаете на картинку."); } @@ -122,6 +133,19 @@ public final class Defender { } } } + if (plugin.theme != null) { + ThemeData theme = plugin.theme; + rules.add("Тема «" + theme.name + "»: меняет цвета и вид экранов мода и TikTok"); + calm.add("Меняет оформление: цвета, формы и рамки. Ничего не скрывает и не двигает. " + + "Вернуть как было можно в «Оформление» или режимом DEBUG."); + if (theme.textContrast() < 30) { + watch.add("Текст на карточках темы плохо читается: контраст " + tenths(theme.textContrast()) + " при нужных 3.0."); + } + if (theme.accentContrast() < 30) { + watch.add("Текст на кнопках и заголовках темы плохо читается: контраст " + tenths(theme.accentContrast()) + + " при нужных 3.0."); + } + } if (!plugin.assets.isEmpty()) { calm.add("Файлов внутри: " + plugin.assets.size() + ". Тип каждого проверен по первым байтам, они входят в хэш."); } @@ -134,6 +158,10 @@ public final class Defender { !plugin.hosts.isEmpty()); } + private static String tenths(int value) { + return (value / 10) + "." + (value % 10); + } + private static String join(List items) { StringBuilder out = new StringBuilder(); for (int i = 0; i < items.size(); i++) out.append(i > 0 ? ", " : "").append(items.get(i)); diff --git a/src/lihont/two/plugin/Evaluator.java b/src/lihont/two/plugin/Evaluator.java index 46bb5ca..577578c 100644 --- a/src/lihont/two/plugin/Evaluator.java +++ b/src/lihont/two/plugin/Evaluator.java @@ -35,6 +35,7 @@ public final class Evaluator { if (act.kind == Act.PREFIX) result = expand(act.text, result, ctx) + result; else if (act.kind == Act.SUFFIX) result = result + expand(act.text, result, ctx); else if (act.kind == Act.REPLACE) result = expand(act.text, result, ctx); + else if (act.kind == Act.STYLE) result = Act.restyle(act.text, result); } } if (result.length() > MAX_NAME) result = result.substring(0, MAX_NAME); diff --git a/src/lihont/two/plugin/OverlaySpec.java b/src/lihont/two/plugin/OverlaySpec.java index 6d57d53..fcffd8e 100644 --- a/src/lihont/two/plugin/OverlaySpec.java +++ b/src/lihont/two/plugin/OverlaySpec.java @@ -34,6 +34,8 @@ public final class OverlaySpec { public static final String TAP_ANIMATE = "animate"; public static final String TAP_SOUND = "sound"; public static final String TAP_LIKE = "like"; + public static final String TAP_CONFETTI = "confetti"; + public static final String TAP_BUZZ = "buzz"; public static final String WALK_BOUNCE = "bounce"; public static final String WALK_WANDER = "wander"; @@ -106,8 +108,8 @@ public final class OverlaySpec { } else { for (Object item : Fields.list(map.get("tap"), where + ", «tap»")) { String what = Fields.text(item, 12, where + ", «tap»"); - if (!Fields.in(what, TAP_ANIMATE, TAP_SOUND, TAP_LIKE)) { - throw new LtpException(where + ", «tap»: можно animate, sound и like, а не «" + what + "»"); + if (!Fields.in(what, TAP_ANIMATE, TAP_SOUND, TAP_LIKE, TAP_CONFETTI, TAP_BUZZ)) { + throw new LtpException(where + ", «tap»: можно animate, sound, like, confetti и buzz, а не «" + what + "»"); } if (tap.contains(what)) throw new LtpException(where + ", «tap»: «" + what + "» названо дважды"); tap.add(what); diff --git a/src/lihont/two/plugin/Permission.java b/src/lihont/two/plugin/Permission.java index 3e895cd..8d447a6 100644 --- a/src/lihont/two/plugin/Permission.java +++ b/src/lihont/two/plugin/Permission.java @@ -19,6 +19,7 @@ public final class Permission { public static final String SOUND = "ui.sound"; public static final String LIKE = "feed.like"; public static final String NET_DOWNLOAD = "net.download"; + public static final String UI_THEME = "ui.theme"; private static final Map TEXT = new LinkedHashMap(); @@ -29,6 +30,8 @@ public final class Permission { TEXT.put(OVERLAY, "Показывать свою картинку поверх приложения (её можно двигать)"); TEXT.put(SOUND, "Проигрывать звук плагина, когда вы нажимаете на его картинку"); TEXT.put(LIKE, "Ставить лайк видео на главной ленте, когда вы нажимаете на картинку плагина"); + TEXT.put(UI_THEME, "Менять оформление экранов мода и TikTok: цвета, формы, рамки " + + "(ничего не скрывает и не двигает; вернуть можно в «Оформление» или режимом DEBUG)"); TEXT.put(NET_DOWNLOAD, "Скачивать картинки и звуки с названных сайтов (включается отдельным переключателем, " + "каждый адрес вы подтверждаете)"); } diff --git a/src/lihont/two/plugin/Plugin.java b/src/lihont/two/plugin/Plugin.java index 2c6be39..4ce987a 100644 --- a/src/lihont/two/plugin/Plugin.java +++ b/src/lihont/two/plugin/Plugin.java @@ -50,10 +50,13 @@ public final class Plugin { public final String license; /** The AI models the author says helped write it; empty when none are named. Said by the author, not checked. */ public final List ai; + /** The look the plugin brings (right ui.theme), or null. */ + public final ThemeData theme; private Plugin(String id, String name, String version, String author, String description, List permissions, List rules, String sha256, Set assets, List hosts, - String license, List ai) { + String license, List ai, ThemeData theme) { + this.theme = theme; this.license = license; this.ai = Collections.unmodifiableList(ai); this.hosts = Collections.unmodifiableList(hosts); @@ -125,13 +128,25 @@ public final class Plugin { permissions.add(right); } - List raw = Fields.list(root.get("rules"), "plugin.json, «rules»"); - if (raw.isEmpty()) throw new LtpException("В плагине нет правил"); + ThemeData theme = null; + if (root.get("theme") != null) { + if (!permissions.contains(Permission.UI_THEME)) { + throw new LtpException("plugin.json: есть «theme», но нет права «ui.theme»"); + } + theme = ThemeData.parse(root.get("theme"), "plugin.json, «theme»"); + } else if (permissions.contains(Permission.UI_THEME)) { + throw new LtpException("plugin.json: право «ui.theme» требует поле «theme»"); + } + // a plugin that only brings a theme has no rules + List raw = root.get("rules") == null && theme != null ? new ArrayList() + : Fields.list(root.get("rules"), "plugin.json, «rules»"); + if (raw.isEmpty() && theme == null) throw new LtpException("В плагине нет правил"); if (raw.size() > MAX_RULES) throw new LtpException("В плагине больше " + MAX_RULES + " правил"); List rules = new ArrayList(); for (int i = 0; i < raw.size(); i++) rules.add(Rule.parse(raw.get(i), i, permissions)); for (String right : permissions) { + if (right.equals(Permission.UI_THEME)) continue; // used by the "theme" part, not by a rule boolean used = false; for (Rule rule : rules) used = used || rule.uses(right); if (!used) throw new LtpException("Плагин просит право «" + right + "», но не использует его"); @@ -146,7 +161,7 @@ public final class Plugin { for (OverlaySpec spec : rule.overlays()) spec.check(known, "Правило «" + rule.title + "»"); } return new Plugin(id, name, version, author, description, permissions, rules, sha256(bytes, files), names, hosts, - license, ai); + license, ai, theme); } /** diff --git a/src/lihont/two/plugin/PluginRegistry.java b/src/lihont/two/plugin/PluginRegistry.java index 4acd707..8ac10c4 100644 --- a/src/lihont/two/plugin/PluginRegistry.java +++ b/src/lihont/two/plugin/PluginRegistry.java @@ -317,6 +317,11 @@ public final class PluginRegistry { return prefs(context).getBoolean("safe", false); } + /** Puts the plugins into safe mode: none of them runs until the person leaves it. Used by the recovery mode. */ + public static synchronized void enterSafeMode(Context context) { + prefs(context).edit().putBoolean("safe", true).apply(); + } + public static synchronized void leaveSafeMode(Context context) { prefs(context).edit().putBoolean("safe", false).putInt("early", 0).apply(); version++; diff --git a/src/lihont/two/plugin/PluginScreen.java b/src/lihont/two/plugin/PluginScreen.java index bafb076..01b499c 100644 --- a/src/lihont/two/plugin/PluginScreen.java +++ b/src/lihont/two/plugin/PluginScreen.java @@ -313,6 +313,14 @@ public final class PluginScreen { } } if (spec.tap.contains(OverlaySpec.TAP_ANIMATE) && play(view)) did.append("анимация "); + if (spec.tap.contains(OverlaySpec.TAP_CONFETTI)) { + Confetti.burst(host, view); + did.append("конфетти "); + } + if (spec.tap.contains(OverlaySpec.TAP_BUZZ)) { + view.performHapticFeedback(android.view.HapticFeedbackConstants.LONG_PRESS); + did.append("вибрация "); + } if (spec.tap.contains(OverlaySpec.TAP_LIKE)) { did.append(like() ? "лайк" : "лайк не поставлен (не главная лента)"); } diff --git a/src/lihont/two/plugin/ThemeData.java b/src/lihont/two/plugin/ThemeData.java new file mode 100644 index 0000000..e378701 --- /dev/null +++ b/src/lihont/two/plugin/ThemeData.java @@ -0,0 +1,149 @@ +package lihont.two.plugin; + +import java.util.Map; + +/** + * The "theme" part of a plugin: a look for the mod's screens, as data. It holds colours and a few shape numbers and nothing + * else: a theme paints, it never moves, hides or adds a control. Needs the right "ui.theme". + * + * "theme": {"name": "Закат", "page": "#2b1d3a", "card": "#3d2b52", "text": "#fbe9ff", "accent": "#ff8a5b", + * "radius": 20, "outline": 2, "shadow": 4} + * + * The same fields and limits are checked by sdk/lihont-ltp/lihont_ltp/validate.py (check_theme). + */ +public final class ThemeData { + public static final int MAX_NAME = 24; + public static final int MAX_RADIUS = 40; + public static final int MAX_OUTLINE = 6; + public static final int MAX_SHADOW = 12; + + public final String name; + public final boolean dark; + public final int page; + public final int card; + public final int text; + public final int muted; + public final int accent; + public final int onAccent; + public final int line; + public final int titleFrom; + public final int titleTo; + public final int radius; + public final int outline; + public final int shadow; + public final boolean bevel; + public final boolean tickBox; + public final boolean titleBars; + + private ThemeData(String name, boolean dark, int page, int card, int text, int muted, int accent, int onAccent, int line, + int titleFrom, int titleTo, int radius, int outline, int shadow, boolean bevel, boolean tickBox, boolean titleBars) { + this.name = name; + this.dark = dark; + this.page = page; + this.card = card; + this.text = text; + this.muted = muted; + this.accent = accent; + this.onAccent = onAccent; + this.line = line; + this.titleFrom = titleFrom; + this.titleTo = titleTo; + this.radius = radius; + this.outline = outline; + this.shadow = shadow; + this.bevel = bevel; + this.tickBox = tickBox; + this.titleBars = titleBars; + } + + static ThemeData parse(Object node, String where) throws LtpException { + Map map = Fields.map(node, where); + for (String key : map.keySet()) { + if (!Fields.in(key, "name", "dark", "page", "card", "text", "muted", "accent", "on_accent", "line", "title_from", + "title_to", "radius", "outline", "shadow", "bevel", "tick_box", "title_bars")) { + throw new LtpException(where + ": нет поля «" + key + "»"); + } + } + String name = Fields.string(map, "name", true, MAX_NAME, where).trim(); + if (name.length() == 0) throw new LtpException(where + ": название темы не может быть пустым"); + int page = colour(map, "page", true, 0, where); + int card = colour(map, "card", true, 0, where); + int text = colour(map, "text", true, 0, where); + int accent = colour(map, "accent", true, 0, where); + int muted = colour(map, "muted", false, text, where); + int onAccent = colour(map, "on_accent", false, 0xFFFFFF, where); + int line = colour(map, "line", false, text, where); + int titleFrom = colour(map, "title_from", false, accent, where); + int titleTo = colour(map, "title_to", false, accent, where); + int radius = number(map, "radius", 12, MAX_RADIUS, where); + int outline = number(map, "outline", 0, MAX_OUTLINE, where); + int shadow = number(map, "shadow", 0, MAX_SHADOW, where); + return new ThemeData(name, flag(map, "dark", where), page, card, text, muted, accent, onAccent, line, titleFrom, titleTo, + radius, outline, shadow, flag(map, "bevel", where), flag(map, "tick_box", where), flag(map, "title_bars", where)); + } + + /** A colour as "#rrggbb" (the # and six hex digits), returned as 0xRRGGBB. */ + private static int colour(Map map, String key, boolean required, int fallback, String where) + throws LtpException { + Object value = map.get(key); + if (value == null) { + if (required) throw new LtpException(where + ": нет поля «" + key + "»"); + return fallback; + } + String text = Fields.text(value, 7, where + ", поле «" + key + "»"); + if (text.length() != 7 || text.charAt(0) != '#') { + throw new LtpException(where + ", поле «" + key + "»: цвет пишут как #rrggbb, например #2b1d3a"); + } + int out = 0; + for (int i = 1; i < 7; i++) { + char ch = text.charAt(i); + int digit = Character.digit(ch, 16); + // lower case only, like the Python checker: #2b1d3a, not #2B1D3A + if (digit < 0 || (ch >= 'A' && ch <= 'F')) { + throw new LtpException(where + ", поле «" + key + "»: цвет пишут как #rrggbb, например #2b1d3a"); + } + out = out * 16 + digit; + } + return out; + } + + private static int number(Map map, String key, int fallback, int max, String where) throws LtpException { + Object value = map.get(key); + if (value == null) return fallback; + return Fields.integer(value, 0, max, where + ", поле «" + key + "»"); + } + + private static boolean flag(Map map, String key, String where) throws LtpException { + Object value = map.get(key); + if (value == null) return false; + if (!(value instanceof Boolean)) throw new LtpException(where + ", поле «" + key + "»: нужно true или false"); + return (Boolean) value; + } + + /** WCAG contrast of two colours in tenths (21.0 is 210), cut down not rounded, so the Java and Python checks agree. */ + static int contrastTenths(int a, int b) { + double one = luminance(a) + 0.05; + double two = luminance(b) + 0.05; + double ratio = one > two ? one / two : two / one; + return (int) (ratio * 10); + } + + private static double luminance(int rgb) { + return 0.2126 * linear((rgb >> 16) & 0xFF) + 0.7152 * linear((rgb >> 8) & 0xFF) + 0.0722 * linear(rgb & 0xFF); + } + + private static double linear(int channel) { + double c = channel / 255.0; + return c <= 0.03928 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4); + } + + /** The contrast of the text on a card in tenths. */ + public int textContrast() { + return contrastTenths(text, card); + } + + /** The contrast of the text on an accent (buttons, title bars) in tenths. */ + public int accentContrast() { + return contrastTenths(onAccent, accent); + } +} diff --git a/src/lihont/two/profile/ProfilePanel.java b/src/lihont/two/profile/ProfilePanel.java index cd09a0c..feb9baf 100644 --- a/src/lihont/two/profile/ProfilePanel.java +++ b/src/lihont/two/profile/ProfilePanel.java @@ -218,7 +218,7 @@ final class ProfilePanel { if (view.getBackground() instanceof Tone || (host != null && host.getBackground() instanceof Tone)) return; boolean action = host != null && saturated(host.getBackground()); View target = host != null ? host : view; - target.setBackground(new Tone(action ? palette.primary : palette.secondaryContainer, Md3.SHAPE_FULL * density)); + target.setBackground(new Tone(activity, action ? palette.primary : palette.secondaryContainer, Md3.SHAPE_FULL * density)); inkAll(view, action ? palette.onPrimary : palette.onSecondaryContainer); note("pill " + describe(view) + (action ? " action" : " tonal") + " on " + describe(target)); } @@ -267,7 +267,7 @@ final class ProfilePanel { Drawable background = button.getBackground(); if (background instanceof Tone) return; boolean filled = isFilled(background); - button.setBackground(new Tone(filled ? palette.primary : palette.secondaryContainer, Md3.SHAPE_FULL * density)); + button.setBackground(new Tone(activity, filled ? palette.primary : palette.secondaryContainer, Md3.SHAPE_FULL * density)); ink(button, filled ? palette.onPrimary : palette.onSecondaryContainer); note("button " + describe(button) + (filled ? " filled" : " tonal")); } @@ -325,7 +325,7 @@ final class ProfilePanel { if (!(row.getBackground() instanceof InsetDrawable)) { int side = (int) (12 * density); int gap = (int) (6 * density); - row.setBackground(new InsetDrawable(new Tone(palette.surfaceContainer, CARD_RADIUS_DP * density), + row.setBackground(new InsetDrawable(new Tone(activity, palette.surfaceContainer, CARD_RADIUS_DP * density), side, gap, side, gap)); } ink(text, palette.onSurface); diff --git a/src/lihont/two/profile/Tone.java b/src/lihont/two/profile/Tone.java index 0b7312a..d2d4f1a 100644 --- a/src/lihont/two/profile/Tone.java +++ b/src/lihont/two/profile/Tone.java @@ -1,11 +1,20 @@ package lihont.two.profile; +import android.content.Context; import android.graphics.drawable.GradientDrawable; +import lihont.two.settings.ThemeEngine; + /** A rounded tonal fill of the profile skin; the type tells the skin which backgrounds are its own. */ final class Tone extends GradientDrawable { - Tone(int color, float radiusPx) { + Tone(Context context, int color, float radiusPx) { setColor(color); - setCornerRadius(radiusPx); + if (ThemeEngine.square(context)) { + // a square theme: no rounding, a thin edge so the fill reads as a panel + setCornerRadius(0f); + setStroke(Math.max(1, Math.round(context.getResources().getDisplayMetrics().density)), ThemeEngine.edge(context)); + } else { + setCornerRadius(radiusPx); + } } } diff --git a/src/lihont/two/settings/BevelDrawable.java b/src/lihont/two/settings/BevelDrawable.java new file mode 100644 index 0000000..be971ec --- /dev/null +++ b/src/lihont/two/settings/BevelDrawable.java @@ -0,0 +1,63 @@ +package lihont.two.settings; + +import android.graphics.Canvas; +import android.graphics.Color; +import android.graphics.ColorFilter; +import android.graphics.Paint; +import android.graphics.PixelFormat; +import android.graphics.Rect; +import android.graphics.drawable.Drawable; + +/** + * The two-line 3D edge of Windows 95: a face with a light edge on the top and left and a dark one on the bottom and right + * (raised, like a button or a window), or the other way round (sunken, like a field or a tick box). + */ +final class BevelDrawable extends Drawable { + private final Paint paint = new Paint(); + private final int face; + private final boolean raised; + private final int edge; + + BevelDrawable(int face, boolean raised, int edgePx) { + this.face = face; + this.raised = raised; + this.edge = Math.max(1, edgePx); + } + + @Override public void draw(Canvas canvas) { + Rect b = getBounds(); + int white = Color.WHITE; + int light = Color.rgb(223, 223, 223); + int grey = Color.rgb(128, 128, 128); + int black = Color.BLACK; + paint.setStyle(Paint.Style.FILL); + paint.setColor(face); + canvas.drawRect(b, paint); + // outer ring, then the inner ring one edge in; raised: light top-left and dark bottom-right, sunken: the reverse + ring(canvas, b.left, b.top, b.right, b.bottom, raised ? white : grey, raised ? black : white); + ring(canvas, b.left + edge, b.top + edge, b.right - edge, b.bottom - edge, + raised ? light : black, raised ? grey : light); + } + + private void ring(Canvas canvas, int left, int top, int right, int bottom, int topLeft, int bottomRight) { + paint.setColor(topLeft); + canvas.drawRect(left, top, right - edge, top + edge, paint); + canvas.drawRect(left, top, left + edge, bottom - edge, paint); + paint.setColor(bottomRight); + canvas.drawRect(left + edge, bottom - edge, right, bottom, paint); + canvas.drawRect(right - edge, top + edge, right, bottom, paint); + } + + @Override public void setAlpha(int alpha) {} + + @Override public void setColorFilter(ColorFilter filter) {} + + @Override public int getOpacity() { + return PixelFormat.OPAQUE; + } + + @Override public boolean getPadding(Rect padding) { + padding.set(edge * 2, edge * 2, edge * 2, edge * 2); + return true; + } +} diff --git a/src/lihont/two/settings/LihonTSettingsActivity.java b/src/lihont/two/settings/LihonTSettingsActivity.java index 5c9cfba..52a2e9f 100644 --- a/src/lihont/two/settings/LihonTSettingsActivity.java +++ b/src/lihont/two/settings/LihonTSettingsActivity.java @@ -46,13 +46,14 @@ import java.util.Locale; /** Material 3 settings screen for LihonT 2. */ public final class LihonTSettingsActivity extends Activity { - private static final String VERSION_LINE = "LihonT 2.0 · Luna"; + private static final String VERSION_LINE = "LihonT 2.0 · Serena alpha"; private static final String BASE_LINE = "База TikTok 47.1.3"; private static final String CHANNEL_URL = "https://t.me/lihont"; private static final String SOURCE_URL = "https://git.lihont.space/lihont/LihonT"; private static final String LICENSE_URL = SOURCE_URL + "/src/branch/main/LICENSE"; private static final String CHANGES = - "• Призрак (раздел «Приватность»): истории без отметки о просмотре и чаты без «прочитано». Переключатели выключены, пока вы их не включите.\n" + "• Serena alpha: оформление на выбор (Material 3, Стикеры или обычный TikTok) в настройках мода.\n" + + "• Призрак (раздел «Приватность»): истории без отметки о просмотре и чаты без «прочитано». Переключатели выключены, пока вы их не включите.\n" + "• Несколько фото в одном комментарии (до 9), если это даёт сервер для вашего аккаунта.\n" + "• Плагины .ltp: правила для ленты, имён и картинок без кода. Права вы одобряете сами, плагины включаются на каждый аккаунт отдельно, есть журнал, откат версии и защитник, который говорит простыми словами, что делает плагин.\n" + "• Плагин может скачивать картинки и звуки с названных сайтов, но только когда вы включили ему интернет и подтвердили адрес. У плагина видны лицензия и ИИ, которые назвал автор.\n" @@ -190,6 +191,8 @@ public final class LihonTSettingsActivity extends Activity { Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.BOTTOM_BAR, palette.onPrimaryContainer, 8), settings.md3(), TOGGLE_MD3)); cardFunc.addView(Md3.cardDivider(this, palette)); + cardFunc.addView(styleRow()); + cardFunc.addView(Md3.cardDivider(this, palette)); cardFunc.addView(switchRow("Скачивание без водяного знака", "Сохранённые видео без логотипа TikTok", Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.DOWNLOAD, palette.onPrimaryContainer, 8), settings.noWatermark(), TOGGLE_NO_WATERMARK)); @@ -205,6 +208,10 @@ public final class LihonTSettingsActivity extends Activity { cardPrivacy.addView(ghostMessagesRow()); addSection("Приватность", cardPrivacy, false); + LinearLayout cardDebug = Md3.card(this, palette); + cardDebug.addView(debugRow()); + addSection("Восстановление", cardDebug, false); + LinearLayout cardChat = Md3.card(this, palette); cardChat.addView(bubblesSwitchRow()); cardChat.addView(Md3.cardDivider(this, palette)); @@ -390,6 +397,90 @@ public final class LihonTSettingsActivity extends Activity { return row; } + /** DEBUG: the way back from a broken look or plugin, through Android's "Clear cache" of the app (see DebugMode). */ + private View debugRow() { + Md3Switch toggle = new Md3Switch(this, palette); + toggle.setContentDescription("Режим DEBUG"); + toggle.setChecked(lihont.two.look.DebugMode.enabled(this), false); + toggle.setOnCheckedChangeListener((view, value) -> { + lihont.two.look.DebugMode.set(this, value); + Toast.makeText(this, value + ? "DEBUG включён. Очистка кэша приложения в настройках Android сбросит оформление и плагины" + : "DEBUG выключен", Toast.LENGTH_LONG).show(); + }); + LinearLayout row = Md3.listItem(this, palette, + Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.INFO, palette.onPrimaryContainer, 8), + "Режим DEBUG", "Если оформление или плагин всё сломали: включите заранее, потом очистите кэш приложения " + + "(Настройки Android → Приложения → TikTok → Хранилище → Очистить кэш). Оформление и плагины " + + "сбросятся, файлы плагинов останутся", toggle, true); + row.setOnClickListener(v -> toggle.toggle()); + return row; + } + + private String styleName() { + if (!settings.md3()) return "Обычный TikTok"; + ThemeSpec theme = ThemeEngine.active(this); + return theme != null ? theme.name : "Material 3"; + } + + /** The look of the mod's screens: Material 3, a theme (stickers, Windows 95...) or the plain TikTok one of Serena 1.2. */ + private View styleRow() { + LinearLayout row = Md3.listItem(this, palette, + Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.BOTTOM_BAR, palette.onPrimaryContainer, 8), + "Оформление", styleName(), Md3.chevron(this, palette), true); + row.setOnClickListener(v -> chooseStyle()); + return row; + } + + private void chooseStyle() { + // the two base looks first, then every theme the engine knows + final java.util.List ids = new java.util.ArrayList(); + final java.util.List names = new java.util.ArrayList(); + final java.util.List hints = new java.util.ArrayList(); + ids.add("md3"); + names.add("Material 3"); + hints.add("Мягкие скругления и цвета вашей палитры"); + for (ThemeSpec spec : ThemeSpec.BUILT_IN) { + ids.add(spec.id); + names.add(spec.name); + hints.add(spec.id.equals("win95") ? "Серые окна, объёмные кнопки, синие заголовки и галочки" + : "Толстые контуры и жёсткие тени, как наклейки"); + } + for (lihont.two.plugin.PluginRegistry.Entry entry : lihont.two.plugin.PluginRegistry.entries(this)) { + if (entry.plugin == null || !entry.approved || entry.plugin.theme == null) continue; + ids.add("plugin:" + entry.id); + names.add(entry.plugin.theme.name + " (плагин)"); + hints.add("Тема из плагина «" + entry.plugin.name + "», автор " + entry.plugin.author); + } + ids.add("classic"); + names.add("Обычный TikTok"); + hints.add("Плоский вид Serena 1.2"); + final Dialog[] shown = new Dialog[1]; + LinearLayout list = new LinearLayout(this); + list.setOrientation(LinearLayout.VERTICAL); + for (int i = 0; i < ids.size(); i++) { + final String id = ids.get(i); + boolean current = names.get(i).equals(styleName()); + LinearLayout item = new LinearLayout(this); + item.setOrientation(LinearLayout.VERTICAL); + item.setPadding(Md3.dp(this, 12), Md3.dp(this, 12), Md3.dp(this, 12), Md3.dp(this, 12)); + item.setBackground(Md3.stateLayer(this, Md3.SHAPE_EXTRA_SMALL, Md3.stateLayerColor(palette.onSurface))); + item.setClickable(true); + item.addView(Md3.text(this, names.get(i) + (current ? " ✓" : ""), Md3.BODY_LARGE, true, palette.onSurface)); + item.addView(Md3.text(this, hints.get(i), Md3.BODY_MEDIUM, false, palette.onSurfaceVariant)); + item.setOnClickListener(v -> { + shown[0].dismiss(); + ThemeEngine.set(this, id.equals("md3") || id.equals("classic") ? null : id); + persist(settings.withMd3(!id.equals("classic"))); + showRestartNotice(); + }); + list.addView(item); + } + ScrollView scroll = new ScrollView(this); + scroll.addView(list, new ScrollView.LayoutParams(-1, -2)); + shown[0] = bubbleDialog("Оформление", scroll, null, null); + } + /** Several photos in one comment (TikTok's own picker, up to nine); a choice about the app, so it has its own store. */ private View commentPhotosRow() { Md3Switch toggle = new Md3Switch(this, palette); @@ -1547,6 +1638,8 @@ public final class LihonTSettingsActivity extends Activity { deleteRecursively(ext); } } catch (Throwable ignored) {} + // the app's own restart is not the "Clear cache" of Android: DEBUG must survive it + lihont.two.look.DebugMode.keepMarker(this); } private static boolean deleteRecursively(File file) { diff --git a/src/lihont/two/settings/Md3.java b/src/lihont/two/settings/Md3.java index 3869928..5e65b66 100644 --- a/src/lihont/two/settings/Md3.java +++ b/src/lihont/two/settings/Md3.java @@ -181,6 +181,23 @@ public final class Md3 { Color.rgb(254, 44, 85), Color.rgb(255, 255, 255), Color.rgb(255, 225, 230), Color.rgb(120, 10, 30)); + /** The palette of a theme that brings its own colours (see ThemeSpec): a few colours spread over the 26 roles. */ + static Palette themed(ThemeSpec t) { + int high = Color.rgb(223, 223, 223); + return new Palette(t.dark, false, + t.accent, t.onAccent, + t.accent, t.onAccent, + t.card, t.text, + t.accent, t.onAccent, + t.card, t.text, + t.page, t.card, t.card, + t.card, t.card, high, + t.text, t.muted, + t.line, t.line, + Color.rgb(128, 0, 0), Color.WHITE, + Color.rgb(255, 200, 200), Color.rgb(128, 0, 0)); + } + public static Palette dark() { return DARK; } public static Palette light() { return LIGHT; } @@ -262,7 +279,8 @@ public final class Md3 { /** Resolves the scheme from the saved theme, falling back to the system night mode and dynamic Monet colors. */ public static Palette palette(Context context, ModSettings.Theme theme) { - return palette(context, theme, SettingsHost.accent(), SettingsHost.accentHue(), SettingsHost.amoled()); + return ThemeEngine.palette(context, + palette(context, theme, SettingsHost.accent(), SettingsHost.accentHue(), SettingsHost.amoled())); } /** The scheme for an explicit accent and black-surface choice. */ @@ -284,9 +302,9 @@ public final class Md3 { * settings of the running process and changes after a restart. */ public static Palette palette(Context context, ModSettings settings) { - return settings.md3() - ? palette(context, settings.theme(), settings.accent(), settings.accentHue(), settings.amoled()) - : classic(context, settings.theme()); + if (!settings.md3()) return classic(context, settings.theme()); + return ThemeEngine.palette(context, + palette(context, settings.theme(), settings.accent(), settings.accentHue(), settings.amoled())); } /** The primary colour of an accent, for the swatch that shows it. */ @@ -481,8 +499,22 @@ public final class Md3 { plain.setPadding(dp(context, 20), dp(context, 20), dp(context, 20), dp(context, 10)); return plain; } - TextView view = text(context, value, LABEL_LARGE, true, palette.primary); - view.setPadding(dp(context, 24), dp(context, 12), dp(context, 24), dp(context, 4)); + ThemeSpec theme = ThemeEngine.active(context); + if (theme != null && theme.titleBars) { + // a title bar across the page, like the caption of a window + TextView bar = text(context, value, 14f, true, theme.onAccent); + bar.setBackground(ThemeEngine.titleBar(theme)); + bar.setPadding(dp(context, 10), dp(context, 5), dp(context, 10), dp(context, 5)); + LinearLayout.LayoutParams barParams = new LinearLayout.LayoutParams(-1, -2); + barParams.leftMargin = dp(context, 16); + barParams.rightMargin = dp(context, 16); + barParams.topMargin = dp(context, 12); + bar.setLayoutParams(barParams); + return bar; + } + boolean sticker = theme != null; + TextView view = text(context, value, sticker ? 16f : LABEL_LARGE, true, sticker ? palette.onSurface : palette.primary); + view.setPadding(dp(context, 24), dp(context, sticker ? 16 : 12), dp(context, 24), dp(context, sticker ? 8 : 4)); return view; } @@ -513,9 +545,17 @@ public final class Md3 { public static LinearLayout card(Context context, Palette palette) { LinearLayout card = new LinearLayout(context); card.setOrientation(LinearLayout.VERTICAL); - card.setBackground(shape(palette.surfaceContainer, palette.classic ? SHAPE_SMALL : SHAPE_EXTRA_LARGE, context)); - if (android.os.Build.VERSION.SDK_INT >= 21) { - card.setClipToOutline(true); + ThemeSpec theme = palette.classic ? null : ThemeEngine.active(context); + if (theme != null) { + // the active theme draws the card; a hard shadow lives inside the drawable, so the card keeps room for it + card.setBackground(ThemeEngine.card(context, theme, palette)); + int room = dp(context, ThemeEngine.shadowDp(theme)); + card.setPadding(0, 0, room, room); + } else { + card.setBackground(shape(palette.surfaceContainer, palette.classic ? SHAPE_SMALL : SHAPE_EXTRA_LARGE, context)); + if (android.os.Build.VERSION.SDK_INT >= 21) { + card.setClipToOutline(true); + } } LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(-1, -2); params.leftMargin = dp(context, 16); @@ -722,6 +762,13 @@ public final class Md3 { button.setMinimumHeight(dp(context, 40)); button.setClickable(true); button.setFocusable(true); + ThemeSpec theme = palette.classic ? null : ThemeEngine.active(context); + if (theme != null && theme.bevel) { + button.setBackground(new BevelDrawable(palette.surfaceContainerHigh, true, Math.max(1, dp(context, 1)))); + button.setTextColor(palette.onSurface); + button.setMinimumHeight(dp(context, 30)); + return button; + } button.setBackground(stateLayer(context, SHAPE_FULL, stateLayerColor(palette.primary))); return button; } diff --git a/src/lihont/two/settings/Md3Switch.java b/src/lihont/two/settings/Md3Switch.java index 749198c..26ddf6c 100644 --- a/src/lihont/two/settings/Md3Switch.java +++ b/src/lihont/two/settings/Md3Switch.java @@ -31,6 +31,8 @@ public final class Md3Switch extends View implements Checkable { private final int outline; private final int stateLayer; private final boolean classic; + private final boolean sticker; + private final boolean tickBox; private final float trackWidthDp; private final float trackHeightDp; private final float handleOffDp; @@ -45,6 +47,9 @@ public final class Md3Switch extends View implements Checkable { public Md3Switch(Context context, Md3.Palette palette) { super(context); classic = palette.classic; + ThemeSpec theme = classic ? null : ThemeEngine.active(context); + sticker = theme != null && !theme.tickBox; + tickBox = theme != null && theme.tickBox; if (classic) { // Serena 1.2: a 44x26dp track with a plain white 20dp handle that only changes sides trackWidthDp = 44f; @@ -114,11 +119,19 @@ public final class Md3Switch extends View implements Checkable { } @Override protected void onMeasure(int widthSpec, int heightSpec) { + if (tickBox) { + setMeasuredDimension(dp(20f) + getPaddingLeft() + getPaddingRight(), dp(20f) + getPaddingTop() + getPaddingBottom()); + return; + } setMeasuredDimension(dp(trackWidthDp) + getPaddingLeft() + getPaddingRight(), dp(trackHeightDp) + getPaddingTop() + getPaddingBottom()); } @Override protected void onDraw(Canvas canvas) { + if (tickBox) { + drawTickBox(canvas); + return; + } float height = getHeight() - getPaddingTop() - getPaddingBottom(); float width = Math.min(getWidth() - getPaddingLeft() - getPaddingRight(), dp(trackWidthDp)); float left = getPaddingLeft() + (getWidth() - getPaddingLeft() - getPaddingRight() - width) / 2f; @@ -130,7 +143,13 @@ public final class Md3Switch extends View implements Checkable { paint.setColor(blend(trackOff, trackOn, progress)); canvas.drawRoundRect(track, radius, radius, paint); - if (!classic && progress < 1f) { + if (sticker) { + // the sticker look: a thick ink outline on the track and on the handle, on and off alike + paint.setStyle(Paint.Style.STROKE); + paint.setStrokeWidth(Math.max(2f, dp(2f))); + paint.setColor(outline); + canvas.drawRoundRect(track, radius, radius, paint); + } else if (!classic && progress < 1f) { paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(Math.max(1f, dp(1f))); paint.setColor(withAlpha(outline, (int) (255 * (1f - progress)))); @@ -147,6 +166,12 @@ public final class Md3Switch extends View implements Checkable { paint.setStyle(Paint.Style.FILL); paint.setColor(blend(handleOff, handleOn, progress)); canvas.drawCircle(handleCenter, track.centerY(), handleRadius, paint); + if (sticker) { + paint.setStyle(Paint.Style.STROKE); + paint.setStrokeWidth(Math.max(2f, dp(2f))); + paint.setColor(outline); + canvas.drawCircle(handleCenter, track.centerY(), handleRadius, paint); + } } @Override protected void onDetachedFromWindow() { @@ -154,6 +179,26 @@ public final class Md3Switch extends View implements Checkable { super.onDetachedFromWindow(); } + /** A sunken white square with a black tick when on: the check box of Windows 95. */ + private void drawTickBox(Canvas canvas) { + int size = Math.min(getWidth() - getPaddingLeft() - getPaddingRight(), getHeight() - getPaddingTop() - getPaddingBottom()); + int left = getPaddingLeft() + (getWidth() - getPaddingLeft() - getPaddingRight() - size) / 2; + int top = getPaddingTop() + (getHeight() - getPaddingTop() - getPaddingBottom() - size) / 2; + BevelDrawable box = new BevelDrawable(android.graphics.Color.WHITE, false, Math.max(1, dp(1f))); + box.setBounds(left, top, left + size, top + size); + box.draw(canvas); + if (progress > 0.5f) { + paint.setStyle(Paint.Style.STROKE); + paint.setStrokeWidth(Math.max(2f, dp(2f))); + paint.setStrokeCap(Paint.Cap.SQUARE); + paint.setColor(android.graphics.Color.BLACK); + float u = size / 10f; + canvas.drawLine(left + 2.5f * u, top + 5f * u, left + 4.2f * u, top + 7f * u, paint); + canvas.drawLine(left + 4.2f * u, top + 7f * u, left + 7.8f * u, top + 2.8f * u, paint); + paint.setStrokeCap(Paint.Cap.BUTT); + } + } + private int dp(float value) { return Md3.dp(getContext(), value); } private static int blend(int from, int to, float amount) { @@ -173,4 +218,4 @@ public final class Md3Switch extends View implements Checkable { android.graphics.Color.blue(color)); } } - + diff --git a/src/lihont/two/settings/PluginSettings.java b/src/lihont/two/settings/PluginSettings.java index 0146125..fdc01ce 100644 --- a/src/lihont/two/settings/PluginSettings.java +++ b/src/lihont/two/settings/PluginSettings.java @@ -121,7 +121,7 @@ final class PluginSettings { PluginRegistry.setEnabled(activity, entry.id, uid, value); rebuild.run(); }); - String detail = "v" + entry.plugin.version + " · " + entry.plugin.author + " · правил: " + entry.plugin.rules.size() + String detail = "v" + entry.plugin.version + " · " + entry.plugin.author + " · " + (entry.plugin.rules.isEmpty() && entry.plugin.theme != null ? "тема оформления" : "правил: " + entry.plugin.rules.size()) + (entry.approved ? "" : " · изменён, нужна проверка") + (entry.approved ? accountsNote(entry) : ""); LinearLayout row = Md3.listItem(activity, palette, avatar(letter), entry.plugin.name, detail, toggle, true); diff --git a/src/lihont/two/settings/ThemeEngine.java b/src/lihont/two/settings/ThemeEngine.java new file mode 100644 index 0000000..9106a96 --- /dev/null +++ b/src/lihont/two/settings/ThemeEngine.java @@ -0,0 +1,122 @@ +package lihont.two.settings; + +import android.content.Context; +import android.graphics.Color; +import android.graphics.drawable.Drawable; +import android.graphics.drawable.GradientDrawable; +import android.graphics.drawable.LayerDrawable; + +/** + * Which theme is on and how a theme draws the parts of the settings: cards, title bars, buttons and tick boxes. + * + * The choice is stored on its own (a choice about the look, not part of the settings model) and read each time a screen is + * built. A theme paints; it never moves, hides or adds a control. + */ +public final class ThemeEngine { + private static final String PREFS = "lihont_style"; + private static final String KEY = "theme"; + private static final String LEGACY_STICKER = "sticker"; + + private ThemeEngine() {} + + /** The theme that is on, or null for the base look (Material 3, or plain TikTok when Material 3 is off). */ + static ThemeSpec active(Context context) { + try { + android.content.SharedPreferences prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE); + String id = prefs.getString(KEY, null); + if (id == null && prefs.getBoolean(LEGACY_STICKER, false)) id = "sticker"; + if (id == null) return null; + return id.startsWith("plugin:") ? pluginTheme(context, id.substring(7)) : ThemeSpec.byId(id); + } catch (RuntimeException unreadable) { + return null; + } + } + + private static String cachedId; + private static int cachedVersion = -1; + private static ThemeSpec cachedSpec; + + /** The theme of an installed and approved plugin; null when the plugin is gone, unreadable or has no theme. */ + private static synchronized ThemeSpec pluginTheme(Context context, String pluginId) { + int version = lihont.two.plugin.PluginRegistry.version(); + if (pluginId.equals(cachedId) && version == cachedVersion) return cachedSpec; + ThemeSpec spec = null; + lihont.two.plugin.PluginRegistry.Entry entry = lihont.two.plugin.PluginRegistry.find(context, pluginId); + if (entry != null && entry.plugin != null && entry.approved && entry.plugin.theme != null) { + spec = ThemeSpec.fromPlugin(pluginId, entry.plugin.theme); + } + cachedId = pluginId; + cachedVersion = version; + cachedSpec = spec; + return spec; + } + + /** @param id a theme id, or null for the base look */ + static void set(Context context, String id) { + android.content.SharedPreferences.Editor edit = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit(); + edit.remove(LEGACY_STICKER); + if (id == null) edit.remove(KEY); + else edit.putString(KEY, id); + edit.apply(); + } + + /** Back to the base look: no theme. Public for the recovery mode (DebugMode). */ + public static void reset(Context context) { + set(context, null); + } + + /** True when the active theme draws square corners (Windows 95): skins elsewhere in TikTok then drop their rounding. */ + public static boolean square(Context context) { + ThemeSpec spec = active(context); + return spec != null && spec.ownColors && spec.radiusDp <= 0f; + } + + /** The colour of a thin edge line for a square theme, drawn around tonal fills so they read as panels. */ + public static int edge(Context context) { + ThemeSpec spec = active(context); + return spec != null && spec.ownColors ? spec.line : 0; + } + + /** The palette for the active theme when it brings its own colours; otherwise the palette that was passed in. */ + static Md3.Palette palette(Context context, Md3.Palette base) { + ThemeSpec spec = active(context); + if (spec == null || !spec.ownColors) return base; + Md3.Palette built = spec.palette; + if (built == null) { + built = Md3.themed(spec); + spec.palette = built; + } + return built; + } + + // ---- drawing ----------------------------------------------------------- + + /** A card: a raised bevel, or a face with an ink outline and a hard shadow, depending on the theme. */ + static Drawable card(Context context, ThemeSpec spec, Md3.Palette palette) { + if (spec.bevel) return new BevelDrawable(palette.surfaceContainerHigh, true, Math.max(1, Md3.dp(context, 1))); + int ink = palette.onSurface; + int shadowColor = palette.dark ? Color.BLACK : ink; + int offset = Md3.dp(context, spec.shadowDp); + GradientDrawable face = spec.outlineDp > 0f + ? Md3.outlined(palette.surfaceContainerHigh, ink, spec.outlineDp, spec.radiusDp, context) + : Md3.shape(palette.surfaceContainerHigh, spec.radiusDp, context); + if (offset <= 0) return face; + GradientDrawable shadow = Md3.shape(shadowColor, spec.radiusDp, context); + LayerDrawable layers = new LayerDrawable(new Drawable[] {shadow, face}); + layers.setLayerInset(0, offset, offset, 0, 0); + layers.setLayerInset(1, 0, 0, offset, offset); + return layers; + } + + /** The room a card keeps on its right and bottom for the shadow, in dp. */ + static int shadowDp(ThemeSpec spec) { + return spec.bevel ? 0 : spec.shadowDp; + } + + /** A title bar: a colour that runs from left to right, with square corners. */ + static Drawable titleBar(ThemeSpec spec) { + GradientDrawable bar = new GradientDrawable(GradientDrawable.Orientation.LEFT_RIGHT, + new int[] {spec.titleFrom, spec.titleTo}); + return bar; + } +} diff --git a/src/lihont/two/settings/ThemeSpec.java b/src/lihont/two/settings/ThemeSpec.java new file mode 100644 index 0000000..3d68993 --- /dev/null +++ b/src/lihont/two/settings/ThemeSpec.java @@ -0,0 +1,93 @@ +package lihont.two.settings; + +import android.graphics.Color; + +/** + * A look for the mod's screens, described as plain data: colours, how corners and lines are drawn, how a switch looks. + * + * A theme paints and never changes what is on the screen: it cannot move, hide or add a control, so a theme can make the + * settings ugly but never unusable or dangerous. Built-in themes live here; a theme file in a plugin will fill the same + * fields. + */ +final class ThemeSpec { + final String id; + final String name; + /** True when the theme brings its own colours; false when it keeps the colours of the Material 3 palette. */ + final boolean ownColors; + final boolean dark; + final int page; + final int card; + final int text; + final int muted; + final int accent; + final int onAccent; + final int line; + final int titleFrom; + final int titleTo; + final float radiusDp; + /** Width of the ink outline of a card, in dp; 0 for none. */ + final float outlineDp; + /** Offset of the hard shadow behind a card, in dp; 0 for none. */ + final int shadowDp; + /** Draw raised and sunken 3D edges (the look of Windows 95) instead of flat outlines. */ + final boolean bevel; + /** A switch is drawn as a square tick box instead of a pill. */ + final boolean tickBox; + /** Section headers and the top bar are drawn as a coloured title bar with light text. */ + final boolean titleBars; + /** The Material 3 palette made from this theme, built the first time it is asked for and then reused. */ + Md3.Palette palette; + + private ThemeSpec(String id, String name, boolean ownColors, boolean dark, int page, int card, int text, int muted, + int accent, int onAccent, int line, int titleFrom, int titleTo, float radiusDp, float outlineDp, int shadowDp, + boolean bevel, boolean tickBox, boolean titleBars) { + this.id = id; + this.name = name; + this.ownColors = ownColors; + this.dark = dark; + this.page = page; + this.card = card; + this.text = text; + this.muted = muted; + this.accent = accent; + this.onAccent = onAccent; + this.line = line; + this.titleFrom = titleFrom; + this.titleTo = titleTo; + this.radiusDp = radiusDp; + this.outlineDp = outlineDp; + this.shadowDp = shadowDp; + this.bevel = bevel; + this.tickBox = tickBox; + this.titleBars = titleBars; + } + + /** Thick outlines and hard shadows on the colours of the current Material 3 palette. */ + static final ThemeSpec STICKER = new ThemeSpec("sticker", "Стикеры", false, false, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 22f, 2.5f, 5, false, false, false); + + /** Grey windows on a teal desktop, raised and sunken edges, navy title bars and tick boxes. */ + static final ThemeSpec WIN95 = new ThemeSpec("win95", "Windows 95", true, false, + Color.rgb(0, 128, 128), Color.rgb(192, 192, 192), Color.BLACK, Color.rgb(64, 64, 64), + Color.rgb(0, 0, 128), Color.WHITE, Color.rgb(128, 128, 128), Color.rgb(0, 0, 128), Color.rgb(16, 132, 208), + 0f, 0f, 0, true, true, true); + + static final ThemeSpec[] BUILT_IN = {STICKER, WIN95}; + + /** The theme a plugin brings (right ui.theme): the same fields, read from its checked plugin.json. */ + static ThemeSpec fromPlugin(String pluginId, lihont.two.plugin.ThemeData data) { + return new ThemeSpec("plugin:" + pluginId, data.name + " (плагин)", true, data.dark, + 0xFF000000 | data.page, 0xFF000000 | data.card, 0xFF000000 | data.text, 0xFF000000 | data.muted, + 0xFF000000 | data.accent, 0xFF000000 | data.onAccent, 0xFF000000 | data.line, + 0xFF000000 | data.titleFrom, 0xFF000000 | data.titleTo, + data.radius, data.outline, data.shadow, data.bevel, data.tickBox, data.titleBars); + } + + /** The built-in theme with this id, or null (Material 3 and plain TikTok are not themes: they are the two base looks). */ + static ThemeSpec byId(String id) { + for (ThemeSpec spec : BUILT_IN) { + if (spec.id.equals(id)) return spec; + } + return null; + } +} diff --git a/src/web/assets/site/plugin_howto.svg b/src/web/assets/site/plugin_howto.svg new file mode 100644 index 0000000..eb0df28 --- /dev/null +++ b/src/web/assets/site/plugin_howto.svg @@ -0,0 +1,10 @@ + + + +Свой плагин для LihonT + +night.pyfrom lihont_ltp import *plugin = Plugin("Тихая ночь", author="Вася")plugin.video(night & hashtag("fyp"), hide)plugin.save()1. Напиши правило, как предложениеВидео с #fyp ночью скрыть: три строки на Python +$ python night.pyЗащитник: Обратите внимание• Скрывает видео из ленты по условиям правилПлагин не может: читать сообщения и пароли, запускать код.Готово: vasya.tihaya-noch.ltp.ltp2. Запусти: защитник покажет всёЧто делает каждое правило и насколько ему можно доверять +ltp phonevasya.tihaya-noch.ltpDownload/ltp3. Отправь на телефон по проводуКоманда ltp phone кладёт файл в Download/ltp +Установить «Тихая ночь»?Защитник: Обратите вниманиеПрава: скрывать видео по правиламОтменаСтавьПлагин включён ✓4. Установи и включиПеред установкой видно права, правила и вердикт защитника + \ No newline at end of file diff --git a/src/web/index.html b/src/web/index.html index b874f7a..f012d79 100644 --- a/src/web/index.html +++ b/src/web/index.html @@ -4,376 +4,419 @@ - - - - - + + + + + - LihonT — TikTok в стиле Material 3 + LihonT 2 · Luna: TikTok в стиле Material 3 - - + - + + -
-
- - - - LihonT - -