diff --git a/lihont/axml.py b/lihont/axml.py index bad8d79..d2c50bd 100644 --- a/lihont/axml.py +++ b/lihont/axml.py @@ -1,509 +1,538 @@ -"""Binary XML (AXML) read and write. - -Android's compiled XML is a handful of chunks: a string pool, a map from -attribute name to framework resource id, and a flat stream of start/end nodes. -This module parses that into objects, lets you edit them, and writes it back. - -Nothing here rebuilds resources.arsc, so every id an attribute refers to has to -be an id the apk already has. Strings are different: the pool is ours to append -to, and appended strings never disturb the indices already in use -- which is -what keeps the resource map (aligned with the first N pool entries) valid. -""" - -from __future__ import annotations - -import struct -from typing import List, Optional - -# chunk types -RES_STRING_POOL = 0x0001 -RES_XML = 0x0003 -RES_XML_START_NAMESPACE = 0x0100 -RES_XML_END_NAMESPACE = 0x0101 -RES_XML_START_ELEMENT = 0x0102 -RES_XML_END_ELEMENT = 0x0103 -RES_XML_CDATA = 0x0104 -RES_XML_RESOURCE_MAP = 0x0180 - -# Res_value types -TYPE_NULL = 0x00 -TYPE_REFERENCE = 0x01 -TYPE_STRING = 0x03 -TYPE_INT_BOOLEAN = 0x12 - -ANDROID_NS = "http://schemas.android.com/apk/res/android" - -# The framework attributes we need to be able to write. These never change -- -# they are public ids, fixed the day each one shipped -- and the build checks -# every one of them against android.jar rather than trusting this table. -ATTR_IDS = { - "theme": 0x01010000, - "label": 0x01010001, - "icon": 0x01010002, - "name": 0x01010003, - "exported": 0x01010010, - "enabled": 0x0101000E, - "configChanges": 0x0101001F, - "launchMode": 0x0101001D, - "roundIcon": 0x0101052C, - "authorities": 0x01010018, - # 16842779, read out of android.jar rather than written down: the build - # checks every one of these against it and stops on a disagreement - "grantUriPermissions": 0x0101001B, - "targetActivity": 0x01010202, - "taskAffinity": 0x01010012, - "minSdkVersion": 0x0101020C, - "drawable": 0x01010199, - "value": 0x01010024, - "scheme": 0x01010027, - "host": 0x01010028, -} - -NO_ENTRY = 0xFFFFFFFF - - -class AxmlError(Exception): - pass - - -# --------------------------------------------------------------- string pool - - -class StringPool: - """The pool of every string the file mentions, in its original order. - - Strings are appended, never reordered or removed: every node and every - entry of the resource map refers to a string by index. - """ - - SORTED = 1 << 0 - UTF8 = 1 << 8 - - def __init__(self, strings: List[str], flags: int, styles: bytes, style_offsets: List[int]): - self.strings = strings - # a sorted pool stops being sorted the moment we append to it, and - # nothing in a manifest relies on the flag - self.flags = flags & ~self.SORTED - self.styles = styles - self.style_offsets = style_offsets - - @property - def utf8(self) -> bool: - return bool(self.flags & self.UTF8) - - def index(self, value: str) -> int: - """The index of `value`, appending it to the pool if it is new.""" - try: - return self.strings.index(value) - except ValueError: - self.strings.append(value) - return len(self.strings) - 1 - - def get(self, index: int) -> Optional[str]: - if index == NO_ENTRY or index < 0 or index >= len(self.strings): - return None - return self.strings[index] - - # -- parsing - - @classmethod - def parse(cls, data: bytes, start: int) -> "StringPool": - kind, header_size, size = struct.unpack_from(" bytes: - offsets = [] - blob = bytearray() - seen = {} - for s in self.strings: - if s in seen: - offsets.append(seen[s]) - continue - seen[s] = len(blob) - offsets.append(len(blob)) - blob += _write_string(s, self.utf8) - while len(blob) % 4: - blob.append(0) - - header_size = 28 - strings_start = header_size + 4 * len(offsets) + 4 * len(self.style_offsets) - styles_start = (strings_start + len(blob)) if self.styles else 0 - size = strings_start + len(blob) + len(self.styles) - - out = bytearray() - out += struct.pack(" str: - if utf8: - _chars, pos = _read_len(data, pos, True) # length in utf-16 units, unused - nbytes, pos = _read_len(data, pos, True) - return data[pos : pos + nbytes].decode("utf-8", "replace") - nchars, pos = _read_len(data, pos, False) - return data[pos : pos + nchars * 2].decode("utf-16-le", "replace") - - -def _write_len(value: int, utf8: bool) -> bytes: - if utf8: - if value > 0x7F: - return bytes([0x80 | ((value >> 8) & 0x7F), value & 0xFF]) - return bytes([value]) - if value > 0x7FFF: - return struct.pack("> 16) & 0x7FFF), value & 0xFFFF) - return struct.pack(" bytes: - if utf8: - raw = value.encode("utf-8") - chars = len(value.encode("utf-16-le")) // 2 - return _write_len(chars, True) + _write_len(len(raw), True) + raw + b"\x00" - raw = value.encode("utf-16-le") - return _write_len(len(raw) // 2, False) + raw + b"\x00\x00" - - -# --------------------------------------------------------------------- nodes - - -class Attribute: - def __init__(self, ns: int, name: int, raw: int, size: int, res0: int, kind: int, data: int): - self.ns = ns - self.name = name - self.raw = raw - self.size = size - self.res0 = res0 - self.kind = kind - self.data = data - - def pack(self) -> bytes: - return struct.pack( - " bytes: - body = bytearray() - if self.kind in (RES_XML_START_NAMESPACE, RES_XML_END_NAMESPACE): - body += struct.pack(" "Axml": - kind, header_size, _size = struct.unpack_from(" bytes: - body = bytearray() - body += self.pool.build() - if self.resource_map: - size = 8 + 4 * len(self.resource_map) - body += struct.pack(" Optional[str]: - return self.pool.get(index) - - def elements(self, name: str) -> List[Node]: - return [ - n - for n in self.nodes - if n.kind == RES_XML_START_ELEMENT and self.pool.get(n.name) == name - ] - - def attr(self, node: Node, name: str) -> Optional[Attribute]: - for a in node.attributes: - if self.pool.get(a.name) == name and self.pool.get(a.ns) in (ANDROID_NS, None): - return a - return None - - def attr_string(self, node: Node, name: str) -> Optional[str]: - a = self.attr(node, name) - if a is None: - return None - if a.kind == TYPE_STRING: - return self.pool.get(a.data) - return self.pool.get(a.raw) - - # -- editing - - def attribute_name_index(self, name: str) -> int: - """The pool index for an `android:` attribute name. - - The resource map runs parallel to the first entries of the pool, so an - attribute name has to sit at the index whose map entry is its id. An - attribute the file already uses is simply found there. One it does not - is inserted at the end of the map -- in the middle of the pool -- and - every index above it is shifted up to match. - """ - if name not in ATTR_IDS: - raise AxmlError("unknown framework attribute: %s" % name) - wanted = ATTR_IDS[name] - for i, rid in enumerate(self.resource_map): - if rid == wanted: - if self.pool.get(i) != name: - raise AxmlError( - "resource map says %d is %s, the pool says %r" - % (i, name, self.pool.get(i)) - ) - return i - - at = len(self.resource_map) - self.pool.strings.insert(at, name) - self.resource_map.append(wanted) - self._shift_indices(at) - return at - - def _shift_indices(self, at: int) -> None: - """Move every string reference at or above `at` up by one.""" - - def bump(index: int) -> int: - return index + 1 if index != NO_ENTRY and index >= at else index - - seen = set() - for node in self.nodes + self.pending: - if id(node) in seen: - continue - seen.add(id(node)) - if node.kind in (RES_XML_START_NAMESPACE, RES_XML_END_NAMESPACE): - node.prefix = bump(node.prefix) - node.uri = bump(node.uri) - continue - node.ns = bump(node.ns) - node.name = bump(node.name) - for a in node.attributes: - a.ns = bump(a.ns) - a.name = bump(a.name) - a.raw = bump(a.raw) - if a.kind == TYPE_STRING: - a.data = bump(a.data) - if node.kind == RES_XML_CDATA and len(node.tail) == 8: - size, res0, kind, data = struct.unpack(" None: - """Set an `android:` attribute, replacing it if the element has it.""" - name_index = self.attribute_name_index(name) - ns_index = self.pool.index(ANDROID_NS) - existing = self.attr(node, name) - if existing is not None: - existing.ns = ns_index - existing.name = name_index - existing.raw = raw - existing.size = 8 - existing.res0 = 0 - existing.kind = kind - existing.data = data - return - attr = Attribute(ns_index, name_index, raw, 8, 0, kind, data) - # attributes are expected in ascending resource-id order - ids = [ATTR_IDS.get(self.pool.get(a.name) or "", 0) for a in node.attributes] - where = len(node.attributes) - for i, rid in enumerate(ids): - if rid and rid > ATTR_IDS[name]: - where = i - break - node.attributes.insert(where, attr) - - def set_attr_string(self, node: Node, name: str, value: str) -> None: - # the attribute's own name goes in first: adding one renumbers the pool - # from the end of the resource map up, and a value index looked up - # before that would be pointing one string to the left afterwards - self.attribute_name_index(name) - index = self.pool.index(value) - self.set_attr(node, name, TYPE_STRING, index, raw=index) - - def set_attr_bool(self, node: Node, name: str, value: bool) -> None: - self.set_attr(node, name, TYPE_INT_BOOLEAN, 0xFFFFFFFF if value else 0) - - def set_attr_ref(self, node: Node, name: str, res_id: int) -> None: - self.set_attr(node, name, TYPE_REFERENCE, res_id) - - def make_element(self, name: str) -> Node: - node = Node(RES_XML_START_ELEMENT, 0, NO_ENTRY) - node.ns = NO_ENTRY - node.name = self.pool.index(name) - self.pending.append(node) - return node - - def close_element(self, start: Node) -> Node: - node = Node(RES_XML_END_ELEMENT, 0, NO_ENTRY) - node.ns = start.ns - node.name = start.name - self.pending.append(node) - return node - - def insert_into(self, parent: Node, subtree: List[Node]) -> None: - """Put a subtree in as the last child of `parent`.""" - depth = 0 - for i in range(self.nodes.index(parent) + 1, len(self.nodes)): - node = self.nodes[i] - if node.kind == RES_XML_START_ELEMENT: - depth += 1 - elif node.kind == RES_XML_END_ELEMENT: - if depth == 0: - self.nodes[i:i] = subtree - return - depth -= 1 - raise AxmlError("element has no end tag") - - -def _parse_node(data: bytes, pos: int, ctype: int, chdr: int, csize: int) -> Node: - line, comment = struct.unpack_from(" bool: + return bool(self.flags & self.UTF8) + + def index(self, value: str) -> int: + """The index of `value`, appending it to the pool if it is new.""" + try: + return self.strings.index(value) + except ValueError: + self.strings.append(value) + return len(self.strings) - 1 + + def get(self, index: int) -> Optional[str]: + if index == NO_ENTRY or index < 0 or index >= len(self.strings): + return None + return self.strings[index] + + # -- parsing + + @classmethod + def parse(cls, data: bytes, start: int) -> "StringPool": + kind, header_size, size = struct.unpack_from(" bytes: + offsets = [] + blob = bytearray() + seen = {} + for s in self.strings: + if s in seen: + offsets.append(seen[s]) + continue + seen[s] = len(blob) + offsets.append(len(blob)) + blob += _write_string(s, self.utf8) + while len(blob) % 4: + blob.append(0) + + header_size = 28 + strings_start = header_size + 4 * len(offsets) + 4 * len(self.style_offsets) + styles_start = (strings_start + len(blob)) if self.styles else 0 + size = strings_start + len(blob) + len(self.styles) + + out = bytearray() + out += struct.pack(" str: + if utf8: + _chars, pos = _read_len(data, pos, True) # length in utf-16 units, unused + nbytes, pos = _read_len(data, pos, True) + return data[pos : pos + nbytes].decode("utf-8", "replace") + nchars, pos = _read_len(data, pos, False) + return data[pos : pos + nchars * 2].decode("utf-16-le", "replace") + + +def _write_len(value: int, utf8: bool) -> bytes: + if utf8: + if value > 0x7F: + return bytes([0x80 | ((value >> 8) & 0x7F), value & 0xFF]) + return bytes([value]) + if value > 0x7FFF: + return struct.pack("> 16) & 0x7FFF), value & 0xFFFF) + return struct.pack(" bytes: + if utf8: + raw = value.encode("utf-8") + chars = len(value.encode("utf-16-le")) // 2 + return _write_len(chars, True) + _write_len(len(raw), True) + raw + b"\x00" + raw = value.encode("utf-16-le") + return _write_len(len(raw) // 2, False) + raw + b"\x00\x00" + + +# --------------------------------------------------------------------- nodes + + +class Attribute: + def __init__(self, ns: int, name: int, raw: int, size: int, res0: int, kind: int, data: int): + self.ns = ns + self.name = name + self.raw = raw + self.size = size + self.res0 = res0 + self.kind = kind + self.data = data + + def pack(self) -> bytes: + return struct.pack( + " bytes: + body = bytearray() + if self.kind in (RES_XML_START_NAMESPACE, RES_XML_END_NAMESPACE): + body += struct.pack(" "Axml": + kind, header_size, _size = struct.unpack_from(" bytes: + body = bytearray() + body += self.pool.build() + if self.resource_map: + size = 8 + 4 * len(self.resource_map) + body += struct.pack(" Optional[str]: + return self.pool.get(index) + + def elements(self, name: str) -> List[Node]: + return [ + n + for n in self.nodes + if n.kind == RES_XML_START_ELEMENT and self.pool.get(n.name) == name + ] + + def attr(self, node: Node, name: str) -> Optional[Attribute]: + for a in node.attributes: + if self.pool.get(a.name) == name and self.pool.get(a.ns) in (ANDROID_NS, None): + return a + return None + + def attr_string(self, node: Node, name: str) -> Optional[str]: + a = self.attr(node, name) + if a is None: + return None + if a.kind == TYPE_STRING: + return self.pool.get(a.data) + return self.pool.get(a.raw) + + # -- editing + + def attribute_name_index(self, name: str) -> int: + """The pool index for an `android:` attribute name. + + The resource map runs parallel to the first entries of the pool, so an + attribute name has to sit at the index whose map entry is its id. An + attribute the file already uses is simply found there. One it does not + is inserted at the end of the map -- in the middle of the pool -- and + every index above it is shifted up to match. + """ + if name not in ATTR_IDS: + raise AxmlError("unknown framework attribute: %s" % name) + wanted = ATTR_IDS[name] + for i, rid in enumerate(self.resource_map): + if rid == wanted: + # a resource-optimised file keeps only the ids and leaves the names empty + if self.pool.get(i) not in (name, "", None): + raise AxmlError( + "resource map says %d is %s, the pool says %r" + % (i, name, self.pool.get(i)) + ) + return i + + at = len(self.resource_map) + self.pool.strings.insert(at, name) + self.resource_map.append(wanted) + self._shift_indices(at) + return at + + def _shift_indices(self, at: int) -> None: + """Move every string reference at or above `at` up by one.""" + + def bump(index: int) -> int: + return index + 1 if index != NO_ENTRY and index >= at else index + + seen = set() + for node in self.nodes + self.pending: + if id(node) in seen: + continue + seen.add(id(node)) + if node.kind in (RES_XML_START_NAMESPACE, RES_XML_END_NAMESPACE): + node.prefix = bump(node.prefix) + node.uri = bump(node.uri) + continue + node.ns = bump(node.ns) + node.name = bump(node.name) + for a in node.attributes: + a.ns = bump(a.ns) + a.name = bump(a.name) + a.raw = bump(a.raw) + if a.kind == TYPE_STRING: + a.data = bump(a.data) + if node.kind == RES_XML_CDATA and len(node.tail) == 8: + size, res0, kind, data = struct.unpack(" None: + """Set an `android:` attribute, replacing it if the element has it.""" + name_index = self.attribute_name_index(name) + ns_index = self.pool.index(ANDROID_NS) + existing = self.attr(node, name) + if existing is not None: + existing.ns = ns_index + existing.name = name_index + existing.raw = raw + existing.size = 8 + existing.res0 = 0 + existing.kind = kind + existing.data = data + return + attr = Attribute(ns_index, name_index, raw, 8, 0, kind, data) + # Attributes must stay in ascending resource-id order: Android walks the file's list and the + # requested one side by side and silently skips whatever is out of order. Every attribute counts, + # not only the ones this module can write (a `widgetCategory` that was already there once put + # `resizeMode` behind it, and the launcher then read no resize range and no target cells at all). + wanted = ATTR_IDS[name] + where = len(node.attributes) + for i, other in enumerate(node.attributes): + rid = self.resource_map[other.name] if 0 <= other.name < len(self.resource_map) else 0 + if rid and rid > wanted: + where = i + break + node.attributes.insert(where, attr) + + def set_attr_string(self, node: Node, name: str, value: str) -> None: + # the attribute's own name goes in first: adding one renumbers the pool + # from the end of the resource map up, and a value index looked up + # before that would be pointing one string to the left afterwards + self.attribute_name_index(name) + index = self.pool.index(value) + self.set_attr(node, name, TYPE_STRING, index, raw=index) + + def set_attr_bool(self, node: Node, name: str, value: bool) -> None: + self.set_attr(node, name, TYPE_INT_BOOLEAN, 0xFFFFFFFF if value else 0) + + def set_attr_ref(self, node: Node, name: str, res_id: int) -> None: + self.set_attr(node, name, TYPE_REFERENCE, res_id) + + def make_element(self, name: str) -> Node: + node = Node(RES_XML_START_ELEMENT, 0, NO_ENTRY) + node.ns = NO_ENTRY + node.name = self.pool.index(name) + self.pending.append(node) + return node + + def close_element(self, start: Node) -> Node: + node = Node(RES_XML_END_ELEMENT, 0, NO_ENTRY) + node.ns = start.ns + node.name = start.name + self.pending.append(node) + return node + + def insert_into(self, parent: Node, subtree: List[Node]) -> None: + """Put a subtree in as the last child of `parent`.""" + depth = 0 + for i in range(self.nodes.index(parent) + 1, len(self.nodes)): + node = self.nodes[i] + if node.kind == RES_XML_START_ELEMENT: + depth += 1 + elif node.kind == RES_XML_END_ELEMENT: + if depth == 0: + self.nodes[i:i] = subtree + return + depth -= 1 + raise AxmlError("element has no end tag") + + +def _parse_node(data: bytes, pos: int, ctype: int, chdr: int, csize: int) -> Node: + line, comment = struct.unpack_from(" 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} diff --git a/lihont/upgrade.py b/lihont/upgrade.py index 15b4e5f..cc9a9a0 100644 --- a/lihont/upgrade.py +++ b/lihont/upgrade.py @@ -1,589 +1,609 @@ -"""Build LihonT 2.0 test build: TikTok 47.1.3 arm64, BY region helper, and -native profile banners / comment reposts behind the settings switches. - -python -m lihont.upgrade OriginalAPKtiktok/ -o ComplectAPK/lihont-2.0-test.apk -""" -from __future__ import annotations - -import argparse -import hashlib -import json -import os -import re -import subprocess -from collections import defaultdict -from pathlib import Path - -from . import avatar_patch, badge_patch, bar_patch, dexpatch, feed_patch, media_patch, region, profile_features, settings_patch, theme_patch -from .apkzip import Apk -from .axml import Axml -from .toolchain import Toolchain - -SOURCE_VERSION = "47.1.3" -SETTINGS_ACTIVITY = "lihont.two.settings.LihonTSettingsActivity" -# Existing app theme keeps system bars/insets compatible with TikTok; the -# activity draws its own Nothing-inspired surface. -SETTINGS_THEME = 0x7F120364 - -# dex -> list of class descriptors patched for the region feature -REGION_TARGETS = { - "classes35.dex": ["LX/1DHU;", "LX/1DHB;"], - "classes21.dex": ["LX/0kmK;", "LX/0kmL;"], -} - -# TikTok 47.1.3's native settings Compose composables. -# SettingsCell.draw injects the row into the Activity section card above ManagePostsVM. -SETTINGS_TARGET_DEX = "classes36.dex" -SETTINGS_TARGET_CLASSES = [settings_patch.RENDERER_CLASS, settings_patch.GROUP_CLASS] - - - -def patch_classes(apk: Apk, targets: dict, tools: Toolchain, room: Path, api: int) -> dict: - compiler = room / "compiler" - compiler.mkdir(parents=True, exist_ok=True) - grouped: dict = defaultdict(list) - for name, owners in targets.items(): - for owner in owners: - grouped[name].append(owner) - reports: dict = {} - smali = dexpatch.Smali(tools.smali, api, jobs=2, heap="1g") - subprocess.run( - ["javac", "--release", "17", "-cp", tools.smali, "-d", str(compiler), - "src/ReplaceClasses.java", "src/MergeClasses.java"], check=True - ) - for name, owners in grouped.items(): - folder = room / name[:-4] - folder.mkdir(parents=True, exist_ok=True) - before = folder / "original.dex" - before.write_bytes(apk.read(name)) - decoded = folder / "smali" - for owner in owners: - subprocess.run( - ["java", "-Xmx1g", "-cp", - os.pathsep.join([tools.smali, "tools/baksmali.jar"]), - "com.android.tools.smali.baksmali.Main", "disassemble", - str(before), "--classes", owner, "-o", str(decoded)], check=True - ) - hits: dict = {} - for owner in owners: - path = decoded / (owner[1:-1] + ".smali") - text = path.read_text(encoding="utf-8") - class_desc = re.search(r"^\.class[^\n]* (L[^;]+;)$", text, re.M) - if class_desc is None or class_desc.group(1) != owner: - raise ValueError("Unexpected smali class in " + owner) - if owner == "LX/1DHB;": - rewritten, counts = region.rewrite_monitor(text) - elif owner in region.LAMBDAS: - rewritten, counts = region.rewrite_lambda(text, owner) - else: - rewritten, counts = region.rewrite(text, owner) - if not counts: - raise ValueError("Region hook missing in " + owner) - path.write_text(rewritten, encoding="utf-8", newline="\n") - hits[owner] = counts - replacement = folder / "replacement.dex" - smali.assemble(str(decoded), str(replacement)) - after = folder / "patched.dex" - subprocess.run( - ["java", "-Xmx1g", "-cp", os.pathsep.join([str(compiler), tools.smali]), - "ReplaceClasses", str(before), str(replacement), str(after), str(api)], - check=True - ) - old, new = before.read_bytes(), after.read_bytes() - if dexpatch.defined_methods(old) != dexpatch.defined_methods(new) or \ - dexpatch.dex_format(old) != dexpatch.dex_format(new): - raise ValueError("Class definitions or DEX version changed in " + name) - apk.replace(name, new) - reports[name] = {"sha256": hashlib.sha256(new).hexdigest(), "hooks": hits} - return reports - - -def patch_settings_entry(apk: Apk, tools: Toolchain, room: Path, api: int) -> dict: - """Inject the native Jetpack Compose settings row into TikTok's settings card.""" - name = SETTINGS_TARGET_DEX - before = apk.read(name) - folder = room / "settings-entry" - folder.mkdir(parents=True, exist_ok=True) - original = folder / "original.dex" - original.write_bytes(before) - decoded = folder / "smali" - for owner in SETTINGS_TARGET_CLASSES: - subprocess.run( - ["java", "-Xmx1g", "-cp", - os.pathsep.join([tools.smali, "tools/baksmali.jar"]), - "com.android.tools.smali.baksmali.Main", "disassemble", - str(original), "--classes", owner, "-o", str(decoded)], - check=True, - ) - - dvk_path = decoded / (settings_patch.RENDERER_CLASS[1:-1] + ".smali") - dur_path = decoded / (settings_patch.GROUP_CLASS[1:-1] + ".smali") - if not dvk_path.exists() or not dur_path.exists(): - raise ValueError("Settings Compose classes missing from " + name) - - dvk_text = dvk_path.read_text(encoding="utf-8").replace("\r\n", "\n") - dur_text = dur_path.read_text(encoding="utf-8").replace("\r\n", "\n") - - patched_dvk = settings_patch.rewrite_1dvk(dvk_text) - patched_dur = settings_patch.rewrite_1dur(dur_text) - - dvk_path.write_text(patched_dvk, encoding="utf-8", newline="\n") - dur_path.write_text(patched_dur, encoding="utf-8", newline="\n") - - replacement = folder / "replacement.dex" - dexpatch.Smali(tools.smali, api, jobs=2, heap="1g").assemble(str(decoded), str(replacement)) - - compiler = room / "compiler" - compiler.mkdir(parents=True, exist_ok=True) - subprocess.run( - ["javac", "--release", "17", "-cp", tools.smali, "-d", str(compiler), - "src/ReplaceClasses.java", "src/MergeClasses.java"], - check=True, - ) - patched_path = folder / "patched.dex" - subprocess.run( - ["java", "-Xmx1g", "-cp", os.pathsep.join([str(compiler), tools.smali]), - "ReplaceClasses", str(original), str(replacement), str(patched_path), str(api)], - check=True, - ) - patched = patched_path.read_bytes() - before_methods = dexpatch.defined_methods(before) - patched_methods = dexpatch.defined_methods(patched) - if not before_methods.issubset(patched_methods): - raise ValueError("Settings entry hook lost existing methods") - if not any("LX/1DvK;->lihont(" in m for m in patched_methods): - raise ValueError("LX/1DvK;->lihont missing after patch") - if b"Llihont/two/settings/SettingsCell;" not in patched: - raise ValueError("SettingsCell hook missing in patched dex") - if dexpatch.dex_format(before) != dexpatch.dex_format(patched): - raise ValueError("Settings entry hook changed DEX format") - apk.replace(name, patched) - return { - "dex": name, - "classes": SETTINGS_TARGET_CLASSES, - "hook": settings_patch.DRAW_HOOK, - "sha256": hashlib.sha256(patched).hexdigest(), - } - - -def patch_md3_settings_icons(apk: Apk, tools: Toolchain, room: Path, api: int) -> dict: - """Inject Material 3 flower badge transformer into TikTok's settings cell renderer in classes9.dex.""" - name = "classes9.dex" - before = apk.read(name) - folder = room / "settings-md3-icons" - folder.mkdir(parents=True, exist_ok=True) - original = folder / "original.dex" - original.write_bytes(before) - decoded = folder / "smali" - subprocess.run( - ["java", "-Xmx1g", "-cp", - os.pathsep.join([tools.smali, "tools/baksmali.jar"]), - "com.android.tools.smali.baksmali.Main", "disassemble", - str(original), "--classes", settings_patch.CELL_CLASS, "-o", str(decoded)], - check=True, - ) - - ldm_path = decoded / (settings_patch.CELL_CLASS[1:-1] + ".smali") - if not ldm_path.exists(): - raise ValueError("Settings cell class missing from " + name) - - ldm_text = ldm_path.read_text(encoding="utf-8").replace("\r\n", "\n") - patched_ldm = settings_patch.rewrite_0ldm(ldm_text) - ldm_path.write_text(patched_ldm, encoding="utf-8", newline="\n") - - painter_src = Path("src/smali/lihont/two/settings/Md3BadgePainter.smali") - if not painter_src.exists(): - raise ValueError(f"{painter_src} missing") - painter_dst = decoded / "lihont" / "two" / "settings" / "Md3BadgePainter.smali" - painter_dst.parent.mkdir(parents=True, exist_ok=True) - painter_dst.write_text(painter_src.read_text(encoding="utf-8"), encoding="utf-8", newline="\n") - - replacement = folder / "replacement.dex" - dexpatch.Smali(tools.smali, api, jobs=2, heap="1g").assemble(str(decoded), str(replacement)) - - compiler = room / "compiler" - compiler.mkdir(parents=True, exist_ok=True) - subprocess.run( - ["javac", "--release", "17", "-cp", tools.smali, "-d", str(compiler), - "src/ReplaceClasses.java", "src/MergeClasses.java"], - check=True, - ) - patched_path = folder / "patched.dex" - subprocess.run( - ["java", "-Xmx1g", "-cp", os.pathsep.join([str(compiler), tools.smali]), - "ReplaceClasses", str(original), str(replacement), str(patched_path), str(api)], - check=True, - ) - patched = patched_path.read_bytes() - before_methods = dexpatch.defined_methods(before) - patched_methods = dexpatch.defined_methods(patched) - if not before_methods.issubset(patched_methods): - raise ValueError("MD3 settings icon hook lost existing methods") - if not any("Llihont/two/settings/Md3BadgePainter;->LJIIIZ(" in m for m in patched_methods): - raise ValueError("Md3BadgePainter missing after patch") - if b"Llihont/two/settings/SettingsCell;" not in patched or b"transformIcon" not in patched: - raise ValueError("transformIcon hook missing in patched dex") - if dexpatch.dex_format(before) != dexpatch.dex_format(patched): - raise ValueError("MD3 settings icon hook changed DEX format") - apk.replace(name, patched) - return { - "dex": name, - "classes": [settings_patch.CELL_CLASS, settings_patch.PAINTER_CLASS], - "hook": "Llihont/two/settings/SettingsCell;->transformIcon(Ljava/lang/Object;Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/Object;", - "sha256": hashlib.sha256(patched).hexdigest(), - } - - -def patch_class(apk: Apk, tools: Toolchain, room: Path, api: int, dex_name: str, owner: str, - label: str, rewrite, marker: bytes) -> dict: - """Disassemble one class, rewrite its smali, and put the reassembled class back in its dex.""" - before = apk.read(dex_name) - folder = room / label - folder.mkdir(parents=True, exist_ok=True) - original = folder / "original.dex" - original.write_bytes(before) - decoded = folder / "smali" - subprocess.run( - ["java", "-Xmx1g", "-cp", - os.pathsep.join([tools.smali, "tools/baksmali.jar"]), - "com.android.tools.smali.baksmali.Main", "disassemble", - str(original), "--classes", owner, "-o", str(decoded)], - check=True, - ) - source = decoded / (owner[1:-1] + ".smali") - if not source.exists(): - raise ValueError("%s missing from %s" % (owner, dex_name)) - text = source.read_text(encoding="utf-8").replace("\r\n", "\n") - source.write_text(rewrite(text), encoding="utf-8", newline="\n") - - replacement = folder / "replacement.dex" - dexpatch.Smali(tools.smali, api, jobs=2, heap="1g").assemble(str(decoded), str(replacement)) - - compiler = room / "compiler" - compiler.mkdir(parents=True, exist_ok=True) - subprocess.run( - ["javac", "--release", "17", "-cp", tools.smali, "-d", str(compiler), - "src/ReplaceClasses.java", "src/MergeClasses.java"], - check=True, - ) - patched_path = folder / "patched.dex" - subprocess.run( - ["java", "-Xmx1g", "-cp", os.pathsep.join([str(compiler), tools.smali]), - "ReplaceClasses", str(original), str(replacement), str(patched_path), str(api)], - check=True, - ) - patched = patched_path.read_bytes() - if not dexpatch.defined_methods(before).issubset(dexpatch.defined_methods(patched)): - raise ValueError("%s rewrite lost existing methods" % owner) - if marker not in patched: - raise ValueError("%s rewrite did not reach the dex" % owner) - if dexpatch.dex_format(before) != dexpatch.dex_format(patched): - raise ValueError("%s rewrite changed the DEX format" % owner) - apk.replace(dex_name, patched) - return {"dex": dex_name, "class": owner, "sha256": hashlib.sha256(patched).hexdigest()} - - -def patch_native_theme(apk: Apk, tools: Toolchain, room: Path, api: int) -> dict: - """Pass TikTok's Compose colour tokens through lihont.two.theme.NativeTheme.""" - report = patch_class(apk, tools, room, api, "classes9.dex", theme_patch.ACCESSOR_CLASS, - "native-theme", theme_patch.rewrite_colors_accessor, - b"Llihont/two/theme/NativeTheme;") - report["hook"] = theme_patch.HOOK - return report - - -def patch_settings_rows(apk: Apk, tools: Toolchain, room: Path, api: int) -> dict: - """Let NativeTheme give TikTok's settings rows their own rounded shape and spacing.""" - report = patch_class(apk, tools, room, api, "classes9.dex", theme_patch.ROW_CLASS, - "native-rows", theme_patch.rewrite_row_lambda, - b"Llihont/two/theme/NativeTheme;") - report["hooks"] = theme_patch.row_targets() - return report - - -def patch_section_labels(apk: Apk, tools: Toolchain, room: Path, api: int) -> dict: - """Let NativeTheme colour the title above each settings group.""" - report = patch_class(apk, tools, room, api, "classes9.dex", theme_patch.SECTION_CLASS, - "section-labels", theme_patch.rewrite_section_label, - b"Llihont/two/theme/NativeTheme;") - report["hook"] = theme_patch.SECTION_HOOK - return report - - -def patch_language_card(apk: Apk, tools: Toolchain, room: Path, api: int) -> dict: - """Let NativeTheme drop the language row's own card inside TikTok settings.""" - report = patch_class(apk, tools, room, api, "classes9.dex", theme_patch.LANGUAGE_CLASS, - "language-card", theme_patch.rewrite_language_card, - b"Llihont/two/theme/NativeTheme;") - report["hook"] = theme_patch.CARD_HOOK - return report - - -def patch_main_activity(apk: Apk, tools: Toolchain, room: Path, api: int) -> dict: - """Tell the bottom-bar code when TikTok's main screen comes to the front.""" - report = patch_class(apk, tools, room, api, bar_patch.DEX, bar_patch.OWNER, "main-activity", - bar_patch.rewrite_main_activity, b"Llihont/two/bar/BottomBar;") - report["hook"] = bar_patch.HOOK - return report - - -def patch_downloads(apk: Apk, tools: Toolchain, room: Path, api: int) -> dict: - """Let saved videos come out of the download chain without the watermark.""" - marker = b"Llihont/two/media/Downloads;" - report = { - "source": patch_class(apk, tools, room, api, media_patch.DEX, media_patch.SOURCE_OWNER, - "download-source", media_patch.rewrite_source, marker), - "context": patch_class(apk, tools, room, api, media_patch.DEX, media_patch.CONTEXT_OWNER, - "download-context", media_patch.rewrite_context, marker), - } - menu = b"Llihont/two/media/DownloadMenu;" - for owner in media_patch.SAVE_OWNERS: - label = "download-save-" + owner[1:-1].rsplit("/", 1)[1].lower() - report["save " + owner] = patch_class(apk, tools, room, api, media_patch.DEX, owner, label, - media_patch.rewrite_save, menu) - report["photo"] = patch_class(apk, tools, room, api, media_patch.DEX, media_patch.PHOTO_OWNER, - "download-photo", media_patch.rewrite_photo, menu) - report["hooks"] = media_patch.runtime_targets() - return report - - -def patch_feed(apk: Apk, tools: Toolchain, room: Path, api: int) -> dict: - """Let lihont.two.feed.FeedFilter take advertisements and live streams out of the feed.""" - marker = b"Llihont/two/feed/FeedFilter;" - report = {} - for owner, rewrite in feed_patch.REWRITES.items(): - label = "feed-" + owner.rsplit("/", 1)[1].rstrip(";").lower() - report[owner] = patch_class(apk, tools, room, api, feed_patch.DEXES[owner], owner, label, - lambda text, rewrite=rewrite: rewrite(text)[0], marker) - report["hooks"] = feed_patch.runtime_targets() - return report - - -def patch_avatars(apk: Apk, tools: Toolchain, room: Path, api: int) -> dict: - """Let lihont.two.avatar.AvatarShapes cut every avatar to the shape chosen in the settings.""" - marker = b"Llihont/two/avatar/AvatarShapes;" - report = {"avatar": patch_class(apk, tools, room, api, avatar_patch.DEX, avatar_patch.OWNER, "avatar-view", - avatar_patch.rewrite_avatar, marker)} - report["hooks"] = avatar_patch.runtime_targets() - return report - - -def patch_badges(apk: Apk, tools: Toolchain, room: Path, api: int) -> dict: - """Let lihont.two.badge.Badges put badges next to names, and ship the two pictures TikTok You builds in.""" - marker = b"Llihont/two/badge/Badges;" - report = {} - for owner, rewrite in badge_patch.REWRITES.items(): - label = "badge-" + owner.rsplit("/", 1)[1].rstrip(";").lower() - report[owner] = patch_class(apk, tools, room, api, badge_patch.DEXES[owner], owner, label, - lambda text, rewrite=rewrite: rewrite(text)[0], marker) - shipped = [] - for name in ("supporter.png", "developer.png"): - source = Path("src/compat", name) - if not source.is_file(): - continue # third-party artwork that the repository does not carry: see src/compat/README.md - entry = "assets/lihont/compat/" + name - data = source.read_bytes() - if apk.has(entry): - apk.replace(entry, data) - else: - apk.add(entry, data) - shipped.append(name) - report["compat_pictures"] = shipped - report["hooks"] = badge_patch.runtime_targets() - return report - - -def merge_runtime(host_dex: bytes, runtime_dex: bytes, tools: Toolchain, room: Path, api: int) -> bytes: - """Add the runtime classes to an existing dex with dexlib2 class merging.""" - folder = room / "runtime-merge" - folder.mkdir(parents=True, exist_ok=True) - host = folder / "host.dex" - extra = folder / "extra.dex" - merged = folder / "merged.dex" - host.write_bytes(host_dex) - extra.write_bytes(runtime_dex) - subprocess.run( - ["java", "-Xmx1g", "-cp", - os.pathsep.join([str(room / "compiler"), tools.smali]), - "MergeClasses", str(host), str(extra), str(merged), str(api)], - check=True, - ) - result = merged.read_bytes() - if dexpatch.dex_format(host_dex) != dexpatch.dex_format(result): - raise ValueError("Runtime merge changed the DEX format") - host_classes = dexpatch.defined_methods(host_dex) - merged_classes = dexpatch.defined_methods(result) - if not host_classes.issubset(merged_classes): - raise ValueError("Runtime merge lost existing classes") - if not any(m.startswith("Llihont/two/LihonTRegion;->") for m in merged_classes): - raise ValueError("Runtime merge did not add LihonTRegion") - return result - - -def patch_feature_flags(apk: Apk, tools: Toolchain, room: Path, api: int) -> dict: - """Route native profile banner and comment repost flag reads through LihonTFlags. - - Only direct SettingsManager-style reads whose String argument is a known - flag literal are rewritten; the original call stays in place and its result - goes to the LihonT switch for that flag. Verified per-dex against the - method-definition table. - """ - flags = {**profile_features.PROFILE_FLAGS, **profile_features.REPOST_FLAGS} - counts: dict = {} - changed: dict = {} - smali = dexpatch.Smali(tools.smali, api, jobs=2, heap="768m") - for name in sorted(apk.names()): - if not name.endswith(".dex"): - continue - data = apk.read(name) - if not profile_features.interesting(data, flags): - continue - owners = profile_features.literal_owners(data, flags) - if not owners: - continue - dex_room = room / ("flags-" + name[:-4]) - dex_room.mkdir(parents=True, exist_ok=True) - dex_input = dex_room / "in.dex" - dex_output = dex_room / "out.dex" - dex_input.write_bytes(data) - decoded = dex_room / "smali" - smali.disassemble(str(dex_input), str(decoded)) - originals = {} - hits = {} - try: - for path in profile_features.candidate_files(str(decoded), flags, owners): - raw = Path(path).read_bytes() - rewritten, file_hits = profile_features.rewrite_smali( - raw.decode("utf-8"), flags - ) - if not file_hits: - continue - originals[path] = raw - Path(path).write_bytes(rewritten.encode("utf-8")) - for key, count in file_hits.items(): - hits[key] = hits.get(key, 0) + count - if not hits: - print("%s: no direct flag reads" % name, flush=True) - continue - print("%s: %s" % (name, hits), flush=True) - smali.assemble(str(decoded), str(dex_output)) - patched = dex_output.read_bytes() - if dexpatch.dex_format(patched) != dexpatch.dex_format(data): - raise ValueError("DEX format changed in " + name) - if dexpatch.defined_methods(patched) != dexpatch.defined_methods(data): - raise ValueError("Class method definitions changed in " + name) - apk.replace(name, patched) - changed[name] = {"sha256": hashlib.sha256(patched).hexdigest(), "counts": hits} - for key, count in hits.items(): - counts[key] = counts.get(key, 0) + count - finally: - for path, raw in originals.items(): - Path(path).write_bytes(raw) - missing = sorted(flags.keys() - counts.keys()) - if missing: - raise ValueError("Could not verify native flag reads: " + ", ".join(missing)) - return {"counts": counts, "changed_dex": changed} - - -def build(source: str, output: str, workspace: str = "work/build") -> dict: - source_path, output_path, room = ( - Path(source).resolve(), Path(output).resolve(), Path(workspace).resolve() - ) - if source_path == output_path: - raise ValueError("Keep the source APK unchanged") - digest = hashlib.sha256(source_path.read_bytes()).hexdigest() - room.mkdir(parents=True, exist_ok=True) - tools = Toolchain("tools") - apk = Apk(str(source_path)) - report = { - "edition": "lihont", "mod_version": "2.0-test", - "source": source_path.name, "source_sha256": digest, - } - try: - xml = Axml.parse(apk.read("AndroidManifest.xml")) - from . import manifest as manifest_module - package = manifest_module.package_name(xml) - version = manifest_module.version_name(xml) - if package != "com.zhiliaoapp.musically" or version != SOURCE_VERSION: - raise ValueError("Expected TikTok " + SOURCE_VERSION + ", got " + version) - api = manifest_module.min_sdk(xml) - report["source_version"] = version - # Register the private settings screen in the host manifest. It is - # intentionally non-exported: only the in-app settings hook should - # be able to launch it. No intent-filter is added, so it cannot appear - # as a launcher entry or be reached through an external deep link. - from . import manifest as manifest_module - if not manifest_module.has_activity(xml, SETTINGS_ACTIVITY): - manifest_module.add_activity( - xml, SETTINGS_ACTIVITY, "LihonT", SETTINGS_THEME, exported=False - ) - apk.replace("AndroidManifest.xml", xml.build()) - report["manifest"] = {"settings_activity": SETTINGS_ACTIVITY, "exported": False} - else: - report["manifest"] = {"settings_activity": SETTINGS_ACTIVITY, "exported": False, "already_present": True} - # The launcher icons the settings screen offers: one disabled alias per catalog icon. - from . import app_icons - report["app_icons"] = app_icons.apply(apk, xml, app_icons.load_catalog(Path("src/icons"))) - report["changed_dex"] = patch_classes(apk, REGION_TARGETS, tools, room, api) - report["settings_entry"] = patch_settings_entry(apk, tools, room, api) - report["settings_icons"] = patch_md3_settings_icons(apk, tools, room, api) - report["native_theme"] = patch_native_theme(apk, tools, room, api) - report["native_rows"] = patch_settings_rows(apk, tools, room, api) - report["section_labels"] = patch_section_labels(apk, tools, room, api) - report["language_card"] = patch_language_card(apk, tools, room, api) - report["main_activity"] = patch_main_activity(apk, tools, room, api) - report["downloads"] = patch_downloads(apk, tools, room, api) - report["feed"] = patch_feed(apk, tools, room, api) - report["badges"] = patch_badges(apk, tools, room, api) - report["avatars"] = patch_avatars(apk, tools, room, api) - report["feature_flags"] = patch_feature_flags(apk, tools, room, api) - runtime_path = tools.compile_dex("src/lihont/two", str(room / "runtime"), api) - runtime = Path(runtime_path).read_bytes() - if b"Llihont/two/LihonTRegion;" not in runtime: - raise ValueError("Runtime class missing") - # classes.dex is a live TikTok dex here, never overwrite it: the small - # runtime rides along inside the patched classes35.dex instead. - apk.replace("classes35.dex", merge_runtime(apk.read("classes35.dex"), runtime, tools, room, api)) - report["runtime"] = {"dex": "classes35.dex", "sha256": hashlib.sha256(runtime).hexdigest()} - merged = dexpatch.defined_methods(apk.read("classes35.dex")) - if not any(m.startswith("Llihont/two/LihonTRegion;->") for m in merged): - raise ValueError("LihonTRegion missing after merge") - absent = [t for t in profile_features.runtime_targets() + theme_patch.runtime_targets() - + theme_patch.section_targets() + theme_patch.row_targets() - + theme_patch.card_targets() + bar_patch.runtime_targets() - + media_patch.runtime_targets() + feed_patch.runtime_targets() - + badge_patch.runtime_targets() + avatar_patch.runtime_targets() if t not in merged] - if absent: - raise ValueError("Hooks have no runtime target: " + ", ".join(absent)) - report["feature_flags"]["runtime"] = profile_features.FLAGS_CLASS - report["region"] = { - "country": "by", "operator": "25701", "carrier": "A1 BY", - "expected_hooks": region.expected_hits(), - } - apk.drop_signature() - output_path.parent.mkdir(parents=True, exist_ok=True) - apk.write(str(output_path)) - finally: - apk.close() - tools.sign(str(output_path)) - report.update({ - "file": output_path.name, "bytes": output_path.stat().st_size, - "sha256": hashlib.sha256(output_path.read_bytes()).hexdigest(), - }) - Path(str(output_path) + ".json").write_text( - json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8" - ) - return report - - -def main() -> None: - parser = argparse.ArgumentParser() - parser.add_argument("apk") - parser.add_argument("-o", "--out", required=True) - parser.add_argument("--work", default="work/build") - args = parser.parse_args() - print(json.dumps(build(args.apk, args.out, args.work), ensure_ascii=False, indent=2)) - - -if __name__ == "__main__": - main() +"""Build LihonT 2.0 test build: TikTok 47.1.3 arm64, BY region helper, and +native profile banners / comment reposts behind the settings switches. + +python -m lihont.upgrade OriginalAPKtiktok/ -o ComplectAPK/lihont-2.0-test.apk +""" +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import re +import subprocess +from collections import defaultdict +from pathlib import Path + +from . import avatar_patch, badge_patch, bar_patch, dexpatch, feed_patch, media_patch, region, profile_features, settings_patch, theme_patch +from .apkzip import Apk +from .axml import Axml +from .toolchain import Toolchain + +SOURCE_VERSION = "47.1.3" +SETTINGS_ACTIVITY = "lihont.two.settings.LihonTSettingsActivity" +# Existing app theme keeps system bars/insets compatible with TikTok; the +# activity draws its own Nothing-inspired surface. +SETTINGS_THEME = 0x7F120364 + +# dex -> list of class descriptors patched for the region feature +REGION_TARGETS = { + "classes35.dex": ["LX/1DHU;", "LX/1DHB;"], + "classes21.dex": ["LX/0kmK;", "LX/0kmL;"], +} + +# TikTok 47.1.3's native settings Compose composables. +# SettingsCell.draw injects the row into the Activity section card above ManagePostsVM. +SETTINGS_TARGET_DEX = "classes36.dex" +SETTINGS_TARGET_CLASSES = [settings_patch.RENDERER_CLASS, settings_patch.GROUP_CLASS] + + + +def patch_classes(apk: Apk, targets: dict, tools: Toolchain, room: Path, api: int) -> dict: + compiler = room / "compiler" + compiler.mkdir(parents=True, exist_ok=True) + grouped: dict = defaultdict(list) + for name, owners in targets.items(): + for owner in owners: + grouped[name].append(owner) + reports: dict = {} + smali = dexpatch.Smali(tools.smali, api, jobs=2, heap="1g") + subprocess.run( + ["javac", "--release", "17", "-cp", tools.smali, "-d", str(compiler), + "src/ReplaceClasses.java", "src/MergeClasses.java"], check=True + ) + for name, owners in grouped.items(): + folder = room / name[:-4] + folder.mkdir(parents=True, exist_ok=True) + before = folder / "original.dex" + before.write_bytes(apk.read(name)) + decoded = folder / "smali" + for owner in owners: + subprocess.run( + ["java", "-Xmx1g", "-cp", + os.pathsep.join([tools.smali, "tools/baksmali.jar"]), + "com.android.tools.smali.baksmali.Main", "disassemble", + str(before), "--classes", owner, "-o", str(decoded)], check=True + ) + hits: dict = {} + for owner in owners: + path = decoded / (owner[1:-1] + ".smali") + text = path.read_text(encoding="utf-8") + class_desc = re.search(r"^\.class[^\n]* (L[^;]+;)$", text, re.M) + if class_desc is None or class_desc.group(1) != owner: + raise ValueError("Unexpected smali class in " + owner) + if owner == "LX/1DHB;": + rewritten, counts = region.rewrite_monitor(text) + elif owner in region.LAMBDAS: + rewritten, counts = region.rewrite_lambda(text, owner) + else: + rewritten, counts = region.rewrite(text, owner) + if not counts: + raise ValueError("Region hook missing in " + owner) + path.write_text(rewritten, encoding="utf-8", newline="\n") + hits[owner] = counts + replacement = folder / "replacement.dex" + smali.assemble(str(decoded), str(replacement)) + after = folder / "patched.dex" + subprocess.run( + ["java", "-Xmx1g", "-cp", os.pathsep.join([str(compiler), tools.smali]), + "ReplaceClasses", str(before), str(replacement), str(after), str(api)], + check=True + ) + old, new = before.read_bytes(), after.read_bytes() + if dexpatch.defined_methods(old) != dexpatch.defined_methods(new) or \ + dexpatch.dex_format(old) != dexpatch.dex_format(new): + raise ValueError("Class definitions or DEX version changed in " + name) + apk.replace(name, new) + reports[name] = {"sha256": hashlib.sha256(new).hexdigest(), "hooks": hits} + return reports + + +def patch_settings_entry(apk: Apk, tools: Toolchain, room: Path, api: int) -> dict: + """Inject the native Jetpack Compose settings row into TikTok's settings card.""" + name = SETTINGS_TARGET_DEX + before = apk.read(name) + folder = room / "settings-entry" + folder.mkdir(parents=True, exist_ok=True) + original = folder / "original.dex" + original.write_bytes(before) + decoded = folder / "smali" + for owner in SETTINGS_TARGET_CLASSES: + subprocess.run( + ["java", "-Xmx1g", "-cp", + os.pathsep.join([tools.smali, "tools/baksmali.jar"]), + "com.android.tools.smali.baksmali.Main", "disassemble", + str(original), "--classes", owner, "-o", str(decoded)], + check=True, + ) + + dvk_path = decoded / (settings_patch.RENDERER_CLASS[1:-1] + ".smali") + dur_path = decoded / (settings_patch.GROUP_CLASS[1:-1] + ".smali") + if not dvk_path.exists() or not dur_path.exists(): + raise ValueError("Settings Compose classes missing from " + name) + + dvk_text = dvk_path.read_text(encoding="utf-8").replace("\r\n", "\n") + dur_text = dur_path.read_text(encoding="utf-8").replace("\r\n", "\n") + + patched_dvk = settings_patch.rewrite_1dvk(dvk_text) + patched_dur = settings_patch.rewrite_1dur(dur_text) + + dvk_path.write_text(patched_dvk, encoding="utf-8", newline="\n") + dur_path.write_text(patched_dur, encoding="utf-8", newline="\n") + + replacement = folder / "replacement.dex" + dexpatch.Smali(tools.smali, api, jobs=2, heap="1g").assemble(str(decoded), str(replacement)) + + compiler = room / "compiler" + compiler.mkdir(parents=True, exist_ok=True) + subprocess.run( + ["javac", "--release", "17", "-cp", tools.smali, "-d", str(compiler), + "src/ReplaceClasses.java", "src/MergeClasses.java"], + check=True, + ) + patched_path = folder / "patched.dex" + subprocess.run( + ["java", "-Xmx1g", "-cp", os.pathsep.join([str(compiler), tools.smali]), + "ReplaceClasses", str(original), str(replacement), str(patched_path), str(api)], + check=True, + ) + patched = patched_path.read_bytes() + before_methods = dexpatch.defined_methods(before) + patched_methods = dexpatch.defined_methods(patched) + if not before_methods.issubset(patched_methods): + raise ValueError("Settings entry hook lost existing methods") + if not any("LX/1DvK;->lihont(" in m for m in patched_methods): + raise ValueError("LX/1DvK;->lihont missing after patch") + if b"Llihont/two/settings/SettingsCell;" not in patched: + raise ValueError("SettingsCell hook missing in patched dex") + if dexpatch.dex_format(before) != dexpatch.dex_format(patched): + raise ValueError("Settings entry hook changed DEX format") + apk.replace(name, patched) + return { + "dex": name, + "classes": SETTINGS_TARGET_CLASSES, + "hook": settings_patch.DRAW_HOOK, + "sha256": hashlib.sha256(patched).hexdigest(), + } + + +def patch_md3_settings_icons(apk: Apk, tools: Toolchain, room: Path, api: int) -> dict: + """Inject Material 3 flower badge transformer into TikTok's settings cell renderer in classes9.dex.""" + name = "classes9.dex" + before = apk.read(name) + folder = room / "settings-md3-icons" + folder.mkdir(parents=True, exist_ok=True) + original = folder / "original.dex" + original.write_bytes(before) + decoded = folder / "smali" + subprocess.run( + ["java", "-Xmx1g", "-cp", + os.pathsep.join([tools.smali, "tools/baksmali.jar"]), + "com.android.tools.smali.baksmali.Main", "disassemble", + str(original), "--classes", settings_patch.CELL_CLASS, "-o", str(decoded)], + check=True, + ) + + ldm_path = decoded / (settings_patch.CELL_CLASS[1:-1] + ".smali") + if not ldm_path.exists(): + raise ValueError("Settings cell class missing from " + name) + + ldm_text = ldm_path.read_text(encoding="utf-8").replace("\r\n", "\n") + patched_ldm = settings_patch.rewrite_0ldm(ldm_text) + ldm_path.write_text(patched_ldm, encoding="utf-8", newline="\n") + + painter_src = Path("src/smali/lihont/two/settings/Md3BadgePainter.smali") + if not painter_src.exists(): + raise ValueError(f"{painter_src} missing") + painter_dst = decoded / "lihont" / "two" / "settings" / "Md3BadgePainter.smali" + painter_dst.parent.mkdir(parents=True, exist_ok=True) + painter_dst.write_text(painter_src.read_text(encoding="utf-8"), encoding="utf-8", newline="\n") + + replacement = folder / "replacement.dex" + dexpatch.Smali(tools.smali, api, jobs=2, heap="1g").assemble(str(decoded), str(replacement)) + + compiler = room / "compiler" + compiler.mkdir(parents=True, exist_ok=True) + subprocess.run( + ["javac", "--release", "17", "-cp", tools.smali, "-d", str(compiler), + "src/ReplaceClasses.java", "src/MergeClasses.java"], + check=True, + ) + patched_path = folder / "patched.dex" + subprocess.run( + ["java", "-Xmx1g", "-cp", os.pathsep.join([str(compiler), tools.smali]), + "ReplaceClasses", str(original), str(replacement), str(patched_path), str(api)], + check=True, + ) + patched = patched_path.read_bytes() + before_methods = dexpatch.defined_methods(before) + patched_methods = dexpatch.defined_methods(patched) + if not before_methods.issubset(patched_methods): + raise ValueError("MD3 settings icon hook lost existing methods") + if not any("Llihont/two/settings/Md3BadgePainter;->LJIIIZ(" in m for m in patched_methods): + raise ValueError("Md3BadgePainter missing after patch") + if b"Llihont/two/settings/SettingsCell;" not in patched or b"transformIcon" not in patched: + raise ValueError("transformIcon hook missing in patched dex") + if dexpatch.dex_format(before) != dexpatch.dex_format(patched): + raise ValueError("MD3 settings icon hook changed DEX format") + apk.replace(name, patched) + return { + "dex": name, + "classes": [settings_patch.CELL_CLASS, settings_patch.PAINTER_CLASS], + "hook": "Llihont/two/settings/SettingsCell;->transformIcon(Ljava/lang/Object;Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/Object;", + "sha256": hashlib.sha256(patched).hexdigest(), + } + + +def patch_class(apk: Apk, tools: Toolchain, room: Path, api: int, dex_name: str, owner: str, + label: str, rewrite, marker: bytes) -> dict: + """Disassemble one class, rewrite its smali, and put the reassembled class back in its dex.""" + before = apk.read(dex_name) + folder = room / label + folder.mkdir(parents=True, exist_ok=True) + original = folder / "original.dex" + original.write_bytes(before) + decoded = folder / "smali" + subprocess.run( + ["java", "-Xmx1g", "-cp", + os.pathsep.join([tools.smali, "tools/baksmali.jar"]), + "com.android.tools.smali.baksmali.Main", "disassemble", + str(original), "--classes", owner, "-o", str(decoded)], + check=True, + ) + source = decoded / (owner[1:-1] + ".smali") + if not source.exists(): + raise ValueError("%s missing from %s" % (owner, dex_name)) + text = source.read_text(encoding="utf-8").replace("\r\n", "\n") + source.write_text(rewrite(text), encoding="utf-8", newline="\n") + + replacement = folder / "replacement.dex" + dexpatch.Smali(tools.smali, api, jobs=2, heap="1g").assemble(str(decoded), str(replacement)) + + compiler = room / "compiler" + compiler.mkdir(parents=True, exist_ok=True) + subprocess.run( + ["javac", "--release", "17", "-cp", tools.smali, "-d", str(compiler), + "src/ReplaceClasses.java", "src/MergeClasses.java"], + check=True, + ) + patched_path = folder / "patched.dex" + subprocess.run( + ["java", "-Xmx1g", "-cp", os.pathsep.join([str(compiler), tools.smali]), + "ReplaceClasses", str(original), str(replacement), str(patched_path), str(api)], + check=True, + ) + patched = patched_path.read_bytes() + if not dexpatch.defined_methods(before).issubset(dexpatch.defined_methods(patched)): + raise ValueError("%s rewrite lost existing methods" % owner) + if marker not in patched: + raise ValueError("%s rewrite did not reach the dex" % owner) + if dexpatch.dex_format(before) != dexpatch.dex_format(patched): + raise ValueError("%s rewrite changed the DEX format" % owner) + apk.replace(dex_name, patched) + return {"dex": dex_name, "class": owner, "sha256": hashlib.sha256(patched).hexdigest()} + + +def patch_native_theme(apk: Apk, tools: Toolchain, room: Path, api: int) -> dict: + """Pass TikTok's Compose colour tokens through lihont.two.theme.NativeTheme.""" + report = patch_class(apk, tools, room, api, "classes9.dex", theme_patch.ACCESSOR_CLASS, + "native-theme", theme_patch.rewrite_colors_accessor, + b"Llihont/two/theme/NativeTheme;") + report["hook"] = theme_patch.HOOK + return report + + +def patch_settings_rows(apk: Apk, tools: Toolchain, room: Path, api: int) -> dict: + """Let NativeTheme give TikTok's settings rows their own rounded shape and spacing.""" + report = patch_class(apk, tools, room, api, "classes9.dex", theme_patch.ROW_CLASS, + "native-rows", theme_patch.rewrite_row_lambda, + b"Llihont/two/theme/NativeTheme;") + report["hooks"] = theme_patch.row_targets() + return report + + +def patch_section_labels(apk: Apk, tools: Toolchain, room: Path, api: int) -> dict: + """Let NativeTheme colour the title above each settings group.""" + report = patch_class(apk, tools, room, api, "classes9.dex", theme_patch.SECTION_CLASS, + "section-labels", theme_patch.rewrite_section_label, + b"Llihont/two/theme/NativeTheme;") + report["hook"] = theme_patch.SECTION_HOOK + return report + + +def patch_language_card(apk: Apk, tools: Toolchain, room: Path, api: int) -> dict: + """Let NativeTheme drop the language row's own card inside TikTok settings.""" + report = patch_class(apk, tools, room, api, "classes9.dex", theme_patch.LANGUAGE_CLASS, + "language-card", theme_patch.rewrite_language_card, + b"Llihont/two/theme/NativeTheme;") + report["hook"] = theme_patch.CARD_HOOK + return report + + +def patch_main_activity(apk: Apk, tools: Toolchain, room: Path, api: int) -> dict: + """Tell the bottom-bar code when TikTok's main screen comes to the front.""" + report = patch_class(apk, tools, room, api, bar_patch.DEX, bar_patch.OWNER, "main-activity", + bar_patch.rewrite_main_activity, b"Llihont/two/bar/BottomBar;") + report["hook"] = bar_patch.HOOK + return report + + +def patch_downloads(apk: Apk, tools: Toolchain, room: Path, api: int) -> dict: + """Let saved videos come out of the download chain without the watermark.""" + marker = b"Llihont/two/media/Downloads;" + report = { + "source": patch_class(apk, tools, room, api, media_patch.DEX, media_patch.SOURCE_OWNER, + "download-source", media_patch.rewrite_source, marker), + "context": patch_class(apk, tools, room, api, media_patch.DEX, media_patch.CONTEXT_OWNER, + "download-context", media_patch.rewrite_context, marker), + } + menu = b"Llihont/two/media/DownloadMenu;" + for owner in media_patch.SAVE_OWNERS: + label = "download-save-" + owner[1:-1].rsplit("/", 1)[1].lower() + report["save " + owner] = patch_class(apk, tools, room, api, media_patch.DEX, owner, label, + media_patch.rewrite_save, menu) + report["photo"] = patch_class(apk, tools, room, api, media_patch.DEX, media_patch.PHOTO_OWNER, + "download-photo", media_patch.rewrite_photo, menu) + report["hooks"] = media_patch.runtime_targets() + return report + + +def patch_feed(apk: Apk, tools: Toolchain, room: Path, api: int) -> dict: + """Let lihont.two.feed.FeedFilter take advertisements and live streams out of the feed.""" + marker = b"Llihont/two/feed/FeedFilter;" + report = {} + for owner, rewrite in feed_patch.REWRITES.items(): + label = "feed-" + owner.rsplit("/", 1)[1].rstrip(";").lower() + report[owner] = patch_class(apk, tools, room, api, feed_patch.DEXES[owner], owner, label, + lambda text, rewrite=rewrite: rewrite(text)[0], marker) + report["hooks"] = feed_patch.runtime_targets() + return report + + +def patch_avatars(apk: Apk, tools: Toolchain, room: Path, api: int) -> dict: + """Let lihont.two.avatar.AvatarShapes cut every avatar to the shape chosen in the settings.""" + marker = b"Llihont/two/avatar/AvatarShapes;" + report = {"avatar": patch_class(apk, tools, room, api, avatar_patch.DEX, avatar_patch.OWNER, "avatar-view", + avatar_patch.rewrite_avatar, marker)} + report["hooks"] = avatar_patch.runtime_targets() + return report + + +def patch_badges(apk: Apk, tools: Toolchain, room: Path, api: int) -> dict: + """Let lihont.two.badge.Badges put badges next to names, and ship the two pictures TikTok You builds in.""" + marker = b"Llihont/two/badge/Badges;" + report = {} + for owner, rewrite in badge_patch.REWRITES.items(): + label = "badge-" + owner.rsplit("/", 1)[1].rstrip(";").lower() + report[owner] = patch_class(apk, tools, room, api, badge_patch.DEXES[owner], owner, label, + lambda text, rewrite=rewrite: rewrite(text)[0], marker) + shipped = [] + for name in ("supporter.png", "developer.png"): + source = Path("src/compat", name) + if not source.is_file(): + continue # third-party artwork that the repository does not carry: see src/compat/README.md + entry = "assets/lihont/compat/" + name + data = source.read_bytes() + if apk.has(entry): + apk.replace(entry, data) + else: + apk.add(entry, data) + shipped.append(name) + report["compat_pictures"] = shipped + report["hooks"] = badge_patch.runtime_targets() + return report + + +def next_dex_name(names) -> str: + """The name of the dex that comes after the last one, refusing a row with a gap (Android would stop at the gap).""" + numbers = set() + for name in names: + match = re.fullmatch(r"classes([0-9]*)\.dex", name) + if match: + numbers.add(int(match.group(1) or 1)) + if not numbers or sorted(numbers) != list(range(1, max(numbers) + 1)): + raise ValueError("The dex files are not numbered one after the other") + return "classes%d.dex" % (max(numbers) + 1) + + +def merge_runtime(host_dex: bytes, runtime_dex: bytes, tools: Toolchain, room: Path, api: int) -> bytes: + """Add the runtime classes to an existing dex with dexlib2 class merging.""" + folder = room / "runtime-merge" + folder.mkdir(parents=True, exist_ok=True) + host = folder / "host.dex" + extra = folder / "extra.dex" + merged = folder / "merged.dex" + host.write_bytes(host_dex) + extra.write_bytes(runtime_dex) + subprocess.run( + ["java", "-Xmx1g", "-cp", + os.pathsep.join([str(room / "compiler"), tools.smali]), + "MergeClasses", str(host), str(extra), str(merged), str(api)], + check=True, + ) + result = merged.read_bytes() + if dexpatch.dex_format(host_dex) != dexpatch.dex_format(result): + raise ValueError("Runtime merge changed the DEX format") + host_classes = dexpatch.defined_methods(host_dex) + merged_classes = dexpatch.defined_methods(result) + if not host_classes.issubset(merged_classes): + raise ValueError("Runtime merge lost existing classes") + if not any(m.startswith("Llihont/two/LihonTRegion;->") for m in merged_classes): + raise ValueError("Runtime merge did not add LihonTRegion") + return result + + +def patch_feature_flags(apk: Apk, tools: Toolchain, room: Path, api: int) -> dict: + """Route native profile banner and comment repost flag reads through LihonTFlags. + + Only direct SettingsManager-style reads whose String argument is a known + flag literal are rewritten; the original call stays in place and its result + goes to the LihonT switch for that flag. Verified per-dex against the + method-definition table. + """ + flags = {**profile_features.PROFILE_FLAGS, **profile_features.REPOST_FLAGS} + counts: dict = {} + changed: dict = {} + smali = dexpatch.Smali(tools.smali, api, jobs=2, heap="768m") + for name in sorted(apk.names()): + if not name.endswith(".dex"): + continue + data = apk.read(name) + if not profile_features.interesting(data, flags): + continue + owners = profile_features.literal_owners(data, flags) + if not owners: + continue + dex_room = room / ("flags-" + name[:-4]) + dex_room.mkdir(parents=True, exist_ok=True) + dex_input = dex_room / "in.dex" + dex_output = dex_room / "out.dex" + dex_input.write_bytes(data) + decoded = dex_room / "smali" + smali.disassemble(str(dex_input), str(decoded)) + originals = {} + hits = {} + try: + for path in profile_features.candidate_files(str(decoded), flags, owners): + raw = Path(path).read_bytes() + rewritten, file_hits = profile_features.rewrite_smali( + raw.decode("utf-8"), flags + ) + if not file_hits: + continue + originals[path] = raw + Path(path).write_bytes(rewritten.encode("utf-8")) + for key, count in file_hits.items(): + hits[key] = hits.get(key, 0) + count + if not hits: + print("%s: no direct flag reads" % name, flush=True) + continue + print("%s: %s" % (name, hits), flush=True) + smali.assemble(str(decoded), str(dex_output)) + patched = dex_output.read_bytes() + if dexpatch.dex_format(patched) != dexpatch.dex_format(data): + raise ValueError("DEX format changed in " + name) + if dexpatch.defined_methods(patched) != dexpatch.defined_methods(data): + raise ValueError("Class method definitions changed in " + name) + apk.replace(name, patched) + changed[name] = {"sha256": hashlib.sha256(patched).hexdigest(), "counts": hits} + for key, count in hits.items(): + counts[key] = counts.get(key, 0) + count + finally: + for path, raw in originals.items(): + Path(path).write_bytes(raw) + missing = sorted(flags.keys() - counts.keys()) + if missing: + raise ValueError("Could not verify native flag reads: " + ", ".join(missing)) + return {"counts": counts, "changed_dex": changed} + + +def build(source: str, output: str, workspace: str = "work/build") -> dict: + source_path, output_path, room = ( + Path(source).resolve(), Path(output).resolve(), Path(workspace).resolve() + ) + if source_path == output_path: + raise ValueError("Keep the source APK unchanged") + digest = hashlib.sha256(source_path.read_bytes()).hexdigest() + room.mkdir(parents=True, exist_ok=True) + tools = Toolchain("tools") + apk = Apk(str(source_path)) + report = { + "edition": "lihont", "mod_version": "2.0-test", + "source": source_path.name, "source_sha256": digest, + } + try: + xml = Axml.parse(apk.read("AndroidManifest.xml")) + from . import manifest as manifest_module + package = manifest_module.package_name(xml) + version = manifest_module.version_name(xml) + if package != "com.zhiliaoapp.musically" or version != SOURCE_VERSION: + raise ValueError("Expected TikTok " + SOURCE_VERSION + ", got " + version) + api = manifest_module.min_sdk(xml) + report["source_version"] = version + # Register the private settings screen in the host manifest. It is + # intentionally non-exported: only the in-app settings hook should + # be able to launch it. No intent-filter is added, so it cannot appear + # as a launcher entry or be reached through an external deep link. + from . import manifest as manifest_module + if not manifest_module.has_activity(xml, SETTINGS_ACTIVITY): + manifest_module.add_activity( + xml, SETTINGS_ACTIVITY, "LihonT", SETTINGS_THEME, exported=False + ) + apk.replace("AndroidManifest.xml", xml.build()) + report["manifest"] = {"settings_activity": SETTINGS_ACTIVITY, "exported": False} + else: + report["manifest"] = {"settings_activity": SETTINGS_ACTIVITY, "exported": False, "already_present": True} + # The launcher icons the settings screen offers: one disabled alias per catalog icon. + from . import app_icons + report["app_icons"] = app_icons.apply(apk, xml, app_icons.load_catalog(Path("src/icons"))) + # TikTok's small Stories widget becomes the streak widget (its picture view is all the widget needs). + from . import widget_patch + report["widget"] = widget_patch.apply(apk, xml, SETTINGS_THEME) + # The alarm of the streak keeper needs a receiver of its own (the manifest is written again with it). + from . import streak_patch + report["streak"] = streak_patch.apply(apk, xml) + report["changed_dex"] = patch_classes(apk, REGION_TARGETS, tools, room, api) + report["settings_entry"] = patch_settings_entry(apk, tools, room, api) + report["settings_icons"] = patch_md3_settings_icons(apk, tools, room, api) + report["native_theme"] = patch_native_theme(apk, tools, room, api) + report["native_rows"] = patch_settings_rows(apk, tools, room, api) + report["section_labels"] = patch_section_labels(apk, tools, room, api) + report["language_card"] = patch_language_card(apk, tools, room, api) + report["main_activity"] = patch_main_activity(apk, tools, room, api) + report["downloads"] = patch_downloads(apk, tools, room, api) + report["feed"] = patch_feed(apk, tools, room, api) + report["badges"] = patch_badges(apk, tools, room, api) + report["avatars"] = patch_avatars(apk, tools, room, api) + report["feature_flags"] = patch_feature_flags(apk, tools, room, api) + runtime_path = tools.compile_dex("src/lihont/two", str(room / "runtime"), api) + runtime = Path(runtime_path).read_bytes() + if b"Llihont/two/LihonTRegion;" not in runtime: + raise ValueError("Runtime class missing") + # The runtime used to ride along inside the patched classes35.dex, which has since run out of room (a dex + # holds at most 65536 methods and the mod grew past it). It is a dex of its own now, the next one in the + # row: Android loads classes.dex, classes2.dex, ... one after the other, and classes are found in any of them. + runtime_dex = next_dex_name(apk.names()) + apk.add(runtime_dex, runtime) + report["runtime"] = {"dex": runtime_dex, "sha256": hashlib.sha256(runtime).hexdigest()} + merged = dexpatch.defined_methods(runtime) + if not any(m.startswith("Llihont/two/LihonTRegion;->") for m in merged): + raise ValueError("LihonTRegion missing from the runtime dex") + absent = [t for t in profile_features.runtime_targets() + theme_patch.runtime_targets() + + theme_patch.section_targets() + theme_patch.row_targets() + + theme_patch.card_targets() + bar_patch.runtime_targets() + + media_patch.runtime_targets() + feed_patch.runtime_targets() + + badge_patch.runtime_targets() + avatar_patch.runtime_targets() if t not in merged] + if absent: + raise ValueError("Hooks have no runtime target: " + ", ".join(absent)) + report["feature_flags"]["runtime"] = profile_features.FLAGS_CLASS + report["region"] = { + "country": "by", "operator": "25701", "carrier": "A1 BY", + "expected_hooks": region.expected_hits(), + } + apk.drop_signature() + output_path.parent.mkdir(parents=True, exist_ok=True) + apk.write(str(output_path)) + finally: + apk.close() + tools.sign(str(output_path)) + report.update({ + "file": output_path.name, "bytes": output_path.stat().st_size, + "sha256": hashlib.sha256(output_path.read_bytes()).hexdigest(), + }) + Path(str(output_path) + ".json").write_text( + json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8" + ) + return report + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("apk") + parser.add_argument("-o", "--out", required=True) + parser.add_argument("--work", default="work/build") + args = parser.parse_args() + print(json.dumps(build(args.apk, args.out, args.work), ensure_ascii=False, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/lihont/widget_patch.py b/lihont/widget_patch.py new file mode 100644 index 0000000..aafc42b --- /dev/null +++ b/lihont/widget_patch.py @@ -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" diff --git a/scripts/make_lihont_cards.py b/scripts/make_lihont_cards.py index eb77da8..028a8e2 100644 --- a/scripts/make_lihont_cards.py +++ b/scripts/make_lihont_cards.py @@ -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() diff --git a/scripts/make_lihont_promo.py b/scripts/make_lihont_promo.py index 6bce553..f2d325c 100644 --- a/scripts/make_lihont_promo.py +++ b/scripts/make_lihont_promo.py @@ -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 diff --git a/scripts/make_widget_preview.py b/scripts/make_widget_preview.py new file mode 100644 index 0000000..a54e14b --- /dev/null +++ b/scripts/make_widget_preview.py @@ -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 = ['', + ' LihonT streak widget', + ' ' % _hex(FLOWER), + ' ' % (middle, middle, reach)] + for i in range(PETALS): + angle = i * 2 * math.pi / PETALS - math.pi / 2 + lines.append(' ' % ( + middle + math.cos(angle) * reach, middle + math.sin(angle) * reach, petal)) + lines.append(' ') + lines.append(' ' % (middle - flame / 2, SIDE * 0.10, scale)) + if close_colors: + lines.append(' ' % ( + _path_data(OUTER), _hex(INK))) + lines.append(' ' % (_path_data(OUTER), _hex(flame_color))) + lines.append(' ' % (_path_data(INNER), _hex(heart_color))) + lines.append(' ') + lines.append(' %s' % ( + middle, SIDE * 0.735, SIDE * 0.32, _hex(INK), sample)) + lines.append('') + 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()) diff --git a/scripts/quick_runtime.py b/scripts/quick_runtime.py index 0f6ea68..dc798a8 100644 --- a/scripts/quick_runtime.py +++ b/scripts/quick_runtime.py @@ -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() diff --git a/src/brand/widget_flame.svg b/src/brand/widget_flame.svg new file mode 100644 index 0000000..19bfa95 --- /dev/null +++ b/src/brand/widget_flame.svg @@ -0,0 +1,20 @@ + + LihonT streak widget + + + + + + + + + + + + + + + + + 7 + diff --git a/src/brand/widget_flame_grey.svg b/src/brand/widget_flame_grey.svg new file mode 100644 index 0000000..8943a47 --- /dev/null +++ b/src/brand/widget_flame_grey.svg @@ -0,0 +1,20 @@ + + LihonT streak widget + + + + + + + + + + + + + + + + + 7 + diff --git a/src/brand/widget_preview.png b/src/brand/widget_preview.png new file mode 100644 index 0000000..9ddcb5b Binary files /dev/null and b/src/brand/widget_preview.png differ diff --git a/src/lihont/two/account/AccountShapeBook.java b/src/lihont/two/account/AccountShapeBook.java new file mode 100644 index 0000000..5c05c41 --- /dev/null +++ b/src/lihont/two/account/AccountShapeBook.java @@ -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 shapes = new LinkedHashMap(); + 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 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; + } +} diff --git a/src/lihont/two/account/AccountShapes.java b/src/lihont/two/account/AccountShapes.java new file mode 100644 index 0000000..00c92fd --- /dev/null +++ b/src/lihont/two/account/AccountShapes.java @@ -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); + } +} diff --git a/src/lihont/two/account/CurrentAccount.java b/src/lihont/two/account/CurrentAccount.java new file mode 100644 index 0000000..9b64b47 --- /dev/null +++ b/src/lihont/two/account/CurrentAccount.java @@ -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; + } +} diff --git a/src/lihont/two/avatar/Owner.java b/src/lihont/two/avatar/Owner.java index f3caae1..e2a73a3 100644 --- a/src/lihont/two/avatar/Owner.java +++ b/src/lihont/two/avatar/Owner.java @@ -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; } diff --git a/src/lihont/two/avatar/PictureOwners.java b/src/lihont/two/avatar/PictureOwners.java index 0542c83..43822e3 100644 --- a/src/lihont/two/avatar/PictureOwners.java +++ b/src/lihont/two/avatar/PictureOwners.java @@ -61,6 +61,13 @@ public final class PictureOwners { } } + /** The accounts whose pictures have been seen so far. */ + public static java.util.Set uids() { + synchronized (OWNERS) { + return new java.util.HashSet(OWNERS.values()); + } + } + private static void remember(String id, String uid) { synchronized (OWNERS) { OWNERS.put(id, uid); diff --git a/src/lihont/two/badge/AccountNames.java b/src/lihont/two/badge/AccountNames.java index 2306492..d3f34a5 100644 --- a/src/lihont/two/badge/AccountNames.java +++ b/src/lihont/two/badge/AccountNames.java @@ -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); diff --git a/src/lihont/two/bar/AvatarBadge.java b/src/lihont/two/bar/AvatarBadge.java index 558233d..485ac4e 100644 --- a/src/lihont/two/bar/AvatarBadge.java +++ b/src/lihont/two/bar/AvatarBadge.java @@ -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()) { diff --git a/src/lihont/two/look/BlackRule.java b/src/lihont/two/look/BlackRule.java new file mode 100644 index 0000000..f3ea1da --- /dev/null +++ b/src/lihont/two/look/BlackRule.java @@ -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; + } +} diff --git a/src/lihont/two/look/TonalSurfaces.java b/src/lihont/two/look/TonalSurfaces.java new file mode 100644 index 0000000..c5bc31e --- /dev/null +++ b/src/lihont/two/look/TonalSurfaces.java @@ -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 judged = Collections.newSetFromMap(new WeakHashMap()); + + 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); + } + } +} diff --git a/src/lihont/two/look/Windows.java b/src/lihont/two/look/Windows.java index 3503bce..88c9d83 100644 --- a/src/lihont/two/look/Windows.java +++ b/src/lihont/two/look/Windows.java @@ -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. } diff --git a/src/lihont/two/settings/KeeperSettings.java b/src/lihont/two/settings/KeeperSettings.java new file mode 100644 index 0000000..29ad46f --- /dev/null +++ b/src/lihont/two/settings/KeeperSettings.java @@ -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 found = new ArrayList(); // uid, name, streak, grey ("1" or "0") + NicheClaim.Account me = NicheClaim.account(); + if (me != null) { + long now = System.currentTimeMillis(); + for (Map.Entry 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() { + @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 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); + } +} diff --git a/src/lihont/two/settings/LihonTSettingsActivity.java b/src/lihont/two/settings/LihonTSettingsActivity.java index dcc3898..f6be997 100644 --- a/src/lihont/two/settings/LihonTSettingsActivity.java +++ b/src/lihont/two/settings/LihonTSettingsActivity.java @@ -1,1455 +1,1545 @@ -package lihont.two.settings; - -import android.app.Activity; -import android.app.Dialog; -import android.content.ActivityNotFoundException; -import android.content.Context; -import android.content.Intent; -import android.graphics.Bitmap; -import android.graphics.BitmapFactory; -import android.graphics.Color; -import android.graphics.Outline; -import android.graphics.drawable.ColorDrawable; -import android.graphics.drawable.Drawable; -import android.net.Uri; -import android.os.Build; -import android.os.Bundle; -import android.os.Handler; -import android.os.Looper; -import android.text.Editable; -import android.text.InputFilter; -import android.text.TextWatcher; -import android.view.Gravity; -import android.view.View; -import android.view.ViewGroup; -import android.view.ViewOutlineProvider; -import android.view.Window; -import android.view.WindowManager; -import android.widget.BaseAdapter; -import android.widget.EditText; -import android.widget.FrameLayout; -import android.widget.ImageView; -import android.widget.LinearLayout; -import android.widget.ListView; -import android.widget.ScrollView; -import android.widget.TextView; -import android.widget.Toast; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; -import java.util.Locale; - -/** Material 3 settings screen for LihonT 2. */ -public final class LihonTSettingsActivity extends Activity { - private static final String VERSION_LINE = "LihonT 2.0 · Luna (пре-релиз)"; - private static final String BASE_LINE = "База TikTok 47.1.3"; - private static final String CHANNEL_URL = "https://t.me/lihont"; - private static final String SOURCE_URL = "https://git.lihont.space/lihont/LihonT"; - private static final String LICENSE_URL = SOURCE_URL + "/src/branch/main/LICENSE"; - private static final String CHANGES = - "• Material 3 в TikTok: нижняя панель с кнопкой «+», меню профиля, профили, настройки и комментарии.\n" - + "• Свой цвет оформления или цвет телефона, один цвет у всех цветочков, чёрный фон AMOLED.\n" - + "• Форма аватарок: круг, цветочек, квадрат, шестиугольник, сердечко, треугольник. Ваша форма видна другим с модом.\n" - + "• Компактная нижняя панель без подписей.\n" - + "• Меню сохранения: качество от меньшего к большему, только звук, фото без водяного знака.\n" - + "• Переключатели рекламы, эфиров и вкладки «Магазин» в ленте.\n" - + "• Значки TikTok You и MargyT рядом с ником и значок «Нишевый мод»."; - private static final String DISCLAIMER = - "Бесплатная модификация TikTok для Android. Проект не связан с ByteDance и TikTok Pte. Ltd."; - - private SettingsRepository repository; - private ModSettings settings; - private Md3.Palette palette; - private LinearLayout content; - private TextView status; - private FrameLayout host; - private View snackbar; - private int bottomInset; - private final Handler handler = new Handler(Looper.getMainLooper()); - private final Runnable hideSnackbar = this::dismissRestartNotice; - - // The "Свой значок" screen: a full-screen dialog that lives on top of this activity. - private CustomIconStore iconStore; - private Dialog iconsDialog; - private LinearLayout iconsList; - private FrameLayout iconsHost; - private View iconsNotice; - private int iconCountShown; - private final Runnable hideIconsNotice = this::dismissIconsNotice; - - /** Entry point for the TikTok Settings hook; the activity stays non-exported. */ - public static Intent intent(Context context) { - return new Intent(context, LihonTSettingsActivity.class); - } - - @Override public void onCreate(Bundle state) { - super.onCreate(state); - try { - repository = SettingsHost.repository(this); - settings = repository.current(); - lihont.two.LihonTRegion.setRegion(settings.region()); - } catch (IOException | RuntimeException error) { - showStorageError(); - return; - } - iconStore = new CustomIconStore(IconShortcuts.directory(this)); - palette = Md3.palette(this, settings); - Window window = getWindow(); - window.setBackgroundDrawable(new ColorDrawable(palette.surface)); - window.setStatusBarColor(palette.surface); - window.setNavigationBarColor(palette.surface); - if (Build.VERSION.SDK_INT >= 29) { - window.setNavigationBarContrastEnforced(false); - window.setStatusBarContrastEnforced(false); - } - updateSystemBars(window, palette.dark); - buildScreen(); - } - - // ---- screen ------------------------------------------------------------ - - private void buildScreen() { - handler.removeCallbacks(hideSnackbar); - snackbar = null; - LinearLayout root = new LinearLayout(this); - root.setOrientation(LinearLayout.VERTICAL); - root.setBackgroundColor(palette.surface); - - root.addView(Md3.appBar(this, palette, "Настройки мода", Md3Icon.BACK, "Назад", v -> finish())); - - ScrollView scroll = new ScrollView(this); - scroll.setFillViewport(true); - scroll.setClipToPadding(false); - scroll.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS); - scroll.setFocusable(true); - scroll.setFocusableInTouchMode(true); - content = new LinearLayout(this); - content.setOrientation(LinearLayout.VERTICAL); - content.setPadding(0, 0, 0, Md3.dp(this, 32)); - scroll.addView(content, new ScrollView.LayoutParams(-1, -2)); - root.addView(scroll, new LinearLayout.LayoutParams(-1, 0, 1f)); - applyInsets(root, scroll); - host = new FrameLayout(this); - host.addView(root, new FrameLayout.LayoutParams( - ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); - setContentView(host); - - content.addView(Md3.subheader(this, palette, "Функции")); - LinearLayout cardFunc = Md3.card(this, palette); - cardFunc.addView(switchRow("Баннеры профиля", "Карточки и фон в шапке профиля", - Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.BANNER, palette.onPrimaryContainer, 8), - settings.profileBanners(), TOGGLE_BANNERS)); - cardFunc.addView(Md3.cardDivider(this, palette)); - cardFunc.addView(switchRow("Репост комментариев", "Действие репоста у комментария", - Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.REPOST, palette.onPrimaryContainer, 8), - settings.commentReposts(), TOGGLE_REPOSTS)); - cardFunc.addView(Md3.cardDivider(this, palette)); - cardFunc.addView(switchRow("Интерфейс в стиле MD3", - "Нижняя панель, меню профиля и настройки TikTok. Выключено: вид Serena 1.2", - Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.BOTTOM_BAR, palette.onPrimaryContainer, 8), - settings.md3(), TOGGLE_MD3)); - cardFunc.addView(Md3.cardDivider(this, palette)); - cardFunc.addView(switchRow("Скачивание без водяного знака", "Сохранённые видео без логотипа TikTok", - Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.DOWNLOAD, palette.onPrimaryContainer, 8), - settings.noWatermark(), TOGGLE_NO_WATERMARK)); - cardFunc.addView(Md3.cardDivider(this, palette)); - cardFunc.addView(switchRow("Меню сохранения", "Качество от меньшего к большему, только звук, фото карусели", - Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.DOWNLOAD, palette.onPrimaryContainer, 8), - settings.downloadMenu(), TOGGLE_MENU)); - content.addView(cardFunc); - - content.addView(Md3.subheader(this, palette, "Лента")); - LinearLayout cardFeed = Md3.card(this, palette); - cardFeed.addView(switchRow("Убрать рекламу", "Рекламные ролики и вставки между видео", - Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.AD_OFF, palette.onPrimaryContainer, 8), - settings.hideAds(), TOGGLE_ADS)); - cardFeed.addView(Md3.cardDivider(this, palette)); - cardFeed.addView(switchRow("Убрать эфиры из ленты", "Прямые трансляции не появляются между видео", - Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.LIVE, palette.onPrimaryContainer, 8), - settings.hideLive(), TOGGLE_LIVE)); - cardFeed.addView(Md3.cardDivider(this, palette)); - cardFeed.addView(switchRow("Убрать раздел «Магазин»", "Вкладка над лентой. В бете может сбиться полоса под вкладками", - Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.SHOP, palette.onPrimaryContainer, 8), - settings.hideShop(), TOGGLE_SHOP)); - content.addView(cardFeed); - - content.addView(Md3.subheader(this, palette, "Значки в именах")); - LinearLayout cardBadges = Md3.card(this, palette); - cardBadges.addView(switchRow("Значки других модов", "TikTok You и MargyT рядом с ником", - Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.NOTE, palette.onPrimaryContainer, 8), - settings.foreignBadges(), TOGGLE_BADGES)); - cardBadges.addView(Md3.cardDivider(this, palette)); - cardBadges.addView(nicheRow()); - content.addView(cardBadges); - - content.addView(Md3.subheader(this, palette, "Параметры")); - LinearLayout cardParams = Md3.card(this, palette); - cardParams.addView(regionRow()); - cardParams.addView(Md3.cardDivider(this, palette)); - cardParams.addView(themeRow()); - cardParams.addView(Md3.cardDivider(this, palette)); - cardParams.addView(accentRow()); - cardParams.addView(Md3.cardDivider(this, palette)); - cardParams.addView(shapeRow()); - cardParams.addView(Md3.cardDivider(this, palette)); - cardParams.addView(switchRow("AMOLED: чёрный фон", "Чистый чёрный в тёмной теме", - Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.MOON, palette.onPrimaryContainer, 8), - settings.amoled(), TOGGLE_AMOLED)); - cardParams.addView(Md3.cardDivider(this, palette)); - cardParams.addView(switchRow("Компактная нижняя панель", "Без подписей под значками", - Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.BOTTOM_BAR, palette.onPrimaryContainer, 8), - settings.compactBar(), TOGGLE_COMPACT)); - content.addView(cardParams); - - content.addView(Md3.subheader(this, palette, "Значок")); - LinearLayout cardIcon = Md3.card(this, palette); - View appIcon = appIconRow(); - if (appIcon != null) { - cardIcon.addView(appIcon); - cardIcon.addView(Md3.cardDivider(this, palette)); - } - cardIcon.addView(iconsRow()); - content.addView(cardIcon); - - content.addView(Md3.subheader(this, palette, "О моде")); - LinearLayout cardAbout = Md3.card(this, palette); - cardAbout.addView(Md3.listItem(this, palette, - Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.INFO, palette.onPrimaryContainer, 8), - "Версия", VERSION_LINE, null, false)); - cardAbout.addView(Md3.cardDivider(this, palette)); - cardAbout.addView(Md3.listItem(this, palette, - Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.TIKTOK, palette.onPrimaryContainer, 8), - "База", BASE_LINE, null, false)); - cardAbout.addView(Md3.cardDivider(this, palette)); - cardAbout.addView(Md3.cardDivider(this, palette)); - cardAbout.addView(linkRow("Что нового", "Что есть в этой версии", Md3Icon.INFO, null)); - cardAbout.addView(Md3.cardDivider(this, palette)); - cardAbout.addView(telegramRow()); - cardAbout.addView(Md3.cardDivider(this, palette)); - cardAbout.addView(linkRow("Исходный код", SOURCE_URL, Md3Icon.CODE, SOURCE_URL)); - cardAbout.addView(Md3.cardDivider(this, palette)); - cardAbout.addView(linkRow("Лицензия", "EVHNMKHU", Md3Icon.INFO, LICENSE_URL)); - content.addView(cardAbout); - - status = Md3.text(this, "", Md3.BODY_SMALL, false, palette.onSurfaceVariant); - status.setGravity(Gravity.CENTER_HORIZONTAL); - status.setPadding(Md3.dp(this, 24), Md3.dp(this, 8), Md3.dp(this, 24), Md3.dp(this, 4)); - content.addView(status); - - TextView disclaimer = Md3.text(this, DISCLAIMER, Md3.BODY_SMALL, false, palette.onSurfaceVariant); - disclaimer.setGravity(Gravity.CENTER_HORIZONTAL); - disclaimer.setPadding(Md3.dp(this, 24), Md3.dp(this, 4), Md3.dp(this, 24), Md3.dp(this, 12)); - content.addView(disclaimer); - - LinearLayout actions = new LinearLayout(this); - actions.setOrientation(LinearLayout.VERTICAL); - actions.setGravity(Gravity.CENTER_HORIZONTAL); - actions.setPadding(Md3.dp(this, 16), Md3.dp(this, 8), Md3.dp(this, 16), Md3.dp(this, 16)); - if (repository.restartRequired()) { - TextView restartBtn = Md3.filledButton(this, palette, "Перезагрузить и очистить кэш"); - restartBtn.setOnClickListener(v -> showRestartDialog()); - LinearLayout.LayoutParams restartParams = new LinearLayout.LayoutParams(-2, -2); - restartParams.bottomMargin = Md3.dp(this, 12); - actions.addView(restartBtn, restartParams); - } - TextView reset = Md3.filledTonalButton(this, palette, "Сбросить настройки"); - reset.setOnClickListener(v -> confirmReset()); - actions.addView(reset); - content.addView(actions); - - updateStatus(); - } - - private static final int TOGGLE_BANNERS = 0; - private static final int TOGGLE_REPOSTS = 1; - private static final int TOGGLE_MD3 = 2; - private static final int TOGGLE_NO_WATERMARK = 3; - private static final int TOGGLE_ADS = 4; - private static final int TOGGLE_LIVE = 5; - private static final int TOGGLE_SHOP = 6; - private static final int TOGGLE_BADGES = 7; - private static final int TOGGLE_AMOLED = 8; - private static final int TOGGLE_COMPACT = 9; - private static final int TOGGLE_MENU = 10; - - private ModSettings withToggle(int which, boolean value) { - if (which == TOGGLE_BANNERS) return settings.withProfileBanners(value); - if (which == TOGGLE_REPOSTS) return settings.withCommentReposts(value); - if (which == TOGGLE_NO_WATERMARK) return settings.withNoWatermark(value); - if (which == TOGGLE_ADS) return settings.withHideAds(value); - if (which == TOGGLE_LIVE) return settings.withHideLive(value); - if (which == TOGGLE_SHOP) return settings.withHideShop(value); - if (which == TOGGLE_BADGES) return settings.withForeignBadges(value); - if (which == TOGGLE_AMOLED) return settings.withAmoled(value); - if (which == TOGGLE_COMPACT) return settings.withCompactBar(value); - if (which == TOGGLE_MENU) return settings.withDownloadMenu(value); - return settings.withMd3(value); - } - - private boolean toggleValue(int which) { - if (which == TOGGLE_BANNERS) return settings.profileBanners(); - if (which == TOGGLE_REPOSTS) return settings.commentReposts(); - if (which == TOGGLE_NO_WATERMARK) return settings.noWatermark(); - if (which == TOGGLE_ADS) return settings.hideAds(); - if (which == TOGGLE_LIVE) return settings.hideLive(); - if (which == TOGGLE_SHOP) return settings.hideShop(); - if (which == TOGGLE_BADGES) return settings.foreignBadges(); - if (which == TOGGLE_AMOLED) return settings.amoled(); - if (which == TOGGLE_COMPACT) return settings.compactBar(); - if (which == TOGGLE_MENU) return settings.downloadMenu(); - return settings.md3(); - } - - private View switchRow(String title, String hint, View leading, boolean checked, final int which) { - Md3Switch toggle = new Md3Switch(this, palette); - toggle.setContentDescription(title); - toggle.setChecked(checked, false); - toggle.setOnCheckedChangeListener((view, value) -> { - if (!persist(withToggle(which, value))) { - view.setChecked(toggleValue(which), true); - } else if (repository.restartRequired()) { - showRestartNotice(); - } - }); - LinearLayout row = Md3.listItem(this, palette, leading, title, hint, toggle, true); - row.setOnClickListener(v -> toggle.toggle()); - return row; - } - - private View regionRow() { - View trailing = Md3.chevron(this, palette); - trailing.setTag("region"); - String label = countryLabel(settings.region()); - String subtitle = settings.needsBannerWarning() ? label : (label + " · по умолчанию"); - LinearLayout row = Md3.listItem(this, palette, - Md3.flowerAvatar(this, palette.primaryContainer, palette.onPrimaryContainer, settings.region(), 8), - "Регион мода", subtitle, trailing, true); - row.setOnClickListener(v -> openRegionPicker()); - return row; - } - - private View themeRow() { - View trailing = Md3.chevron(this, palette); - int themeIcon = palette.dark ? Md3Icon.MOON : Md3Icon.SUN; - LinearLayout row = Md3.listItem(this, palette, - Md3.flowerIconAvatar(this, palette.primaryContainer, themeIcon, palette.onPrimaryContainer, 8), - "Тема оформления", themeLabel(settings.theme()), trailing, true); - row.setOnClickListener(v -> openThemePicker()); - return row; - } - - private View accentRow() { - View trailing = Md3.chevron(this, palette); - int swatch = Md3.swatch(this, settings.accent(), settings.accentHue(), settings.theme()); - LinearLayout row = Md3.listItem(this, palette, - Md3.flowerAvatar(this, swatch, Md3.onSwatch(swatch), "", 8), - "Цвет оформления", accentLabel(settings.accent()), trailing, true); - row.setOnClickListener(v -> openAccentPicker()); - return row; - } - - private View shapeRow() { - ShapeView preview = shapeView(settings.avatarShape(), 40); - LinearLayout row = Md3.listItem(this, palette, preview, "Форма аватарок", - shapeLabel(settings.avatarShape()), Md3.chevron(this, palette), true); - row.setOnClickListener(v -> openShapePicker()); - return row; - } - - private ShapeView shapeView(ModSettings.AvatarShape shape, int sizeDp) { - ShapeView view = new ShapeView(this, shape, palette.primaryContainer); - view.setLayoutParams(new LinearLayout.LayoutParams(Md3.dp(this, sizeDp), Md3.dp(this, sizeDp))); - return view; - } - - private void openShapePicker() { - final Dialog dialog = new Dialog(this); - dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); - LinearLayout root = new LinearLayout(this); - root.setOrientation(LinearLayout.VERTICAL); - root.setBackground(Md3.shape(palette.surfaceContainerHigh, Md3.dialogRadius(palette), this)); - root.setPadding(0, Md3.dp(this, 8), 0, Md3.dp(this, 8)); - for (final ModSettings.AvatarShape option : ModSettings.AvatarShape.values()) { - View trailing = null; - if (option == settings.avatarShape()) { - ImageView check = new ImageView(this); - check.setImageDrawable(Md3Icon.of(Md3Icon.CHECK, palette.primary, this)); - check.setScaleType(ImageView.ScaleType.CENTER); - check.setLayoutParams(new LinearLayout.LayoutParams(Md3.dp(this, 24), Md3.dp(this, 24))); - trailing = check; - } - LinearLayout row = Md3.listItem(this, palette, shapeView(option, 40), shapeLabel(option), null, - trailing, true); - row.setOnClickListener(v -> { - dialog.dismiss(); - if (persist(settings.withAvatarShape(option))) shareShape(option); - }); - root.addView(row); - } - ScrollView scroll = new ScrollView(this); - scroll.addView(root); - dialog.setContentView(scroll); - styleDialog(dialog); - dialog.show(); - sizeDialog(dialog, 0.85f); - } - - /** Publishes the chosen shape for other members; asks for the code in the bio when the account is not proven yet. */ - private void shareShape(final ModSettings.AvatarShape option) { - lihont.two.avatar.ShapePublisher.publish(this, option, result -> { - if (result.published) { - Toast.makeText(this, result.message, Toast.LENGTH_LONG).show(); - } else if (result.code != null) { - openShapeProofDialog(option, result.code); - } else { - Toast.makeText(this, result.message, Toast.LENGTH_LONG).show(); - } - }); - } - - private void openShapeProofDialog(final ModSettings.AvatarShape option, final String proof) { - final Dialog dialog = new Dialog(this); - dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); - LinearLayout box = new LinearLayout(this); - box.setOrientation(LinearLayout.VERTICAL); - box.setPadding(Md3.dp(this, 24), Md3.dp(this, 24), Md3.dp(this, 24), Md3.dp(this, 16)); - box.setBackground(Md3.shape(palette.surfaceContainerHigh, Md3.dialogRadius(palette), this)); - box.addView(Md3.text(this, "Показать форму другим", Md3.HEADLINE_SMALL, false, palette.onSurface)); - final TextView info = Md3.text(this, - "У вас форма уже стоит. Чтобы её видели и другие с модом, сервер должен убедиться, что аккаунт ваш.\n" - + "1. Скопируйте код.\n2. Вставьте его в описание профиля TikTok.\n" - + "3. Нажмите «Проверить»: после этого форму можно менять без кода.", - Md3.BODY_MEDIUM, false, palette.onSurfaceVariant); - info.setPadding(0, Md3.dp(this, 12), 0, Md3.dp(this, 12)); - box.addView(info); - box.addView(Md3.text(this, proof, Md3.TITLE_LARGE, true, palette.primary)); - final TextView result = Md3.text(this, "", Md3.BODY_MEDIUM, false, palette.onSurface); - result.setPadding(0, Md3.dp(this, 12), 0, 0); - box.addView(result); - LinearLayout buttons = new LinearLayout(this); - buttons.setGravity(Gravity.END); - buttons.setPadding(0, Md3.dp(this, 16), 0, 0); - TextView copy = Md3.textButton(this, palette, "Скопировать"); - TextView check = Md3.filledButton(this, palette, "Проверить"); - TextView close = Md3.textButton(this, palette, "Закрыть"); - buttons.addView(close); - buttons.addView(copy); - buttons.addView(check); - box.addView(buttons); - close.setOnClickListener(v -> dialog.dismiss()); - copy.setOnClickListener(v -> { - android.content.ClipboardManager clipboard = - (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); - clipboard.setPrimaryClip(android.content.ClipData.newPlainText("LihonT", proof)); - result.setText("Код скопирован"); - }); - check.setOnClickListener(v -> { - result.setText("Проверяем…"); - lihont.two.avatar.ShapePublisher.publish(this, option, outcome -> { - result.setText(outcome.message); - if (outcome.published) Toast.makeText(this, outcome.message, Toast.LENGTH_LONG).show(); - }); - }); - dialog.setContentView(box); - styleDialog(dialog); - dialog.show(); - sizeDialog(dialog, 0.92f); - } - - private String shapeLabel(ModSettings.AvatarShape shape) { - switch (shape) { - case FLOWER: return "Цветочек"; - case SQUIRCLE: return "Скруглённый квадрат"; - case HEXAGON: return "Шестиугольник"; - case HEART: return "Сердечко"; - case TRIANGLE: return "Треугольник"; - default: return "Круг (как в TikTok)"; - } - } - - private void openAccentPicker() { - final Dialog dialog = new Dialog(this); - dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); - LinearLayout root = new LinearLayout(this); - root.setOrientation(LinearLayout.VERTICAL); - root.setBackground(Md3.shape(palette.surfaceContainerHigh, Md3.dialogRadius(palette), this)); - root.setPadding(0, Md3.dp(this, 8), 0, Md3.dp(this, 8)); - for (final ModSettings.Accent option : ModSettings.Accent.values()) { - View trailing = null; - if (option == settings.accent()) { - ImageView check = new ImageView(this); - check.setImageDrawable(Md3Icon.of(Md3Icon.CHECK, palette.primary, this)); - check.setScaleType(ImageView.ScaleType.CENTER); - check.setLayoutParams(new LinearLayout.LayoutParams(Md3.dp(this, 24), Md3.dp(this, 24))); - trailing = check; - } - int swatch = Md3.swatch(this, option, settings.accentHue(), settings.theme()); - LinearLayout row = Md3.listItem(this, palette, - Md3.flowerAvatar(this, swatch, Md3.onSwatch(swatch), "", 8), - accentLabel(option), null, trailing, true); - row.setOnClickListener(v -> { - dialog.dismiss(); - if (option == ModSettings.Accent.CUSTOM) { - openHueDialog(); - } else { - persist(settings.withAccent(option)); - } - }); - root.addView(row); - } - ScrollView scroll = new ScrollView(this); - scroll.addView(root); - dialog.setContentView(scroll); - styleDialog(dialog); - dialog.show(); - sizeDialog(dialog, 0.85f); - } - - private String accentLabel(ModSettings.Accent accent) { - switch (accent) { - case VIOLET: return "Фиолетовый"; - case BLUE: return "Синий"; - case TEAL: return "Бирюзовый"; - case GREEN: return "Зелёный"; - case ROSE: return "Розовый"; - case ORANGE: return "Оранжевый"; - case CUSTOM: return "Свой цвет"; - default: return "Как у телефона"; - } - } - - /** The own colour: drag along the rainbow, see the flower take the hue, then keep it. */ - private void openHueDialog() { - final int[] chosen = {settings.accent() == ModSettings.Accent.CUSTOM ? settings.accentHue() - : settings.accent().hue() >= 0 ? settings.accent().hue() : settings.accentHue()}; - final Dialog dialog = new Dialog(this); - dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); - LinearLayout root = new LinearLayout(this); - root.setOrientation(LinearLayout.VERTICAL); - root.setBackground(Md3.shape(palette.surfaceContainerHigh, Md3.dialogRadius(palette), this)); - root.setPadding(Md3.dp(this, 24), Md3.dp(this, 24), Md3.dp(this, 24), Md3.dp(this, 16)); - root.addView(Md3.text(this, "Свой цвет", Md3.HEADLINE_SMALL, false, palette.onSurface)); - final LinearLayout preview = new LinearLayout(this); - preview.setGravity(Gravity.CENTER_VERTICAL); - preview.setPadding(0, Md3.dp(this, 16), 0, Md3.dp(this, 4)); - root.addView(preview); - final TextView hint = Md3.text(this, "", Md3.BODY_MEDIUM, false, palette.onSurfaceVariant); - hint.setPadding(0, Md3.dp(this, 4), 0, Md3.dp(this, 8)); - root.addView(hint); - final Runnable refresh = new Runnable() { - @Override public void run() { - int color = Md3.swatch(LihonTSettingsActivity.this, ModSettings.Accent.CUSTOM, chosen[0], - settings.theme()); - preview.removeAllViews(); - preview.addView(Md3.flowerAvatar(LihonTSettingsActivity.this, color, Md3.onSwatch(color), "", 8)); - hint.setText("Оттенок " + chosen[0] + "°. Все цветочки и переключатели возьмут этот цвет " - + "после перезапуска TikTok."); - } - }; - HuePicker picker = new HuePicker(this, chosen[0], new HuePicker.Listener() { - @Override public void onHue(int hue) { - chosen[0] = hue; - refresh.run(); - } - }); - root.addView(picker, new LinearLayout.LayoutParams(-1, -2)); - LinearLayout buttons = new LinearLayout(this); - buttons.setGravity(Gravity.END); - buttons.setPadding(0, Md3.dp(this, 12), 0, 0); - TextView cancel = Md3.textButton(this, palette, "Отмена"); - TextView done = Md3.filledButton(this, palette, "Готово"); - cancel.setOnClickListener(v -> dialog.dismiss()); - done.setOnClickListener(v -> { - dialog.dismiss(); - persist(settings.withAccentHue(chosen[0]).withAccent(ModSettings.Accent.CUSTOM)); - }); - buttons.addView(cancel); - buttons.addView(done); - root.addView(buttons); - refresh.run(); - dialog.setContentView(root); - styleDialog(dialog); - dialog.show(); - sizeDialog(dialog, 0.92f); - } - - /** A row of the About card: opens a link, or the list of changes when there is no link. */ - private View linkRow(String title, String hint, int icon, final String url) { - LinearLayout row = Md3.listItem(this, palette, - Md3.flowerIconAvatar(this, palette.primaryContainer, icon, palette.onPrimaryContainer, 8), - title, hint, url == null ? Md3.chevron(this, palette) : null, true); - if (url == null) { - row.setOnClickListener(v -> basicDialog("Что нового", CHANGES, null, "Закрыть", null)); - } else { - row.setOnClickListener(v -> openUrl(url)); - } - return row; - } - - private View telegramRow() { - LinearLayout row = Md3.listItem(this, palette, - Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.SEND, palette.onPrimaryContainer, 8), - "Telegram-канал", CHANNEL_URL, null, true); - row.setOnClickListener(v -> openUrl(CHANNEL_URL)); - return row; - } - - // ---- niche mod badge --------------------------------------------------- - - private View nicheRow() { - LinearLayout row = Md3.listItem(this, palette, - Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.NOTE, palette.onPrimaryContainer, 8), - "Значок «Нишевый мод»", "Получить можно до 15 ноября 12:34 (МСК)", Md3.chevron(this, palette), true); - row.setOnClickListener(v -> openNicheDialog()); - return row; - } - - private void openNicheDialog() { - final lihont.two.badge.NicheClaim.Account account = lihont.two.badge.NicheClaim.account(); - final Dialog dialog = new Dialog(this); - dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); - LinearLayout box = new LinearLayout(this); - box.setOrientation(LinearLayout.VERTICAL); - box.setPadding(Md3.dp(this, 24), Md3.dp(this, 24), Md3.dp(this, 24), Md3.dp(this, 16)); - box.setBackground(Md3.shape(palette.surfaceContainerHigh, Md3.dialogRadius(palette), this)); - box.addView(Md3.text(this, "Значок «Нишевый мод»", Md3.HEADLINE_SMALL, false, palette.onSurface)); - final TextView info = Md3.text(this, account == null - ? "Войдите в TikTok, чтобы получить значок." - : "1. Скопируйте код.\n2. Вставьте его в описание профиля TikTok.\n3. Нажмите «Проверить»: " - + "сервер найдёт код и выдаст значок. Он будет виден рядом с вашим ником у всех с модом.", - Md3.BODY_MEDIUM, false, palette.onSurfaceVariant); - info.setPadding(0, Md3.dp(this, 12), 0, Md3.dp(this, 12)); - box.addView(info); - final TextView code = Md3.text(this, account == null ? "" : "…", Md3.TITLE_LARGE, true, palette.primary); - box.addView(code); - final TextView result = Md3.text(this, "", Md3.BODY_MEDIUM, false, palette.onSurface); - result.setPadding(0, Md3.dp(this, 12), 0, 0); - box.addView(result); - LinearLayout buttons = new LinearLayout(this); - buttons.setGravity(Gravity.END); - buttons.setPadding(0, Md3.dp(this, 16), 0, 0); - TextView copy = Md3.textButton(this, palette, "Скопировать"); - TextView check = Md3.filledButton(this, palette, "Проверить"); - TextView close = Md3.textButton(this, palette, "Закрыть"); - buttons.addView(close); - buttons.addView(copy); - buttons.addView(check); - box.addView(buttons); - close.setOnClickListener(v -> dialog.dismiss()); - if (account != null) { - lihont.two.badge.NicheClaim.fetchCode(account, (ok, message, value) -> { - code.setText(ok ? value : ""); - if (!ok) result.setText(message); - }); - copy.setOnClickListener(v -> { - android.content.ClipboardManager clipboard = - (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); - clipboard.setPrimaryClip(android.content.ClipData.newPlainText("LihonT", code.getText())); - result.setText("Код скопирован"); - }); - check.setOnClickListener(v -> { - result.setText("Проверяем…"); - lihont.two.badge.NicheClaim.claim(account, (ok, message, value) -> result.setText(message)); - }); - } - dialog.setContentView(box); - styleDialog(dialog); - dialog.show(); - sizeDialog(dialog, 0.92f); - } - - // ---- app icon ---------------------------------------------------------- - - /** The row that opens the choice of built-in app icons; null when this build ships none. */ - private View appIconRow() { - List choices = AppIcons.list(this); - if (choices.size() < 2) return null; - AppIcons.Choice current = choices.get(0); - for (AppIcons.Choice choice : choices) { - if (choice.selected) current = choice; - } - LinearLayout row = Md3.listItem(this, palette, iconPreview(current.icon), "Значок приложения", - current.title, Md3.chevron(this, palette), true); - row.setOnClickListener(v -> openAppIconPicker()); - return row; - } - - /** An app icon as a 40dp rounded square, the way the launcher masks it. */ - private ImageView iconPreview(Drawable icon) { - final int size = Md3.dp(this, 40); - ImageView view = new ImageView(this); - view.setImageDrawable(icon); - view.setScaleType(ImageView.ScaleType.CENTER_CROP); - view.setOutlineProvider(new ViewOutlineProvider() { - @Override public void getOutline(View v, Outline outline) { - outline.setRoundRect(0, 0, v.getWidth(), v.getHeight(), size * 0.24f); - } - }); - view.setClipToOutline(true); - view.setLayoutParams(new LinearLayout.LayoutParams(size, size)); - return view; - } - - private void openAppIconPicker() { - final Dialog dialog = new Dialog(this); - dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); - LinearLayout list = new LinearLayout(this); - list.setOrientation(LinearLayout.VERTICAL); - list.setPadding(0, Md3.dp(this, 8), 0, Md3.dp(this, 8)); - TextView title = Md3.text(this, "Значок приложения", Md3.HEADLINE_SMALL, false, palette.onSurface); - title.setPadding(Md3.dp(this, 24), Md3.dp(this, 16), Md3.dp(this, 24), Md3.dp(this, 8)); - list.addView(title); - for (final AppIcons.Choice choice : AppIcons.list(this)) { - View trailing = null; - if (choice.selected) { - ImageView check = new ImageView(this); - check.setImageDrawable(Md3Icon.of(Md3Icon.CHECK, palette.primary, this)); - check.setScaleType(ImageView.ScaleType.CENTER); - check.setLayoutParams(new LinearLayout.LayoutParams(Md3.dp(this, 24), Md3.dp(this, 24))); - trailing = check; - } - LinearLayout row = Md3.listItem(this, palette, iconPreview(choice.icon), choice.title, null, trailing, true); - row.setOnClickListener(v -> { - dialog.dismiss(); - chooseAppIcon(choice); - }); - list.addView(row); - } - ScrollView scroll = new ScrollView(this); - scroll.addView(list, new ScrollView.LayoutParams(-1, -2)); - scroll.setBackground(Md3.shape(palette.surfaceContainerHigh, Md3.dialogRadius(palette), this)); - dialog.setContentView(scroll); - styleDialog(dialog); - dialog.show(); - sizeDialog(dialog, 0.9f); - } - - private void chooseAppIcon(AppIcons.Choice choice) { - if (choice.selected) return; - boolean done = AppIcons.select(this, choice.component); - buildScreen(); - showNotice(done - ? "Значок сменится через несколько секунд. Если не изменился, перезапустите лончер." - : "Не удалось сменить значок"); - } - - // ---- custom icon ------------------------------------------------------- - - private View iconsRow() { - int count = iconStore.list().size(); - iconCountShown = count; - String hint = count == 0 ? "Своё фото как значок на главном экране" : "Сохранено значков: " + count; - LinearLayout row = Md3.listItem(this, palette, - Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.ADD_PHOTO, palette.onPrimaryContainer, 8), - "Свой значок", hint, Md3.chevron(this, palette), true); - row.setOnClickListener(v -> openIconsScreen()); - return row; - } - - private void openIconsScreen() { - final Dialog dialog = new Dialog(this); - dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); - LinearLayout root = new LinearLayout(this); - root.setOrientation(LinearLayout.VERTICAL); - root.setBackgroundColor(palette.surface); - applyInsets(root); - root.addView(Md3.appBar(this, palette, "Свой значок", Md3Icon.CLOSE, "Закрыть", v -> dialog.dismiss())); - ScrollView scroll = new ScrollView(this); - scroll.setFillViewport(true); - iconsList = new LinearLayout(this); - iconsList.setOrientation(LinearLayout.VERTICAL); - scroll.addView(iconsList, new ScrollView.LayoutParams(-1, -2)); - root.addView(scroll, new LinearLayout.LayoutParams(-1, 0, 1f)); - iconsHost = new FrameLayout(this); - iconsHost.addView(root, new FrameLayout.LayoutParams(-1, -1)); - iconsDialog = dialog; - dialog.setOnDismissListener(d -> { - handler.removeCallbacks(hideIconsNotice); - iconsDialog = null; - iconsList = null; - iconsHost = null; - iconsNotice = null; - if (iconStore.list().size() != iconCountShown) buildScreen(); - }); - renderIcons(); - dialog.setContentView(iconsHost); - styleDialog(dialog); - dialog.show(); - if (dialog.getWindow() != null) { - dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); - } - } - - private void renderIcons() { - if (iconsList == null) return; - iconsList.removeAllViews(); - TextView intro = Md3.text(this, - "Выберите фото: оно станет значком TikTok на главном экране. Значок самого приложения в меню остаётся прежним.", - Md3.BODY_MEDIUM, false, palette.onSurfaceVariant); - intro.setPadding(Md3.dp(this, 24), Md3.dp(this, 8), Md3.dp(this, 24), Md3.dp(this, 16)); - iconsList.addView(intro); - - TextView add = Md3.filledTonalButton(this, palette, "Добавить фото"); - add.setOnClickListener(v -> pickIcon()); - LinearLayout.LayoutParams addParams = new LinearLayout.LayoutParams(-2, -2); - addParams.leftMargin = Md3.dp(this, 16); - addParams.bottomMargin = Md3.dp(this, 8); - iconsList.addView(add, addParams); - - if (!IconShortcuts.canPin(this)) { - TextView unsupported = Md3.text(this, - "Этот лончер не умеет закреплять ярлыки: значки можно сохранить, но вынести на экран не получится.", - Md3.BODY_SMALL, false, palette.error); - unsupported.setPadding(Md3.dp(this, 24), Md3.dp(this, 8), Md3.dp(this, 24), Md3.dp(this, 8)); - iconsList.addView(unsupported); - } - - final List entries = iconStore.list(); - if (entries.isEmpty()) { - TextView empty = Md3.text(this, "Пока нет значков", Md3.BODY_MEDIUM, false, palette.onSurfaceVariant); - empty.setPadding(Md3.dp(this, 24), Md3.dp(this, 16), Md3.dp(this, 24), Md3.dp(this, 8)); - iconsList.addView(empty); - return; - } - iconsList.addView(Md3.subheader(this, palette, "Мои значки")); - LinearLayout card = Md3.card(this, palette); - for (int i = 0; i < entries.size(); i++) { - if (i > 0) card.addView(Md3.cardDivider(this, palette)); - card.addView(iconRow(entries.get(i))); - } - iconsList.addView(card); - } - - private View iconRow(final CustomIconStore.Entry entry) { - int size = Md3.dp(this, 40); - ImageView preview = new ImageView(this); - Bitmap stored = BitmapFactory.decodeFile(entry.image.getAbsolutePath()); - if (stored != null) { - preview.setImageBitmap(IconShortcuts.roundedPreview(stored, size)); - stored.recycle(); - } - preview.setLayoutParams(new LinearLayout.LayoutParams(size, size)); - - ImageView delete = new ImageView(this); - delete.setImageDrawable(Md3Icon.of(Md3Icon.DELETE, palette.onSurfaceVariant, this)); - delete.setScaleType(ImageView.ScaleType.CENTER); - delete.setBackground(Md3.stateLayer(this, Md3.SHAPE_FULL, Md3.stateLayerColor(palette.onSurface))); - delete.setContentDescription("Удалить значок " + entry.name); - delete.setClickable(true); - delete.setFocusable(true); - delete.setLayoutParams(new LinearLayout.LayoutParams(size, size)); - delete.setOnClickListener(v -> confirmDeleteIcon(entry)); - - LinearLayout row = Md3.listItem(this, palette, preview, entry.name, - "Нажмите, чтобы добавить на главный экран", delete, true); - row.setOnClickListener(v -> pinIcon(entry)); - return row; - } - - private void pickIcon() { - try { - startActivityForResult(IconShortcuts.pickIntent(), IconShortcuts.REQUEST_PICK); - } catch (ActivityNotFoundException | SecurityException none) { - showIconsNotice("Не нашлось приложения для выбора фото"); - } - } - - @Override protected void onActivityResult(int request, int result, Intent data) { - super.onActivityResult(request, result, data); - if (request != IconShortcuts.REQUEST_PICK || result != RESULT_OK || data == null || iconStore == null) return; - final Uri uri = data.getData(); - if (uri == null) return; - new Thread(() -> { - Bitmap square = null; - try { - square = IconShortcuts.decodeSquare(getContentResolver(), uri); - } catch (IOException | RuntimeException | OutOfMemoryError unreadable) { - // Reported on the screen below. - } - final Bitmap picked = square; - handler.post(() -> { - if (isFinishing()) return; - if (iconsDialog == null) openIconsScreen(); - if (picked == null) showIconsNotice("Не удалось открыть это фото"); - else showIconNameDialog(picked); - }); - }, "lihont-icon-decode").start(); - } - - private void showIconNameDialog(final Bitmap square) { - final Dialog dialog = new Dialog(this); - dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); - LinearLayout root = new LinearLayout(this); - root.setOrientation(LinearLayout.VERTICAL); - root.setBackground(Md3.shape(palette.surfaceContainerHigh, Md3.dialogRadius(palette), this)); - root.setPadding(Md3.dp(this, 24), Md3.dp(this, 24), Md3.dp(this, 24), Md3.dp(this, 24)); - root.addView(Md3.text(this, "Новый значок", Md3.HEADLINE_SMALL, false, palette.onSurface)); - - int previewSize = Md3.dp(this, 96); - ImageView preview = new ImageView(this); - preview.setImageBitmap(IconShortcuts.roundedPreview(square, previewSize)); - LinearLayout.LayoutParams previewParams = new LinearLayout.LayoutParams(previewSize, previewSize); - previewParams.gravity = Gravity.CENTER_HORIZONTAL; - previewParams.topMargin = Md3.dp(this, 16); - root.addView(preview, previewParams); - - TextView caption = Md3.text(this, "Так значок выглядит на главном экране", Md3.BODY_SMALL, false, - palette.onSurfaceVariant); - caption.setGravity(Gravity.CENTER_HORIZONTAL); - LinearLayout.LayoutParams captionParams = new LinearLayout.LayoutParams(-1, -2); - captionParams.topMargin = Md3.dp(this, 8); - captionParams.bottomMargin = Md3.dp(this, 16); - root.addView(caption, captionParams); - - final EditText input = new EditText(this); - input.setText(CustomIconStore.DEFAULT_NAME); - input.setSelectAllOnFocus(true); - input.setHint("Название под значком"); - input.setHintTextColor(palette.onSurfaceVariant); - input.setTextColor(palette.onSurface); - input.setTextSize(Md3.BODY_LARGE); - input.setSingleLine(true); - input.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CustomIconStore.MAX_NAME) }); - input.setBackground(Md3.outlined(Color.TRANSPARENT, palette.outline, 1f, Md3.SHAPE_EXTRA_SMALL, this)); - input.setPadding(Md3.dp(this, 16), Md3.dp(this, 14), Md3.dp(this, 16), Md3.dp(this, 14)); - root.addView(input, new LinearLayout.LayoutParams(-1, -2)); - - LinearLayout actions = new LinearLayout(this); - actions.setGravity(Gravity.END); - LinearLayout.LayoutParams actionsParams = new LinearLayout.LayoutParams(-1, -2); - actionsParams.topMargin = Md3.dp(this, 24); - root.addView(actions, actionsParams); - TextView cancel = Md3.textButton(this, palette, "Отмена"); - cancel.setOnClickListener(v -> dialog.dismiss()); - actions.addView(cancel); - TextView save = Md3.textButton(this, palette, "Добавить"); - save.setOnClickListener(v -> { - dialog.dismiss(); - try { - iconStore.add(IconShortcuts.toPng(square), input.getText().toString()); - renderIcons(); - showIconsNotice("Значок добавлен. Нажмите на него, чтобы вынести на главный экран"); - } catch (IOException | RuntimeException error) { - showIconsNotice(iconStore.list().size() >= CustomIconStore.MAX_ICONS - ? "Достигнут предел в " + CustomIconStore.MAX_ICONS + " значков. Удалите ненужный." - : "Не удалось сохранить значок"); - } - }); - LinearLayout.LayoutParams saveParams = new LinearLayout.LayoutParams(-2, -2); - saveParams.leftMargin = Md3.dp(this, 8); - actions.addView(save, saveParams); - - dialog.setContentView(root); - styleDialog(dialog); - dialog.show(); - sizeDialog(dialog, 0.9f); - } - - private void pinIcon(CustomIconStore.Entry entry) { - if (IconShortcuts.pin(this, entry)) { - showIconsNotice("Подтвердите добавление значка в окне лончера"); - } else if (!IconShortcuts.canPin(this)) { - showIconsNotice("Этот лончер не умеет закреплять ярлыки"); - } else { - showIconsNotice("Не удалось добавить значок"); - } - } - - private void confirmDeleteIcon(final CustomIconStore.Entry entry) { - basicDialog("Удалить значок «" + entry.name + "»?", - "Копия на главном экране перестанет открываться.", - "Отмена", "Удалить", () -> { - if (iconStore.remove(entry.id)) { - IconShortcuts.unpin(this, entry.id); - renderIcons(); - } else { - showIconsNotice("Не удалось удалить значок"); - } - }); - } - - /** A message at the bottom of the icons screen; the settings screen's own snackbar is under it. */ - private void showIconsNotice(String message) { - if (iconsHost == null) return; - handler.removeCallbacks(hideIconsNotice); - if (iconsNotice != null) iconsHost.removeView(iconsNotice); - iconsNotice = Md3.snackbar(this, palette, message, "OK", v -> dismissIconsNotice()); - FrameLayout.LayoutParams params = new FrameLayout.LayoutParams( - ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM); - params.leftMargin = Md3.dp(this, 16); - params.rightMargin = Md3.dp(this, 16); - params.bottomMargin = bottomInset + Md3.dp(this, 16); - iconsHost.addView(iconsNotice, params); - handler.postDelayed(hideIconsNotice, 6000); - } - - private void dismissIconsNotice() { - handler.removeCallbacks(hideIconsNotice); - if (iconsNotice != null && iconsHost != null) iconsHost.removeView(iconsNotice); - iconsNotice = null; - } - - // ---- pickers ----------------------------------------------------------- - - private void openRegionPicker() { - final Dialog dialog = new Dialog(this); - dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); - LinearLayout root = new LinearLayout(this); - root.setOrientation(LinearLayout.VERTICAL); - root.setBackgroundColor(palette.surface); - applyInsets(root); - root.addView(Md3.appBar(this, palette, "Регион мода", Md3Icon.CLOSE, "Закрыть", v -> dialog.dismiss())); - - LinearLayout searchBar = new LinearLayout(this); - searchBar.setOrientation(LinearLayout.HORIZONTAL); - searchBar.setGravity(Gravity.CENTER_VERTICAL); - searchBar.setBackground(Md3.shape(palette.surfaceContainerHigh, Md3.SHAPE_FULL, this)); - searchBar.setPadding(Md3.dp(this, 16), 0, Md3.dp(this, 16), 0); - ImageView searchIcon = new ImageView(this); - searchIcon.setImageDrawable(Md3Icon.of(Md3Icon.SEARCH, palette.onSurfaceVariant, this)); - searchBar.addView(searchIcon, new LinearLayout.LayoutParams(Md3.dp(this, 24), Md3.dp(this, 24))); - EditText input = new EditText(this); - input.setHint("Поиск страны или ISO-кода"); - input.setHintTextColor(palette.onSurfaceVariant); - input.setTextColor(palette.onSurface); - input.setTextSize(Md3.BODY_LARGE); - input.setSingleLine(true); - input.setBackground(null); - LinearLayout.LayoutParams inputParams = new LinearLayout.LayoutParams(0, -1, 1f); - inputParams.leftMargin = Md3.dp(this, 12); - searchBar.addView(input, inputParams); - LinearLayout.LayoutParams barParams = new LinearLayout.LayoutParams(-1, Md3.dp(this, 56)); - barParams.leftMargin = Md3.dp(this, 16); - barParams.rightMargin = Md3.dp(this, 16); - barParams.topMargin = Md3.dp(this, 4); - barParams.bottomMargin = Md3.dp(this, 8); - root.addView(searchBar, barParams); - - final List entries = countryEntries(); - final List visible = new ArrayList(entries); - final BaseAdapter adapter = new BaseAdapter() { - @Override public int getCount() { return visible.size(); } - @Override public Object getItem(int position) { return visible.get(position); } - @Override public long getItemId(int position) { return position; } - @Override public View getView(int position, View recycled, ViewGroup parent) { - String[] entry = visible.get(position); - boolean selected = entry[0].equals(settings.region()); - View trailing = null; - if (selected) { - ImageView check = new ImageView(LihonTSettingsActivity.this); - check.setImageDrawable(Md3Icon.of(Md3Icon.CHECK, palette.primary, LihonTSettingsActivity.this)); - check.setScaleType(ImageView.ScaleType.CENTER); - check.setLayoutParams(new LinearLayout.LayoutParams(Md3.dp(LihonTSettingsActivity.this, 24), - Md3.dp(LihonTSettingsActivity.this, 24))); - trailing = check; - } - LinearLayout row = Md3.listItem(LihonTSettingsActivity.this, palette, - Md3.flowerAvatar(LihonTSettingsActivity.this, palette.primaryContainer, palette.onPrimaryContainer, entry[0], 8), - entry[1], entry[0], trailing, false); - row.setOnClickListener(v -> chooseRegion(dialog, entry[0])); - return row; - } - }; - ListView list = new ListView(this); - list.setDivider(null); - list.setSelector(new ColorDrawable(Color.TRANSPARENT)); - list.setAdapter(adapter); - list.setOnItemClickListener((parent, view, position, id) -> chooseRegion(dialog, visible.get(position)[0])); - root.addView(list, new LinearLayout.LayoutParams(-1, 0, 1f)); - - input.addTextChangedListener(new TextWatcher() { - @Override public void beforeTextChanged(CharSequence s, int a, int b, int c) { } - @Override public void onTextChanged(CharSequence s, int a, int b, int c) { } - @Override public void afterTextChanged(Editable s) { - String query = s.toString().trim().toLowerCase(Locale.ROOT); - visible.clear(); - for (String[] entry : entries) { - if (query.length() == 0 || entry[1].toLowerCase(Locale.ROOT).contains(query) - || entry[0].toLowerCase(Locale.ROOT).contains(query)) { - visible.add(entry); - } - } - adapter.notifyDataSetChanged(); - } - }); - - dialog.setContentView(root); - styleDialog(dialog); - dialog.show(); - if (dialog.getWindow() != null) { - dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); - } - } - - private void chooseRegion(final Dialog dialog, final String code) { - persist(settings.withRegion(code)); - dialog.dismiss(); - showRestartDialog(); - } - - private void showRestartDialog() { - basicDialog("Для изменения настроек перезагрузите приложение", - "Кэш приложения будет очищен, чтобы новые настройки применились корректно.", - "Отмена", "Перезагрузить", () -> { - restartApp(); - }); - } - - /** A bottom message for switches: the change is saved, but only the next TikTok start uses it. */ - private void showRestartNotice() { - showSnack("Изменения применятся после перезапуска TikTok", "Перезапуск", () -> { - dismissRestartNotice(); - showRestartDialog(); - }); - } - - private void showNotice(String message) { - showSnack(message, "OK", this::dismissRestartNotice); - } - - private void showSnack(String message, String action, final Runnable onAction) { - if (host == null) return; - handler.removeCallbacks(hideSnackbar); - if (snackbar != null) host.removeView(snackbar); - snackbar = Md3.snackbar(this, palette, message, action, v -> onAction.run()); - FrameLayout.LayoutParams params = new FrameLayout.LayoutParams( - ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, - Gravity.BOTTOM); - params.leftMargin = Md3.dp(this, 16); - params.rightMargin = Md3.dp(this, 16); - params.bottomMargin = bottomInset + Md3.dp(this, 16); - snackbar.setAlpha(0f); - snackbar.setTranslationY(Md3.dp(this, 24)); - host.addView(snackbar, params); - snackbar.animate().alpha(1f).translationY(0f).setDuration(200).start(); - handler.postDelayed(hideSnackbar, 8000); - } - - private void dismissRestartNotice() { - handler.removeCallbacks(hideSnackbar); - final View bar = snackbar; - if (bar == null || host == null) return; - snackbar = null; - bar.animate().alpha(0f).translationY(Md3.dp(this, 24)).setDuration(150) - .withEndAction(() -> { if (host != null) host.removeView(bar); }).start(); - } - - @Override protected void onDestroy() { - handler.removeCallbacks(hideSnackbar); - handler.removeCallbacks(hideIconsNotice); - if (iconsDialog != null) { - iconsDialog.setOnDismissListener(null); - iconsDialog.dismiss(); - } - super.onDestroy(); - } - - private void clearCache() { - try { - deleteRecursively(getCacheDir()); - if (Build.VERSION.SDK_INT >= 21) { - deleteRecursively(getCodeCacheDir()); - } - File ext = getExternalCacheDir(); - if (ext != null) { - deleteRecursively(ext); - } - } catch (Throwable ignored) {} - } - - private static boolean deleteRecursively(File file) { - if (file == null || !file.exists()) return true; - if (file.isDirectory()) { - File[] children = file.listFiles(); - if (children != null) { - for (File child : children) { - deleteRecursively(child); - } - } - } - return file.delete(); - } - - private void restartApp() { - clearCache(); - try { - Intent intent = getPackageManager().getLaunchIntentForPackage(getPackageName()); - if (intent != null) { - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); - startActivity(intent); - } - } catch (Throwable ignored) {} - System.exit(0); - } - - private void openThemePicker() { - final Dialog dialog = new Dialog(this); - dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); - LinearLayout root = new LinearLayout(this); - root.setOrientation(LinearLayout.VERTICAL); - root.setBackground(Md3.shape(palette.surfaceContainerHigh, Md3.dialogRadius(palette), this)); - root.setPadding(0, Md3.dp(this, 8), 0, Md3.dp(this, 8)); - for (final ModSettings.Theme option : ModSettings.Theme.values()) { - boolean selected = option == settings.theme(); - View trailing = null; - if (selected) { - ImageView check = new ImageView(this); - check.setImageDrawable(Md3Icon.of(Md3Icon.CHECK, palette.primary, this)); - check.setScaleType(ImageView.ScaleType.CENTER); - check.setLayoutParams(new LinearLayout.LayoutParams(Md3.dp(this, 24), Md3.dp(this, 24))); - trailing = check; - } - LinearLayout row = Md3.listItem(this, palette, null, themeLabel(option), null, trailing, true); - row.setOnClickListener(v -> { - persist(settings.withTheme(option)); - dialog.dismiss(); - }); - root.addView(row); - } - dialog.setContentView(root); - styleDialog(dialog); - dialog.show(); - sizeDialog(dialog, 0.85f); - } - - private void confirmReset() { - basicDialog("Сбросить настройки?", "Значения вернутся к состоянию по умолчанию: Япония, баннеры и репосты включены.", - "Отмена", "Сбросить", () -> { - try { - repository.reset(); - settings = repository.current(); - palette = Md3.palette(this, settings); - Window window = getWindow(); - window.setBackgroundDrawable(new ColorDrawable(palette.surface)); - window.setStatusBarColor(palette.surface); - window.setNavigationBarColor(palette.surface); - updateSystemBars(window, palette.dark); - buildScreen(); - } catch (IOException | RuntimeException error) { - updateStatus(); - } - }); - } - - private Dialog basicDialog(CharSequence title, CharSequence message, CharSequence negative, - CharSequence positive, final Runnable onPositive) { - final Dialog dialog = new Dialog(this); - dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); - LinearLayout root = new LinearLayout(this); - root.setOrientation(LinearLayout.VERTICAL); - root.setBackground(Md3.shape(palette.surfaceContainerHigh, Md3.dialogRadius(palette), this)); - root.setPadding(Md3.dp(this, 24), Md3.dp(this, 24), Md3.dp(this, 24), Md3.dp(this, 24)); - root.addView(Md3.text(this, title, Md3.HEADLINE_SMALL, false, palette.onSurface)); - if (message != null) { - TextView body = Md3.text(this, message, Md3.BODY_MEDIUM, false, palette.onSurfaceVariant); - LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(-1, -2); - params.topMargin = Md3.dp(this, 16); - root.addView(body, params); - } - LinearLayout actions = new LinearLayout(this); - actions.setGravity(Gravity.END); - LinearLayout.LayoutParams actionsParams = new LinearLayout.LayoutParams(-1, -2); - actionsParams.topMargin = Md3.dp(this, 24); - root.addView(actions, actionsParams); - if (negative != null) { - TextView cancel = Md3.textButton(this, palette, negative); - cancel.setOnClickListener(v -> dialog.dismiss()); - actions.addView(cancel); - } - if (positive != null) { - TextView confirm = Md3.textButton(this, palette, positive); - confirm.setOnClickListener(v -> { - dialog.dismiss(); - if (onPositive != null) onPositive.run(); - }); - LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(-2, -2); - params.leftMargin = Md3.dp(this, 8); - actions.addView(confirm, params); - } - dialog.setContentView(root); - styleDialog(dialog); - dialog.show(); - sizeDialog(dialog, 0.9f); - return dialog; - } - - private void showStorageError() { - palette = Md3.dark(); - Window window = getWindow(); - window.setBackgroundDrawable(new ColorDrawable(palette.surface)); - window.setStatusBarColor(palette.surface); - window.setNavigationBarColor(palette.surface); - if (Build.VERSION.SDK_INT >= 29) { - window.setNavigationBarContrastEnforced(false); - window.setStatusBarContrastEnforced(false); - } - updateSystemBars(window, palette.dark); - LinearLayout root = new LinearLayout(this); - root.setOrientation(LinearLayout.VERTICAL); - root.setBackgroundColor(palette.surface); - applyInsets(root, null); - root.addView(Md3.appBar(this, palette, "Настройки мода", Md3Icon.CLOSE, "Закрыть", v -> finish())); - TextView message = Md3.text(this, - "Не удалось прочитать локальные настройки. Данные не были перезаписаны.", - Md3.BODY_MEDIUM, false, palette.onSurfaceVariant); - message.setPadding(Md3.dp(this, 16), Md3.dp(this, 8), Md3.dp(this, 16), 0); - root.addView(message); - setContentView(root); - } - - // ---- state ------------------------------------------------------------- - - private boolean persist(ModSettings next) { - try { - repository.save(next); - lihont.two.LihonTRegion.setRegion(next.region()); - settings = next; - palette = Md3.palette(this, settings); - Window window = getWindow(); - window.setBackgroundDrawable(new ColorDrawable(palette.surface)); - window.setStatusBarColor(palette.surface); - window.setNavigationBarColor(palette.surface); - updateSystemBars(window, palette.dark); - buildScreen(); - return true; - } catch (IOException | RuntimeException error) { - if (status != null) { - status.setText("Не удалось сохранить настройки."); - status.setTextColor(palette.error); - } - return false; - } - } - - private void updateStatus() { - if (status == null) return; - StringBuilder message = new StringBuilder("Значения хранятся локально и не выдаются за серверные."); - if (repository.restartRequired()) message.append(" Изменения применятся после перезапуска TikTok."); - if (settings.needsBannerWarning()) message.append(" В выбранном регионе часть баннеров может быть недоступна."); - status.setText(message); - status.setTextColor(settings.needsBannerWarning() ? palette.error : palette.onSurfaceVariant); - } - - // ---- helpers ----------------------------------------------------------- - - private List countryEntries() { - List entries = new ArrayList(); - for (String code : ModSettings.COUNTRY_CODES) { - String name = new Locale("", code).getDisplayCountry(new Locale("ru")); - if (name == null || name.length() == 0) name = code; - entries.add(new String[] { code, name }); - } - Collections.sort(entries, new Comparator() { - @Override public int compare(String[] left, String[] right) { - return left[1].compareToIgnoreCase(right[1]); - } - }); - return entries; - } - - private String countryLabel(String code) { - String name = new Locale("", code).getDisplayCountry(new Locale("ru")); - return (name == null || name.length() == 0) ? code : name; - } - - private String themeLabel(ModSettings.Theme theme) { - if (theme == ModSettings.Theme.LIGHT) return "Светлая"; - if (theme == ModSettings.Theme.DARK) return "Тёмная"; - return "Системная"; - } - - private void openUrl(String url) { - try { - startActivity(new Intent(Intent.ACTION_VIEW, android.net.Uri.parse(url))); - } catch (RuntimeException ignored) { - // No browser or blocked link: the row simply stays informational. - } - } - - private void applyInsets(final View root) { - applyInsets(root, null); - } - - private void applyInsets(final View root, final View scroll) { - if (Build.VERSION.SDK_INT >= 20) { - root.setOnApplyWindowInsetsListener((v, insets) -> { - int top = 0; - int bottom = 0; - if (Build.VERSION.SDK_INT >= 30) { - android.graphics.Insets bars = insets.getInsets(android.view.WindowInsets.Type.systemBars()); - top = bars.top; - bottom = bars.bottom; - } else { - top = insets.getSystemWindowInsetTop(); - bottom = insets.getSystemWindowInsetBottom(); - } - v.setPadding(0, top, 0, scroll == null ? bottom : 0); - if (scroll != null) { - bottomInset = bottom; - if (snackbar != null && snackbar.getLayoutParams() instanceof FrameLayout.LayoutParams) { - FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) snackbar.getLayoutParams(); - lp.bottomMargin = bottom + Md3.dp(LihonTSettingsActivity.this, 16); - snackbar.setLayoutParams(lp); - } - scroll.setPadding(0, 0, 0, bottom + Md3.dp(LihonTSettingsActivity.this, 24)); - } - return insets; - }); - } - } - - private void updateSystemBars(Window window, boolean isDark) { - if (Build.VERSION.SDK_INT >= 30) { - android.view.WindowInsetsController controller = window.getInsetsController(); - if (controller != null) { - int appearance = 0; - if (!isDark) { - appearance |= android.view.WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS; - appearance |= android.view.WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS; - } - controller.setSystemBarsAppearance(appearance, - android.view.WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS | - android.view.WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS); - } - } else if (Build.VERSION.SDK_INT >= 26) { - View decor = window.getDecorView(); - int flags = decor.getSystemUiVisibility(); - if (!isDark) { - flags |= View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR; - flags |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR; - } else { - flags &= ~View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR; - flags &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR; - } - decor.setSystemUiVisibility(flags); - } - } - - private void styleDialog(Dialog dialog) { - Window window = dialog.getWindow(); - if (window == null) return; - window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); - window.setStatusBarColor(palette.surface); - window.setNavigationBarColor(palette.surface); - if (Build.VERSION.SDK_INT >= 29) { - window.setNavigationBarContrastEnforced(false); - window.setStatusBarContrastEnforced(false); - } - updateSystemBars(window, palette.dark); - window.setDimAmount(0.5f); - window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); - } - - private void sizeDialog(Dialog dialog, float widthFraction) { - Window window = dialog.getWindow(); - if (window == null) return; - int width = (int) (getResources().getDisplayMetrics().widthPixels * widthFraction); - window.setLayout(width, ViewGroup.LayoutParams.WRAP_CONTENT); - } -} - - +package lihont.two.settings; + +import android.app.Activity; +import android.app.Dialog; +import android.content.ActivityNotFoundException; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.graphics.Color; +import android.graphics.Outline; +import android.graphics.drawable.ColorDrawable; +import android.graphics.drawable.Drawable; +import android.net.Uri; +import android.os.Build; +import android.os.Bundle; +import android.os.Handler; +import android.os.Looper; +import android.text.Editable; +import android.text.InputFilter; +import android.text.TextWatcher; +import android.view.Gravity; +import android.view.View; +import android.view.ViewGroup; +import android.view.ViewOutlineProvider; +import android.view.Window; +import android.view.WindowManager; +import android.widget.BaseAdapter; +import android.widget.EditText; +import android.widget.FrameLayout; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.ListView; +import android.widget.ScrollView; +import android.widget.TextView; +import android.widget.Toast; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.Locale; + +/** Material 3 settings screen for LihonT 2. */ +public final class LihonTSettingsActivity extends Activity { + private static final String VERSION_LINE = "LihonT 2.0 · Luna (пре-релиз)"; + private static final String BASE_LINE = "База TikTok 47.1.3"; + private static final String CHANNEL_URL = "https://t.me/lihont"; + private static final String SOURCE_URL = "https://git.lihont.space/lihont/LihonT"; + private static final String LICENSE_URL = SOURCE_URL + "/src/branch/main/LICENSE"; + private static final String CHANGES = + "• Material 3 в TikTok: нижняя панель с кнопкой «+», меню профиля, профили, настройки и комментарии.\n" + + "• Свой цвет оформления или цвет телефона, один цвет у всех цветочков, чёрный фон AMOLED.\n" + + "• Форма аватарок: круг, цветочек, квадрат, шестиугольник, сердечко, треугольник. Ваша форма видна другим с модом.\n" + + "• Компактная нижняя панель без подписей.\n" + + "• Меню сохранения: качество от меньшего к большему, только звук, фото без водяного знака.\n" + + "• Переключатели рекламы, эфиров и вкладки «Магазин» в ленте.\n" + + "• Значки TikTok You и MargyT рядом с ником и значок «Нишевый мод»."; + private static final String DISCLAIMER = + "Бесплатная модификация TikTok для Android. Проект не связан с ByteDance и TikTok Pte. Ltd."; + + private SettingsRepository repository; + private ModSettings settings; + private Md3.Palette palette; + private LinearLayout content; + private TextView status; + private FrameLayout host; + private View snackbar; + private int bottomInset; + private final Handler handler = new Handler(Looper.getMainLooper()); + private final Runnable hideSnackbar = this::dismissRestartNotice; + + // The "Свой значок" screen: a full-screen dialog that lives on top of this activity. + private CustomIconStore iconStore; + private Dialog iconsDialog; + private LinearLayout iconsList; + private FrameLayout iconsHost; + private View iconsNotice; + private int iconCountShown; + private final Runnable hideIconsNotice = this::dismissIconsNotice; + + /** Entry point for the TikTok Settings hook; the activity stays non-exported. */ + public static Intent intent(Context context) { + return new Intent(context, LihonTSettingsActivity.class); + } + + @Override public void onCreate(Bundle state) { + super.onCreate(state); + try { + repository = SettingsHost.repository(this); + settings = repository.current(); + lihont.two.LihonTRegion.setRegion(settings.region()); + } catch (IOException | RuntimeException error) { + showStorageError(); + return; + } + iconStore = new CustomIconStore(IconShortcuts.directory(this)); + palette = Md3.palette(this, settings); + Window window = getWindow(); + window.setBackgroundDrawable(new ColorDrawable(palette.surface)); + window.setStatusBarColor(palette.surface); + window.setNavigationBarColor(palette.surface); + if (Build.VERSION.SDK_INT >= 29) { + window.setNavigationBarContrastEnforced(false); + window.setStatusBarContrastEnforced(false); + } + updateSystemBars(window, palette.dark); + buildScreen(); + } + + // ---- screen ------------------------------------------------------------ + + /** A titled card that opens and closes by a tap on its title; what is open is remembered. */ + private void addSection(final String title, final LinearLayout card, boolean openByDefault) { + final SharedPreferences ui = getSharedPreferences("lihont_settings_ui", MODE_PRIVATE); + boolean open = ui.getBoolean("open." + title, openByDefault); + LinearLayout header = new LinearLayout(this); + header.setOrientation(LinearLayout.HORIZONTAL); + header.setGravity(Gravity.CENTER_VERTICAL); + header.setClickable(true); + header.setFocusable(true); + header.setContentDescription(title); + header.addView(Md3.subheader(this, palette, title), new LinearLayout.LayoutParams(0, -2, 1f)); + final ImageView chevron = new ImageView(this); + chevron.setImageDrawable(Md3Icon.of(Md3Icon.CHEVRON_RIGHT, palette.onSurfaceVariant, this)); + chevron.setScaleType(ImageView.ScaleType.CENTER); + chevron.setRotation(open ? 90f : 0f); + LinearLayout.LayoutParams chevronParams = new LinearLayout.LayoutParams(Md3.dp(this, 24), Md3.dp(this, 24)); + chevronParams.rightMargin = Md3.dp(this, 20); + header.addView(chevron, chevronParams); + card.setVisibility(open ? View.VISIBLE : View.GONE); + header.setOnClickListener(v -> { + boolean show = card.getVisibility() != View.VISIBLE; + card.setVisibility(show ? View.VISIBLE : View.GONE); + chevron.animate().rotation(show ? 90f : 0f).setDuration(150).start(); + ui.edit().putBoolean("open." + title, show).apply(); + }); + content.addView(header); + content.addView(card); + } + + private void buildScreen() { + handler.removeCallbacks(hideSnackbar); + snackbar = null; + LinearLayout root = new LinearLayout(this); + root.setOrientation(LinearLayout.VERTICAL); + root.setBackgroundColor(palette.surface); + + root.addView(Md3.appBar(this, palette, "Настройки мода", Md3Icon.BACK, "Назад", v -> finish())); + + ScrollView scroll = new ScrollView(this); + scroll.setFillViewport(true); + scroll.setClipToPadding(false); + scroll.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS); + scroll.setFocusable(true); + scroll.setFocusableInTouchMode(true); + content = new LinearLayout(this); + content.setOrientation(LinearLayout.VERTICAL); + content.setPadding(0, 0, 0, Md3.dp(this, 32)); + scroll.addView(content, new ScrollView.LayoutParams(-1, -2)); + root.addView(scroll, new LinearLayout.LayoutParams(-1, 0, 1f)); + applyInsets(root, scroll); + host = new FrameLayout(this); + host.addView(root, new FrameLayout.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); + setContentView(host); + + LinearLayout cardFunc = Md3.card(this, palette); + cardFunc.addView(switchRow("Баннеры профиля", "Карточки и фон в шапке профиля", + Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.BANNER, palette.onPrimaryContainer, 8), + settings.profileBanners(), TOGGLE_BANNERS)); + cardFunc.addView(Md3.cardDivider(this, palette)); + cardFunc.addView(switchRow("Репост комментариев", "Действие репоста у комментария", + Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.REPOST, palette.onPrimaryContainer, 8), + settings.commentReposts(), TOGGLE_REPOSTS)); + cardFunc.addView(Md3.cardDivider(this, palette)); + cardFunc.addView(switchRow("Интерфейс в стиле MD3", + "Нижняя панель, меню профиля и настройки TikTok. Выключено: вид Serena 1.2", + Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.BOTTOM_BAR, palette.onPrimaryContainer, 8), + settings.md3(), TOGGLE_MD3)); + cardFunc.addView(Md3.cardDivider(this, palette)); + cardFunc.addView(switchRow("Скачивание без водяного знака", "Сохранённые видео без логотипа TikTok", + Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.DOWNLOAD, palette.onPrimaryContainer, 8), + settings.noWatermark(), TOGGLE_NO_WATERMARK)); + cardFunc.addView(Md3.cardDivider(this, palette)); + cardFunc.addView(switchRow("Меню сохранения", "Качество от меньшего к большему, только звук, фото карусели", + Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.DOWNLOAD, palette.onPrimaryContainer, 8), + settings.downloadMenu(), TOGGLE_MENU)); + addSection("Функции", cardFunc, true); + + LinearLayout cardFeed = Md3.card(this, palette); + cardFeed.addView(switchRow("Убрать рекламу", "Рекламные ролики и вставки между видео", + Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.AD_OFF, palette.onPrimaryContainer, 8), + settings.hideAds(), TOGGLE_ADS)); + cardFeed.addView(Md3.cardDivider(this, palette)); + cardFeed.addView(switchRow("Убрать эфиры из ленты", "Прямые трансляции не появляются между видео", + Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.LIVE, palette.onPrimaryContainer, 8), + settings.hideLive(), TOGGLE_LIVE)); + cardFeed.addView(Md3.cardDivider(this, palette)); + cardFeed.addView(switchRow("Убрать раздел «Магазин»", "Вкладка над лентой. В бете может сбиться полоса под вкладками", + Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.SHOP, palette.onPrimaryContainer, 8), + settings.hideShop(), TOGGLE_SHOP)); + addSection("Лента", cardFeed, false); + + LinearLayout cardBadges = Md3.card(this, palette); + cardBadges.addView(switchRow("Значки других модов", "TikTok You и MargyT рядом с ником", + Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.NOTE, palette.onPrimaryContainer, 8), + settings.foreignBadges(), TOGGLE_BADGES)); + cardBadges.addView(Md3.cardDivider(this, palette)); + cardBadges.addView(nicheRow()); + addSection("Значки в именах", cardBadges, false); + + LinearLayout cardParams = Md3.card(this, palette); + cardParams.addView(regionRow()); + cardParams.addView(Md3.cardDivider(this, palette)); + cardParams.addView(themeRow()); + cardParams.addView(Md3.cardDivider(this, palette)); + cardParams.addView(accentRow()); + cardParams.addView(Md3.cardDivider(this, palette)); + cardParams.addView(shapeRow()); + cardParams.addView(Md3.cardDivider(this, palette)); + cardParams.addView(switchRow("AMOLED: чёрный фон", "Чистый чёрный в тёмной теме", + Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.MOON, palette.onPrimaryContainer, 8), + settings.amoled(), TOGGLE_AMOLED)); + cardParams.addView(Md3.cardDivider(this, palette)); + cardParams.addView(switchRow("Компактная нижняя панель", "Без подписей под значками", + Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.BOTTOM_BAR, palette.onPrimaryContainer, 8), + settings.compactBar(), TOGGLE_COMPACT)); + addSection("Параметры", cardParams, false); + + LinearLayout cardIcon = Md3.card(this, palette); + View appIcon = appIconRow(); + if (appIcon != null) { + cardIcon.addView(appIcon); + cardIcon.addView(Md3.cardDivider(this, palette)); + } + cardIcon.addView(iconsRow()); + addSection("Значок", cardIcon, false); + + LinearLayout cardWidget = Md3.card(this, palette); + cardWidget.addView(widgetRow()); + addSection("Виджеты", cardWidget, false); + + LinearLayout cardKeeper = Md3.card(this, palette); + new KeeperSettings(this, palette, this::buildScreen).fill(cardKeeper); + addSection("Огоньки", cardKeeper, false); + + LinearLayout cardAbout = Md3.card(this, palette); + cardAbout.addView(Md3.listItem(this, palette, + Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.INFO, palette.onPrimaryContainer, 8), + "Версия", VERSION_LINE, null, false)); + cardAbout.addView(Md3.cardDivider(this, palette)); + cardAbout.addView(Md3.listItem(this, palette, + Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.TIKTOK, palette.onPrimaryContainer, 8), + "База", BASE_LINE, null, false)); + cardAbout.addView(Md3.cardDivider(this, palette)); + cardAbout.addView(Md3.cardDivider(this, palette)); + cardAbout.addView(linkRow("Что нового", "Что есть в этой версии", Md3Icon.INFO, null)); + cardAbout.addView(Md3.cardDivider(this, palette)); + cardAbout.addView(telegramRow()); + cardAbout.addView(Md3.cardDivider(this, palette)); + cardAbout.addView(linkRow("Исходный код", SOURCE_URL, Md3Icon.CODE, SOURCE_URL)); + cardAbout.addView(Md3.cardDivider(this, palette)); + cardAbout.addView(linkRow("Лицензия", "EVHNMKHU", Md3Icon.INFO, LICENSE_URL)); + addSection("О моде", cardAbout, false); + + status = Md3.text(this, "", Md3.BODY_SMALL, false, palette.onSurfaceVariant); + status.setGravity(Gravity.CENTER_HORIZONTAL); + status.setPadding(Md3.dp(this, 24), Md3.dp(this, 8), Md3.dp(this, 24), Md3.dp(this, 4)); + content.addView(status); + + TextView disclaimer = Md3.text(this, DISCLAIMER, Md3.BODY_SMALL, false, palette.onSurfaceVariant); + disclaimer.setGravity(Gravity.CENTER_HORIZONTAL); + disclaimer.setPadding(Md3.dp(this, 24), Md3.dp(this, 4), Md3.dp(this, 24), Md3.dp(this, 12)); + content.addView(disclaimer); + + LinearLayout actions = new LinearLayout(this); + actions.setOrientation(LinearLayout.VERTICAL); + actions.setGravity(Gravity.CENTER_HORIZONTAL); + actions.setPadding(Md3.dp(this, 16), Md3.dp(this, 8), Md3.dp(this, 16), Md3.dp(this, 16)); + if (repository.restartRequired()) { + TextView restartBtn = Md3.filledButton(this, palette, "Перезагрузить и очистить кэш"); + restartBtn.setOnClickListener(v -> showRestartDialog()); + LinearLayout.LayoutParams restartParams = new LinearLayout.LayoutParams(-2, -2); + restartParams.bottomMargin = Md3.dp(this, 12); + actions.addView(restartBtn, restartParams); + } + TextView reset = Md3.filledTonalButton(this, palette, "Сбросить настройки"); + reset.setOnClickListener(v -> confirmReset()); + actions.addView(reset); + content.addView(actions); + + updateStatus(); + } + + private static final int TOGGLE_BANNERS = 0; + private static final int TOGGLE_REPOSTS = 1; + private static final int TOGGLE_MD3 = 2; + private static final int TOGGLE_NO_WATERMARK = 3; + private static final int TOGGLE_ADS = 4; + private static final int TOGGLE_LIVE = 5; + private static final int TOGGLE_SHOP = 6; + private static final int TOGGLE_BADGES = 7; + private static final int TOGGLE_AMOLED = 8; + private static final int TOGGLE_COMPACT = 9; + private static final int TOGGLE_MENU = 10; + + private ModSettings withToggle(int which, boolean value) { + if (which == TOGGLE_BANNERS) return settings.withProfileBanners(value); + if (which == TOGGLE_REPOSTS) return settings.withCommentReposts(value); + if (which == TOGGLE_NO_WATERMARK) return settings.withNoWatermark(value); + if (which == TOGGLE_ADS) return settings.withHideAds(value); + if (which == TOGGLE_LIVE) return settings.withHideLive(value); + if (which == TOGGLE_SHOP) return settings.withHideShop(value); + if (which == TOGGLE_BADGES) return settings.withForeignBadges(value); + if (which == TOGGLE_AMOLED) return settings.withAmoled(value); + if (which == TOGGLE_COMPACT) return settings.withCompactBar(value); + if (which == TOGGLE_MENU) return settings.withDownloadMenu(value); + return settings.withMd3(value); + } + + private boolean toggleValue(int which) { + if (which == TOGGLE_BANNERS) return settings.profileBanners(); + if (which == TOGGLE_REPOSTS) return settings.commentReposts(); + if (which == TOGGLE_NO_WATERMARK) return settings.noWatermark(); + if (which == TOGGLE_ADS) return settings.hideAds(); + if (which == TOGGLE_LIVE) return settings.hideLive(); + if (which == TOGGLE_SHOP) return settings.hideShop(); + if (which == TOGGLE_BADGES) return settings.foreignBadges(); + if (which == TOGGLE_AMOLED) return settings.amoled(); + if (which == TOGGLE_COMPACT) return settings.compactBar(); + if (which == TOGGLE_MENU) return settings.downloadMenu(); + return settings.md3(); + } + + private View switchRow(String title, String hint, View leading, boolean checked, final int which) { + Md3Switch toggle = new Md3Switch(this, palette); + toggle.setContentDescription(title); + toggle.setChecked(checked, false); + toggle.setOnCheckedChangeListener((view, value) -> { + if (!persist(withToggle(which, value))) { + view.setChecked(toggleValue(which), true); + } else if (repository.restartRequired()) { + showRestartNotice(); + } + }); + LinearLayout row = Md3.listItem(this, palette, leading, title, hint, toggle, true); + row.setOnClickListener(v -> toggle.toggle()); + return row; + } + + private View regionRow() { + View trailing = Md3.chevron(this, palette); + trailing.setTag("region"); + String label = countryLabel(settings.region()); + String subtitle = settings.needsBannerWarning() ? label : (label + " · по умолчанию"); + LinearLayout row = Md3.listItem(this, palette, + Md3.flowerAvatar(this, palette.primaryContainer, palette.onPrimaryContainer, settings.region(), 8), + "Регион мода", subtitle, trailing, true); + row.setOnClickListener(v -> openRegionPicker()); + return row; + } + + private View themeRow() { + View trailing = Md3.chevron(this, palette); + int themeIcon = palette.dark ? Md3Icon.MOON : Md3Icon.SUN; + LinearLayout row = Md3.listItem(this, palette, + Md3.flowerIconAvatar(this, palette.primaryContainer, themeIcon, palette.onPrimaryContainer, 8), + "Тема оформления", themeLabel(settings.theme()), trailing, true); + row.setOnClickListener(v -> openThemePicker()); + return row; + } + + private View accentRow() { + View trailing = Md3.chevron(this, palette); + int swatch = Md3.swatch(this, settings.accent(), settings.accentHue(), settings.theme()); + LinearLayout row = Md3.listItem(this, palette, + Md3.flowerAvatar(this, swatch, Md3.onSwatch(swatch), "", 8), + "Цвет оформления", accentLabel(settings.accent()), trailing, true); + row.setOnClickListener(v -> openAccentPicker()); + return row; + } + + /** The shape belongs to the account that is signed in: every account on the phone has its own. */ + private View shapeRow() { + String account = lihont.two.account.CurrentAccount.uniqueId(); + ModSettings.AvatarShape shape = lihont.two.account.AccountShapes.current(); + ShapeView preview = shapeView(shape, 40); + String subtitle = account == null ? "Войдите в TikTok, чтобы выбрать форму" + : shapeLabel(shape) + " · @" + account; + LinearLayout row = Md3.listItem(this, palette, preview, "Форма аватарок", subtitle, + Md3.chevron(this, palette), true); + row.setOnClickListener(v -> openShapePicker()); + return row; + } + + private ShapeView shapeView(ModSettings.AvatarShape shape, int sizeDp) { + ShapeView view = new ShapeView(this, shape, palette.primaryContainer); + view.setLayoutParams(new LinearLayout.LayoutParams(Md3.dp(this, sizeDp), Md3.dp(this, sizeDp))); + return view; + } + + private void openShapePicker() { + final String uid = lihont.two.account.CurrentAccount.uid(); + if (uid == null) { + Toast.makeText(this, "Войдите в TikTok, чтобы выбрать форму аватарок", Toast.LENGTH_LONG).show(); + return; + } + final ModSettings.AvatarShape chosen = lihont.two.account.AccountShapes.current(); + final Dialog dialog = new Dialog(this); + dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + LinearLayout root = new LinearLayout(this); + root.setOrientation(LinearLayout.VERTICAL); + root.setBackground(Md3.shape(palette.surfaceContainerHigh, Md3.dialogRadius(palette), this)); + root.setPadding(0, Md3.dp(this, 8), 0, Md3.dp(this, 8)); + for (final ModSettings.AvatarShape option : ModSettings.AvatarShape.values()) { + View trailing = null; + if (option == chosen) { + ImageView check = new ImageView(this); + check.setImageDrawable(Md3Icon.of(Md3Icon.CHECK, palette.primary, this)); + check.setScaleType(ImageView.ScaleType.CENTER); + check.setLayoutParams(new LinearLayout.LayoutParams(Md3.dp(this, 24), Md3.dp(this, 24))); + trailing = check; + } + LinearLayout row = Md3.listItem(this, palette, shapeView(option, 40), shapeLabel(option), null, + trailing, true); + row.setOnClickListener(v -> { + dialog.dismiss(); + lihont.two.account.AccountShapes.set(this, uid, option); + buildScreen(); + shareShape(option); + }); + root.addView(row); + } + ScrollView scroll = new ScrollView(this); + scroll.addView(root); + dialog.setContentView(scroll); + styleDialog(dialog); + dialog.show(); + sizeDialog(dialog, 0.85f); + } + + /** Publishes the chosen shape for other members; asks for the code in the bio when the account is not proven yet. */ + private void shareShape(final ModSettings.AvatarShape option) { + lihont.two.avatar.ShapePublisher.publish(this, option, result -> { + if (result.published) { + Toast.makeText(this, result.message, Toast.LENGTH_LONG).show(); + } else if (result.code != null) { + openShapeProofDialog(option, result.code); + } else { + Toast.makeText(this, result.message, Toast.LENGTH_LONG).show(); + } + }); + } + + private void openShapeProofDialog(final ModSettings.AvatarShape option, final String proof) { + final Dialog dialog = new Dialog(this); + dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + LinearLayout box = new LinearLayout(this); + box.setOrientation(LinearLayout.VERTICAL); + box.setPadding(Md3.dp(this, 24), Md3.dp(this, 24), Md3.dp(this, 24), Md3.dp(this, 16)); + box.setBackground(Md3.shape(palette.surfaceContainerHigh, Md3.dialogRadius(palette), this)); + box.addView(Md3.text(this, "Показать форму другим", Md3.HEADLINE_SMALL, false, palette.onSurface)); + final TextView info = Md3.text(this, + "У вас форма уже стоит. Чтобы её видели и другие с модом, сервер должен убедиться, что аккаунт ваш.\n" + + "1. Скопируйте код.\n2. Вставьте его в описание профиля TikTok.\n" + + "3. Нажмите «Проверить»: после этого форму можно менять без кода.", + Md3.BODY_MEDIUM, false, palette.onSurfaceVariant); + info.setPadding(0, Md3.dp(this, 12), 0, Md3.dp(this, 12)); + box.addView(info); + box.addView(Md3.text(this, proof, Md3.TITLE_LARGE, true, palette.primary)); + final TextView result = Md3.text(this, "", Md3.BODY_MEDIUM, false, palette.onSurface); + result.setPadding(0, Md3.dp(this, 12), 0, 0); + box.addView(result); + LinearLayout buttons = new LinearLayout(this); + buttons.setGravity(Gravity.END); + buttons.setPadding(0, Md3.dp(this, 16), 0, 0); + TextView copy = Md3.textButton(this, palette, "Скопировать"); + TextView check = Md3.filledButton(this, palette, "Проверить"); + TextView close = Md3.textButton(this, palette, "Закрыть"); + buttons.addView(close); + buttons.addView(copy); + buttons.addView(check); + box.addView(buttons); + close.setOnClickListener(v -> dialog.dismiss()); + copy.setOnClickListener(v -> { + android.content.ClipboardManager clipboard = + (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); + clipboard.setPrimaryClip(android.content.ClipData.newPlainText("LihonT", proof)); + result.setText("Код скопирован"); + }); + check.setOnClickListener(v -> { + result.setText("Проверяем…"); + lihont.two.avatar.ShapePublisher.publish(this, option, outcome -> { + result.setText(outcome.message); + if (outcome.published) Toast.makeText(this, outcome.message, Toast.LENGTH_LONG).show(); + }); + }); + dialog.setContentView(box); + styleDialog(dialog); + dialog.show(); + sizeDialog(dialog, 0.92f); + } + + private String shapeLabel(ModSettings.AvatarShape shape) { + switch (shape) { + case FLOWER: return "Цветочек"; + case SQUIRCLE: return "Скруглённый квадрат"; + case HEXAGON: return "Шестиугольник"; + case HEART: return "Сердечко"; + case TRIANGLE: return "Треугольник"; + default: return "Круг (как в TikTok)"; + } + } + + private void openAccentPicker() { + final Dialog dialog = new Dialog(this); + dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + LinearLayout root = new LinearLayout(this); + root.setOrientation(LinearLayout.VERTICAL); + root.setBackground(Md3.shape(palette.surfaceContainerHigh, Md3.dialogRadius(palette), this)); + root.setPadding(0, Md3.dp(this, 8), 0, Md3.dp(this, 8)); + for (final ModSettings.Accent option : ModSettings.Accent.values()) { + View trailing = null; + if (option == settings.accent()) { + ImageView check = new ImageView(this); + check.setImageDrawable(Md3Icon.of(Md3Icon.CHECK, palette.primary, this)); + check.setScaleType(ImageView.ScaleType.CENTER); + check.setLayoutParams(new LinearLayout.LayoutParams(Md3.dp(this, 24), Md3.dp(this, 24))); + trailing = check; + } + int swatch = Md3.swatch(this, option, settings.accentHue(), settings.theme()); + LinearLayout row = Md3.listItem(this, palette, + Md3.flowerAvatar(this, swatch, Md3.onSwatch(swatch), "", 8), + accentLabel(option), null, trailing, true); + row.setOnClickListener(v -> { + dialog.dismiss(); + if (option == ModSettings.Accent.CUSTOM) { + openHueDialog(); + } else { + persist(settings.withAccent(option)); + } + }); + root.addView(row); + } + ScrollView scroll = new ScrollView(this); + scroll.addView(root); + dialog.setContentView(scroll); + styleDialog(dialog); + dialog.show(); + sizeDialog(dialog, 0.85f); + } + + private String accentLabel(ModSettings.Accent accent) { + switch (accent) { + case VIOLET: return "Фиолетовый"; + case BLUE: return "Синий"; + case TEAL: return "Бирюзовый"; + case GREEN: return "Зелёный"; + case ROSE: return "Розовый"; + case ORANGE: return "Оранжевый"; + case CUSTOM: return "Свой цвет"; + default: return "Как у телефона"; + } + } + + /** The own colour: drag along the rainbow, see the flower take the hue, then keep it. */ + private void openHueDialog() { + final int[] chosen = {settings.accent() == ModSettings.Accent.CUSTOM ? settings.accentHue() + : settings.accent().hue() >= 0 ? settings.accent().hue() : settings.accentHue()}; + final Dialog dialog = new Dialog(this); + dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + LinearLayout root = new LinearLayout(this); + root.setOrientation(LinearLayout.VERTICAL); + root.setBackground(Md3.shape(palette.surfaceContainerHigh, Md3.dialogRadius(palette), this)); + root.setPadding(Md3.dp(this, 24), Md3.dp(this, 24), Md3.dp(this, 24), Md3.dp(this, 16)); + root.addView(Md3.text(this, "Свой цвет", Md3.HEADLINE_SMALL, false, palette.onSurface)); + final LinearLayout preview = new LinearLayout(this); + preview.setGravity(Gravity.CENTER_VERTICAL); + preview.setPadding(0, Md3.dp(this, 16), 0, Md3.dp(this, 4)); + root.addView(preview); + final TextView hint = Md3.text(this, "", Md3.BODY_MEDIUM, false, palette.onSurfaceVariant); + hint.setPadding(0, Md3.dp(this, 4), 0, Md3.dp(this, 8)); + root.addView(hint); + final Runnable refresh = new Runnable() { + @Override public void run() { + int color = Md3.swatch(LihonTSettingsActivity.this, ModSettings.Accent.CUSTOM, chosen[0], + settings.theme()); + preview.removeAllViews(); + preview.addView(Md3.flowerAvatar(LihonTSettingsActivity.this, color, Md3.onSwatch(color), "", 8)); + hint.setText("Оттенок " + chosen[0] + "°. Все цветочки и переключатели возьмут этот цвет " + + "после перезапуска TikTok."); + } + }; + HuePicker picker = new HuePicker(this, chosen[0], new HuePicker.Listener() { + @Override public void onHue(int hue) { + chosen[0] = hue; + refresh.run(); + } + }); + root.addView(picker, new LinearLayout.LayoutParams(-1, -2)); + LinearLayout buttons = new LinearLayout(this); + buttons.setGravity(Gravity.END); + buttons.setPadding(0, Md3.dp(this, 12), 0, 0); + TextView cancel = Md3.textButton(this, palette, "Отмена"); + TextView done = Md3.filledButton(this, palette, "Готово"); + cancel.setOnClickListener(v -> dialog.dismiss()); + done.setOnClickListener(v -> { + dialog.dismiss(); + persist(settings.withAccentHue(chosen[0]).withAccent(ModSettings.Accent.CUSTOM)); + }); + buttons.addView(cancel); + buttons.addView(done); + root.addView(buttons); + refresh.run(); + dialog.setContentView(root); + styleDialog(dialog); + dialog.show(); + sizeDialog(dialog, 0.92f); + } + + /** A row of the About card: opens a link, or the list of changes when there is no link. */ + private View linkRow(String title, String hint, int icon, final String url) { + LinearLayout row = Md3.listItem(this, palette, + Md3.flowerIconAvatar(this, palette.primaryContainer, icon, palette.onPrimaryContainer, 8), + title, hint, url == null ? Md3.chevron(this, palette) : null, true); + if (url == null) { + row.setOnClickListener(v -> basicDialog("Что нового", CHANGES, null, "Закрыть", null)); + } else { + row.setOnClickListener(v -> openUrl(url)); + } + return row; + } + + private View telegramRow() { + LinearLayout row = Md3.listItem(this, palette, + Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.SEND, palette.onPrimaryContainer, 8), + "Telegram-канал", CHANNEL_URL, null, true); + row.setOnClickListener(v -> openUrl(CHANNEL_URL)); + return row; + } + + // ---- streak widget ----------------------------------------------------- + + private View widgetRow() { + LinearLayout row = Md3.listItem(this, palette, + Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.FLAME, palette.onPrimaryContainer, 8), + "Виджет «Огонёк»", "Цветочек с числом дней огонька выбранного чата. Размер от 1×1 до 4×4", + Md3.chevron(this, palette), true); + row.setOnClickListener(v -> openWidgetSizePicker()); + return row; + } + + private void openWidgetSizePicker() { + final Dialog dialog = new Dialog(this); + dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + LinearLayout root = new LinearLayout(this); + root.setOrientation(LinearLayout.VERTICAL); + root.setBackground(Md3.shape(palette.surfaceContainerHigh, Md3.dialogRadius(palette), this)); + root.setPadding(0, Md3.dp(this, 16), 0, Md3.dp(this, 8)); + TextView title = Md3.text(this, "Размер виджета", Md3.HEADLINE_SMALL, false, palette.onSurface); + title.setPadding(Md3.dp(this, 24), 0, Md3.dp(this, 24), Md3.dp(this, 4)); + root.addView(title); + TextView hint = Md3.text(this, "Потом его можно растянуть или сжать на главном экране.", Md3.BODY_MEDIUM, + false, palette.onSurfaceVariant); + hint.setPadding(Md3.dp(this, 24), 0, Md3.dp(this, 24), Md3.dp(this, 8)); + root.addView(hint); + String[] notes = {"Только число и огонёк", "С именем друга", "Крупнее", "Самый большой"}; + for (final int cells : lihont.two.widget.StreakWidget.SIZES) { + LinearLayout row = Md3.listItem(this, palette, + Md3.flowerAvatar(this, palette.primaryContainer, palette.onPrimaryContainer, cells + "×" + cells, 8), + cells + " × " + cells, notes[cells - 1], null, true); + row.setOnClickListener(v -> { + dialog.dismiss(); + if (!lihont.two.widget.StreakWidget.requestPin(this, cells)) { + Toast.makeText(this, "Добавьте виджет «Огонёк LihonT» из списка виджетов: долгое нажатие на " + + "экране, затем «Виджеты».", Toast.LENGTH_LONG).show(); + } + }); + root.addView(row); + } + dialog.setContentView(root); + styleDialog(dialog); + dialog.show(); + sizeDialog(dialog, 0.85f); + } + + // ---- niche mod badge --------------------------------------------------- + + private View nicheRow() { + LinearLayout row = Md3.listItem(this, palette, + Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.NOTE, palette.onPrimaryContainer, 8), + "Значок «Нишевый мод»", "Получить можно до 15 ноября 12:34 (МСК)", Md3.chevron(this, palette), true); + row.setOnClickListener(v -> openNicheDialog()); + return row; + } + + private void openNicheDialog() { + final lihont.two.badge.NicheClaim.Account account = lihont.two.badge.NicheClaim.account(); + final Dialog dialog = new Dialog(this); + dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + LinearLayout box = new LinearLayout(this); + box.setOrientation(LinearLayout.VERTICAL); + box.setPadding(Md3.dp(this, 24), Md3.dp(this, 24), Md3.dp(this, 24), Md3.dp(this, 16)); + box.setBackground(Md3.shape(palette.surfaceContainerHigh, Md3.dialogRadius(palette), this)); + box.addView(Md3.text(this, "Значок «Нишевый мод»", Md3.HEADLINE_SMALL, false, palette.onSurface)); + final TextView info = Md3.text(this, account == null + ? "Войдите в TikTok, чтобы получить значок." + : "1. Скопируйте код.\n2. Вставьте его в описание профиля TikTok.\n3. Нажмите «Проверить»: " + + "сервер найдёт код и выдаст значок. Он будет виден рядом с вашим ником у всех с модом.", + Md3.BODY_MEDIUM, false, palette.onSurfaceVariant); + info.setPadding(0, Md3.dp(this, 12), 0, Md3.dp(this, 12)); + box.addView(info); + final TextView code = Md3.text(this, account == null ? "" : "…", Md3.TITLE_LARGE, true, palette.primary); + box.addView(code); + final TextView result = Md3.text(this, "", Md3.BODY_MEDIUM, false, palette.onSurface); + result.setPadding(0, Md3.dp(this, 12), 0, 0); + box.addView(result); + LinearLayout buttons = new LinearLayout(this); + buttons.setGravity(Gravity.END); + buttons.setPadding(0, Md3.dp(this, 16), 0, 0); + TextView copy = Md3.textButton(this, palette, "Скопировать"); + TextView check = Md3.filledButton(this, palette, "Проверить"); + TextView close = Md3.textButton(this, palette, "Закрыть"); + buttons.addView(close); + buttons.addView(copy); + buttons.addView(check); + box.addView(buttons); + close.setOnClickListener(v -> dialog.dismiss()); + if (account != null) { + lihont.two.badge.NicheClaim.fetchCode(account, (ok, message, value) -> { + code.setText(ok ? value : ""); + if (!ok) result.setText(message); + }); + copy.setOnClickListener(v -> { + android.content.ClipboardManager clipboard = + (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); + clipboard.setPrimaryClip(android.content.ClipData.newPlainText("LihonT", code.getText())); + result.setText("Код скопирован"); + }); + check.setOnClickListener(v -> { + result.setText("Проверяем…"); + lihont.two.badge.NicheClaim.claim(account, (ok, message, value) -> result.setText(message)); + }); + } + dialog.setContentView(box); + styleDialog(dialog); + dialog.show(); + sizeDialog(dialog, 0.92f); + } + + // ---- app icon ---------------------------------------------------------- + + /** The row that opens the choice of built-in app icons; null when this build ships none. */ + private View appIconRow() { + List choices = AppIcons.list(this); + if (choices.size() < 2) return null; + AppIcons.Choice current = choices.get(0); + for (AppIcons.Choice choice : choices) { + if (choice.selected) current = choice; + } + LinearLayout row = Md3.listItem(this, palette, iconPreview(current.icon), "Значок приложения", + current.title, Md3.chevron(this, palette), true); + row.setOnClickListener(v -> openAppIconPicker()); + return row; + } + + /** An app icon as a 40dp rounded square, the way the launcher masks it. */ + private ImageView iconPreview(Drawable icon) { + final int size = Md3.dp(this, 40); + ImageView view = new ImageView(this); + view.setImageDrawable(icon); + view.setScaleType(ImageView.ScaleType.CENTER_CROP); + view.setOutlineProvider(new ViewOutlineProvider() { + @Override public void getOutline(View v, Outline outline) { + outline.setRoundRect(0, 0, v.getWidth(), v.getHeight(), size * 0.24f); + } + }); + view.setClipToOutline(true); + view.setLayoutParams(new LinearLayout.LayoutParams(size, size)); + return view; + } + + private void openAppIconPicker() { + final Dialog dialog = new Dialog(this); + dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + LinearLayout list = new LinearLayout(this); + list.setOrientation(LinearLayout.VERTICAL); + list.setPadding(0, Md3.dp(this, 8), 0, Md3.dp(this, 8)); + TextView title = Md3.text(this, "Значок приложения", Md3.HEADLINE_SMALL, false, palette.onSurface); + title.setPadding(Md3.dp(this, 24), Md3.dp(this, 16), Md3.dp(this, 24), Md3.dp(this, 8)); + list.addView(title); + for (final AppIcons.Choice choice : AppIcons.list(this)) { + View trailing = null; + if (choice.selected) { + ImageView check = new ImageView(this); + check.setImageDrawable(Md3Icon.of(Md3Icon.CHECK, palette.primary, this)); + check.setScaleType(ImageView.ScaleType.CENTER); + check.setLayoutParams(new LinearLayout.LayoutParams(Md3.dp(this, 24), Md3.dp(this, 24))); + trailing = check; + } + LinearLayout row = Md3.listItem(this, palette, iconPreview(choice.icon), choice.title, null, trailing, true); + row.setOnClickListener(v -> { + dialog.dismiss(); + chooseAppIcon(choice); + }); + list.addView(row); + } + ScrollView scroll = new ScrollView(this); + scroll.addView(list, new ScrollView.LayoutParams(-1, -2)); + scroll.setBackground(Md3.shape(palette.surfaceContainerHigh, Md3.dialogRadius(palette), this)); + dialog.setContentView(scroll); + styleDialog(dialog); + dialog.show(); + sizeDialog(dialog, 0.9f); + } + + private void chooseAppIcon(AppIcons.Choice choice) { + if (choice.selected) return; + boolean done = AppIcons.select(this, choice.component); + buildScreen(); + showNotice(done + ? "Значок сменится через несколько секунд. Если не изменился, перезапустите лончер." + : "Не удалось сменить значок"); + } + + // ---- custom icon ------------------------------------------------------- + + private View iconsRow() { + int count = iconStore.list().size(); + iconCountShown = count; + String hint = count == 0 ? "Своё фото как значок на главном экране" : "Сохранено значков: " + count; + LinearLayout row = Md3.listItem(this, palette, + Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.ADD_PHOTO, palette.onPrimaryContainer, 8), + "Свой значок", hint, Md3.chevron(this, palette), true); + row.setOnClickListener(v -> openIconsScreen()); + return row; + } + + private void openIconsScreen() { + final Dialog dialog = new Dialog(this); + dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + LinearLayout root = new LinearLayout(this); + root.setOrientation(LinearLayout.VERTICAL); + root.setBackgroundColor(palette.surface); + applyInsets(root); + root.addView(Md3.appBar(this, palette, "Свой значок", Md3Icon.CLOSE, "Закрыть", v -> dialog.dismiss())); + ScrollView scroll = new ScrollView(this); + scroll.setFillViewport(true); + iconsList = new LinearLayout(this); + iconsList.setOrientation(LinearLayout.VERTICAL); + scroll.addView(iconsList, new ScrollView.LayoutParams(-1, -2)); + root.addView(scroll, new LinearLayout.LayoutParams(-1, 0, 1f)); + iconsHost = new FrameLayout(this); + iconsHost.addView(root, new FrameLayout.LayoutParams(-1, -1)); + iconsDialog = dialog; + dialog.setOnDismissListener(d -> { + handler.removeCallbacks(hideIconsNotice); + iconsDialog = null; + iconsList = null; + iconsHost = null; + iconsNotice = null; + if (iconStore.list().size() != iconCountShown) buildScreen(); + }); + renderIcons(); + dialog.setContentView(iconsHost); + styleDialog(dialog); + dialog.show(); + if (dialog.getWindow() != null) { + dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); + } + } + + private void renderIcons() { + if (iconsList == null) return; + iconsList.removeAllViews(); + TextView intro = Md3.text(this, + "Выберите фото: оно станет значком TikTok на главном экране. Значок самого приложения в меню остаётся прежним.", + Md3.BODY_MEDIUM, false, palette.onSurfaceVariant); + intro.setPadding(Md3.dp(this, 24), Md3.dp(this, 8), Md3.dp(this, 24), Md3.dp(this, 16)); + iconsList.addView(intro); + + TextView add = Md3.filledTonalButton(this, palette, "Добавить фото"); + add.setOnClickListener(v -> pickIcon()); + LinearLayout.LayoutParams addParams = new LinearLayout.LayoutParams(-2, -2); + addParams.leftMargin = Md3.dp(this, 16); + addParams.bottomMargin = Md3.dp(this, 8); + iconsList.addView(add, addParams); + + if (!IconShortcuts.canPin(this)) { + TextView unsupported = Md3.text(this, + "Этот лончер не умеет закреплять ярлыки: значки можно сохранить, но вынести на экран не получится.", + Md3.BODY_SMALL, false, palette.error); + unsupported.setPadding(Md3.dp(this, 24), Md3.dp(this, 8), Md3.dp(this, 24), Md3.dp(this, 8)); + iconsList.addView(unsupported); + } + + final List entries = iconStore.list(); + if (entries.isEmpty()) { + TextView empty = Md3.text(this, "Пока нет значков", Md3.BODY_MEDIUM, false, palette.onSurfaceVariant); + empty.setPadding(Md3.dp(this, 24), Md3.dp(this, 16), Md3.dp(this, 24), Md3.dp(this, 8)); + iconsList.addView(empty); + return; + } + iconsList.addView(Md3.subheader(this, palette, "Мои значки")); + LinearLayout card = Md3.card(this, palette); + for (int i = 0; i < entries.size(); i++) { + if (i > 0) card.addView(Md3.cardDivider(this, palette)); + card.addView(iconRow(entries.get(i))); + } + iconsList.addView(card); + } + + private View iconRow(final CustomIconStore.Entry entry) { + int size = Md3.dp(this, 40); + ImageView preview = new ImageView(this); + Bitmap stored = BitmapFactory.decodeFile(entry.image.getAbsolutePath()); + if (stored != null) { + preview.setImageBitmap(IconShortcuts.roundedPreview(stored, size)); + stored.recycle(); + } + preview.setLayoutParams(new LinearLayout.LayoutParams(size, size)); + + ImageView delete = new ImageView(this); + delete.setImageDrawable(Md3Icon.of(Md3Icon.DELETE, palette.onSurfaceVariant, this)); + delete.setScaleType(ImageView.ScaleType.CENTER); + delete.setBackground(Md3.stateLayer(this, Md3.SHAPE_FULL, Md3.stateLayerColor(palette.onSurface))); + delete.setContentDescription("Удалить значок " + entry.name); + delete.setClickable(true); + delete.setFocusable(true); + delete.setLayoutParams(new LinearLayout.LayoutParams(size, size)); + delete.setOnClickListener(v -> confirmDeleteIcon(entry)); + + LinearLayout row = Md3.listItem(this, palette, preview, entry.name, + "Нажмите, чтобы добавить на главный экран", delete, true); + row.setOnClickListener(v -> pinIcon(entry)); + return row; + } + + private void pickIcon() { + try { + startActivityForResult(IconShortcuts.pickIntent(), IconShortcuts.REQUEST_PICK); + } catch (ActivityNotFoundException | SecurityException none) { + showIconsNotice("Не нашлось приложения для выбора фото"); + } + } + + @Override protected void onActivityResult(int request, int result, Intent data) { + super.onActivityResult(request, result, data); + if (request != IconShortcuts.REQUEST_PICK || result != RESULT_OK || data == null || iconStore == null) return; + final Uri uri = data.getData(); + if (uri == null) return; + new Thread(() -> { + Bitmap square = null; + try { + square = IconShortcuts.decodeSquare(getContentResolver(), uri); + } catch (IOException | RuntimeException | OutOfMemoryError unreadable) { + // Reported on the screen below. + } + final Bitmap picked = square; + handler.post(() -> { + if (isFinishing()) return; + if (iconsDialog == null) openIconsScreen(); + if (picked == null) showIconsNotice("Не удалось открыть это фото"); + else showIconNameDialog(picked); + }); + }, "lihont-icon-decode").start(); + } + + private void showIconNameDialog(final Bitmap square) { + final Dialog dialog = new Dialog(this); + dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + LinearLayout root = new LinearLayout(this); + root.setOrientation(LinearLayout.VERTICAL); + root.setBackground(Md3.shape(palette.surfaceContainerHigh, Md3.dialogRadius(palette), this)); + root.setPadding(Md3.dp(this, 24), Md3.dp(this, 24), Md3.dp(this, 24), Md3.dp(this, 24)); + root.addView(Md3.text(this, "Новый значок", Md3.HEADLINE_SMALL, false, palette.onSurface)); + + int previewSize = Md3.dp(this, 96); + ImageView preview = new ImageView(this); + preview.setImageBitmap(IconShortcuts.roundedPreview(square, previewSize)); + LinearLayout.LayoutParams previewParams = new LinearLayout.LayoutParams(previewSize, previewSize); + previewParams.gravity = Gravity.CENTER_HORIZONTAL; + previewParams.topMargin = Md3.dp(this, 16); + root.addView(preview, previewParams); + + TextView caption = Md3.text(this, "Так значок выглядит на главном экране", Md3.BODY_SMALL, false, + palette.onSurfaceVariant); + caption.setGravity(Gravity.CENTER_HORIZONTAL); + LinearLayout.LayoutParams captionParams = new LinearLayout.LayoutParams(-1, -2); + captionParams.topMargin = Md3.dp(this, 8); + captionParams.bottomMargin = Md3.dp(this, 16); + root.addView(caption, captionParams); + + final EditText input = new EditText(this); + input.setText(CustomIconStore.DEFAULT_NAME); + input.setSelectAllOnFocus(true); + input.setHint("Название под значком"); + input.setHintTextColor(palette.onSurfaceVariant); + input.setTextColor(palette.onSurface); + input.setTextSize(Md3.BODY_LARGE); + input.setSingleLine(true); + input.setFilters(new InputFilter[] { new InputFilter.LengthFilter(CustomIconStore.MAX_NAME) }); + input.setBackground(Md3.outlined(Color.TRANSPARENT, palette.outline, 1f, Md3.SHAPE_EXTRA_SMALL, this)); + input.setPadding(Md3.dp(this, 16), Md3.dp(this, 14), Md3.dp(this, 16), Md3.dp(this, 14)); + root.addView(input, new LinearLayout.LayoutParams(-1, -2)); + + LinearLayout actions = new LinearLayout(this); + actions.setGravity(Gravity.END); + LinearLayout.LayoutParams actionsParams = new LinearLayout.LayoutParams(-1, -2); + actionsParams.topMargin = Md3.dp(this, 24); + root.addView(actions, actionsParams); + TextView cancel = Md3.textButton(this, palette, "Отмена"); + cancel.setOnClickListener(v -> dialog.dismiss()); + actions.addView(cancel); + TextView save = Md3.textButton(this, palette, "Добавить"); + save.setOnClickListener(v -> { + dialog.dismiss(); + try { + iconStore.add(IconShortcuts.toPng(square), input.getText().toString()); + renderIcons(); + showIconsNotice("Значок добавлен. Нажмите на него, чтобы вынести на главный экран"); + } catch (IOException | RuntimeException error) { + showIconsNotice(iconStore.list().size() >= CustomIconStore.MAX_ICONS + ? "Достигнут предел в " + CustomIconStore.MAX_ICONS + " значков. Удалите ненужный." + : "Не удалось сохранить значок"); + } + }); + LinearLayout.LayoutParams saveParams = new LinearLayout.LayoutParams(-2, -2); + saveParams.leftMargin = Md3.dp(this, 8); + actions.addView(save, saveParams); + + dialog.setContentView(root); + styleDialog(dialog); + dialog.show(); + sizeDialog(dialog, 0.9f); + } + + private void pinIcon(CustomIconStore.Entry entry) { + if (IconShortcuts.pin(this, entry)) { + showIconsNotice("Подтвердите добавление значка в окне лончера"); + } else if (!IconShortcuts.canPin(this)) { + showIconsNotice("Этот лончер не умеет закреплять ярлыки"); + } else { + showIconsNotice("Не удалось добавить значок"); + } + } + + private void confirmDeleteIcon(final CustomIconStore.Entry entry) { + basicDialog("Удалить значок «" + entry.name + "»?", + "Копия на главном экране перестанет открываться.", + "Отмена", "Удалить", () -> { + if (iconStore.remove(entry.id)) { + IconShortcuts.unpin(this, entry.id); + renderIcons(); + } else { + showIconsNotice("Не удалось удалить значок"); + } + }); + } + + /** A message at the bottom of the icons screen; the settings screen's own snackbar is under it. */ + private void showIconsNotice(String message) { + if (iconsHost == null) return; + handler.removeCallbacks(hideIconsNotice); + if (iconsNotice != null) iconsHost.removeView(iconsNotice); + iconsNotice = Md3.snackbar(this, palette, message, "OK", v -> dismissIconsNotice()); + FrameLayout.LayoutParams params = new FrameLayout.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM); + params.leftMargin = Md3.dp(this, 16); + params.rightMargin = Md3.dp(this, 16); + params.bottomMargin = bottomInset + Md3.dp(this, 16); + iconsHost.addView(iconsNotice, params); + handler.postDelayed(hideIconsNotice, 6000); + } + + private void dismissIconsNotice() { + handler.removeCallbacks(hideIconsNotice); + if (iconsNotice != null && iconsHost != null) iconsHost.removeView(iconsNotice); + iconsNotice = null; + } + + // ---- pickers ----------------------------------------------------------- + + private void openRegionPicker() { + final Dialog dialog = new Dialog(this); + dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + LinearLayout root = new LinearLayout(this); + root.setOrientation(LinearLayout.VERTICAL); + root.setBackgroundColor(palette.surface); + applyInsets(root); + root.addView(Md3.appBar(this, palette, "Регион мода", Md3Icon.CLOSE, "Закрыть", v -> dialog.dismiss())); + + LinearLayout searchBar = new LinearLayout(this); + searchBar.setOrientation(LinearLayout.HORIZONTAL); + searchBar.setGravity(Gravity.CENTER_VERTICAL); + searchBar.setBackground(Md3.shape(palette.surfaceContainerHigh, Md3.SHAPE_FULL, this)); + searchBar.setPadding(Md3.dp(this, 16), 0, Md3.dp(this, 16), 0); + ImageView searchIcon = new ImageView(this); + searchIcon.setImageDrawable(Md3Icon.of(Md3Icon.SEARCH, palette.onSurfaceVariant, this)); + searchBar.addView(searchIcon, new LinearLayout.LayoutParams(Md3.dp(this, 24), Md3.dp(this, 24))); + EditText input = new EditText(this); + input.setHint("Поиск страны или ISO-кода"); + input.setHintTextColor(palette.onSurfaceVariant); + input.setTextColor(palette.onSurface); + input.setTextSize(Md3.BODY_LARGE); + input.setSingleLine(true); + input.setBackground(null); + LinearLayout.LayoutParams inputParams = new LinearLayout.LayoutParams(0, -1, 1f); + inputParams.leftMargin = Md3.dp(this, 12); + searchBar.addView(input, inputParams); + LinearLayout.LayoutParams barParams = new LinearLayout.LayoutParams(-1, Md3.dp(this, 56)); + barParams.leftMargin = Md3.dp(this, 16); + barParams.rightMargin = Md3.dp(this, 16); + barParams.topMargin = Md3.dp(this, 4); + barParams.bottomMargin = Md3.dp(this, 8); + root.addView(searchBar, barParams); + + final List entries = countryEntries(); + final List visible = new ArrayList(entries); + final BaseAdapter adapter = new BaseAdapter() { + @Override public int getCount() { return visible.size(); } + @Override public Object getItem(int position) { return visible.get(position); } + @Override public long getItemId(int position) { return position; } + @Override public View getView(int position, View recycled, ViewGroup parent) { + String[] entry = visible.get(position); + boolean selected = entry[0].equals(settings.region()); + View trailing = null; + if (selected) { + ImageView check = new ImageView(LihonTSettingsActivity.this); + check.setImageDrawable(Md3Icon.of(Md3Icon.CHECK, palette.primary, LihonTSettingsActivity.this)); + check.setScaleType(ImageView.ScaleType.CENTER); + check.setLayoutParams(new LinearLayout.LayoutParams(Md3.dp(LihonTSettingsActivity.this, 24), + Md3.dp(LihonTSettingsActivity.this, 24))); + trailing = check; + } + LinearLayout row = Md3.listItem(LihonTSettingsActivity.this, palette, + Md3.flowerAvatar(LihonTSettingsActivity.this, palette.primaryContainer, palette.onPrimaryContainer, entry[0], 8), + entry[1], entry[0], trailing, false); + row.setOnClickListener(v -> chooseRegion(dialog, entry[0])); + return row; + } + }; + ListView list = new ListView(this); + list.setDivider(null); + list.setSelector(new ColorDrawable(Color.TRANSPARENT)); + list.setAdapter(adapter); + list.setOnItemClickListener((parent, view, position, id) -> chooseRegion(dialog, visible.get(position)[0])); + root.addView(list, new LinearLayout.LayoutParams(-1, 0, 1f)); + + input.addTextChangedListener(new TextWatcher() { + @Override public void beforeTextChanged(CharSequence s, int a, int b, int c) { } + @Override public void onTextChanged(CharSequence s, int a, int b, int c) { } + @Override public void afterTextChanged(Editable s) { + String query = s.toString().trim().toLowerCase(Locale.ROOT); + visible.clear(); + for (String[] entry : entries) { + if (query.length() == 0 || entry[1].toLowerCase(Locale.ROOT).contains(query) + || entry[0].toLowerCase(Locale.ROOT).contains(query)) { + visible.add(entry); + } + } + adapter.notifyDataSetChanged(); + } + }); + + dialog.setContentView(root); + styleDialog(dialog); + dialog.show(); + if (dialog.getWindow() != null) { + dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); + } + } + + private void chooseRegion(final Dialog dialog, final String code) { + persist(settings.withRegion(code)); + dialog.dismiss(); + showRestartDialog(); + } + + private void showRestartDialog() { + basicDialog("Для изменения настроек перезагрузите приложение", + "Кэш приложения будет очищен, чтобы новые настройки применились корректно.", + "Отмена", "Перезагрузить", () -> { + restartApp(); + }); + } + + /** A bottom message for switches: the change is saved, but only the next TikTok start uses it. */ + private void showRestartNotice() { + showSnack("Изменения применятся после перезапуска TikTok", "Перезапуск", () -> { + dismissRestartNotice(); + showRestartDialog(); + }); + } + + private void showNotice(String message) { + showSnack(message, "OK", this::dismissRestartNotice); + } + + private void showSnack(String message, String action, final Runnable onAction) { + if (host == null) return; + handler.removeCallbacks(hideSnackbar); + if (snackbar != null) host.removeView(snackbar); + snackbar = Md3.snackbar(this, palette, message, action, v -> onAction.run()); + FrameLayout.LayoutParams params = new FrameLayout.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, + Gravity.BOTTOM); + params.leftMargin = Md3.dp(this, 16); + params.rightMargin = Md3.dp(this, 16); + params.bottomMargin = bottomInset + Md3.dp(this, 16); + snackbar.setAlpha(0f); + snackbar.setTranslationY(Md3.dp(this, 24)); + host.addView(snackbar, params); + snackbar.animate().alpha(1f).translationY(0f).setDuration(200).start(); + handler.postDelayed(hideSnackbar, 8000); + } + + private void dismissRestartNotice() { + handler.removeCallbacks(hideSnackbar); + final View bar = snackbar; + if (bar == null || host == null) return; + snackbar = null; + bar.animate().alpha(0f).translationY(Md3.dp(this, 24)).setDuration(150) + .withEndAction(() -> { if (host != null) host.removeView(bar); }).start(); + } + + @Override protected void onDestroy() { + handler.removeCallbacks(hideSnackbar); + handler.removeCallbacks(hideIconsNotice); + if (iconsDialog != null) { + iconsDialog.setOnDismissListener(null); + iconsDialog.dismiss(); + } + super.onDestroy(); + } + + private void clearCache() { + try { + deleteRecursively(getCacheDir()); + if (Build.VERSION.SDK_INT >= 21) { + deleteRecursively(getCodeCacheDir()); + } + File ext = getExternalCacheDir(); + if (ext != null) { + deleteRecursively(ext); + } + } catch (Throwable ignored) {} + } + + private static boolean deleteRecursively(File file) { + if (file == null || !file.exists()) return true; + if (file.isDirectory()) { + File[] children = file.listFiles(); + if (children != null) { + for (File child : children) { + deleteRecursively(child); + } + } + } + return file.delete(); + } + + private void restartApp() { + clearCache(); + try { + Intent intent = getPackageManager().getLaunchIntentForPackage(getPackageName()); + if (intent != null) { + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); + startActivity(intent); + } + } catch (Throwable ignored) {} + System.exit(0); + } + + private void openThemePicker() { + final Dialog dialog = new Dialog(this); + dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + LinearLayout root = new LinearLayout(this); + root.setOrientation(LinearLayout.VERTICAL); + root.setBackground(Md3.shape(palette.surfaceContainerHigh, Md3.dialogRadius(palette), this)); + root.setPadding(0, Md3.dp(this, 8), 0, Md3.dp(this, 8)); + for (final ModSettings.Theme option : ModSettings.Theme.values()) { + boolean selected = option == settings.theme(); + View trailing = null; + if (selected) { + ImageView check = new ImageView(this); + check.setImageDrawable(Md3Icon.of(Md3Icon.CHECK, palette.primary, this)); + check.setScaleType(ImageView.ScaleType.CENTER); + check.setLayoutParams(new LinearLayout.LayoutParams(Md3.dp(this, 24), Md3.dp(this, 24))); + trailing = check; + } + LinearLayout row = Md3.listItem(this, palette, null, themeLabel(option), null, trailing, true); + row.setOnClickListener(v -> { + persist(settings.withTheme(option)); + dialog.dismiss(); + }); + root.addView(row); + } + dialog.setContentView(root); + styleDialog(dialog); + dialog.show(); + sizeDialog(dialog, 0.85f); + } + + private void confirmReset() { + basicDialog("Сбросить настройки?", "Значения вернутся к состоянию по умолчанию: Япония, баннеры и репосты включены.", + "Отмена", "Сбросить", () -> { + try { + repository.reset(); + settings = repository.current(); + palette = Md3.palette(this, settings); + Window window = getWindow(); + window.setBackgroundDrawable(new ColorDrawable(palette.surface)); + window.setStatusBarColor(palette.surface); + window.setNavigationBarColor(palette.surface); + updateSystemBars(window, palette.dark); + buildScreen(); + } catch (IOException | RuntimeException error) { + updateStatus(); + } + }); + } + + Dialog basicDialog(CharSequence title, CharSequence message, CharSequence negative, + CharSequence positive, final Runnable onPositive) { + final Dialog dialog = new Dialog(this); + dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + LinearLayout root = new LinearLayout(this); + root.setOrientation(LinearLayout.VERTICAL); + root.setBackground(Md3.shape(palette.surfaceContainerHigh, Md3.dialogRadius(palette), this)); + root.setPadding(Md3.dp(this, 24), Md3.dp(this, 24), Md3.dp(this, 24), Md3.dp(this, 24)); + root.addView(Md3.text(this, title, Md3.HEADLINE_SMALL, false, palette.onSurface)); + if (message != null) { + TextView body = Md3.text(this, message, Md3.BODY_MEDIUM, false, palette.onSurfaceVariant); + LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(-1, -2); + params.topMargin = Md3.dp(this, 16); + root.addView(body, params); + } + LinearLayout actions = new LinearLayout(this); + actions.setGravity(Gravity.END); + LinearLayout.LayoutParams actionsParams = new LinearLayout.LayoutParams(-1, -2); + actionsParams.topMargin = Md3.dp(this, 24); + root.addView(actions, actionsParams); + if (negative != null) { + TextView cancel = Md3.textButton(this, palette, negative); + cancel.setOnClickListener(v -> dialog.dismiss()); + actions.addView(cancel); + } + if (positive != null) { + TextView confirm = Md3.textButton(this, palette, positive); + confirm.setOnClickListener(v -> { + dialog.dismiss(); + if (onPositive != null) onPositive.run(); + }); + LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(-2, -2); + params.leftMargin = Md3.dp(this, 8); + actions.addView(confirm, params); + } + dialog.setContentView(root); + styleDialog(dialog); + dialog.show(); + sizeDialog(dialog, 0.9f); + return dialog; + } + + private void showStorageError() { + palette = Md3.dark(); + Window window = getWindow(); + window.setBackgroundDrawable(new ColorDrawable(palette.surface)); + window.setStatusBarColor(palette.surface); + window.setNavigationBarColor(palette.surface); + if (Build.VERSION.SDK_INT >= 29) { + window.setNavigationBarContrastEnforced(false); + window.setStatusBarContrastEnforced(false); + } + updateSystemBars(window, palette.dark); + LinearLayout root = new LinearLayout(this); + root.setOrientation(LinearLayout.VERTICAL); + root.setBackgroundColor(palette.surface); + applyInsets(root, null); + root.addView(Md3.appBar(this, palette, "Настройки мода", Md3Icon.CLOSE, "Закрыть", v -> finish())); + TextView message = Md3.text(this, + "Не удалось прочитать локальные настройки. Данные не были перезаписаны.", + Md3.BODY_MEDIUM, false, palette.onSurfaceVariant); + message.setPadding(Md3.dp(this, 16), Md3.dp(this, 8), Md3.dp(this, 16), 0); + root.addView(message); + setContentView(root); + } + + // ---- state ------------------------------------------------------------- + + private boolean persist(ModSettings next) { + try { + repository.save(next); + lihont.two.LihonTRegion.setRegion(next.region()); + settings = next; + palette = Md3.palette(this, settings); + Window window = getWindow(); + window.setBackgroundDrawable(new ColorDrawable(palette.surface)); + window.setStatusBarColor(palette.surface); + window.setNavigationBarColor(palette.surface); + updateSystemBars(window, palette.dark); + buildScreen(); + return true; + } catch (IOException | RuntimeException error) { + if (status != null) { + status.setText("Не удалось сохранить настройки."); + status.setTextColor(palette.error); + } + return false; + } + } + + private void updateStatus() { + if (status == null) return; + StringBuilder message = new StringBuilder("Значения хранятся локально и не выдаются за серверные."); + if (repository.restartRequired()) message.append(" Изменения применятся после перезапуска TikTok."); + if (settings.needsBannerWarning()) message.append(" В выбранном регионе часть баннеров может быть недоступна."); + status.setText(message); + status.setTextColor(settings.needsBannerWarning() ? palette.error : palette.onSurfaceVariant); + } + + // ---- helpers ----------------------------------------------------------- + + private List countryEntries() { + List entries = new ArrayList(); + for (String code : ModSettings.COUNTRY_CODES) { + String name = new Locale("", code).getDisplayCountry(new Locale("ru")); + if (name == null || name.length() == 0) name = code; + entries.add(new String[] { code, name }); + } + Collections.sort(entries, new Comparator() { + @Override public int compare(String[] left, String[] right) { + return left[1].compareToIgnoreCase(right[1]); + } + }); + return entries; + } + + private String countryLabel(String code) { + String name = new Locale("", code).getDisplayCountry(new Locale("ru")); + return (name == null || name.length() == 0) ? code : name; + } + + private String themeLabel(ModSettings.Theme theme) { + if (theme == ModSettings.Theme.LIGHT) return "Светлая"; + if (theme == ModSettings.Theme.DARK) return "Тёмная"; + return "Системная"; + } + + private void openUrl(String url) { + try { + startActivity(new Intent(Intent.ACTION_VIEW, android.net.Uri.parse(url))); + } catch (RuntimeException ignored) { + // No browser or blocked link: the row simply stays informational. + } + } + + private void applyInsets(final View root) { + applyInsets(root, null); + } + + private void applyInsets(final View root, final View scroll) { + if (Build.VERSION.SDK_INT >= 20) { + root.setOnApplyWindowInsetsListener((v, insets) -> { + int top = 0; + int bottom = 0; + if (Build.VERSION.SDK_INT >= 30) { + android.graphics.Insets bars = insets.getInsets(android.view.WindowInsets.Type.systemBars()); + top = bars.top; + bottom = bars.bottom; + } else { + top = insets.getSystemWindowInsetTop(); + bottom = insets.getSystemWindowInsetBottom(); + } + v.setPadding(0, top, 0, scroll == null ? bottom : 0); + if (scroll != null) { + bottomInset = bottom; + if (snackbar != null && snackbar.getLayoutParams() instanceof FrameLayout.LayoutParams) { + FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) snackbar.getLayoutParams(); + lp.bottomMargin = bottom + Md3.dp(LihonTSettingsActivity.this, 16); + snackbar.setLayoutParams(lp); + } + scroll.setPadding(0, 0, 0, bottom + Md3.dp(LihonTSettingsActivity.this, 24)); + } + return insets; + }); + } + } + + private void updateSystemBars(Window window, boolean isDark) { + if (Build.VERSION.SDK_INT >= 30) { + android.view.WindowInsetsController controller = window.getInsetsController(); + if (controller != null) { + int appearance = 0; + if (!isDark) { + appearance |= android.view.WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS; + appearance |= android.view.WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS; + } + controller.setSystemBarsAppearance(appearance, + android.view.WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS | + android.view.WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS); + } + } else if (Build.VERSION.SDK_INT >= 26) { + View decor = window.getDecorView(); + int flags = decor.getSystemUiVisibility(); + if (!isDark) { + flags |= View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR; + flags |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR; + } else { + flags &= ~View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR; + flags &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR; + } + decor.setSystemUiVisibility(flags); + } + } + + void styleDialog(Dialog dialog) { + Window window = dialog.getWindow(); + if (window == null) return; + window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); + window.setStatusBarColor(palette.surface); + window.setNavigationBarColor(palette.surface); + if (Build.VERSION.SDK_INT >= 29) { + window.setNavigationBarContrastEnforced(false); + window.setStatusBarContrastEnforced(false); + } + updateSystemBars(window, palette.dark); + window.setDimAmount(0.5f); + window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); + } + + void sizeDialog(Dialog dialog, float widthFraction) { + Window window = dialog.getWindow(); + if (window == null) return; + int width = (int) (getResources().getDisplayMetrics().widthPixels * widthFraction); + window.setLayout(width, ViewGroup.LayoutParams.WRAP_CONTENT); + } +} + + diff --git a/src/lihont/two/settings/Md3Icon.java b/src/lihont/two/settings/Md3Icon.java index 8e8c4b0..0b2ab65 100644 --- a/src/lihont/two/settings/Md3Icon.java +++ b/src/lihont/two/settings/Md3Icon.java @@ -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); } +} diff --git a/src/lihont/two/streak/AutoFlame.java b/src/lihont/two/streak/AutoFlame.java new file mode 100644 index 0000000..29f041e --- /dev/null +++ b/src/lihont/two/streak/AutoFlame.java @@ -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 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 nextLines(Context context) { + List out = new ArrayList(); + 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; + } +} diff --git a/src/lihont/two/streak/AutoFlameBook.java b/src/lihont/two/streak/AutoFlameBook.java new file mode 100644 index 0000000..cb3d949 --- /dev/null +++ b/src/lihont/two/streak/AutoFlameBook.java @@ -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 chats = new LinkedHashSet(); + private final Map sentOn = new HashMap(); + + 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 chats() { return new ArrayList(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 pending(long nowMillis, TimeZone zone) { + List out = new ArrayList(); + 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 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); + } + } +} diff --git a/src/lihont/two/streak/AutoFlameReceiver.java b/src/lihont/two/streak/AutoFlameReceiver.java new file mode 100644 index 0000000..3e9c389 --- /dev/null +++ b/src/lihont/two/streak/AutoFlameReceiver.java @@ -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(); + } +} diff --git a/src/lihont/two/streak/AutoFlameStore.java b/src/lihont/two/streak/AutoFlameStore.java new file mode 100644 index 0000000..ad8c1a0 --- /dev/null +++ b/src/lihont/two/streak/AutoFlameStore.java @@ -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(); + } +} diff --git a/src/lihont/two/streak/FlameSender.java b/src/lihont/two/streak/FlameSender.java new file mode 100644 index 0000000..856dee3 --- /dev/null +++ b/src/lihont/two/streak/FlameSender.java @@ -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; + } + }); + } +} diff --git a/src/lihont/two/widget/AppContext.java b/src/lihont/two/widget/AppContext.java new file mode 100644 index 0000000..023126d --- /dev/null +++ b/src/lihont/two/widget/AppContext.java @@ -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; + } + } +} diff --git a/src/lihont/two/widget/Contacts.java b/src/lihont/two/widget/Contacts.java new file mode 100644 index 0000000..ac42cbf --- /dev/null +++ b/src/lihont/two/widget/Contacts.java @@ -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> LISTS = + new HashMap>(); + 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 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 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 all(Context context, String owner) { + synchronized (LISTS) { + load(context); + save(context, true); + LinkedHashMap merged = new LinkedHashMap(); + LinkedHashMap shared = LISTS.get(SHARED); + if (shared != null) merged.putAll(shared); + LinkedHashMap 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 list(String owner) { + LinkedHashMap list = LISTS.get(owner); + if (list == null) { + if (LISTS.size() >= MAX_ACCOUNTS) return null; + list = new LinkedHashMap(); + 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 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 list = list(owner); + if (list == null) continue; + Iterator 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> list : LISTS.entrySet()) { + JSONObject json = new JSONObject(); + for (Map.Entry 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); + } +} diff --git a/src/lihont/two/widget/FlowerArt.java b/src/lihont/two/widget/FlowerArt.java new file mode 100644 index 0000000..c05f4e5 --- /dev/null +++ b/src/lihont/two/widget/FlowerArt.java @@ -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; + } +} diff --git a/src/lihont/two/widget/StreakApi.java b/src/lihont/two/widget/StreakApi.java new file mode 100644 index 0000000..31e723f --- /dev/null +++ b/src/lihont/two/widget/StreakApi.java @@ -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::"; 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); + } +} diff --git a/src/lihont/two/widget/StreakConfigActivity.java b/src/lihont/two/widget/StreakConfigActivity.java new file mode 100644 index 0000000..e0cf803 --- /dev/null +++ b/src/lihont/two/widget/StreakConfigActivity.java @@ -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 found = new ArrayList(); + final NicheClaim.Account me = NicheClaim.account(); + if (me != null) { + for (Map.Entry 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() { + @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 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(); + } +} diff --git a/src/lihont/two/widget/StreakWidget.java b/src/lihont/two/widget/StreakWidget.java new file mode 100644 index 0000000..2b3d71e --- /dev/null +++ b/src/lihont/two/widget/StreakWidget.java @@ -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); + } +} diff --git a/src/lihont/two/widget/StreakWidget1.java b/src/lihont/two/widget/StreakWidget1.java new file mode 100644 index 0000000..094b7ee --- /dev/null +++ b/src/lihont/two/widget/StreakWidget1.java @@ -0,0 +1,4 @@ +package lihont.two.widget; + +/** The 1x1-cell receiver of the streak widget (see StreakWidget). */ +public final class StreakWidget1 extends StreakWidget {} diff --git a/src/lihont/two/widget/StreakWidget3.java b/src/lihont/two/widget/StreakWidget3.java new file mode 100644 index 0000000..5a6c61d --- /dev/null +++ b/src/lihont/two/widget/StreakWidget3.java @@ -0,0 +1,4 @@ +package lihont.two.widget; + +/** The 3x3-cell receiver of the streak widget (see StreakWidget). */ +public final class StreakWidget3 extends StreakWidget {} diff --git a/src/lihont/two/widget/StreakWidget4.java b/src/lihont/two/widget/StreakWidget4.java new file mode 100644 index 0000000..fcd7e34 --- /dev/null +++ b/src/lihont/two/widget/StreakWidget4.java @@ -0,0 +1,4 @@ +package lihont.two.widget; + +/** The 4x4-cell receiver of the streak widget (see StreakWidget). */ +public final class StreakWidget4 extends StreakWidget {} diff --git a/src/lihont/two/widget/WidgetStore.java b/src/lihont/two/widget/WidgetStore.java new file mode 100644 index 0000000..f703955 --- /dev/null +++ b/src/lihont/two/widget/WidgetStore.java @@ -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(); + } +} diff --git a/tests/java/lihont/two/account/AccountShapeBookTest.java b/tests/java/lihont/two/account/AccountShapeBookTest.java new file mode 100644 index 0000000..297c34e --- /dev/null +++ b/tests/java/lihont/two/account/AccountShapeBookTest.java @@ -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); + } +} diff --git a/tests/java/lihont/two/look/BlackRuleTest.java b/tests/java/lihont/two/look/BlackRuleTest.java new file mode 100644 index 0000000..07e01ed --- /dev/null +++ b/tests/java/lihont/two/look/BlackRuleTest.java @@ -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); + } +} diff --git a/tests/java/lihont/two/settings/IconRenderTest.java b/tests/java/lihont/two/settings/IconRenderTest.java index 0d3ebe8..ee8956a 100644 --- a/tests/java/lihont/two/settings/IconRenderTest.java +++ b/tests/java/lihont/two/settings/IconRenderTest.java @@ -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); + } +} diff --git a/tests/java/lihont/two/streak/AutoFlameBookTest.java b/tests/java/lihont/two/streak/AutoFlameBookTest.java new file mode 100644 index 0000000..ada0c36 --- /dev/null +++ b/tests/java/lihont/two/streak/AutoFlameBookTest.java @@ -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 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); + } +} diff --git a/tests/test_account_shapes.py b/tests/test_account_shapes.py new file mode 100644 index 0000000..87c6c5c --- /dev/null +++ b/tests/test_account_shapes.py @@ -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() diff --git a/tests/test_attr_ids.py b/tests/test_attr_ids.py new file mode 100644 index 0000000..1df9f42 --- /dev/null +++ b/tests/test_attr_ids.py @@ -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() diff --git a/tests/test_auto_flame.py b/tests/test_auto_flame.py new file mode 100644 index 0000000..f9c2403 --- /dev/null +++ b/tests/test_auto_flame.py @@ -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() diff --git a/tests/test_black_rule.py b/tests/test_black_rule.py new file mode 100644 index 0000000..8736c78 --- /dev/null +++ b/tests/test_black_rule.py @@ -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() diff --git a/tests/test_dex_slot.py b/tests/test_dex_slot.py new file mode 100644 index 0000000..0632903 --- /dev/null +++ b/tests/test_dex_slot.py @@ -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() diff --git a/tests/test_streak_patch.py b/tests/test_streak_patch.py new file mode 100644 index 0000000..9e35e37 --- /dev/null +++ b/tests/test_streak_patch.py @@ -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() diff --git a/tests/test_widget_patch.py b/tests/test_widget_patch.py new file mode 100644 index 0000000..6173e8c --- /dev/null +++ b/tests/test_widget_patch.py @@ -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()