LihonT 2 Serena alpha 2

Plugin icons for the feed buttons (right ui.icons: like, comment, collect, share), preview cards that a theme author
attaches and the list of looks shows before a theme is picked, the sample plugins lihont.icons-sticker, lihont.theme-win95 and
lihont.theme-sunset with their pictures, docs, SDK, skill and tests for all of it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
cheb0chik
2026-11-02 13:08:56 +03:00
parent 8b7fa5ff57
commit 38e7b2551e
33 changed files with 976 additions and 27 deletions

View File

@@ -81,6 +81,7 @@ python scripts/make_ltp.py plugins/my.plugin
| `feed.like` | Ставить лайк видео на главной ленте, когда вы нажимаете на картинку плагина. | | `feed.like` | Ставить лайк видео на главной ленте, когда вы нажимаете на картинку плагина. |
| `net.download` | Скачивать картинки и звуки с сайтов, названных в `net` (см. ниже). Нужен ещё переключатель «Интернет» у плагина. | | `net.download` | Скачивать картинки и звуки с сайтов, названных в `net` (см. ниже). Нужен ещё переключатель «Интернет» у плагина. |
| `ui.theme` | Менять оформление экранов мода и TikTok: цвета, формы, рамки (см. «Тема»). Ничего не скрывает и не двигает. | | `ui.theme` | Менять оформление экранов мода и TikTok: цвета, формы, рамки (см. «Тема»). Ничего не скрывает и не двигает. |
| `ui.icons` | Менять картинки кнопок справа в ленте: лайк, комментарии, избранное, поделиться (см. «Значки кнопок»). Кнопки остаются на месте и работают как раньше. |
## Правило ## Правило
@@ -222,12 +223,36 @@ python scripts/make_ltp.py plugins/my.plugin
| `bevel` | Объёмные рамки, как у окон Windows 95. | | `bevel` | Объёмные рамки, как у окон Windows 95. |
| `tick_box` | Переключатели рисуются квадратной галочкой. | | `tick_box` | Переключатели рисуются квадратной галочкой. |
| `title_bars` | Заголовки разделов становятся цветной полосой. | | `title_bars` | Заголовки разделов становятся цветной полосой. |
| `preview` | До четырёх своих картинок-карточек (png, gif или webp из `assets/`). Их видно в списке «Оформление», пока тема ещё не выбрана: так автор показывает, как она выглядит. |
Защитник проверяет контраст текста на карточках и на акценте. Если он ниже 3.0, он честно напишет, что текст будет плохо Защитник проверяет контраст текста на карточках и на акценте. Если он ниже 3.0, он честно напишет, что текст будет плохо
читаться, но тему не запретит. Если тема всё-таки сломала экран, вернуть вид можно режимом DEBUG (Настройки мода → читаться, но тему не запретит. Если тема всё-таки сломала экран, вернуть вид можно режимом DEBUG (Настройки мода →
«Восстановление»): включите его заранее, потом очистите кэш приложения в настройках Android. Выбирается тема в настройках «Восстановление»): включите его заранее, потом очистите кэш приложения в настройках Android. Выбирается тема в настройках
мода, строка «Оформление». В SDK: `plugin.theme("Закат", page="#2b1d3a", card="#3d2b52", text="#fbe9ff", accent="#ff8a5b")`. мода, строка «Оформление». В SDK: `plugin.theme("Закат", page="#2b1d3a", card="#3d2b52", text="#fbe9ff", accent="#ff8a5b")`.
## Значки кнопок (`icons`)
Плагин с правом `ui.icons` может поменять картинки на кнопках справа в ленте. Меняется только картинка: кнопки не двигаются,
не пропадают и делают то же, что и раньше. Правила в таком плагине не нужны.
```json
"permissions": ["ui.icons"],
"icons": {"like": "heart.png", "comment": "bubble.png", "collect": "star.png", "share": "plane.png"}
```
| Кнопка | Что это |
| --- | --- |
| `like` | Лайк. |
| `comment` | Комментарии. |
| `collect` | Избранное. |
| `share` | Поделиться. |
Нужна хотя бы одна кнопка. Файлы лежат в `assets/` плагина (png, gif или webp, до 400 КБ, как и остальные картинки) и входят в
хэш. Кнопки мод находит по тому, что они говорят людям с экранным диктором («Поставить лайк», «Прочитать или оставить
комментарии», «Добавьте это видео в Избранное», «Поделиться видео»), поэтому это работает, пока TikTok не меняет эти подписи.
Если плагин выключить, TikTok получает свои картинки обратно. В SDK: `plugin.icons(like="heart.png", comment="bubble.png")`;
пример: `plugins/lihont.icons-sticker`.
## Как установить ## Как установить
В настройках мода откройте раздел «Плагины» → «Установить плагин» → выберите `.ltp`. Мод покажет, кто автор, какие В настройках мода откройте раздел «Плагины» → «Установить плагин» → выберите `.ltp`. Мод покажет, кто автор, какие

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.2 KiB

View File

@@ -0,0 +1,17 @@
{
"ltp": 1,
"id": "lihont.icons-sticker",
"name": "Стикерные значки",
"version": "1.0",
"author": "LihonT",
"description": "Лайк, комментарии, избранное и «поделиться» в ленте: яркие наклейки с толстым контуром.",
"license": "VCBFU-2",
"ai": ["Claude Sonnet 5.5 (Claude Code)"],
"permissions": ["ui.icons"],
"icons": {
"like": "heart.png",
"comment": "bubble.png",
"collect": "star.png",
"share": "plane.png"
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

View File

@@ -6,8 +6,12 @@
"author": "LihonT", "author": "LihonT",
"description": "Тёмно-лиловый фон, тёплый оранжевый акцент, толстые контуры и мягкие тени.", "description": "Тёмно-лиловый фон, тёплый оранжевый акцент, толстые контуры и мягкие тени.",
"license": "VCBFU-2", "license": "VCBFU-2",
"ai": ["Claude Sonnet 5.5 (Claude Code)"], "ai": [
"permissions": ["ui.theme"], "Claude Sonnet 5.5 (Claude Code)"
],
"permissions": [
"ui.theme"
],
"theme": { "theme": {
"name": "Закат", "name": "Закат",
"dark": true, "dark": true,
@@ -20,6 +24,10 @@
"line": "#fbe9ff", "line": "#fbe9ff",
"radius": 20, "radius": 20,
"outline": 2, "outline": 2,
"shadow": 4 "shadow": 4,
"preview": [
"preview1.png",
"preview2.png"
]
} }
} }

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

View File

@@ -6,8 +6,12 @@
"author": "LihonT", "author": "LihonT",
"description": "Серые окна на бирюзовом рабочем столе, объёмные рамки, синие заголовки и квадратные галочки.", "description": "Серые окна на бирюзовом рабочем столе, объёмные рамки, синие заголовки и квадратные галочки.",
"license": "VCBFU-2", "license": "VCBFU-2",
"ai": ["Claude Sonnet 5.5 (Claude Code)"], "ai": [
"permissions": ["ui.theme"], "Claude Sonnet 5.5 (Claude Code)"
],
"permissions": [
"ui.theme"
],
"theme": { "theme": {
"name": "Windows 95", "name": "Windows 95",
"page": "#008080", "page": "#008080",
@@ -22,6 +26,10 @@
"radius": 0, "radius": 0,
"bevel": true, "bevel": true,
"tick_box": true, "tick_box": true,
"title_bars": true "title_bars": true,
"preview": [
"preview1.png",
"preview2.png"
]
} }
} }

View File

