LihonT 2 Luna pre-release 2
Streak widget from 1x1 to 4x4 with an animated flame (orange while lit, grey when not), a streak keeper that writes the chosen message once a day to the chosen chats (off until switched on), avatar shapes, widgets and the keeper kept per account, Material 3 tonal surfaces instead of black (AMOLED keeps pure black), launcher previews of our own, and the mod runtime in a dex of its own. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1047
lihont/axml.py
1047
lihont/axml.py
File diff suppressed because it is too large
Load Diff
36
lihont/streak_patch.py
Normal file
36
lihont/streak_patch.py
Normal file
@@ -0,0 +1,36 @@
|
||||
"""Declare the receiver of the streak keeper's alarm in TikTok's manifest.
|
||||
|
||||
The keeper (lihont.two.streak.AutoFlame) wakes at the time the user chose through an alarm, and an alarm needs a
|
||||
receiver that is named in the manifest. The receiver is not exported: only the alarm the app sets for itself can
|
||||
reach it. Nothing else is added: no permission is asked (the alarm is the kind that needs none) and no intent filter
|
||||
is given, so no other app can start it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Dict
|
||||
|
||||
from . import manifest as manifest_module
|
||||
from .axml import Axml
|
||||
|
||||
RECEIVER = "lihont.two.streak.AutoFlameReceiver"
|
||||
|
||||
|
||||
class StreakError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def has_receiver(xml: Axml, class_name: str) -> bool:
|
||||
return any(xml.attr_string(node, "name") == class_name for node in xml.elements("receiver"))
|
||||
|
||||
|
||||
def apply(apk, xml: Axml) -> Dict[str, object]:
|
||||
"""Add the receiver to the manifest object `xml` and write the manifest into the apk."""
|
||||
if has_receiver(xml, RECEIVER):
|
||||
raise StreakError("%s is already declared" % RECEIVER)
|
||||
receiver = xml.make_element("receiver")
|
||||
xml.set_attr_string(receiver, "name", RECEIVER)
|
||||
xml.set_attr_bool(receiver, "exported", False)
|
||||
xml.insert_into(manifest_module.application(xml), [receiver, xml.close_element(receiver)])
|
||||
apk.replace("AndroidManifest.xml", xml.build())
|
||||
return {"receiver": RECEIVER, "exported": False}
|
||||
1198
lihont/upgrade.py
1198
lihont/upgrade.py
File diff suppressed because it is too large
Load Diff
280
lihont/widget_patch.py
Normal file
280
lihont/widget_patch.py
Normal file
@@ -0,0 +1,280 @@
|
||||
"""Turn four of TikTok's own home-screen widgets into the LihonT streak widget in four sizes.
|
||||
|
||||
TikTok already ships six widgets, so nothing has to be added to the resource table. Each widget is declared in
|
||||
the manifest by class name and described by a small provider file (size, layout, update period). The rewrite
|
||||
|
||||
* points four of those receivers at lihont.two.widget.StreakWidget1 / StreakWidget / StreakWidget3 /
|
||||
StreakWidget4 (1x1, 2x2, 3x3 and 4x4 cells) and gives them one name for the widget picker,
|
||||
* rewrites their provider files: the size, the layout (every size draws into the layout of the small
|
||||
Stories widget, whose picture view is all the widget needs), resizing in both directions (down to one
|
||||
cell), no TikTok description or preview layout, and a configuration screen
|
||||
(lihont.two.widget.StreakConfigActivity) that the launcher opens when the widget is dropped and which
|
||||
lets the user choose the chat,
|
||||
* declares that screen in the manifest,
|
||||
* makes the layout the widgets draw into as large as the widget (TikTok fixes it at 132dp, which cut the
|
||||
middle out of a one-cell widget),
|
||||
* puts our flower picture in the place of TikTok's previews in the launcher's widget list.
|
||||
|
||||
Every step refuses a file that does not look the way it did when it was read.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Dict, List
|
||||
|
||||
from . import manifest as manifest_module
|
||||
from .arsc import Arsc
|
||||
from .axml import Attribute, Axml, NO_ENTRY, Node, RES_XML_END_ELEMENT, RES_XML_START_ELEMENT
|
||||
|
||||
TYPE_REFERENCE = 0x01
|
||||
TYPE_DIMENSION = 0x05
|
||||
TYPE_INT_DEC = 0x10
|
||||
TYPE_INT_HEX = 0x11
|
||||
|
||||
LAYOUT = 0x7F0D0178 # TikTok's layout of the small Stories widget: one picture view
|
||||
LAYOUT_FILE = "res/b/pr.xml"
|
||||
PICTURE = 0x7F0A1DAB # its picture view
|
||||
MATCH_PARENT = 0xFFFFFFFF
|
||||
# The animated widget: a ViewFlipper (FLIPPER_VIEW) holds the picture view (frame 0, PICTURE) and three more
|
||||
# (FRAME_VIEWS). All of them are ids TikTok's resource table already has; StreakWidget.java repeats them, and
|
||||
# tests/test_widget_patch.py checks the two lists agree.
|
||||
FLIPPER_VIEW = 0x7F0A1DAA
|
||||
FRAME_VIEWS = (0x7F0A1DAC, 0x7F0A1DAD, 0x7F0A1DAE)
|
||||
FLIP_INTERVAL_MS = 450
|
||||
ANIM_FADE_IN = 0x010A0000 # android.R.anim.fade_in
|
||||
ANIM_FADE_OUT = 0x010A0001 # android.R.anim.fade_out
|
||||
# The layout file has no attribute names left, only resource ids.
|
||||
ATTR_ID = 0x010100D0
|
||||
ATTR_LAYOUT_WIDTH = 0x010100F4
|
||||
ATTR_LAYOUT_HEIGHT = 0x010100F5
|
||||
CONFIG_CLASS = "lihont.two.widget.StreakConfigActivity"
|
||||
LABEL = "Огонёк LihonT"
|
||||
CONFIG_LABEL = "Огонёк"
|
||||
CONFIGURE_ACTION = "android.appwidget.action.APPWIDGET_CONFIGURE"
|
||||
UPDATE_PERIOD_MS = 1800000
|
||||
RESIZE_BOTH = 3 # horizontal | vertical
|
||||
MAX_RESIZE_DP = 320
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Size:
|
||||
cells: int
|
||||
original: str # the TikTok receiver that is reused
|
||||
provider: str # its provider file in the apk
|
||||
widget: str # our class that replaces it
|
||||
|
||||
|
||||
SIZES: List[Size] = [
|
||||
Size(1, "com.ss.android.ugc.aweme.core.SmallAppWidgetProvider", "res/au/d.xml", "lihont.two.widget.StreakWidget1"),
|
||||
Size(2, "com.ss.android.ugc.aweme.story.widget.SmallStoryWidget", "res/au/g.xml", "lihont.two.widget.StreakWidget"),
|
||||
Size(3, "com.ss.android.ugc.aweme.search.widget.core.ui.SearchMiddleWidget", "res/au/e.xml", "lihont.two.widget.StreakWidget3"),
|
||||
Size(4, "com.ss.android.ugc.aweme.story.widget.LargeStoryWidget", "res/au/f.xml", "lihont.two.widget.StreakWidget4"),
|
||||
]
|
||||
|
||||
|
||||
class WidgetError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def dp(value: int) -> int:
|
||||
"""A dimension in dp as the binary XML stores it."""
|
||||
return (value << 8) | 0x01
|
||||
|
||||
|
||||
def cell_dp(cells: int) -> int:
|
||||
"""The least size in dp that makes a launcher give a widget this many cells."""
|
||||
return 70 * cells - 30
|
||||
|
||||
|
||||
def _receiver(xml: Axml, name: str):
|
||||
for node in xml.elements("receiver"):
|
||||
if xml.attr_string(node, "name") == name:
|
||||
return node
|
||||
return None
|
||||
|
||||
|
||||
def retarget_manifest(xml: Axml, theme: int) -> Dict[str, object]:
|
||||
"""The manifest side: the four receivers and the configuration screen."""
|
||||
if any(_receiver(xml, size.widget) is not None for size in SIZES):
|
||||
raise WidgetError("the widget is already declared")
|
||||
done = {}
|
||||
for size in SIZES:
|
||||
node = _receiver(xml, size.original)
|
||||
if node is None:
|
||||
raise WidgetError("receiver %s not found" % size.original)
|
||||
xml.set_attr_string(node, "name", size.widget)
|
||||
xml.set_attr_string(node, "label", LABEL)
|
||||
done["%dx%d" % (size.cells, size.cells)] = size.widget
|
||||
|
||||
if manifest_module.has_activity(xml, CONFIG_CLASS):
|
||||
raise WidgetError("%s is already declared" % CONFIG_CLASS)
|
||||
activity = xml.make_element("activity")
|
||||
xml.set_attr(activity, "theme", manifest_module.TYPE_REFERENCE, theme)
|
||||
xml.set_attr_string(activity, "label", CONFIG_LABEL)
|
||||
xml.set_attr_string(activity, "name", CONFIG_CLASS)
|
||||
xml.set_attr_bool(activity, "exported", True)
|
||||
intent_filter = xml.make_element("intent-filter")
|
||||
action = xml.make_element("action")
|
||||
xml.set_attr_string(action, "name", CONFIGURE_ACTION)
|
||||
xml.insert_into(manifest_module.application(xml), [
|
||||
activity, intent_filter, action, xml.close_element(action),
|
||||
xml.close_element(intent_filter), xml.close_element(activity),
|
||||
])
|
||||
return {"receivers": done, "label": LABEL, "configure": CONFIG_CLASS}
|
||||
|
||||
|
||||
def rewrite_provider(provider: Axml, cells: int) -> None:
|
||||
"""The provider description side: size, layout, resizing and the configuration screen."""
|
||||
found = [n for n in provider.nodes
|
||||
if n.kind == RES_XML_START_ELEMENT and provider.pool.get(n.name) == "appwidget-provider"]
|
||||
if len(found) != 1:
|
||||
raise WidgetError("expected one appwidget-provider element, found %d" % len(found))
|
||||
node = found[0]
|
||||
if provider.attr(node, "configure") is not None:
|
||||
raise WidgetError("the provider description already has a configuration screen")
|
||||
# what TikTok says about its own widget does not apply to ours
|
||||
node.attributes = [a for a in node.attributes
|
||||
if provider.pool.get(a.name) not in ("description", "previewLayout")]
|
||||
size = cell_dp(cells)
|
||||
provider.set_attr(node, "minWidth", TYPE_DIMENSION, dp(size))
|
||||
provider.set_attr(node, "minHeight", TYPE_DIMENSION, dp(size))
|
||||
provider.set_attr(node, "targetCellWidth", TYPE_INT_DEC, cells)
|
||||
provider.set_attr(node, "targetCellHeight", TYPE_INT_DEC, cells)
|
||||
provider.set_attr(node, "resizeMode", TYPE_INT_HEX, RESIZE_BOTH)
|
||||
provider.set_attr(node, "minResizeWidth", TYPE_DIMENSION, dp(cell_dp(1)))
|
||||
provider.set_attr(node, "minResizeHeight", TYPE_DIMENSION, dp(cell_dp(1)))
|
||||
provider.set_attr(node, "maxResizeWidth", TYPE_DIMENSION, dp(MAX_RESIZE_DP))
|
||||
provider.set_attr(node, "maxResizeHeight", TYPE_DIMENSION, dp(MAX_RESIZE_DP))
|
||||
provider.set_attr(node, "updatePeriodMillis", TYPE_INT_DEC, UPDATE_PERIOD_MS)
|
||||
provider.set_attr_ref(node, "initialLayout", LAYOUT)
|
||||
provider.set_attr_string(node, "configure", CONFIG_CLASS)
|
||||
|
||||
|
||||
def _attr_by_id(xml: Axml, node, resource_id: int):
|
||||
"""An attribute found by its resource id (the layout file has stripped every attribute name)."""
|
||||
for a in node.attributes:
|
||||
if 0 <= a.name < len(xml.resource_map) and xml.resource_map[a.name] == resource_id:
|
||||
return a
|
||||
return None
|
||||
|
||||
|
||||
def _picture(layout: Axml):
|
||||
"""The root element and the picture view of the widget layout, or a WidgetError."""
|
||||
elements = [n for n in layout.nodes if n.kind == RES_XML_START_ELEMENT]
|
||||
if not elements or layout.pool.get(elements[0].name) != "RelativeLayout":
|
||||
raise WidgetError("the widget layout does not start with a RelativeLayout")
|
||||
for node in elements:
|
||||
if layout.pool.get(node.name) != "ImageView":
|
||||
continue
|
||||
ident = _attr_by_id(layout, node, ATTR_ID)
|
||||
if ident is not None and ident.data == PICTURE:
|
||||
return elements[0], node
|
||||
raise WidgetError("the picture view is not in the widget layout")
|
||||
|
||||
|
||||
def animate_layout(layout: Axml) -> None:
|
||||
"""Put the picture view into a ViewFlipper with three more picture views behind it.
|
||||
|
||||
A widget cannot run code of its own, but its host can flip a ViewFlipper by itself: the widget fills the four
|
||||
pictures with the frames of the flame (see FlowerArt) and the launcher shows them one after another, blending
|
||||
each into the next. Frame 0 is the old picture view, so a widget that draws only that one still works.
|
||||
Run after fill_layout: the new pictures copy the size the first one has.
|
||||
"""
|
||||
_, picture = _picture(layout)
|
||||
start = layout.nodes.index(picture)
|
||||
if layout.nodes[start + 1].kind != RES_XML_END_ELEMENT:
|
||||
raise WidgetError("the picture view of the widget layout has children")
|
||||
|
||||
flipper = layout.make_element("ViewFlipper")
|
||||
layout.set_attr(flipper, "id", TYPE_REFERENCE, FLIPPER_VIEW)
|
||||
layout.set_attr(flipper, "layout_width", TYPE_INT_DEC, MATCH_PARENT)
|
||||
layout.set_attr(flipper, "layout_height", TYPE_INT_DEC, MATCH_PARENT)
|
||||
layout.set_attr_bool(flipper, "autoStart", True)
|
||||
layout.set_attr(flipper, "flipInterval", TYPE_INT_DEC, FLIP_INTERVAL_MS)
|
||||
layout.set_attr_ref(flipper, "inAnimation", ANIM_FADE_IN)
|
||||
layout.set_attr_ref(flipper, "outAnimation", ANIM_FADE_OUT)
|
||||
flipper.id_index = 1 # the id is the first of its attributes (counted from one)
|
||||
flipper_end = layout.close_element(flipper)
|
||||
|
||||
frames = []
|
||||
for view_id in FRAME_VIEWS:
|
||||
copy = Node(RES_XML_START_ELEMENT, picture.line, picture.comment)
|
||||
copy.ns, copy.name = picture.ns, picture.name
|
||||
copy.id_index, copy.class_index, copy.style_index = picture.id_index, picture.class_index, picture.style_index
|
||||
copy.attributes = [Attribute(a.ns, a.name, a.raw, a.size, a.res0, a.kind, a.data) for a in picture.attributes]
|
||||
_attr_by_id(layout, copy, ATTR_ID).data = view_id
|
||||
frames += [copy, layout.close_element(copy)]
|
||||
|
||||
# the picture and its end tag stay where they are; the flipper opens before them and closes after the frames
|
||||
after_picture = layout.nodes.index(picture) + 2
|
||||
layout.nodes[after_picture:after_picture] = frames + [flipper_end]
|
||||
layout.nodes[start:start] = [flipper]
|
||||
|
||||
|
||||
def fill_layout(layout: Axml) -> None:
|
||||
"""Make the layout the widgets draw into as large as the widget it sits in.
|
||||
|
||||
TikTok's small Stories widget fixes both its root and its picture at 132dp. In a smaller cell (one
|
||||
cell is about 70dp) the launcher showed only the middle of that square, so the flower's petals were
|
||||
cut away and the number ran out of the tile; in a bigger one the picture floated in the middle.
|
||||
"""
|
||||
root, picture = _picture(layout)
|
||||
for node in (root, picture):
|
||||
for resource_id in (ATTR_LAYOUT_WIDTH, ATTR_LAYOUT_HEIGHT):
|
||||
attr = _attr_by_id(layout, node, resource_id)
|
||||
if attr is None:
|
||||
raise WidgetError("the widget layout has no size on %s" % layout.pool.get(node.name))
|
||||
attr.kind = TYPE_INT_DEC
|
||||
attr.data = MATCH_PARENT
|
||||
attr.raw = NO_ENTRY
|
||||
|
||||
|
||||
def preview_files(provider: Axml, table: Arsc) -> List[str]:
|
||||
"""The picture files a provider description points at as its preview in the launcher's widget list."""
|
||||
found = [n for n in provider.nodes
|
||||
if n.kind == RES_XML_START_ELEMENT and provider.pool.get(n.name) == "appwidget-provider"]
|
||||
attr = provider.attr(found[0], "previewImage") if found else None
|
||||
if attr is None or attr.kind != TYPE_REFERENCE:
|
||||
return []
|
||||
paths = []
|
||||
for value in table.values(attr.data):
|
||||
path = table.file_path(value)
|
||||
if path:
|
||||
paths.append(path)
|
||||
return paths
|
||||
|
||||
|
||||
def apply(apk, xml: Axml, theme: int) -> Dict[str, object]:
|
||||
"""Patch the manifest object `xml`, the four provider files, the layout and the previews, and write them into the apk.
|
||||
|
||||
The previews are TikTok's own pictures for the widgets these receivers used to be (a camera, a search bar).
|
||||
In 47.1.3 only the four provider files and the layouts of those same widgets point at them, so the files take
|
||||
the flower of preview_asset() instead; every provider gets the same picture.
|
||||
"""
|
||||
report = retarget_manifest(xml, theme)
|
||||
table = Arsc(apk.read("resources.arsc"))
|
||||
previews = set()
|
||||
for size in SIZES:
|
||||
provider = Axml.parse(apk.read(size.provider))
|
||||
previews.update(preview_files(provider, table)) # read before the rewrite keeps or drops anything
|
||||
rewrite_provider(provider, size.cells)
|
||||
apk.replace(size.provider, provider.build())
|
||||
layout = Axml.parse(apk.read(LAYOUT_FILE))
|
||||
fill_layout(layout)
|
||||
animate_layout(layout)
|
||||
apk.replace(LAYOUT_FILE, layout.build())
|
||||
picture = preview_asset().read_bytes()
|
||||
for path in sorted(previews):
|
||||
apk.replace(path, picture)
|
||||
apk.replace("AndroidManifest.xml", xml.build())
|
||||
report["providers"] = [size.provider for size in SIZES]
|
||||
report["layout"] = LAYOUT_FILE
|
||||
report["previews"] = sorted(previews)
|
||||
return report
|
||||
|
||||
|
||||
def preview_asset() -> Path:
|
||||
"""The flower picture drawn by scripts/make_widget_preview.py."""
|
||||
return Path(__file__).resolve().parent.parent / "src" / "brand" / "widget_preview.png"
|
||||
@@ -1,164 +1,197 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
News cards for the Telegram post about LihonT 2 «Luna pre-release»: 1080x1350 PNGs in work/promo/cards/.
|
||||
Uses the same screenshots and drawing helpers as the promo video (make_lihont_promo.py).
|
||||
|
||||
usage (from the repository root): py -B scripts/make_lihont_cards.py
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import random
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
import make_lihont_promo as P # noqa: E402
|
||||
|
||||
CW, CH = 1080, 1350
|
||||
OUT_DIR = P.ROOT / "work" / "promo" / "cards"
|
||||
|
||||
|
||||
def backdrop(seed: int) -> Image.Image:
|
||||
img = Image.new("RGBA", (CW, CH), P.BG + (255,))
|
||||
rnd = random.Random(seed)
|
||||
spots = [(0.25, 0.2), (0.8, 0.55), (0.3, 0.9)]
|
||||
for n, blob_img in enumerate(P.ASSETS["blobs"]):
|
||||
fx, fy = spots[n]
|
||||
img.alpha_composite(blob_img, (int(CW * fx - blob_img.width / 2), int(CH * fy - blob_img.height / 2)))
|
||||
for _ in range(12):
|
||||
img.alpha_composite(P.ASSETS["flower"], (int(rnd.random() * CW), int(rnd.random() * CH)))
|
||||
return img
|
||||
|
||||
|
||||
def head(layer: Image.Image, title: str, sub: str, y: int = 150) -> None:
|
||||
P.draw_text(layer, (CW / 2, y), title, 84, P.ON + (255,))
|
||||
P.draw_text(layer, (CW / 2, y + 96), sub, 42, P.PRIMARY + (255,), bold=False)
|
||||
|
||||
|
||||
def footer(layer: Image.Image) -> None:
|
||||
P.draw_text(layer, (CW / 2, CH - 44), "LihonT 2 · Luna pre-release · @lihont", 32, P.MUTED + (255,), bold=False)
|
||||
|
||||
|
||||
def card_hero() -> Image.Image:
|
||||
img = backdrop(1)
|
||||
layer = Image.new("RGBA", (CW, CH), (0, 0, 0, 0))
|
||||
P.place(layer, P.ASSETS["blobs"][1], CW / 2, 470, 1.4)
|
||||
P.place(layer, P.ASSETS["logo"], CW / 2, 470, 0.5)
|
||||
P.draw_text(layer, (CW / 2, 830), "LihonT 2", 150, P.ON + (255,))
|
||||
P.draw_text(layer, (CW / 2, 960), "Luna · пре-релиз", 64, P.PRIMARY + (255,))
|
||||
P.draw_text(layer, (CW / 2, 1040), "Мод для TikTok в стиле Material 3", 44, P.MUTED + (255,), bold=False)
|
||||
P.chip(layer, CW / 2, 1170, "Скачать: git.lihont.space", 1.0, size=48, fill=P.PRIMARY, fg=P.BG)
|
||||
P.chip(layer, CW / 2, 1270, "Telegram · @lihont", 1.0, size=40)
|
||||
img.alpha_composite(layer)
|
||||
return img
|
||||
|
||||
|
||||
def card_system() -> Image.Image:
|
||||
img = backdrop(2)
|
||||
layer = Image.new("RGBA", (CW, CH), (0, 0, 0, 0))
|
||||
head(layer, "Всё в стиле Material 3", "Меню, настройки, нижняя панель")
|
||||
P.place(layer, P.ASSETS["phones"]["menu"], 300, 930, 0.82, 6)
|
||||
P.place(layer, P.ASSETS["phones"]["native"], 790, 990, 0.82, -5)
|
||||
img.alpha_composite(layer)
|
||||
return img
|
||||
|
||||
|
||||
def card_comments() -> Image.Image:
|
||||
img = backdrop(3)
|
||||
layer = Image.new("RGBA", (CW, CH), (0, 0, 0, 0))
|
||||
head(layer, "Новые комментарии", "Карточки, ручка шторки, поле-пилюля")
|
||||
P.place(layer, P.ASSETS["phones"]["comments"], CW / 2, 930, 0.95)
|
||||
P.chip(layer, 190, 560, "Карточки", 1.0, size=38)
|
||||
P.chip(layer, 890, 470, "Ручка шторки", 1.0, size=38)
|
||||
P.chip(layer, 860, 1230, "Поле-пилюля", 1.0, size=38)
|
||||
img.alpha_composite(layer)
|
||||
return img
|
||||
|
||||
|
||||
def card_shapes() -> Image.Image:
|
||||
img = backdrop(7)
|
||||
layer = Image.new("RGBA", (CW, CH), (0, 0, 0, 0))
|
||||
head(layer, "Форма аватарок", "Её видят все, у кого есть мод")
|
||||
P.place(layer, P.ASSETS["phones"]["shapes"], CW / 2, 800, 0.62, -3)
|
||||
for n, kind in enumerate(P.SHAPE_KINDS):
|
||||
P.place(layer, P.shape_silhouette(kind, 120, P.PRIMARY), 190 + n * 140, 1230, 1.0)
|
||||
P.chip(layer, 200, 560, "Круг, как в TikTok", 1.0, size=34)
|
||||
P.chip(layer, 880, 640, "Без мода — круг", 1.0, size=34)
|
||||
footer(layer)
|
||||
img.alpha_composite(layer)
|
||||
return img
|
||||
|
||||
|
||||
def card_save() -> Image.Image:
|
||||
img = backdrop(8)
|
||||
layer = Image.new("RGBA", (CW, CH), (0, 0, 0, 0))
|
||||
head(layer, "Скачать как надо", "Качество, звук, все фото")
|
||||
P.place(layer, P.ASSETS["phones"]["save"], CW / 2, 930, 0.95)
|
||||
P.chip(layer, 190, 520, "Без водяного знака", 1.0, size=36)
|
||||
P.chip(layer, 890, 760, "Только звук", 1.0, size=36)
|
||||
P.chip(layer, 880, 1230, "Фото карусели", 1.0, size=36)
|
||||
img.alpha_composite(layer)
|
||||
return img
|
||||
|
||||
|
||||
def card_feed() -> Image.Image:
|
||||
img = backdrop(4)
|
||||
layer = Image.new("RGBA", (CW, CH), (0, 0, 0, 0))
|
||||
head(layer, "Лента без лишнего", "Включай только нужное")
|
||||
first, _second = P.ASSETS["mod_screens"]
|
||||
phone = P.mount(P.ASSETS["mod_shell"], first)
|
||||
P.place(layer, phone, 640, 960, 0.9)
|
||||
for n, text in enumerate(["Без водяного знака", "Убрать рекламу", "Убрать эфиры", "Скрыть «Магазин»"]):
|
||||
P.chip(layer, 230, 520 + n * 190, text, 1.0, size=34)
|
||||
img.alpha_composite(layer)
|
||||
return img
|
||||
|
||||
|
||||
def card_badges() -> Image.Image:
|
||||
img = backdrop(5)
|
||||
layer = Image.new("RGBA", (CW, CH), (0, 0, 0, 0))
|
||||
head(layer, "Значки у ников", "TikTok You, MargyT и нишевый мод")
|
||||
profile = P.ASSETS["shots"]["profile"]
|
||||
card = P.rounded(profile.crop((0, 0, 1080, 900)).resize((940, 783), Image.Resampling.LANCZOS), 56)
|
||||
P.place(layer, card, CW / 2, 720, 1.0)
|
||||
zoom = P.rounded(profile.crop((20, 166, 700, 270)).resize((880, 135), Image.Resampling.LANCZOS), 40)
|
||||
ring = P.rounded(Image.new("RGBA", (896, 151), P.PRIMARY + (255,)), 48)
|
||||
P.place(layer, ring, CW / 2, 1210)
|
||||
P.place(layer, zoom, CW / 2, 1210)
|
||||
footer(layer)
|
||||
img.alpha_composite(layer)
|
||||
return img
|
||||
|
||||
|
||||
def card_icons() -> Image.Image:
|
||||
img = backdrop(6)
|
||||
layer = Image.new("RGBA", (CW, CH), (0, 0, 0, 0))
|
||||
head(layer, "Иконки приложения", "Выбери свою или добавь свою")
|
||||
spots = [(340, 560), (740, 560), (340, 980), (740, 980)]
|
||||
for (slug, label), (x, y) in zip(P.ICONS, spots):
|
||||
P.place(layer, P.ASSETS["icons"][slug], x, y, 1.0)
|
||||
P.draw_text(layer, (x, y + 205), label, 40, P.ON + (255,))
|
||||
footer(layer)
|
||||
img.alpha_composite(layer)
|
||||
return img
|
||||
|
||||
|
||||
def main() -> None:
|
||||
P.init_assets()
|
||||
OUT_DIR.mkdir(parents=True, exist_ok=True)
|
||||
cards = [("1_hero", card_hero), ("2_material3", card_system), ("3_comments", card_comments),
|
||||
("4_shapes", card_shapes), ("5_save", card_save), ("6_feed", card_feed),
|
||||
("7_badges", card_badges), ("8_icons", card_icons)]
|
||||
for name, make in cards:
|
||||
path = OUT_DIR / ("card_%s.png" % name)
|
||||
make().convert("RGB").save(path)
|
||||
print(path)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
News cards for the Telegram post about LihonT 2 «Luna pre-release»: 1080x1350 PNGs in work/promo/cards/.
|
||||
Uses the same screenshots and drawing helpers as the promo video (make_lihont_promo.py).
|
||||
|
||||
usage (from the repository root): py -B scripts/make_lihont_cards.py
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import random
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
import make_lihont_promo as P # noqa: E402
|
||||
|
||||
CW, CH = 1080, 1350
|
||||
OUT_DIR = P.ROOT / "work" / "promo" / "cards"
|
||||
|
||||
|
||||
def backdrop(seed: int) -> Image.Image:
|
||||
img = Image.new("RGBA", (CW, CH), P.BG + (255,))
|
||||
rnd = random.Random(seed)
|
||||
spots = [(0.25, 0.2), (0.8, 0.55), (0.3, 0.9)]
|
||||
for n, blob_img in enumerate(P.ASSETS["blobs"]):
|
||||
fx, fy = spots[n]
|
||||
img.alpha_composite(blob_img, (int(CW * fx - blob_img.width / 2), int(CH * fy - blob_img.height / 2)))
|
||||
for _ in range(12):
|
||||
img.alpha_composite(P.ASSETS["flower"], (int(rnd.random() * CW), int(rnd.random() * CH)))
|
||||
return img
|
||||
|
||||
|
||||
def head(layer: Image.Image, title: str, sub: str, y: int = 150) -> None:
|
||||
P.draw_text(layer, (CW / 2, y), title, 84, P.ON + (255,))
|
||||
P.draw_text(layer, (CW / 2, y + 96), sub, 42, P.PRIMARY + (255,), bold=False)
|
||||
|
||||
|
||||
def footer(layer: Image.Image) -> None:
|
||||
P.draw_text(layer, (CW / 2, CH - 44), "LihonT 2 · Luna · @lihont", 32, P.MUTED + (255,), bold=False)
|
||||
|
||||
|
||||
def card_hero() -> Image.Image:
|
||||
img = backdrop(1)
|
||||
layer = Image.new("RGBA", (CW, CH), (0, 0, 0, 0))
|
||||
P.place(layer, P.ASSETS["blobs"][1], CW / 2, 470, 1.4)
|
||||
P.place(layer, P.ASSETS["logo"], CW / 2, 470, 0.5)
|
||||
P.draw_text(layer, (CW / 2, 830), "LihonT 2", 150, P.ON + (255,))
|
||||
P.draw_text(layer, (CW / 2, 960), "Luna · пре-релиз", 64, P.PRIMARY + (255,))
|
||||
P.draw_text(layer, (CW / 2, 1040), "Мод для TikTok в стиле Material 3", 44, P.MUTED + (255,), bold=False)
|
||||
P.chip(layer, CW / 2, 1170, "Скачать: git.lihont.space", 1.0, size=48, fill=P.PRIMARY, fg=P.BG)
|
||||
P.chip(layer, CW / 2, 1270, "Telegram · @lihont", 1.0, size=40)
|
||||
img.alpha_composite(layer)
|
||||
return img
|
||||
|
||||
|
||||
def card_system() -> Image.Image:
|
||||
img = backdrop(2)
|
||||
layer = Image.new("RGBA", (CW, CH), (0, 0, 0, 0))
|
||||
head(layer, "Всё в стиле Material 3", "Меню, настройки, нижняя панель")
|
||||
P.place(layer, P.ASSETS["phones"]["menu"], 300, 930, 0.82, 6)
|
||||
P.place(layer, P.ASSETS["phones"]["native"], 790, 990, 0.82, -5)
|
||||
img.alpha_composite(layer)
|
||||
return img
|
||||
|
||||
|
||||
def card_comments() -> Image.Image:
|
||||
img = backdrop(3)
|
||||
layer = Image.new("RGBA", (CW, CH), (0, 0, 0, 0))
|
||||
head(layer, "Новые комментарии", "Карточки, ручка шторки, поле-пилюля")
|
||||
P.place(layer, P.ASSETS["phones"]["comments"], CW / 2, 930, 0.95)
|
||||
P.chip(layer, 190, 560, "Карточки", 1.0, size=38)
|
||||
P.chip(layer, 890, 470, "Ручка шторки", 1.0, size=38)
|
||||
P.chip(layer, 860, 1230, "Поле-пилюля", 1.0, size=38)
|
||||
img.alpha_composite(layer)
|
||||
return img
|
||||
|
||||
|
||||
def card_shapes() -> Image.Image:
|
||||
img = backdrop(7)
|
||||
layer = Image.new("RGBA", (CW, CH), (0, 0, 0, 0))
|
||||
head(layer, "Форма аватарок", "Её видят все, у кого есть мод")
|
||||
P.place(layer, P.ASSETS["phones"]["shapes"], CW / 2, 800, 0.62, -3)
|
||||
for n, kind in enumerate(P.SHAPE_KINDS):
|
||||
P.place(layer, P.shape_silhouette(kind, 120, P.PRIMARY), 190 + n * 140, 1230, 1.0)
|
||||
P.chip(layer, 200, 560, "Круг, как в TikTok", 1.0, size=34)
|
||||
P.chip(layer, 880, 640, "Без мода — круг", 1.0, size=34)
|
||||
footer(layer)
|
||||
img.alpha_composite(layer)
|
||||
return img
|
||||
|
||||
|
||||
def card_save() -> Image.Image:
|
||||
img = backdrop(8)
|
||||
layer = Image.new("RGBA", (CW, CH), (0, 0, 0, 0))
|
||||
head(layer, "Скачать как надо", "Качество, звук, все фото")
|
||||
P.place(layer, P.ASSETS["phones"]["save"], CW / 2, 930, 0.95)
|
||||
P.chip(layer, 190, 520, "Без водяного знака", 1.0, size=36)
|
||||
P.chip(layer, 890, 760, "Только звук", 1.0, size=36)
|
||||
P.chip(layer, 880, 1230, "Фото карусели", 1.0, size=36)
|
||||
img.alpha_composite(layer)
|
||||
return img
|
||||
|
||||
|
||||
def card_feed() -> Image.Image:
|
||||
img = backdrop(4)
|
||||
layer = Image.new("RGBA", (CW, CH), (0, 0, 0, 0))
|
||||
head(layer, "Лента без лишнего", "Включай только нужное")
|
||||
first, _second = P.ASSETS["mod_screens"]
|
||||
phone = P.mount(P.ASSETS["mod_shell"], first)
|
||||
P.place(layer, phone, 640, 960, 0.9)
|
||||
for n, text in enumerate(["Без водяного знака", "Убрать рекламу", "Убрать эфиры", "Скрыть «Магазин»"]):
|
||||
P.chip(layer, 230, 520 + n * 190, text, 1.0, size=34)
|
||||
img.alpha_composite(layer)
|
||||
return img
|
||||
|
||||
|
||||
def card_badges() -> Image.Image:
|
||||
img = backdrop(5)
|
||||
layer = Image.new("RGBA", (CW, CH), (0, 0, 0, 0))
|
||||
head(layer, "Значки у ников", "TikTok You, MargyT и нишевый мод")
|
||||
profile = P.ASSETS["shots"]["profile"]
|
||||
card = P.rounded(profile.crop((0, 0, 1080, 900)).resize((940, 783), Image.Resampling.LANCZOS), 56)
|
||||
P.place(layer, card, CW / 2, 720, 1.0)
|
||||
zoom = P.rounded(profile.crop((20, 166, 700, 270)).resize((880, 135), Image.Resampling.LANCZOS), 40)
|
||||
ring = P.rounded(Image.new("RGBA", (896, 151), P.PRIMARY + (255,)), 48)
|
||||
P.place(layer, ring, CW / 2, 1210)
|
||||
P.place(layer, zoom, CW / 2, 1210)
|
||||
footer(layer)
|
||||
img.alpha_composite(layer)
|
||||
return img
|
||||
|
||||
|
||||
def card_icons() -> Image.Image:
|
||||
img = backdrop(6)
|
||||
layer = Image.new("RGBA", (CW, CH), (0, 0, 0, 0))
|
||||
head(layer, "Иконки приложения", "Выбери свою или добавь свою")
|
||||
spots = [(340, 560), (740, 560), (340, 980), (740, 980)]
|
||||
for (slug, label), (x, y) in zip(P.ICONS, spots):
|
||||
P.place(layer, P.ASSETS["icons"][slug], x, y, 1.0)
|
||||
P.draw_text(layer, (x, y + 205), label, 40, P.ON + (255,))
|
||||
footer(layer)
|
||||
img.alpha_composite(layer)
|
||||
return img
|
||||
|
||||
|
||||
def card_flame() -> Image.Image:
|
||||
img = backdrop(9)
|
||||
layer = Image.new("RGBA", (CW, CH), (0, 0, 0, 0))
|
||||
head(layer, "Живой огонёк", "Виджет от 1×1 до 4×4")
|
||||
lit = Image.open(P.ROOT / "src" / "brand" / "widget_preview.png").convert("RGBA")
|
||||
cold = Image.open(P.SHOTS / "luna" / "widget_grey.png").convert("RGBA")
|
||||
P.place(layer, lit, 300, 760, 0.82)
|
||||
P.place(layer, cold, 780, 760, 0.82)
|
||||
P.chip(layer, 300, 1110, "Горит: оранжевый", 1.0, size=38)
|
||||
P.chip(layer, 780, 1110, "Пора писать: серый", 1.0, size=38)
|
||||
P.chip(layer, CW / 2, 1230, "Огонёк качается прямо на экране", 1.0, size=36)
|
||||
footer(layer)
|
||||
img.alpha_composite(layer)
|
||||
return img
|
||||
|
||||
|
||||
def card_keeper() -> Image.Image:
|
||||
img = backdrop(10)
|
||||
layer = Image.new("RGBA", (CW, CH), (0, 0, 0, 0))
|
||||
head(layer, "Автопродление", "Огоньки живут сами: раз в день, в нужное время")
|
||||
shot = P.load_shot("luna/keeper.png")
|
||||
shot = shot.crop((0, 0, shot.width, 1800)) # down to the row of the chats; a toast covers what is below
|
||||
P.place(layer, P.build_phone(shot), 700, 850, 0.72)
|
||||
P.chip(layer, 235, 560, "По умолчанию 12:00", 1.0, size=34)
|
||||
P.chip(layer, 235, 760, "Огонёк или свой текст", 1.0, size=32)
|
||||
P.chip(layer, 235, 960, "Свои чаты", 1.0, size=34)
|
||||
P.chip(layer, 235, 1160, "Свой набор у аккаунта", 1.0, size=30)
|
||||
footer(layer)
|
||||
img.alpha_composite(layer)
|
||||
return img
|
||||
|
||||
|
||||
def main() -> None:
|
||||
P.init_assets()
|
||||
OUT_DIR.mkdir(parents=True, exist_ok=True)
|
||||
cards = [("1_hero", card_hero), ("2_material3", card_system), ("3_comments", card_comments),
|
||||
("4_shapes", card_shapes), ("5_save", card_save), ("6_feed", card_feed),
|
||||
("7_badges", card_badges), ("8_icons", card_icons),
|
||||
("9_flame", card_flame), ("10_keeper", card_keeper)]
|
||||
for name, make in cards:
|
||||
path = OUT_DIR / ("card_%s.png" % name)
|
||||
make().convert("RGB").save(path)
|
||||
print(path)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
LihonT 2 «Luna pre-release» promo video: 1080x1920, 30 fps, about 37 seconds, with a synthesised soundtrack.
|
||||
LihonT 2 «Luna pre-release» promo video: 1080x1920, 30 fps, about 37 seconds, with a synthesised soundtrack (make_lihont_music.py).
|
||||
|
||||
The screens are real screenshots of the mod on a phone, taken to work/promo/shots/ (the status bar and the
|
||||
gesture strip are cut off). Frames are drawn with Pillow in worker processes and piped to ffmpeg.
|
||||
@@ -17,9 +17,8 @@ import argparse
|
||||
import math
|
||||
import random
|
||||
import shutil
|
||||
import struct
|
||||
import subprocess
|
||||
import wave
|
||||
import sys
|
||||
from multiprocessing import Pool
|
||||
from pathlib import Path
|
||||
|
||||
@@ -27,6 +26,7 @@ from PIL import Image, ImageDraw, ImageFilter, ImageFont
|
||||
|
||||
W, H, FPS = 1080, 1920, 30
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
SHOTS = ROOT / "work" / "promo" / "shots"
|
||||
OUT = ROOT / "work" / "promo" / "lihont_promo.mp4"
|
||||
AUDIO = ROOT / "work" / "promo" / "promo_audio.wav"
|
||||
@@ -111,51 +111,9 @@ def pop(lt: float, delay: float, duration: float = 0.55) -> float:
|
||||
# ---------------------------------------------------------------- audio
|
||||
|
||||
def generate_audio(path: Path, duration: float) -> None:
|
||||
rate = 44100
|
||||
n = int(rate * duration)
|
||||
bpm = 120
|
||||
beat = 60.0 / bpm
|
||||
random.seed(7)
|
||||
arp = [220.0, 261.63, 293.66, 329.63, 392.0, 440.0, 523.25, 587.33]
|
||||
risers = [s[1] - 0.8 for s in SCENES[1:]]
|
||||
out = []
|
||||
for i in range(n):
|
||||
t = i / rate
|
||||
idx = int(t / beat)
|
||||
pos = (t % beat) / beat
|
||||
kick = 0.0
|
||||
if pos < 0.3:
|
||||
freq = 160.0 * math.exp(-pos * 20) + 45.0
|
||||
kick = math.sin(2 * math.pi * freq * pos) * math.exp(-pos * 12) * 0.85
|
||||
clap = 0.0
|
||||
if idx % 2 == 1 and pos < 0.22:
|
||||
clap = ((random.random() * 2 - 1) * 0.7 + math.sin(2 * math.pi * 210 * pos) * 0.3) * math.exp(-pos * 16) * 0.55
|
||||
hat = 0.0
|
||||
sp = ((t * 4) % beat) / beat
|
||||
if sp < 0.06:
|
||||
hat = (random.random() * 2 - 1) * math.exp(-sp * 48) * (0.30 if int(t * 4 / beat) % 2 else 0.15)
|
||||
root = [55.0, 55.0, 65.4, 73.4][(idx // 4) % 4]
|
||||
side = min(1.0, pos * 3.5) if pos < 0.3 else 1.0
|
||||
bass = (math.sin(2 * math.pi * root * t) + 0.3 * math.sin(4 * math.pi * root * t)) * side * 0.38
|
||||
note = arp[int(t * 8) % len(arp)]
|
||||
pluck = math.sin(2 * math.pi * note * t) * math.exp(-(t % 0.125) * 22) * 0.2
|
||||
rise = 0.0
|
||||
for cut in risers:
|
||||
if 0 <= cut + 0.8 - t < 0.8 and t >= cut:
|
||||
p = (t - cut) / 0.8
|
||||
rise += (math.sin(2 * math.pi * (250 + p * p * 3000) * t) + random.random() * 0.3) * p * 0.28
|
||||
fade = 1.0
|
||||
if t < 0.4:
|
||||
fade = t / 0.4
|
||||
if t > duration - 1.4:
|
||||
fade = max(0.0, (duration - t) / 1.4)
|
||||
mix = max(-0.95, min(0.95, (kick + clap + hat + bass + pluck + rise) * fade))
|
||||
out.append(int(mix * 32767))
|
||||
with wave.open(str(path), "wb") as wf:
|
||||
wf.setnchannels(1)
|
||||
wf.setsampwidth(2)
|
||||
wf.setframerate(rate)
|
||||
wf.writeframes(struct.pack("<%dh" % len(out), *out))
|
||||
"""The soundtrack comes from make_lihont_music.py, with its transitions on the scene changes."""
|
||||
import make_lihont_music
|
||||
make_lihont_music.generate(path, duration, tuple(s[1] for s in SCENES[1:]))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- assets
|
||||
|
||||
174
scripts/make_widget_preview.py
Normal file
174
scripts/make_widget_preview.py
Normal file
@@ -0,0 +1,174 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Draws the picture the home-screen widget list shows for the LihonT streak widget.
|
||||
|
||||
The launcher shows a preview of every widget before it is added. The four streak widgets used to show TikTok's
|
||||
own previews (a camera, a search bar), because they ride in TikTok's widget slots. This draws a flower with the
|
||||
flame and a sample number in the colours of the LihonT logo, once, into src/brand/widget_preview.png; the build
|
||||
(lihont/widget_patch.py) puts that picture in the place of TikTok's previews.
|
||||
|
||||
It mirrors the drawing in src/lihont/two/widget/FlowerArt.java (eight petals, the flame, the number), at the
|
||||
size of the 360-unit grid that class draws on.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
OUT = ROOT / "src" / "brand" / "widget_preview.png"
|
||||
|
||||
SIDE = 360.0 # FlowerArt.SIDE
|
||||
PETALS = 8
|
||||
FLOWER = (0xE2, 0x6D, 0x6D, 255) # the coral of the logo
|
||||
INK = (0x4E, 0x13, 0x20, 255) # its dark maroon
|
||||
FLAME = (0xFF, 0x7A, 0x00, 255) # a lit flame, as FlowerArt.FLAME
|
||||
FLAME_HEART = (0xFF, 0xC5, 0x3D, 255)
|
||||
COLD = (0x8E, 0x93, 0x99, 255) # FlowerArt.COLD: the flame that is not lit
|
||||
COLD_HEART = (0xC7, 0xCB, 0xD0, 255)
|
||||
SAMPLE = "7"
|
||||
SCALE = 4 # supersampling
|
||||
PIXELS = 512
|
||||
|
||||
OUTER = [
|
||||
("M", (12, 1.5)),
|
||||
("C", (13.2, 6), (19.5, 9), (19.5, 15.2)),
|
||||
("C", (19.5, 19.6), (16.2, 22.5), (12, 22.5)),
|
||||
("C", (7.8, 22.5), (4.5, 19.6), (4.5, 15.4)),
|
||||
("C", (4.5, 12.6), (6, 10.6), (7.8, 8.8)),
|
||||
("C", (8, 11), (8.9, 12.2), (10.2, 12.8)),
|
||||
("C", (9.5, 8.6), (10.4, 4.8), (12, 1.5)),
|
||||
]
|
||||
INNER = [
|
||||
("M", (12, 20.3)),
|
||||
("C", (9.9, 20.3), (8.6, 18.9), (8.6, 17.2)),
|
||||
("C", (8.6, 15.5), (10.2, 14.2), (12, 12.2)),
|
||||
("C", (13.8, 14.2), (15.4, 15.5), (15.4, 17.2)),
|
||||
("C", (15.4, 18.9), (14.1, 20.3), (12, 20.3)),
|
||||
]
|
||||
|
||||
|
||||
def flatten(commands, place):
|
||||
"""The outline of a path of moves and cubic curves as a list of points, placed by `place`."""
|
||||
points = []
|
||||
current = None
|
||||
for command in commands:
|
||||
if command[0] == "M":
|
||||
current = command[1]
|
||||
points.append(place(current))
|
||||
else:
|
||||
_, c1, c2, end = command
|
||||
for step in range(1, 25):
|
||||
t = step / 24.0
|
||||
u = 1 - t
|
||||
x = u ** 3 * current[0] + 3 * u * u * t * c1[0] + 3 * u * t * t * c2[0] + t ** 3 * end[0]
|
||||
y = u ** 3 * current[1] + 3 * u * u * t * c1[1] + 3 * u * t * t * c2[1] + t ** 3 * end[1]
|
||||
points.append(place((x, y)))
|
||||
current = end
|
||||
return points
|
||||
|
||||
|
||||
def render(lit: bool = True) -> Image.Image:
|
||||
flame_color, heart_color = (FLAME, FLAME_HEART) if lit else (COLD, COLD_HEART)
|
||||
size = PIXELS * SCALE
|
||||
k = size / SIDE
|
||||
image = Image.new("RGBA", (size, size), (0, 0, 0, 0))
|
||||
draw = ImageDraw.Draw(image)
|
||||
|
||||
def circle(cx, cy, r):
|
||||
draw.ellipse([(cx - r) * k, (cy - r) * k, (cx + r) * k, (cy + r) * k], fill=FLOWER)
|
||||
|
||||
middle = SIDE / 2
|
||||
reach = SIDE * 0.30
|
||||
petal = SIDE * 0.20
|
||||
import math
|
||||
circle(middle, middle, reach)
|
||||
for i in range(PETALS):
|
||||
angle = i * 2 * math.pi / PETALS - math.pi / 2
|
||||
circle(middle + math.cos(angle) * reach, middle + math.sin(angle) * reach, petal)
|
||||
|
||||
flame = SIDE * 0.30
|
||||
left = middle - flame / 2
|
||||
top = SIDE * 0.10
|
||||
scale = flame / 24.0
|
||||
|
||||
def place(point):
|
||||
return ((left + point[0] * scale) * k, (top + point[1] * scale) * k)
|
||||
|
||||
outline = flatten(OUTER, place)
|
||||
if max(abs(a - b) for a, b in zip(FLOWER[:3], flame_color[:3])) < 110: # FlowerArt.MIN_CONTRAST
|
||||
draw.line(outline + [outline[0]], fill=INK, width=int(1.5 * scale * k * 2), joint="curve")
|
||||
draw.polygon(outline, fill=flame_color)
|
||||
draw.polygon(flatten(INNER, place), fill=heart_color)
|
||||
|
||||
font = ImageFont.truetype(r"C:\Windows\Fonts\arialbd.ttf", int(SIDE * 0.32 * k))
|
||||
draw.text((middle * k, SIDE * 0.735 * k), SAMPLE, font=font, fill=INK, anchor="ms")
|
||||
return image.resize((PIXELS, PIXELS), Image.LANCZOS)
|
||||
|
||||
|
||||
def _hex(color) -> str:
|
||||
return "#%02X%02X%02X" % color[:3]
|
||||
|
||||
|
||||
def _path_data(commands) -> str:
|
||||
"""An SVG path (absolute move and curve commands) of one of the flame outlines."""
|
||||
parts = []
|
||||
for command in commands:
|
||||
if command[0] == "M":
|
||||
parts.append("M%g %g" % command[1])
|
||||
else:
|
||||
parts.append("C%g %g %g %g %g %g" % (command[1] + command[2] + command[3]))
|
||||
return " ".join(parts) + "Z"
|
||||
|
||||
|
||||
def svg(lit: bool = True, sample: str = SAMPLE) -> str:
|
||||
"""The widget as a vector picture on the 360-unit grid of FlowerArt: crisp at any size, one file to edit.
|
||||
|
||||
The number is text in a bold sans font; a viewer without Arial or Roboto draws its own bold sans.
|
||||
"""
|
||||
import math
|
||||
flame_color, heart_color = (FLAME, FLAME_HEART) if lit else (COLD, COLD_HEART)
|
||||
middle = SIDE / 2
|
||||
reach = SIDE * 0.30
|
||||
petal = SIDE * 0.20
|
||||
flame = SIDE * 0.30
|
||||
scale = flame / 24.0
|
||||
close_colors = max(abs(a - b) for a, b in zip(FLOWER[:3], flame_color[:3])) < 110 # FlowerArt.MIN_CONTRAST
|
||||
lines = ['<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 360 360" width="360" height="360">',
|
||||
' <title>LihonT streak widget</title>',
|
||||
' <g fill="%s">' % _hex(FLOWER),
|
||||
' <circle cx="%g" cy="%g" r="%g"/>' % (middle, middle, reach)]
|
||||
for i in range(PETALS):
|
||||
angle = i * 2 * math.pi / PETALS - math.pi / 2
|
||||
lines.append(' <circle cx="%.3f" cy="%.3f" r="%g"/>' % (
|
||||
middle + math.cos(angle) * reach, middle + math.sin(angle) * reach, petal))
|
||||
lines.append(' </g>')
|
||||
lines.append(' <g transform="translate(%g %g) scale(%g)">' % (middle - flame / 2, SIDE * 0.10, scale))
|
||||
if close_colors:
|
||||
lines.append(' <path d="%s" fill="none" stroke="%s" stroke-width="1.5" stroke-linejoin="round"/>' % (
|
||||
_path_data(OUTER), _hex(INK)))
|
||||
lines.append(' <path d="%s" fill="%s"/>' % (_path_data(OUTER), _hex(flame_color)))
|
||||
lines.append(' <path d="%s" fill="%s"/>' % (_path_data(INNER), _hex(heart_color)))
|
||||
lines.append(' </g>')
|
||||
lines.append(' <text x="%g" y="%g" font-family="Roboto, Arial, Helvetica, sans-serif" font-weight="700" '
|
||||
'font-size="%g" text-anchor="middle" fill="%s">%s</text>' % (
|
||||
middle, SIDE * 0.735, SIDE * 0.32, _hex(INK), sample))
|
||||
lines.append('</svg>')
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
def main() -> int:
|
||||
OUT.parent.mkdir(parents=True, exist_ok=True)
|
||||
render().save(OUT, optimize=True)
|
||||
(OUT.parent / "widget_flame.svg").write_text(svg(True), encoding="utf-8")
|
||||
(OUT.parent / "widget_flame_grey.svg").write_text(svg(False), encoding="utf-8")
|
||||
if len(sys.argv) > 1: # a picture of the grey flame too, for the release cards
|
||||
render(lit=False).save(sys.argv[1], optimize=True)
|
||||
print("wrote", OUT, OUT.stat().st_size, "bytes, and widget_flame.svg, widget_flame_grey.svg")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -1,80 +1,102 @@
|
||||
"""Quick rebuild after a change in the runtime Java only (src/lihont/two).
|
||||
|
||||
Takes an APK that py -m lihont.upgrade built earlier, swaps the mod's runtime classes inside its
|
||||
classes35.dex for a fresh compile of src/lihont/two, and signs the result. The smali patches of TikTok's
|
||||
own classes are not touched, so this is only right while lihont/*_patch.py and lihont/upgrade.py are
|
||||
unchanged since that APK was built; after any such change run the full build.
|
||||
|
||||
usage (from the repository root):
|
||||
py -B scripts/quick_runtime.py ComplectAPK/lihont-2.0-luna-beta5.apk -o ComplectAPK/lihont-2.0-luna-beta6.apk
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
os.chdir(ROOT)
|
||||
|
||||
from lihont import dexpatch, manifest as manifest_module # noqa: E402
|
||||
from lihont.apkzip import Apk # noqa: E402
|
||||
from lihont.axml import Axml # noqa: E402
|
||||
from lihont.toolchain import Toolchain # noqa: E402
|
||||
|
||||
RUNTIME = "Llihont/two/"
|
||||
DEX = "classes35.dex"
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("built", help="an APK built by lihont.upgrade")
|
||||
parser.add_argument("-o", "--out", required=True)
|
||||
parser.add_argument("--work", default="work/quick")
|
||||
args = parser.parse_args()
|
||||
|
||||
source, output, room = Path(args.built).resolve(), Path(args.out).resolve(), Path(args.work).resolve()
|
||||
if source == output:
|
||||
raise SystemExit("Write to a new file: the built APK stays as it is")
|
||||
room.mkdir(parents=True, exist_ok=True)
|
||||
tools = Toolchain("tools")
|
||||
apk = Apk(str(source))
|
||||
try:
|
||||
api = manifest_module.min_sdk(Axml.parse(apk.read("AndroidManifest.xml")))
|
||||
runtime = Path(tools.compile_dex("src/lihont/two", str(room / "runtime"), api)).read_bytes()
|
||||
|
||||
compiler = room / "compiler"
|
||||
compiler.mkdir(parents=True, exist_ok=True)
|
||||
subprocess.run(["javac", "--release", "17", "-cp", tools.smali, "-d", str(compiler),
|
||||
"src/RefreshClasses.java"], check=True)
|
||||
host_dex = apk.read(DEX)
|
||||
host, fresh, merged = room / "host.dex", room / "fresh.dex", room / "merged.dex"
|
||||
host.write_bytes(host_dex)
|
||||
fresh.write_bytes(runtime)
|
||||
subprocess.run(["java", "-Xmx1g", "-cp", os.pathsep.join([str(compiler), tools.smali]),
|
||||
"RefreshClasses", str(host), str(fresh), str(merged), str(api)], check=True)
|
||||
result = merged.read_bytes()
|
||||
|
||||
if dexpatch.dex_format(host_dex) != dexpatch.dex_format(result):
|
||||
raise SystemExit("The refresh changed the DEX format")
|
||||
before = {m for m in dexpatch.defined_methods(host_dex) if not m.startswith(RUNTIME)}
|
||||
after = dexpatch.defined_methods(result)
|
||||
if not before.issubset(after):
|
||||
raise SystemExit("The refresh lost classes that are not part of the runtime")
|
||||
if not any(m.startswith("Llihont/two/LihonTRegion;->") for m in after):
|
||||
raise SystemExit("LihonTRegion is missing after the refresh")
|
||||
|
||||
apk.replace(DEX, result)
|
||||
apk.drop_signature()
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
apk.write(str(output))
|
||||
finally:
|
||||
apk.close()
|
||||
tools.sign(str(output))
|
||||
print("%s %d bytes" % (output.name, output.stat().st_size))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
"""Quick rebuild after a change in the runtime Java only (src/lihont/two).
|
||||
|
||||
Takes an APK that py -m lihont.upgrade built earlier, swaps the mod's runtime for a fresh compile of
|
||||
src/lihont/two (the dex of its own that holds only the runtime, or, in an APK built before that dex existed, the
|
||||
runtime classes inside classes35.dex), and signs the result. The smali patches of TikTok's
|
||||
own classes are not touched, so this is only right while lihont/*_patch.py and lihont/upgrade.py are
|
||||
unchanged since that APK was built; after any such change run the full build.
|
||||
|
||||
usage (from the repository root):
|
||||
py -B scripts/quick_runtime.py ComplectAPK/lihont-2.0-luna-beta5.apk -o ComplectAPK/lihont-2.0-luna-beta6.apk
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
os.chdir(ROOT)
|
||||
|
||||
from lihont import dexpatch, manifest as manifest_module # noqa: E402
|
||||
from lihont.apkzip import Apk # noqa: E402
|
||||
from lihont.axml import Axml # noqa: E402
|
||||
from lihont.toolchain import Toolchain # noqa: E402
|
||||
|
||||
RUNTIME = "Llihont/two/"
|
||||
DEX = "classes35.dex"
|
||||
|
||||
|
||||
def runtime_dex_of(apk: Apk):
|
||||
"""The dex that defines the mod's runtime and nothing else, or None when it rides inside a TikTok dex."""
|
||||
for name in sorted(apk.names()):
|
||||
if not name.endswith(".dex"):
|
||||
continue
|
||||
data = apk.read(name)
|
||||
if b"Llihont/two/LihonTRegion;" not in data:
|
||||
continue
|
||||
defined = dexpatch.defined_methods(data)
|
||||
if defined and all(m.startswith(RUNTIME) for m in defined):
|
||||
return name
|
||||
return None
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("built", help="an APK built by lihont.upgrade")
|
||||
parser.add_argument("-o", "--out", required=True)
|
||||
parser.add_argument("--work", default="work/quick")
|
||||
args = parser.parse_args()
|
||||
|
||||
source, output, room = Path(args.built).resolve(), Path(args.out).resolve(), Path(args.work).resolve()
|
||||
if source == output:
|
||||
raise SystemExit("Write to a new file: the built APK stays as it is")
|
||||
room.mkdir(parents=True, exist_ok=True)
|
||||
tools = Toolchain("tools")
|
||||
apk = Apk(str(source))
|
||||
try:
|
||||
api = manifest_module.min_sdk(Axml.parse(apk.read("AndroidManifest.xml")))
|
||||
runtime = Path(tools.compile_dex("src/lihont/two", str(room / "runtime"), api)).read_bytes()
|
||||
|
||||
target = runtime_dex_of(apk)
|
||||
if target is not None:
|
||||
# a dex that holds nothing but the runtime is simply replaced
|
||||
replacement = runtime
|
||||
else:
|
||||
# an APK built before the runtime had a dex of its own: its classes ride inside classes35.dex
|
||||
target = DEX
|
||||
compiler = room / "compiler"
|
||||
compiler.mkdir(parents=True, exist_ok=True)
|
||||
subprocess.run(["javac", "--release", "17", "-cp", tools.smali, "-d", str(compiler),
|
||||
"src/RefreshClasses.java"], check=True)
|
||||
host_dex = apk.read(DEX)
|
||||
host, fresh, merged = room / "host.dex", room / "fresh.dex", room / "merged.dex"
|
||||
host.write_bytes(host_dex)
|
||||
fresh.write_bytes(runtime)
|
||||
subprocess.run(["java", "-Xmx1g", "-cp", os.pathsep.join([str(compiler), tools.smali]),
|
||||
"RefreshClasses", str(host), str(fresh), str(merged), str(api)], check=True)
|
||||
replacement = merged.read_bytes()
|
||||
|
||||
if dexpatch.dex_format(host_dex) != dexpatch.dex_format(replacement):
|
||||
raise SystemExit("The refresh changed the DEX format")
|
||||
before = {m for m in dexpatch.defined_methods(host_dex) if not m.startswith(RUNTIME)}
|
||||
after = dexpatch.defined_methods(replacement)
|
||||
if not before.issubset(after):
|
||||
raise SystemExit("The refresh lost classes that are not part of the runtime")
|
||||
if not any(m.startswith("Llihont/two/LihonTRegion;->") for m in after):
|
||||
raise SystemExit("LihonTRegion is missing after the refresh")
|
||||
|
||||
apk.replace(target, replacement)
|
||||
apk.drop_signature()
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
apk.write(str(output))
|
||||
finally:
|
||||
apk.close()
|
||||
tools.sign(str(output))
|
||||
print("%s %d bytes (runtime in %s)" % (output.name, output.stat().st_size, target))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
20
src/brand/widget_flame.svg
Normal file
20
src/brand/widget_flame.svg
Normal file
@@ -0,0 +1,20 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 360 360" width="360" height="360">
|
||||
<title>LihonT streak widget</title>
|
||||
<g fill="#E26D6D">
|
||||
<circle cx="180" cy="180" r="108"/>
|
||||
<circle cx="180.000" cy="72.000" r="72"/>
|
||||
<circle cx="256.368" cy="103.632" r="72"/>
|
||||
<circle cx="288.000" cy="180.000" r="72"/>
|
||||
<circle cx="256.368" cy="256.368" r="72"/>
|
||||
<circle cx="180.000" cy="288.000" r="72"/>
|
||||
<circle cx="103.632" cy="256.368" r="72"/>
|
||||
<circle cx="72.000" cy="180.000" r="72"/>
|
||||
<circle cx="103.632" cy="103.632" r="72"/>
|
||||
</g>
|
||||
<g transform="translate(126 36) scale(4.5)">
|
||||
<path d="M12 1.5 C13.2 6 19.5 9 19.5 15.2 C19.5 19.6 16.2 22.5 12 22.5 C7.8 22.5 4.5 19.6 4.5 15.4 C4.5 12.6 6 10.6 7.8 8.8 C8 11 8.9 12.2 10.2 12.8 C9.5 8.6 10.4 4.8 12 1.5Z" fill="none" stroke="#4E1320" stroke-width="1.5" stroke-linejoin="round"/>
|
||||
<path d="M12 1.5 C13.2 6 19.5 9 19.5 15.2 C19.5 19.6 16.2 22.5 12 22.5 C7.8 22.5 4.5 19.6 4.5 15.4 C4.5 12.6 6 10.6 7.8 8.8 C8 11 8.9 12.2 10.2 12.8 C9.5 8.6 10.4 4.8 12 1.5Z" fill="#FF7A00"/>
|
||||
<path d="M12 20.3 C9.9 20.3 8.6 18.9 8.6 17.2 C8.6 15.5 10.2 14.2 12 12.2 C13.8 14.2 15.4 15.5 15.4 17.2 C15.4 18.9 14.1 20.3 12 20.3Z" fill="#FFC53D"/>
|
||||
</g>
|
||||
<text x="180" y="264.6" font-family="Roboto, Arial, Helvetica, sans-serif" font-weight="700" font-size="115.2" text-anchor="middle" fill="#4E1320">7</text>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.4 KiB |
20
src/brand/widget_flame_grey.svg
Normal file
20
src/brand/widget_flame_grey.svg
Normal file
@@ -0,0 +1,20 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 360 360" width="360" height="360">
|
||||
<title>LihonT streak widget</title>
|
||||
<g fill="#E26D6D">
|
||||
<circle cx="180" cy="180" r="108"/>
|
||||
<circle cx="180.000" cy="72.000" r="72"/>
|
||||
<circle cx="256.368" cy="103.632" r="72"/>
|
||||
<circle cx="288.000" cy="180.000" r="72"/>
|
||||
<circle cx="256.368" cy="256.368" r="72"/>
|
||||
<circle cx="180.000" cy="288.000" r="72"/>
|
||||
<circle cx="103.632" cy="256.368" r="72"/>
|
||||
<circle cx="72.000" cy="180.000" r="72"/>
|
||||
<circle cx="103.632" cy="103.632" r="72"/>
|
||||
</g>
|
||||
<g transform="translate(126 36) scale(4.5)">
|
||||
<path d="M12 1.5 C13.2 6 19.5 9 19.5 15.2 C19.5 19.6 16.2 22.5 12 22.5 C7.8 22.5 4.5 19.6 4.5 15.4 C4.5 12.6 6 10.6 7.8 8.8 C8 11 8.9 12.2 10.2 12.8 C9.5 8.6 10.4 4.8 12 1.5Z" fill="none" stroke="#4E1320" stroke-width="1.5" stroke-linejoin="round"/>
|
||||
<path d="M12 1.5 C13.2 6 19.5 9 19.5 15.2 C19.5 19.6 16.2 22.5 12 22.5 C7.8 22.5 4.5 19.6 4.5 15.4 C4.5 12.6 6 10.6 7.8 8.8 C8 11 8.9 12.2 10.2 12.8 C9.5 8.6 10.4 4.8 12 1.5Z" fill="#8E9399"/>
|
||||
<path d="M12 20.3 C9.9 20.3 8.6 18.9 8.6 17.2 C8.6 15.5 10.2 14.2 12 12.2 C13.8 14.2 15.4 15.5 15.4 17.2 C15.4 18.9 14.1 20.3 12 20.3Z" fill="#C7CBD0"/>
|
||||
</g>
|
||||
<text x="180" y="264.6" font-family="Roboto, Arial, Helvetica, sans-serif" font-weight="700" font-size="115.2" text-anchor="middle" fill="#4E1320">7</text>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.4 KiB |
BIN
src/brand/widget_preview.png
Normal file
BIN
src/brand/widget_preview.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 38 KiB |
85
src/lihont/two/account/AccountShapeBook.java
Normal file
85
src/lihont/two/account/AccountShapeBook.java
Normal file
@@ -0,0 +1,85 @@
|
||||
package lihont.two.account;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* The avatar shape each TikTok account on this phone has chosen for itself.
|
||||
*
|
||||
* Plain Java on purpose (the shape is kept by its name, the way the settings file keeps it), so that it can be
|
||||
* tested on a desktop JVM; AccountShapes puts it into a private file and turns the names into shapes.
|
||||
*
|
||||
* The text form is one line "uid=shape" per account and a line "migrated=1" once the shape that used to be
|
||||
* one setting for everybody has been handed to the account that was active at the time.
|
||||
*/
|
||||
public final class AccountShapeBook {
|
||||
private static final Pattern UID = Pattern.compile("[0-9]{1,20}");
|
||||
private static final Pattern SHAPE = Pattern.compile("[a-z]{1,16}");
|
||||
private static final String CIRCLE = "circle";
|
||||
private static final String MIGRATED = "migrated";
|
||||
|
||||
private final Map<String, String> shapes = new LinkedHashMap<String, String>();
|
||||
private boolean migrated;
|
||||
|
||||
public static boolean validUid(String uid) {
|
||||
return uid != null && UID.matcher(uid).matches();
|
||||
}
|
||||
|
||||
/** Reads the text form; a line that does not make sense is skipped, so a damaged file loses only that line. */
|
||||
public static AccountShapeBook decode(String text) {
|
||||
AccountShapeBook book = new AccountShapeBook();
|
||||
if (text == null) return book;
|
||||
for (String line : text.split("\n")) {
|
||||
int equals = line.indexOf('=');
|
||||
if (equals <= 0) continue;
|
||||
String key = line.substring(0, equals).trim();
|
||||
String value = line.substring(equals + 1).trim();
|
||||
if (key.equals(MIGRATED)) {
|
||||
book.migrated = value.equals("1");
|
||||
} else if (validUid(key) && SHAPE.matcher(value).matches()) {
|
||||
book.shapes.put(key, value);
|
||||
}
|
||||
}
|
||||
return book;
|
||||
}
|
||||
|
||||
public String encode() {
|
||||
StringBuilder out = new StringBuilder();
|
||||
if (migrated) out.append(MIGRATED).append("=1\n");
|
||||
for (Map.Entry<String, String> entry : shapes.entrySet()) {
|
||||
out.append(entry.getKey()).append('=').append(entry.getValue()).append('\n');
|
||||
}
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
/** The shape this account chose, or null when it has not chosen one on this phone. */
|
||||
public String shapeOf(String uid) {
|
||||
return validUid(uid) ? shapes.get(uid) : null;
|
||||
}
|
||||
|
||||
/** Remembers the choice of one account; a choice of the round shape is a choice too. */
|
||||
public void put(String uid, String shape) {
|
||||
if (!validUid(uid)) throw new IllegalArgumentException("Not an account id");
|
||||
if (shape == null || !SHAPE.matcher(shape).matches()) throw new IllegalArgumentException("Not a shape name");
|
||||
shapes.put(uid, shape);
|
||||
}
|
||||
|
||||
public boolean migrated() {
|
||||
return migrated;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hands the shape that used to be one setting for the whole app to the account that is active now, once.
|
||||
* Does nothing (and may be asked again) while no account is known. Returns whether the book changed.
|
||||
*/
|
||||
public boolean migrate(String legacyShape, String activeUid) {
|
||||
if (migrated || !validUid(activeUid)) return false;
|
||||
migrated = true;
|
||||
if (legacyShape != null && !legacyShape.equals(CIRCLE) && SHAPE.matcher(legacyShape).matches()
|
||||
&& !shapes.containsKey(activeUid)) {
|
||||
shapes.put(activeUid, legacyShape);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
110
src/lihont/two/account/AccountShapes.java
Normal file
110
src/lihont/two/account/AccountShapes.java
Normal file
@@ -0,0 +1,110 @@
|
||||
package lihont.two.account;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
|
||||
import lihont.two.settings.ModSettings;
|
||||
import lihont.two.settings.SettingsHost;
|
||||
import lihont.two.widget.AppContext;
|
||||
|
||||
/**
|
||||
* The avatar shape of every account on this phone: each account has its own, and the one that is signed in
|
||||
* decides how its own pictures look. Kept in a small private file (see AccountShapeBook).
|
||||
*
|
||||
* The shape used to be a single setting for the whole app. The first time an account is known, that old value
|
||||
* goes to it, so nobody loses the shape they had chosen.
|
||||
*/
|
||||
public final class AccountShapes {
|
||||
private static final String FILE = "lihont_account_shapes";
|
||||
private static final String KEY = "book";
|
||||
|
||||
private static AccountShapeBook book;
|
||||
private static Context application;
|
||||
private static ModSettings.AvatarShape current = ModSettings.AvatarShape.CIRCLE;
|
||||
private static String currentFor;
|
||||
private static long checkedAt;
|
||||
|
||||
private AccountShapes() {}
|
||||
|
||||
/**
|
||||
* The shape of the signed-in account's pictures (round when nobody is signed in or the account has not
|
||||
* chosen one). Asked on every avatar draw, so the work is cached for a moment. Never throws.
|
||||
*/
|
||||
public static synchronized ModSettings.AvatarShape current() {
|
||||
try {
|
||||
long now = android.os.SystemClock.uptimeMillis();
|
||||
if (checkedAt != 0L && now - checkedAt < 1500L) return current;
|
||||
checkedAt = now;
|
||||
String uid = CurrentAccount.uid();
|
||||
Context context = context();
|
||||
if (uid == null || context == null || !load(context)) {
|
||||
current = ModSettings.AvatarShape.CIRCLE;
|
||||
currentFor = null;
|
||||
return current;
|
||||
}
|
||||
// Only once the settings can be read: the answer before that is the default, not the old choice.
|
||||
ModSettings settings = SettingsHost.active();
|
||||
if (settings != null && book.migrate(settings.avatarShape().value(), uid)) save(context);
|
||||
current = shape(book.shapeOf(uid));
|
||||
currentFor = uid;
|
||||
return current;
|
||||
} catch (Throwable unavailable) {
|
||||
return ModSettings.AvatarShape.CIRCLE;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The shape one of the accounts of this phone chose, or null for an account that has not chosen one here
|
||||
* (the picture of a stranger; the members service is asked about those). Never throws.
|
||||
*/
|
||||
public static synchronized ModSettings.AvatarShape localFor(String uid) {
|
||||
try {
|
||||
Context context = context();
|
||||
if (context == null || !load(context)) return null;
|
||||
String name = book.shapeOf(uid);
|
||||
return name == null ? null : shape(name);
|
||||
} catch (Throwable unavailable) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Remembers the shape of one account, and shows it at once if that account is the signed-in one. */
|
||||
public static synchronized void set(Context context, String uid, ModSettings.AvatarShape shape) {
|
||||
if (!load(context)) return;
|
||||
book.put(uid, shape.value());
|
||||
save(context);
|
||||
if (uid.equals(currentFor)) current = shape;
|
||||
checkedAt = 0L;
|
||||
}
|
||||
|
||||
/** The application, asked for once: this is called for every avatar that is drawn. */
|
||||
private static Context context() {
|
||||
if (application == null) application = AppContext.get();
|
||||
return application;
|
||||
}
|
||||
|
||||
/** A name this version does not know (written by a newer one) is shown round. */
|
||||
private static ModSettings.AvatarShape shape(String name) {
|
||||
if (name == null) return ModSettings.AvatarShape.CIRCLE;
|
||||
try {
|
||||
return ModSettings.AvatarShape.fromValue(name);
|
||||
} catch (IllegalArgumentException unknown) {
|
||||
return ModSettings.AvatarShape.CIRCLE;
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean load(Context context) {
|
||||
if (book != null) return true;
|
||||
if (context == null) return false;
|
||||
book = AccountShapeBook.decode(prefs(context).getString(KEY, null));
|
||||
return true;
|
||||
}
|
||||
|
||||
private static void save(Context context) {
|
||||
prefs(context).edit().putString(KEY, book.encode()).apply();
|
||||
}
|
||||
|
||||
private static SharedPreferences prefs(Context context) {
|
||||
return context.getSharedPreferences(FILE, Context.MODE_PRIVATE);
|
||||
}
|
||||
}
|
||||
46
src/lihont/two/account/CurrentAccount.java
Normal file
46
src/lihont/two/account/CurrentAccount.java
Normal file
@@ -0,0 +1,46 @@
|
||||
package lihont.two.account;
|
||||
|
||||
import android.os.SystemClock;
|
||||
|
||||
import lihont.two.badge.NicheClaim;
|
||||
|
||||
/**
|
||||
* Which TikTok account is signed in right now, for code that asks on every frame or every redraw (avatar
|
||||
* shapes, widgets). TikTok's own service is asked at most every few seconds; the answer in between is the
|
||||
* last one. Switching to another account shows up within that time.
|
||||
*/
|
||||
public final class CurrentAccount {
|
||||
private static final long REFRESH_MS = 3000L;
|
||||
|
||||
private static String uid;
|
||||
private static String uniqueId;
|
||||
private static long refreshAt;
|
||||
|
||||
private CurrentAccount() {}
|
||||
|
||||
/** The id of the signed-in account, or null when nobody is signed in (or TikTok cannot say yet). */
|
||||
public static synchronized String uid() {
|
||||
refresh();
|
||||
return uid;
|
||||
}
|
||||
|
||||
/** The public username (without the @) of the signed-in account, or null. */
|
||||
public static synchronized String uniqueId() {
|
||||
refresh();
|
||||
return uniqueId;
|
||||
}
|
||||
|
||||
/** Forgets the cached answer, so the next question goes to TikTok (after a sign-in, say). */
|
||||
public static synchronized void forget() {
|
||||
refreshAt = 0L;
|
||||
}
|
||||
|
||||
private static void refresh() {
|
||||
long now = SystemClock.uptimeMillis();
|
||||
if (refreshAt != 0L && now < refreshAt) return;
|
||||
NicheClaim.Account account = NicheClaim.account();
|
||||
uid = account == null ? null : account.uid;
|
||||
uniqueId = account == null ? null : account.uniqueId;
|
||||
refreshAt = now + REFRESH_MS;
|
||||
}
|
||||
}
|
||||
@@ -9,9 +9,9 @@ import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import lihont.two.account.AccountShapes;
|
||||
import lihont.two.bar.UserAvatar;
|
||||
import lihont.two.settings.ModSettings;
|
||||
import lihont.two.settings.SettingsHost;
|
||||
|
||||
/**
|
||||
* Whose picture an avatar view shows, and so which shape it is drawn in.
|
||||
@@ -42,9 +42,12 @@ final class Owner {
|
||||
try {
|
||||
String id = Pictures.id(addressOf(view));
|
||||
if (id == null) return null;
|
||||
if (isMine(id)) return SettingsHost.avatarShape();
|
||||
if (isMine(id)) return AccountShapes.current();
|
||||
String uid = PictureOwners.uidOf(id);
|
||||
return uid == null ? null : ShapeCatalog.shapeOf(uid, view);
|
||||
if (uid == null) return null;
|
||||
// another account of this phone (the account switcher shows them all) wears its own choice
|
||||
ModSettings.AvatarShape own = AccountShapes.localFor(uid);
|
||||
return own != null ? own : ShapeCatalog.shapeOf(uid, view);
|
||||
} catch (Throwable unreadable) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -61,6 +61,13 @@ public final class PictureOwners {
|
||||
}
|
||||
}
|
||||
|
||||
/** The accounts whose pictures have been seen so far. */
|
||||
public static java.util.Set<String> uids() {
|
||||
synchronized (OWNERS) {
|
||||
return new java.util.HashSet<String>(OWNERS.values());
|
||||
}
|
||||
}
|
||||
|
||||
private static void remember(String id, String uid) {
|
||||
synchronized (OWNERS) {
|
||||
OWNERS.put(id, uid);
|
||||
|
||||
@@ -40,6 +40,7 @@ final class AccountNames {
|
||||
String uid = (String) user.getClass().getMethod("getUid").invoke(user);
|
||||
if (!validUid(uid)) return name;
|
||||
lihont.two.avatar.PictureOwners.learn(user, uid);
|
||||
lihont.two.widget.Contacts.learn(user, uid, name);
|
||||
String copy = new String(name);
|
||||
synchronized (NAMES) {
|
||||
NAMES.put(copy, uid);
|
||||
|
||||
@@ -74,7 +74,7 @@ final class AvatarBadge extends Drawable {
|
||||
matrix.setScale(2f * radius / bitmap.getWidth(), 2f * radius / bitmap.getHeight());
|
||||
matrix.postTranslate(cx - radius, cy - radius);
|
||||
shader.setLocalMatrix(matrix);
|
||||
ModSettings.AvatarShape shape = SettingsHost.avatarShape();
|
||||
ModSettings.AvatarShape shape = lihont.two.account.AccountShapes.current();
|
||||
if (shape == ModSettings.AvatarShape.CIRCLE) {
|
||||
canvas.drawCircle(cx, cy, radius, fill);
|
||||
if (item.isSelected()) {
|
||||
|
||||
19
src/lihont/two/look/BlackRule.java
Normal file
19
src/lihont/two/look/BlackRule.java
Normal file
@@ -0,0 +1,19 @@
|
||||
package lihont.two.look;
|
||||
|
||||
/**
|
||||
* Which colours the tonal-surface skin takes for "black". Only a colour that is fully opaque and as good as
|
||||
* black: a scrim (half transparent black) must stay a scrim, and dark greys, which TikTok uses for cards, stay
|
||||
* what they are, so a card keeps its lift over the background.
|
||||
*/
|
||||
public final class BlackRule {
|
||||
/** The largest value of a colour channel that still counts as black (0x0C is 12 of 255). */
|
||||
public static final int CHANNEL_MAX = 0x0C;
|
||||
|
||||
private BlackRule() {}
|
||||
|
||||
public static boolean isBlack(int argb) {
|
||||
if ((argb >>> 24) != 0xFF) return false;
|
||||
return ((argb >> 16) & 0xFF) <= CHANNEL_MAX && ((argb >> 8) & 0xFF) <= CHANNEL_MAX
|
||||
&& (argb & 0xFF) <= CHANNEL_MAX;
|
||||
}
|
||||
}
|
||||
225
src/lihont/two/look/TonalSurfaces.java
Normal file
225
src/lihont/two/look/TonalSurfaces.java
Normal file
@@ -0,0 +1,225 @@
|
||||
package lihont.two.look;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.content.res.ColorStateList;
|
||||
import android.graphics.Bitmap;
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.PorterDuff;
|
||||
import android.graphics.PorterDuffColorFilter;
|
||||
import android.graphics.Rect;
|
||||
import android.graphics.drawable.ColorDrawable;
|
||||
import android.graphics.drawable.Drawable;
|
||||
import android.graphics.drawable.GradientDrawable;
|
||||
import android.graphics.drawable.LayerDrawable;
|
||||
import android.graphics.drawable.ShapeDrawable;
|
||||
import android.os.Build;
|
||||
import android.util.Log;
|
||||
import android.view.SurfaceView;
|
||||
import android.view.TextureView;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.view.ViewTreeObserver;
|
||||
import android.webkit.WebView;
|
||||
import android.widget.ImageView;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Set;
|
||||
import java.util.WeakHashMap;
|
||||
|
||||
/**
|
||||
* Replaces the black backgrounds of the screen that is on top with the tonal surface colour of the Material 3
|
||||
* palette, so that a dark TikTok is dark blue-green (or whatever the accent gives) and not black.
|
||||
*
|
||||
* TikTok paints most of its screens with plain black and recycles its views all the time, so, as for the comment
|
||||
* sheet and the profile, a light check runs before every frame: it looks at the background of each visible view and
|
||||
* swaps the black ones (see BlackRule). Three kinds of black are met:
|
||||
*
|
||||
* - a flat colour (a view's background colour): replaced by the surface colour;
|
||||
* - a flat shape, or a fade of two colours that ends in solid black: its black becomes the surface colour;
|
||||
* - a shape painted by a shader that is black with a changing see-through (TikTok darkens the banner of a profile
|
||||
* into the page this way, and the shader cannot be read): a filter keeps its see-through and paints the surface
|
||||
* colour, so the banner melts into the page and not into a black block.
|
||||
*
|
||||
* A picture, a video surface or a web page is never touched, and neither is anything that is not black: scrims over
|
||||
* a video, shadows and the grey cards stay as they are. When the pure black of AMOLED is wanted the skin is not
|
||||
* started at all.
|
||||
*/
|
||||
public final class TonalSurfaces {
|
||||
private static final String TAG = "LIHONT";
|
||||
private static final int MAX_DEPTH = 60;
|
||||
/** A screen with more views than this is checked only every few frames. */
|
||||
private static final int BIG_TREE = 1800;
|
||||
|
||||
private static Watcher current;
|
||||
|
||||
private TonalSurfaces() {}
|
||||
|
||||
/** Starts watching this screen; the colour is the surface of the palette in use. Never throws. */
|
||||
public static void watch(Activity activity, int surface) {
|
||||
try {
|
||||
if (BlackRule.isBlack(surface)) return; // it would repaint its own colour for ever
|
||||
View decor = activity.getWindow().getDecorView();
|
||||
if (current != null && current.decor == decor && current.surface == surface) return;
|
||||
if (current != null) current.stop();
|
||||
current = new Watcher(decor, surface);
|
||||
current.start();
|
||||
Log.i(TAG, "tonal: surfaces on " + activity.getClass().getName());
|
||||
} catch (Throwable ignored) {
|
||||
// Decoration: never let it take a screen down.
|
||||
}
|
||||
}
|
||||
|
||||
private static final class Watcher implements ViewTreeObserver.OnPreDrawListener, View.OnAttachStateChangeListener {
|
||||
final View decor;
|
||||
final int surface;
|
||||
private int visited;
|
||||
private int frames;
|
||||
private int failures;
|
||||
/** Shader shapes already judged (once is enough), without keeping them alive. */
|
||||
private final Set<Drawable> judged = Collections.newSetFromMap(new WeakHashMap<Drawable, Boolean>());
|
||||
|
||||
Watcher(View decor, int surface) {
|
||||
this.decor = decor;
|
||||
this.surface = surface;
|
||||
}
|
||||
|
||||
void start() {
|
||||
decor.getViewTreeObserver().addOnPreDrawListener(this);
|
||||
decor.addOnAttachStateChangeListener(this);
|
||||
}
|
||||
|
||||
void stop() {
|
||||
decor.getViewTreeObserver().removeOnPreDrawListener(this);
|
||||
decor.removeOnAttachStateChangeListener(this);
|
||||
if (current == this) current = null;
|
||||
}
|
||||
|
||||
@Override public boolean onPreDraw() {
|
||||
try {
|
||||
// a big screen is looked at every third frame, a small one on every frame
|
||||
if (visited > BIG_TREE && ++frames % 3 != 0) return true;
|
||||
visited = 0;
|
||||
repaint(decor, 0);
|
||||
} catch (Throwable failure) {
|
||||
if (failures++ < 5) Log.i(TAG, "tonal: frame check failed: " + failure);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private void repaint(View view, int depth) {
|
||||
if (view.getVisibility() != View.VISIBLE || depth > MAX_DEPTH) return;
|
||||
visited++;
|
||||
if (view instanceof SurfaceView || view instanceof TextureView || view instanceof WebView) return;
|
||||
Drawable background = view.getBackground();
|
||||
if (background instanceof ColorDrawable) {
|
||||
if (BlackRule.isBlack(((ColorDrawable) background).getColor())) view.setBackgroundColor(surface);
|
||||
} else if (background != null) {
|
||||
recolor(background, 0);
|
||||
}
|
||||
if (view instanceof ImageView) {
|
||||
Drawable source = ((ImageView) view).getDrawable();
|
||||
// a picture is left alone; only a flat shape or a fade of black used as a picture is repainted
|
||||
if (source instanceof GradientDrawable || source instanceof LayerDrawable) recolor(source, 0);
|
||||
}
|
||||
if (view instanceof ViewGroup) {
|
||||
ViewGroup group = (ViewGroup) view;
|
||||
for (int i = 0, count = group.getChildCount(); i < count; i++) repaint(group.getChildAt(i), depth + 1);
|
||||
}
|
||||
}
|
||||
|
||||
/** Repaints the black parts of a drawable that is not a plain colour: layers, flat shapes and fades. */
|
||||
private void recolor(Drawable drawable, int depth) {
|
||||
if (drawable instanceof LayerDrawable && depth < 3) {
|
||||
LayerDrawable layers = (LayerDrawable) drawable;
|
||||
for (int i = 0, count = layers.getNumberOfLayers(); i < count; i++) {
|
||||
Drawable layer = layers.getDrawable(i);
|
||||
if (layer instanceof ColorDrawable) {
|
||||
if (BlackRule.isBlack(((ColorDrawable) layer).getColor())) {
|
||||
((ColorDrawable) layer.mutate()).setColor(surface);
|
||||
}
|
||||
} else if (layer != null) {
|
||||
recolor(layer, depth + 1);
|
||||
}
|
||||
}
|
||||
} else if (drawable instanceof GradientDrawable && Build.VERSION.SDK_INT >= 24) {
|
||||
tintShape((GradientDrawable) drawable);
|
||||
} else if (drawable instanceof ShapeDrawable) {
|
||||
tintOverlay((ShapeDrawable) drawable);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A flat black shape becomes the surface colour. A fade of two colours that ends in solid black ends in the
|
||||
* surface colour instead, and a transparent black at its other end becomes a transparent surface, so no
|
||||
* darker band shows in the middle. A fade of more stops, or one that never reaches solid black (a shadow),
|
||||
* is left alone.
|
||||
*/
|
||||
private void tintShape(GradientDrawable shape) {
|
||||
int[] stops = shape.getColors();
|
||||
if (stops == null) {
|
||||
ColorStateList fill = shape.getColor();
|
||||
if (fill != null && BlackRule.isBlack(fill.getDefaultColor())) {
|
||||
((GradientDrawable) shape.mutate()).setColor(surface);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (stops.length != 2 || !(BlackRule.isBlack(stops[0]) || BlackRule.isBlack(stops[1]))) return;
|
||||
int[] fixed = new int[2];
|
||||
for (int i = 0; i < 2; i++) {
|
||||
int color = stops[i];
|
||||
if (BlackRule.isBlack(color)) {
|
||||
fixed[i] = surface;
|
||||
} else if ((color >>> 24) != 0xFF && (color & 0x00FFFFFF) == 0) {
|
||||
fixed[i] = (color & 0xFF000000) | (surface & 0x00FFFFFF);
|
||||
} else {
|
||||
fixed[i] = color;
|
||||
}
|
||||
}
|
||||
((GradientDrawable) shape.mutate()).setColors(fixed);
|
||||
}
|
||||
|
||||
/**
|
||||
* A shape painted by a shader whose pixels are black with a changing see-through gets a filter that keeps
|
||||
* the see-through and paints the surface colour instead of the black. Looked at once per drawable; anything
|
||||
* with a colour of its own, or with a filter already, is left alone.
|
||||
*/
|
||||
private void tintOverlay(ShapeDrawable overlay) {
|
||||
if (overlay.getBounds().isEmpty() || judged.contains(overlay)) return;
|
||||
judged.add(overlay);
|
||||
if (overlay.getColorFilter() != null || !paintsOnlyBlack(overlay)) return;
|
||||
((ShapeDrawable) overlay.mutate()).setColorFilter(new PorterDuffColorFilter(surface, PorterDuff.Mode.SRC_IN));
|
||||
}
|
||||
|
||||
/** Whether everything this drawable paints, wherever it paints anything, is black. */
|
||||
private boolean paintsOnlyBlack(Drawable drawable) {
|
||||
try {
|
||||
Rect saved = new Rect(drawable.getBounds());
|
||||
Bitmap bitmap = Bitmap.createBitmap(4, 32, Bitmap.Config.ARGB_8888);
|
||||
drawable.setBounds(0, 0, 4, 32);
|
||||
drawable.draw(new Canvas(bitmap));
|
||||
drawable.setBounds(saved);
|
||||
boolean any = false;
|
||||
boolean black = true;
|
||||
for (int y = 0; y < 32 && black; y++) {
|
||||
int pixel = bitmap.getPixel(2, y);
|
||||
if ((pixel >>> 24) == 0) continue;
|
||||
any = true;
|
||||
black = BlackRule.isBlack(pixel | 0xFF000000);
|
||||
}
|
||||
bitmap.recycle();
|
||||
return any && black;
|
||||
} catch (Throwable unsampled) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override public void onViewAttachedToWindow(View v) {
|
||||
decor.getViewTreeObserver().removeOnPreDrawListener(this);
|
||||
decor.getViewTreeObserver().addOnPreDrawListener(this);
|
||||
}
|
||||
|
||||
@Override public void onViewDetachedFromWindow(View v) {
|
||||
decor.getViewTreeObserver().removeOnPreDrawListener(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import android.util.Log;
|
||||
|
||||
import lihont.two.comments.CommentSkin;
|
||||
import lihont.two.profile.ProfileSkin;
|
||||
import lihont.two.settings.Md3;
|
||||
import lihont.two.settings.ModSettings;
|
||||
import lihont.two.settings.SettingsHost;
|
||||
|
||||
@@ -33,11 +34,17 @@ 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) {
|
||||
try {
|
||||
// The streak keeper does not depend on the look: it only asks whether today's time has come.
|
||||
lihont.two.streak.AutoFlame.onForeground(activity);
|
||||
if (!SettingsHost.md3()) return;
|
||||
ModSettings active = SettingsHost.active();
|
||||
ModSettings.Theme theme = active != null ? active.theme() : ModSettings.Theme.SYSTEM;
|
||||
lihont.two.widget.StreakWidget.refreshAll(activity);
|
||||
CommentSkin.watch(activity, theme);
|
||||
ProfileSkin.watch(activity, theme);
|
||||
// Black backgrounds become the palette's tonal surface, unless pure black (AMOLED) is wanted.
|
||||
Md3.Palette palette = Md3.palette(activity, active != null ? active : ModSettings.defaults());
|
||||
if (palette.dark && (active == null || !active.amoled())) TonalSurfaces.watch(activity, palette.surface);
|
||||
} catch (Throwable ignored) {
|
||||
// Decoration: never let it take a screen down.
|
||||
}
|
||||
|
||||
350
src/lihont/two/settings/KeeperSettings.java
Normal file
350
src/lihont/two/settings/KeeperSettings.java
Normal file
@@ -0,0 +1,350 @@
|
||||
package lihont.two.settings;
|
||||
|
||||
import android.app.Dialog;
|
||||
import android.app.TimePickerDialog;
|
||||
import android.graphics.Color;
|
||||
import android.text.InputFilter;
|
||||
import android.view.Gravity;
|
||||
import android.view.View;
|
||||
import android.view.Window;
|
||||
import android.widget.EditText;
|
||||
import android.widget.LinearLayout;
|
||||
import android.widget.ScrollView;
|
||||
import android.widget.TextView;
|
||||
import android.widget.Toast;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import lihont.two.account.CurrentAccount;
|
||||
import lihont.two.badge.NicheClaim;
|
||||
import lihont.two.streak.AutoFlame;
|
||||
import lihont.two.streak.AutoFlameBook;
|
||||
import lihont.two.streak.AutoFlameStore;
|
||||
import lihont.two.widget.Contacts;
|
||||
import lihont.two.widget.StreakApi;
|
||||
|
||||
/**
|
||||
* The "Огоньки" section of the mod settings: the streak keeper of the signed-in account. Every account has its own
|
||||
* switch, time, message and chats. The keeper writes real messages, so it is off until it is switched on, and
|
||||
* switching it on asks once what it is going to do.
|
||||
*/
|
||||
final class KeeperSettings {
|
||||
/** The messages offered; the last choice in the dialog is a text of the user's own. */
|
||||
private static final String[] PRESETS = {
|
||||
"🔥", "✨", "❤️🔥", "👋", "😊",
|
||||
};
|
||||
private static final String[] PRESET_NAMES = {"Огонёк", "Искры", "Сердце в огне", "Привет", "Улыбка"};
|
||||
|
||||
private final LihonTSettingsActivity activity;
|
||||
private final Md3.Palette palette;
|
||||
private final Runnable rebuild;
|
||||
private final String uid;
|
||||
private final AutoFlameBook book;
|
||||
|
||||
KeeperSettings(LihonTSettingsActivity activity, Md3.Palette palette, Runnable rebuild) {
|
||||
this.activity = activity;
|
||||
this.palette = palette;
|
||||
this.rebuild = rebuild;
|
||||
this.uid = CurrentAccount.uid();
|
||||
this.book = uid == null ? null : AutoFlameStore.load(activity, uid);
|
||||
}
|
||||
|
||||
void fill(LinearLayout card) {
|
||||
if (book == null) {
|
||||
card.addView(Md3.listItem(activity, palette, flame(), "Автопродление огоньков",
|
||||
"Войдите в TikTok, чтобы настроить", null, false));
|
||||
return;
|
||||
}
|
||||
card.addView(switchRow());
|
||||
card.addView(Md3.cardDivider(activity, palette));
|
||||
card.addView(timeRow());
|
||||
card.addView(Md3.cardDivider(activity, palette));
|
||||
card.addView(messageRow());
|
||||
card.addView(Md3.cardDivider(activity, palette));
|
||||
card.addView(chatsRow());
|
||||
card.addView(Md3.cardDivider(activity, palette));
|
||||
card.addView(nowRow());
|
||||
}
|
||||
|
||||
private View flame() {
|
||||
return Md3.flowerIconAvatar(activity, palette.primaryContainer, Md3Icon.FLAME, palette.onPrimaryContainer, 8);
|
||||
}
|
||||
|
||||
private void save() {
|
||||
AutoFlameStore.save(activity, uid, book);
|
||||
AutoFlame.schedule(activity);
|
||||
}
|
||||
|
||||
private static String clock(int minute) {
|
||||
return String.format(java.util.Locale.ROOT, "%02d:%02d", minute / 60, minute % 60);
|
||||
}
|
||||
|
||||
// ---- rows ---------------------------------------------------------------
|
||||
|
||||
private View switchRow() {
|
||||
String who = CurrentAccount.uniqueId();
|
||||
String hint = "Раз в день пишет в выбранные чаты, где огонёк серый"
|
||||
+ (who == null ? "" : " · @" + who) + ". " + AutoFlame.nextLines(activity).get(0);
|
||||
final Md3Switch toggle = new Md3Switch(activity, palette);
|
||||
toggle.setContentDescription("Автопродление огоньков");
|
||||
toggle.setChecked(book.enabled(), false);
|
||||
toggle.setOnCheckedChangeListener((view, value) -> {
|
||||
if (!value) {
|
||||
book.setEnabled(false);
|
||||
save();
|
||||
rebuild.run();
|
||||
return;
|
||||
}
|
||||
if (book.chats().isEmpty()) {
|
||||
Toast.makeText(activity, "Сначала выберите чаты", Toast.LENGTH_LONG).show();
|
||||
view.setChecked(false, true);
|
||||
return;
|
||||
}
|
||||
view.setChecked(false, false); // it turns on only when the user agrees below
|
||||
activity.basicDialog("Включить автопродление?",
|
||||
"Раз в день в " + clock(book.minute()) + " мод сам отправит «" + book.message() + "» от вашего имени "
|
||||
+ "в выбранные чаты (" + book.chats().size() + "), где огонёк серый. Это настоящие "
|
||||
+ "сообщения: друзья их увидят. Выключить можно здесь же.",
|
||||
"Отмена", "Включить", () -> {
|
||||
book.setEnabled(true);
|
||||
save();
|
||||
rebuild.run();
|
||||
});
|
||||
});
|
||||
LinearLayout row = Md3.listItem(activity, palette, flame(), "Автопродление огоньков", hint, toggle, true);
|
||||
row.setOnClickListener(v -> toggle.toggle());
|
||||
return row;
|
||||
}
|
||||
|
||||
private View timeRow() {
|
||||
LinearLayout row = Md3.listItem(activity, palette,
|
||||
Md3.flowerAvatar(activity, palette.primaryContainer, palette.onPrimaryContainer, "12", 8),
|
||||
"Время отправки", clock(book.minute()) + " · по умолчанию полдень", Md3.chevron(activity, palette), true);
|
||||
row.setOnClickListener(v -> new TimePickerDialog(activity, (picker, hour, minute) -> {
|
||||
book.setMinute(hour * 60 + minute);
|
||||
save();
|
||||
rebuild.run();
|
||||
}, book.minute() / 60, book.minute() % 60, true).show());
|
||||
return row;
|
||||
}
|
||||
|
||||
private View messageRow() {
|
||||
LinearLayout row = Md3.listItem(activity, palette,
|
||||
Md3.flowerAvatar(activity, palette.primaryContainer, palette.onPrimaryContainer, book.message(), 8),
|
||||
"Что отправлять", "«" + book.message() + "»", Md3.chevron(activity, palette), true);
|
||||
row.setOnClickListener(v -> openMessageDialog());
|
||||
return row;
|
||||
}
|
||||
|
||||
private View chatsRow() {
|
||||
int count = book.chats().size();
|
||||
LinearLayout row = Md3.listItem(activity, palette,
|
||||
Md3.flowerAvatar(activity, palette.primaryContainer, palette.onPrimaryContainer, String.valueOf(count), 8),
|
||||
"Чаты", count == 0 ? "Ничего не выбрано" : "Выбрано: " + count + " из " + AutoFlameBook.MAX_CHATS,
|
||||
Md3.chevron(activity, palette), true);
|
||||
row.setOnClickListener(v -> openChatsDialog());
|
||||
return row;
|
||||
}
|
||||
|
||||
private View nowRow() {
|
||||
LinearLayout row = Md3.listItem(activity, palette, flame(), "Отправить сейчас",
|
||||
"Только в выбранные чаты, где огонёк серый", null, true);
|
||||
row.setOnClickListener(v -> {
|
||||
if (book.chats().isEmpty()) {
|
||||
Toast.makeText(activity, "Сначала выберите чаты", Toast.LENGTH_LONG).show();
|
||||
return;
|
||||
}
|
||||
activity.basicDialog("Отправить сейчас?",
|
||||
"В выбранные чаты (" + book.chats().size() + "), где огонёк серый, уйдёт «" + book.message()
|
||||
+ "» от вашего имени. Это настоящие сообщения.",
|
||||
"Отмена", "Отправить", this::sendNow);
|
||||
});
|
||||
return row;
|
||||
}
|
||||
|
||||
private void sendNow() {
|
||||
Toast.makeText(activity, "Отправляем…", Toast.LENGTH_SHORT).show();
|
||||
new Thread(new Runnable() {
|
||||
@Override public void run() {
|
||||
final AutoFlame.Report report = AutoFlame.sendNow(activity);
|
||||
activity.runOnUiThread(new Runnable() {
|
||||
@Override public void run() {
|
||||
Toast.makeText(activity, report.describe(), Toast.LENGTH_LONG).show();
|
||||
rebuild.run();
|
||||
}
|
||||
});
|
||||
}
|
||||
}, "lihont-streak-now").start();
|
||||
}
|
||||
|
||||
// ---- dialogs ------------------------------------------------------------
|
||||
|
||||
private Dialog dialog(LinearLayout root) {
|
||||
final Dialog dialog = new Dialog(activity);
|
||||
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
|
||||
root.setBackground(Md3.shape(palette.surfaceContainerHigh, Md3.dialogRadius(palette), activity));
|
||||
ScrollView scroll = new ScrollView(activity);
|
||||
scroll.addView(root);
|
||||
dialog.setContentView(scroll);
|
||||
activity.styleDialog(dialog);
|
||||
return dialog;
|
||||
}
|
||||
|
||||
private void openMessageDialog() {
|
||||
LinearLayout root = new LinearLayout(activity);
|
||||
root.setOrientation(LinearLayout.VERTICAL);
|
||||
root.setPadding(0, Md3.dp(activity, 16), 0, Md3.dp(activity, 8));
|
||||
TextView title = Md3.text(activity, "Что отправлять", Md3.HEADLINE_SMALL, false, palette.onSurface);
|
||||
title.setPadding(Md3.dp(activity, 24), 0, Md3.dp(activity, 24), Md3.dp(activity, 8));
|
||||
root.addView(title);
|
||||
final Dialog dialog = dialog(root);
|
||||
for (int i = 0; i < PRESETS.length; i++) {
|
||||
final String preset = PRESETS[i];
|
||||
LinearLayout row = Md3.listItem(activity, palette,
|
||||
Md3.flowerAvatar(activity, palette.primaryContainer, palette.onPrimaryContainer, preset, 8),
|
||||
PRESET_NAMES[i], preset, null, true);
|
||||
row.setOnClickListener(v -> {
|
||||
dialog.dismiss();
|
||||
book.setMessage(preset);
|
||||
save();
|
||||
rebuild.run();
|
||||
});
|
||||
root.addView(row);
|
||||
}
|
||||
LinearLayout own = Md3.listItem(activity, palette,
|
||||
Md3.flowerAvatar(activity, palette.primaryContainer, palette.onPrimaryContainer, "…", 8),
|
||||
"Свой текст", "До " + AutoFlameBook.MAX_MESSAGE + " символов, одна строка", null, true);
|
||||
own.setOnClickListener(v -> {
|
||||
dialog.dismiss();
|
||||
openOwnMessageDialog();
|
||||
});
|
||||
root.addView(own);
|
||||
TextView note = Md3.text(activity, "Стикеры TikTok появятся позже: сначала проверяем отправку текстом.",
|
||||
Md3.BODY_SMALL, false, palette.onSurfaceVariant);
|
||||
note.setPadding(Md3.dp(activity, 24), Md3.dp(activity, 8), Md3.dp(activity, 24), Md3.dp(activity, 8));
|
||||
root.addView(note);
|
||||
dialog.show();
|
||||
activity.sizeDialog(dialog, 0.88f);
|
||||
}
|
||||
|
||||
private void openOwnMessageDialog() {
|
||||
LinearLayout root = new LinearLayout(activity);
|
||||
root.setOrientation(LinearLayout.VERTICAL);
|
||||
root.setPadding(Md3.dp(activity, 24), Md3.dp(activity, 24), Md3.dp(activity, 24), Md3.dp(activity, 24));
|
||||
root.addView(Md3.text(activity, "Свой текст", Md3.HEADLINE_SMALL, false, palette.onSurface));
|
||||
final EditText input = new EditText(activity);
|
||||
input.setText(book.message());
|
||||
input.setSelectAllOnFocus(true);
|
||||
input.setHintTextColor(palette.onSurfaceVariant);
|
||||
input.setTextColor(palette.onSurface);
|
||||
input.setTextSize(Md3.BODY_LARGE);
|
||||
input.setSingleLine(true);
|
||||
input.setFilters(new InputFilter[] {new InputFilter.LengthFilter(AutoFlameBook.MAX_MESSAGE)});
|
||||
input.setBackground(Md3.outlined(Color.TRANSPARENT, palette.outline, 1f, Md3.SHAPE_EXTRA_SMALL, activity));
|
||||
input.setPadding(Md3.dp(activity, 16), Md3.dp(activity, 14), Md3.dp(activity, 16), Md3.dp(activity, 14));
|
||||
LinearLayout.LayoutParams inputParams = new LinearLayout.LayoutParams(-1, -2);
|
||||
inputParams.topMargin = Md3.dp(activity, 16);
|
||||
root.addView(input, inputParams);
|
||||
LinearLayout actions = new LinearLayout(activity);
|
||||
actions.setGravity(Gravity.END);
|
||||
LinearLayout.LayoutParams actionsParams = new LinearLayout.LayoutParams(-1, -2);
|
||||
actionsParams.topMargin = Md3.dp(activity, 24);
|
||||
root.addView(actions, actionsParams);
|
||||
final Dialog dialog = dialog(root);
|
||||
TextView cancel = Md3.textButton(activity, palette, "Отмена");
|
||||
cancel.setOnClickListener(v -> dialog.dismiss());
|
||||
actions.addView(cancel);
|
||||
TextView ok = Md3.textButton(activity, palette, "Сохранить");
|
||||
ok.setOnClickListener(v -> {
|
||||
String text = input.getText().toString();
|
||||
if (!AutoFlameBook.validMessage(text)) {
|
||||
Toast.makeText(activity, "Нужна одна строка без управляющих символов", Toast.LENGTH_SHORT).show();
|
||||
return;
|
||||
}
|
||||
dialog.dismiss();
|
||||
book.setMessage(text);
|
||||
save();
|
||||
rebuild.run();
|
||||
});
|
||||
LinearLayout.LayoutParams okParams = new LinearLayout.LayoutParams(-2, -2);
|
||||
okParams.leftMargin = Md3.dp(activity, 8);
|
||||
actions.addView(ok, okParams);
|
||||
dialog.show();
|
||||
activity.sizeDialog(dialog, 0.9f);
|
||||
}
|
||||
|
||||
/** The chats that have a streak with this account, asked about off the main thread; the user ticks the ones to keep. */
|
||||
private void openChatsDialog() {
|
||||
Toast.makeText(activity, "Ищем чаты с огоньком…", Toast.LENGTH_SHORT).show();
|
||||
final android.content.Context app = activity.getApplicationContext();
|
||||
new Thread(new Runnable() {
|
||||
@Override public void run() {
|
||||
final List<String[]> found = new ArrayList<String[]>(); // uid, name, streak, grey ("1" or "0")
|
||||
NicheClaim.Account me = NicheClaim.account();
|
||||
if (me != null) {
|
||||
long now = System.currentTimeMillis();
|
||||
for (Map.Entry<String, String> contact : Contacts.all(app, me.uid).entrySet()) {
|
||||
StreakApi.Info info = StreakApi.info(StreakApi.conversationId(me.uid, contact.getKey()));
|
||||
if (info == null) continue;
|
||||
found.add(new String[] {contact.getKey(), contact.getValue(), String.valueOf(info.streak),
|
||||
StreakApi.cold(info.remindAt, info.endAt, now) ? "1" : "0"});
|
||||
}
|
||||
}
|
||||
Collections.sort(found, new Comparator<String[]>() {
|
||||
@Override public int compare(String[] a, String[] b) {
|
||||
return Integer.parseInt(b[2]) - Integer.parseInt(a[2]);
|
||||
}
|
||||
});
|
||||
activity.runOnUiThread(new Runnable() {
|
||||
@Override public void run() {
|
||||
showChats(found);
|
||||
}
|
||||
});
|
||||
}
|
||||
}, "lihont-streak-chats").start();
|
||||
}
|
||||
|
||||
private void showChats(List<String[]> found) {
|
||||
if (activity.isFinishing()) return;
|
||||
LinearLayout root = new LinearLayout(activity);
|
||||
root.setOrientation(LinearLayout.VERTICAL);
|
||||
root.setPadding(0, Md3.dp(activity, 16), 0, Md3.dp(activity, 8));
|
||||
TextView title = Md3.text(activity, "Чаты для автопродления", Md3.HEADLINE_SMALL, false, palette.onSurface);
|
||||
title.setPadding(Md3.dp(activity, 24), 0, Md3.dp(activity, 24), Md3.dp(activity, 4));
|
||||
root.addView(title);
|
||||
final Dialog dialog = dialog(root);
|
||||
dialog.setOnDismissListener(d -> rebuild.run());
|
||||
if (found.isEmpty()) {
|
||||
TextView none = Md3.text(activity,
|
||||
"Чатов с огоньком не видно. Откройте «Входящие» в TikTok под этим аккаунтом, чтобы мод увидел их, и вернитесь.",
|
||||
Md3.BODY_MEDIUM, false, palette.onSurfaceVariant);
|
||||
none.setPadding(Md3.dp(activity, 24), Md3.dp(activity, 8), Md3.dp(activity, 24), Md3.dp(activity, 16));
|
||||
root.addView(none);
|
||||
}
|
||||
for (final String[] chat : found) {
|
||||
final Md3Switch toggle = new Md3Switch(activity, palette);
|
||||
toggle.setChecked(book.hasChat(chat[0]), false);
|
||||
toggle.setOnCheckedChangeListener((view, value) -> {
|
||||
if (!book.setChat(chat[0], value)) {
|
||||
Toast.makeText(activity, "Не больше " + AutoFlameBook.MAX_CHATS + " чатов", Toast.LENGTH_SHORT).show();
|
||||
view.setChecked(false, true);
|
||||
return;
|
||||
}
|
||||
if (!value && book.chats().isEmpty()) book.setEnabled(false);
|
||||
save();
|
||||
});
|
||||
String letter = chat[1].length() == 0 ? "?" : chat[1].substring(0, 1).toUpperCase();
|
||||
LinearLayout row = Md3.listItem(activity, palette,
|
||||
Md3.flowerAvatar(activity, palette.primaryContainer, palette.onPrimaryContainer, letter, 8),
|
||||
chat[1], "Огонёк: " + chat[2] + ("1".equals(chat[3]) ? " · серый" : " · горит"), toggle, true);
|
||||
row.setOnClickListener(v -> toggle.toggle());
|
||||
root.addView(row);
|
||||
}
|
||||
dialog.show();
|
||||
activity.sizeDialog(dialog, 0.92f);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,239 +1,243 @@
|
||||
package lihont.two.settings;
|
||||
|
||||
import android.content.Context;
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.ColorFilter;
|
||||
import android.graphics.Paint;
|
||||
import android.graphics.Path;
|
||||
import android.graphics.PixelFormat;
|
||||
import android.graphics.RectF;
|
||||
import android.graphics.drawable.Drawable;
|
||||
|
||||
/**
|
||||
* Rounded, filled icons drawn from SVG path data, so no icon font or image resources are needed.
|
||||
*
|
||||
* All glyphs are Material Symbols Rounded, weight 400, fill 1 (npm @material-symbols/svg-400
|
||||
* 0.28.2, Apache License 2.0), except TIKTOK, the TikTok mark from Simple Icons 13.21.0
|
||||
* (CC0 1.0; TikTok is a trademark of its owner and is shown only to name the app).
|
||||
*/
|
||||
public final class Md3Icon extends Drawable {
|
||||
public static final int BACK = 0;
|
||||
public static final int CLOSE = 1;
|
||||
public static final int CHECK = 2;
|
||||
public static final int CHEVRON_RIGHT = 3;
|
||||
public static final int SEARCH = 4;
|
||||
public static final int BANNER = 5;
|
||||
public static final int REPOST = 6;
|
||||
public static final int SUN = 7;
|
||||
public static final int MOON = 8;
|
||||
public static final int INFO = 9;
|
||||
public static final int NOTE = 10;
|
||||
public static final int SEND = 11;
|
||||
public static final int TIKTOK = 12;
|
||||
public static final int ADD_PHOTO = 13;
|
||||
public static final int DELETE = 14;
|
||||
public static final int BOTTOM_BAR = 15;
|
||||
public static final int DOWNLOAD = 16;
|
||||
public static final int AD_OFF = 17;
|
||||
public static final int LIVE = 18;
|
||||
public static final int SHOP = 19;
|
||||
public static final int CODE = 20;
|
||||
|
||||
/** Path data in the order of the constants above. */
|
||||
static final String[] PATHS = {
|
||||
// arrow_back
|
||||
"m274-450 227 227q9 9 9 21t-9 21q-9 9-21 9t-21-9L181-459q-5-5-7-10t-2-11q0-6 2-11t7-10l278-278q9-9 21"
|
||||
+ "-9t21 9q9 9 9 21t-9 21L274-510h496q13 0 21.5 8.5T800-480q0 13-8.5 21.5T770-450H274Z",
|
||||
// close
|
||||
"M480-438 270-228q-9 9-21 9t-21-9q-9-9-9-21t9-21l210-210-210-210q-9-9-9-21t9-21q9-9 21-9t21 9l210 210"
|
||||
+ " 210-210q9-9 21-9t21 9q9 9 9 21t-9 21L522-480l210 210q9 9 9 21t-9 21q-9 9-21 9t-21-9L480-438Z",
|
||||
// check
|
||||
"m378-332 363-363q9.27-9 21.64-9 12.36 0 21.36 9.05 9 9.06 9 21.5 0 12.45-9 21.45L399-267q-9 9-21 9t-"
|
||||
+ "21-9L175-449q-9-9.07-8.5-21.53.5-12.47 9.55-21.47 9.06-9 21.5-9 12.45 0 21.45 9l159 160Z",
|
||||
// chevron_right
|
||||
"M530-481 353-658q-9-9-8.5-21t9.5-21q9-9 21.5-9t21.5 9l198 198q5 5 7 10t2 11q0 6-2 11t-7 10L396-261q-"
|
||||
+ "9 9-21 8.5t-21-9.5q-9-9-9-21.5t9-21.5l176-176Z",
|
||||
// search
|
||||
"M378-329q-108.16 0-183.08-75Q120-479 120-585t75-181q75-75 181.5-75t181 75Q632-691 632-584.85 632-542"
|
||||
+ " 618-502q-14 40-42 75l242 240q9 8.56 9 21.78T818-143q-9 9-22.22 9-13.22 0-21.78-9L533-384q-30 26-69."
|
||||
+ "96 40.5Q423.08-329 378-329Zm-1-60q81.25 0 138.13-57.5Q572-504 572-585t-56.87-138.5Q458.25-781 377-78"
|
||||
+ "1q-82.08 0-139.54 57.5Q180-666 180-585t57.46 138.5Q294.92-389 377-389Z",
|
||||
// wallpaper
|
||||
"M180-120q-24 0-42-18t-18-42v-240q0-12.75 8.68-21.38 8.67-8.62 21.5-8.62 12.82 0 21.32 8.62 8.5 8.63 "
|
||||
+ "8.5 21.38v240h240q12.75 0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32-8.63 8.5-21.38 8.5H180Zm"
|
||||
+ "600 0H540q-12.75 0-21.37-8.68-8.63-8.67-8.63-21.5 0-12.82 8.63-21.32 8.62-8.5 21.37-8.5h240v-240q0-1"
|
||||
+ "2.75 8.68-21.38 8.67-8.62 21.5-8.62 12.82 0 21.32 8.62 8.5 8.63 8.5 21.38v240q0 24-18 42t-42 18ZM448"
|
||||
+ "-293l120-155q5-6 12-6t12 6l117 156q5 8 .75 16T697-268H268q-9 0-13.5-8t1.5-16l87-112q5-6 12-6t12 6l81"
|
||||
+ " 111ZM120-780q0-24 18-42t42-18h240q12.75 0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32-8.63 8."
|
||||
+ "5-21.38 8.5H180v240q0 12.75-8.68 21.37-8.67 8.63-21.5 8.63-12.82 0-21.32-8.63-8.5-8.62-8.5-21.37v-24"
|
||||
+ "0Zm720 0v240q0 12.75-8.68 21.37-8.67 8.63-21.5 8.63-12.82 0-21.32-8.63-8.5-8.62-8.5-21.37v-240H540q-"
|
||||
+ "12.75 0-21.37-8.68-8.63-8.67-8.63-21.5 0-12.82 8.63-21.32 8.62-8.5 21.37-8.5h240q24 0 42 18t18 42ZM6"
|
||||
+ "24-570q-23.4 0-38.7-15.3Q570-600.6 570-624q0-23.4 15.3-38.7Q600.6-678 624-678q23.4 0 38.7 15.3Q678-6"
|
||||
+ "47.4 678-624q0 23.4-15.3 38.7Q647.4-570 624-570Z",
|
||||
// repeat
|
||||
"m236-210 65 65q9 9 8.5 21t-8.75 21.12q-9 9.12-21.37 9.5Q267-93 258-102L141-219q-5-5-7-10.13-2-5.14-2"
|
||||
+ "-11 0-5.87 2-10.87 2-5 7-10l117-117q9.07-9 21.53-8.5Q292-386 301-377q8.25 9 8.63 21 .37 12-8.63 21l-"
|
||||
+ "65 65h464v-130q0-12.75 8.68-21.38 8.67-8.62 21.5-8.62 12.82 0 21.32 8.62 8.5 8.63 8.5 21.38v130q0 24"
|
||||
+ ".75-17.62 42.37Q724.75-210 700-210H236Zm488-480H260v130q0 12.75-8.68 21.37-8.67 8.63-21.5 8.63-12.82"
|
||||
+ " 0-21.32-8.63-8.5-8.62-8.5-21.37v-130q0-24.75 17.63-42.38Q235.25-750 260-750h464l-65-65q-9-9-8.5-21t"
|
||||
+ "8.75-21.12q9-9.12 21.38-9.5Q693-867 702-858l117 117q5 5 7 10.13 2 5.14 2 11 0 5.87-2 10.87-2 5-7 10L"
|
||||
+ "702-582q-9.07 9-21.53 8.5Q668-574 659-583q-8.25-9-8.62-21-.38-12 8.62-21l65-65Z",
|
||||
// light_mode
|
||||
"M480-280q-83 0-141.5-58.5T280-480q0-83 58.5-141.5T480-680q83 0 141.5 58.5T680-480q0 83-58.5 141.5T48"
|
||||
+ "0-280ZM70-450q-12.75 0-21.37-8.68-8.63-8.67-8.63-21.5 0-12.82 8.63-21.32Q57.25-510 70-510h100q12.75 "
|
||||
+ "0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32-8.63 8.5-21.38 8.5H70Zm720 0q-12.75 0-21.37-8.68"
|
||||
+ "-8.63-8.67-8.63-21.5 0-12.82 8.63-21.32 8.62-8.5 21.37-8.5h100q12.75 0 21.38 8.68 8.62 8.67 8.62 21."
|
||||
+ "5 0 12.82-8.62 21.32-8.63 8.5-21.38 8.5H790ZM479.82-760q-12.82 0-21.32-8.63-8.5-8.62-8.5-21.37v-100q"
|
||||
+ "0-12.75 8.68-21.38 8.67-8.62 21.5-8.62 12.82 0 21.32 8.62 8.5 8.63 8.5 21.38v100q0 12.75-8.68 21.37-"
|
||||
+ "8.67 8.63-21.5 8.63Zm0 720Q467-40 458.5-48.63 450-57.25 450-70v-100q0-12.75 8.68-21.38 8.67-8.62 21."
|
||||
+ "5-8.62 12.82 0 21.32 8.62 8.5 8.63 8.5 21.38v100q0 12.75-8.68 21.37-8.67 8.63-21.5 8.63ZM240-678l-57"
|
||||
+ "-56q-9-9-8.63-21.6.37-12.61 8.53-21.5 8.89-8.9 21.5-8.9 12.6 0 21.6 9l56 57q8 9 8 21t-8 20.5q-8 8.5-"
|
||||
+ "20.5 8.5t-21.5-8Zm494 495-56-57q-8-9-8-21.38 0-12.37 8.5-20.62 8.5-9 20.5-9t21 9l57 56q9 9 8.63 21.6"
|
||||
+ "-.37 12.61-8.53 21.5-8.89 8.9-21.5 8.9-12.6 0-21.6-9Zm-56-495q-9-9-9-21t9-21l56-57q9-9 21.6-8.63 12."
|
||||
+ "61.37 21.5 8.53 8.9 8.89 8.9 21.5 0 12.6-9 21.6l-57 56q-8 8-20.36 8-12.37 0-21.64-8ZM182.9-182.9q-8."
|
||||
+ "9-8.89-8.9-21.5 0-12.6 9-21.6l57-56q8.8-9 20.9-9 12.1 0 20.71 9 9.39 9 9.39 21t-9 21l-56 57q-9 9-21."
|
||||
+ "6 8.63-12.61-.37-21.5-8.53Z",
|
||||
// dark_mode
|
||||
"M480-120q-150 0-255-105T120-480q0-135 79.5-229T408-830q20-5 34-1t22 15q8 10 7.5 25t-8.5 35q-9 23-14 "
|
||||
+ "47t-5 49q0 90 63 153t153 63q25 0 48.5-4.5T754-461q22-8 38-7t26 9q10 8 13 23t-2 36q-27 121-121 200.5T"
|
||||
+ "480-120Z",
|
||||
// info
|
||||
"M483.18-280q12.82 0 21.32-8.63 8.5-8.62 8.5-21.37v-180q0-12.75-8.68-21.38-8.67-8.62-21.5-8.62-12.82 "
|
||||
+ "0-21.32 8.62-8.5 8.63-8.5 21.38v180q0 12.75 8.68 21.37 8.67 8.63 21.5 8.63Zm-3.2-314q14.02 0 23.52-9"
|
||||
+ ".2T513-626q0-14.45-9.48-24.22-9.48-9.78-23.5-9.78t-23.52 9.78Q447-640.45 447-626q0 13.6 9.48 22.8 9."
|
||||
+ "48 9.2 23.5 9.2Zm.29 514q-82.74 0-155.5-31.5Q252-143 197.5-197.5t-86-127.34Q80-397.68 80-480.5t31.5-"
|
||||
+ "155.66Q143-709 197.5-763t127.34-85.5Q397.68-880 480.5-880t155.66 31.5Q709-817 763-763t85.5 127Q880-5"
|
||||
+ "63 880-480.27q0 82.74-31.5 155.5Q817-252 763-197.68q-54 54.31-127 86Q563-80 480.27-80Z",
|
||||
// music_note
|
||||
"M393-120q-63 0-106.5-43.5T243-270q0-63 43.5-106.5T393-420q28 0 50.5 8t39.5 22v-420q0-13 8.5-21.5T513"
|
||||
+ "-840h174q13 0 21.5 8.5T717-810v75q0 13-8.5 21.5T687-705H543v435q0 63-43.5 106.5T393-120Z",
|
||||
// send
|
||||
"M162-178q-15 6-28.5-2.5T120-205v-200l302-75-302-77v-198q0-16 13.5-24.5T162-782l652 274q18 8 18 28t-1"
|
||||
+ "8 28L162-178Z",
|
||||
// tiktok
|
||||
"M12.525.02c1.31-.02 2.61-.01 3.91-.02.08 1.53.63 3.09 1.75 4.17 1.12 1.11 2.7 1.62 4.24 1.79v4.03c-1"
|
||||
+ ".44-.05-2.89-.35-4.2-.97-.57-.26-1.1-.59-1.62-.93-.01 2.92.01 5.84-.02 8.75-.08 1.4-.54 2.79-1.35 3."
|
||||
+ "94-1.31 1.92-3.58 3.17-5.91 3.21-1.43.08-2.86-.31-4.08-1.03-2.02-1.19-3.44-3.37-3.65-5.71-.02-.5-.03"
|
||||
+ "-1-.01-1.49.18-1.9 1.12-3.72 2.58-4.96 1.66-1.44 3.98-2.13 6.15-1.72.02 1.48-.04 2.96-.04 4.44-.99-."
|
||||
+ "32-2.15-.23-3.02.37-.63.41-1.11 1.04-1.36 1.75-.21.51-.15 1.07-.14 1.61.24 1.64 1.82 3.02 3.5 2.87 1"
|
||||
+ ".12-.01 2.19-.66 2.77-1.61.19-.33.4-.67.41-1.06.1-1.79.06-3.57.07-5.36.01-4.03-.01-8.05.02-12.07z",
|
||||
// add_photo_alternate
|
||||
"M180-120q-24 0-42-18t-18-42v-600q0-24 18-42t42-18h357q15.61 0 23.8 14.5 8.2 14.5.2 29.5-8 17-12 35.2"
|
||||
+ "9-4 18.28-4 37.71 0 73.87 52.07 125.93Q649.13-545 723-545q19.43 0 37.71-4Q779-553 796-561q16-7 30 .5"
|
||||
+ "t14 23.5v357q0 24-18 42t-42 18H180Zm60-162h480L576-474 449-307l-94-124-115 149Zm482.82-323q-12.82 0-"
|
||||
+ "21.32-8.63-8.5-8.62-8.5-21.37v-57h-58q-12.75 0-21.37-8.68-8.63-8.67-8.63-21.5 0-12.82 8.63-21.32 8.6"
|
||||
+ "2-8.5 21.37-8.5h58v-58q0-12.75 8.68-21.38 8.67-8.62 21.5-8.62 12.82 0 21.32 8.62 8.5 8.63 8.5 21.38v"
|
||||
+ "58h57q12.75 0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32-8.63 8.5-21.38 8.5h-57v57q0 12.75-8."
|
||||
+ "68 21.37-8.67 8.63-21.5 8.63Z",
|
||||
// delete
|
||||
"M261-120q-24.75 0-42.37-17.63Q201-155.25 201-180v-570h-11q-12.75 0-21.37-8.68-8.63-8.67-8.63-21.5 0-"
|
||||
+ "12.82 8.63-21.32 8.62-8.5 21.37-8.5h158q0-13 8.63-21.5 8.62-8.5 21.37-8.5h204q12.75 0 21.38 8.62Q612"
|
||||
+ "-822.75 612-810h158q12.75 0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32-8.63 8.5-21.38 8.5h-11"
|
||||
+ "v570q0 24.75-17.62 42.37Q723.75-120 699-120H261Zm136.18-146q12.82 0 21.32-8.63 8.5-8.62 8.5-21.37v-3"
|
||||
+ "39q0-12.75-8.68-21.38-8.67-8.62-21.5-8.62-12.82 0-21.32 8.62-8.5 8.63-8.5 21.38v339q0 12.75 8.68 21."
|
||||
+ "37 8.67 8.63 21.5 8.63Zm166 0q12.82 0 21.32-8.63 8.5-8.62 8.5-21.37v-339q0-12.75-8.68-21.38-8.67-8.6"
|
||||
+ "2-21.5-8.62-12.82 0-21.32 8.62-8.5 8.63-8.5 21.38v339q0 12.75 8.68 21.37 8.67 8.63 21.5 8.63Z",
|
||||
// dock_to_bottom
|
||||
"M180-120q-24.75 0-42.37-17.63Q120-155.25 120-180v-600q0-24.75 17.63-42.38Q155.25-840 180-840h600q24."
|
||||
+ "75 0 42.38 17.62Q840-804.75 840-780v600q0 24.75-17.62 42.37Q804.75-120 780-120H180Zm0-267h600v-393H1"
|
||||
+ "80v393Z",
|
||||
// download
|
||||
"M479.87-325q-5.87 0-10.87-2-5-2-10-7L308-485q-9-9.27-8.5-21.64.5-12.36 9.11-21.36 9.39-9 21.89-9t21."
|
||||
+ "5 9l98 99v-341q0-12.75 8.68-21.38 8.67-8.62 21.5-8.62 12.82 0 21.32 8.62 8.5 8.63 8.5 21.38v341l99-9"
|
||||
+ "9q8.8-9 20.9-8.5 12.1.5 21.49 9.5 8.61 9 8.61 21.5t-9 21.5L501-334q-5 5-10.13 7-5.14 2-11 2ZM220-160"
|
||||
+ "q-24 0-42-18t-18-42v-113q0-12.75 8.68-21.38 8.67-8.62 21.5-8.62 12.82 0 21.32 8.62 8.5 8.63 8.5 21.3"
|
||||
+ "8v113h520v-113q0-12.75 8.68-21.38 8.67-8.62 21.5-8.62 12.82 0 21.32 8.62 8.5 8.63 8.5 21.38v113q0 24"
|
||||
+ "-18 42t-42 18H220Z",
|
||||
// block
|
||||
"M480-80q-83 0-156-31.5T197-197q-54-54-85.5-127T80-480q0-83 31.5-156T197-763q54-54 127-85.5T480-880q8"
|
||||
+ "3 0 156 31.5T763-763q54 54 85.5 127T880-480q0 83-31.5 156T763-197q-54 54-127 85.5T480-80Zm0-80q54 0 "
|
||||
+ "104-17.5t92-50.5L228-676q-33 42-50.5 92T160-480q0 134 93 227t227 93Zm252-124q33-42 50.5-92T800-480q0"
|
||||
+ "-134-93-227t-227-93q-54 0-104 17.5T284-732l448 448Z",
|
||||
// sensors
|
||||
"M400,-480 A80 80 0 1 1 560,-480 A80 80 0 1 1 400,-480 Z M607.3,-607.3 A180 180 0 0 1 607.3,-352.7 L6"
|
||||
+ "63.8,-296.2 A260 260 0 0 0 663.8,-663.8 Z M352.7,-352.7 A180 180 0 0 1 352.7,-607.3 L296.2,-663.8 A2"
|
||||
+ "60 260 0 0 0 296.2,-296.2 Z M713.3,-713.3 A330 330 0 0 1 713.3,-246.7 L769.9,-190.1 A410 410 0 0 0 7"
|
||||
+ "69.9,-769.9 Z M246.7,-246.7 A330 330 0 0 1 246.7,-713.3 L190.1,-769.9 A410 410 0 0 0 190.1,-190.1 Z",
|
||||
// shopping bag
|
||||
"M240,-640 H720 A40 40 0 0 1 760,-600 V-200 A40 40 0 0 1 720,-160 H240 A40 40 0 0 1 200,-200 V-600 A4"
|
||||
+ "0 40 0 0 1 240,-640 Z M320,-640 A160 160 0 0 1 640,-640 L560,-640 A80 80 0 0 0 400,-640 Z",
|
||||
// code
|
||||
"M315.6,-699 L155.6,-509 A45 45 0 0 0 224.4,-451 L384.4,-641 A45 45 0 0 0 315.6,-699 Z M155.6,-451 L3"
|
||||
+ "15.6,-261 A45 45 0 0 0 384.4,-319 L224.4,-509 A45 45 0 0 0 155.6,-451 Z M575.6,-641 L735.6,-451 A45 "
|
||||
+ "45 0 0 0 804.4,-509 L644.4,-699 A45 45 0 0 0 575.6,-641 Z M735.6,-509 L575.6,-319 A45 45 0 0 0 644.4"
|
||||
+ ",-261 L804.4,-451 A45 45 0 0 0 735.6,-509 Z M501.3,-750.9 L371.3,-230.9 A45 45 0 0 0 458.7,-209.1 L5"
|
||||
+ "88.7,-729.1 A45 45 0 0 0 501.3,-750.9 Z",
|
||||
};
|
||||
|
||||
/** Side of the square grid each path is drawn on: Material Symbols use 960, Simple Icons 24. */
|
||||
static final float[] GRID = {960f, 960f, 960f, 960f, 960f, 960f, 960f, 960f, 960f, 960f, 960f, 960f, 24f, 960f, 960f, 960f, 960f, 960f, 960f, 960f, 960f};
|
||||
|
||||
/** Top of the grid on the y axis: Material Symbols start at -960, Simple Icons at 0. */
|
||||
static final float[] ORIGIN_Y = {-960f, -960f, -960f, -960f, -960f, -960f, -960f, -960f, -960f, -960f, -960f, -960f, 0f, -960f, -960f, -960f, -960f, -960f, -960f, -960f, -960f};
|
||||
|
||||
private final float density;
|
||||
private final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
|
||||
private final Path path = new Path();
|
||||
|
||||
private Md3Icon(int kind, int color, float density) {
|
||||
if (kind < 0 || kind >= PATHS.length) throw new IllegalArgumentException("Unknown icon " + kind);
|
||||
this.density = density;
|
||||
paint.setColor(color);
|
||||
paint.setStyle(Paint.Style.FILL);
|
||||
build(kind, new SvgPath.Sink() {
|
||||
@Override public void moveTo(float x, float y) { path.moveTo(x, y); }
|
||||
|
||||
@Override public void lineTo(float x, float y) { path.lineTo(x, y); }
|
||||
|
||||
@Override public void cubicTo(float x1, float y1, float x2, float y2, float x, float y) {
|
||||
path.cubicTo(x1, y1, x2, y2, x, y);
|
||||
}
|
||||
|
||||
@Override public void close() { path.close(); }
|
||||
});
|
||||
}
|
||||
|
||||
/** Feeds one icon to a sink, mapped from its own grid onto the 24 unit square the drawable uses. */
|
||||
static void build(int kind, final SvgPath.Sink sink) {
|
||||
final float scale = 24f / GRID[kind];
|
||||
final float top = ORIGIN_Y[kind];
|
||||
SvgPath.parse(PATHS[kind], new SvgPath.Sink() {
|
||||
@Override public void moveTo(float x, float y) { sink.moveTo(x * scale, (y - top) * scale); }
|
||||
|
||||
@Override public void lineTo(float x, float y) { sink.lineTo(x * scale, (y - top) * scale); }
|
||||
|
||||
@Override public void cubicTo(float x1, float y1, float x2, float y2, float x, float y) {
|
||||
sink.cubicTo(x1 * scale, (y1 - top) * scale, x2 * scale, (y2 - top) * scale,
|
||||
x * scale, (y - top) * scale);
|
||||
}
|
||||
|
||||
@Override public void close() { sink.close(); }
|
||||
});
|
||||
}
|
||||
|
||||
public static Drawable of(int kind, int color, Context context) {
|
||||
return new Md3Icon(kind, color, context.getResources().getDisplayMetrics().density);
|
||||
}
|
||||
|
||||
@Override public void draw(Canvas canvas) {
|
||||
RectF bounds = new RectF(getBounds());
|
||||
float scale = Math.min(bounds.width(), bounds.height()) / 24f;
|
||||
if (scale <= 0f) return;
|
||||
canvas.save();
|
||||
canvas.translate(bounds.left + (bounds.width() - 24f * scale) / 2f,
|
||||
bounds.top + (bounds.height() - 24f * scale) / 2f);
|
||||
canvas.scale(scale, scale);
|
||||
canvas.drawPath(path, paint);
|
||||
canvas.restore();
|
||||
}
|
||||
|
||||
@Override public void setAlpha(int alpha) { paint.setAlpha(alpha); }
|
||||
|
||||
@Override public void setColorFilter(ColorFilter filter) { paint.setColorFilter(filter); }
|
||||
|
||||
@Override public int getOpacity() { return PixelFormat.TRANSLUCENT; }
|
||||
|
||||
@Override public int getIntrinsicWidth() { return (int) (24f * density + .5f); }
|
||||
|
||||
@Override public int getIntrinsicHeight() { return (int) (24f * density + .5f); }
|
||||
}
|
||||
package lihont.two.settings;
|
||||
|
||||
import android.content.Context;
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.ColorFilter;
|
||||
import android.graphics.Paint;
|
||||
import android.graphics.Path;
|
||||
import android.graphics.PixelFormat;
|
||||
import android.graphics.RectF;
|
||||
import android.graphics.drawable.Drawable;
|
||||
|
||||
/**
|
||||
* Rounded, filled icons drawn from SVG path data, so no icon font or image resources are needed.
|
||||
*
|
||||
* All glyphs are Material Symbols Rounded, weight 400, fill 1 (npm @material-symbols/svg-400
|
||||
* 0.28.2, Apache License 2.0), except TIKTOK, the TikTok mark from Simple Icons 13.21.0
|
||||
* (CC0 1.0; TikTok is a trademark of its owner and is shown only to name the app).
|
||||
*/
|
||||
public final class Md3Icon extends Drawable {
|
||||
public static final int BACK = 0;
|
||||
public static final int CLOSE = 1;
|
||||
public static final int CHECK = 2;
|
||||
public static final int CHEVRON_RIGHT = 3;
|
||||
public static final int SEARCH = 4;
|
||||
public static final int BANNER = 5;
|
||||
public static final int REPOST = 6;
|
||||
public static final int SUN = 7;
|
||||
public static final int MOON = 8;
|
||||
public static final int INFO = 9;
|
||||
public static final int NOTE = 10;
|
||||
public static final int SEND = 11;
|
||||
public static final int TIKTOK = 12;
|
||||
public static final int ADD_PHOTO = 13;
|
||||
public static final int DELETE = 14;
|
||||
public static final int BOTTOM_BAR = 15;
|
||||
public static final int DOWNLOAD = 16;
|
||||
public static final int AD_OFF = 17;
|
||||
public static final int LIVE = 18;
|
||||
public static final int SHOP = 19;
|
||||
public static final int CODE = 20;
|
||||
public static final int FLAME = 21;
|
||||
|
||||
/** Path data in the order of the constants above. */
|
||||
static final String[] PATHS = {
|
||||
// arrow_back
|
||||
"m274-450 227 227q9 9 9 21t-9 21q-9 9-21 9t-21-9L181-459q-5-5-7-10t-2-11q0-6 2-11t7-10l278-278q9-9 21"
|
||||
+ "-9t21 9q9 9 9 21t-9 21L274-510h496q13 0 21.5 8.5T800-480q0 13-8.5 21.5T770-450H274Z",
|
||||
// close
|
||||
"M480-438 270-228q-9 9-21 9t-21-9q-9-9-9-21t9-21l210-210-210-210q-9-9-9-21t9-21q9-9 21-9t21 9l210 210"
|
||||
+ " 210-210q9-9 21-9t21 9q9 9 9 21t-9 21L522-480l210 210q9 9 9 21t-9 21q-9 9-21 9t-21-9L480-438Z",
|
||||
// check
|
||||
"m378-332 363-363q9.27-9 21.64-9 12.36 0 21.36 9.05 9 9.06 9 21.5 0 12.45-9 21.45L399-267q-9 9-21 9t-"
|
||||
+ "21-9L175-449q-9-9.07-8.5-21.53.5-12.47 9.55-21.47 9.06-9 21.5-9 12.45 0 21.45 9l159 160Z",
|
||||
// chevron_right
|
||||
"M530-481 353-658q-9-9-8.5-21t9.5-21q9-9 21.5-9t21.5 9l198 198q5 5 7 10t2 11q0 6-2 11t-7 10L396-261q-"
|
||||
+ "9 9-21 8.5t-21-9.5q-9-9-9-21.5t9-21.5l176-176Z",
|
||||
// search
|
||||
"M378-329q-108.16 0-183.08-75Q120-479 120-585t75-181q75-75 181.5-75t181 75Q632-691 632-584.85 632-542"
|
||||
+ " 618-502q-14 40-42 75l242 240q9 8.56 9 21.78T818-143q-9 9-22.22 9-13.22 0-21.78-9L533-384q-30 26-69."
|
||||
+ "96 40.5Q423.08-329 378-329Zm-1-60q81.25 0 138.13-57.5Q572-504 572-585t-56.87-138.5Q458.25-781 377-78"
|
||||
+ "1q-82.08 0-139.54 57.5Q180-666 180-585t57.46 138.5Q294.92-389 377-389Z",
|
||||
// wallpaper
|
||||
"M180-120q-24 0-42-18t-18-42v-240q0-12.75 8.68-21.38 8.67-8.62 21.5-8.62 12.82 0 21.32 8.62 8.5 8.63 "
|
||||
+ "8.5 21.38v240h240q12.75 0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32-8.63 8.5-21.38 8.5H180Zm"
|
||||
+ "600 0H540q-12.75 0-21.37-8.68-8.63-8.67-8.63-21.5 0-12.82 8.63-21.32 8.62-8.5 21.37-8.5h240v-240q0-1"
|
||||
+ "2.75 8.68-21.38 8.67-8.62 21.5-8.62 12.82 0 21.32 8.62 8.5 8.63 8.5 21.38v240q0 24-18 42t-42 18ZM448"
|
||||
+ "-293l120-155q5-6 12-6t12 6l117 156q5 8 .75 16T697-268H268q-9 0-13.5-8t1.5-16l87-112q5-6 12-6t12 6l81"
|
||||
+ " 111ZM120-780q0-24 18-42t42-18h240q12.75 0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32-8.63 8."
|
||||
+ "5-21.38 8.5H180v240q0 12.75-8.68 21.37-8.67 8.63-21.5 8.63-12.82 0-21.32-8.63-8.5-8.62-8.5-21.37v-24"
|
||||
+ "0Zm720 0v240q0 12.75-8.68 21.37-8.67 8.63-21.5 8.63-12.82 0-21.32-8.63-8.5-8.62-8.5-21.37v-240H540q-"
|
||||
+ "12.75 0-21.37-8.68-8.63-8.67-8.63-21.5 0-12.82 8.63-21.32 8.62-8.5 21.37-8.5h240q24 0 42 18t18 42ZM6"
|
||||
+ "24-570q-23.4 0-38.7-15.3Q570-600.6 570-624q0-23.4 15.3-38.7Q600.6-678 624-678q23.4 0 38.7 15.3Q678-6"
|
||||
+ "47.4 678-624q0 23.4-15.3 38.7Q647.4-570 624-570Z",
|
||||
// repeat
|
||||
"m236-210 65 65q9 9 8.5 21t-8.75 21.12q-9 9.12-21.37 9.5Q267-93 258-102L141-219q-5-5-7-10.13-2-5.14-2"
|
||||
+ "-11 0-5.87 2-10.87 2-5 7-10l117-117q9.07-9 21.53-8.5Q292-386 301-377q8.25 9 8.63 21 .37 12-8.63 21l-"
|
||||
+ "65 65h464v-130q0-12.75 8.68-21.38 8.67-8.62 21.5-8.62 12.82 0 21.32 8.62 8.5 8.63 8.5 21.38v130q0 24"
|
||||
+ ".75-17.62 42.37Q724.75-210 700-210H236Zm488-480H260v130q0 12.75-8.68 21.37-8.67 8.63-21.5 8.63-12.82"
|
||||
+ " 0-21.32-8.63-8.5-8.62-8.5-21.37v-130q0-24.75 17.63-42.38Q235.25-750 260-750h464l-65-65q-9-9-8.5-21t"
|
||||
+ "8.75-21.12q9-9.12 21.38-9.5Q693-867 702-858l117 117q5 5 7 10.13 2 5.14 2 11 0 5.87-2 10.87-2 5-7 10L"
|
||||
+ "702-582q-9.07 9-21.53 8.5Q668-574 659-583q-8.25-9-8.62-21-.38-12 8.62-21l65-65Z",
|
||||
// light_mode
|
||||
"M480-280q-83 0-141.5-58.5T280-480q0-83 58.5-141.5T480-680q83 0 141.5 58.5T680-480q0 83-58.5 141.5T48"
|
||||
+ "0-280ZM70-450q-12.75 0-21.37-8.68-8.63-8.67-8.63-21.5 0-12.82 8.63-21.32Q57.25-510 70-510h100q12.75 "
|
||||
+ "0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32-8.63 8.5-21.38 8.5H70Zm720 0q-12.75 0-21.37-8.68"
|
||||
+ "-8.63-8.67-8.63-21.5 0-12.82 8.63-21.32 8.62-8.5 21.37-8.5h100q12.75 0 21.38 8.68 8.62 8.67 8.62 21."
|
||||
+ "5 0 12.82-8.62 21.32-8.63 8.5-21.38 8.5H790ZM479.82-760q-12.82 0-21.32-8.63-8.5-8.62-8.5-21.37v-100q"
|
||||
+ "0-12.75 8.68-21.38 8.67-8.62 21.5-8.62 12.82 0 21.32 8.62 8.5 8.63 8.5 21.38v100q0 12.75-8.68 21.37-"
|
||||
+ "8.67 8.63-21.5 8.63Zm0 720Q467-40 458.5-48.63 450-57.25 450-70v-100q0-12.75 8.68-21.38 8.67-8.62 21."
|
||||
+ "5-8.62 12.82 0 21.32 8.62 8.5 8.63 8.5 21.38v100q0 12.75-8.68 21.37-8.67 8.63-21.5 8.63ZM240-678l-57"
|
||||
+ "-56q-9-9-8.63-21.6.37-12.61 8.53-21.5 8.89-8.9 21.5-8.9 12.6 0 21.6 9l56 57q8 9 8 21t-8 20.5q-8 8.5-"
|
||||
+ "20.5 8.5t-21.5-8Zm494 495-56-57q-8-9-8-21.38 0-12.37 8.5-20.62 8.5-9 20.5-9t21 9l57 56q9 9 8.63 21.6"
|
||||
+ "-.37 12.61-8.53 21.5-8.89 8.9-21.5 8.9-12.6 0-21.6-9Zm-56-495q-9-9-9-21t9-21l56-57q9-9 21.6-8.63 12."
|
||||
+ "61.37 21.5 8.53 8.9 8.89 8.9 21.5 0 12.6-9 21.6l-57 56q-8 8-20.36 8-12.37 0-21.64-8ZM182.9-182.9q-8."
|
||||
+ "9-8.89-8.9-21.5 0-12.6 9-21.6l57-56q8.8-9 20.9-9 12.1 0 20.71 9 9.39 9 9.39 21t-9 21l-56 57q-9 9-21."
|
||||
+ "6 8.63-12.61-.37-21.5-8.53Z",
|
||||
// dark_mode
|
||||
"M480-120q-150 0-255-105T120-480q0-135 79.5-229T408-830q20-5 34-1t22 15q8 10 7.5 25t-8.5 35q-9 23-14 "
|
||||
+ "47t-5 49q0 90 63 153t153 63q25 0 48.5-4.5T754-461q22-8 38-7t26 9q10 8 13 23t-2 36q-27 121-121 200.5T"
|
||||
+ "480-120Z",
|
||||
// info
|
||||
"M483.18-280q12.82 0 21.32-8.63 8.5-8.62 8.5-21.37v-180q0-12.75-8.68-21.38-8.67-8.62-21.5-8.62-12.82 "
|
||||
+ "0-21.32 8.62-8.5 8.63-8.5 21.38v180q0 12.75 8.68 21.37 8.67 8.63 21.5 8.63Zm-3.2-314q14.02 0 23.52-9"
|
||||
+ ".2T513-626q0-14.45-9.48-24.22-9.48-9.78-23.5-9.78t-23.52 9.78Q447-640.45 447-626q0 13.6 9.48 22.8 9."
|
||||
+ "48 9.2 23.5 9.2Zm.29 514q-82.74 0-155.5-31.5Q252-143 197.5-197.5t-86-127.34Q80-397.68 80-480.5t31.5-"
|
||||
+ "155.66Q143-709 197.5-763t127.34-85.5Q397.68-880 480.5-880t155.66 31.5Q709-817 763-763t85.5 127Q880-5"
|
||||
+ "63 880-480.27q0 82.74-31.5 155.5Q817-252 763-197.68q-54 54.31-127 86Q563-80 480.27-80Z",
|
||||
// music_note
|
||||
"M393-120q-63 0-106.5-43.5T243-270q0-63 43.5-106.5T393-420q28 0 50.5 8t39.5 22v-420q0-13 8.5-21.5T513"
|
||||
+ "-840h174q13 0 21.5 8.5T717-810v75q0 13-8.5 21.5T687-705H543v435q0 63-43.5 106.5T393-120Z",
|
||||
// send
|
||||
"M162-178q-15 6-28.5-2.5T120-205v-200l302-75-302-77v-198q0-16 13.5-24.5T162-782l652 274q18 8 18 28t-1"
|
||||
+ "8 28L162-178Z",
|
||||
// tiktok
|
||||
"M12.525.02c1.31-.02 2.61-.01 3.91-.02.08 1.53.63 3.09 1.75 4.17 1.12 1.11 2.7 1.62 4.24 1.79v4.03c-1"
|
||||
+ ".44-.05-2.89-.35-4.2-.97-.57-.26-1.1-.59-1.62-.93-.01 2.92.01 5.84-.02 8.75-.08 1.4-.54 2.79-1.35 3."
|
||||
+ "94-1.31 1.92-3.58 3.17-5.91 3.21-1.43.08-2.86-.31-4.08-1.03-2.02-1.19-3.44-3.37-3.65-5.71-.02-.5-.03"
|
||||
+ "-1-.01-1.49.18-1.9 1.12-3.72 2.58-4.96 1.66-1.44 3.98-2.13 6.15-1.72.02 1.48-.04 2.96-.04 4.44-.99-."
|
||||
+ "32-2.15-.23-3.02.37-.63.41-1.11 1.04-1.36 1.75-.21.51-.15 1.07-.14 1.61.24 1.64 1.82 3.02 3.5 2.87 1"
|
||||
+ ".12-.01 2.19-.66 2.77-1.61.19-.33.4-.67.41-1.06.1-1.79.06-3.57.07-5.36.01-4.03-.01-8.05.02-12.07z",
|
||||
// add_photo_alternate
|
||||
"M180-120q-24 0-42-18t-18-42v-600q0-24 18-42t42-18h357q15.61 0 23.8 14.5 8.2 14.5.2 29.5-8 17-12 35.2"
|
||||
+ "9-4 18.28-4 37.71 0 73.87 52.07 125.93Q649.13-545 723-545q19.43 0 37.71-4Q779-553 796-561q16-7 30 .5"
|
||||
+ "t14 23.5v357q0 24-18 42t-42 18H180Zm60-162h480L576-474 449-307l-94-124-115 149Zm482.82-323q-12.82 0-"
|
||||
+ "21.32-8.63-8.5-8.62-8.5-21.37v-57h-58q-12.75 0-21.37-8.68-8.63-8.67-8.63-21.5 0-12.82 8.63-21.32 8.6"
|
||||
+ "2-8.5 21.37-8.5h58v-58q0-12.75 8.68-21.38 8.67-8.62 21.5-8.62 12.82 0 21.32 8.62 8.5 8.63 8.5 21.38v"
|
||||
+ "58h57q12.75 0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32-8.63 8.5-21.38 8.5h-57v57q0 12.75-8."
|
||||
+ "68 21.37-8.67 8.63-21.5 8.63Z",
|
||||
// delete
|
||||
"M261-120q-24.75 0-42.37-17.63Q201-155.25 201-180v-570h-11q-12.75 0-21.37-8.68-8.63-8.67-8.63-21.5 0-"
|
||||
+ "12.82 8.63-21.32 8.62-8.5 21.37-8.5h158q0-13 8.63-21.5 8.62-8.5 21.37-8.5h204q12.75 0 21.38 8.62Q612"
|
||||
+ "-822.75 612-810h158q12.75 0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32-8.63 8.5-21.38 8.5h-11"
|
||||
+ "v570q0 24.75-17.62 42.37Q723.75-120 699-120H261Zm136.18-146q12.82 0 21.32-8.63 8.5-8.62 8.5-21.37v-3"
|
||||
+ "39q0-12.75-8.68-21.38-8.67-8.62-21.5-8.62-12.82 0-21.32 8.62-8.5 8.63-8.5 21.38v339q0 12.75 8.68 21."
|
||||
+ "37 8.67 8.63 21.5 8.63Zm166 0q12.82 0 21.32-8.63 8.5-8.62 8.5-21.37v-339q0-12.75-8.68-21.38-8.67-8.6"
|
||||
+ "2-21.5-8.62-12.82 0-21.32 8.62-8.5 8.63-8.5 21.38v339q0 12.75 8.68 21.37 8.67 8.63 21.5 8.63Z",
|
||||
// dock_to_bottom
|
||||
"M180-120q-24.75 0-42.37-17.63Q120-155.25 120-180v-600q0-24.75 17.63-42.38Q155.25-840 180-840h600q24."
|
||||
+ "75 0 42.38 17.62Q840-804.75 840-780v600q0 24.75-17.62 42.37Q804.75-120 780-120H180Zm0-267h600v-393H1"
|
||||
+ "80v393Z",
|
||||
// download
|
||||
"M479.87-325q-5.87 0-10.87-2-5-2-10-7L308-485q-9-9.27-8.5-21.64.5-12.36 9.11-21.36 9.39-9 21.89-9t21."
|
||||
+ "5 9l98 99v-341q0-12.75 8.68-21.38 8.67-8.62 21.5-8.62 12.82 0 21.32 8.62 8.5 8.63 8.5 21.38v341l99-9"
|
||||
+ "9q8.8-9 20.9-8.5 12.1.5 21.49 9.5 8.61 9 8.61 21.5t-9 21.5L501-334q-5 5-10.13 7-5.14 2-11 2ZM220-160"
|
||||
+ "q-24 0-42-18t-18-42v-113q0-12.75 8.68-21.38 8.67-8.62 21.5-8.62 12.82 0 21.32 8.62 8.5 8.63 8.5 21.3"
|
||||
+ "8v113h520v-113q0-12.75 8.68-21.38 8.67-8.62 21.5-8.62 12.82 0 21.32 8.62 8.5 8.63 8.5 21.38v113q0 24"
|
||||
+ "-18 42t-42 18H220Z",
|
||||
// block
|
||||
"M480-80q-83 0-156-31.5T197-197q-54-54-85.5-127T80-480q0-83 31.5-156T197-763q54-54 127-85.5T480-880q8"
|
||||
+ "3 0 156 31.5T763-763q54 54 85.5 127T880-480q0 83-31.5 156T763-197q-54 54-127 85.5T480-80Zm0-80q54 0 "
|
||||
+ "104-17.5t92-50.5L228-676q-33 42-50.5 92T160-480q0 134 93 227t227 93Zm252-124q33-42 50.5-92T800-480q0"
|
||||
+ "-134-93-227t-227-93q-54 0-104 17.5T284-732l448 448Z",
|
||||
// sensors
|
||||
"M400,-480 A80 80 0 1 1 560,-480 A80 80 0 1 1 400,-480 Z M607.3,-607.3 A180 180 0 0 1 607.3,-352.7 L6"
|
||||
+ "63.8,-296.2 A260 260 0 0 0 663.8,-663.8 Z M352.7,-352.7 A180 180 0 0 1 352.7,-607.3 L296.2,-663.8 A2"
|
||||
+ "60 260 0 0 0 296.2,-296.2 Z M713.3,-713.3 A330 330 0 0 1 713.3,-246.7 L769.9,-190.1 A410 410 0 0 0 7"
|
||||
+ "69.9,-769.9 Z M246.7,-246.7 A330 330 0 0 1 246.7,-713.3 L190.1,-769.9 A410 410 0 0 0 190.1,-190.1 Z",
|
||||
// shopping bag
|
||||
"M240,-640 H720 A40 40 0 0 1 760,-600 V-200 A40 40 0 0 1 720,-160 H240 A40 40 0 0 1 200,-200 V-600 A4"
|
||||
+ "0 40 0 0 1 240,-640 Z M320,-640 A160 160 0 0 1 640,-640 L560,-640 A80 80 0 0 0 400,-640 Z",
|
||||
// code
|
||||
"M315.6,-699 L155.6,-509 A45 45 0 0 0 224.4,-451 L384.4,-641 A45 45 0 0 0 315.6,-699 Z M155.6,-451 L3"
|
||||
+ "15.6,-261 A45 45 0 0 0 384.4,-319 L224.4,-509 A45 45 0 0 0 155.6,-451 Z M575.6,-641 L735.6,-451 A45 "
|
||||
+ "45 0 0 0 804.4,-509 L644.4,-699 A45 45 0 0 0 575.6,-641 Z M735.6,-509 L575.6,-319 A45 45 0 0 0 644.4"
|
||||
+ ",-261 L804.4,-451 A45 45 0 0 0 735.6,-509 Z M501.3,-750.9 L371.3,-230.9 A45 45 0 0 0 458.7,-209.1 L5"
|
||||
+ "88.7,-729.1 A45 45 0 0 0 501.3,-750.9 Z",
|
||||
// flame (the streak widget)
|
||||
"M480,-900 C528,-720 780,-600 780,-352 C780,-176 648,-60 480,-60 C312,-60 180,-176 180,-344 C180,-456 2"
|
||||
+ "40,-536 312,-608 C320,-520 356,-472 408,-448 C380,-616 416,-768 480,-900 Z",
|
||||
};
|
||||
|
||||
/** Side of the square grid each path is drawn on: Material Symbols use 960, Simple Icons 24. */
|
||||
static final float[] GRID = {960f, 960f, 960f, 960f, 960f, 960f, 960f, 960f, 960f, 960f, 960f, 960f, 24f, 960f, 960f, 960f, 960f, 960f, 960f, 960f, 960f, 960f};
|
||||
|
||||
/** Top of the grid on the y axis: Material Symbols start at -960, Simple Icons at 0. */
|
||||
static final float[] ORIGIN_Y = {-960f, -960f, -960f, -960f, -960f, -960f, -960f, -960f, -960f, -960f, -960f, -960f, 0f, -960f, -960f, -960f, -960f, -960f, -960f, -960f, -960f, -960f};
|
||||
|
||||
private final float density;
|
||||
private final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
|
||||
private final Path path = new Path();
|
||||
|
||||
private Md3Icon(int kind, int color, float density) {
|
||||
if (kind < 0 || kind >= PATHS.length) throw new IllegalArgumentException("Unknown icon " + kind);
|
||||
this.density = density;
|
||||
paint.setColor(color);
|
||||
paint.setStyle(Paint.Style.FILL);
|
||||
build(kind, new SvgPath.Sink() {
|
||||
@Override public void moveTo(float x, float y) { path.moveTo(x, y); }
|
||||
|
||||
@Override public void lineTo(float x, float y) { path.lineTo(x, y); }
|
||||
|
||||
@Override public void cubicTo(float x1, float y1, float x2, float y2, float x, float y) {
|
||||
path.cubicTo(x1, y1, x2, y2, x, y);
|
||||
}
|
||||
|
||||
@Override public void close() { path.close(); }
|
||||
});
|
||||
}
|
||||
|
||||
/** Feeds one icon to a sink, mapped from its own grid onto the 24 unit square the drawable uses. */
|
||||
static void build(int kind, final SvgPath.Sink sink) {
|
||||
final float scale = 24f / GRID[kind];
|
||||
final float top = ORIGIN_Y[kind];
|
||||
SvgPath.parse(PATHS[kind], new SvgPath.Sink() {
|
||||
@Override public void moveTo(float x, float y) { sink.moveTo(x * scale, (y - top) * scale); }
|
||||
|
||||
@Override public void lineTo(float x, float y) { sink.lineTo(x * scale, (y - top) * scale); }
|
||||
|
||||
@Override public void cubicTo(float x1, float y1, float x2, float y2, float x, float y) {
|
||||
sink.cubicTo(x1 * scale, (y1 - top) * scale, x2 * scale, (y2 - top) * scale,
|
||||
x * scale, (y - top) * scale);
|
||||
}
|
||||
|
||||
@Override public void close() { sink.close(); }
|
||||
});
|
||||
}
|
||||
|
||||
public static Drawable of(int kind, int color, Context context) {
|
||||
return new Md3Icon(kind, color, context.getResources().getDisplayMetrics().density);
|
||||
}
|
||||
|
||||
@Override public void draw(Canvas canvas) {
|
||||
RectF bounds = new RectF(getBounds());
|
||||
float scale = Math.min(bounds.width(), bounds.height()) / 24f;
|
||||
if (scale <= 0f) return;
|
||||
canvas.save();
|
||||
canvas.translate(bounds.left + (bounds.width() - 24f * scale) / 2f,
|
||||
bounds.top + (bounds.height() - 24f * scale) / 2f);
|
||||
canvas.scale(scale, scale);
|
||||
canvas.drawPath(path, paint);
|
||||
canvas.restore();
|
||||
}
|
||||
|
||||
@Override public void setAlpha(int alpha) { paint.setAlpha(alpha); }
|
||||
|
||||
@Override public void setColorFilter(ColorFilter filter) { paint.setColorFilter(filter); }
|
||||
|
||||
@Override public int getOpacity() { return PixelFormat.TRANSLUCENT; }
|
||||
|
||||
@Override public int getIntrinsicWidth() { return (int) (24f * density + .5f); }
|
||||
|
||||
@Override public int getIntrinsicHeight() { return (int) (24f * density + .5f); }
|
||||
}
|
||||
|
||||
213
src/lihont/two/streak/AutoFlame.java
Normal file
213
src/lihont/two/streak/AutoFlame.java
Normal file
@@ -0,0 +1,213 @@
|
||||
package lihont.two.streak;
|
||||
|
||||
import android.app.AlarmManager;
|
||||
import android.app.PendingIntent;
|
||||
import android.content.ComponentName;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.os.Build;
|
||||
import android.os.SystemClock;
|
||||
import android.util.Log;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import lihont.two.account.CurrentAccount;
|
||||
import lihont.two.widget.StreakApi;
|
||||
|
||||
/**
|
||||
* Keeps the streaks of the chosen chats alive: once a day, from the time the user chose, it writes the chosen
|
||||
* message to every chosen chat whose flame is grey (a lit flame needs nothing, and a chat is never written to
|
||||
* twice in a day). Everything it does is for the account that is signed in now, with that account's own settings.
|
||||
*
|
||||
* It runs from an alarm at the chosen time, and also whenever TikTok comes to the screen after that time, so a
|
||||
* day the alarm could not wake the app is made up for as soon as the user opens it.
|
||||
*/
|
||||
public final class AutoFlame {
|
||||
private static final String TAG = "LIHONT";
|
||||
static final String RECEIVER = "lihont.two.streak.AutoFlameReceiver";
|
||||
private static final int ALARM_CODE = 7701;
|
||||
private static final long CATCH_UP_EVERY_MS = 60000L;
|
||||
private static final long BETWEEN_SENDS_MS = 900L;
|
||||
private static final long RETRY_MS = 15L * 60L * 1000L;
|
||||
|
||||
/** What one run did, for the screen and for the alarm. */
|
||||
public static final class Report {
|
||||
public int sent;
|
||||
public int lit;
|
||||
public int failed;
|
||||
/** No account or no chat core yet: worth another go in a few minutes. */
|
||||
public boolean retryLater;
|
||||
public String problem;
|
||||
|
||||
public String describe() {
|
||||
if (problem != null) return problem;
|
||||
StringBuilder out = new StringBuilder();
|
||||
out.append("Отправлено: ").append(sent);
|
||||
if (lit > 0) out.append(", огонёк уже горит: ").append(lit);
|
||||
if (failed > 0) out.append(", не вышло: ").append(failed);
|
||||
return out.toString();
|
||||
}
|
||||
}
|
||||
|
||||
private static long caughtUpAt;
|
||||
private static boolean running;
|
||||
|
||||
private AutoFlame() {}
|
||||
|
||||
/** Called when TikTok is on screen: puts the alarm in place and, if today's time has passed, writes the chats. */
|
||||
public static void onForeground(final Context context) {
|
||||
try {
|
||||
final Context app = application(context);
|
||||
long now = SystemClock.uptimeMillis();
|
||||
synchronized (AutoFlame.class) {
|
||||
if (running || (caughtUpAt != 0 && now - caughtUpAt < CATCH_UP_EVERY_MS)) return;
|
||||
caughtUpAt = now;
|
||||
running = true;
|
||||
}
|
||||
new Thread(new Runnable() {
|
||||
@Override public void run() {
|
||||
try {
|
||||
schedule(app);
|
||||
runDue(app, false);
|
||||
} catch (Throwable ignored) {
|
||||
// The keeper never gets in the way of TikTok.
|
||||
} finally {
|
||||
synchronized (AutoFlame.class) {
|
||||
running = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}, "lihont-streak").start();
|
||||
} catch (Throwable ignored) {
|
||||
// Decoration.
|
||||
}
|
||||
}
|
||||
|
||||
/** Writes the chosen chats now, whatever the time and whatever was sent today, only where the flame is grey. */
|
||||
public static Report sendNow(Context context) {
|
||||
return run(application(context), true);
|
||||
}
|
||||
|
||||
/** Writes the chosen chats if the keeper is on and its time has come. */
|
||||
public static Report runDue(Context context, boolean fromAlarm) {
|
||||
Report report = run(application(context), false);
|
||||
if (fromAlarm && report.retryLater) scheduleAt(application(context), System.currentTimeMillis() + RETRY_MS);
|
||||
return report;
|
||||
}
|
||||
|
||||
private static Report run(Context context, boolean force) {
|
||||
Report report = new Report();
|
||||
try {
|
||||
String me = CurrentAccount.uid();
|
||||
if (me == null) {
|
||||
report.retryLater = true;
|
||||
report.problem = "Войдите в TikTok";
|
||||
return report;
|
||||
}
|
||||
AutoFlameBook book = AutoFlameStore.load(context, me);
|
||||
TimeZone zone = TimeZone.getDefault();
|
||||
long now = System.currentTimeMillis();
|
||||
List<String> chats = force ? book.chats() : book.pending(now, zone);
|
||||
if (chats.isEmpty()) {
|
||||
if (force) report.problem = "Не выбрано ни одного чата";
|
||||
return report;
|
||||
}
|
||||
int unknown = 0;
|
||||
for (String friend : chats) {
|
||||
StreakApi.Info info = StreakApi.info(StreakApi.conversationId(me, friend));
|
||||
if (info == null) { // no streak with this person any more, or the streak module is not up yet
|
||||
unknown++;
|
||||
continue;
|
||||
}
|
||||
if (!StreakApi.cold(info.remindAt, info.endAt, now)) {
|
||||
report.lit++;
|
||||
continue;
|
||||
}
|
||||
FlameSender.Result result = FlameSender.sendText(info.conversation, book.message());
|
||||
if (result.submitted) {
|
||||
report.sent++;
|
||||
book.markSent(friend, now, zone);
|
||||
AutoFlameStore.save(context, me, book);
|
||||
Thread.sleep(BETWEEN_SENDS_MS);
|
||||
} else {
|
||||
report.failed++;
|
||||
report.retryLater = true;
|
||||
Log.i(TAG, "streak: not sent: " + result.error);
|
||||
}
|
||||
}
|
||||
if (report.sent == 0 && report.lit == 0 && report.failed == 0 && unknown > 0) report.retryLater = true;
|
||||
} catch (Throwable failure) {
|
||||
report.problem = "Сбой: " + failure.getClass().getSimpleName();
|
||||
Log.i(TAG, "streak: run failed " + failure);
|
||||
}
|
||||
return report;
|
||||
}
|
||||
|
||||
/** Puts the alarm of the signed-in account's chosen time in place (or takes it away when the keeper is off). */
|
||||
public static void schedule(Context context) {
|
||||
Context app = application(context);
|
||||
String me = CurrentAccount.uid();
|
||||
AutoFlameBook book = me == null ? null : AutoFlameStore.load(app, me);
|
||||
if (book == null || !book.enabled() || book.chats().isEmpty()) {
|
||||
cancel(app);
|
||||
return;
|
||||
}
|
||||
scheduleAt(app, book.nextTrigger(System.currentTimeMillis(), TimeZone.getDefault()));
|
||||
}
|
||||
|
||||
/** What the screen says about the next write, from the settings of the signed-in account. */
|
||||
public static List<String> nextLines(Context context) {
|
||||
List<String> out = new ArrayList<String>();
|
||||
String me = CurrentAccount.uid();
|
||||
if (me == null) {
|
||||
out.add("Войдите в TikTok");
|
||||
return out;
|
||||
}
|
||||
AutoFlameBook book = AutoFlameStore.load(application(context), me);
|
||||
if (!book.enabled()) {
|
||||
out.add("Выключено");
|
||||
} else if (book.chats().isEmpty()) {
|
||||
out.add("Выберите чаты");
|
||||
} else {
|
||||
long next = book.nextTrigger(System.currentTimeMillis(), TimeZone.getDefault());
|
||||
out.add("Дальше: " + new java.text.SimpleDateFormat("d MMM, HH:mm", new java.util.Locale("ru")).format(
|
||||
new java.util.Date(next)));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private static void scheduleAt(Context context, long triggerAt) {
|
||||
try {
|
||||
AlarmManager alarms = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
|
||||
if (alarms == null) return;
|
||||
PendingIntent intent = alarmIntent(context);
|
||||
// A few minutes either way do not matter for a daily message, so no permission for exact alarms is asked.
|
||||
if (Build.VERSION.SDK_INT >= 23) alarms.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, triggerAt, intent);
|
||||
else alarms.set(AlarmManager.RTC_WAKEUP, triggerAt, intent);
|
||||
} catch (Throwable ignored) {
|
||||
// No alarm: the catch-up when TikTok opens still does the work.
|
||||
}
|
||||
}
|
||||
|
||||
private static void cancel(Context context) {
|
||||
try {
|
||||
AlarmManager alarms = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
|
||||
if (alarms != null) alarms.cancel(alarmIntent(context));
|
||||
} catch (Throwable ignored) {
|
||||
// Nothing to take away.
|
||||
}
|
||||
}
|
||||
|
||||
private static PendingIntent alarmIntent(Context context) {
|
||||
Intent intent = new Intent().setComponent(new ComponentName(context.getPackageName(), RECEIVER));
|
||||
return PendingIntent.getBroadcast(context, ALARM_CODE, intent,
|
||||
PendingIntent.FLAG_UPDATE_CURRENT | (Build.VERSION.SDK_INT >= 23 ? PendingIntent.FLAG_IMMUTABLE : 0));
|
||||
}
|
||||
|
||||
private static Context application(Context context) {
|
||||
Context app = context.getApplicationContext();
|
||||
return app != null ? app : context;
|
||||
}
|
||||
}
|
||||
203
src/lihont/two/streak/AutoFlameBook.java
Normal file
203
src/lihont/two/streak/AutoFlameBook.java
Normal file
@@ -0,0 +1,203 @@
|
||||
package lihont.two.streak;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.net.URLDecoder;
|
||||
import java.net.URLEncoder;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Calendar;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.TimeZone;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* The settings of one account's automatic streak keeper, and what it has already sent: whether it is on, the time
|
||||
* of day, the message, the chats it may write to, and the day each chat was last written to.
|
||||
*
|
||||
* Plain Java (no Android), so it can be tested on a desktop JVM. Times are always worked out in the zone the
|
||||
* caller passes in, so a day means the user's own day, also across a change of the clock.
|
||||
*/
|
||||
public final class AutoFlameBook {
|
||||
public static final int DEFAULT_MINUTE = 12 * 60;
|
||||
/** The flame emoji. */
|
||||
public static final String DEFAULT_MESSAGE = "🔥";
|
||||
/** The most chats the keeper writes to; every message is a real one, so the list stays short on purpose. */
|
||||
public static final int MAX_CHATS = 20;
|
||||
public static final int MAX_MESSAGE = 40;
|
||||
private static final long DAY_MS = 24L * 60L * 60L * 1000L;
|
||||
private static final Pattern UID = Pattern.compile("[0-9]{1,20}");
|
||||
|
||||
private boolean enabled;
|
||||
private int minute = DEFAULT_MINUTE;
|
||||
private String message = DEFAULT_MESSAGE;
|
||||
private final LinkedHashSet<String> chats = new LinkedHashSet<String>();
|
||||
private final Map<String, Long> sentOn = new HashMap<String, Long>();
|
||||
|
||||
public boolean enabled() { return enabled; }
|
||||
|
||||
public void setEnabled(boolean value) { enabled = value; }
|
||||
|
||||
/** Minutes after midnight. */
|
||||
public int minute() { return minute; }
|
||||
|
||||
public void setMinute(int value) {
|
||||
if (value < 0 || value >= 24 * 60) throw new IllegalArgumentException("Not a time of day");
|
||||
minute = value;
|
||||
}
|
||||
|
||||
public String message() { return message; }
|
||||
|
||||
/** A message is one line of up to MAX_MESSAGE characters, with no control characters. */
|
||||
public static boolean validMessage(String value) {
|
||||
if (value == null) return false;
|
||||
String text = value.trim();
|
||||
if (text.isEmpty() || text.length() > MAX_MESSAGE) return false;
|
||||
for (int i = 0; i < text.length(); i++) {
|
||||
if (Character.isISOControl(text.charAt(i))) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public void setMessage(String value) {
|
||||
if (!validMessage(value)) throw new IllegalArgumentException("Not a usable message");
|
||||
message = value.trim();
|
||||
}
|
||||
|
||||
public static boolean validUid(String uid) {
|
||||
return uid != null && UID.matcher(uid).matches();
|
||||
}
|
||||
|
||||
public List<String> chats() { return new ArrayList<String>(chats); }
|
||||
|
||||
public boolean hasChat(String uid) { return chats.contains(uid); }
|
||||
|
||||
/** Adds or removes a chat. False when the list is full (or the id is not an id) and nothing changed. */
|
||||
public boolean setChat(String uid, boolean on) {
|
||||
if (!validUid(uid)) return false;
|
||||
if (!on) {
|
||||
chats.remove(uid);
|
||||
return true;
|
||||
}
|
||||
if (!chats.contains(uid) && chats.size() >= MAX_CHATS) return false;
|
||||
chats.add(uid);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** The user's own day number of this moment (days since 1970 in the zone). */
|
||||
public static long dayOf(long nowMillis, TimeZone zone) {
|
||||
return floorDiv(nowMillis + zone.getOffset(nowMillis), DAY_MS);
|
||||
}
|
||||
|
||||
/** Minutes after midnight in the zone at this moment. */
|
||||
public static int minuteOf(long nowMillis, TimeZone zone) {
|
||||
long local = floorMod(nowMillis + zone.getOffset(nowMillis), DAY_MS);
|
||||
return (int) (local / 60000L);
|
||||
}
|
||||
|
||||
/** The next moment the chosen time of day comes round, today if it has not yet, else tomorrow. */
|
||||
public long nextTrigger(long nowMillis, TimeZone zone) {
|
||||
Calendar calendar = Calendar.getInstance(zone);
|
||||
calendar.setTimeInMillis(nowMillis);
|
||||
calendar.set(Calendar.HOUR_OF_DAY, minute / 60);
|
||||
calendar.set(Calendar.MINUTE, minute % 60);
|
||||
calendar.set(Calendar.SECOND, 0);
|
||||
calendar.set(Calendar.MILLISECOND, 0);
|
||||
if (calendar.getTimeInMillis() <= nowMillis) calendar.add(Calendar.DAY_OF_MONTH, 1);
|
||||
return calendar.getTimeInMillis();
|
||||
}
|
||||
|
||||
/** Whether the keeper is on and today's time has come (it stays due for the rest of the day, so a late start catches up). */
|
||||
public boolean due(long nowMillis, TimeZone zone) {
|
||||
return enabled && minuteOf(nowMillis, zone) >= minute;
|
||||
}
|
||||
|
||||
/** The chosen chats nothing was sent to today, in the order they were chosen. Empty while not due. */
|
||||
public List<String> pending(long nowMillis, TimeZone zone) {
|
||||
List<String> out = new ArrayList<String>();
|
||||
if (!due(nowMillis, zone)) return out;
|
||||
long today = dayOf(nowMillis, zone);
|
||||
for (String uid : chats) {
|
||||
Long last = sentOn.get(uid);
|
||||
if (last == null || last.longValue() < today) out.add(uid);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Remembers that the chat was written to at this moment, so it is left alone for the rest of the day. */
|
||||
public void markSent(String uid, long nowMillis, TimeZone zone) {
|
||||
if (!validUid(uid)) throw new IllegalArgumentException("Not an account id");
|
||||
sentOn.put(uid, Long.valueOf(dayOf(nowMillis, zone)));
|
||||
}
|
||||
|
||||
public String encode() {
|
||||
StringBuilder out = new StringBuilder();
|
||||
out.append("enabled=").append(enabled ? 1 : 0).append('\n');
|
||||
out.append("minute=").append(minute).append('\n');
|
||||
out.append("message=").append(escape(message)).append('\n');
|
||||
for (String uid : chats) out.append("chat=").append(uid).append('\n');
|
||||
for (Map.Entry<String, Long> entry : sentOn.entrySet()) {
|
||||
out.append("sent=").append(entry.getKey()).append(':').append(entry.getValue()).append('\n');
|
||||
}
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
/** Reads the text form; a line that makes no sense is skipped, so a damaged file loses only that line. */
|
||||
public static AutoFlameBook decode(String text) {
|
||||
AutoFlameBook book = new AutoFlameBook();
|
||||
if (text == null) return book;
|
||||
for (String line : text.split("\n")) {
|
||||
int equals = line.indexOf('=');
|
||||
if (equals <= 0) continue;
|
||||
String key = line.substring(0, equals);
|
||||
String value = line.substring(equals + 1);
|
||||
try {
|
||||
if (key.equals("enabled")) {
|
||||
book.enabled = value.equals("1");
|
||||
} else if (key.equals("minute")) {
|
||||
book.setMinute(Integer.parseInt(value));
|
||||
} else if (key.equals("message")) {
|
||||
String unescaped = unescape(value);
|
||||
if (validMessage(unescaped)) book.message = unescaped.trim();
|
||||
} else if (key.equals("chat")) {
|
||||
book.setChat(value, true);
|
||||
} else if (key.equals("sent")) {
|
||||
int colon = value.indexOf(':');
|
||||
if (colon > 0 && validUid(value.substring(0, colon))) {
|
||||
book.sentOn.put(value.substring(0, colon), Long.valueOf(Long.parseLong(value.substring(colon + 1))));
|
||||
}
|
||||
}
|
||||
} catch (IllegalArgumentException damagedLine) {
|
||||
// skipped: that setting keeps its default
|
||||
}
|
||||
}
|
||||
return book;
|
||||
}
|
||||
|
||||
// Math.floorDiv and floorMod only exist from Android 7; this is the same arithmetic.
|
||||
private static long floorDiv(long a, long b) {
|
||||
long q = a / b;
|
||||
return (a % b != 0 && ((a < 0) != (b < 0))) ? q - 1 : q;
|
||||
}
|
||||
|
||||
private static long floorMod(long a, long b) {
|
||||
return a - floorDiv(a, b) * b;
|
||||
}
|
||||
|
||||
private static String escape(String value) {
|
||||
try {
|
||||
return URLEncoder.encode(value, "UTF-8");
|
||||
} catch (UnsupportedEncodingException never) {
|
||||
throw new IllegalStateException(never);
|
||||
}
|
||||
}
|
||||
|
||||
private static String unescape(String value) {
|
||||
try {
|
||||
return URLDecoder.decode(value, "UTF-8");
|
||||
} catch (UnsupportedEncodingException never) {
|
||||
throw new IllegalStateException(never);
|
||||
}
|
||||
}
|
||||
}
|
||||
28
src/lihont/two/streak/AutoFlameReceiver.java
Normal file
28
src/lihont/two/streak/AutoFlameReceiver.java
Normal file
@@ -0,0 +1,28 @@
|
||||
package lihont.two.streak;
|
||||
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
|
||||
/** The alarm of the streak keeper: writes the chats that are due, then sets the next alarm. */
|
||||
public final class AutoFlameReceiver extends BroadcastReceiver {
|
||||
@Override public void onReceive(final Context context, Intent intent) {
|
||||
final PendingResult pending = goAsync();
|
||||
new Thread(new Runnable() {
|
||||
@Override public void run() {
|
||||
try {
|
||||
AutoFlame.runDue(context, true);
|
||||
} catch (Throwable ignored) {
|
||||
// Whatever went wrong, the next alarm is still set below.
|
||||
} finally {
|
||||
try {
|
||||
AutoFlame.schedule(context);
|
||||
} catch (Throwable ignored) {
|
||||
// The catch-up when TikTok opens remains.
|
||||
}
|
||||
pending.finish();
|
||||
}
|
||||
}
|
||||
}, "lihont-streak-alarm").start();
|
||||
}
|
||||
}
|
||||
26
src/lihont/two/streak/AutoFlameStore.java
Normal file
26
src/lihont/two/streak/AutoFlameStore.java
Normal file
@@ -0,0 +1,26 @@
|
||||
package lihont.two.streak;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
|
||||
/** The streak keeper's settings of every account on the phone, each in its own entry of one private file. */
|
||||
public final class AutoFlameStore {
|
||||
private static final String FILE = "lihont_auto_flame";
|
||||
|
||||
private AutoFlameStore() {}
|
||||
|
||||
private static SharedPreferences prefs(Context context) {
|
||||
return context.getSharedPreferences(FILE, Context.MODE_PRIVATE);
|
||||
}
|
||||
|
||||
/** The settings of this account; a new account (or a damaged entry) starts from the defaults, which is "off". */
|
||||
public static AutoFlameBook load(Context context, String accountUid) {
|
||||
if (!AutoFlameBook.validUid(accountUid)) return new AutoFlameBook();
|
||||
return AutoFlameBook.decode(prefs(context).getString("book." + accountUid, null));
|
||||
}
|
||||
|
||||
public static void save(Context context, String accountUid, AutoFlameBook book) {
|
||||
if (!AutoFlameBook.validUid(accountUid)) return;
|
||||
prefs(context).edit().putString("book." + accountUid, book.encode()).apply();
|
||||
}
|
||||
}
|
||||
138
src/lihont/two/streak/FlameSender.java
Normal file
138
src/lihont/two/streak/FlameSender.java
Normal file
@@ -0,0 +1,138 @@
|
||||
package lihont.two.streak;
|
||||
|
||||
import android.util.Log;
|
||||
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.lang.reflect.InvocationHandler;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Proxy;
|
||||
|
||||
/**
|
||||
* Sends one text message into a direct chat the way TikTok's own chat does, through the instant messaging core it
|
||||
* keeps for itself (TikTok 47.1.3; the names are the ones its build has, found by reading how the chat sends).
|
||||
*
|
||||
* The chain is: a conversation id, the message content (a TextContent, whose type number and JSON the core
|
||||
* itself works out), the parameters object those go into, and the sender of the core's "social" channel. Every
|
||||
* step is looked up by name when it is first needed and any failure comes back as a sentence, never a crash, so a
|
||||
* TikTok update that renames something costs the feature and nothing else. The text of a message is never written
|
||||
* to the log.
|
||||
*/
|
||||
public final class FlameSender {
|
||||
private static final String TAG = "LIHONT";
|
||||
|
||||
/** What came of one send: it is only known to have been handed over, the core delivers it afterwards. */
|
||||
public static final class Result {
|
||||
public final boolean submitted;
|
||||
public final String error;
|
||||
|
||||
Result(boolean submitted, String error) {
|
||||
this.submitted = submitted;
|
||||
this.error = error;
|
||||
}
|
||||
}
|
||||
|
||||
private static final String SERVICE_HOLDER = "X.0Uiz"; // static LIZ(): the core's proxy service
|
||||
private static final String CHANNEL = "X.0qkC"; // enum, value TIKTOK_SOCIAL_IM
|
||||
private static final String CHANNEL_VALUE = "TIKTOK_SOCIAL_IM";
|
||||
private static final String SERVICE = "com.bytedance.ies.im.core.api.proxy.IIMCoreProxyService";
|
||||
private static final String TEXT_CONTENT = "com.ss.android.ugc.aweme.im.message.content.TextContent";
|
||||
private static final String CONTENT_BASE = "X.0UVO"; // the base of every message content
|
||||
private static final String TYPE_OF = "X.0Un7"; // static LIZ(content): the message type number
|
||||
private static final String JSON_OF = "X.1D0u"; // static LJ(object, boolean): the JSON text
|
||||
private static final String CONVERSATION = "X.04my"; // (String id), a conversation reference
|
||||
private static final String CONVERSATION_BASE = "X.04mz";
|
||||
private static final String PAYLOAD = "X.0Tus"; // (String json), the content as sent
|
||||
private static final String PAYLOAD_BASE = "X.0Tuu";
|
||||
private static final String CORE = "X.13uU"; // the core of one channel: LJFF() is its sender
|
||||
private static final String SENDER = "X.13bW"; // the sender: (params, options, listener)
|
||||
private static final String PARAMS = "X.13k5"; // the 13 arguments of a send
|
||||
private static final String OPTIONS = "X.0Unf"; // (boolean, order, defaults mask)
|
||||
private static final String OPTIONS_ORDER = "X.0Unh";
|
||||
private static final String LISTENER = "X.0q1P"; // onEvent(event)
|
||||
/** The send parameters that follow the first three take their defaults (empty text, no maps, no references). */
|
||||
private static final int PARAMS_DEFAULTS = 0xFF8;
|
||||
private static final int OPTIONS_DEFAULTS = 3;
|
||||
|
||||
private FlameSender() {}
|
||||
|
||||
/** Hands one text message over to the chat core; never throws. */
|
||||
public static Result sendText(String conversationId, String text) {
|
||||
try {
|
||||
if (conversationId == null || conversationId.length() == 0 || text == null || text.length() == 0) {
|
||||
return new Result(false, "Нет чата или текста");
|
||||
}
|
||||
Class<?> baseContent = Class.forName(CONTENT_BASE);
|
||||
Object content = Class.forName(TEXT_CONTENT).getMethod("obtain", String.class).invoke(null, text);
|
||||
int type = ((Number) Class.forName(TYPE_OF).getMethod("LIZ", baseContent).invoke(null, content)).intValue();
|
||||
String json = (String) Class.forName(JSON_OF).getMethod("LJ", Object.class, boolean.class)
|
||||
.invoke(null, content, Boolean.FALSE);
|
||||
if (json == null || json.length() == 0) return new Result(false, "Не удалось собрать сообщение");
|
||||
|
||||
Object conversation = Class.forName(CONVERSATION).getConstructor(String.class).newInstance(conversationId);
|
||||
Object payload = Class.forName(PAYLOAD).getConstructor(String.class).newInstance(json);
|
||||
Object params = newParams(conversation, type, payload);
|
||||
|
||||
Object service = Class.forName(SERVICE_HOLDER).getMethod("LIZ").invoke(null);
|
||||
if (service == null) return new Result(false, "Чаты TikTok ещё не готовы");
|
||||
Class<?> channelClass = Class.forName(CHANNEL);
|
||||
Object channel = null;
|
||||
for (Object value : channelClass.getEnumConstants()) {
|
||||
if (CHANNEL_VALUE.equals(((Enum<?>) value).name())) channel = value;
|
||||
}
|
||||
if (channel == null) return new Result(false, "Канал чатов TikTok не найден");
|
||||
Object core = Class.forName(SERVICE).getMethod("LIZJ", channelClass).invoke(service, channel);
|
||||
if (core == null) return new Result(false, "Чаты TikTok ещё не готовы");
|
||||
Object sender = Class.forName(CORE).getMethod("LJFF").invoke(core);
|
||||
if (sender == null) return new Result(false, "Чаты TikTok ещё не готовы");
|
||||
|
||||
Class<?> optionsClass = Class.forName(OPTIONS);
|
||||
Object options = optionsClass.getConstructor(boolean.class, Class.forName(OPTIONS_ORDER), int.class)
|
||||
.newInstance(Boolean.FALSE, null, Integer.valueOf(OPTIONS_DEFAULTS));
|
||||
Object listener = listener();
|
||||
Method send = findSend(Class.forName(SENDER), params.getClass(), optionsClass, Class.forName(LISTENER));
|
||||
send.invoke(sender, params, options, listener);
|
||||
Log.i(TAG, "streak: message handed to the chat core, type " + type);
|
||||
return new Result(true, null);
|
||||
} catch (Throwable failure) {
|
||||
Throwable cause = failure.getCause() != null ? failure.getCause() : failure;
|
||||
Log.i(TAG, "streak: send failed " + cause);
|
||||
return new Result(false, "Не получилось отправить: " + cause.getClass().getSimpleName());
|
||||
}
|
||||
}
|
||||
|
||||
private static Object newParams(Object conversation, int type, Object payload) throws Exception {
|
||||
Class<?> params = Class.forName(PARAMS);
|
||||
Constructor<?> constructor = params.getConstructor(Class.forName(CONVERSATION_BASE), int.class,
|
||||
Class.forName(PAYLOAD_BASE), String.class, String.class, java.util.Map.class, java.util.Map.class,
|
||||
Class.forName("okio.ByteString"), Class.forName("okio.ByteString"), android.util.SparseArray.class,
|
||||
java.util.List.class, Class.forName("com.bytedance.im.core.proto.ReferenceInfo"), int.class);
|
||||
return constructor.newInstance(conversation, Integer.valueOf(type), payload, null, null, null, null, null,
|
||||
null, null, null, null, Integer.valueOf(PARAMS_DEFAULTS));
|
||||
}
|
||||
|
||||
/** The core's sender method that takes the parameters, the options and a listener (its name is obfuscated). */
|
||||
private static Method findSend(Class<?> sender, Class<?> params, Class<?> options, Class<?> listener)
|
||||
throws NoSuchMethodException {
|
||||
for (Method method : sender.getMethods()) {
|
||||
Class<?>[] types = method.getParameterTypes();
|
||||
if (types.length == 3 && types[0].isAssignableFrom(params) && types[1].isAssignableFrom(options)
|
||||
&& types[2].isAssignableFrom(listener)) {
|
||||
return method;
|
||||
}
|
||||
}
|
||||
throw new NoSuchMethodException("the send method of the chat core");
|
||||
}
|
||||
|
||||
/** A listener that only notes what kind of event came back, never what the message said. */
|
||||
private static Object listener() throws ClassNotFoundException {
|
||||
Class<?> type = Class.forName(LISTENER);
|
||||
return Proxy.newProxyInstance(type.getClassLoader(), new Class<?>[] {type}, new InvocationHandler() {
|
||||
@Override public Object invoke(Object proxy, Method method, Object[] args) {
|
||||
if ("onEvent".equals(method.getName()) && args != null && args.length == 1 && args[0] != null) {
|
||||
Log.i(TAG, "streak: chat core event " + args[0].getClass().getName());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
17
src/lihont/two/widget/AppContext.java
Normal file
17
src/lihont/two/widget/AppContext.java
Normal file
@@ -0,0 +1,17 @@
|
||||
package lihont.two.widget;
|
||||
|
||||
import android.content.Context;
|
||||
|
||||
/** The running application, for code that is called from TikTok's own hooks and has no context of its own. */
|
||||
public final class AppContext {
|
||||
private AppContext() {}
|
||||
|
||||
public static Context get() {
|
||||
try {
|
||||
Object app = Class.forName("android.app.ActivityThread").getMethod("currentApplication").invoke(null);
|
||||
return app instanceof Context ? (Context) app : null;
|
||||
} catch (Throwable unavailable) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
169
src/lihont/two/widget/Contacts.java
Normal file
169
src/lihont/two/widget/Contacts.java
Normal file
@@ -0,0 +1,169 @@
|
||||
package lihont.two.widget;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
import android.os.SystemClock;
|
||||
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import lihont.two.account.CurrentAccount;
|
||||
|
||||
/**
|
||||
* The people TikTok has shown names of, kept in a small private file, so that the widget's chat picker has
|
||||
* somebody to ask about without the inbox being open. Fed by the user models passing through the name
|
||||
* getters (see lihont.two.badge.AccountNames); only the public id and the public nickname are kept.
|
||||
*
|
||||
* Every account of the phone has its own list: a name is filed under the account that was signed in when
|
||||
* TikTok showed it, so the picker of one account does not offer the friends of another. Names seen before
|
||||
* lists were per account (or while no account could be told) sit in a shared list that every account sees.
|
||||
*/
|
||||
public final class Contacts {
|
||||
private static final String FILE = "lihont_streak_contacts";
|
||||
/** The key of the shared list; the list of an account is "names." and its id. */
|
||||
private static final String SHARED_KEY = "names";
|
||||
private static final String ACCOUNT_KEY = "names.";
|
||||
private static final String SHARED = "";
|
||||
private static final int LIMIT = 600;
|
||||
private static final int MAX_ACCOUNTS = 12;
|
||||
private static final long SAVE_EVERY_MS = 20000L;
|
||||
|
||||
/** Account id (or "" for the shared list) to the people seen under it, most recently seen last. */
|
||||
private static final Map<String, LinkedHashMap<String, String>> LISTS =
|
||||
new HashMap<String, LinkedHashMap<String, String>>();
|
||||
private static boolean loaded;
|
||||
private static boolean dirty;
|
||||
private static long savedAt;
|
||||
|
||||
private Contacts() {}
|
||||
|
||||
/** Called with a user model, its account id and the name that was just read from it; never throws. */
|
||||
public static void learn(Object user, String uid, String name) {
|
||||
try {
|
||||
String nickname = field(user, "nickname");
|
||||
String shown = nickname != null && nickname.length() > 0 ? nickname : name;
|
||||
if (shown == null || shown.length() == 0) return;
|
||||
Context context = AppContext.get();
|
||||
String owner = CurrentAccount.uid();
|
||||
synchronized (LISTS) {
|
||||
load(context);
|
||||
LinkedHashMap<String, String> list = list(owner == null ? SHARED : owner);
|
||||
if (list == null) return;
|
||||
String known = list.get(uid);
|
||||
if (shown.equals(known)) return;
|
||||
list.remove(uid);
|
||||
list.put(uid, shown);
|
||||
while (list.size() > LIMIT) {
|
||||
Iterator<String> oldest = list.keySet().iterator();
|
||||
oldest.next();
|
||||
oldest.remove();
|
||||
}
|
||||
dirty = true;
|
||||
save(context, false);
|
||||
}
|
||||
} catch (Throwable ignored) {
|
||||
// A name that is not remembered only means one less choice in the picker.
|
||||
}
|
||||
}
|
||||
|
||||
/** Everybody this account has seen, then the shared list; most recently seen last within each. */
|
||||
public static Map<String, String> all(Context context, String owner) {
|
||||
synchronized (LISTS) {
|
||||
load(context);
|
||||
save(context, true);
|
||||
LinkedHashMap<String, String> merged = new LinkedHashMap<String, String>();
|
||||
LinkedHashMap<String, String> shared = LISTS.get(SHARED);
|
||||
if (shared != null) merged.putAll(shared);
|
||||
LinkedHashMap<String, String> own = owner == null ? null : LISTS.get(owner);
|
||||
if (own != null) merged.putAll(own);
|
||||
return merged;
|
||||
}
|
||||
}
|
||||
|
||||
/** The list of one account, made when it is the first time; null when too many accounts are kept already. */
|
||||
private static LinkedHashMap<String, String> list(String owner) {
|
||||
LinkedHashMap<String, String> list = LISTS.get(owner);
|
||||
if (list == null) {
|
||||
if (LISTS.size() >= MAX_ACCOUNTS) return null;
|
||||
list = new LinkedHashMap<String, String>();
|
||||
LISTS.put(owner, list);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
private static String field(Object user, String name) {
|
||||
try {
|
||||
Field field = user.getClass().getDeclaredField(name);
|
||||
field.setAccessible(true);
|
||||
Object value = field.get(user);
|
||||
return value instanceof String ? (String) value : null;
|
||||
} catch (Throwable absent) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static void load(Context context) {
|
||||
if (loaded || context == null) return;
|
||||
loaded = true;
|
||||
try {
|
||||
SharedPreferences prefs = prefs(context);
|
||||
for (Map.Entry<String, ?> entry : prefs.getAll().entrySet()) {
|
||||
String key = entry.getKey();
|
||||
String owner;
|
||||
if (key.equals(SHARED_KEY)) {
|
||||
owner = SHARED;
|
||||
} else if (key.startsWith(ACCOUNT_KEY) && key.length() > ACCOUNT_KEY.length()) {
|
||||
owner = key.substring(ACCOUNT_KEY.length());
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
if (!(entry.getValue() instanceof String)) continue;
|
||||
try {
|
||||
JSONObject json = new JSONObject((String) entry.getValue());
|
||||
LinkedHashMap<String, String> list = list(owner);
|
||||
if (list == null) continue;
|
||||
Iterator<String> keys = json.keys();
|
||||
while (keys.hasNext()) {
|
||||
String uid = keys.next();
|
||||
if (!list.containsKey(uid)) list.put(uid, json.getString(uid));
|
||||
}
|
||||
} catch (Exception damaged) {
|
||||
// One damaged list is replaced by what is learned from now on; the others stay.
|
||||
}
|
||||
}
|
||||
} catch (Exception unreadable) {
|
||||
// Nothing known yet.
|
||||
}
|
||||
}
|
||||
|
||||
private static void save(Context context, boolean force) {
|
||||
if (!dirty || context == null) return;
|
||||
long now = SystemClock.uptimeMillis();
|
||||
if (!force && now - savedAt < SAVE_EVERY_MS) return;
|
||||
try {
|
||||
SharedPreferences.Editor editor = prefs(context).edit();
|
||||
for (Map.Entry<String, LinkedHashMap<String, String>> list : LISTS.entrySet()) {
|
||||
JSONObject json = new JSONObject();
|
||||
for (Map.Entry<String, String> entry : list.getValue().entrySet()) {
|
||||
json.put(entry.getKey(), entry.getValue());
|
||||
}
|
||||
String key = list.getKey().equals(SHARED) ? SHARED_KEY : ACCOUNT_KEY + list.getKey();
|
||||
editor.putString(key, json.toString());
|
||||
}
|
||||
editor.apply();
|
||||
dirty = false;
|
||||
savedAt = now;
|
||||
} catch (Exception ignored) {
|
||||
// Kept in memory; tried again next time.
|
||||
}
|
||||
}
|
||||
|
||||
private static SharedPreferences prefs(Context context) {
|
||||
return context.getSharedPreferences(FILE, Context.MODE_PRIVATE);
|
||||
}
|
||||
}
|
||||
209
src/lihont/two/widget/FlowerArt.java
Normal file
209
src/lihont/two/widget/FlowerArt.java
Normal file
@@ -0,0 +1,209 @@
|
||||
package lihont.two.widget;
|
||||
|
||||
import android.graphics.Bitmap;
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.Paint;
|
||||
import android.graphics.Path;
|
||||
import android.graphics.Typeface;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* What the streak widget shows: a Material 3 flower in the accent's container colour, with a flame, the
|
||||
* number of days of the streak and a short name of the chat inside. The whole widget is one bitmap, so the
|
||||
* look never depends on the layout of TikTok's own widget it rides in.
|
||||
*
|
||||
* The flame is orange while the streak burns and grey when it is not lit (TikTok's own grey flame: the day's
|
||||
* message is still to be sent). A burning flame comes in FRAMES slightly different pictures, which the widget's
|
||||
* layout flips through by itself; a grey one is the same picture in every frame.
|
||||
*/
|
||||
final class FlowerArt {
|
||||
/** The picture is composed on a grid of this side and scaled to the widget. */
|
||||
static final int SIDE = 360;
|
||||
/** How many pictures a burning flame takes to sway once. */
|
||||
static final int FRAMES = 4;
|
||||
private static final int PETALS = 8;
|
||||
private static final int MAX_NAME = 12;
|
||||
|
||||
private static final int FLAME = 0xFFFF7A00;
|
||||
private static final int FLAME_HEART = 0xFFFFC53D;
|
||||
private static final int COLD = 0xFF8E9399;
|
||||
private static final int COLD_HEART = 0xFFC7CBD0;
|
||||
/** Below this distance in colour the flame would melt into the flower, so it gets a thin outline. */
|
||||
private static final int MIN_CONTRAST = 110;
|
||||
/** Per frame: the flame's height factor and how far its tip leans (both around its base). */
|
||||
private static final float[][] SWAY = {{1.00f, 0f}, {1.06f, 0.07f}, {0.97f, 0f}, {1.04f, -0.07f}};
|
||||
/** Per frame: the factor of the lighter heart of the flame. */
|
||||
private static final float[] HEART = {1.00f, 1.10f, 0.92f, 1.06f};
|
||||
|
||||
private FlowerArt() {}
|
||||
|
||||
/** The colours the picture is drawn with. */
|
||||
static final class Colors {
|
||||
final int flower;
|
||||
final int ink;
|
||||
final int dimInk;
|
||||
|
||||
Colors(int flower, int ink, int dimInk) {
|
||||
this.flower = flower;
|
||||
this.ink = ink;
|
||||
this.dimInk = dimInk;
|
||||
}
|
||||
}
|
||||
|
||||
/** One picture for a widget that does not move (no chat chosen, or the flame is grey) or the sway of a lit one. */
|
||||
static Bitmap[] frames(Colors colors, int days, boolean fading, String name, int side, boolean compact) {
|
||||
Bitmap[] out = new Bitmap[FRAMES];
|
||||
if (days < 0 || fading) {
|
||||
Arrays.fill(out, render(colors, days, fading, name, side, compact, 0));
|
||||
return out;
|
||||
}
|
||||
for (int i = 0; i < FRAMES; i++) out[i] = render(colors, days, false, name, side, compact, i);
|
||||
return out;
|
||||
}
|
||||
|
||||
static Bitmap render(Colors colors, int days, boolean fading, String name, int side, boolean compact) {
|
||||
return render(colors, days, fading, name, side, compact, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param days the streak, or a negative number for "no chat chosen yet" (a plus is drawn instead)
|
||||
* @param fading whether the flame is not lit: it is drawn grey, as it is in TikTok
|
||||
* @param side the side of the bitmap in pixels
|
||||
* @param compact a one-cell widget: the flame and the number only, the number a little larger
|
||||
* @param phase which of the FRAMES pictures of the swaying flame to draw
|
||||
*/
|
||||
static Bitmap render(Colors colors, int days, boolean fading, String name, int side, boolean compact,
|
||||
int phase) {
|
||||
Bitmap bitmap = Bitmap.createBitmap(side, side, Bitmap.Config.ARGB_8888);
|
||||
Canvas canvas = new Canvas(bitmap);
|
||||
canvas.scale(side / (float) SIDE, side / (float) SIDE);
|
||||
Paint fill = new Paint(Paint.ANTI_ALIAS_FLAG);
|
||||
fill.setColor(colors.flower);
|
||||
canvas.drawPath(flower(SIDE), fill);
|
||||
|
||||
float middle = SIDE / 2f;
|
||||
if (days < 0) {
|
||||
Paint ink = new Paint(Paint.ANTI_ALIAS_FLAG);
|
||||
ink.setColor(colors.dimInk);
|
||||
drawPlus(canvas, ink, middle, compact ? middle : middle * 0.95f, SIDE * (compact ? 0.22f : 0.2f));
|
||||
if (!compact) drawText(canvas, "Выбрать чат", colors.ink, SIDE * 0.085f, middle, SIDE * 0.80f, false);
|
||||
return bitmap;
|
||||
}
|
||||
drawFlame(canvas, colors, fading, middle, compact, phase);
|
||||
|
||||
String number = Integer.toString(days);
|
||||
float size = number.length() >= 4 ? SIDE * 0.25f : SIDE * 0.32f;
|
||||
if (compact) size *= number.length() >= 3 ? 1.05f : 1.2f;
|
||||
drawText(canvas, number, colors.ink, size, middle, SIDE * (compact ? 0.80f : 0.735f), true);
|
||||
if (!compact && name != null && name.length() > 0) {
|
||||
String shown = name.length() > MAX_NAME ? name.substring(0, MAX_NAME - 1) + "…" : name;
|
||||
drawText(canvas, shown, colors.ink, SIDE * 0.085f, middle, SIDE * 0.86f, false);
|
||||
}
|
||||
return bitmap;
|
||||
}
|
||||
|
||||
private static void drawFlame(Canvas canvas, Colors colors, boolean cold, float middle, boolean compact,
|
||||
int phase) {
|
||||
int outer = cold ? COLD : FLAME;
|
||||
int heart = cold ? COLD_HEART : FLAME_HEART;
|
||||
float[] sway = SWAY[frame(phase)];
|
||||
float size = SIDE * (compact ? 0.28f : 0.30f);
|
||||
canvas.save();
|
||||
canvas.translate(middle - size / 2f, SIDE * (compact ? 0.12f : 0.10f));
|
||||
canvas.scale(size / 24f, size / 24f);
|
||||
// sway around the base of the flame (the icon's grid is 24 by 24, the base at 12 and 22.5)
|
||||
canvas.translate(12f, 22.5f);
|
||||
canvas.skew(sway[1], 0f);
|
||||
canvas.scale(1f, sway[0]);
|
||||
canvas.translate(-12f, -22.5f);
|
||||
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
|
||||
if (distance(colors.flower, outer) < MIN_CONTRAST) {
|
||||
paint.setStyle(Paint.Style.STROKE);
|
||||
paint.setStrokeWidth(1.5f);
|
||||
paint.setStrokeJoin(Paint.Join.ROUND);
|
||||
paint.setColor(colors.ink);
|
||||
canvas.drawPath(flameOuter(), paint);
|
||||
paint.setStyle(Paint.Style.FILL);
|
||||
}
|
||||
paint.setColor(outer);
|
||||
canvas.drawPath(flameOuter(), paint);
|
||||
paint.setColor(heart);
|
||||
float pulse = cold ? 1f : HEART[frame(phase)];
|
||||
canvas.translate(12f, 20.3f);
|
||||
canvas.scale(pulse, pulse);
|
||||
canvas.translate(-12f, -20.3f);
|
||||
canvas.drawPath(flameInner(), paint);
|
||||
canvas.restore();
|
||||
}
|
||||
|
||||
private static int frame(int phase) {
|
||||
return ((phase % FRAMES) + FRAMES) % FRAMES;
|
||||
}
|
||||
|
||||
/** How far apart two colours are, the largest difference of a colour channel. */
|
||||
static int distance(int a, int b) {
|
||||
int red = Math.abs(((a >> 16) & 0xFF) - ((b >> 16) & 0xFF));
|
||||
int green = Math.abs(((a >> 8) & 0xFF) - ((b >> 8) & 0xFF));
|
||||
int blue = Math.abs((a & 0xFF) - (b & 0xFF));
|
||||
return Math.max(red, Math.max(green, blue));
|
||||
}
|
||||
|
||||
private static void drawText(Canvas canvas, String text, int color, float size, float x, float baseline,
|
||||
boolean bold) {
|
||||
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
|
||||
paint.setColor(color);
|
||||
paint.setTextSize(size);
|
||||
paint.setTextAlign(Paint.Align.CENTER);
|
||||
paint.setTypeface(bold ? Typeface.create(Typeface.DEFAULT, Typeface.BOLD) : Typeface.DEFAULT);
|
||||
canvas.drawText(text, x, baseline, paint);
|
||||
}
|
||||
|
||||
private static void drawPlus(Canvas canvas, Paint paint, float x, float y, float half) {
|
||||
paint.setStrokeWidth(half * 0.38f);
|
||||
paint.setStrokeCap(Paint.Cap.ROUND);
|
||||
canvas.drawLine(x - half, y, x + half, y, paint);
|
||||
canvas.drawLine(x, y - half, x, y + half, paint);
|
||||
}
|
||||
|
||||
/** Eight petals around a round middle, filling a square of this side. */
|
||||
static Path flower(int side) {
|
||||
Path path = new Path();
|
||||
float middle = side / 2f;
|
||||
float reach = side * 0.30f;
|
||||
float petal = side * 0.20f;
|
||||
path.addCircle(middle, middle, reach, Path.Direction.CW);
|
||||
for (int i = 0; i < PETALS; i++) {
|
||||
double angle = i * 2 * Math.PI / PETALS - Math.PI / 2;
|
||||
path.addCircle(middle + (float) Math.cos(angle) * reach, middle + (float) Math.sin(angle) * reach, petal,
|
||||
Path.Direction.CW);
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
/** The flame as a 24 by 24 icon: a tongue with a notch on its left side. */
|
||||
static Path flameOuter() {
|
||||
Path path = new Path();
|
||||
path.moveTo(12f, 1.5f);
|
||||
path.cubicTo(13.2f, 6f, 19.5f, 9f, 19.5f, 15.2f);
|
||||
path.cubicTo(19.5f, 19.6f, 16.2f, 22.5f, 12f, 22.5f);
|
||||
path.cubicTo(7.8f, 22.5f, 4.5f, 19.6f, 4.5f, 15.4f);
|
||||
path.cubicTo(4.5f, 12.6f, 6f, 10.6f, 7.8f, 8.8f);
|
||||
path.cubicTo(8f, 11f, 8.9f, 12.2f, 10.2f, 12.8f);
|
||||
path.cubicTo(9.5f, 8.6f, 10.4f, 4.8f, 12f, 1.5f);
|
||||
path.close();
|
||||
return path;
|
||||
}
|
||||
|
||||
/** The lighter heart of the flame, inside it. */
|
||||
static Path flameInner() {
|
||||
Path path = new Path();
|
||||
path.moveTo(12f, 20.3f);
|
||||
path.cubicTo(9.9f, 20.3f, 8.6f, 18.9f, 8.6f, 17.2f);
|
||||
path.cubicTo(8.6f, 15.5f, 10.2f, 14.2f, 12f, 12.2f);
|
||||
path.cubicTo(13.8f, 14.2f, 15.4f, 15.5f, 15.4f, 17.2f);
|
||||
path.cubicTo(15.4f, 18.9f, 14.1f, 20.3f, 12f, 20.3f);
|
||||
path.close();
|
||||
return path;
|
||||
}
|
||||
}
|
||||
110
src/lihont/two/widget/StreakApi.java
Normal file
110
src/lihont/two/widget/StreakApi.java
Normal file
@@ -0,0 +1,110 @@
|
||||
package lihont.two.widget;
|
||||
|
||||
import android.util.Log;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
/**
|
||||
* TikTok's own streak module, reached through the service manager the way the account service is
|
||||
* (see lihont.two.bar.UserAvatar): the interface name is kept by TikTok because services are looked up
|
||||
* by class, and its data class keeps the field names of a Kotlin data class.
|
||||
*
|
||||
* A direct chat has the id "0:1:<smaller uid>:<larger uid>"; asking the module for it gives the streak
|
||||
* of that chat or nothing when there is none.
|
||||
*/
|
||||
public final class StreakApi {
|
||||
private static final String TAG = "LIHONT";
|
||||
private static final String SERVICE_MANAGER = "com.ss.android.ugc.aweme.framework.services.ServiceManager";
|
||||
private static final String STREAK_SERVICE = "com.ss.android.ugc.aweme.im.streak.api.IStreakService";
|
||||
/** IStreakService.I(String conversationId, boolean fromServerCache): the streak data of one chat. */
|
||||
private static final String DATA_METHOD = "I";
|
||||
|
||||
/** What the widget shows about a chat. */
|
||||
public static final class Info {
|
||||
public final String conversation;
|
||||
public final int streak;
|
||||
public final long endAt;
|
||||
public final long remindAt;
|
||||
|
||||
Info(String conversation, int streak, long endAt, long remindAt) {
|
||||
this.conversation = conversation;
|
||||
this.streak = streak;
|
||||
this.endAt = endAt;
|
||||
this.remindAt = remindAt;
|
||||
}
|
||||
|
||||
@Override public String toString() {
|
||||
return "streak " + streak + " end " + endAt + " remind " + remindAt;
|
||||
}
|
||||
}
|
||||
|
||||
private static Object service;
|
||||
private static Method dataMethod;
|
||||
private static final Object NONE = new Object();
|
||||
|
||||
private StreakApi() {}
|
||||
|
||||
/**
|
||||
* Whether the flame is grey, as TikTok shows it: the time of the day's reminder has passed and the streak has
|
||||
* not ended yet, so a message still has to go out today. A flame that burns needs nothing.
|
||||
*/
|
||||
public static boolean cold(long remindAt, long endAt, long nowMillis) {
|
||||
long remind = millis(remindAt);
|
||||
long end = millis(endAt);
|
||||
return remind > 0 && nowMillis >= remind && (end == 0 || nowMillis < end);
|
||||
}
|
||||
|
||||
/** The service reports seconds or milliseconds; anything below 10^11 is taken for seconds. */
|
||||
public static long millis(long value) {
|
||||
return value > 0 && value < 100000000000L ? value * 1000L : value;
|
||||
}
|
||||
|
||||
/** The id of the direct chat between two accounts. */
|
||||
public static String conversationId(String firstUid, String secondUid) {
|
||||
try {
|
||||
long a = Long.parseLong(firstUid);
|
||||
long b = Long.parseLong(secondUid);
|
||||
return "0:1:" + Math.min(a, b) + ":" + Math.max(a, b);
|
||||
} catch (NumberFormatException invalid) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** The streak of this chat, or null when there is none or the module is not reachable. Never throws. */
|
||||
public static synchronized Info info(String conversation) {
|
||||
try {
|
||||
if (conversation == null || !prepare()) return null;
|
||||
Object data = dataMethod.invoke(service, conversation, Boolean.FALSE);
|
||||
if (data == null) return null;
|
||||
int streak = ((Number) field(data, "streak")).intValue();
|
||||
if (streak <= 0) return null;
|
||||
return new Info(conversation, streak, ((Number) field(data, "endAt")).longValue(),
|
||||
((Number) field(data, "remindAt")).longValue());
|
||||
} catch (Throwable unavailable) {
|
||||
Log.i(TAG, "streak: " + unavailable);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean prepare() throws Exception {
|
||||
if (service != null && service != NONE) return true;
|
||||
if (service == NONE) return false;
|
||||
Class<?> managerClass = Class.forName(SERVICE_MANAGER);
|
||||
Object manager = managerClass.getMethod("get").invoke(null);
|
||||
Class<?> api = Class.forName(STREAK_SERVICE);
|
||||
Object found = managerClass.getMethod("getService", Class.class).invoke(manager, api);
|
||||
if (found == null) {
|
||||
service = NONE;
|
||||
return false;
|
||||
}
|
||||
dataMethod = api.getMethod(DATA_METHOD, String.class, boolean.class);
|
||||
service = found;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static Object field(Object data, String name) throws Exception {
|
||||
Field field = data.getClass().getField(name);
|
||||
return field.get(data);
|
||||
}
|
||||
}
|
||||
150
src/lihont/two/widget/StreakConfigActivity.java
Normal file
150
src/lihont/two/widget/StreakConfigActivity.java
Normal file
@@ -0,0 +1,150 @@
|
||||
package lihont.two.widget;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.appwidget.AppWidgetManager;
|
||||
import android.content.Intent;
|
||||
import android.graphics.drawable.ColorDrawable;
|
||||
import android.os.Build;
|
||||
import android.os.Bundle;
|
||||
import android.view.Gravity;
|
||||
import android.view.View;
|
||||
import android.view.Window;
|
||||
import android.widget.LinearLayout;
|
||||
import android.widget.ScrollView;
|
||||
import android.widget.TextView;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import lihont.two.badge.NicheClaim;
|
||||
import lihont.two.settings.Md3;
|
||||
import lihont.two.settings.ModSettings;
|
||||
import lihont.two.settings.SettingsHost;
|
||||
|
||||
/**
|
||||
* Opens when the streak widget is put on the home screen (and when an empty one is tapped): lists the chats
|
||||
* that have a streak and lets the user choose the one the widget follows.
|
||||
*
|
||||
* The chats are the people TikTok has shown names of (see Contacts), each asked about its streak; a person
|
||||
* without one is simply not offered. Leaving the screen without a choice removes the widget.
|
||||
*/
|
||||
public final class StreakConfigActivity extends Activity {
|
||||
private static final class Candidate {
|
||||
final String uid;
|
||||
final String name;
|
||||
final StreakApi.Info info;
|
||||
|
||||
Candidate(String uid, String name, StreakApi.Info info) {
|
||||
this.uid = uid;
|
||||
this.name = name;
|
||||
this.info = info;
|
||||
}
|
||||
}
|
||||
|
||||
private int widgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
|
||||
private Md3.Palette palette;
|
||||
private LinearLayout list;
|
||||
private TextView status;
|
||||
|
||||
@Override protected void onCreate(Bundle state) {
|
||||
super.onCreate(state);
|
||||
widgetId = getIntent().getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
|
||||
setResult(RESULT_CANCELED, new Intent().putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId));
|
||||
if (widgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
|
||||
finish();
|
||||
return;
|
||||
}
|
||||
ModSettings active = SettingsHost.active();
|
||||
palette = Md3.palette(this, active != null ? active : ModSettings.defaults());
|
||||
Window window = getWindow();
|
||||
window.setBackgroundDrawable(new ColorDrawable(palette.surface));
|
||||
window.setStatusBarColor(palette.surface);
|
||||
window.setNavigationBarColor(palette.surface);
|
||||
if (Build.VERSION.SDK_INT >= 23) {
|
||||
int flags = window.getDecorView().getSystemUiVisibility();
|
||||
window.getDecorView().setSystemUiVisibility(palette.dark ? flags & ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
|
||||
: flags | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
|
||||
}
|
||||
build();
|
||||
load();
|
||||
}
|
||||
|
||||
private void build() {
|
||||
ScrollView scroll = new ScrollView(this);
|
||||
scroll.setBackgroundColor(palette.surface);
|
||||
LinearLayout root = new LinearLayout(this);
|
||||
root.setOrientation(LinearLayout.VERTICAL);
|
||||
root.setPadding(Md3.dp(this, 16), Md3.dp(this, 56), Md3.dp(this, 16), Md3.dp(this, 24));
|
||||
root.addView(Md3.text(this, "Огонёк", Md3.HEADLINE_SMALL, false, palette.onSurface));
|
||||
status = Md3.text(this, "Ищем чаты с огоньком…", Md3.BODY_MEDIUM, false, palette.onSurfaceVariant);
|
||||
status.setPadding(0, Md3.dp(this, 8), 0, Md3.dp(this, 16));
|
||||
root.addView(status);
|
||||
list = new LinearLayout(this);
|
||||
list.setOrientation(LinearLayout.VERTICAL);
|
||||
root.addView(list);
|
||||
scroll.addView(root);
|
||||
setContentView(scroll);
|
||||
}
|
||||
|
||||
private void load() {
|
||||
final android.content.Context app = getApplicationContext();
|
||||
new Thread(new Runnable() {
|
||||
@Override public void run() {
|
||||
final List<Candidate> found = new ArrayList<Candidate>();
|
||||
final NicheClaim.Account me = NicheClaim.account();
|
||||
if (me != null) {
|
||||
for (Map.Entry<String, String> contact : Contacts.all(app, me.uid).entrySet()) {
|
||||
StreakApi.Info info = StreakApi.info(StreakApi.conversationId(me.uid, contact.getKey()));
|
||||
if (info != null) found.add(new Candidate(contact.getKey(), contact.getValue(), info));
|
||||
}
|
||||
}
|
||||
Collections.sort(found, new Comparator<Candidate>() {
|
||||
@Override public int compare(Candidate a, Candidate b) {
|
||||
return b.info.streak - a.info.streak;
|
||||
}
|
||||
});
|
||||
runOnUiThread(new Runnable() {
|
||||
@Override public void run() {
|
||||
show(found, me);
|
||||
}
|
||||
});
|
||||
}
|
||||
}, "lihont-widget-chats").start();
|
||||
}
|
||||
|
||||
private void show(List<Candidate> found, final NicheClaim.Account account) {
|
||||
if (isFinishing()) return;
|
||||
list.removeAllViews();
|
||||
if (found.isEmpty()) {
|
||||
status.setText(account != null
|
||||
? "У аккаунта @" + account.uniqueId + " чатов с огоньком пока не видно. Откройте «Входящие» в "
|
||||
+ "TikTok под этим аккаунтом, чтобы приложение увидело его чаты, и вернитесь сюда."
|
||||
: "Войдите в TikTok, чтобы выбрать чат.");
|
||||
return;
|
||||
}
|
||||
status.setText("Аккаунт @" + account.uniqueId + ". Выберите чат, огонёк которого показывать:");
|
||||
for (final Candidate candidate : found) {
|
||||
String letter = candidate.name.length() == 0 ? "?" : candidate.name.substring(0, 1).toUpperCase();
|
||||
LinearLayout row = Md3.listItem(this, palette,
|
||||
Md3.flowerAvatar(this, palette.primaryContainer, palette.onPrimaryContainer, letter, 8),
|
||||
candidate.name, "Огонёк: " + candidate.info.streak, null, true);
|
||||
row.setOnClickListener(new View.OnClickListener() {
|
||||
@Override public void onClick(View v) {
|
||||
choose(candidate, account.uid);
|
||||
}
|
||||
});
|
||||
list.addView(row);
|
||||
}
|
||||
}
|
||||
|
||||
private void choose(Candidate candidate, String owner) {
|
||||
WidgetStore.put(this, widgetId, new WidgetStore.Choice(candidate.info.conversation, candidate.uid,
|
||||
candidate.name, candidate.info.streak, candidate.info.endAt, candidate.info.remindAt, owner));
|
||||
StreakWidget.draw(this, AppWidgetManager.getInstance(this), widgetId);
|
||||
setResult(RESULT_OK, new Intent().putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId));
|
||||
finish();
|
||||
}
|
||||
}
|
||||
243
src/lihont/two/widget/StreakWidget.java
Normal file
243
src/lihont/two/widget/StreakWidget.java
Normal file
@@ -0,0 +1,243 @@
|
||||
package lihont.two.widget;
|
||||
|
||||
import android.app.PendingIntent;
|
||||
import android.appwidget.AppWidgetManager;
|
||||
import android.appwidget.AppWidgetProvider;
|
||||
import android.content.ComponentName;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.graphics.Bitmap;
|
||||
import android.net.Uri;
|
||||
import android.os.Build;
|
||||
import android.os.Bundle;
|
||||
import android.os.SystemClock;
|
||||
import android.util.Log;
|
||||
import android.view.View;
|
||||
import android.widget.RemoteViews;
|
||||
|
||||
import lihont.two.account.CurrentAccount;
|
||||
import lihont.two.settings.Md3;
|
||||
import lihont.two.settings.ModSettings;
|
||||
import lihont.two.settings.SettingsHost;
|
||||
|
||||
/**
|
||||
* The streak widget: a flower with the flame and the number of days of the streak with one friend.
|
||||
*
|
||||
* It rides in the layout of TikTok's own small Stories widget (see lihont/widget_patch.py), which holds a
|
||||
* picture view and two views that stay hidden; the whole picture is drawn by FlowerArt, in the colours of
|
||||
* the accent chosen in the mod settings, as large as the widget is on the screen (the widget can be dragged
|
||||
* to any size). The numbers come from TikTok's streak module while the app is running; when it is not, the
|
||||
* last numbers seen are shown. A tap opens the chat. Four subclasses (StreakWidget1, StreakWidget3,
|
||||
* StreakWidget4 and this one for 2x2) exist only because each size is a receiver of its own in the manifest.
|
||||
*/
|
||||
public class StreakWidget extends AppWidgetProvider {
|
||||
private static final String TAG = "LIHONT";
|
||||
static final String CONFIG_CLASS = "lihont.two.widget.StreakConfigActivity";
|
||||
/** The route TikTok itself opens a direct chat with, by the account id of the other person. */
|
||||
private static final String CHAT_ROUTE = "snssdk1233://chat/message?uid=";
|
||||
|
||||
// Resource ids of TikTok 47.1.3's own layout of the small Stories widget (res/b/pr.xml).
|
||||
private static final int LAYOUT = 0x7F0D0178;
|
||||
private static final int PICTURE = 0x7F0A1DAB;
|
||||
/**
|
||||
* The three more picture views that lihont/widget_patch.py puts next to PICTURE inside a ViewFlipper. The
|
||||
* launcher flips through the four by itself, so the flame moves without any code running in the widget.
|
||||
*/
|
||||
private static final int[] FRAME_VIEWS = {0x7F0A1DAC, 0x7F0A1DAD, 0x7F0A1DAE};
|
||||
private static final int BADGE = 0x7F0A881C;
|
||||
private static final int LABEL = 0x7F0A8829;
|
||||
|
||||
private static final long REFRESH_EVERY_MS = 120000L;
|
||||
private static final int MIN_SIDE_PX = 96;
|
||||
private static final int MAX_SIDE_PX = 640;
|
||||
/** A lit widget carries four pictures; the launcher keeps a widget's pictures within a few megabytes. */
|
||||
private static final int MAX_ANIMATED_SIDE_PX = 440;
|
||||
private static long refreshedAt;
|
||||
private static String lastAccount;
|
||||
|
||||
/** The sizes the widget can be added in, in cells of the home screen's grid. */
|
||||
public static final int[] SIZES = {1, 2, 3, 4};
|
||||
|
||||
@Override public void onUpdate(Context context, AppWidgetManager manager, int[] ids) {
|
||||
for (int id : ids) {
|
||||
draw(context, manager, id);
|
||||
refreshLive(context, id);
|
||||
}
|
||||
}
|
||||
|
||||
@Override public void onAppWidgetOptionsChanged(Context context, AppWidgetManager manager, int id,
|
||||
Bundle options) {
|
||||
draw(context, manager, id);
|
||||
}
|
||||
|
||||
@Override public void onDeleted(Context context, int[] ids) {
|
||||
for (int id : ids) WidgetStore.remove(context, id);
|
||||
}
|
||||
|
||||
/** Draws one widget from what is stored for it. */
|
||||
static void draw(Context context, AppWidgetManager manager, int id) {
|
||||
try {
|
||||
if (!hasLayout(context)) return;
|
||||
WidgetStore.Choice choice = WidgetStore.get(context, id);
|
||||
ModSettings active = SettingsHost.active();
|
||||
ModSettings.Theme theme = active != null ? active.theme() : ModSettings.Theme.SYSTEM;
|
||||
Md3.Palette palette = Md3.palette(context, theme);
|
||||
FlowerArt.Colors colors = new FlowerArt.Colors(palette.primaryContainer, palette.onPrimaryContainer,
|
||||
palette.outline);
|
||||
int dp = sizeDp(manager, id);
|
||||
int side = Math.max(MIN_SIDE_PX, Math.min(MAX_SIDE_PX,
|
||||
Math.round(dp * context.getResources().getDisplayMetrics().density)));
|
||||
boolean compact = dp < 100;
|
||||
boolean burning = choice != null && !fading(choice);
|
||||
// four pictures of a swaying flame stay in the launcher's memory, so they are drawn a little smaller
|
||||
int drawn = burning ? Math.min(side, MAX_ANIMATED_SIDE_PX) : side;
|
||||
Bitmap[] frames = choice == null ? FlowerArt.frames(colors, -1, false, null, drawn, compact)
|
||||
: FlowerArt.frames(colors, choice.streak, fading(choice), choice.name, drawn, compact);
|
||||
RemoteViews views = new RemoteViews(context.getPackageName(), LAYOUT);
|
||||
views.setImageViewBitmap(PICTURE, frames[0]);
|
||||
for (int i = 0; i < FRAME_VIEWS.length; i++) views.setImageViewBitmap(FRAME_VIEWS[i], frames[i + 1]);
|
||||
views.setViewVisibility(BADGE, View.GONE);
|
||||
views.setViewVisibility(LABEL, View.GONE);
|
||||
views.setOnClickPendingIntent(PICTURE, choice == null ? chooser(context, id)
|
||||
: foreign(choice) ? launcher(context, id) : chat(context, id, choice.uid));
|
||||
manager.updateAppWidget(id, views);
|
||||
} catch (Throwable failure) {
|
||||
Log.i(TAG, "widget: draw failed " + failure);
|
||||
}
|
||||
}
|
||||
|
||||
/** The side of the square the widget has on the screen, in dp (from the launcher's size report). */
|
||||
private static int sizeDp(AppWidgetManager manager, int id) {
|
||||
Bundle options = manager.getAppWidgetOptions(id);
|
||||
int width = options.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH, 0);
|
||||
int height = options.getInt(AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT, 0);
|
||||
return width > 0 && height > 0 ? Math.min(width, height) : 110;
|
||||
}
|
||||
|
||||
/** Asks the streak module for fresh numbers, off the main thread, and draws again when they came. */
|
||||
static void refreshLive(final Context context, final int id) {
|
||||
final Context app = context.getApplicationContext() != null ? context.getApplicationContext() : context;
|
||||
new Thread(new Runnable() {
|
||||
@Override public void run() {
|
||||
try {
|
||||
WidgetStore.Choice choice = WidgetStore.get(app, id);
|
||||
if (choice == null) return;
|
||||
if (foreign(choice)) {
|
||||
// Another account is signed in: its module knows nothing of this chat, so the stored
|
||||
// numbers stay, and the tap is redrawn to open TikTok instead of a chat of the wrong account.
|
||||
draw(app, AppWidgetManager.getInstance(app), id);
|
||||
return;
|
||||
}
|
||||
StreakApi.Info info = StreakApi.info(choice.conversation);
|
||||
if (info == null) return;
|
||||
WidgetStore.put(app, id, choice.with(info));
|
||||
draw(app, AppWidgetManager.getInstance(app), id);
|
||||
} catch (Throwable ignored) {
|
||||
// The stored numbers stay on the screen.
|
||||
}
|
||||
}
|
||||
}, "lihont-widget").start();
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether this widget was set up under another account than the one signed in now. When TikTok cannot
|
||||
* say who is signed in, or the widget is older than the owner field, it counts as the account's own.
|
||||
*/
|
||||
private static boolean foreign(WidgetStore.Choice choice) {
|
||||
if (choice.owner.length() == 0) return false;
|
||||
String current = CurrentAccount.uid();
|
||||
return current != null && !choice.owner.equals(current);
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when TikTok is on screen: the numbers are as fresh as they will ever be, so every widget is
|
||||
* redrawn. Switching to another account redraws at once, since which widgets are live has just changed.
|
||||
*/
|
||||
public static void refreshAll(Context context) {
|
||||
try {
|
||||
long now = SystemClock.uptimeMillis();
|
||||
String account = CurrentAccount.uid();
|
||||
boolean switched = account != null && !account.equals(lastAccount);
|
||||
if (!switched && refreshedAt != 0 && now - refreshedAt < REFRESH_EVERY_MS) return;
|
||||
refreshedAt = now;
|
||||
if (account != null) lastAccount = account;
|
||||
Context app = context.getApplicationContext() != null ? context.getApplicationContext() : context;
|
||||
AppWidgetManager manager = AppWidgetManager.getInstance(app);
|
||||
for (Class<?> type : providers()) {
|
||||
for (int id : manager.getAppWidgetIds(new ComponentName(app, type))) refreshLive(app, id);
|
||||
}
|
||||
} catch (Throwable ignored) {
|
||||
// Decoration.
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Asks the launcher to put a widget of this many cells on the home screen (it shows its own confirmation,
|
||||
* then the chat picker). False when the launcher cannot do that, in which case the widget has to be added
|
||||
* from the launcher's own widget list.
|
||||
*/
|
||||
public static boolean requestPin(Context context, int cells) {
|
||||
try {
|
||||
AppWidgetManager manager = AppWidgetManager.getInstance(context);
|
||||
return Build.VERSION.SDK_INT >= 26 && manager.isRequestPinAppWidgetSupported()
|
||||
&& manager.requestPinAppWidget(new ComponentName(context, provider(cells)), null, null);
|
||||
} catch (Throwable unavailable) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static Class<?> provider(int cells) {
|
||||
switch (cells) {
|
||||
case 1: return StreakWidget1.class;
|
||||
case 3: return StreakWidget3.class;
|
||||
case 4: return StreakWidget4.class;
|
||||
default: return StreakWidget.class;
|
||||
}
|
||||
}
|
||||
|
||||
private static Class<?>[] providers() {
|
||||
return new Class<?>[] {StreakWidget1.class, StreakWidget.class, StreakWidget3.class, StreakWidget4.class};
|
||||
}
|
||||
|
||||
private static boolean hasLayout(Context context) {
|
||||
try {
|
||||
return "layout".equals(context.getResources().getResourceTypeName(LAYOUT))
|
||||
&& "id".equals(context.getResources().getResourceTypeName(PICTURE));
|
||||
} catch (Throwable missing) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether the streak is about to end, which TikTok shows with a grey flame. */
|
||||
private static boolean fading(WidgetStore.Choice choice) {
|
||||
return StreakApi.cold(choice.remindAt, choice.endAt, System.currentTimeMillis());
|
||||
}
|
||||
|
||||
/** Opens the chat with this person in TikTok; TikTok's start screen when it does not know the route. */
|
||||
private static PendingIntent chat(Context context, int id, String uid) {
|
||||
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(CHAT_ROUTE + uid))
|
||||
.setPackage(context.getPackageName()).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
|
||||
if (uid == null || uid.length() == 0 || context.getPackageManager().resolveActivity(intent, 0) == null) {
|
||||
intent = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
|
||||
if (intent == null) return chooser(context, id);
|
||||
}
|
||||
return PendingIntent.getActivity(context, id, intent, flags());
|
||||
}
|
||||
|
||||
/** Opens TikTok itself: a widget of another account cannot open its chat, and the user switches account there. */
|
||||
private static PendingIntent launcher(Context context, int id) {
|
||||
Intent intent = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
|
||||
if (intent == null) return chooser(context, id);
|
||||
return PendingIntent.getActivity(context, id, intent, flags());
|
||||
}
|
||||
|
||||
private static PendingIntent chooser(Context context, int id) {
|
||||
Intent intent = new Intent().setClassName(context.getPackageName(), CONFIG_CLASS)
|
||||
.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, id).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
|
||||
return PendingIntent.getActivity(context, id, intent, flags());
|
||||
}
|
||||
|
||||
private static int flags() {
|
||||
return PendingIntent.FLAG_UPDATE_CURRENT | (Build.VERSION.SDK_INT >= 23 ? PendingIntent.FLAG_IMMUTABLE : 0);
|
||||
}
|
||||
}
|
||||
4
src/lihont/two/widget/StreakWidget1.java
Normal file
4
src/lihont/two/widget/StreakWidget1.java
Normal file
@@ -0,0 +1,4 @@
|
||||
package lihont.two.widget;
|
||||
|
||||
/** The 1x1-cell receiver of the streak widget (see StreakWidget). */
|
||||
public final class StreakWidget1 extends StreakWidget {}
|
||||
4
src/lihont/two/widget/StreakWidget3.java
Normal file
4
src/lihont/two/widget/StreakWidget3.java
Normal file
@@ -0,0 +1,4 @@
|
||||
package lihont.two.widget;
|
||||
|
||||
/** The 3x3-cell receiver of the streak widget (see StreakWidget). */
|
||||
public final class StreakWidget3 extends StreakWidget {}
|
||||
4
src/lihont/two/widget/StreakWidget4.java
Normal file
4
src/lihont/two/widget/StreakWidget4.java
Normal file
@@ -0,0 +1,4 @@
|
||||
package lihont.two.widget;
|
||||
|
||||
/** The 4x4-cell receiver of the streak widget (see StreakWidget). */
|
||||
public final class StreakWidget4 extends StreakWidget {}
|
||||
75
src/lihont/two/widget/WidgetStore.java
Normal file
75
src/lihont/two/widget/WidgetStore.java
Normal file
@@ -0,0 +1,75 @@
|
||||
package lihont.two.widget;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
|
||||
/** The chat each streak widget was set up for, and the last numbers seen for it (kept so a widget never goes blank). */
|
||||
final class WidgetStore {
|
||||
private static final String FILE = "lihont_streak_widget";
|
||||
|
||||
/** One widget's chat and what was last known about its streak. */
|
||||
static final class Choice {
|
||||
final String conversation;
|
||||
final String uid;
|
||||
final String name;
|
||||
final int streak;
|
||||
final long endAt;
|
||||
final long remindAt;
|
||||
/**
|
||||
* The account that was signed in when the widget was set up: a streak belongs to a chat of that account,
|
||||
* and only that account can open the chat or ask for fresh numbers. Empty for a widget made before the
|
||||
* owner was kept; such a widget behaves as it always did.
|
||||
*/
|
||||
final String owner;
|
||||
|
||||
Choice(String conversation, String uid, String name, int streak, long endAt, long remindAt, String owner) {
|
||||
this.conversation = conversation;
|
||||
this.uid = uid;
|
||||
this.name = name;
|
||||
this.streak = streak;
|
||||
this.endAt = endAt;
|
||||
this.remindAt = remindAt;
|
||||
this.owner = owner == null ? "" : owner;
|
||||
}
|
||||
|
||||
Choice with(StreakApi.Info info) {
|
||||
return new Choice(conversation, uid, name, info.streak, info.endAt, info.remindAt, owner);
|
||||
}
|
||||
}
|
||||
|
||||
private WidgetStore() {}
|
||||
|
||||
private static SharedPreferences prefs(Context context) {
|
||||
return context.getSharedPreferences(FILE, Context.MODE_PRIVATE);
|
||||
}
|
||||
|
||||
static Choice get(Context context, int id) {
|
||||
SharedPreferences prefs = prefs(context);
|
||||
String conversation = prefs.getString("w" + id + ".conversation", null);
|
||||
if (conversation == null) return null;
|
||||
return new Choice(conversation, prefs.getString("w" + id + ".uid", ""),
|
||||
prefs.getString("w" + id + ".name", ""), prefs.getInt("w" + id + ".streak", 0),
|
||||
prefs.getLong("w" + id + ".end", 0L), prefs.getLong("w" + id + ".remind", 0L),
|
||||
prefs.getString("w" + id + ".owner", ""));
|
||||
}
|
||||
|
||||
static void put(Context context, int id, Choice choice) {
|
||||
prefs(context).edit()
|
||||
.putString("w" + id + ".conversation", choice.conversation)
|
||||
.putString("w" + id + ".uid", choice.uid)
|
||||
.putString("w" + id + ".name", choice.name)
|
||||
.putInt("w" + id + ".streak", choice.streak)
|
||||
.putLong("w" + id + ".end", choice.endAt)
|
||||
.putLong("w" + id + ".remind", choice.remindAt)
|
||||
.putString("w" + id + ".owner", choice.owner)
|
||||
.apply();
|
||||
}
|
||||
|
||||
static void remove(Context context, int id) {
|
||||
prefs(context).edit()
|
||||
.remove("w" + id + ".conversation").remove("w" + id + ".uid").remove("w" + id + ".name")
|
||||
.remove("w" + id + ".streak").remove("w" + id + ".end").remove("w" + id + ".remind")
|
||||
.remove("w" + id + ".owner")
|
||||
.apply();
|
||||
}
|
||||
}
|
||||
109
tests/java/lihont/two/account/AccountShapeBookTest.java
Normal file
109
tests/java/lihont/two/account/AccountShapeBookTest.java
Normal file
@@ -0,0 +1,109 @@
|
||||
package lihont.two.account;
|
||||
|
||||
/** Behavioral tests of the per-account shape book, without Android or a test library. */
|
||||
public final class AccountShapeBookTest {
|
||||
public static void main(String[] args) {
|
||||
if (args.length != 1) throw new AssertionError("Expected a test scenario");
|
||||
switch (args[0]) {
|
||||
case "perAccount": perAccount(); break;
|
||||
case "roundTrip": roundTrip(); break;
|
||||
case "damaged": damaged(); break;
|
||||
case "invalid": invalid(); break;
|
||||
case "migrate": migrate(); break;
|
||||
default: throw new AssertionError("Unknown test scenario");
|
||||
}
|
||||
System.out.println("PASS " + args[0]);
|
||||
}
|
||||
|
||||
private static void perAccount() {
|
||||
AccountShapeBook book = new AccountShapeBook();
|
||||
check(book.shapeOf("111") == null, "An account that chose nothing has no shape");
|
||||
book.put("111", "flower");
|
||||
book.put("222", "heart");
|
||||
check("flower".equals(book.shapeOf("111")) && "heart".equals(book.shapeOf("222")),
|
||||
"Each account keeps its own shape");
|
||||
book.put("111", "hexagon");
|
||||
check("hexagon".equals(book.shapeOf("111")) && "heart".equals(book.shapeOf("222")),
|
||||
"Changing one account leaves the other alone");
|
||||
book.put("222", "circle");
|
||||
check("circle".equals(book.shapeOf("222")), "Choosing the round shape is a choice too");
|
||||
check(book.shapeOf(null) == null && book.shapeOf("abc") == null, "A bad id has no shape");
|
||||
}
|
||||
|
||||
private static void roundTrip() {
|
||||
AccountShapeBook book = new AccountShapeBook();
|
||||
book.put("111", "flower");
|
||||
book.put("9223372036854775807", "triangle");
|
||||
book.migrate("heart", "111");
|
||||
AccountShapeBook back = AccountShapeBook.decode(book.encode());
|
||||
check("flower".equals(back.shapeOf("111")), "The first account survives the file");
|
||||
check("triangle".equals(back.shapeOf("9223372036854775807")), "A long account id survives the file");
|
||||
check(back.migrated(), "The migration flag survives the file");
|
||||
check(back.encode().equals(book.encode()), "Writing it again gives the same text");
|
||||
check(AccountShapeBook.decode(null).shapeOf("111") == null, "No file is an empty book");
|
||||
check(AccountShapeBook.decode("").shapeOf("111") == null, "An empty file is an empty book");
|
||||
}
|
||||
|
||||
private static void damaged() {
|
||||
String text = "migrated=1\n111=flower\nnonsense\n=heart\n222=\nabc=flower\n333=Heart\n444=triangle\n"
|
||||
+ "555=has space\n666=flower=extra\n";
|
||||
AccountShapeBook book = AccountShapeBook.decode(text);
|
||||
check("flower".equals(book.shapeOf("111")), "A good line before the damage is kept");
|
||||
check("triangle".equals(book.shapeOf("444")), "A good line after the damage is kept");
|
||||
check(book.shapeOf("222") == null && book.shapeOf("333") == null && book.shapeOf("555") == null
|
||||
&& book.shapeOf("666") == null, "Damaged lines are skipped");
|
||||
check(book.migrated(), "The flag is read");
|
||||
check(AccountShapeBook.decode("migrated=0\n").migrated() == false, "Any other flag value is not migrated");
|
||||
}
|
||||
|
||||
private static void invalid() {
|
||||
AccountShapeBook book = new AccountShapeBook();
|
||||
expectRefused(book, "", "flower");
|
||||
expectRefused(book, "abc", "flower");
|
||||
expectRefused(book, "12345678901234567890123", "flower");
|
||||
expectRefused(book, "111", null);
|
||||
expectRefused(book, "111", "");
|
||||
expectRefused(book, "111", "Flower");
|
||||
expectRefused(book, "111", "flower\nmigrated=1");
|
||||
check(book.encode().isEmpty(), "A refused choice leaves nothing behind");
|
||||
check(AccountShapeBook.validUid("1") && !AccountShapeBook.validUid("") && !AccountShapeBook.validUid("1 2"),
|
||||
"Account ids are plain digits");
|
||||
}
|
||||
|
||||
private static void migrate() {
|
||||
AccountShapeBook book = new AccountShapeBook();
|
||||
check(!book.migrate("flower", null), "Nothing happens while no account is known");
|
||||
check(!book.migrated(), "The flag stays off, so it is asked again later");
|
||||
check(!book.migrate("flower", "not-an-id"), "A bad id does not count as an account");
|
||||
check(book.migrate("flower", "111"), "The first known account takes the old shape");
|
||||
check("flower".equals(book.shapeOf("111")), "The old shape is now that account's");
|
||||
check(book.migrated(), "The flag is on");
|
||||
check(!book.migrate("heart", "222"), "It happens only once");
|
||||
check(book.shapeOf("222") == null, "A second account starts with nothing");
|
||||
|
||||
AccountShapeBook round = new AccountShapeBook();
|
||||
check(round.migrate("circle", "111"), "Migrating the round shape still counts");
|
||||
check(round.shapeOf("111") == null && round.migrated(), "The round shape is no choice, only the flag is set");
|
||||
|
||||
AccountShapeBook kept = new AccountShapeBook();
|
||||
kept.put("111", "heart");
|
||||
check(kept.migrate("flower", "111"), "The flag is set");
|
||||
check("heart".equals(kept.shapeOf("111")), "An account that already chose keeps its choice");
|
||||
|
||||
AccountShapeBook unknown = new AccountShapeBook();
|
||||
check(unknown.migrate(null, "111") && unknown.shapeOf("111") == null, "No old shape means nothing to hand over");
|
||||
}
|
||||
|
||||
private static void expectRefused(AccountShapeBook book, String uid, String shape) {
|
||||
try {
|
||||
book.put(uid, shape);
|
||||
} catch (IllegalArgumentException expected) {
|
||||
return;
|
||||
}
|
||||
throw new AssertionError("Should have been refused: " + uid + " " + shape);
|
||||
}
|
||||
|
||||
private static void check(boolean condition, String message) {
|
||||
if (!condition) throw new AssertionError(message);
|
||||
}
|
||||
}
|
||||
44
tests/java/lihont/two/look/BlackRuleTest.java
Normal file
44
tests/java/lihont/two/look/BlackRuleTest.java
Normal file
@@ -0,0 +1,44 @@
|
||||
package lihont.two.look;
|
||||
|
||||
/** Behavioral tests of the "what is black" rule, without Android or a test library. */
|
||||
public final class BlackRuleTest {
|
||||
public static void main(String[] args) {
|
||||
if (args.length != 1) throw new AssertionError("Expected a test scenario");
|
||||
switch (args[0]) {
|
||||
case "black": black(); break;
|
||||
case "notBlack": notBlack(); break;
|
||||
case "surfaces": surfaces(); break;
|
||||
default: throw new AssertionError("Unknown test scenario");
|
||||
}
|
||||
System.out.println("PASS " + args[0]);
|
||||
}
|
||||
|
||||
private static void black() {
|
||||
check(BlackRule.isBlack(0xFF000000), "Pure black is black");
|
||||
check(BlackRule.isBlack(0xFF0A0A0A), "Almost black is black");
|
||||
check(BlackRule.isBlack(0xFF0C0C0C), "The limit itself is black");
|
||||
check(BlackRule.isBlack(0xFF000C00) && BlackRule.isBlack(0xFF0C0000), "Each channel counts on its own");
|
||||
}
|
||||
|
||||
private static void notBlack() {
|
||||
check(!BlackRule.isBlack(0xFF0D0D0D), "One step past the limit is not black");
|
||||
check(!BlackRule.isBlack(0xFF121212), "The dark grey of cards stays");
|
||||
check(!BlackRule.isBlack(0xFF1E1E1E), "A lighter grey stays");
|
||||
check(!BlackRule.isBlack(0xFF000020), "A dark blue is not black");
|
||||
check(!BlackRule.isBlack(0xFFFFFFFF), "White is not black");
|
||||
check(!BlackRule.isBlack(0x80000000), "A half transparent black is a scrim, not a background");
|
||||
check(!BlackRule.isBlack(0xFE000000), "Not quite opaque is not black");
|
||||
check(!BlackRule.isBlack(0x00000000), "Fully transparent is nothing");
|
||||
check(!BlackRule.isBlack(0x00FFFFFF), "Transparent white is nothing");
|
||||
}
|
||||
|
||||
/** The tonal colours the skin paints with must never be taken for black again, or it would repaint forever. */
|
||||
private static void surfaces() {
|
||||
int[] darkSurfaces = {0xFF10131A, 0xFF141218, 0xFF0F1415, 0xFF111318, 0xFF121212, 0xFF191C1A, 0xFF0E1514};
|
||||
for (int surface : darkSurfaces) check(!BlackRule.isBlack(surface), "Surface " + Integer.toHexString(surface));
|
||||
}
|
||||
|
||||
private static void check(boolean condition, String message) {
|
||||
if (!condition) throw new AssertionError(message);
|
||||
}
|
||||
}
|
||||
@@ -1,183 +1,183 @@
|
||||
package lihont.two.settings;
|
||||
|
||||
import java.awt.Color;
|
||||
import java.awt.Font;
|
||||
import java.awt.FontMetrics;
|
||||
import java.awt.Graphics2D;
|
||||
import java.awt.RenderingHints;
|
||||
import java.awt.geom.AffineTransform;
|
||||
import java.awt.geom.Ellipse2D;
|
||||
import java.awt.geom.Path2D;
|
||||
import java.awt.geom.Rectangle2D;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.File;
|
||||
import javax.imageio.ImageIO;
|
||||
|
||||
/** Parses every icon path on a desktop JVM and checks, or draws, the resulting shapes. */
|
||||
public final class IconRenderTest {
|
||||
private static final String[] NAMES = {
|
||||
"BACK", "CLOSE", "CHECK", "CHEVRON_RIGHT", "SEARCH", "BANNER", "REPOST", "SUN", "MOON", "INFO", "NOTE",
|
||||
"SEND", "TIKTOK", "ADD_PHOTO", "DELETE", "BOTTOM_BAR", "DOWNLOAD", "AD_OFF", "LIVE", "SHOP", "CODE",
|
||||
};
|
||||
|
||||
/** Where each icon appears in the app, for the preview sheet. */
|
||||
private static final String[] USES = {
|
||||
"Назад (шапка)", "Закрыть (окна)", "Галочка выбора", "Стрелка в строках", "Поиск страны",
|
||||
"Баннеры профиля", "Репост комментариев", "Тема: светлая", "Тема: тёмная", "Версия мода",
|
||||
"Строка в настройках TikTok", "Telegram-канал", "База TikTok", "Свой значок", "Удалить значок", "Нижнее меню", "Скачивание",
|
||||
"Убрать рекламу", "Убрать эфиры", "Убрать «Магазин»", "Исходный код (О моде)",
|
||||
};
|
||||
|
||||
private static Path2D.Float shape(int kind) {
|
||||
final Path2D.Float path = new Path2D.Float(Path2D.WIND_NON_ZERO);
|
||||
Md3Icon.build(kind, new SvgPath.Sink() {
|
||||
@Override public void moveTo(float x, float y) { path.moveTo(x, y); }
|
||||
|
||||
@Override public void lineTo(float x, float y) { path.lineTo(x, y); }
|
||||
|
||||
@Override public void cubicTo(float x1, float y1, float x2, float y2, float x, float y) {
|
||||
path.curveTo(x1, y1, x2, y2, x, y);
|
||||
}
|
||||
|
||||
@Override public void close() { path.closePath(); }
|
||||
});
|
||||
return path;
|
||||
}
|
||||
|
||||
private static Path2D.Float shape(String data) {
|
||||
final Path2D.Float path = new Path2D.Float(Path2D.WIND_NON_ZERO);
|
||||
SvgPath.parse(data, new SvgPath.Sink() {
|
||||
@Override public void moveTo(float x, float y) { path.moveTo(x, y); }
|
||||
|
||||
@Override public void lineTo(float x, float y) { path.lineTo(x, y); }
|
||||
|
||||
@Override public void cubicTo(float x1, float y1, float x2, float y2, float x, float y) {
|
||||
path.curveTo(x1, y1, x2, y2, x, y);
|
||||
}
|
||||
|
||||
@Override public void close() { path.closePath(); }
|
||||
});
|
||||
return path;
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
switch (args[0]) {
|
||||
case "bounds": bounds(); break;
|
||||
case "tokens": tokens(); break;
|
||||
case "render": render(new File(args[1])); return;
|
||||
default: throw new AssertionError("Unknown scenario " + args[0]);
|
||||
}
|
||||
System.out.println("PASS " + args[0]);
|
||||
}
|
||||
|
||||
private static void bounds() {
|
||||
if (Md3Icon.PATHS.length != NAMES.length) throw new AssertionError("Icon table and names differ");
|
||||
if (Md3Icon.GRID.length != NAMES.length || Md3Icon.ORIGIN_Y.length != NAMES.length) {
|
||||
throw new AssertionError("Grid tables and names differ");
|
||||
}
|
||||
for (int i = 0; i < NAMES.length; i++) {
|
||||
Rectangle2D box = shape(i).getBounds2D();
|
||||
if (box.getMinX() < -0.01 || box.getMinY() < -0.01 || box.getMaxX() > 24.01 || box.getMaxY() > 24.01) {
|
||||
throw new AssertionError(NAMES[i] + " leaves the 24 unit grid: " + box);
|
||||
}
|
||||
if (Math.max(box.getWidth(), box.getHeight()) < 10) {
|
||||
throw new AssertionError(NAMES[i] + " is too small to read as an icon: " + box);
|
||||
}
|
||||
double ink = coverage(shape(i));
|
||||
if (ink < 0.03 || ink > 0.8) throw new AssertionError(NAMES[i] + " ink coverage " + ink);
|
||||
}
|
||||
}
|
||||
|
||||
/** Share of the 24x24 grid the icon paints, found by rasterising it. */
|
||||
private static double coverage(Path2D.Float path) {
|
||||
int size = 96;
|
||||
BufferedImage image = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB);
|
||||
Graphics2D g = image.createGraphics();
|
||||
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
|
||||
g.setColor(Color.BLACK);
|
||||
g.fill(new Path2D.Float(path, AffineTransform.getScaleInstance(size / 24.0, size / 24.0)));
|
||||
g.dispose();
|
||||
int painted = 0;
|
||||
for (int y = 0; y < size; y++) {
|
||||
for (int x = 0; x < size; x++) {
|
||||
if ((image.getRGB(x, y) >>> 24) > 127) painted++;
|
||||
}
|
||||
}
|
||||
return painted / (double) (size * size);
|
||||
}
|
||||
|
||||
private static void tokens() {
|
||||
// Shortened forms: no separator before a minus or a second dot, implicit repeats, relative moves.
|
||||
// After the z the pen is back at (0.5, 0.5), so "m4 0" starts the second shape at x = 4.5.
|
||||
Rectangle2D box = shape("M.5.5h1-1v1zm4 0l1 1-1 1z").getBounds2D();
|
||||
near(0.5, box.getMinX());
|
||||
near(5.5, box.getMaxX());
|
||||
near(2.5, box.getMaxY());
|
||||
// Arc flags written without separators, as Material icons do: a2 2 0 00-2 2.
|
||||
Rectangle2D arc = shape("M4 4v2a2 2 0 00 2 2h2").getBounds2D();
|
||||
near(4.0, arc.getMinX());
|
||||
near(8.0, arc.getMaxX());
|
||||
near(8.0, arc.getMaxY());
|
||||
// A half circle of radius 5 drawn with an arc spans 10 units.
|
||||
Rectangle2D half = shape("M0 5a5 5 0 0010 0").getBounds2D();
|
||||
near(10.0, half.getWidth());
|
||||
near(5.0, half.getHeight());
|
||||
// Smooth quadratics, which Material Symbols use for rounded ends: T repeats the last control point.
|
||||
Rectangle2D smooth = shape("M0 0q4 0 4 4T8 8").getBounds2D();
|
||||
near(8.0, smooth.getMaxX());
|
||||
boolean rejected = false;
|
||||
try { shape("M1 1 5"); } catch (IllegalArgumentException expected) { rejected = true; }
|
||||
if (!rejected) throw new AssertionError("A lone coordinate must be rejected");
|
||||
}
|
||||
|
||||
private static void near(double expected, double actual) {
|
||||
if (Math.abs(expected - actual) > 0.15) {
|
||||
throw new AssertionError("expected " + expected + " but was " + actual);
|
||||
}
|
||||
}
|
||||
|
||||
/** A flower badge like the one in the app: a disc and eight petals. */
|
||||
private static void flower(Graphics2D g, double cx, double cy, double r) {
|
||||
g.fill(new Ellipse2D.Double(cx - r * 0.70, cy - r * 0.70, r * 1.40, r * 1.40));
|
||||
double petal = r * 0.38, dist = r * 0.62;
|
||||
for (int i = 0; i < 8; i++) {
|
||||
double angle = i * (2 * Math.PI / 8) + Math.PI / 8;
|
||||
g.fill(new Ellipse2D.Double(cx + Math.cos(angle) * dist - petal, cy + Math.sin(angle) * dist - petal,
|
||||
petal * 2, petal * 2));
|
||||
}
|
||||
}
|
||||
|
||||
private static void render(File out) throws Exception {
|
||||
int columns = 4, tileW = 240, tileH = 190, rows = (NAMES.length + columns - 1) / columns;
|
||||
BufferedImage image = new BufferedImage(tileW * columns, tileH * rows, BufferedImage.TYPE_INT_RGB);
|
||||
Graphics2D g = image.createGraphics();
|
||||
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
|
||||
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
|
||||
g.setColor(new Color(0x1a1b21));
|
||||
g.fillRect(0, 0, image.getWidth(), image.getHeight());
|
||||
Font number = new Font("Dialog", Font.BOLD, 26), label = new Font("Dialog", Font.PLAIN, 16);
|
||||
for (int i = 0; i < NAMES.length; i++) {
|
||||
int ox = (i % columns) * tileW, oy = (i / columns) * tileH;
|
||||
g.setColor(new Color(0x2b2930));
|
||||
g.fillRoundRect(ox + 8, oy + 8, tileW - 16, tileH - 16, 28, 28);
|
||||
g.setColor(new Color(0x4a4458));
|
||||
flower(g, ox + tileW / 2.0, oy + 76, 64);
|
||||
g.setColor(new Color(0xe8def8));
|
||||
double scale = 3.6;
|
||||
AffineTransform move = new AffineTransform();
|
||||
move.translate(ox + tileW / 2.0 - 12 * scale, oy + 76 - 12 * scale);
|
||||
move.scale(scale, scale);
|
||||
g.fill(new Path2D.Float(shape(i), move));
|
||||
g.setFont(number);
|
||||
g.setColor(Color.WHITE);
|
||||
g.drawString(String.valueOf(i + 1), ox + 22, oy + 40);
|
||||
g.setFont(label);
|
||||
g.setColor(new Color(0xc9c5d0));
|
||||
FontMetrics metrics = g.getFontMetrics();
|
||||
g.drawString(USES[i], ox + (tileW - metrics.stringWidth(USES[i])) / 2, oy + tileH - 22);
|
||||
}
|
||||
g.dispose();
|
||||
ImageIO.write(image, "png", out);
|
||||
System.out.println("wrote " + out);
|
||||
}
|
||||
}
|
||||
package lihont.two.settings;
|
||||
|
||||
import java.awt.Color;
|
||||
import java.awt.Font;
|
||||
import java.awt.FontMetrics;
|
||||
import java.awt.Graphics2D;
|
||||
import java.awt.RenderingHints;
|
||||
import java.awt.geom.AffineTransform;
|
||||
import java.awt.geom.Ellipse2D;
|
||||
import java.awt.geom.Path2D;
|
||||
import java.awt.geom.Rectangle2D;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.File;
|
||||
import javax.imageio.ImageIO;
|
||||
|
||||
/** Parses every icon path on a desktop JVM and checks, or draws, the resulting shapes. */
|
||||
public final class IconRenderTest {
|
||||
private static final String[] NAMES = {
|
||||
"BACK", "CLOSE", "CHECK", "CHEVRON_RIGHT", "SEARCH", "BANNER", "REPOST", "SUN", "MOON", "INFO", "NOTE",
|
||||
"SEND", "TIKTOK", "ADD_PHOTO", "DELETE", "BOTTOM_BAR", "DOWNLOAD", "AD_OFF", "LIVE", "SHOP", "CODE", "FLAME",
|
||||
};
|
||||
|
||||
/** Where each icon appears in the app, for the preview sheet. */
|
||||
private static final String[] USES = {
|
||||
"Назад (шапка)", "Закрыть (окна)", "Галочка выбора", "Стрелка в строках", "Поиск страны",
|
||||
"Баннеры профиля", "Репост комментариев", "Тема: светлая", "Тема: тёмная", "Версия мода",
|
||||
"Строка в настройках TikTok", "Telegram-канал", "База TikTok", "Свой значок", "Удалить значок", "Нижнее меню", "Скачивание",
|
||||
"Убрать рекламу", "Убрать эфиры", "Убрать «Магазин»", "Исходный код (О моде)", "Виджет «Огонёк»",
|
||||
};
|
||||
|
||||
private static Path2D.Float shape(int kind) {
|
||||
final Path2D.Float path = new Path2D.Float(Path2D.WIND_NON_ZERO);
|
||||
Md3Icon.build(kind, new SvgPath.Sink() {
|
||||
@Override public void moveTo(float x, float y) { path.moveTo(x, y); }
|
||||
|
||||
@Override public void lineTo(float x, float y) { path.lineTo(x, y); }
|
||||
|
||||
@Override public void cubicTo(float x1, float y1, float x2, float y2, float x, float y) {
|
||||
path.curveTo(x1, y1, x2, y2, x, y);
|
||||
}
|
||||
|
||||
@Override public void close() { path.closePath(); }
|
||||
});
|
||||
return path;
|
||||
}
|
||||
|
||||
private static Path2D.Float shape(String data) {
|
||||
final Path2D.Float path = new Path2D.Float(Path2D.WIND_NON_ZERO);
|
||||
SvgPath.parse(data, new SvgPath.Sink() {
|
||||
@Override public void moveTo(float x, float y) { path.moveTo(x, y); }
|
||||
|
||||
@Override public void lineTo(float x, float y) { path.lineTo(x, y); }
|
||||
|
||||
@Override public void cubicTo(float x1, float y1, float x2, float y2, float x, float y) {
|
||||
path.curveTo(x1, y1, x2, y2, x, y);
|
||||
}
|
||||
|
||||
@Override public void close() { path.closePath(); }
|
||||
});
|
||||
return path;
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
switch (args[0]) {
|
||||
case "bounds": bounds(); break;
|
||||
case "tokens": tokens(); break;
|
||||
case "render": render(new File(args[1])); return;
|
||||
default: throw new AssertionError("Unknown scenario " + args[0]);
|
||||
}
|
||||
System.out.println("PASS " + args[0]);
|
||||
}
|
||||
|
||||
private static void bounds() {
|
||||
if (Md3Icon.PATHS.length != NAMES.length) throw new AssertionError("Icon table and names differ");
|
||||
if (Md3Icon.GRID.length != NAMES.length || Md3Icon.ORIGIN_Y.length != NAMES.length) {
|
||||
throw new AssertionError("Grid tables and names differ");
|
||||
}
|
||||
for (int i = 0; i < NAMES.length; i++) {
|
||||
Rectangle2D box = shape(i).getBounds2D();
|
||||
if (box.getMinX() < -0.01 || box.getMinY() < -0.01 || box.getMaxX() > 24.01 || box.getMaxY() > 24.01) {
|
||||
throw new AssertionError(NAMES[i] + " leaves the 24 unit grid: " + box);
|
||||
}
|
||||
if (Math.max(box.getWidth(), box.getHeight()) < 10) {
|
||||
throw new AssertionError(NAMES[i] + " is too small to read as an icon: " + box);
|
||||
}
|
||||
double ink = coverage(shape(i));
|
||||
if (ink < 0.03 || ink > 0.8) throw new AssertionError(NAMES[i] + " ink coverage " + ink);
|
||||
}
|
||||
}
|
||||
|
||||
/** Share of the 24x24 grid the icon paints, found by rasterising it. */
|
||||
private static double coverage(Path2D.Float path) {
|
||||
int size = 96;
|
||||
BufferedImage image = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB);
|
||||
Graphics2D g = image.createGraphics();
|
||||
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
|
||||
g.setColor(Color.BLACK);
|
||||
g.fill(new Path2D.Float(path, AffineTransform.getScaleInstance(size / 24.0, size / 24.0)));
|
||||
g.dispose();
|
||||
int painted = 0;
|
||||
for (int y = 0; y < size; y++) {
|
||||
for (int x = 0; x < size; x++) {
|
||||
if ((image.getRGB(x, y) >>> 24) > 127) painted++;
|
||||
}
|
||||
}
|
||||
return painted / (double) (size * size);
|
||||
}
|
||||
|
||||
private static void tokens() {
|
||||
// Shortened forms: no separator before a minus or a second dot, implicit repeats, relative moves.
|
||||
// After the z the pen is back at (0.5, 0.5), so "m4 0" starts the second shape at x = 4.5.
|
||||
Rectangle2D box = shape("M.5.5h1-1v1zm4 0l1 1-1 1z").getBounds2D();
|
||||
near(0.5, box.getMinX());
|
||||
near(5.5, box.getMaxX());
|
||||
near(2.5, box.getMaxY());
|
||||
// Arc flags written without separators, as Material icons do: a2 2 0 00-2 2.
|
||||
Rectangle2D arc = shape("M4 4v2a2 2 0 00 2 2h2").getBounds2D();
|
||||
near(4.0, arc.getMinX());
|
||||
near(8.0, arc.getMaxX());
|
||||
near(8.0, arc.getMaxY());
|
||||
// A half circle of radius 5 drawn with an arc spans 10 units.
|
||||
Rectangle2D half = shape("M0 5a5 5 0 0010 0").getBounds2D();
|
||||
near(10.0, half.getWidth());
|
||||
near(5.0, half.getHeight());
|
||||
// Smooth quadratics, which Material Symbols use for rounded ends: T repeats the last control point.
|
||||
Rectangle2D smooth = shape("M0 0q4 0 4 4T8 8").getBounds2D();
|
||||
near(8.0, smooth.getMaxX());
|
||||
boolean rejected = false;
|
||||
try { shape("M1 1 5"); } catch (IllegalArgumentException expected) { rejected = true; }
|
||||
if (!rejected) throw new AssertionError("A lone coordinate must be rejected");
|
||||
}
|
||||
|
||||
private static void near(double expected, double actual) {
|
||||
if (Math.abs(expected - actual) > 0.15) {
|
||||
throw new AssertionError("expected " + expected + " but was " + actual);
|
||||
}
|
||||
}
|
||||
|
||||
/** A flower badge like the one in the app: a disc and eight petals. */
|
||||
private static void flower(Graphics2D g, double cx, double cy, double r) {
|
||||
g.fill(new Ellipse2D.Double(cx - r * 0.70, cy - r * 0.70, r * 1.40, r * 1.40));
|
||||
double petal = r * 0.38, dist = r * 0.62;
|
||||
for (int i = 0; i < 8; i++) {
|
||||
double angle = i * (2 * Math.PI / 8) + Math.PI / 8;
|
||||
g.fill(new Ellipse2D.Double(cx + Math.cos(angle) * dist - petal, cy + Math.sin(angle) * dist - petal,
|
||||
petal * 2, petal * 2));
|
||||
}
|
||||
}
|
||||
|
||||
private static void render(File out) throws Exception {
|
||||
int columns = 4, tileW = 240, tileH = 190, rows = (NAMES.length + columns - 1) / columns;
|
||||
BufferedImage image = new BufferedImage(tileW * columns, tileH * rows, BufferedImage.TYPE_INT_RGB);
|
||||
Graphics2D g = image.createGraphics();
|
||||
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
|
||||
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
|
||||
g.setColor(new Color(0x1a1b21));
|
||||
g.fillRect(0, 0, image.getWidth(), image.getHeight());
|
||||
Font number = new Font("Dialog", Font.BOLD, 26), label = new Font("Dialog", Font.PLAIN, 16);
|
||||
for (int i = 0; i < NAMES.length; i++) {
|
||||
int ox = (i % columns) * tileW, oy = (i / columns) * tileH;
|
||||
g.setColor(new Color(0x2b2930));
|
||||
g.fillRoundRect(ox + 8, oy + 8, tileW - 16, tileH - 16, 28, 28);
|
||||
g.setColor(new Color(0x4a4458));
|
||||
flower(g, ox + tileW / 2.0, oy + 76, 64);
|
||||
g.setColor(new Color(0xe8def8));
|
||||
double scale = 3.6;
|
||||
AffineTransform move = new AffineTransform();
|
||||
move.translate(ox + tileW / 2.0 - 12 * scale, oy + 76 - 12 * scale);
|
||||
move.scale(scale, scale);
|
||||
g.fill(new Path2D.Float(shape(i), move));
|
||||
g.setFont(number);
|
||||
g.setColor(Color.WHITE);
|
||||
g.drawString(String.valueOf(i + 1), ox + 22, oy + 40);
|
||||
g.setFont(label);
|
||||
g.setColor(new Color(0xc9c5d0));
|
||||
FontMetrics metrics = g.getFontMetrics();
|
||||
g.drawString(USES[i], ox + (tileW - metrics.stringWidth(USES[i])) / 2, oy + tileH - 22);
|
||||
}
|
||||
g.dispose();
|
||||
ImageIO.write(image, "png", out);
|
||||
System.out.println("wrote " + out);
|
||||
}
|
||||
}
|
||||
|
||||
211
tests/java/lihont/two/streak/AutoFlameBookTest.java
Normal file
211
tests/java/lihont/two/streak/AutoFlameBookTest.java
Normal file
@@ -0,0 +1,211 @@
|
||||
package lihont.two.streak;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Calendar;
|
||||
import java.util.List;
|
||||
import java.util.TimeZone;
|
||||
|
||||
/** Behavioral tests of the streak keeper's settings and day bookkeeping, without Android or a test library. */
|
||||
public final class AutoFlameBookTest {
|
||||
private static final TimeZone MOSCOW = TimeZone.getTimeZone("Europe/Moscow"); // no change of the clock
|
||||
private static final TimeZone NEW_YORK = TimeZone.getTimeZone("America/New_York"); // changes on 2026-03-08 and 11-01
|
||||
|
||||
public static void main(String[] args) {
|
||||
if (args.length != 1) throw new AssertionError("Expected a test scenario");
|
||||
switch (args[0]) {
|
||||
case "defaults": defaults(); break;
|
||||
case "validation": validation(); break;
|
||||
case "chats": chats(); break;
|
||||
case "trigger": trigger(); break;
|
||||
case "due": due(); break;
|
||||
case "perDay": perDay(); break;
|
||||
case "clockChange": clockChange(); break;
|
||||
case "roundTrip": roundTrip(); break;
|
||||
case "damaged": damaged(); break;
|
||||
default: throw new AssertionError("Unknown test scenario");
|
||||
}
|
||||
System.out.println("PASS " + args[0]);
|
||||
}
|
||||
|
||||
private static long at(TimeZone zone, int year, int month, int day, int hour, int minute) {
|
||||
Calendar calendar = Calendar.getInstance(zone);
|
||||
calendar.clear();
|
||||
calendar.set(year, month - 1, day, hour, minute, 0);
|
||||
return calendar.getTimeInMillis();
|
||||
}
|
||||
|
||||
private static void defaults() {
|
||||
AutoFlameBook book = new AutoFlameBook();
|
||||
check(!book.enabled(), "The keeper is off until it is switched on");
|
||||
check(book.minute() == 12 * 60, "The default time is noon");
|
||||
check("🔥".equals(book.message()), "The default message is the flame");
|
||||
check(book.chats().isEmpty(), "No chat is written to until it is chosen");
|
||||
check(book.pending(at(MOSCOW, 2026, 10, 25, 13, 0), MOSCOW).isEmpty(), "Nothing is pending while it is off");
|
||||
}
|
||||
|
||||
private static void validation() {
|
||||
AutoFlameBook book = new AutoFlameBook();
|
||||
book.setMinute(0);
|
||||
book.setMinute(23 * 60 + 59);
|
||||
expectRefused(() -> book.setMinute(-1));
|
||||
expectRefused(() -> book.setMinute(24 * 60));
|
||||
check(book.minute() == 23 * 60 + 59, "A refused time leaves the old one");
|
||||
book.setMessage(" ✨🔥 ");
|
||||
check("✨🔥".equals(book.message()), "A message is trimmed");
|
||||
expectRefused(() -> book.setMessage(""));
|
||||
expectRefused(() -> book.setMessage(" "));
|
||||
expectRefused(() -> book.setMessage(null));
|
||||
expectRefused(() -> book.setMessage("two\nlines"));
|
||||
expectRefused(() -> book.setMessage("tab\there"));
|
||||
expectRefused(() -> book.setMessage(repeat("x", AutoFlameBook.MAX_MESSAGE + 1)));
|
||||
book.setMessage(repeat("x", AutoFlameBook.MAX_MESSAGE));
|
||||
check(book.message().length() == AutoFlameBook.MAX_MESSAGE, "The longest message is allowed");
|
||||
}
|
||||
|
||||
private static void chats() {
|
||||
AutoFlameBook book = new AutoFlameBook();
|
||||
check(book.setChat("111", true) && book.setChat("222", true), "Chats are added");
|
||||
check(book.chats().equals(Arrays.asList("111", "222")), "They keep the order they were chosen in");
|
||||
check(book.setChat("111", true) && book.chats().size() == 2, "Choosing a chat twice keeps one");
|
||||
check(!book.setChat("abc", true) && !book.setChat("", true) && !book.setChat(null, true), "Bad ids are refused");
|
||||
check(book.setChat("111", false) && !book.hasChat("111"), "A chat is removed");
|
||||
check(book.setChat("999", false), "Removing a chat that was never there is fine");
|
||||
AutoFlameBook full = new AutoFlameBook();
|
||||
for (int i = 1; i <= AutoFlameBook.MAX_CHATS; i++) check(full.setChat(String.valueOf(i), true), "Chat " + i);
|
||||
check(!full.setChat("1000", true), "The list stops at its limit");
|
||||
check(full.setChat("5", true), "A chat that is already in does not need room");
|
||||
check(full.setChat("5", false) && full.setChat("1000", true), "Removing one makes room again");
|
||||
}
|
||||
|
||||
private static void trigger() {
|
||||
AutoFlameBook book = new AutoFlameBook();
|
||||
long morning = at(MOSCOW, 2026, 10, 25, 9, 30);
|
||||
check(book.nextTrigger(morning, MOSCOW) == at(MOSCOW, 2026, 10, 25, 12, 0), "Before noon it is today at noon");
|
||||
long afternoon = at(MOSCOW, 2026, 10, 25, 15, 0);
|
||||
check(book.nextTrigger(afternoon, MOSCOW) == at(MOSCOW, 2026, 10, 26, 12, 0), "After noon it is tomorrow");
|
||||
long exactly = at(MOSCOW, 2026, 10, 25, 12, 0);
|
||||
check(book.nextTrigger(exactly, MOSCOW) == at(MOSCOW, 2026, 10, 26, 12, 0), "At noon sharp it is tomorrow");
|
||||
book.setMinute(7 * 60 + 5);
|
||||
check(book.nextTrigger(morning, MOSCOW) == at(MOSCOW, 2026, 10, 26, 7, 5), "Another time of day");
|
||||
long endOfMonth = at(MOSCOW, 2026, 10, 31, 23, 0);
|
||||
check(book.nextTrigger(endOfMonth, MOSCOW) == at(MOSCOW, 2026, 11, 1, 7, 5), "Over the end of a month");
|
||||
check(book.nextTrigger(endOfMonth, MOSCOW) > endOfMonth, "The trigger is always in the future");
|
||||
}
|
||||
|
||||
private static void due() {
|
||||
AutoFlameBook book = new AutoFlameBook();
|
||||
long before = at(MOSCOW, 2026, 10, 25, 11, 59);
|
||||
long sharp = at(MOSCOW, 2026, 10, 25, 12, 0);
|
||||
long late = at(MOSCOW, 2026, 10, 25, 23, 59);
|
||||
book.setChat("111", true);
|
||||
check(!book.due(sharp, MOSCOW), "Off: never due");
|
||||
book.setEnabled(true);
|
||||
check(!book.due(before, MOSCOW), "Not due before the time");
|
||||
check(book.pending(before, MOSCOW).isEmpty(), "Nothing to send before the time");
|
||||
check(book.due(sharp, MOSCOW), "Due at the time");
|
||||
check(book.due(late, MOSCOW), "Still due late in the day, so a late start catches up");
|
||||
check(book.pending(late, MOSCOW).equals(Arrays.asList("111")), "The chosen chat is pending");
|
||||
check(!book.due(at(MOSCOW, 2026, 10, 26, 0, 0), MOSCOW), "Not due again at midnight");
|
||||
}
|
||||
|
||||
private static void perDay() {
|
||||
AutoFlameBook book = new AutoFlameBook();
|
||||
book.setEnabled(true);
|
||||
book.setChat("111", true);
|
||||
book.setChat("222", true);
|
||||
long noon = at(MOSCOW, 2026, 10, 25, 12, 0);
|
||||
check(book.pending(noon, MOSCOW).equals(Arrays.asList("111", "222")), "Both are pending at first");
|
||||
book.markSent("111", noon, MOSCOW);
|
||||
check(book.pending(noon + 60000L, MOSCOW).equals(Arrays.asList("222")), "A chat written to is left alone");
|
||||
check(book.pending(at(MOSCOW, 2026, 10, 25, 20, 0), MOSCOW).equals(Arrays.asList("222")),
|
||||
"It stays left alone the rest of the day");
|
||||
List<String> tomorrow = book.pending(at(MOSCOW, 2026, 10, 26, 12, 1), MOSCOW);
|
||||
check(tomorrow.equals(Arrays.asList("111", "222")), "The next day both are pending again");
|
||||
long late = at(MOSCOW, 2026, 10, 25, 23, 50);
|
||||
book.markSent("222", late, MOSCOW);
|
||||
check(book.pending(at(MOSCOW, 2026, 10, 26, 12, 0), MOSCOW).equals(Arrays.asList("111", "222")),
|
||||
"A message sent just before midnight does not count for the next day");
|
||||
try {
|
||||
book.markSent("abc", noon, MOSCOW);
|
||||
throw new AssertionError("A bad id must be refused");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
// fine
|
||||
}
|
||||
// the same moment is a different day in another zone
|
||||
long moment = at(MOSCOW, 2026, 10, 25, 23, 30); // 20:30 UTC, 16:30 in New York
|
||||
check(AutoFlameBook.dayOf(moment, MOSCOW) != AutoFlameBook.dayOf(moment + 2 * 3600000L, MOSCOW),
|
||||
"Midnight in the zone starts a new day");
|
||||
}
|
||||
|
||||
private static void clockChange() {
|
||||
AutoFlameBook book = new AutoFlameBook();
|
||||
book.setMinute(2 * 60 + 30); // does not exist on 2026-03-08 in New York (02:00 jumps to 03:00)
|
||||
long before = at(NEW_YORK, 2026, 3, 8, 1, 0);
|
||||
long trigger = book.nextTrigger(before, NEW_YORK);
|
||||
check(trigger > before && trigger - before < 3L * 3600000L, "A skipped time still triggers within hours: " + (trigger - before));
|
||||
// the day after the change, noon is noon again
|
||||
AutoFlameBook noon = new AutoFlameBook();
|
||||
check(noon.nextTrigger(at(NEW_YORK, 2026, 3, 8, 13, 0), NEW_YORK) == at(NEW_YORK, 2026, 3, 9, 12, 0),
|
||||
"After the change the next noon is local noon");
|
||||
check(noon.nextTrigger(at(NEW_YORK, 2026, 10, 31, 13, 0), NEW_YORK) == at(NEW_YORK, 2026, 11, 1, 12, 0),
|
||||
"Across the autumn change the next noon is local noon");
|
||||
check(AutoFlameBook.minuteOf(at(NEW_YORK, 2026, 11, 1, 12, 0), NEW_YORK) == 12 * 60, "Minute of day follows the zone");
|
||||
check(AutoFlameBook.dayOf(at(NEW_YORK, 2026, 11, 1, 0, 30), NEW_YORK)
|
||||
== AutoFlameBook.dayOf(at(NEW_YORK, 2026, 11, 1, 23, 30), NEW_YORK), "The long day is one day");
|
||||
}
|
||||
|
||||
private static void roundTrip() {
|
||||
AutoFlameBook book = new AutoFlameBook();
|
||||
book.setEnabled(true);
|
||||
book.setMinute(18 * 60 + 45);
|
||||
book.setMessage("🔥 = a=b & c%d +");
|
||||
book.setChat("111", true);
|
||||
book.setChat("9223372036854775807", true);
|
||||
book.markSent("111", at(MOSCOW, 2026, 10, 25, 12, 0), MOSCOW);
|
||||
AutoFlameBook back = AutoFlameBook.decode(book.encode());
|
||||
check(back.enabled() && back.minute() == 18 * 60 + 45, "Switch and time survive the file");
|
||||
check(back.message().equals("🔥 = a=b & c%d +"), "A message with emoji and symbols survives, got " + back.message());
|
||||
check(back.chats().equals(book.chats()), "The chats survive in order");
|
||||
check(back.pending(at(MOSCOW, 2026, 10, 25, 19, 0), MOSCOW).equals(Arrays.asList("9223372036854775807")),
|
||||
"What was sent today is still known after the file");
|
||||
check(back.encode().equals(book.encode()), "Writing it again gives the same text");
|
||||
check(!AutoFlameBook.decode(null).enabled() && !AutoFlameBook.decode("").enabled(), "No file is the defaults");
|
||||
}
|
||||
|
||||
private static void damaged() {
|
||||
String text = "enabled=1\nminute=99999\nminute=abc\nmessage=%ZZ\nmessage=%0A\nchat=abc\nchat=\n"
|
||||
+ "garbage\n=x\nsent=abc:5\nsent=111:notanumber\nchat=222\nminute=600\n";
|
||||
AutoFlameBook book = AutoFlameBook.decode(text);
|
||||
check(book.enabled(), "A good line before the damage is kept");
|
||||
check(book.minute() == 600, "A good line after the damage is kept, got " + book.minute());
|
||||
check("🔥".equals(book.message()), "A bad message leaves the default");
|
||||
check(book.chats().equals(Arrays.asList("222")), "Only the good chat is kept");
|
||||
check(book.pending(at(MOSCOW, 2026, 10, 25, 12, 0), MOSCOW).equals(Arrays.asList("222")), "Bad sent lines are ignored");
|
||||
AutoFlameBook many = new AutoFlameBook();
|
||||
StringBuilder lines = new StringBuilder();
|
||||
for (int i = 1; i <= AutoFlameBook.MAX_CHATS + 10; i++) lines.append("chat=").append(i).append('\n');
|
||||
check(AutoFlameBook.decode(lines.toString()).chats().size() == AutoFlameBook.MAX_CHATS, "A long list is cut at the limit");
|
||||
check(many.chats().isEmpty(), "A fresh book is empty");
|
||||
}
|
||||
|
||||
private interface Action { void run(); }
|
||||
|
||||
private static void expectRefused(Action action) {
|
||||
try {
|
||||
action.run();
|
||||
} catch (IllegalArgumentException expected) {
|
||||
return;
|
||||
}
|
||||
throw new AssertionError("Should have been refused");
|
||||
}
|
||||
|
||||
private static String repeat(String text, int times) {
|
||||
StringBuilder out = new StringBuilder();
|
||||
for (int i = 0; i < times; i++) out.append(text);
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
private static void check(boolean condition, String message) {
|
||||
if (!condition) throw new AssertionError(message);
|
||||
}
|
||||
}
|
||||
75
tests/test_account_shapes.py
Normal file
75
tests/test_account_shapes.py
Normal file
@@ -0,0 +1,75 @@
|
||||
"""Run the per-account avatar shape book on a real JVM.
|
||||
|
||||
The book is plain Java (the Android part, AccountShapes, only keeps it in a private file), so the
|
||||
tests compile it with javac and run each scenario in its own process.
|
||||
"""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SOURCE = ROOT / "src" / "lihont" / "two" / "account" / "AccountShapeBook.java"
|
||||
HARNESS = ROOT / "tests" / "java" / "lihont" / "two" / "account" / "AccountShapeBookTest.java"
|
||||
|
||||
|
||||
class AccountShapeBookTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.javac = shutil.which("javac")
|
||||
cls.java = shutil.which("java")
|
||||
if not cls.javac or not cls.java:
|
||||
raise RuntimeError("Account shape tests require a JDK with java and javac")
|
||||
cls.temporary = tempfile.TemporaryDirectory(prefix="lihont-account-tests-")
|
||||
cls.addClassCleanup(cls.temporary.cleanup)
|
||||
cls.classes = Path(cls.temporary.name) / "classes"
|
||||
cls.classes.mkdir()
|
||||
cls.environment = dict(os.environ)
|
||||
cls.environment.pop("JAVA_TOOL_OPTIONS", None)
|
||||
cls.run_command([
|
||||
cls.javac, "--release", "17", "-encoding", "UTF-8", "-Xlint:all", "-Werror",
|
||||
"-d", str(cls.classes), str(SOURCE), str(HARNESS),
|
||||
])
|
||||
|
||||
@classmethod
|
||||
def run_command(cls, command):
|
||||
result = subprocess.run(
|
||||
command, capture_output=True, text=True, encoding="utf-8",
|
||||
env=cls.environment, timeout=120,
|
||||
)
|
||||
if result.returncode:
|
||||
raise AssertionError(
|
||||
f"Command failed with exit {result.returncode}: {command[0]}\n"
|
||||
+ result.stdout + result.stderr
|
||||
)
|
||||
return result
|
||||
|
||||
def run_scenario(self, name):
|
||||
result = self.run_command([
|
||||
self.java, "-cp", str(self.classes),
|
||||
"lihont.two.account.AccountShapeBookTest", name,
|
||||
])
|
||||
self.assertEqual(result.stdout.strip(), "PASS " + name)
|
||||
|
||||
def test_every_account_keeps_its_own_shape(self):
|
||||
self.run_scenario("perAccount")
|
||||
|
||||
def test_the_book_survives_the_file(self):
|
||||
self.run_scenario("roundTrip")
|
||||
|
||||
def test_a_damaged_file_loses_only_the_damaged_lines(self):
|
||||
self.run_scenario("damaged")
|
||||
|
||||
def test_bad_ids_and_names_are_refused(self):
|
||||
self.run_scenario("invalid")
|
||||
|
||||
def test_the_old_single_shape_goes_to_the_first_known_account_once(self):
|
||||
self.run_scenario("migrate")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
50
tests/test_attr_ids.py
Normal file
50
tests/test_attr_ids.py
Normal file
@@ -0,0 +1,50 @@
|
||||
"""Every framework attribute id in lihont.axml.ATTR_IDS is the one android.jar defines (a wrong id is silently ignored by Android)."""
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from lihont.axml import ATTR_IDS
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SOURCE = """
|
||||
import java.io.File;
|
||||
import java.net.URL;
|
||||
import java.net.URLClassLoader;
|
||||
|
||||
public class Ids {
|
||||
public static void main(String[] args) throws Exception {
|
||||
URLClassLoader loader = new URLClassLoader(new URL[] {new File(args[0]).toURI().toURL()}, null);
|
||||
Class<?> attr = loader.loadClass("android.R$attr");
|
||||
for (int i = 1; i < args.length; i++) {
|
||||
System.out.println(args[i] + " " + attr.getField(args[i]).getInt(null));
|
||||
}
|
||||
}
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
class AttributeIdsTest(unittest.TestCase):
|
||||
def test_every_id_matches_android_jar(self):
|
||||
javac, java = shutil.which("javac"), shutil.which("java")
|
||||
jar = ROOT / "tools" / "android.jar"
|
||||
if not javac or not java or not jar.is_file():
|
||||
self.skipTest("needs a JDK and tools/android.jar")
|
||||
with tempfile.TemporaryDirectory(prefix="lihont-attrs-") as out:
|
||||
Path(out, "Ids.java").write_text(SOURCE, encoding="utf-8")
|
||||
subprocess.run([javac, "-d", out, str(Path(out, "Ids.java"))], check=True, capture_output=True)
|
||||
env = dict(os.environ)
|
||||
env.pop("JAVA_TOOL_OPTIONS", None)
|
||||
result = subprocess.run([java, "-cp", out, "Ids", str(jar)] + sorted(ATTR_IDS),
|
||||
capture_output=True, text=True, timeout=60, env=env)
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
defined = {line.split()[0]: int(line.split()[1]) & 0xFFFFFFFF for line in result.stdout.splitlines()}
|
||||
wrong = {name: (hex(ATTR_IDS[name]), hex(defined[name])) for name in ATTR_IDS if ATTR_IDS[name] != defined[name]}
|
||||
self.assertEqual({}, wrong, "ids that differ from android.jar: " + repr(wrong))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
87
tests/test_auto_flame.py
Normal file
87
tests/test_auto_flame.py
Normal file
@@ -0,0 +1,87 @@
|
||||
"""Run the streak keeper's settings and day bookkeeping on a real JVM.
|
||||
|
||||
The book is plain Java (the Android parts only store it and send with it), so the tests compile it with
|
||||
javac and run each scenario in its own process.
|
||||
"""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SOURCE = ROOT / "src" / "lihont" / "two" / "streak" / "AutoFlameBook.java"
|
||||
HARNESS = ROOT / "tests" / "java" / "lihont" / "two" / "streak" / "AutoFlameBookTest.java"
|
||||
|
||||
|
||||
class AutoFlameBookTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.javac = shutil.which("javac")
|
||||
cls.java = shutil.which("java")
|
||||
if not cls.javac or not cls.java:
|
||||
raise RuntimeError("Streak keeper tests require a JDK with java and javac")
|
||||
cls.temporary = tempfile.TemporaryDirectory(prefix="lihont-streak-tests-")
|
||||
cls.addClassCleanup(cls.temporary.cleanup)
|
||||
cls.classes = Path(cls.temporary.name) / "classes"
|
||||
cls.classes.mkdir()
|
||||
cls.environment = dict(os.environ)
|
||||
cls.environment.pop("JAVA_TOOL_OPTIONS", None)
|
||||
cls.run_command([
|
||||
cls.javac, "--release", "17", "-encoding", "UTF-8", "-Xlint:all", "-Werror",
|
||||
"-d", str(cls.classes), str(SOURCE), str(HARNESS),
|
||||
])
|
||||
|
||||
@classmethod
|
||||
def run_command(cls, command):
|
||||
result = subprocess.run(
|
||||
command, capture_output=True, text=True, encoding="utf-8",
|
||||
env=cls.environment, timeout=120,
|
||||
)
|
||||
if result.returncode:
|
||||
raise AssertionError(
|
||||
f"Command failed with exit {result.returncode}: {command[0]}\n"
|
||||
+ result.stdout + result.stderr
|
||||
)
|
||||
return result
|
||||
|
||||
def run_scenario(self, name):
|
||||
result = self.run_command([
|
||||
self.java, "-Dfile.encoding=UTF-8", "-cp", str(self.classes),
|
||||
"lihont.two.streak.AutoFlameBookTest", name,
|
||||
])
|
||||
self.assertEqual(result.stdout.strip(), "PASS " + name)
|
||||
|
||||
def test_defaults_are_off_noon_and_the_flame(self):
|
||||
self.run_scenario("defaults")
|
||||
|
||||
def test_time_and_message_are_validated(self):
|
||||
self.run_scenario("validation")
|
||||
|
||||
def test_chat_list_has_a_limit_and_an_order(self):
|
||||
self.run_scenario("chats")
|
||||
|
||||
def test_next_trigger_is_the_next_chosen_time(self):
|
||||
self.run_scenario("trigger")
|
||||
|
||||
def test_due_from_the_chosen_time_until_the_end_of_the_day(self):
|
||||
self.run_scenario("due")
|
||||
|
||||
def test_a_chat_is_written_to_once_a_day(self):
|
||||
self.run_scenario("perDay")
|
||||
|
||||
def test_the_change_of_the_clock_does_not_break_the_day(self):
|
||||
self.run_scenario("clockChange")
|
||||
|
||||
def test_everything_survives_the_file(self):
|
||||
self.run_scenario("roundTrip")
|
||||
|
||||
def test_a_damaged_file_loses_only_the_damaged_lines(self):
|
||||
self.run_scenario("damaged")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
58
tests/test_black_rule.py
Normal file
58
tests/test_black_rule.py
Normal file
@@ -0,0 +1,58 @@
|
||||
"""Run the "what is black" rule of the tonal-surface skin on a real JVM."""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SOURCE = ROOT / "src" / "lihont" / "two" / "look" / "BlackRule.java"
|
||||
HARNESS = ROOT / "tests" / "java" / "lihont" / "two" / "look" / "BlackRuleTest.java"
|
||||
|
||||
|
||||
class BlackRuleTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.javac = shutil.which("javac")
|
||||
cls.java = shutil.which("java")
|
||||
if not cls.javac or not cls.java:
|
||||
raise RuntimeError("Black rule tests require a JDK with java and javac")
|
||||
cls.temporary = tempfile.TemporaryDirectory(prefix="lihont-black-tests-")
|
||||
cls.addClassCleanup(cls.temporary.cleanup)
|
||||
cls.classes = Path(cls.temporary.name) / "classes"
|
||||
cls.classes.mkdir()
|
||||
cls.environment = dict(os.environ)
|
||||
cls.environment.pop("JAVA_TOOL_OPTIONS", None)
|
||||
cls.run_command([
|
||||
cls.javac, "--release", "17", "-encoding", "UTF-8", "-Xlint:all", "-Werror",
|
||||
"-d", str(cls.classes), str(SOURCE), str(HARNESS),
|
||||
])
|
||||
|
||||
@classmethod
|
||||
def run_command(cls, command):
|
||||
result = subprocess.run(command, capture_output=True, text=True, encoding="utf-8",
|
||||
env=cls.environment, timeout=120)
|
||||
if result.returncode:
|
||||
raise AssertionError(f"Command failed with exit {result.returncode}: {command[0]}\n"
|
||||
+ result.stdout + result.stderr)
|
||||
return result
|
||||
|
||||
def run_scenario(self, name):
|
||||
result = self.run_command([self.java, "-cp", str(self.classes), "lihont.two.look.BlackRuleTest", name])
|
||||
self.assertEqual(result.stdout.strip(), "PASS " + name)
|
||||
|
||||
def test_black_and_almost_black(self):
|
||||
self.run_scenario("black")
|
||||
|
||||
def test_scrims_greys_and_colours_are_left_alone(self):
|
||||
self.run_scenario("notBlack")
|
||||
|
||||
def test_the_skin_does_not_repaint_its_own_colours(self):
|
||||
self.run_scenario("surfaces")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
29
tests/test_dex_slot.py
Normal file
29
tests/test_dex_slot.py
Normal file
@@ -0,0 +1,29 @@
|
||||
"""The runtime gets a dex of its own: the one after the last of TikTok's, never over a gap."""
|
||||
|
||||
import unittest
|
||||
|
||||
from lihont.upgrade import next_dex_name
|
||||
|
||||
|
||||
class NextDexNameTest(unittest.TestCase):
|
||||
def test_the_next_dex_follows_the_last_one(self):
|
||||
names = ["classes.dex"] + ["classes%d.dex" % n for n in range(2, 54)] + ["AndroidManifest.xml", "res/a.png"]
|
||||
self.assertEqual("classes54.dex", next_dex_name(names))
|
||||
|
||||
def test_the_second_dex_follows_a_single_one(self):
|
||||
self.assertEqual("classes2.dex", next_dex_name(["classes.dex", "assets/x.dex.json"]))
|
||||
|
||||
def test_a_gap_in_the_row_is_refused(self):
|
||||
with self.assertRaises(ValueError):
|
||||
next_dex_name(["classes.dex", "classes2.dex", "classes4.dex"])
|
||||
|
||||
def test_no_dex_at_all_is_refused(self):
|
||||
with self.assertRaises(ValueError):
|
||||
next_dex_name(["AndroidManifest.xml"])
|
||||
|
||||
def test_other_files_that_look_alike_do_not_count(self):
|
||||
self.assertEqual("classes3.dex", next_dex_name(["classes.dex", "classes2.dex", "classes9.dex.bak", "lib/classes7.dex"]))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
64
tests/test_streak_patch.py
Normal file
64
tests/test_streak_patch.py
Normal file
@@ -0,0 +1,64 @@
|
||||
import unittest
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
from lihont import streak_patch, widget_patch
|
||||
from lihont.axml import Axml, RES_XML_END_ELEMENT
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
APKS = sorted((ROOT / "OriginalAPKtiktok").glob("*.apk")) if (ROOT / "OriginalAPKtiktok").is_dir() else []
|
||||
|
||||
|
||||
class FakeApk:
|
||||
"""Just enough of lihont.apkzip.Apk: reads from the original apk, remembers what is replaced."""
|
||||
|
||||
def __init__(self, path):
|
||||
self.zip = zipfile.ZipFile(path)
|
||||
self.replaced = {}
|
||||
|
||||
def read(self, name):
|
||||
return self.replaced.get(name) or self.zip.read(name)
|
||||
|
||||
def replace(self, name, data):
|
||||
self.replaced[name] = data
|
||||
|
||||
|
||||
@unittest.skipUnless(APKS, "the original TikTok apk is not in OriginalAPKtiktok/")
|
||||
class StreakPatchTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.apk = FakeApk(APKS[0])
|
||||
self.xml = Axml.parse(self.apk.read("AndroidManifest.xml"))
|
||||
|
||||
def test_the_alarm_receiver_is_declared_and_private(self):
|
||||
report = streak_patch.apply(self.apk, self.xml)
|
||||
rebuilt = Axml.parse(self.apk.replaced["AndroidManifest.xml"])
|
||||
nodes = [n for n in rebuilt.elements("receiver") if rebuilt.attr_string(n, "name") == streak_patch.RECEIVER]
|
||||
self.assertEqual(1, len(nodes))
|
||||
self.assertEqual(0, rebuilt.attr(nodes[0], "exported").data, "no other app can reach it")
|
||||
self.assertEqual({"receiver": streak_patch.RECEIVER, "exported": False}, report)
|
||||
ids = [rebuilt.resource_map[a.name] for a in nodes[0].attributes]
|
||||
self.assertEqual(sorted(ids), ids, "the attributes stay in ascending id order")
|
||||
|
||||
def test_it_has_no_intent_filter(self):
|
||||
streak_patch.apply(self.apk, self.xml)
|
||||
rebuilt = Axml.parse(self.apk.replaced["AndroidManifest.xml"])
|
||||
node = next(n for n in rebuilt.elements("receiver") if rebuilt.attr_string(n, "name") == streak_patch.RECEIVER)
|
||||
following = rebuilt.nodes[rebuilt.nodes.index(node) + 1]
|
||||
self.assertEqual(RES_XML_END_ELEMENT, following.kind, "the receiver closes right away: no intent filter")
|
||||
|
||||
def test_a_second_pass_is_refused(self):
|
||||
streak_patch.apply(self.apk, self.xml)
|
||||
with self.assertRaises(streak_patch.StreakError):
|
||||
streak_patch.apply(self.apk, self.xml)
|
||||
|
||||
def test_it_sits_next_to_the_widget_changes(self):
|
||||
widget_patch.apply(self.apk, self.xml, 0x7F120364)
|
||||
streak_patch.apply(self.apk, self.xml)
|
||||
rebuilt = Axml.parse(self.apk.replaced["AndroidManifest.xml"])
|
||||
names = {rebuilt.attr_string(n, "name") for n in rebuilt.elements("receiver")}
|
||||
self.assertIn(streak_patch.RECEIVER, names)
|
||||
self.assertIn("lihont.two.widget.StreakWidget1", names)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
173
tests/test_widget_patch.py
Normal file
173
tests/test_widget_patch.py
Normal file
@@ -0,0 +1,173 @@
|
||||
import unittest
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
from lihont import manifest as manifest_module
|
||||
from lihont import widget_patch
|
||||
from lihont.axml import Axml, RES_XML_END_ELEMENT, RES_XML_START_ELEMENT
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
APKS = sorted((ROOT / "OriginalAPKtiktok").glob("*.apk")) if (ROOT / "OriginalAPKtiktok").is_dir() else []
|
||||
|
||||
|
||||
class FakeApk:
|
||||
"""Just enough of lihont.apkzip.Apk: reads from the original apk, remembers what is replaced."""
|
||||
|
||||
def __init__(self, path):
|
||||
self.zip = zipfile.ZipFile(path)
|
||||
self.replaced = {}
|
||||
|
||||
def read(self, name):
|
||||
return self.replaced.get(name) or self.zip.read(name)
|
||||
|
||||
def replace(self, name, data):
|
||||
self.replaced[name] = data
|
||||
|
||||
|
||||
def provider_node(axml):
|
||||
return next(n for n in axml.nodes
|
||||
if n.kind == RES_XML_START_ELEMENT and axml.pool.get(n.name) == "appwidget-provider")
|
||||
|
||||
|
||||
@unittest.skipUnless(APKS, "the original TikTok apk is not in OriginalAPKtiktok/")
|
||||
class WidgetPatchTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.apk = FakeApk(APKS[0])
|
||||
self.xml = Axml.parse(self.apk.read("AndroidManifest.xml"))
|
||||
|
||||
def receivers(self, xml):
|
||||
return {xml.attr_string(n, "name"): n for n in xml.elements("receiver")}
|
||||
|
||||
def test_four_widgets_become_ours_with_one_name(self):
|
||||
report = widget_patch.apply(self.apk, self.xml, 0x7F120364)
|
||||
rebuilt = Axml.parse(self.apk.replaced["AndroidManifest.xml"])
|
||||
receivers = self.receivers(rebuilt)
|
||||
for size in widget_patch.SIZES:
|
||||
self.assertIn(size.widget, receivers)
|
||||
self.assertNotIn(size.original, receivers)
|
||||
self.assertEqual(widget_patch.LABEL, rebuilt.attr_string(receivers[size.widget], "label"))
|
||||
self.assertEqual({"1x1", "2x2", "3x3", "4x4"}, set(report["receivers"]))
|
||||
|
||||
def test_the_configuration_screen_is_declared_and_exported(self):
|
||||
widget_patch.apply(self.apk, self.xml, 0x7F120364)
|
||||
rebuilt = Axml.parse(self.apk.replaced["AndroidManifest.xml"])
|
||||
self.assertTrue(manifest_module.has_activity(rebuilt, widget_patch.CONFIG_CLASS))
|
||||
node = next(n for n in rebuilt.elements("activity")
|
||||
if rebuilt.attr_string(n, "name") == widget_patch.CONFIG_CLASS)
|
||||
self.assertNotEqual(0, rebuilt.attr(node, "exported").data)
|
||||
actions = [rebuilt.attr_string(n, "name") for n in rebuilt.elements("action")]
|
||||
self.assertIn(widget_patch.CONFIGURE_ACTION, actions)
|
||||
|
||||
def test_every_provider_has_its_size_its_layout_and_can_be_resized(self):
|
||||
widget_patch.apply(self.apk, self.xml, 0x7F120364)
|
||||
for size in widget_patch.SIZES:
|
||||
provider = Axml.parse(self.apk.replaced[size.provider])
|
||||
node = provider_node(provider)
|
||||
self.assertEqual(widget_patch.CONFIG_CLASS, provider.attr_string(node, "configure"))
|
||||
self.assertEqual(size.cells, provider.attr(node, "targetCellWidth").data)
|
||||
self.assertEqual(size.cells, provider.attr(node, "targetCellHeight").data)
|
||||
self.assertEqual(widget_patch.dp(widget_patch.cell_dp(size.cells)), provider.attr(node, "minWidth").data)
|
||||
self.assertEqual(widget_patch.LAYOUT, provider.attr(node, "initialLayout").data)
|
||||
self.assertEqual(3, provider.attr(node, "resizeMode").data)
|
||||
self.assertEqual(widget_patch.dp(40), provider.attr(node, "minResizeWidth").data)
|
||||
self.assertIsNone(provider.attr(node, "description"))
|
||||
self.assertIsNone(provider.attr(node, "previewLayout"))
|
||||
|
||||
def test_provider_attributes_stay_in_ascending_id_order(self):
|
||||
# Android reads the attributes side by side with its own sorted list and skips what is out of
|
||||
# order; with widgetCategory ahead of resizeMode the launcher saw a widget that could not be resized
|
||||
widget_patch.apply(self.apk, self.xml, 0x7F120364)
|
||||
for size in widget_patch.SIZES:
|
||||
provider = Axml.parse(self.apk.replaced[size.provider])
|
||||
node = provider_node(provider)
|
||||
ids = [provider.resource_map[a.name] for a in node.attributes]
|
||||
self.assertEqual(sorted(ids), ids, size.provider)
|
||||
self.assertEqual(len(ids), len(set(ids)), "an attribute is written twice in " + size.provider)
|
||||
|
||||
def test_the_layout_fills_the_widget_instead_of_a_fixed_square(self):
|
||||
widget_patch.apply(self.apk, self.xml, 0x7F120364)
|
||||
layout = Axml.parse(self.apk.replaced[widget_patch.LAYOUT_FILE])
|
||||
elements = [n for n in layout.nodes if n.kind == RES_XML_START_ELEMENT]
|
||||
picture = next(n for n in elements if layout.pool.get(n.name) == "ImageView")
|
||||
for node in (elements[0], picture):
|
||||
for resource_id in (widget_patch.ATTR_LAYOUT_WIDTH, widget_patch.ATTR_LAYOUT_HEIGHT):
|
||||
attr = widget_patch._attr_by_id(layout, node, resource_id)
|
||||
self.assertEqual(widget_patch.MATCH_PARENT, attr.data)
|
||||
# the picture view of TikTok's layout is still the one the widget draws into
|
||||
self.assertEqual(widget_patch.PICTURE,
|
||||
widget_patch._attr_by_id(layout, picture, widget_patch.ATTR_ID).data)
|
||||
|
||||
def test_the_layout_flips_between_four_pictures_by_itself(self):
|
||||
widget_patch.apply(self.apk, self.xml, 0x7F120364)
|
||||
layout = Axml.parse(self.apk.replaced[widget_patch.LAYOUT_FILE])
|
||||
starts = [n for n in layout.nodes if n.kind == RES_XML_START_ELEMENT]
|
||||
ends = [n for n in layout.nodes if n.kind == RES_XML_END_ELEMENT]
|
||||
self.assertEqual(len(starts), len(ends), "every element is closed")
|
||||
names = [layout.pool.get(n.name) for n in starts]
|
||||
self.assertEqual(["RelativeLayout", "ViewFlipper", "ImageView", "ImageView", "ImageView", "ImageView"], names[:6])
|
||||
|
||||
flipper = starts[1]
|
||||
flipper_ids = [layout.resource_map[a.name] for a in flipper.attributes]
|
||||
self.assertEqual(sorted(flipper_ids), flipper_ids, "the flipper's attributes are in ascending id order")
|
||||
by_id = {layout.resource_map[a.name]: a for a in flipper.attributes}
|
||||
self.assertEqual(widget_patch.FLIPPER_VIEW, by_id[widget_patch.ATTR_ID].data)
|
||||
self.assertEqual(0xFFFFFFFF, by_id[0x010102B5].data, "it starts flipping on its own")
|
||||
self.assertEqual(widget_patch.FLIP_INTERVAL_MS, by_id[0x01010179].data)
|
||||
self.assertEqual(widget_patch.ANIM_FADE_IN, by_id[0x01010177].data)
|
||||
self.assertEqual(widget_patch.ANIM_FADE_OUT, by_id[0x01010178].data)
|
||||
|
||||
# the old picture view is the first frame; the three new ones copy it with ids of their own
|
||||
frames = starts[2:6]
|
||||
got = [widget_patch._attr_by_id(layout, f, widget_patch.ATTR_ID).data for f in frames]
|
||||
self.assertEqual([widget_patch.PICTURE] + list(widget_patch.FRAME_VIEWS), got)
|
||||
sizes = {tuple(widget_patch._attr_by_id(layout, f, rid).data
|
||||
for rid in (widget_patch.ATTR_LAYOUT_WIDTH, widget_patch.ATTR_LAYOUT_HEIGHT)) for f in frames}
|
||||
self.assertEqual({(widget_patch.MATCH_PARENT, widget_patch.MATCH_PARENT)}, sizes)
|
||||
# the hidden badge and label views of TikTok's layout are still there
|
||||
self.assertIn("FrameLayout", names)
|
||||
self.assertIn("TextView", names)
|
||||
|
||||
def test_the_java_side_uses_the_same_view_ids(self):
|
||||
source = (ROOT / "src" / "lihont" / "two" / "widget" / "StreakWidget.java").read_text(encoding="utf-8")
|
||||
import re
|
||||
picture = int(re.search(r"PICTURE\s*=\s*(0x[0-9A-Fa-f]+)", source).group(1), 16)
|
||||
frames = re.search(r"FRAME_VIEWS\s*=\s*\{([^}]*)\}", source).group(1)
|
||||
self.assertEqual(widget_patch.PICTURE, picture)
|
||||
self.assertEqual(list(widget_patch.FRAME_VIEWS), [int(h, 16) for h in re.findall(r"0x[0-9A-Fa-f]+", frames)])
|
||||
|
||||
def test_the_widget_list_shows_our_flower_instead_of_tiktoks_pictures(self):
|
||||
report = widget_patch.apply(self.apk, self.xml, 0x7F120364)
|
||||
picture = widget_patch.preview_asset().read_bytes()
|
||||
self.assertTrue(picture.startswith(b"\x89PNG"))
|
||||
# the pictures of 47.1.3's own widgets: a nine-patch, a webp and a png
|
||||
self.assertEqual(["res/c/i2.9.png", "res/c/i6.png", "res/c/i9.webp"], report["previews"])
|
||||
for path in report["previews"]:
|
||||
self.assertEqual(picture, self.apk.replaced[path])
|
||||
|
||||
def test_a_layout_that_is_not_the_expected_one_is_refused(self):
|
||||
layout = Axml.parse(self.apk.read("res/b/pr.xml"))
|
||||
for node in layout.nodes:
|
||||
if node.kind == RES_XML_START_ELEMENT and layout.pool.get(node.name) == "ImageView":
|
||||
node.name = layout.pool.index("TextView")
|
||||
with self.assertRaises(widget_patch.WidgetError):
|
||||
widget_patch.fill_layout(layout)
|
||||
|
||||
def test_a_second_pass_is_refused(self):
|
||||
widget_patch.apply(self.apk, self.xml, 0x7F120364)
|
||||
with self.assertRaises(widget_patch.WidgetError):
|
||||
widget_patch.apply(self.apk, self.xml, 0x7F120364)
|
||||
|
||||
def test_a_manifest_without_the_widget_is_refused(self):
|
||||
for node in self.xml.elements("receiver"):
|
||||
if self.xml.attr_string(node, "name") == widget_patch.SIZES[0].original:
|
||||
self.xml.set_attr_string(node, "name", "x.Other")
|
||||
with self.assertRaises(widget_patch.WidgetError):
|
||||
widget_patch.apply(self.apk, self.xml, 0x7F120364)
|
||||
|
||||
def test_cells_are_sized_the_way_launchers_count_them(self):
|
||||
self.assertEqual([40, 110, 180, 250], [widget_patch.cell_dp(n) for n in (1, 2, 3, 4)])
|
||||
self.assertEqual(0x6E01, widget_patch.dp(110))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user