@@ -0,0 +1,276 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
LihonT 2 «Serena alpha 2» promo in the sticker style: 1080x1920, 30 fps, about 29 seconds.
New in it: the plugin icons for the feed buttons (white TikTok icons turn into sticker ones), the preview cards an author attaches
to a theme and the list of looks that shows them, the five lines that bring both, and what plugins can never get.
Everything is drawn here; the sticker icons and the preview cards are the real pictures of the sample plugins.
usage (from the repository root):
py -X utf8 -B scripts/make_serena_promo2.py # work/serena-promo/serena_promo2.mp4
py -X utf8 -B scripts/make_serena_promo2.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_promo2.mp4"
AUDIO = ROOT / "work" / "serena-promo" / "serena_audio2.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.2, CREAM),
("icons", 3.2, 9.4, (190, 240, 220)),
("cards", 9.4, 15.6, (215, 200, 255)),
("author", 15.6, 21.0, (255, 236, 150)),
("safe", 21.0, 25.4, (255, 205, 225)),
("outro", 25.4, 29.6, (255, 196, 176)),
]
DURATION = SCENES[-1][2]
FRAMES = int(round(DURATION * FPS))
WIPE = V.WIPE
ICONS = ROOT / "plugins" / "lihont.icons-sticker" / "assets"
CARDS = ROOT / "plugins" / "lihont.theme-sunset" / "assets"
_extra: dict = {}
def extra():
if not _extra:
_extra["icons"] = {n: Image.open(ICONS / (n + ".png")).convert("RGBA").resize((150, 150), Image.Resampling.LANCZOS)
for n in ("heart", "bubble", "star", "plane")}
_extra["cards"] = [Image.open(CARDS / ("preview%d.png" % n)).convert("RGBA") for n in (1, 2)]
return _extra
def tiktok_icon(layer, kind, cx, cy):
"""The plain white icons of TikTok's feed: a heart, a bubble with dots, a bookmark and an arrow."""
d = ImageDraw.Draw(layer, "RGBA")
w = (255, 255, 255, 255)
if kind == "heart":
d.ellipse([cx - 62, cy - 52, cx, cy + 10], fill=w)
d.ellipse([cx, cy - 52, cx + 62, cy + 10], fill=w)
d.polygon([(cx - 60, cy - 14), (cx + 60, cy - 14), (cx, cy + 62)], fill=w)
elif kind == "bubble":
d.rounded_rectangle([cx - 62, cy - 50, cx + 62, cy + 34], radius=40, fill=w)
d.polygon([(cx - 30, cy + 30), (cx - 44, cy + 62), (cx + 6, cy + 32)], fill=w)
for dx in (-30, 0, 30):
d.ellipse([cx + dx - 8, cy - 18, cx + dx + 8, cy - 2], fill=(150, 150, 160, 255))
elif kind == "star":
d.polygon([(cx - 44, cy - 62), (cx + 44, cy - 62), (cx + 44, cy + 62), (cx, cy + 28), (cx - 44, cy + 62)], fill=w)
else:
d.polygon([(cx - 66, cy + 6), (cx + 8, cy - 58), (cx + 8, cy - 22), (cx + 66, cy - 22), (cx + 66, cy + 40),
(cx + 8, cy + 40), (cx + 8, cy + 62)], fill=w)
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=24)
V.title(layer, max(0.0, lt - 0.9), "Serena alpha 2", "значки и карточки тем", y=1230)
V.label(layer, W / 2, 1480, "плагины умеют больше", pop(lt, 1.8), size=44, fill=YELLOW)
def scene_icons(layer, lt):
V.title(layer, lt, "Свои значки", "кнопки ленты, как вам хочется")
d = ImageDraw.Draw(layer, "RGBA")
# a feed screen: dark panel with the four buttons on the right
box = (150, 480, 930, 1540)
d.rounded_rectangle([box[0] + 10, box[1] + 10, box[2] + 10, box[3] + 10], radius=48, fill=INK + (255,))
d.rounded_rectangle(box, radius=48, fill=(46, 34, 66, 255), outline=INK + (255,), width=6)
for i in range(0, 760, 40):
d.line([(box[0] + 6, box[1] + 20 + i * 1.3), (box[2] - 6, box[1] + 90 + i * 1.3)], fill=(60, 44, 84, 255), width=3)
P.draw_text(layer, (230, 1470), "@автор #видео", 36, (255, 255, 255, 220), bold=False, anchor="lm")
names = ("heart", "bubble", "star", "plane")
counts = ("26,9 тыс.", "574", "5099", "8616")
for n, name in enumerate(names):
cx, cy = 810, 640 + n * 215
swapped = lt > 2.0 + n * 0.45
if swapped:
k = clamp(pop(lt, 2.0 + n * 0.45, 0.5), 0, 1.15)
V.place(layer, extra()["icons"][name], cx, cy, k)
V.ring(layer, cx, cy, lt, 2.0 + n * 0.45, color=MINT, size=110)
else:
tiktok_icon(layer, name, cx, cy)
P.draw_text(layer, (cx, cy + 92), counts[n], 30, (255, 255, 255, 255), anchor="mm")
V.burst(layer, 810, 860, lt, 2.0, seed=7, count=36, power=800)
V.label(layer, W / 2, 1640, "plugin.icons(like=\"heart.png\", ...)", pop(lt, 0.8), size=34, fill=WHITE)
V.label(layer, W / 2, 1760, "Кнопки на местах и работают как раньше", pop(lt, 3.6), size=34, fill=YELLOW)
def scene_cards(layer, lt):
V.title(layer, lt, "Карточки тем", "автор показывает, как выглядит")
d = ImageDraw.Draw(layer, "RGBA")
x0, x1, y0 = 90, 990, 470
V.sticker(layer, (x0, y0, x1, 1560), WHITE, radius=44)
P.draw_text(layer, (x0 + 50, y0 + 60), "Оформление", 46, INK + (255,), anchor="lm")
rows = [("Material 3", "Мягкие скругления"), ("Windows 95", "Серые окна, объёмные кнопки"),
("Закат (плагин)", "Тема из плагина, автор Вася")]
y = y0 + 130
for n, (name, hint) in enumerate(rows):
chosen = n == 2 and lt > 1.6
h = 150 if n < 2 else (540 if chosen else 150)
fill = (255, 236, 150) if chosen else (255, 255, 255)
d.rounded_rectangle([x0 + 30, y, x1 - 30, y + h], radius=30, fill=fill + (255,), outline=INK + (255,), width=4)
P.draw_text(layer, (x0 + 70, y + 40), name + (" ✓" if chosen and lt > 3.6 else ""), 42, INK + (255,), anchor="lm")
P.draw_text(layer, (x0 + 70, y + 98), hint, 30, (90, 80, 110, 255), bold=False, anchor="lm")
if chosen:
# the author's cards slide in from the right, one after the other, and the row scrolls sideways
slide = ease_out_cubic((lt - 2.0) / 0.9)
shift = -math.sin(clamp((lt - 3.4) / 1.6) * math.pi) * 36
for i, card in enumerate(extra()["cards"]):
cw, ch = 360, 270
c = card.resize((cw, ch), Image.Resampling.LANCZOS)
cx = x0 + 70 + i * (cw + 24) + (1 - slide) * 700 + shift
if cx + cw < x1 - 40 or cx < x1 - 100:
layer.alpha_composite(c, (int(cx), int(y + 170)))
d.rounded_rectangle([cx, y + 170, cx + cw, y + 170 + ch], radius=10, outline=INK + (255,), width=4)
V.ring(layer, x1 - 120, y + 60, lt, 1.6, color=INK, size=120)
y += h + 24
V.label(layer, W / 2, 1650, "Карточки кладёт сам автор", pop(lt, 0.9), size=38, fill=PINK)
V.label(layer, W / 2, 1760, "Видно ещё до выбора", pop(lt, 1.4), size=36, fill=WHITE)
CODE = [
'plugin = Plugin("Закат", author="Вася")',
"plugin.theme(",
' page="#2b1d3a", card="#3d2b52",',
' text="#fbe9ff", accent="#ff8a5b",',
' preview=["card1.png", "card2.png"])',
'plugin.icons(like="heart.png")',
"plugin.save()",
]
def scene_author(layer, lt):
V.title(layer, lt, "Как это сделать", "один файл на Python")
d = ImageDraw.Draw(layer, "RGBA")
box = (80, 470, 1000, 1110)
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([120 + i * 44, 505, 150 + i * 44, 535], fill=c + (255,))
total = sum(len(t) + 1 for t in CODE)
shown = int(clamp((lt - 0.5) / 3.0) * total)
y = 590
for line in CODE:
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, (120, y), part, 36, color, bold=False, anchor="lm")
y += 66
if shown < 0:
break
V.label(layer, 330, 1240, "ui.theme", pop(lt, 3.6), size=48, fill=SKY)
V.label(layer, 720, 1240, "ui.icons", pop(lt, 3.9), size=48, fill=MINT)
V.label(layer, W / 2, 1400, "Права видно в окне установки", pop(lt, 4.2), size=36, fill=WHITE)
V.label(layer, W / 2, 1520, "Защитник проверяет контраст", pop(lt, 4.5), size=36, fill=YELLOW)
def scene_safe(layer, lt):
V.title(layer, lt, "Безопасно", "плагины закрыты от этого навсегда")
items = [("пароли и коды входа", CORAL), ("токены и ключи", PINK), ("куки и сессии", YELLOW), ("тексты чатов", SKY),
("запуск кода", MINT)]
for n, (text, color) in enumerate(items):
k = ease_out_back((lt - 0.4 - n * 0.3) / 0.5)
x_off = (1 - k) * (900 if n % 2 else -900)
y = 600 + n * 190
V.sticker(layer, (110 + x_off, y - 70, 970 + x_off, y + 70), WHITE, radius=44)
d = ImageDraw.Draw(layer, "RGBA")
d.ellipse([150 + x_off, y - 34, 218 + x_off, y + 34], fill=color + (255,), outline=INK + (255,), width=5)
d.line([(166 + x_off, y - 16), (202 + x_off, y + 16)], fill=INK + (255,), width=7)
d.line([(202 + x_off, y - 16), (166 + x_off, y + 16)], fill=INK + (255,), width=7)
P.draw_text(layer, (250 + x_off, y), text, 44, INK + (255,), anchor="lm")
V.label(layer, W / 2, 1620, "Тема и значки только красят", pop(lt, 2.4), size=38, fill=YELLOW)
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=29, count=60, power=1000)
V.title(layer, max(0.0, lt - 0.5), "Serena alpha 2", "Открытый код · лицензия 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)
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 / ("still2_%.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()

View File

@@ -0,0 +1,97 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Draws the four sticker-style icons of the sample plugin lihont.icons-sticker (the buttons at the right of the feed).
usage: py -X utf8 -B scripts/make_sticker_icons.py
Writes plugins/lihont.icons-sticker/assets/{heart,bubble,star,plane}.png (96x96, a thick dark outline and a hard shadow) and
copies them to sdk/lihont-ltp/examples/files/ for the example 09_icons.py.
"""
import math
import shutil
from pathlib import Path
from PIL import Image, ImageDraw
ROOT = Path(__file__).resolve().parent.parent
OUT = ROOT / "plugins" / "lihont.icons-sticker" / "assets"
EXAMPLES = ROOT / "sdk" / "lihont-ltp" / "examples" / "files"
SIZE = 96
SCALE = 6
INK = (34, 28, 46, 255)
def canvas():
s = SIZE * SCALE
return Image.new("RGBA", (s, s), (0, 0, 0, 0)), s
def finish(img):
return img.resize((SIZE, SIZE), Image.Resampling.LANCZOS)
def sticker(draw_shape, fill):
"""Shadow first (shifted down and right), then the outlined shape on top."""
img, s = canvas()
d = ImageDraw.Draw(img)
off = s * 0.045
draw_shape(d, s, off, INK, None, 0)
draw_shape(d, s, 0, fill, INK, int(s * 0.04))
return finish(img)
def heart(d, s, off, fill, outline, width):
def bez(p0, p1, p2, p3, n=30):
return [((1 - t) ** 3 * p0[0] + 3 * (1 - t) ** 2 * t * p1[0] + 3 * (1 - t) * t * t * p2[0] + t ** 3 * p3[0],
(1 - t) ** 3 * p0[1] + 3 * (1 - t) ** 2 * t * p1[1] + 3 * (1 - t) * t * t * p2[1] + t ** 3 * p3[1])
for t in [i / n for i in range(n + 1)]]
q = lambda x, y: (s * x * 0.86 + s * 0.07 + off, s * y * 0.86 + s * 0.07 + off) # noqa: E731
pts = (bez(q(0.5, 0.94), q(0.10, 0.62), q(0.02, 0.40), q(0.10, 0.24)) + bez(q(0.10, 0.24), q(0.18, 0.08), q(0.40, 0.06), q(0.5, 0.27))
+ bez(q(0.5, 0.27), q(0.60, 0.06), q(0.82, 0.08), q(0.90, 0.24)) + bez(q(0.90, 0.24), q(0.98, 0.40), q(0.90, 0.62), q(0.5, 0.94)))
d.polygon(pts, fill=fill)
if outline:
d.line(pts + [pts[0]], fill=outline, width=width, joint="curve")
def bubble(d, s, off, fill, outline, width):
box = [s * 0.08 + off, s * 0.12 + off, s * 0.92 + off, s * 0.70 + off]
tail = [(s * 0.28 + off, s * 0.66 + off), (s * 0.22 + off, s * 0.92 + off), (s * 0.52 + off, s * 0.68 + off)]
d.rounded_rectangle(box, radius=s * 0.2, fill=fill, outline=outline, width=width)
d.polygon(tail, fill=fill)
if outline:
d.line([tail[0], tail[1], tail[2]], fill=outline, width=width, joint="curve")
d.line([(s * 0.30 + off, s * 0.665 + off), (s * 0.51 + off, s * 0.675 + off)], fill=fill, width=width + 2)
def star(d, s, off, fill, outline, width):
pts = []
for i in range(10):
r = s * (0.46 if i % 2 == 0 else 0.2)
a = -math.pi / 2 + i * math.pi / 5
pts.append((s / 2 + off + math.cos(a) * r, s * 0.54 + off + math.sin(a) * r))
d.polygon(pts, fill=fill)
if outline:
d.line(pts + [pts[0]], fill=outline, width=width, joint="curve")
def plane(d, s, off, fill, outline, width):
pts = [(s * 0.08 + off, s * 0.46 + off), (s * 0.92 + off, s * 0.12 + off), (s * 0.62 + off, s * 0.88 + off),
(s * 0.48 + off, s * 0.58 + off)]
d.polygon(pts, fill=fill)
if outline:
d.line(pts + [pts[0]], fill=outline, width=width, joint="curve")
d.line([pts[3], pts[1]], fill=outline, width=width)
def main():
OUT.mkdir(parents=True, exist_ok=True)
EXAMPLES.mkdir(parents=True, exist_ok=True)
for name, shape, color in (("heart", heart, (255, 107, 107, 255)), ("bubble", bubble, (90, 180, 255, 255)),
("star", star, (255, 205, 60, 255)), ("plane", plane, (94, 214, 170, 255))):
path = OUT / (name + ".png")
sticker(shape, color).save(path, optimize=True)
shutil.copy2(path, EXAMPLES / (name + ".png"))
print(path.name, path.stat().st_size, "bytes")
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,50 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Draws the preview cards of the sample theme plugins (lihont.theme-win95, lihont.theme-sunset).
A theme author attaches such pictures to the plugin ("theme": {"preview": ["preview1.png", ...]}); the list of looks in the
settings shows them before the theme is picked. These two are drawn with the same mock of the settings screen as the promo video.
usage: py -X utf8 -B scripts/make_theme_previews.py
"""
import sys
from pathlib import Path
from PIL import Image
sys.path.insert(0, str(Path(__file__).resolve().parent))
import make_serena_promo as S # noqa: E402
ROOT = S.ROOT
CARDS = {
"lihont.theme-win95": "win95",
"lihont.theme-sunset": "sunset",
}
ROWS = {
1: None,
2: ["anna: смотрите, вайб!", "luna: нашёл своих", "boy: огонёк горит", "я: пузыри топ"],
}
def render(look, rows):
img = Image.new("RGBA", (780 + 120, 520 + 150), (0, 0, 0, 0))
S.settings_card(img, look, (60, 70, 60 + 780, 70 + 520), lt=-1, rows=rows)
# crop to the drawn page and scale down to a card that stays well under 400 KB
box = (30, 40, 60 + 780 + 30, 70 + 520 + 30)
card = img.crop(box).convert("RGB")
card.thumbnail((540, 400), Image.Resampling.LANCZOS)
return card
def main():
for folder, look in CARDS.items():
out = ROOT / "plugins" / folder / "assets"
out.mkdir(parents=True, exist_ok=True)
for n, rows in ROWS.items():
path = out / ("preview%d.png" % n)
render(look, rows).save(path, optimize=True)
print(folder, path.name, path.stat().st_size, "bytes")
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,9 @@
# Пример 9: свои значки на кнопках справа в ленте (лайк, комментарии, избранное, поделиться).
# Картинки (png, gif или webp) лежат в папке files рядом со скриптом. Кнопки остаются на местах и работают как раньше.
from lihont_ltp import *
plugin = Plugin("Стикерные значки", author="Вася", description="Яркие наклейки на кнопках ленты", license="MIT")
plugin.icons(like="heart.png", comment="bubble.png", collect="star.png", share="plane.png")
plugin.save()

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 355 B

After

Width:  |  Height:  |  Size: 6.2 KiB

View File

@@ -352,6 +352,7 @@ class Plugin:
self.id = id or "%s.%s" % (_slug(author) or "me", _slug(name) or "plugin") self.id = id or "%s.%s" % (_slug(author) or "me", _slug(name) or "plugin")
self._rules = [] self._rules = []
self._theme = None self._theme = None
self._icons = None
self._base = _caller_folder() self._base = _caller_folder()
# правила ---------------------------------------------------------------------------------------------------- # правила ----------------------------------------------------------------------------------------------------
@@ -372,11 +373,13 @@ class Plugin:
def theme(self, name=None, *, page, card, text, accent, muted=None, on_accent=None, line=None, title_from=None, 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_to=None, dark=False, radius=None, outline=None, shadow=None, bevel=False, tick_box=False,
title_bars=False): title_bars=False, preview=None):
"""Тема оформления: цвета и пара чисел. Тема только красит: она ничего не прячет и не двигает. """Тема оформления: цвета и пара чисел. Тема только красит: она ничего не прячет и не двигает.
plugin.theme("Закат", page="#2b1d3a", card="#3d2b52", text="#fbe9ff", accent="#ff8a5b", radius=20) plugin.theme("Закат", page="#2b1d3a", card="#3d2b52", text="#fbe9ff", accent="#ff8a5b", radius=20)
preview=["card1.png", "card2.png"] — до четырёх своих картинок-карточек: их видно в списке «Оформление»
до выбора темы (png, gif или webp рядом со скриптом).
Цвета пишутся как #rrggbb маленькими буквами. radius 0–40, outline 0–6, shadow 0–12. Цвета пишутся как #rrggbb маленькими буквами. radius 0–40, outline 0–6, shadow 0–12.
bevel даёт объёмные рамки (как Windows 95), tick_box рисует переключатель галочкой, title_bars делает bevel даёт объёмные рамки (как Windows 95), tick_box рисует переключатель галочкой, title_bars делает
заголовки разделов полосой. заголовки разделов полосой.
@@ -389,9 +392,26 @@ class Plugin:
for key, value in (("dark", dark), ("bevel", bevel), ("tick_box", tick_box), ("title_bars", title_bars)): for key, value in (("dark", dark), ("bevel", bevel), ("tick_box", tick_box), ("title_bars", title_bars)):
if value: if value:
theme[key] = True theme[key] = True
if preview:
theme["preview"] = [preview] if isinstance(preview, str) else list(preview)
self._theme = theme self._theme = theme
return self return self
def icons(self, like=None, comment=None, collect=None, share=None):
"""Свои картинки для кнопок справа в ленте: лайк, комментарии, избранное, поделиться.
plugin.icons(like="heart.png", comment="bubble.png")
Картинки (png, gif или webp) лежат рядом со скриптом. Кнопки остаются на месте и работают как раньше:
меняется только картинка на них.
"""
icons = {slot: value for slot, value in (("like", like), ("comment", comment), ("collect", collect),
("share", share)) if value}
if not icons:
raise LtpError("icons(...): назови хотя бы одну кнопку, например icons(like=\"heart.png\")")
self._icons = icons
return self
def _add(self, kind, trigger, when, actions, title, limit): def _add(self, kind, trigger, when, actions, title, limit):
if isinstance(when, Action): # забыли условие: plugin.video(hide) значит «всегда» if isinstance(when, Action): # забыли условие: plugin.video(hide) значит «всегда»
actions = (when,) + tuple(actions) actions = (when,) + tuple(actions)
@@ -437,6 +457,8 @@ class Plugin:
manifest["ai"] = self.ai manifest["ai"] = self.ai
if self._theme is not None: if self._theme is not None:
rights.append("ui.theme") rights.append("ui.theme")
if self._icons is not None:
rights.append("ui.icons")
manifest["permissions"] = rights manifest["permissions"] = rights
if "net.download" in rights: if "net.download" in rights:
# сайты берутся из адресов скачиваний: писать их отдельно не нужно # сайты берутся из адресов скачиваний: писать их отдельно не нужно
@@ -451,7 +473,9 @@ class Plugin:
manifest["net"] = {"hosts": hosts} manifest["net"] = {"hosts": hosts}
if self._theme is not None: if self._theme is not None:
manifest["theme"] = self._theme manifest["theme"] = self._theme
if rules or self._theme is None: if self._icons is not None:
manifest["icons"] = self._icons
if rules or (self._theme is None and self._icons is None):
manifest["rules"] = rules manifest["rules"] = rules
if not self.description: if not self.description:
del manifest["description"] del manifest["description"]

View File

@@ -17,6 +17,7 @@ CANNOT_NET = ("Плагин не может: ходить куда-либо, к
"и только после вашего подтверждения.") "и только после вашего подтверждения.")
DEFAULT_LIMIT = 3 DEFAULT_LIMIT = 3
ICON_WORDS = {"like": "лайк", "comment": "комментарии", "collect": "избранное", "share": "поделиться"}
STYLE_WORDS = {"upper": "заглавными буквами", "lower": "строчными буквами", "reverse": "задом наперёд", STYLE_WORDS = {"upper": "заглавными буквами", "lower": "строчными буквами", "reverse": "задом наперёд",
"wave": "волной (пРиВеТ)", "spaced": "с пробелами между буквами"} "wave": "волной (пРиВеТ)", "spaced": "с пробелами между буквами"}
DAYS = ["", "пн", "вт", "ср", "чт", "пт", "сб", "вс"] DAYS = ["", "пн", "вт", "ср", "чт", "пт", "сб", "вс"]
@@ -261,6 +262,8 @@ def check(manifest, asset_names=()):
rules.append("Тема «%s»: меняет цвета и вид экранов мода и TikTok" % theme["name"].strip()) rules.append("Тема «%s»: меняет цвета и вид экранов мода и TikTok" % theme["name"].strip())
calm.append("Меняет оформление: цвета, формы и рамки. Ничего не скрывает и не двигает. " calm.append("Меняет оформление: цвета, формы и рамки. Ничего не скрывает и не двигает. "
"Вернуть как было можно в «Оформление» или режимом DEBUG.") "Вернуть как было можно в «Оформление» или режимом DEBUG.")
if theme.get("preview"):
calm.append("К теме приложены картинки-превью: они показываются, когда вы выбираете оформление.")
text, card, accent, on_accent = validate.theme_values(theme) text, card, accent, on_accent = validate.theme_values(theme)
text_tenths = validate.contrast_tenths(text, card) text_tenths = validate.contrast_tenths(text, card)
if text_tenths < 30: if text_tenths < 30:
@@ -269,6 +272,11 @@ def check(manifest, asset_names=()):
if accent_tenths < 30: if accent_tenths < 30:
watch.append("Текст на кнопках и заголовках темы плохо читается: контраст %s при нужных 3.0." watch.append("Текст на кнопках и заголовках темы плохо читается: контраст %s при нужных 3.0."
% _tenths(accent_tenths)) % _tenths(accent_tenths))
icons = manifest.get("icons")
if icons:
words = ", ".join(ICON_WORDS[slot] for slot in validate.ICON_SLOTS if slot in icons)
rules.append("Значки кнопок в ленте (%s): свои картинки вместо значков TikTok" % words)
calm.append("Меняет картинки кнопок справа в ленте. Кнопки остаются на месте и работают как раньше.")
if asset_names: if asset_names:
calm.append("Файлов внутри: %d. Тип каждого проверен по первым байтам, они входят в хэш." % len(set(asset_names))) calm.append("Файлов внутри: %d. Тип каждого проверен по первым байтам, они входят в хэш." % len(set(asset_names)))
if not (manifest.get("license") or "").strip(): if not (manifest.get("license") or "").strip():

View File

@@ -24,7 +24,7 @@ MAX_ICON = 64 * 1024
MAX_FILE = 1024 * 1024 MAX_FILE = 1024 * 1024
TRIGGERS = ("feed.item", "name.show", "screen.show") TRIGGERS = ("feed.item", "name.show", "screen.show")
RIGHTS = ("feed.hide", "names", "ui.notice", "ui.overlay", "ui.sound", "feed.like", "net.download", "ui.theme") RIGHTS = ("feed.hide", "names", "ui.notice", "ui.overlay", "ui.sound", "feed.like", "net.download", "ui.theme", "ui.icons")
ACTIONS = ("feed.hide", "name.prefix", "name.suffix", "name.replace", "name.style", "notice", "overlay", "download") ACTIONS = ("feed.hide", "name.prefix", "name.suffix", "name.replace", "name.style", "notice", "overlay", "download")
NAME_STYLES = ("upper", "lower", "reverse", "wave", "spaced") NAME_STYLES = ("upper", "lower", "reverse", "wave", "spaced")
TAPS = ("animate", "sound", "like", "confetti", "buzz") TAPS = ("animate", "sound", "like", "confetti", "buzz")
@@ -35,11 +35,13 @@ DOWNLOAD_KEYS = ("url", "as", "sha256")
MAX_LICENSE = 40 MAX_LICENSE = 40
MAX_THEME_NAME = 24 MAX_THEME_NAME = 24
ICON_SLOTS = ("like", "comment", "collect", "share")
MAX_RADIUS = 40 MAX_RADIUS = 40
MAX_OUTLINE = 6 MAX_OUTLINE = 6
MAX_SHADOW = 12 MAX_SHADOW = 12
THEME_KEYS = ("name", "dark", "page", "card", "text", "muted", "accent", "on_accent", "line", "title_from", "title_to", THEME_KEYS = ("name", "dark", "page", "card", "text", "muted", "accent", "on_accent", "line", "title_from", "title_to",
"radius", "outline", "shadow", "bevel", "tick_box", "title_bars") "radius", "outline", "shadow", "bevel", "tick_box", "title_bars", "preview")
MAX_PREVIEW = 4
THEME_COLOURS = ("page", "card", "text", "muted", "accent", "on_accent", "line", "title_from", "title_to") THEME_COLOURS = ("page", "card", "text", "muted", "accent", "on_accent", "line", "title_from", "title_to")
THEME_FLAGS = ("dark", "bevel", "tick_box", "title_bars") THEME_FLAGS = ("dark", "bevel", "tick_box", "title_bars")
COLOUR = re.compile(r"#[0-9a-f]{6}") COLOUR = re.compile(r"#[0-9a-f]{6}")
@@ -296,6 +298,25 @@ def rights_of(action):
return ["names"] return ["names"]
def check_icons(icons, where="plugin.json, «icons»"):
"""Значки кнопок ленты: кнопка → файл картинки. Те же правила, что в Plugin.java (parseIcons)."""
if not isinstance(icons, dict):
raise LtpError("%s: нужен объект {…}" % where)
for key in icons:
if key not in ICON_SLOTS:
raise LtpError("%s: нет кнопки «%s» (можно like, comment, collect, share)" % (where, key))
named = 0
for slot in ICON_SLOTS:
if icons.get(slot) is None:
continue
name = _text(icons[slot], 40, where + ", «%s»" % slot)
if KINDS.get("." + name.rsplit(".", 1)[-1].lower(), "") != "image":
raise LtpError("%s, «%s»: это png, gif или webp, а не «%s»" % (where, slot, name))
named += 1
if not named:
raise LtpError("%s: назови хотя бы одну кнопку" % where)
def theme_colour(theme, key, default): def theme_colour(theme, key, default):
"""Цвет темы как число 0xRRGGBB; если поля нет — значение по умолчанию (те же, что в приложении).""" """Цвет темы как число 0xRRGGBB; если поля нет — значение по умолчанию (те же, что в приложении)."""
value = theme.get(key) value = theme.get(key)
@@ -350,6 +371,18 @@ def check_theme(theme, where="plugin.json, «theme»"):
for key, high in (("radius", MAX_RADIUS), ("outline", MAX_OUTLINE), ("shadow", MAX_SHADOW)): for key, high in (("radius", MAX_RADIUS), ("outline", MAX_OUTLINE), ("shadow", MAX_SHADOW)):
if theme.get(key) is not None: if theme.get(key) is not None:
_integer(theme[key], 0, high, where + ", поле «%s»" % key) _integer(theme[key], 0, high, where + ", поле «%s»" % key)
if theme.get("preview") is not None:
cards = theme["preview"]
if not isinstance(cards, list):
raise LtpError("%s: нужен список […]" % (where + ", поле «preview»"))
if not 1 <= len(cards) <= MAX_PREVIEW:
raise LtpError("%s, поле «preview»: от 1 до %d картинок" % (where, MAX_PREVIEW))
for card in cards:
file = _text(card, 40, where + ", поле «preview»")
if KINDS.get("." + file.rsplit(".", 1)[-1].lower(), "") != "image":
raise LtpError("%s, поле «preview»: это png, gif или webp, а не «%s»" % (where, file))
if len(set(cards)) != len(cards):
raise LtpError("%s, поле «preview»: одна и та же картинка названа дважды" % where)
for key in THEME_FLAGS: for key in THEME_FLAGS:
if theme.get(key) is not None and not isinstance(theme[key], bool): if theme.get(key) is not None and not isinstance(theme[key], bool):
raise LtpError("%s, поле «%s»: нужно true или false" % (where, key)) raise LtpError("%s, поле «%s»: нужно true или false" % (where, key))
@@ -400,10 +433,18 @@ def check_manifest(manifest, assets=None):
check_theme(theme) check_theme(theme)
elif "ui.theme" in permissions: elif "ui.theme" in permissions:
raise LtpError("plugin.json: право «ui.theme» требует поле «theme»") raise LtpError("plugin.json: право «ui.theme» требует поле «theme»")
icons = manifest.get("icons")
if icons is not None:
if "ui.icons" not in permissions:
raise LtpError("plugin.json: есть «icons», но нет права «ui.icons»")
check_icons(icons)
elif "ui.icons" in permissions:
raise LtpError("plugin.json: право «ui.icons» требует поле «icons»")
looks = theme is not None or icons is not None
rules = manifest.get("rules") rules = manifest.get("rules")
if rules is None and theme is not None: if rules is None and looks:
rules = [] # a plugin that only brings a theme has no rules rules = [] # a plugin that only brings a theme or icons has no rules
if not isinstance(rules, list) or (not rules and theme is None): if not isinstance(rules, list) or (not rules and not looks):
raise LtpError("В плагине нет правил: добавь хотя бы одно, например plugin.video(hashtag(\"fyp\"), hide)") raise LtpError("В плагине нет правил: добавь хотя бы одно, например plugin.video(hashtag(\"fyp\"), hide)")
if len(rules) > MAX_RULES: if len(rules) > MAX_RULES:
raise LtpError("В плагине больше %d правил" % MAX_RULES) raise LtpError("В плагине больше %d правил" % MAX_RULES)
@@ -437,7 +478,7 @@ def check_manifest(manifest, assets=None):
if rule.get("limit") is not None: if rule.get("limit") is not None:
_integer(rule["limit"], 1, MAX_LIMIT, where + ", «limit»") _integer(rule["limit"], 1, MAX_LIMIT, where + ", «limit»")
for right in permissions: for right in permissions:
if right != "ui.theme" and right not in used: if right not in ("ui.theme", "ui.icons") and right not in used:
raise LtpError("Плагин просит право «%s», но не использует его" % right) raise LtpError("Плагин просит право «%s», но не использует его" % right)
check_net(manifest.get("net"), permissions, downloads, assets) check_net(manifest.get("net"), permissions, downloads, assets)
if assets is not None: if assets is not None:
@@ -504,6 +545,13 @@ def referenced_files(manifest):
for key in ("image", "sound", "pet"): for key in ("image", "sound", "pet"):
if spec.get(key) and spec[key] not in fetched: if spec.get(key) and spec[key] not in fetched:
names.append(spec[key]) names.append(spec[key])
for slot in ICON_SLOTS:
name = (manifest.get("icons") or {}).get(slot)
if name and name not in names:
names.append(name)
for card in (manifest.get("theme") or {}).get("preview") or []:
if card not in names:
names.append(card)
return names return names
@@ -518,6 +566,14 @@ def check_assets(manifest, assets):
"и внутри должен быть именно этот тип файла" % name) "и внутри должен быть именно этот тип файла" % name)
if len(body) > MAX_ASSET: if len(body) > MAX_ASSET:
raise LtpError("Файл %s больше 400 КБ (сейчас %d КБ): сожми его" % (name, len(body) // 1024)) raise LtpError("Файл %s больше 400 КБ (сейчас %d КБ): сожми его" % (name, len(body) // 1024))
for card in (manifest.get("theme") or {}).get("preview") or []:
if card not in assets:
raise LtpError("Плагину нужен файл %s для превью темы, а его нет рядом со скриптом (положи рядом или в папку files)"
% card)
for slot, name in (manifest.get("icons") or {}).items():
if name not in assets:
raise LtpError("Плагину нужен файл %s для кнопки %s, а его нет рядом со скриптом (положи рядом или в папку files)"
% (name, slot))
fetched = downloaded_files(manifest) fetched = downloaded_files(manifest)
for rule in manifest.get("rules", []): for rule in manifest.get("rules", []):
for action in rule.get("do", []): for action in rule.get("do", []):

View File

@@ -37,6 +37,7 @@ plugin.save()
- **Про что**: `plugin.video(...)`, `plugin.name(...)`, `plugin.screen(...)`. - **Про что**: `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")`. - **Если** (необязательно, без него «всегда»): `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, иначе защитник предупредит. - **Тема оформления**: `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, иначе защитник предупредит.
- **Значки кнопок в ленте**: `plugin.icons(like="heart.png", comment="bubble.png", collect="star.png", share="plane.png")`. Кнопки: like, comment, collect, share; картинки png/gif/webp до 400 КБ лежат рядом со скриптом. Кнопки остаются на месте и работают как раньше, меняется только картинка. Правила в таком плагине не нужны.
- **Что сделать**: `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`). - **Что сделать**: `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` ставит лайк по нажатию, поэтому добавляй его, только если человек прямо попросил. - В `picture`: `like` ставит лайк по нажатию, поэтому добавляй его, только если человек прямо попросил.
- Лицензия и ИИ: всегда ставь `license="MIT"` (или `"VCBFU-2"`) и `ai="<какая модель написала>"`. Без лицензии защитник отметит замечание, а для полки «проверенные» нужна MIT или VCBFU-2. - Лицензия и ИИ: всегда ставь `license="MIT"` (или `"VCBFU-2"`) и `ai="<какая модель написала>"`. Без лицензии защитник отметит замечание, а для полки «проверенные» нужна MIT или VCBFU-2.
@@ -54,6 +55,7 @@ plugin.save()
| Картинка поверх приложения с анимацией, звуком, перетаскиванием, лайком по нажатию | Запускать код, вызывать любые функции | | Картинка поверх приложения с анимацией, звуком, перетаскиванием, лайком по нажатию | Запускать код, вызывать любые функции |
| Скачать картинку или звук (https, до 400 КБ, названный сайт, два согласия человека) | Ходить в интернет иначе; скачивать другое; отправлять данные | | Скачать картинку или звук (https, до 400 КБ, названный сайт, два согласия человека) | Ходить в интернет иначе; скачивать другое; отправлять данные |
| Тема оформления: цвета, радиус, контур, тень, объёмные рамки, галочки, полосы заголовков | Прятать, двигать и добавлять элементы экрана | | Тема оформления: цвета, радиус, контур, тень, объёмные рамки, галочки, полосы заголовков | Прятать, двигать и добавлять элементы экрана |
| Значки кнопок ленты (лайк, комментарии, избранное, поделиться): только картинка | Прятать, двигать кнопки и менять, что они делают |
| Лимиты: до 32 правил, до 8 действий в правиле, до 8 файлов по 400 КБ, всего 1 МБ | Темы, виджеты, кнопки: этого вида плагинов пока нет | | Лимиты: до 32 правил, до 8 действий в правиле, до 8 файлов по 400 КБ, всего 1 МБ | Темы, виджеты, кнопки: этого вида плагинов пока нет |
Если просят то, чего в левой колонке нет, скажи прямо: это пока невозможно. Не изобретай несуществующие функции и не предлагай обходные пути через код. Если просят то, чего в левой колонке нет, скажи прямо: это пока невозможно. Не изобретай несуществующие функции и не предлагай обходные пути через код.

View File

@@ -138,6 +138,9 @@ public final class Defender {
rules.add("Тема «" + theme.name + "»: меняет цвета и вид экранов мода и TikTok"); rules.add("Тема «" + theme.name + "»: меняет цвета и вид экранов мода и TikTok");
calm.add("Меняет оформление: цвета, формы и рамки. Ничего не скрывает и не двигает. " calm.add("Меняет оформление: цвета, формы и рамки. Ничего не скрывает и не двигает. "
+ "Вернуть как было можно в «Оформление» или режимом DEBUG."); + "Вернуть как было можно в «Оформление» или режимом DEBUG.");
if (!theme.preview.isEmpty()) {
calm.add("К теме приложены картинки-превью: они показываются, когда вы выбираете оформление.");
}
if (theme.textContrast() < 30) { if (theme.textContrast() < 30) {
watch.add("Текст на карточках темы плохо читается: контраст " + tenths(theme.textContrast()) + " при нужных 3.0."); watch.add("Текст на карточках темы плохо читается: контраст " + tenths(theme.textContrast()) + " при нужных 3.0.");
} }
@@ -146,6 +149,15 @@ public final class Defender {
+ " при нужных 3.0."); + " при нужных 3.0.");
} }
} }
if (!plugin.icons.isEmpty()) {
StringBuilder words = new StringBuilder();
for (String slot : Plugin.ICON_SLOTS) {
if (!plugin.icons.containsKey(slot)) continue;
words.append(words.length() > 0 ? ", " : "").append(Plugin.iconWord(slot));
}
rules.add("Значки кнопок в ленте (" + words + "): свои картинки вместо значков TikTok");
calm.add("Меняет картинки кнопок справа в ленте. Кнопки остаются на месте и работают как раньше.");
}
if (!plugin.assets.isEmpty()) { if (!plugin.assets.isEmpty()) {
calm.add("Файлов внутри: " + plugin.assets.size() + ". Тип каждого проверен по первым байтам, они входят в хэш."); calm.add("Файлов внутри: " + plugin.assets.size() + ". Тип каждого проверен по первым байтам, они входят в хэш.");
} }

View File

@@ -0,0 +1,133 @@
package lihont.two.plugin;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;
/**
* Puts the pictures of a plugin (right ui.icons) on the buttons at the right of the feed: like, comments, favourites, share.
*
* TikTok does not name these views in a way that stays put, but each button says what it is to people who cannot see it
* ("Поставить лайк", "Прочитать или оставить комментарии", "Добавьте это видео в Избранное", "Поделиться видео"), so the
* buttons are found by that sentence and the first picture inside each one is swapped. Nothing else changes: the buttons keep
* their place, size and what they do. The swap is checked a few times a second, because the feed reuses its views and TikTok
* puts its own picture back (for a like, for example); when the plugin goes away, the picture TikTok had is put back.
*/
final class IconSkin {
private static final long TICK_MS = 200L;
private static final int MAX_VIEWS = 4000;
private static final int MAX_DEPTH = 6;
private static final WeakHashMap<View, Boolean> WATCHED = new WeakHashMap<View, Boolean>();
/** The picture TikTok had on a button before it was swapped, to put it back. */
private static final WeakHashMap<ImageView, Drawable> ORIGINAL = new WeakHashMap<ImageView, Drawable>();
/** The decoded pictures by file and age, a few at a time. */
private static final Map<String, Drawable> PICTURES = new java.util.LinkedHashMap<String, Drawable>(8, 0.75f, true) {
@Override protected boolean removeEldestEntry(Map.Entry<String, Drawable> eldest) {
return size() > 8;
}
};
private IconSkin() {}
/** Starts the checks on this screen (once); the checks do nothing while no active plugin has icons. */
static void attach(final Activity activity) {
final View decor = activity.getWindow().getDecorView();
if (WATCHED.containsKey(decor)) return;
WATCHED.put(decor, Boolean.TRUE);
decor.postDelayed(new Runnable() {
@Override public void run() {
if (activity.isFinishing() || !decor.isAttachedToWindow()) {
WATCHED.remove(decor);
return;
}
try {
tick(decor);
} catch (Throwable ignored) {
// A look: never worth taking the feed down.
}
decor.postDelayed(this, TICK_MS);
}
}, TICK_MS);
}
private static void tick(View decor) {
Map<String, File> wanted = PluginEngine.icons();
if (wanted.isEmpty() && ORIGINAL.isEmpty()) return;
int[] budget = {MAX_VIEWS};
walk(decor, wanted, 0, budget);
}
private static void walk(View view, Map<String, File> wanted, int depth, int[] budget) {
if (budget[0]-- <= 0) return;
CharSequence said = view.getContentDescription();
if (said != null && view.getVisibility() == View.VISIBLE) {
String slot = slotOf(said.toString());
if (slot != null) {
ImageView image = firstImage(view, 0);
if (image != null) swap(image, wanted.get(slot));
return;
}
}
if (view instanceof ViewGroup && depth < MAX_DEPTH + 10) {
ViewGroup group = (ViewGroup) view;
for (int i = 0; i < group.getChildCount(); i++) walk(group.getChildAt(i), wanted, depth + 1, budget);
}
}
/** Which feed button a spoken sentence belongs to, or null. The order matters: a like button says no word of the others. */
static String slotOf(String said) {
String lower = said.toLowerCase(java.util.Locale.ROOT);
if (lower.startsWith("прочитать или оставить комментар") || lower.startsWith("read or add comments")) return "comment";
if (lower.startsWith("добавьте это видео в избранное") || lower.startsWith("add this video to favorites")
|| lower.startsWith("add to favorites")) return "collect";
if (lower.startsWith("поделиться видео") || lower.startsWith("share video")) return "share";
if (lower.startsWith("поставить лайк") || lower.startsWith("like video") || lower.startsWith("убрать лайк")) return "like";
return null;
}
private static ImageView firstImage(View view, int depth) {
if (view instanceof ImageView) return (ImageView) view;
if (!(view instanceof ViewGroup) || depth > MAX_DEPTH) return null;
ViewGroup group = (ViewGroup) view;
for (int i = 0; i < group.getChildCount(); i++) {
ImageView found = firstImage(group.getChildAt(i), depth + 1);
if (found != null) return found;
}
return null;
}
private static void swap(ImageView image, File file) {
Drawable ours = file == null ? null : picture(image, file);
Drawable now = image.getDrawable();
if (ours == null) {
Drawable original = ORIGINAL.remove(image);
if (original != null) image.setImageDrawable(original);
return;
}
if (now == ours) return;
if (!ORIGINAL.containsKey(image) && now != null) ORIGINAL.put(image, now);
image.setImageDrawable(ours);
}
private static Drawable picture(ImageView view, File file) {
String key = file.getAbsolutePath() + ":" + file.lastModified();
Drawable known = PICTURES.get(key);
if (known != null) return known;
Bitmap bitmap = BitmapFactory.decodeFile(file.getPath());
if (bitmap == null) return null;
Drawable drawable = new BitmapDrawable(view.getResources(), bitmap);
PICTURES.put(key, drawable);
return drawable;
}
}

View File

@@ -20,6 +20,7 @@ public final class Permission {
public static final String LIKE = "feed.like"; public static final String LIKE = "feed.like";
public static final String NET_DOWNLOAD = "net.download"; public static final String NET_DOWNLOAD = "net.download";
public static final String UI_THEME = "ui.theme"; public static final String UI_THEME = "ui.theme";
public static final String UI_ICONS = "ui.icons";
private static final Map<String, String> TEXT = new LinkedHashMap<String, String>(); private static final Map<String, String> TEXT = new LinkedHashMap<String, String>();
@@ -32,6 +33,8 @@ public final class Permission {
TEXT.put(LIKE, "Ставить лайк видео на главной ленте, когда вы нажимаете на картинку плагина"); TEXT.put(LIKE, "Ставить лайк видео на главной ленте, когда вы нажимаете на картинку плагина");
TEXT.put(UI_THEME, "Менять оформление экранов мода и TikTok: цвета, формы, рамки " TEXT.put(UI_THEME, "Менять оформление экранов мода и TikTok: цвета, формы, рамки "
+ "(ничего не скрывает и не двигает; вернуть можно в «Оформление» или режимом DEBUG)"); + "(ничего не скрывает и не двигает; вернуть можно в «Оформление» или режимом DEBUG)");
TEXT.put(UI_ICONS, "Менять картинки кнопок справа в ленте (лайк, комментарии, избранное, поделиться); "
+ "кнопки остаются на месте и работают как раньше");
TEXT.put(NET_DOWNLOAD, "Скачивать картинки и звуки с названных сайтов (включается отдельным переключателем, " TEXT.put(NET_DOWNLOAD, "Скачивать картинки и звуки с названных сайтов (включается отдельным переключателем, "
+ "каждый адрес вы подтверждаете)"); + "каждый адрес вы подтверждаете)");
} }

View File

@@ -52,10 +52,24 @@ public final class Plugin {
public final List<String> ai; public final List<String> ai;
/** The look the plugin brings (right ui.theme), or null. */ /** The look the plugin brings (right ui.theme), or null. */
public final ThemeData theme; public final ThemeData theme;
/** The pictures for the buttons of the feed (right ui.icons): slot ("like", "comment", "collect", "share") to file name. */
public final Map<String, String> icons;
/** The slots of the feed buttons, in the order the defender lists them, with the words it uses. */
public static final String[] ICON_SLOTS = {"like", "comment", "collect", "share"};
private static final String[] ICON_WORDS = {"лайк", "комментарии", "избранное", "поделиться"};
public static String iconWord(String slot) {
for (int i = 0; i < ICON_SLOTS.length; i++) {
if (ICON_SLOTS[i].equals(slot)) return ICON_WORDS[i];
}
return slot;
}
private Plugin(String id, String name, String version, String author, String description, private Plugin(String id, String name, String version, String author, String description,
List<String> permissions, List<Rule> rules, String sha256, Set<String> assets, List<String> hosts, List<String> permissions, List<Rule> rules, String sha256, Set<String> assets, List<String> hosts,
String license, List<String> ai, ThemeData theme) { String license, List<String> ai, ThemeData theme, Map<String, String> icons) {
this.icons = Collections.unmodifiableMap(icons);
this.theme = theme; this.theme = theme;
this.license = license; this.license = license;
this.ai = Collections.unmodifiableList(ai); this.ai = Collections.unmodifiableList(ai);
@@ -137,22 +151,36 @@ public final class Plugin {
} else if (permissions.contains(Permission.UI_THEME)) { } else if (permissions.contains(Permission.UI_THEME)) {
throw new LtpException("plugin.json: право «ui.theme» требует поле «theme»"); throw new LtpException("plugin.json: право «ui.theme» требует поле «theme»");
} }
// a plugin that only brings a theme has no rules Map<String, String> icons = parseIcons(root.get("icons"), permissions);
List<Object> raw = root.get("rules") == null && theme != null ? new ArrayList<Object>() // a plugin that only brings a theme or icons has no rules
boolean looks = theme != null || !icons.isEmpty();
List<Object> raw = root.get("rules") == null && looks ? new ArrayList<Object>()
: Fields.list(root.get("rules"), "plugin.json, «rules»"); : Fields.list(root.get("rules"), "plugin.json, «rules»");
if (raw.isEmpty() && theme == null) throw new LtpException("В плагине нет правил"); if (raw.isEmpty() && !looks) throw new LtpException("В плагине нет правил");
if (raw.size() > MAX_RULES) throw new LtpException("В плагине больше " + MAX_RULES + " правил"); if (raw.size() > MAX_RULES) throw new LtpException("В плагине больше " + MAX_RULES + " правил");
List<Rule> rules = new ArrayList<Rule>(); List<Rule> rules = new ArrayList<Rule>();
for (int i = 0; i < raw.size(); i++) rules.add(Rule.parse(raw.get(i), i, permissions)); for (int i = 0; i < raw.size(); i++) rules.add(Rule.parse(raw.get(i), i, permissions));
for (String right : permissions) { for (String right : permissions) {
if (right.equals(Permission.UI_THEME)) continue; // used by the "theme" part, not by a rule if (right.equals(Permission.UI_THEME) || right.equals(Permission.UI_ICONS)) continue; // used by their own part
boolean used = false; boolean used = false;
for (Rule rule : rules) used = used || rule.uses(right); for (Rule rule : rules) used = used || rule.uses(right);
if (!used) throw new LtpException("Плагин просит право «" + right + "», но не использует его"); if (!used) throw new LtpException("Плагин просит право «" + right + "», но не использует его");
} }
Set<String> names = new java.util.TreeSet<String>(files.keySet()); Set<String> names = new java.util.TreeSet<String>(files.keySet());
List<String> hosts = checkNet(root.get("net"), permissions, rules, names); List<String> hosts = checkNet(root.get("net"), permissions, rules, names);
if (theme != null) {
for (String card : theme.preview) {
if (!names.contains(card)) {
throw new LtpException("plugin.json, «theme», поле «preview»: в плагине нет файла assets/" + card);
}
}
}
for (Map.Entry<String, String> icon : icons.entrySet()) {
if (!names.contains(icon.getValue())) {
throw new LtpException("plugin.json, «icons»: в плагине нет файла assets/" + icon.getValue());
}
}
Set<String> known = new java.util.TreeSet<String>(names); Set<String> known = new java.util.TreeSet<String>(names);
for (Rule rule : rules) { for (Rule rule : rules) {
for (DownloadSpec download : rule.downloads()) known.add(download.as); for (DownloadSpec download : rule.downloads()) known.add(download.as);
@@ -161,7 +189,37 @@ public final class Plugin {
for (OverlaySpec spec : rule.overlays()) spec.check(known, "Правило «" + rule.title + "»"); 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, return new Plugin(id, name, version, author, description, permissions, rules, sha256(bytes, files), names, hosts,
license, ai, theme); license, ai, theme, icons);
}
/**
* The "icons" part of the manifest: {"like": "heart.png", "comment": "bubble.png"}. It is there exactly when the plugin
* has the right ui.icons; every slot is one of the buttons of the feed and every file is a picture (png, gif or webp).
*/
private static Map<String, String> parseIcons(Object node, List<String> permissions) throws LtpException {
boolean right = permissions.contains(Permission.UI_ICONS);
Map<String, String> icons = new LinkedHashMap<String, String>();
if (node == null) {
if (right) throw new LtpException("plugin.json: право «ui.icons» требует поле «icons»");
return icons;
}
if (!right) throw new LtpException("plugin.json: есть «icons», но нет права «ui.icons»");
Map<String, Object> map = Fields.map(node, "plugin.json, «icons»");
for (String key : map.keySet()) {
if (!Fields.in(key, ICON_SLOTS)) {
throw new LtpException("plugin.json, «icons»: нет кнопки «" + key + "» (можно like, comment, collect, share)");
}
}
for (String slot : ICON_SLOTS) {
if (map.get(slot) == null) continue;
String file = Fields.text(map.get(slot), 40, "plugin.json, «icons», «" + slot + "»");
if (!"image".equals(OverlaySpec.kind(file))) {
throw new LtpException("plugin.json, «icons», «" + slot + "»: это png, gif или webp, а не «" + file + "»");
}
icons.put(slot, file);
}
if (icons.isEmpty()) throw new LtpException("plugin.json, «icons»: назовите хотя бы одну кнопку");
return icons;
} }
/** /**

View File

@@ -45,8 +45,12 @@ public final class PluginEngine {
final List<Plugin> feed; final List<Plugin> feed;
final List<Plugin> names; final List<Plugin> names;
final List<Screen> screens; final List<Screen> screens;
/** The active plugins that bring pictures for the feed buttons. */
final List<Screen> icons;
Snapshot(String uid, int version, long at, List<Plugin> feed, List<Plugin> names, List<Screen> screens) { Snapshot(String uid, int version, long at, List<Plugin> feed, List<Plugin> names, List<Screen> screens,
List<Screen> icons) {
this.icons = icons;
this.uid = uid; this.uid = uid;
this.version = version; this.version = version;
this.at = at; this.at = at;
@@ -106,7 +110,7 @@ public final class PluginEngine {
private static final List<Plugin> NONE = Collections.<Plugin>emptyList(); private static final List<Plugin> NONE = Collections.<Plugin>emptyList();
private static final List<Screen> NO_SCREENS = Collections.<Screen>emptyList(); private static final List<Screen> NO_SCREENS = Collections.<Screen>emptyList();
private static volatile Snapshot snapshot = new Snapshot("", -1, 0L, NONE, NONE, NO_SCREENS); private static volatile Snapshot snapshot = new Snapshot("", -1, 0L, NONE, NONE, NO_SCREENS, NO_SCREENS);
private static final ThreadLocal<Boolean> BUSY = new ThreadLocal<Boolean>(); private static final ThreadLocal<Boolean> BUSY = new ThreadLocal<Boolean>();
private static final Map<String, ArrayDeque<Long>> SHOWN = new HashMap<String, ArrayDeque<Long>>(); private static final Map<String, ArrayDeque<Long>> SHOWN = new HashMap<String, ArrayDeque<Long>>();
private static final Set<String> LOGGED_NAMES = new HashSet<String>(); private static final Set<String> LOGGED_NAMES = new HashSet<String>();
@@ -135,6 +139,7 @@ public final class PluginEngine {
List<Plugin> feed = new ArrayList<Plugin>(); List<Plugin> feed = new ArrayList<Plugin>();
List<Plugin> names = new ArrayList<Plugin>(); List<Plugin> names = new ArrayList<Plugin>();
List<Screen> screens = new ArrayList<Screen>(); List<Screen> screens = new ArrayList<Screen>();
List<Screen> icons = new ArrayList<Screen>();
int version = PluginRegistry.version(); int version = PluginRegistry.version();
try { try {
uid = CurrentAccount.uid(); uid = CurrentAccount.uid();
@@ -144,18 +149,36 @@ public final class PluginEngine {
if (entry.plugin.hasRulesFor(Rule.FEED)) feed.add(entry.plugin); if (entry.plugin.hasRulesFor(Rule.FEED)) feed.add(entry.plugin);
if (entry.plugin.hasRulesFor(Rule.NAME)) names.add(entry.plugin); if (entry.plugin.hasRulesFor(Rule.NAME)) names.add(entry.plugin);
if (entry.plugin.hasRulesFor(Rule.SCREEN)) screens.add(new Screen(entry.plugin, entry.folder)); if (entry.plugin.hasRulesFor(Rule.SCREEN)) screens.add(new Screen(entry.plugin, entry.folder));
if (!entry.plugin.icons.isEmpty()) icons.add(new Screen(entry.plugin, entry.folder));
} }
} }
if (!feed.isEmpty() || !names.isEmpty() || !screens.isEmpty()) PluginRegistry.started(context); if (!feed.isEmpty() || !names.isEmpty() || !screens.isEmpty() || !icons.isEmpty()) PluginRegistry.started(context);
} catch (Throwable unreadable) { } catch (Throwable unreadable) {
feed.clear(); feed.clear();
names.clear(); names.clear();
screens.clear(); screens.clear();
icons.clear();
} }
snapshot = new Snapshot(uid == null ? "" : uid, version, time, feed, names, screens); snapshot = new Snapshot(uid == null ? "" : uid, version, time, feed, names, screens, icons);
return snapshot; return snapshot;
} }
/** The picture files for the feed buttons by slot, from the active plugins (a later plugin wins); empty when none. */
public static Map<String, File> icons() {
Map<String, File> found = new java.util.LinkedHashMap<String, File>();
try {
for (Screen screen : current().icons) {
for (Map.Entry<String, String> icon : screen.plugin.icons.entrySet()) {
File file = new File(new File(screen.folder, "assets"), icon.getValue());
if (file.isFile()) found.put(icon.getKey(), file);
}
}
} catch (Throwable failure) {
found.clear();
}
return found;
}
/** Whether any plugin hooks the feed right now (asked once per page, before the items). */ /** Whether any plugin hooks the feed right now (asked once per page, before the items). */
public static boolean feedActive() { public static boolean feedActive() {
try { try {

View File

@@ -57,6 +57,11 @@ public final class PluginScreen {
/** Called for every screen of the app that comes to the front. Never throws. */ /** Called for every screen of the app that comes to the front. Never throws. */
public static void attach(Activity activity) { public static void attach(Activity activity) {
try {
IconSkin.attach(activity);
} catch (Throwable failure) {
note("icons failed: " + failure);
}
try { try {
sync(activity); sync(activity);
} catch (Throwable failure) { } catch (Throwable failure) {

View File

@@ -16,6 +16,7 @@ public final class ThemeData {
public static final int MAX_RADIUS = 40; public static final int MAX_RADIUS = 40;
public static final int MAX_OUTLINE = 6; public static final int MAX_OUTLINE = 6;
public static final int MAX_SHADOW = 12; public static final int MAX_SHADOW = 12;
public static final int MAX_PREVIEW = 4;
public final String name; public final String name;
public final boolean dark; public final boolean dark;
@@ -34,9 +35,13 @@ public final class ThemeData {
public final boolean bevel; public final boolean bevel;
public final boolean tickBox; public final boolean tickBox;
public final boolean titleBars; public final boolean titleBars;
/** Pictures the author attached (assets/): cards shown in the list of looks before the theme is picked. */
public final java.util.List<String> preview;
private ThemeData(String name, boolean dark, int page, int card, int text, int muted, int accent, int onAccent, int line, 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) { int titleFrom, int titleTo, int radius, int outline, int shadow, boolean bevel, boolean tickBox, boolean titleBars,
java.util.List<String> preview) {
this.preview = java.util.Collections.unmodifiableList(preview);
this.name = name; this.name = name;
this.dark = dark; this.dark = dark;
this.page = page; this.page = page;
@@ -60,7 +65,7 @@ public final class ThemeData {
Map<String, Object> map = Fields.map(node, where); Map<String, Object> map = Fields.map(node, where);
for (String key : map.keySet()) { for (String key : map.keySet()) {
if (!Fields.in(key, "name", "dark", "page", "card", "text", "muted", "accent", "on_accent", "line", "title_from", 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")) { "title_to", "radius", "outline", "shadow", "bevel", "tick_box", "title_bars", "preview")) {
throw new LtpException(where + ": нет поля «" + key + "»"); throw new LtpException(where + ": нет поля «" + key + "»");
} }
} }
@@ -79,7 +84,27 @@ public final class ThemeData {
int outline = number(map, "outline", 0, MAX_OUTLINE, where); int outline = number(map, "outline", 0, MAX_OUTLINE, where);
int shadow = number(map, "shadow", 0, MAX_SHADOW, 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, 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)); radius, outline, shadow, flag(map, "bevel", where), flag(map, "tick_box", where), flag(map, "title_bars", where),
preview(map, where));
}
/** The preview cards: up to four picture files (png, gif or webp) of the plugin's assets/. */
private static java.util.List<String> preview(Map<String, Object> map, String where) throws LtpException {
java.util.List<String> files = new java.util.ArrayList<String>();
if (map.get("preview") == null) return files;
java.util.List<Object> listed = Fields.list(map.get("preview"), where + ", поле «preview»");
if (listed.isEmpty() || listed.size() > MAX_PREVIEW) {
throw new LtpException(where + ", поле «preview»: от 1 до " + MAX_PREVIEW + " картинок");
}
for (Object item : listed) {
String file = Fields.text(item, 40, where + ", поле «preview»");
if (!"image".equals(OverlaySpec.kind(file))) {
throw new LtpException(where + ", поле «preview»: это png, gif или webp, а не «" + file + "»");
}
if (files.contains(file)) throw new LtpException(where + ", поле «preview»: «" + file + "» названо дважды");
files.add(file);
}
return files;
} }
/** A colour as "#rrggbb" (the # and six hex digits), returned as 0xRRGGBB. */ /** A colour as "#rrggbb" (the # and six hex digits), returned as 0xRRGGBB. */

View File

@@ -437,10 +437,13 @@ public final class LihonTSettingsActivity extends Activity {
final java.util.List<String> ids = new java.util.ArrayList<String>(); final java.util.List<String> ids = new java.util.ArrayList<String>();
final java.util.List<String> names = new java.util.ArrayList<String>(); final java.util.List<String> names = new java.util.ArrayList<String>();
final java.util.List<String> hints = new java.util.ArrayList<String>(); final java.util.List<String> hints = new java.util.ArrayList<String>();
final java.util.List<lihont.two.plugin.PluginRegistry.Entry> owners = new java.util.ArrayList<lihont.two.plugin.PluginRegistry.Entry>();
ids.add("md3"); ids.add("md3");
owners.add(null);
names.add("Material 3"); names.add("Material 3");
hints.add("Мягкие скругления и цвета вашей палитры"); hints.add("Мягкие скругления и цвета вашей палитры");
for (ThemeSpec spec : ThemeSpec.BUILT_IN) { for (ThemeSpec spec : ThemeSpec.BUILT_IN) {
owners.add(null);
ids.add(spec.id); ids.add(spec.id);
names.add(spec.name); names.add(spec.name);
hints.add(spec.id.equals("win95") ? "Серые окна, объёмные кнопки, синие заголовки и галочки" hints.add(spec.id.equals("win95") ? "Серые окна, объёмные кнопки, синие заголовки и галочки"
@@ -448,10 +451,12 @@ public final class LihonTSettingsActivity extends Activity {
} }
for (lihont.two.plugin.PluginRegistry.Entry entry : lihont.two.plugin.PluginRegistry.entries(this)) { for (lihont.two.plugin.PluginRegistry.Entry entry : lihont.two.plugin.PluginRegistry.entries(this)) {
if (entry.plugin == null || !entry.approved || entry.plugin.theme == null) continue; if (entry.plugin == null || !entry.approved || entry.plugin.theme == null) continue;
owners.add(entry);
ids.add("plugin:" + entry.id); ids.add("plugin:" + entry.id);
names.add(entry.plugin.theme.name + " (плагин)"); names.add(entry.plugin.theme.name + " (плагин)");
hints.add("Тема из плагина «" + entry.plugin.name + "», автор " + entry.plugin.author); hints.add("Тема из плагина «" + entry.plugin.name + "», автор " + entry.plugin.author);
} }
owners.add(null);
ids.add("classic"); ids.add("classic");
names.add("Обычный TikTok"); names.add("Обычный TikTok");
hints.add("Плоский вид Serena 1.2"); hints.add("Плоский вид Serena 1.2");
@@ -468,6 +473,8 @@ public final class LihonTSettingsActivity extends Activity {
item.setClickable(true); item.setClickable(true);
item.addView(Md3.text(this, names.get(i) + (current ? " ✓" : ""), Md3.BODY_LARGE, true, palette.onSurface)); 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.addView(Md3.text(this, hints.get(i), Md3.BODY_MEDIUM, false, palette.onSurfaceVariant));
View cards = themeCards(owners.get(i));
if (cards != null) item.addView(cards);
item.setOnClickListener(v -> { item.setOnClickListener(v -> {
shown[0].dismiss(); shown[0].dismiss();
ThemeEngine.set(this, id.equals("md3") || id.equals("classic") ? null : id); ThemeEngine.set(this, id.equals("md3") || id.equals("classic") ? null : id);
@@ -481,6 +488,49 @@ public final class LihonTSettingsActivity extends Activity {
shown[0] = bubbleDialog("Оформление", scroll, null, null); shown[0] = bubbleDialog("Оформление", scroll, null, null);
} }
/** The preview cards an author attached to a theme plugin, as a row that scrolls sideways; null when there are none. */
private View themeCards(lihont.two.plugin.PluginRegistry.Entry entry) {
if (entry == null || entry.plugin == null || entry.plugin.theme == null || entry.plugin.theme.preview.isEmpty()) return null;
android.widget.HorizontalScrollView scroll = new android.widget.HorizontalScrollView(this);
scroll.setHorizontalScrollBarEnabled(false);
LinearLayout row = new LinearLayout(this);
row.setOrientation(LinearLayout.HORIZONTAL);
int height = Md3.dp(this, 120);
for (String name : entry.plugin.theme.preview) {
File file = entry.asset(name);
if (file == null) continue;
Bitmap card = decodeCard(file, height);
if (card == null) continue;
ImageView picture = new ImageView(this);
picture.setImageBitmap(card);
picture.setScaleType(ImageView.ScaleType.FIT_CENTER);
picture.setAdjustViewBounds(true);
picture.setContentDescription("Превью темы «" + entry.plugin.theme.name + "»");
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(-2, height);
params.rightMargin = Md3.dp(this, 8);
params.topMargin = Md3.dp(this, 8);
row.addView(picture, params);
}
if (row.getChildCount() == 0) return null;
scroll.addView(row);
return scroll;
}
/** A card picture scaled down while it is read, so that a few cards cost little memory. */
private static Bitmap decodeCard(File file, int heightPx) {
try {
BitmapFactory.Options bounds = new BitmapFactory.Options();
bounds.inJustDecodeBounds = true;
BitmapFactory.decodeFile(file.getPath(), bounds);
if (bounds.outHeight <= 0) return null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = Math.max(1, bounds.outHeight / Math.max(1, heightPx * 2));
return BitmapFactory.decodeFile(file.getPath(), options);
} catch (RuntimeException | OutOfMemoryError unreadable) {
return null;
}
}
/** Several photos in one comment (TikTok's own picker, up to nine); a choice about the app, so it has its own store. */ /** 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() { private View commentPhotosRow() {
Md3Switch toggle = new Md3Switch(this, palette); Md3Switch toggle = new Md3Switch(this, palette);

View File

@@ -363,6 +363,26 @@ class AgreesWithTheApp(unittest.TestCase):
del no_theme["theme"] del no_theme["theme"]
refused(no_theme, "ui.theme") refused(no_theme, "ui.theme")
def test_the_preview_cards_of_a_theme_are_checked(self):
png = bytes([0x89]) + b"PNG" + bytes([0x0D, 0x0A, 0x1A, 0x0A]) + bytes(32)
good = self.theme_manifest(preview=["a.png", "b.png"])
validate.check_manifest(good, {"a.png": png, "b.png": png})
text = guard_module.check(good, ["a.png", "b.png"]).text()
self.assertIn("К теме приложены картинки-превью", text)
def refused(manifest, word, assets):
with self.assertRaises(LtpError) as caught:
validate.check_manifest(manifest, assets)
self.assertIn(word, str(caught.exception))
refused(self.theme_manifest(preview=["a.png"]), "a.png", {})
refused(self.theme_manifest(preview=["a.ogg"]), "png, gif или webp", {})
refused(self.theme_manifest(preview=[]), "от 1 до 4", {})
refused(self.theme_manifest(preview=["a.png"] * 2), "дважды", {"a.png": png})
refused(self.theme_manifest(preview=["%d.png" % n for n in range(5)]), "от 1 до 4", {})
java = self.java_says([self.folder_of("previewed", good, {"a.png": png, "b.png": png})])
self.assertEqual(java["previewed"], text)
def test_a_theme_can_come_with_rules_and_the_right_is_not_asked_to_be_used_by_a_rule(self): def test_a_theme_can_come_with_rules_and_the_right_is_not_asked_to_be_used_by_a_rule(self):
both = self.theme_manifest() both = self.theme_manifest()
both["permissions"] = ["feed.hide", "ui.theme"] both["permissions"] = ["feed.hide", "ui.theme"]
@@ -391,6 +411,46 @@ class AgreesWithTheApp(unittest.TestCase):
java = self.java_says([self.folder_of("fun", manifest, {"star.png": png})]) java = self.java_says([self.folder_of("fun", manifest, {"star.png": png})])
self.assertEqual(java["fun"], python) self.assertEqual(java["fun"], python)
def icons_manifest(self, **icons):
return {"ltp": 1, "id": "lihont.icons-test", "name": "Значки", "version": "1.0", "author": "тест",
"license": "MIT", "permissions": ["ui.icons"], "icons": icons or {"like": "heart.png"}}
def test_icons_are_checked_like_the_app_checks_them(self):
png = bytes([0x89]) + b"PNG" + bytes([0x0D, 0x0A, 0x1A, 0x0A]) + bytes(32)
validate.check_manifest(self.icons_manifest(like="heart.png", share="plane.png"), {"heart.png": png, "plane.png": png})
def refused(manifest, word, assets=None):
with self.assertRaises(LtpError) as caught:
validate.check_manifest(manifest, {"heart.png": png} if assets is None else assets)
self.assertIn(word, str(caught.exception))
no_right = self.icons_manifest()
no_right["permissions"] = []
refused(no_right, "ui.icons")
no_field = self.icons_manifest()
del no_field["icons"]
refused(no_field, "ui.icons")
refused(self.icons_manifest(follow="x.png"), "нет кнопки")
refused(self.icons_manifest(like="heart.ogg"), "png, gif или webp")
refused(self.icons_manifest(like="heart.png"), "heart.png", assets={})
empty = self.icons_manifest()
empty["icons"] = {}
refused(empty, "хотя бы одну")
def test_icons_get_identical_words_in_both_defenders(self):
png = bytes([0x89]) + b"PNG" + bytes([0x0D, 0x0A, 0x1A, 0x0A]) + bytes(32)
manifest = self.icons_manifest(share="plane.png", like="heart.png")
python = guard_module.check(manifest, ["heart.png", "plane.png"]).text()
self.assertIn("Значки кнопок в ленте (лайк, поделиться)", python)
self.assertIn("Меняет картинки кнопок справа в ленте", python)
java = self.java_says([self.folder_of("icons", manifest, {"heart.png": png, "plane.png": png})])
self.assertEqual(java["icons"], python)
def test_the_feed_buttons_are_found_by_the_sentences_they_say(self):
source = (ROOT / "src" / "lihont" / "two" / "plugin" / "IconSkin.java").read_text(encoding="utf-8")
for sentence in ("поставить лайк", "прочитать или оставить комментар", "добавьте это видео в избранное", "поделиться видео"):
self.assertIn(sentence, source)
def test_the_hash_the_review_prints_is_the_one_the_app_shows(self): def test_the_hash_the_review_prints_is_the_one_the_app_shows(self):
from lihont_ltp import review from lihont_ltp import review
folders, expected = [], {} folders, expected = [], {}