From 2907c99c449c09434fc112c7edaf2bc4e9963e04 Mon Sep 17 00:00:00 2001 From: cheb0chik Date: Wed, 11 Nov 2026 15:11:30 +0300 Subject: [PATCH] LihonT 3 Luna alpha 1: the lock, the journal of entries and the front-camera picture Lock for the whole app, every chat or chosen chats, opened by the phone's own fingerprint, face or lock-screen code. A journal of entries (time, result, wrong fingers, chats opened) with optional front-camera pictures kept in a private folder, and a clear-all button. Also: the mascot and the promo scripts for this release. Co-Authored-By: Claude Sonnet 5.5 --- scripts/make_alpha_cards.py | 147 ++++ scripts/make_mascot.py | 167 +++++ scripts/make_release_video.py | 368 +++++++++ scripts/make_thief_video.py | 700 ++++++++++++++++++ scripts/stage_site.py | 7 +- services/members/server.py | 22 +- src/lihont/two/chat/Bubbles.java | 32 + src/lihont/two/look/Windows.java | 14 +- src/lihont/two/pet/GiftActivity.java | 22 +- src/lihont/two/pet/Species.java | 143 +++- src/lihont/two/privacy/AppLock.java | 476 ++++++++++++ src/lihont/two/privacy/Authenticator.java | 85 +++ src/lihont/two/privacy/IntruderCamera.java | 295 ++++++++ src/lihont/two/privacy/LockJournal.java | 196 +++++ src/lihont/two/privacy/LockSettings.java | 119 +++ .../two/settings/LihonTSettingsActivity.java | 274 ++++++- src/lihont/two/settings/Md3Icon.java | 9 +- src/web/assets/pets/index.json | 20 + src/web/assets/site/oa.css | 4 + src/web/index.html | 107 ++- src/web/pet_index.html | 12 +- .../lihont/two/settings/IconRenderTest.java | 2 +- 22 files changed, 3160 insertions(+), 61 deletions(-) create mode 100644 scripts/make_alpha_cards.py create mode 100644 scripts/make_mascot.py create mode 100644 scripts/make_release_video.py create mode 100644 scripts/make_thief_video.py create mode 100644 src/lihont/two/privacy/AppLock.java create mode 100644 src/lihont/two/privacy/Authenticator.java create mode 100644 src/lihont/two/privacy/IntruderCamera.java create mode 100644 src/lihont/two/privacy/LockJournal.java create mode 100644 src/lihont/two/privacy/LockSettings.java create mode 100644 src/web/assets/pets/index.json diff --git a/scripts/make_alpha_cards.py b/scripts/make_alpha_cards.py new file mode 100644 index 0000000..dcabfe1 --- /dev/null +++ b/scripts/make_alpha_cards.py @@ -0,0 +1,147 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +The cards for the post about LihonT 3 · Luna alpha 1 (the lock, the journal of entries and the picture of the thief): six 1080x1920 PNGs in +work/alpha-cards/, in the light style of the Store cards. The phone, the screens and the faces are the ones of the skit +(scripts/make_thief_video.py), the cat is the mascot (scripts/make_mascot.py). Everything is drawn here. + + py -X utf8 -B scripts/make_alpha_cards.py +""" + +from __future__ import annotations + +import sys +from pathlib import Path + +from PIL import Image + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import make_mascot as MC # noqa: E402 +import make_store_cards as SC # noqa: E402 +import make_store_video as V # noqa: E402 +import make_thief_video as TH # noqa: E402 + +W, H, CX = SC.W, SC.H, SC.CX +INK, GREY, VIOLET = V.INK, V.GREY, V.VIOLET +OUT = V.ROOT / "work" / "alpha-cards" +BRAND = "LihonT 3 · Luna alpha 1" +RED = (214, 60, 70) + + +def footer(img): + flower = Image.open(V.ROOT / "src" / "brand" / "logo_note_flower_gold_1024.png").convert("RGBA").resize((86, 86), Image.Resampling.LANCZOS) + V.put_c(img, flower, CX - 230, H - 96) + V.text(img, (CX - 170, H - 94), BRAND + " · @lihont", 36, "semi", GREY, "lm") + + +def phone_card(img, key, cy=1090, scale=0.8, angle=0.0): + V.put_c(img, V.soft_shadow(380, 700, 60, blur=70, dy=50, alpha=50), CX, cy + 40) + V.put_c(img, TH.phone(key, False), CX, cy, scale, 1.0, angle) + + +def card_hero(): + img = SC.canvas() + SC.petals(img, 31, 26, (60, 80, W - 60, H - 160), avoid=[(140, 360, 940, 1000)]) + cat = MC.mascot(size=760) + V.put_c(img, V.soft_shadow(380, 120, 60, blur=50, dy=30, alpha=46), CX, 860) + V.put_c(img, cat, CX, 560) + V.text(img, (CX, 1000), "LihonT 3", 160, "semi", INK, "mm") + V.candy_text(img, CX, 1200, "ALPHA 1", 170, SC.LATE, 0.0, 0.0) + V.text(img, (CX, 1400), "блокировка и журнал входов", 52, "semi", INK, "mm") + V.text(img, (CX, 1470), "для твоего TikTok", 44, "reg", GREY, "mm") + V.pill(img, CX, 1590, "отпечаток · журнал · фото вора", VIOLET, (255, 255, 255), 36) + footer(img) + return img + + +def card_lock(): + img = SC.canvas() + SC.head(img, "Закрой TikTok\nотпечатком", "тем же, которым открываешь телефон", y=200, size=92) + phone_card(img, ("lock", 0, "wait"), cy=1160, scale=0.82) + footer(img) + return img + + +def card_modes(): + img = SC.canvas() + SC.head(img, "Что закрывать", "выбираешь сам", y=210) + rows = [("Весь TikTok", "открыл приложение, и сразу замок"), ("Все чаты", "каждый чат отдельно, у каждого свой замок"), + ("Выбранные чаты", "только те, которые ты отметил")] + for i, (a, b) in enumerate(rows): + y = 640 + i * 290 + V.put_c(img, V.card(900, 230, 54, blur=28, dy=14, alpha=44), CX, y) + V.put_c(img, V.disc(118, (255, 226, 238) if i == 0 else (222, 232, 255) if i == 1 else (226, 247, 232)), 210, y) + V.text(img, (210, y - 3), str(i + 1), 72, "black", INK, "mm") + V.text(img, (320, y - 34), a, 48, "bold", INK, "lm") + V.text(img, (320, y + 38), b, 30, "reg", GREY, "lm") + V.text(img, (CX, 1560), "Спрашивать снова", 40, "semi", INK, "mm") + for i, label in enumerate(["сразу", "1 мин", "5 мин", "15 мин"]): + V.pill(img, 190 + i * 233, 1650, label, (240, 240, 244), INK, 30) + footer(img) + return img + + +def card_journal(): + img = SC.canvas() + SC.head(img, "Журнал входов", "кто пытался открыть и когда", y=200, size=100) + phone_card(img, ("journal", 10, ""), cy=1170, scale=0.82) + footer(img) + return img + + +def card_thief(): + img = SC.canvas() + SC.petals(img, 33, 18, (40, 1500, W - 40, 1780), avoid=[(120, 1520, 960, 1740)]) + SC.head(img, "Фото при каждом входе", "фронтальная камера снимает того, кто открывает", y=210, size=84) + photo = TH.face_photo("thief", 720) + mask = Image.new("L", photo.size, 0) + from PIL import ImageDraw + ImageDraw.Draw(mask).rounded_rectangle([0, 0, photo.width, photo.height], radius=64, fill=255) + photo = photo.copy() + photo.putalpha(mask) + V.put_c(img, V.card(720, 720, 64, blur=36, dy=20, alpha=56), CX, 900) + V.put_c(img, photo, CX, 900) + V.pill(img, CX, 1320, "03:12 · Не открыто · 2 неверных попытки", RED, (255, 255, 255), 34) + V.text(img, (CX, 1450), "Снимки только в закрытой папке мода,", 40, "reg", GREY, "mm") + V.text(img, (CX, 1510), "не в галерее. Одна кнопка стирает всё.", 40, "reg", GREY, "mm") + V.pill(img, CX, 1650, "Очистить всё", (240, 240, 244), INK, 40) + footer(img) + return img + + +def card_install(): + img = SC.canvas() + SC.head(img, "Как получить", "это alpha: тестовая версия", y=210) + steps = [("Уже с LihonT 3?", "просто поверх, как обновление"), ("Новый?", "сначала удалите официальный TikTok"), + ("Скачайте alpha 1", "git.lihont.space/lihont/LihonT")] + for n, (a, b) in enumerate(steps): + y = 640 + n * 290 + V.put_c(img, V.card(900, 230, 54, blur=28, dy=14, alpha=44), CX, y) + V.put_c(img, V.disc(110, VIOLET), 210, y) + V.text(img, (210, y - 3), str(n + 1), 66, "bold", (255, 255, 255), "mm") + V.text(img, (310, y - 34), a, 44, "bold", INK, "lm") + V.text(img, (310, y + 38), b, 30, "reg", GREY, "lm") + V.put_c(img, MC.mascot(happy=True, size=380), CX, 1530) + V.text(img, (CX, 1730), "lihont.space · @lihont", 46, "semi", INK, "mm") + footer(img) + return img + + +CARDS = [("1_hero", card_hero), ("2_lock", card_lock), ("3_modes", card_modes), ("4_journal", card_journal), ("5_thief", card_thief), + ("6_install", card_install)] + + +def main() -> None: + OUT.mkdir(parents=True, exist_ok=True) + for name, make in CARDS: + path = OUT / ("card_%s.png" % name) + make().convert("RGB").save(path) + print(path) + sheet = Image.new("RGB", (3 * 360 + 8, 2 * 640 + 4), (190, 190, 195)) + for i, (name, _) in enumerate(CARDS): + sheet.paste(Image.open(OUT / ("card_%s.png" % name)).resize((360, 640), Image.Resampling.LANCZOS), ((i % 3) * 362, (i // 3) * 642)) + sheet.save(OUT / "sheet.png") + + +if __name__ == "__main__": + main() diff --git a/scripts/make_mascot.py b/scripts/make_mascot.py new file mode 100644 index 0000000..5a372d7 --- /dev/null +++ b/scripts/make_mascot.py @@ -0,0 +1,167 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +The mascot of LihonT: a tricolour cat (white, brown and black, like the user's own cat) with a collar and, on the collar, a round +tag with the gold flower-and-note of the logo. Drawn with the same hands as the Серийчик animals (scripts/make_pet_designs.py): round, +thick outline, a tail that wags, ears that twitch, a blink. + + py -X utf8 -B scripts/make_mascot.py # work/mascot/*.png, mascot_anim.gif and sheet.png +""" + +from __future__ import annotations + +import math +import sys +from pathlib import Path + +from PIL import Image, ImageChops, ImageDraw + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import make_pet_designs as D # noqa: E402 + +ROOT = Path(__file__).resolve().parents[1] +OUT = ROOT / "work" / "mascot" +SIZE = 1024 +WHITE_FUR = (255, 252, 246) +BROWN = (178, 108, 58) +BLACK = (54, 46, 52) +EAR_IN = (255, 160, 170) +COLLAR = (255, 99, 150) # the pink of the site's candy letters +COLLAR_DARK = (222, 52, 112) +GOLD = (238, 190, 107) +GOLD_DARK = (214, 150, 52) +NOTE = (92, 28, 40) + + +def patch(cv, region, shapes): + """Draws the (cx, cy, rx, ry, colour) ellipses of `shapes` and keeps only what lies inside the ellipse `region`: a patch of colour on the coat.""" + size = cv.img.size + layer = Image.new("RGBA", size, (0, 0, 0, 0)) + d = ImageDraw.Draw(layer) + for cx, cy, rx, ry, color in shapes: + x, y = cv.t(cx, cy) + a, b = rx * D.W * cv.K, ry * D.W * cv.K + d.ellipse([x - a, y - b, x + a, y + b], fill=tuple(cv.c(color)) + (255,)) + mask = Image.new("L", size, 0) + x, y = cv.t(region[0], region[1]) + a, b = region[2] * D.W * cv.K, region[3] * D.W * cv.K + ImageDraw.Draw(mask).ellipse([x - a, y - b, x + a, y + b], fill=255) + layer.putalpha(ImageChops.multiply(layer.getchannel("A"), mask)) + cv.img.alpha_composite(layer) + cv.d = ImageDraw.Draw(cv.img) + + +def collar(cv, cx, head_cy, head): + """The collar round the neck; drawn before the head so the chin lies over it.""" + cv.ell(cx, head_cy + head * 0.86, head * 0.84, head * 0.2, COLLAR) + cv.arc(cx, head_cy + head * 0.86, head * 0.78, head * 0.15, 20, 160, 0.008, tuple(cv.c(COLLAR_DARK))) + + +def tag(cv, cx, cy, r): + """The round tag on the collar: the logo's gold flower with the dark note on it.""" + petals = [(cx + math.cos(k * math.tau / 9) * r * 0.62, cy + math.sin(k * math.tau / 9) * r * 0.62, r * 0.42) for k in range(9)] + for outline in (True, False): + for x, y, rr in petals + [(cx, cy, r * 0.8)]: + (px, py), q = cv.t(x, y), rr * D.W * cv.K + (0.011 * D.W if outline else 0) + cv.d.ellipse([px - q, py - q, px + q, py + q], fill=D.INK if outline else tuple(cv.c(GOLD))) + cv.ell(cx, cy, r * 0.62, r * 0.62, GOLD_DARK, outline=False) + cv.ell(cx, cy, r * 0.56, r * 0.56, GOLD, outline=False) + note = tuple(cv.c(NOTE)) + cv.ell(cx - r * 0.16, cy + r * 0.26, r * 0.22, r * 0.16, NOTE, outline=False) + cv.line([(cx + r * 0.03, cy + r * 0.2), (cx + r * 0.03, cy - r * 0.34)], r * 0.1, note) + cv.poly([(cx + r * 0.0, cy - r * 0.36), (cx + r * 0.3, cy - r * 0.18), (cx + r * 0.3, cy - r * 0.02), (cx + r * 0.0, cy - r * 0.2)], NOTE, outline=False) + + +def mascot(sad=False, frame=0, happy=False, mouth=0.0, size=None): + """One picture of the cat. `mouth` 0..1 opens the mouth (it mews: the eyes close then); `size` is the side in pixels.""" + size = size or SIZE + tail_a, ear_l, ear_r, blink, bob = D.motion(frame) + if sad: + tail_a, ear_l, ear_r = tail_a * 0.3, ear_l * 0.5, ear_r * 0.5 + if happy or mouth > 0.4: + blink = 1.0 + D.SIZE, D.W = size, size * D.S + cv = D.Canvas(sad) + head, body, _, height = D.LOOK["teen"] + head, body = head * 1.12, body * 1.12 + cx, bottom = 0.5, 0.93 + body_h = height + 0.10 + body_cy = bottom - body_h * 0.5 - 0.02 + head_cy = body_cy - body_h * 0.5 - head * 0.45 - bob + fx = cx + body + + # the tail: brown with a black tip, out to the side and curling back at the end + q = [D.rot(p, (fx - 0.02, body_cy + body_h * 0.3), tail_a) for p in + [(fx - 0.02, body_cy + body_h * 0.3), (fx + 0.36, body_cy + body_h * 0.55), (fx + 0.42, body_cy - body_h * 0.75), (fx + 0.12, body_cy - body_h * 0.72)]] + D.tube(cv, q[0], q[1], q[2], q[3], 0.075, 0.045, BROWN, tip=BLACK) + + # body: white, with a black and a brown patch + cv.ell(cx, body_cy, body, body_h * 0.5, WHITE_FUR) + patch(cv, (cx, body_cy, body, body_h * 0.5), [(cx - body * 0.75, body_cy - body_h * 0.35, body * 0.55, body_h * 0.42, BLACK), + (cx + body * 0.85, body_cy - body_h * 0.1, body * 0.5, body_h * 0.5, BROWN)]) + cv.ell(cx, body_cy + body_h * 0.1, body * 0.5, body_h * 0.3, WHITE_FUR, outline=False) + for sign in (-1, 1): + cv.ell(cx + sign * body * 0.52, bottom - 0.035, 0.07, 0.045, BROWN if sign > 0 else WHITE_FUR) + cv.ell(cx + sign * body * 0.52, bottom - 0.02, 0.045, 0.02, WHITE_FUR, outline=False) + for sign in (-1, 1): + cv.ell(cx + sign * (body + 0.012), body_cy - body_h * 0.05, 0.035, 0.07, BLACK if sign < 0 else WHITE_FUR) + collar(cv, cx, head_cy, head) + + # ears: one black, one brown + for sign in (-1, 1): + base = (cx + sign * head * 0.55, head_cy - head * 0.5) + a = ear_l if sign < 0 else ear_r + outer = [D.rot(p, base, a) for p in [(cx + sign * head * 0.28, head_cy - head * 0.7), (cx + sign * head * 0.98, head_cy - head * 1.12), + (cx + sign * head * 0.92, head_cy - head * 0.2)]] + inner = [D.rot(p, base, a) for p in [(cx + sign * head * 0.42, head_cy - head * 0.68), (cx + sign * head * 0.84, head_cy - head * 0.92), + (cx + sign * head * 0.8, head_cy - head * 0.38)]] + cv.poly(outer, BLACK if sign < 0 else BROWN) + cv.poly(inner, EAR_IN, outline=False) + + # head: white, a black patch over the left ear side and a brown one over the right, a white blaze between them + cv.ell(cx, head_cy, head * 1.05, head * 0.92, WHITE_FUR) + patch(cv, (cx, head_cy, head * 1.05, head * 0.92), [(cx - head * 0.78, head_cy - head * 0.52, head * 0.5, head * 0.46, BLACK), + (cx + head * 0.82, head_cy - head * 0.42, head * 0.46, head * 0.52, BROWN), + (cx + head * 0.95, head_cy + head * 0.12, head * 0.2, head * 0.2, BLACK)]) + cv.ell(cx, head_cy + head * 0.32, head * 0.55, head * 0.4, WHITE_FUR, outline=False) + D.face(cv, "cat", cx, head_cy + head * 0.02, head, sad, "cub", blink) + if mouth > 0: # an open mouth over the smile: the muzzle is repainted, then a dark mouth with a tongue + my = head_cy + head * 0.32 + cv.ell(cx, my + head * 0.02, head * 0.2, head * 0.1, WHITE_FUR, outline=False) + cv.ell(cx, my + head * 0.07, head * 0.085 * (0.6 + 0.7 * mouth), head * (0.035 + 0.1 * mouth), (96, 34, 52), width=0.007) + cv.ell(cx, my + head * (0.1 + 0.05 * mouth), head * 0.05 * (0.6 + 0.7 * mouth), head * (0.018 + 0.03 * mouth), (255, 120, 140), outline=False) + tag(cv, cx, head_cy + head * 1.03, head * 0.27) + return cv.img.resize((size, size), Image.LANCZOS) + + +def on(color, image): + base = Image.new("RGBA", image.size, color + (255,)) + base.alpha_composite(image) + return base.convert("RGB") + + +def main() -> None: + OUT.mkdir(parents=True, exist_ok=True) + glad, calm, grey = mascot(happy=True), mascot(frame=4), mascot(sad=True, frame=4) + glad.save(OUT / "mascot_happy.png") + calm.save(OUT / "mascot.png") + grey.save(OUT / "mascot_grey.png") + # the head with the collar and tag as a square picture for icons + face = calm.crop((140, 190, 900, 950)).resize((512, 512), Image.LANCZOS) + face.save(OUT / "mascot_icon_512.png") + face.resize((64, 64), Image.LANCZOS).save(OUT / "mascot_icon_64.png") + frames = [on((255, 255, 255), mascot(frame=f)).resize((384, 384), Image.LANCZOS).quantize(colors=96, method=Image.MEDIANCUT, dither=Image.Dither.NONE) for f in range(D.FRAMES)] + frames[0].save(OUT / "mascot_anim.gif", save_all=True, append_images=frames[1:], duration=83, loop=0, disposal=1) + sheet = Image.new("RGB", (3 * 520, 2 * 520 + 90), (255, 255, 255)) + for i, image in enumerate((calm, glad, grey)): + sheet.paste(on((255, 255, 255), image).resize((500, 500), Image.LANCZOS), (i * 520 + 10, 10)) + sheet.paste(on((20, 20, 24), image).resize((500, 500), Image.LANCZOS), (i * 520 + 10, 530)) + icon = Image.new("RGB", (3 * 520, 90), (244, 244, 246)) + for i, size in enumerate((256, 128, 64)): + icon.paste(on((244, 244, 246), face.resize((size, size), Image.LANCZOS)), (i * 520 + 20, 90 - min(size, 80) if size < 90 else 0)) + sheet.save(OUT / "sheet.png") + print(OUT / "sheet.png") + + +if __name__ == "__main__": + main() diff --git a/scripts/make_release_video.py b/scripts/make_release_video.py new file mode 100644 index 0000000..67af754 --- /dev/null +++ b/scripts/make_release_video.py @@ -0,0 +1,368 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +"A new version": the mascot (scripts/make_mascot.py) meows and the news appear next to it as subtitles, one line at a time. The same +scene for every release: give it the lines (a word between *stars* is highlighted) and it makes the video, with a meow on every line. + + py -X utf8 -B scripts/make_release_video.py # the lines below, 16:9 + py -X utf8 -B scripts/make_release_video.py --vertical # 9:16 + py -X utf8 -B scripts/make_release_video.py --title "alpha 2" --lines "Мяу!" "Вышла *alpha 2*" + py -X utf8 -B scripts/make_release_video.py --still 3.5 # one frame + +Everything is ours: the cat is drawn here, the meows are synthesized here (numpy), the music under them is work/music/store.mp3. +""" + +from __future__ import annotations + +import argparse +import math +import shutil +import subprocess +import sys +from functools import lru_cache +from multiprocessing import Pool +from pathlib import Path + +import numpy as np +from PIL import Image, ImageDraw, ImageFont +from scipy.signal import butter, sosfilt + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import make_mascot as MC # noqa: E402 +import make_store_music as M # noqa: E402 +import make_store_video as V # noqa: E402 +from make_store_video import INK, GREY, VIOLET, burst, card, clamp, font, in_out, lerp, out_back, out_cubic, put, put_c, rr, seg # noqa: E402 + +ROOT = Path(__file__).resolve().parents[1] +OUT = ROOT / "work" / "release-video" +SPRITES = OUT / "sprites" +FPS = 30 +SPRITE = 720 +MOUTHS = (0.0, 0.55, 1.0) +MEOW = 0.62 # how long one meow lasts +FIRST = 1.0 # the first line starts here +TITLE = "alpha 1" +LINES = [ + "Мяу! Вышла новая версия", + "LihonT 3 · Luna *alpha 1*", + "Теперь есть *блокировка* TikTok отпечатком", + "Можно закрыть *все чаты* или только выбранные", + "Журнал входов: кто пытался и его *фото*", + "Скачать на *lihont.space*", +] +W = H = 0 +VERT = False + + +def setup(vertical: bool) -> None: + global W, H, VERT + V.set_format(vertical) + W, H, VERT = V.W, V.H, bool(vertical) + + +# ---------------------------------------------------------------- the cat + +def prepare() -> None: + """Draws every picture of the cat once: 24 frames of the loop with the mouth shut, half open and open.""" + SPRITES.mkdir(parents=True, exist_ok=True) + for frame in range(24): + for level, mouth in enumerate(MOUTHS): + path = SPRITES / ("m_%02d_%d.png" % (frame, level)) + if not path.exists(): + MC.mascot(frame=frame, mouth=mouth, size=SPRITE).save(path) + + +@lru_cache(maxsize=80) +def sprite(frame: int, level: int) -> Image.Image: + return Image.open(SPRITES / ("m_%02d_%d.png" % (frame, level))).convert("RGBA") + + +@lru_cache(maxsize=4) +def shadow(width: int) -> Image.Image: + layer = Image.new("RGBA", (width + 80, width // 4 + 80), (0, 0, 0, 0)) + ImageDraw.Draw(layer).ellipse([40, 40, width + 40, width // 4 + 40], fill=(30, 20, 50, 55)) + from PIL import ImageFilter + return layer.filter(ImageFilter.GaussianBlur(16)) + + +# ---------------------------------------------------------------- the lines + +def parse(line: str) -> list[tuple[str, bool]]: + """Words with a flag: the ones between stars are highlighted.""" + words, on = [], False + for chunk in line.split("*"): + for word in chunk.split(): + words.append((word, on)) + on = not on + return words + + +def wrap(words, size: int, width: int): + f = font(size, "bold") + space = f.getlength(" ") + rows, row, run = [], [], 0.0 + for word, mark in words: + w = f.getlength(word) + if row and run + space + w > width: + rows.append(row) + row, run = [], 0.0 + run += (space if row else 0) + w + row.append((word, mark, w)) + if row: + rows.append(row) + return rows, f + + +GAP = 0.74 # from the start of one meow to the start of the next + + +def meows_in(line: str) -> int: + """How many times the cat meows on a line: two, and three on a long one.""" + return 3 if len(line.replace("*", "")) > 28 else 2 + + +def hold(line: str) -> float: + n = meows_in(line) + return max(2.4, 0.9 + 0.07 * len(line.replace("*", "")), GAP * (n - 1) + MEOW + 1.0) + + +def starts(lines) -> list[float]: + """When each line starts: long ones, and ones with more meows, are kept on the screen a little longer.""" + out, t = [], FIRST + for line in lines: + out.append(t) + t += hold(line) + out.append(t) + return out + + +def meow_times(lines) -> list[tuple[float, int, int]]: + """Every meow: (when, which one of the line, how many on the line).""" + s = starts(lines) + out = [] + for i, line in enumerate(lines): + n = meows_in(line) + for k in range(n): + out.append((s[i] + k * GAP, k, n)) + return out + + +def total(lines) -> float: + return starts(lines)[-1] + 1.6 + + +# ---------------------------------------------------------------- the picture + +def cat_geometry(): + if VERT: + return W // 2, 600, 760 + return 470, 590, 700 + + +def draw_cat(img, t, lines): + s = starts(lines) + cx, cy, size = cat_geometry() + # which meow is going on, and how open the mouth is + open_ = 0.0 + for t0, _, _ in meow_times(lines): + if t0 <= t < t0 + MEOW: + open_ = math.sin(math.pi * (t - t0) / MEOW) ** 0.7 + level = 0 if open_ < 0.2 else 1 if open_ < 0.65 else 2 + pop = out_back(seg(t, 0.15, 0.85), 1.6) + scale = size / SPRITE * pop * (1 + 0.035 * open_) + bob = -10 * open_ + put_c(img, shadow(380), cx, cy + size * 0.43, scale * 1.0, clamp(pop) * 0.9) + put_c(img, sprite(int(t * 12) % 24, level), cx, cy + bob, scale, clamp(pop * 1.5)) + + +def draw_title(img, t, lines): + """The name of the version over the cat: glossy letters that pop in once the first meow is over.""" + a = FIRST + GAP + MEOW + 0.2 + if t < a: + return + fade = 1.0 + cx = W // 2 + y = 215 if VERT else 190 + V.candy_text(img, cx, y, TITLE.upper(), 120 if VERT else 96, t, a, 0.07, alpha=fade) + put_text = V.text + put_text(img, (cx, y - (105 if VERT else 90)), "новая версия LihonT", 40 if VERT else 34, "semi", GREY, "mm", alpha=out_cubic(seg(t, a, a + 0.4))) + + +def draw_subtitle(img, t, lines): + s = starts(lines) + index = max([i for i in range(len(lines)) if t >= s[i]], default=-1) + if index < 0: + return + line, t0 = lines[index], s[index] + words = parse(line) + box_w = 940 if VERT else 900 + size = 76 if VERT else 74 + rows, f = wrap(words, size, box_w - 100) + while len(rows) > 4 and size > 44: + size -= 6 + rows, f = wrap(words, size, box_w - 100) + lh = int(size * 1.28) + box_h = len(rows) * lh + 80 + come = out_back(seg(t, t0, t0 + 0.35), 1.3) + last = index == len(lines) - 1 + leave = 0.0 if last else seg(t, s[index + 1] - 0.18, s[index + 1]) + alpha = clamp(come * 1.4) * (1 - leave) + if VERT: + bx, by = W // 2, 1290 + box_h // 2 - 120 + else: + bx, by = 1330, H // 2 + 40 + layer = card(box_w, box_h, 44, (255, 255, 255), blur=40, dy=18, alpha=52).copy() # the card is cached: it must not be drawn on + pad = 80 + # the little tail of the speech card points at the cat + d = ImageDraw.Draw(layer) + if VERT: + d.polygon([(layer.width // 2 - 34 - 160, pad + 4), (layer.width // 2 + 34 - 160, pad + 4), (layer.width // 2 - 160, pad - 40)], fill=(255, 255, 255, 255)) + else: + d.polygon([(pad + 4, layer.height // 2 - 34), (pad + 4, layer.height // 2 + 34), (pad - 44, layer.height // 2)], fill=(255, 255, 255, 255)) + # the words appear one after another + total_words = sum(len(r) for r in rows) + reveal = min(0.8, 0.13 * total_words) + k = 0 + y = pad + 40 + lh // 2 - 4 + for row in rows: + row_w = sum(w for _, _, w in row) + f.getlength(" ") * (len(row) - 1) + x = (layer.width - row_w) / 2 + for word, mark, w in row: + at = t0 + 0.12 + reveal * k / max(1, total_words) + age = t - at + if age > 0: + lift = (1 - out_cubic(clamp(age / 0.18))) * 14 + ink = VIOLET if mark else INK + ImageDraw.Draw(layer).text((x + w / 2, y + lift), word, font=f, fill=ink + (int(255 * clamp(age / 0.12)),), anchor="mm") + x += w + f.getlength(" ") + k += 1 + y += lh + put_c(img, layer, bx, by, lerp(0.92, 1.0, come), alpha) + if last and t > t0 + 0.9: + burst(img, bx, by - 30, t, t0 + 0.9, seed=4, n=46, power=640, life=1.3) + + +def frame_at(t: float, lines) -> Image.Image: + img = Image.new("RGBA", (W, H), (255, 255, 255, 255)) + draw_cat(img, t, lines) + draw_title(img, t, lines) + draw_subtitle(img, t, lines) + fade_in = clamp(t / 0.25) + if fade_in < 1: + img.alpha_composite(Image.new("RGBA", (W, H), (255, 255, 255, int(255 * (1 - fade_in))))) + return img + + +# ---------------------------------------------------------------- the sound + +def lowpass_band(x, lo, hi): + return sosfilt(butter(2, [lo, hi], "band", fs=M.SR, output="sos"), x) + + +def meow(base=560.0, d=MEOW, seed=0): + """A cat's "мя-а-у": the pitch climbs and falls, the vowel moves from "и" through "а" to "у", with a little breath and vibrato.""" + rng = np.random.default_rng(seed) + t = M.tt(d) + x = np.clip(t / d, 0, 1) + f = base * (0.78 + 0.62 * np.sin(np.pi * np.clip(x * 1.15, 0, 1)) ** 0.9 - 0.2 * x) * (1 + 0.012 * np.sin(2 * math.pi * 6.5 * t)) + phase = 2 * math.pi * np.cumsum(f) / M.SR + source = sum(np.sin(k * phase) / k ** 1.05 for k in range(1, 16)) + low = lowpass_band(source, 300, 700) # "у" + mid = lowpass_band(source, 700, 1500) # "а" + high = lowpass_band(source, 1700, 3200) # "и" + w_i = np.clip(1.4 - 3.2 * x, 0, 1) ** 1.2 + w_a = np.sin(np.pi * np.clip(x * 1.1, 0, 1)) ** 1.4 + w_u = np.clip(3.0 * (x - 0.55), 0, 1) + voice = low * (0.4 + w_u * 1.1) + mid * (0.25 + w_a * 1.0) + high * (0.15 + w_i * 0.9) + breath = lowpass_band(rng.standard_normal(len(t)), 2500, 7000) * 0.02 * np.sin(np.pi * x) + envelope = np.minimum(1, t / 0.025) * np.clip((d - t) / 0.16, 0, 1) ** 1.3 * (0.85 + 0.15 * np.sin(np.pi * x)) + return (voice + breath) * envelope * 0.55 + + +def soundtrack(lines, duration: float, path: Path) -> None: + mix = M.Mix(duration + 0.5) + s = starts(lines) + for i, (t0, k, n) in enumerate(meow_times(lines)): + # each meow of a line a little different: the first is the brightest, the last the lowest and longest + base = [560.0, 610.0, 520.0, 590.0, 640.0][i % 5] * (1.0 - 0.07 * k) + length = MEOW * (1.12 if k == n - 1 and n > 1 else 1.0) + mix.add(meow(base, length, seed=i), t0, 0.9, pan=-0.2 + 0.1 * (k % 2), send=0.1) + if k == 0: + mix.add(M.pop(900, 300, 0.1), t0 + 0.18, 0.18, pan=0.2) + title_at = FIRST + GAP + MEOW + 0.2 + mix.add(M.bell(M.midi(88), 1.4), title_at, 0.28, send=0.4) + mix.add(M.sparkle(1.2, 8, 86, 1), title_at + 0.1, 0.4, send=0.4) + end = s[-2] + mix.add(M.sparkle(1.6, 12, 84, 2), end + 0.9, 0.55, send=0.4) + mix.add(M.bell(M.midi(93), 1.8), end + 0.9, 0.3, send=0.5) + data = np.stack([mix.left, mix.right], axis=1)[: int((duration + 0.5) * M.SR)] + data = np.tanh(data * 1.1) + data /= max(1e-9, np.abs(data).max()) / 0.85 + M.write(path, data.astype(np.float32)) + + +# ---------------------------------------------------------------- the video + +_LINES: list = [] + + +def _init(vertical: bool, lines) -> None: + global _LINES + setup(vertical) + _LINES = lines + + +def render_frame(index: int) -> bytes: + return frame_at(index / FPS, _LINES).convert("RGB").tobytes() + + +def main() -> None: + global TITLE + parser = argparse.ArgumentParser() + parser.add_argument("--title", default=TITLE, help="the name of the version, shown in big letters") + parser.add_argument("--lines", nargs="+", default=LINES) + parser.add_argument("--vertical", action="store_true") + parser.add_argument("--still", type=float, nargs="*") + parser.add_argument("--no-music", action="store_true") + parser.add_argument("--jobs", type=int, default=6) + args = parser.parse_args() + TITLE = args.title + setup(args.vertical) + OUT.mkdir(parents=True, exist_ok=True) + prepare() + lines = list(args.lines) + duration = total(lines) + tag = "_9x16" if args.vertical else "" + if args.still: + for t in args.still: + path = OUT / ("still%s_%05.2f.png" % (tag, t)) + frame_at(t, lines).convert("RGB").save(path) + print(path) + return + wav = OUT / "meows.wav" + soundtrack(lines, duration, wav) + out = OUT / ("release%s.mp4" % tag) + music = ROOT / "work" / "music" / "store.mp3" + command = [shutil.which("ffmpeg") or "ffmpeg", "-y", "-loglevel", "error", "-f", "rawvideo", "-pix_fmt", "rgb24", "-s", "%dx%d" % (W, H), + "-r", str(FPS), "-i", "-", "-i", str(wav)] + if args.no_music or not music.is_file(): + command += ["-af", "afade=t=out:st=%.2f:d=0.6" % (duration - 0.6)] + else: + command += ["-i", str(music), "-filter_complex", + "[2:a]volume=0.2,afade=t=in:st=0:d=0.8,afade=t=out:st=%.2f:d=1.0[b];[1:a][b]amix=inputs=2:duration=first:normalize=0," + "afade=t=out:st=%.2f:d=0.6[a]" % (duration - 1.0, duration - 0.6), "-map", "0:v", "-map", "[a]"] + command += ["-c:v", "libx264", "-preset", "medium", "-crf", "17", "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "192k", "-t", "%.2f" % duration, str(out)] + proc = subprocess.Popen(command, stdin=subprocess.PIPE) + frames = int(round(duration * FPS)) + with Pool(args.jobs, initializer=_init, initargs=(args.vertical, lines)) as pool: + for n, data in enumerate(pool.imap(render_frame, range(frames), chunksize=4)): + proc.stdin.write(data) + if n % 60 == 0: + print("frame %d/%d" % (n, frames), flush=True) + proc.stdin.close() + proc.wait() + print("done:", out) + + +if __name__ == "__main__": + main() diff --git a/scripts/make_thief_video.py b/scripts/make_thief_video.py new file mode 100644 index 0000000..976c6b2 --- /dev/null +++ b/scripts/make_thief_video.py @@ -0,0 +1,700 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +The promo skit for the lock of LihonT 3 · Luna alpha 1: at night a thief takes a phone and cannot open it (the front camera clicks), in the +morning the owner opens the phone with his finger and finds the thief's picture in the journal of entries, then the calico cat (the mascot, +scripts/make_release_video.py) tells about the update and where to get it. Everyone in it is drawn here: no real person, no real picture. + + py -X utf8 -B scripts/make_thief_video.py # work/thief-video/thief.mp4 (16:9) + py -X utf8 -B scripts/make_thief_video.py --vertical # 9:16 + py -X utf8 -B scripts/make_thief_video.py --still 4.0 # one frame +""" + +from __future__ import annotations + +import argparse +import math +import shutil +import subprocess +import sys +from functools import lru_cache +from multiprocessing import Pool +from pathlib import Path + +import numpy as np +from PIL import Image, ImageChops, ImageDraw, ImageFilter + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import make_release_video as R # noqa: E402 +import make_store_music as M # noqa: E402 +import make_store_video as V # noqa: E402 +from make_store_video import INK, clamp, font, in_out, lerp, out_back, out_cubic, put_c, seg # noqa: E402 + +ROOT = Path(__file__).resolve().parents[1] +OUT = ROOT / "work" / "thief-video" +FPS = 30 +SS = 2 +W = H = 0 +VERT = False + +# the timeline (seconds) +T_DAY = 7.6 # the morning begins +T_CAT = 15.6 # the cat scene takes over (its own clock starts a quarter of a second earlier: no fade-in) +CAT_OFFSET = T_CAT - 0.25 +CAT_LINES = [ + "Мяу! Вышла *alpha 1*", + "Блокировка, *фото вора* и журнал входов", + "Всё остаётся только на твоём телефоне", + "Скачать: *lihont.space* и Telegram *@lihont*", +] + +SKIN = (244, 200, 160) +SKIN_DARK = (226, 170, 130) +DARK = (46, 52, 78) +DARKER = (30, 34, 54) +BEANIE = (38, 38, 46) +RED = (214, 60, 70) + + +def setup(vertical: bool) -> None: + global W, H, VERT + R.setup(vertical) + W, H, VERT = V.W, V.H, bool(vertical) + R.TITLE = "alpha 1" + + +HALF = 374 # half the width of the phone picture, at scale 1 + + +def layout() -> dict: + """Where things stand: the phone, the table, the people.""" + if VERT: + return dict(phone=(W // 2, 1160), table=1470, feet=1580, thief_x=190, guy_x=W - 190, person=0.8, base=0.5, zoom=1.3) + return dict(phone=(W // 2, 620), table=930, feet=990, thief_x=W // 2 - 430, guy_x=W // 2 + 430, person=0.95, base=0.5, zoom=0.76) + + +# ---------------------------------------------------------------- small drawing helpers (all at SS times the size) + +def draw_geom(d, kind, g, fill, grow=0, sx=0.0, sy=0.0): + k = SS + if kind == "ell": + cx, cy, rx, ry = g + d.ellipse([(cx + sx - rx - grow) * k, (cy + sy - ry - grow) * k, (cx + sx + rx + grow) * k, (cy + sy + ry + grow) * k], fill=fill) + elif kind == "rr": + x0, y0, x1, y1, r = g + d.rounded_rectangle([(x0 + sx - grow) * k, (y0 + sy - grow) * k, (x1 + sx + grow) * k, (y1 + sy + grow) * k], radius=(r + grow) * k, fill=fill) + elif kind == "poly": + if len(g) == 1 and isinstance(g[0], list): + g = g[0] + pts = [((x + sx) * k, (y + sy) * k) for x, y in g] + d.polygon(pts, fill=fill) + if grow: + d.line(pts + [pts[0]], fill=fill, width=int(2 * grow * k), joint="curve") + elif kind == "line": + p0, p1, w = g + ww = (w + 2 * grow) * k + d.line([((p0[0] + sx) * k, (p0[1] + sy) * k), ((p1[0] + sx) * k, (p1[1] + sy) * k)], fill=fill, width=int(ww)) + for pt in (p0, p1): + r = ww / 2 + d.ellipse([(pt[0] + sx) * k - r, (pt[1] + sy) * k - r, (pt[0] + sx) * k + r, (pt[1] + sy) * k + r], fill=fill) + + +def mask_of(img, kind, g, grow=0, sx=0.0, sy=0.0): + m = Image.new("L", img.size, 0) + draw_geom(ImageDraw.Draw(m), kind, g, 255, grow, sx, sy) + return m + + +def S(img, kind, g, fill, ow=7, shade=True, light=(-10, -13), dark=0.72, hl=None): + """One shape of a character: an ink outline, a darker colour, the real colour on the lit side (cel shading) and, if asked, a shine.""" + d = ImageDraw.Draw(img) + if ow: + draw_geom(d, kind, g, INK + (255,), grow=ow) + base = mask_of(img, kind, g) + shadow = tuple(int(c * dark) for c in fill) + img.paste(shadow + (255,), mask=base) if shade else img.paste(tuple(fill) + (255,), mask=base) + if shade: + lit = ImageChops.darker(base, mask_of(img, kind, g, 0, light[0], light[1])) + img.paste(tuple(fill) + (255,), mask=lit) + if hl: + cx, cy, rx, ry = hl + shine = Image.new("L", img.size, 0) + ImageDraw.Draw(shine).ellipse([(cx - rx) * SS, (cy - ry) * SS, (cx + rx) * SS, (cy + ry) * SS], fill=95) + img.paste((255, 255, 255, 255), mask=ImageChops.darker(shine, base)) + + +def eye(img, cx, cy, mood, look, blink, iris=(96, 62, 40), narrow=False): + d = ImageDraw.Draw(img) + if blink: + d.arc([(cx - 22) * SS, (cy - 14) * SS, (cx + 22) * SS, (cy + 14) * SS], 200, 340, fill=INK + (255,), width=6 * SS) + return + rx, ry = (21, 12) if narrow else ((27, 29) if mood == "shock" else (22, 22)) + S(img, "ell", (cx, cy, rx, ry), (255, 255, 255), ow=5, shade=False) + ix, iy = cx + look[0] * 6, cy + look[1] * 4 + ir = 9 if mood == "shock" else (8 if narrow else 12) + S(img, "ell", (ix, iy, ir, ir), iris, ow=0, shade=False) + S(img, "ell", (ix, iy, ir * 0.55, ir * 0.55), (20, 14, 14), ow=0, shade=False) + d.ellipse([(ix - ir * 0.5 - 3) * SS, (iy - ir * 0.6 - 3) * SS, (ix - ir * 0.5 + 3) * SS, (iy - ir * 0.6 + 3) * SS], fill=(255, 255, 255, 255)) + + +def person(kind: str, step: float = 0.0, arm=None, mood: str = "calm", look=(1, 0), size: float = 1.0, blink: bool = False) -> Image.Image: + """A character 400x700 big (before `size`), feet at the bottom middle. `arm` is where the near hand reaches, in the same units.""" + img = Image.new("RGBA", (400 * SS, 700 * SS), (0, 0, 0, 0)) + d = ImageDraw.Draw(img) + thief = kind == "thief" + skin = SKIN if thief else (238, 190, 150) + skin_shadow = SKIN_DARK + # legs with a swing + for side, phase in ((-1, 0.0), (1, math.pi)): + swing = math.sin(step + phase) + lift = max(0.0, math.cos(step + phase)) * 16 if abs(step) > 0 else 0.0 + x = 200 + side * 42 + swing * 20 + S(img, "line", ((200 + side * 42, 520), (x, 662 - lift), 56), (36, 36, 46) if thief else (70, 98, 168), ow=7) + S(img, "ell", (x + 12, 674 - lift, 42, 18), (30, 30, 36) if thief else (170, 112, 66), ow=6) + if thief: # the sack over the shoulder + S(img, "ell", (92, 410, 64, 80), (172, 126, 80), ow=7, hl=(70, 372, 20, 26)) + S(img, "poly", ([(76, 336), (108, 336), (122, 308), (98, 322), (70, 304)], ), (172, 126, 80), ow=6) if False else None + d.text((92 * SS, 410 * SS), "$", font=font(76 * SS, "black"), fill=(255, 238, 170, 255), anchor="mm") + # body + if thief: + S(img, "rr", (100, 292, 300, 562, 60), (250, 250, 252), ow=7) + stripes = Image.new("L", img.size, 0) + sd = ImageDraw.Draw(stripes) + for k in range(8): + y0 = 300 + k * 34 + sd.rectangle([90 * SS, y0 * SS, 310 * SS, (y0 + 16) * SS], fill=255) + img.paste(INK + (255,), mask=ImageChops.darker(stripes, mask_of(img, "rr", (100, 292, 300, 562, 60)))) + S(img, "rr", (100, 292, 300, 562, 60), (0, 0, 0), ow=0, shade=False) if False else None + else: + S(img, "rr", (94, 296, 306, 566, 80), (248, 248, 250), ow=7) + S(img, "ell", (200, 478, 112, 96), (248, 248, 250), ow=0, hl=(160, 430, 24, 34)) + # the V of the vest and some chest hair + d.polygon([(168 * SS, 296 * SS), (232 * SS, 296 * SS), (200 * SS, 368 * SS)], fill=skin + (255,)) + for k in range(6): + d.line([((186 + k * 5) * SS, (306 + (k % 3) * 8) * SS), ((190 + k * 5) * SS, (318 + (k % 3) * 8) * SS)], fill=(88, 60, 44, 255), width=3 * SS) + S(img, "rr", (92, 518, 308, 586, 30), (70, 98, 168), ow=7) # the trousers + d.rectangle([92 * SS, 540 * SS, 308 * SS, 552 * SS], fill=(40, 40, 54, 255)) + S(img, "rr", (180, 536, 220, 556, 5), (232, 190, 80), ow=3, shade=False) # the buckle + # arms + sleeve = (62, 62, 74) if thief else skin + glove = (30, 30, 36) if thief else skin + S(img, "line", ((112, 340), (82, 478), 46), sleeve, ow=7) + S(img, "ell", (82, 494, 25, 25), glove, ow=6) + if arm is None: + S(img, "line", ((288, 340), (318, 478), 46), sleeve, ow=7) + S(img, "ell", (318, 494, 25, 25), glove, ow=6) + else: + S(img, "line", ((288, 340), arm, 46), sleeve, ow=7) + S(img, "ell", (arm[0], arm[1], 26, 26), glove, ow=6) + if not thief: + S(img, "ell", (arm[0] - 16, arm[1] - 14, 10, 12), glove, ow=4, shade=False) # a thumb + # the head + if thief: + S(img, "ell", (200, 222, 118, 108), (38, 38, 46), ow=7) # the hood behind + for sign in (-1, 1): + S(img, "ell", (200 + sign * 100, 224, 17, 25), skin, ow=6) # the ears + S(img, "ell", (200, 214, 98, 96), skin, ow=7, hl=(165, 170, 22, 30)) + S(img, "poly", ([(102, 190), (110, 150), (200, 112), (290, 150), (298, 190), (270, 168), (200, 156), (130, 168)], ), BEANIE, ow=6) + S(img, "rr", (102, 166, 298, 204, 18), (84, 86, 98), ow=6) # the folded edge + S(img, "rr", (110, 206, 290, 254, 22), (24, 24, 30), ow=6, shade=False) # the mask + eye(img, 158, 230, mood, look, blink, iris=(110, 86, 60), narrow=True) + eye(img, 242, 230, mood, look, blink, iris=(110, 86, 60), narrow=True) + if mood == "angry": + d.line([(124 * SS, 198 * SS), (178 * SS, 214 * SS)], fill=INK + (255,), width=9 * SS) + d.line([(276 * SS, 198 * SS), (222 * SS, 214 * SS)], fill=INK + (255,), width=9 * SS) + S(img, "ell", (200, 262, 12, 10), skin_shadow, ow=4, shade=False) # the nose + if mood == "angry": + d.arc([(168) * SS, (288) * SS, (232) * SS, (322) * SS], 200, 340, fill=INK + (255,), width=7 * SS) + else: + d.line([(170 * SS, 296 * SS), (230 * SS, 292 * SS)], fill=INK + (255,), width=7 * SS) + for k in range(8): + d.ellipse([(144 + k * 14) * SS, (276 + (k % 2) * 9) * SS, (147 + k * 14) * SS, (279 + (k % 2) * 9) * SS], fill=(96, 74, 64, 255)) + else: + S(img, "ell", (200, 228, 108, 100), (138, 120, 104), ow=7) # the hair that is left: round the back and the sides, none on top + for sign in (-1, 1): + S(img, "ell", (200 + sign * 99, 228, 17, 25), skin, ow=6) # the ears + S(img, "ell", (200, 206, 98, 96), skin, ow=7, hl=(160, 140, 30, 22)) + eye(img, 158, 210, mood, look, blink) + eye(img, 242, 210, mood, look, blink) + for sign in (-1, 1): + up = -18 if mood == "shock" else 0 + S(img, "line", ((200 + sign * 74, 176 + up), (200 + sign * 26, 168 + up + sign * 5), 12), (78, 56, 44), ow=0, shade=False) + S(img, "ell", (200, 246, 19, 21), (232, 156, 124), ow=5, hl=(194, 238, 6, 5)) # a big, red nose + S(img, "ell", (166, 278, 44, 16), (92, 58, 40), ow=0, shade=False) # the moustache with curled ends + S(img, "ell", (234, 278, 44, 16), (92, 58, 40), ow=0, shade=False) + S(img, "ell", (126, 270, 12, 10), (92, 58, 40), ow=0, shade=False) + S(img, "ell", (274, 270, 12, 10), (92, 58, 40), ow=0, shade=False) + for k in range(9): # stubble + d.ellipse([(140 + k * 15) * SS, (298 + (k % 2) * 10) * SS, (143 + k * 15) * SS, (301 + (k % 2) * 10) * SS], fill=(112, 88, 72, 255)) + if mood == "shock": + S(img, "ell", (200, 312, 17, 22), (110, 40, 52), ow=5, shade=False) + else: + d.arc([160 * SS, 290 * SS, 240 * SS, 330 * SS], 20, 160, fill=INK + (255,), width=6 * SS) + return img.resize((int(400 * size), int(700 * size)), Image.LANCZOS) + + +@lru_cache(maxsize=8) +def face_photo(kind: str, side: int) -> Image.Image: + """The picture the front camera took: the head and shoulders, on a dim background, a little grainy.""" + base = person(kind, 0.0, None, "angry" if kind == "thief" else "calm", size=1.0, blink=False) + head = base.crop((60, 70, 340, 360)).resize((side, int(side * 290 / 280)), Image.LANCZOS) + bg = Image.new("RGBA", (side, side), (38, 44, 64, 255)) + glow = Image.new("RGBA", (side, side), (0, 0, 0, 0)) + ImageDraw.Draw(glow).ellipse([side * 0.1, side * 0.05, side * 0.9, side * 0.95], fill=(120, 150, 210, 70)) + bg.alpha_composite(glow.filter(ImageFilter.GaussianBlur(side * 0.08))) + bg.alpha_composite(head, (0, side // 12)) + noise = np.random.default_rng(3).integers(-14, 14, (side, side, 1)).astype(np.int16) + arr = np.clip(np.asarray(bg.convert("RGB")).astype(np.int16) + noise, 0, 255).astype(np.uint8) + return Image.fromarray(arr).convert("RGBA") + + +# ---------------------------------------------------------------- the phone + +SCREEN_W, SCREEN_H = 600, 1140 + + +def fingerprint(d, cx, cy, r, color, width=7): + for k, f in enumerate((0.42, 0.62, 0.82, 1.0)): + rr_ = r * f + d.arc([cx - rr_, cy - rr_ * 1.15, cx + rr_, cy + rr_ * 1.15], 205 + k * 4, 335 - k * 4, fill=color, width=width) + d.arc([cx - rr_, cy - rr_ * 1.15, cx + rr_, cy + rr_ * 1.15], 20, 160 - k * 6, fill=color, width=width) + d.line([(cx, cy - r * 0.12), (cx, cy + r * 0.5)], fill=color, width=width) + + +def screen_lock(phase: float, state: str) -> Image.Image: + """The cover of the lock with the phone's own unlock sheet: waiting, wrong finger (red), right finger (green).""" + img = Image.new("RGBA", (SCREEN_W, SCREEN_H), (13, 13, 15, 255)) + d = ImageDraw.Draw(img) + # the padlock + gold, gold_dark = (238, 190, 107), (214, 150, 52) + cx, cy = SCREEN_W // 2, 300 + d.arc([cx - 70, cy - 150, cx + 70, cy + 10], 180, 360, fill=gold_dark, width=26) + d.line([(cx - 70, cy - 70), (cx - 70, cy - 20)], fill=gold_dark, width=26) + d.line([(cx + 70, cy - 70), (cx + 70, cy - 20)], fill=gold_dark, width=26) + d.rounded_rectangle([cx - 105, cy - 30, cx + 105, cy + 120], radius=34, fill=gold) + d.ellipse([cx - 18, cy + 18, cx + 18, cy + 54], fill=(92, 28, 40)) + d.rectangle([cx - 8, cy + 40, cx + 8, cy + 90], fill=(92, 28, 40)) + d.text((cx, 520), "LihonT: TikTok закрыт", font=font(40, "bold"), fill=(245, 245, 247), anchor="mm") + d.text((cx, 580), "Откройте отпечатком", font=font(28, "reg"), fill=(160, 160, 168), anchor="mm") + # the unlock sheet of the phone at the bottom + d.rounded_rectangle([20, 700, SCREEN_W - 20, SCREEN_H - 20], radius=44, fill=(36, 36, 42)) + d.text((cx, 770), "Подтвердите, что это вы", font=font(30, "semi"), fill=(240, 240, 244), anchor="mm") + color = {"wait": (150, 190, 255), "wrong": (255, 90, 100), "right": (90, 220, 140)}[state] + pulse = 1.0 + 0.05 * math.sin(phase * 6) if state == "wait" else 1.0 + fingerprint(d, cx, 930, 92 * pulse, color, 8) + msg = {"wait": "Приложите палец", "wrong": "Не распознано. Ещё раз", "right": "Готово"}[state] + d.text((cx, 1065), msg, font=font(26, "reg"), fill=color, anchor="mm") + return img + + +def screen_journal(highlight: float) -> Image.Image: + """Settings → Privacy → Journal of entries: the newest entry (the night one) with the thief's picture, an older one with the owner's.""" + img = Image.new("RGBA", (SCREEN_W, SCREEN_H), (255, 255, 255, 255)) + d = ImageDraw.Draw(img) + d.rectangle([0, 0, SCREEN_W, 120], fill=(244, 244, 246)) + d.text((40, 70), "←", font=font(44, "bold"), fill=(13, 13, 15), anchor="lm") + d.text((110, 70), "Журнал входов", font=font(38, "bold"), fill=(13, 13, 15), anchor="lm") + rows = [("12 ноя, 03:12 · Не открыто", "Весь TikTok", "Неверных попыток: 2", "thief"), ("11 ноя, 22:40 · Открыто", "Весь TikTok", "Открывал чаты: Аня", "guy")] + y = 150 + for i, (title, lock, extra, kind) in enumerate(rows): + h = 250 + if i == 0 and highlight > 0: + d.rounded_rectangle([14, y - 8, SCREEN_W - 14, y + h - 12], radius=30, fill=(255, 238, 240), outline=(255, 99, 150), width=int(2 + 5 * highlight)) + photo = face_photo(kind, 190) + mask = Image.new("L", photo.size, 0) + ImageDraw.Draw(mask).rounded_rectangle([0, 0, photo.width, photo.height], radius=24, fill=255) + img.paste(photo, (36, y + 14), mask) + d.text((250, y + 48), title.split(" · ")[0], font=font(30, "bold"), fill=(13, 13, 15), anchor="lm") + color = (214, 60, 70) if kind == "thief" else (40, 140, 80) + d.text((250, y + 94), title.split(" · ")[1], font=font(30, "bold"), fill=color, anchor="lm") + d.text((250, y + 138), lock, font=font(26, "reg"), fill=(107, 107, 115), anchor="lm") + d.text((250, y + 176), extra, font=font(26, "reg"), fill=(107, 107, 115), anchor="lm") + y += h + 12 + d.rounded_rectangle([40, SCREEN_H - 150, SCREEN_W - 40, SCREEN_H - 70], radius=40, fill=(244, 244, 246)) + d.text((SCREEN_W // 2, SCREEN_H - 110), "Очистить всё", font=font(30, "semi"), fill=(13, 13, 15), anchor="mm") + return img + + +@lru_cache(maxsize=64) +def phone(screen_key: tuple, camera: bool) -> Image.Image: + kind = screen_key[0] + screen = screen_lock(screen_key[1] / 10.0, screen_key[2]) if kind == "lock" else screen_journal(screen_key[1] / 10.0) + pad = 34 + w, h = SCREEN_W + 2 * pad, SCREEN_H + 2 * pad + 20 + out = Image.new("RGBA", (w + 80, h + 80), (0, 0, 0, 0)) + d = ImageDraw.Draw(out) + d.rounded_rectangle([40 - 9, 40 - 9, 40 + w + 9, 40 + h + 9], radius=86, fill=INK + (255,)) + d.rounded_rectangle([40, 40, 40 + w, 40 + h], radius=77, fill=(58, 60, 72, 255)) # the metal frame + d.rounded_rectangle([46, 46, 40 + w - 6, 40 + h - 6], radius=72, fill=(20, 20, 26, 255)) # the glass + d.arc([46, 46, 46 + 160, 46 + 160], 180, 270, fill=(160, 166, 190, 255), width=4) # a catch of light on the frame + for yy in (260, 340): # the buttons on the side + d.rounded_rectangle([40 + w - 2, yy, 40 + w + 8, yy + 60], radius=4, fill=INK + (255,)) + mask = Image.new("L", screen.size, 0) + ImageDraw.Draw(mask).rounded_rectangle([0, 0, screen.width, screen.height], radius=52, fill=255) + out.paste(screen, (40 + pad, 40 + pad + 10), mask) + # the reflection of the room on the glass + shine = Image.new("RGBA", out.size, (0, 0, 0, 0)) + ImageDraw.Draw(shine).polygon([(40 + pad, 40 + pad + 10), (40 + pad + 330, 40 + pad + 10), (40 + pad, 40 + pad + 640)], fill=(255, 255, 255, 22)) + sm = Image.new("L", out.size, 0) + sm.paste(mask, (40 + pad, 40 + pad + 10)) + shine.putalpha(ImageChops.multiply(shine.getchannel("A"), sm)) + out.alpha_composite(shine) + lens = (60, 230, 120) if camera else (40, 44, 58) + d.ellipse([40 + w // 2 - 15, 40 + 12, 40 + w // 2 + 15, 40 + 42], fill=(10, 10, 14, 255)) + d.ellipse([40 + w // 2 - 9, 40 + 18, 40 + w // 2 + 9, 40 + 36], fill=lens + (255,)) + return out + + +# ---------------------------------------------------------------- the scenes + +def gradient(top, bottom) -> Image.Image: + arr = np.zeros((H, W, 3), np.uint8) + for c in range(3): + arr[:, :, c] = np.linspace(top[c], bottom[c], H).astype(np.uint8)[:, None] + return Image.fromarray(arr).convert("RGBA") + + +@lru_cache(maxsize=2) +def room(night: bool) -> Image.Image: + lay = layout() + img = gradient((14, 18, 42), (30, 38, 72)) if night else gradient((255, 248, 232), (250, 226, 196)) + d = ImageDraw.Draw(img) + # wallpaper: soft vertical stripes + for x in range(0, W, 90): + d.rectangle([x, 0, x + 38, lay["table"] + 70], fill=(255, 255, 255, 3) if night else (255, 255, 255, 7)) + wx, wy, ww, wh = (W // 2 - 280, 80, 560, 500) if not VERT else (W // 2 - 300, 110, 600, 560) + # the window + d.rounded_rectangle([wx - 16, wy - 16, wx + ww + 16, wy + wh + 16], radius=28, fill=INK + (255,)) + sky = (14, 20, 54) if night else (176, 222, 255) + d.rounded_rectangle([wx, wy, wx + ww, wy + wh], radius=18, fill=sky + (255,)) + if night: + rng = np.random.default_rng(5) + for _ in range(34): + sx, sy = wx + int(rng.uniform(20, ww - 20)), wy + int(rng.uniform(20, wh * 0.8)) + r = int(rng.choice([2, 3, 4])) + d.ellipse([sx - r, sy - r, sx + r, sy + r], fill=(240, 240, 255, 255)) + d.ellipse([wx + ww - 200, wy + 50, wx + ww - 70, wy + 180], fill=(252, 248, 220, 255)) + d.ellipse([wx + ww - 168, wy + 42, wx + ww - 52, wy + 158], fill=sky + (255,)) + d.polygon([(wx, wy + wh), (wx + 120, wy + wh - 130), (wx + 260, wy + wh - 60), (wx + 400, wy + wh - 160), (wx + ww, wy + wh - 70), (wx + ww, wy + wh)], fill=(10, 14, 34, 255)) + else: + d.ellipse([wx + 70, wy + 60, wx + 230, wy + 220], fill=(255, 214, 90, 255)) + for k in range(8): + ang = k * math.pi / 4 + d.line([(wx + 150 + math.cos(ang) * 110, wy + 140 + math.sin(ang) * 110), (wx + 150 + math.cos(ang) * 150, wy + 140 + math.sin(ang) * 150)], fill=(255, 224, 120, 255), width=8) + d.polygon([(wx, wy + wh), (wx + 160, wy + wh - 110), (wx + 360, wy + wh - 60), (wx + ww, wy + wh - 130), (wx + ww, wy + wh)], fill=(130, 200, 140, 255)) + d.ellipse([wx + 330, wy + 90, wx + 470, wy + 150], fill=(255, 255, 255, 235)) + d.ellipse([wx + 380, wy + 70, wx + 520, wy + 140], fill=(255, 255, 255, 235)) + d.line([(wx + ww // 2, wy), (wx + ww // 2, wy + wh)], fill=INK + (255,), width=12) + d.line([(wx, wy + wh // 2), (wx + ww, wy + wh // 2)], fill=INK + (255,), width=12) + d.rounded_rectangle([wx - 30, wy + wh + 6, wx + ww + 30, wy + wh + 34], radius=10, fill=(230, 224, 214, 255) if not night else (70, 74, 100, 255), outline=INK + (255,), width=5) + # curtains + cur = (150, 64, 82, 255) if not night else (62, 36, 66, 255) + for sign in (-1, 1): + x0 = wx - 30 if sign < 0 else wx + ww + 30 + pts = [(x0, wy - 40), (x0 + sign * 120, wy - 40), (x0 + sign * 90, wy + wh * 0.55), (x0 + sign * 150, wy + wh + 20), (x0, wy + wh + 20)] + d.polygon(pts, fill=cur) + d.line(pts + [pts[0]], fill=INK + (255,), width=6, joint="curve") + for k in range(1, 4): + d.line([(x0 + sign * 30 * k, wy - 36), (x0 + sign * (24 * k + 10), wy + wh)], fill=(0, 0, 0, 40), width=5) + d.line([(wx - 70, wy - 40), (wx + ww + 70, wy - 40)], fill=INK + (255,), width=10) + # the picture of the cat on the wall + fx, fy = (400, 210) if not VERT else (70, 700) + d.rounded_rectangle([fx - 10, fy - 10, fx + 170, fy + 200], radius=10, fill=(120, 80, 52, 255), outline=INK + (255,), width=5) + d.rectangle([fx + 6, fy + 6, fx + 154, fy + 184], fill=(255, 246, 230, 255) if not night else (80, 86, 116, 255)) + try: + portrait = R.sprite(4, 0).resize((140, 140), Image.LANCZOS) + if night: + portrait = Image.blend(portrait.convert("RGBA"), Image.new("RGBA", portrait.size, (30, 36, 70, 255)), 0.45) + img.alpha_composite(portrait, (fx + 10, fy + 24)) + except Exception: + pass + # the floor with its boards, the table with legs + floor_top = lay["table"] + 70 + d.rectangle([0, floor_top, W, H], fill=(26, 30, 50, 255) if night else (206, 160, 118, 255)) + for k in range(0, W, 140): + d.line([(k, floor_top), (k - 60, H)], fill=(0, 0, 0, 50), width=4) + d.rectangle([0, floor_top - 14, W, floor_top], fill=(38, 42, 70, 255) if night else (240, 228, 214, 255)) # the skirting board + tx0, tx1 = (W // 2 - 470, W // 2 + 470) if not VERT else (110, W - 110) + for lx in (tx0 + 50, tx1 - 90): + d.rectangle([lx, lay["table"] + 30, lx + 40, floor_top + 40], fill=(86, 60, 44, 255) if night else (150, 100, 66, 255), outline=INK + (255,), width=5) + d.rounded_rectangle([tx0, lay["table"], tx1, lay["table"] + 40], radius=16, fill=(104, 72, 54, 255) if night else (190, 134, 90, 255), outline=INK + (255,), width=6) + d.rounded_rectangle([tx0 + 14, lay["table"] + 4, tx1 - 14, lay["table"] + 14], radius=6, fill=(255, 255, 255, 40)) + # light and shade over everything + over = Image.new("RGBA", (W, H), (0, 0, 0, 0)) + od = ImageDraw.Draw(over) + if night: # a beam of moonlight from the window to the floor + od.polygon([(wx + 60, wy + wh), (wx + ww - 60, wy + wh), (wx + ww + 260, H), (wx - 200, H)], fill=(160, 190, 255, 26)) + else: # and of sun + od.polygon([(wx + 40, wy + wh), (wx + ww - 40, wy + wh), (wx + ww + 320, H), (wx - 260, H)], fill=(255, 236, 160, 52)) + img.alpha_composite(over.filter(ImageFilter.GaussianBlur(18))) + return img + + +@lru_cache(maxsize=1) +def vignette() -> Image.Image: + y, x = np.ogrid[:H, :W] + d = np.sqrt(((x - W / 2) / (W / 2)) ** 2 + ((y - H / 2) / (H / 2)) ** 2) + alpha = np.clip((d - 0.65) * 120, 0, 90).astype(np.uint8) + out = Image.new("RGBA", (W, H), (0, 0, 20, 0)) + out.putalpha(Image.fromarray(alpha)) + return out + + +@lru_cache(maxsize=1) +def contact_shadow() -> Image.Image: + layer = Image.new("RGBA", (500, 120), (0, 0, 0, 0)) + ImageDraw.Draw(layer).ellipse([60, 40, 440, 90], fill=(10, 10, 30, 120)) + return layer.filter(ImageFilter.GaussianBlur(12)) + + +def glow(img, x, y, size, alpha): + layer = Image.new("RGBA", (size * 2, size * 2), (0, 0, 0, 0)) + ImageDraw.Draw(layer).ellipse([size // 2, size // 2, size * 3 // 2, size * 3 // 2], fill=(150, 190, 255, int(110 * alpha))) + put_c(img, layer.filter(ImageFilter.GaussianBlur(size // 4)), x, y) + + +def zoom_at(t: float) -> float: + return in_out(seg(t, 11.3, 12.3)) * (1 - in_out(seg(t, 14.4, 14.9))) + + +def phone_state(t: float): + """(screen key, camera dot, x, y, angle, scale) of the phone at time t.""" + lay = layout() + px, py = lay["phone"] + base = lay["base"] + to_thief = in_out(seg(t, 2.5, 3.0)) * (1 - in_out(seg(t, 5.4, 5.9))) + to_guy = in_out(seg(t, 9.5, 10.0)) * (1 - in_out(seg(t, 14.6, 15.2))) + dx = to_thief * (lay["thief_x"] + 250 - px) + to_guy * (lay["guy_x"] - 250 - px) + dy = -80 * to_thief - 60 * to_guy + angle = -7 * to_thief + 7 * to_guy + camera = False + state = "wait" + if 3.4 <= t < 3.9 or 4.6 <= t < 5.1: + state = "wrong" + camera = True + dx += math.sin(t * 60) * 6 + if 10.2 <= t < 10.9: + state = "right" + key = ("lock", int(t * 10), state) + if t >= 10.9: + key = ("journal", int(10 * (0.5 + 0.5 * math.sin((t - 11.5) * 5))) if t > 12.4 else 0, "") + zoom = zoom_at(t) + scale = lerp(base, lay["zoom"], zoom) + cx = lerp(px + dx, W // 2, zoom) + cy = lerp(py + dy, H // 2, zoom) + return key, camera, cx, cy, angle * (1 - zoom), scale + + +def blinks(t: float) -> bool: + """A blink every few seconds.""" + return (t * 0.9) % 3.0 < 0.13 + + +def draw_people(img, t): + lay = layout() + size = lay["person"] + feet = lay["feet"] + top = feet - 700 * size + key, camera, pcx, pcy, pang, pscale = phone_state(t) + # the thief: comes in from the left, reaches, takes the phone, fails, puts it back, goes away + tx = lay["thief_x"] + walking = (0.5 < t < 2.3) or (6.0 < t < 7.5) + x = lerp(-260, tx, out_cubic(seg(t, 0.5, 2.3))) if t < 3.0 else lerp(tx, -320, in_out(seg(t, 6.0, 7.5))) + step = t * 9 if walking else 0.0 + arm = None + mood = "sneak" + if 2.2 <= t < 5.9: + reach = out_cubic(seg(t, 2.2, 2.7)) * (1 - seg(t, 5.5, 5.9)) + hx, hy = pcx - HALF * pscale + 14, pcy + 70 + arm = (lerp(318, 200 + (hx - x) / size, reach), lerp(478, 330 + (hy - top) / size, reach)) + mood = "angry" if t > 5.0 else "sneak" + if t < T_DAY + 0.4: + layer = person("thief", step, arm, mood, size=size, blink=blinks(t)) + bob = abs(math.sin(step)) * 8 if walking else 0 + put_c(img, contact_shadow(), x + 10, feet - 4, size * 0.62, 0.9) + put_c(img, layer, x, feet - layer.height / 2 - bob, 1.0, 1.0) + # the owner: comes in from the right in the morning, opens the phone with his finger, is struck by what he sees + gx = lay["guy_x"] + if t >= 8.0: + xg = lerp(W + 260, gx, out_cubic(seg(t, 8.0, 9.4))) + walking = t < 9.4 + step = t * 9 if walking else 0.0 + mood = "shock" if t >= 12.4 else "calm" + arm = None + if 9.4 <= t < 14.9: + reach = out_cubic(seg(t, 9.4, 9.9)) * (1 - zoom_at(t)) + hx, hy = pcx + HALF * pscale - 14, pcy + 70 + arm = (lerp(318, 200 - (hx - xg) / size, reach), lerp(478, 330 + (hy - top) / size, reach)) + layer = person("guy", step, arm, mood, look=(-1, 0), size=size, blink=blinks(t)).transpose(Image.FLIP_LEFT_RIGHT) + bob = abs(math.sin(step)) * 8 if walking else 0 + put_c(img, contact_shadow(), xg - 10, feet - 4, size * 0.62, 0.9) + put_c(img, layer, xg, feet - layer.height / 2 - bob, 1.0, 1.0) + if t >= 12.5: # the "!" over the head + k = out_back(seg(t, 12.5, 12.9), 2.0) + put_c(img, bang(), xg, top - 20, k * size, clamp(k * 2) * (1 - seg(t, 14.6, 14.9))) + + +@lru_cache(maxsize=1) +def bang() -> Image.Image: + layer = Image.new("RGBA", (200, 200), (0, 0, 0, 0)) + d = ImageDraw.Draw(layer) + d.ellipse([10, 10, 190, 190], fill=INK + (255,)) + d.ellipse([20, 20, 180, 180], fill=(255, 214, 90, 255)) + d.text((100, 104), "!", font=font(130, "black"), fill=INK + (255,), anchor="mm") + return layer + + +def clock(img, t): + text = "03:12" if t < T_DAY else "08:30" + word = "Ночью" if t < T_DAY else "Утром" + ink = (230, 236, 255) if t < T_DAY else INK + x = 90 if not VERT else 80 + plate = Image.new("RGBA", (330, 170), (0, 0, 0, 0)) + ImageDraw.Draw(plate).rounded_rectangle([0, 0, 329, 169], radius=36, fill=(10, 14, 34, 150) if t < T_DAY else (255, 255, 255, 170)) + img.alpha_composite(plate, (x - 28, 22)) + V.text(img, (x + 8, 70), word, 44, "semi", ink, "lm", alpha=out_cubic(seg(t % T_DAY if t < T_DAY else t - T_DAY, 0.2, 0.8))) + V.text(img, (x + 8, 130), text, 72, "black", ink, "lm", alpha=out_cubic(seg(t % T_DAY if t < T_DAY else t - T_DAY, 0.3, 0.9))) + + +def scene(t: float) -> Image.Image: + lay = layout() + night = room(True) + day = room(False) + k = in_out(seg(t, T_DAY - 0.4, T_DAY + 0.3)) + img = night.copy() if k <= 0 else (day.copy() if k >= 1 else Image.blend(night, day, k)) + key, camera, cx, cy, angle, scale = phone_state(t) + if t < T_DAY: + glow(img, cx, cy, 700, 1.0) + draw_people(img, t) + held = abs(cy - lay["phone"][1]) > 6 or abs(cx - lay["phone"][0]) > 6 + if not held and scale < lay["base"] * 1.2: + put_c(img, contact_shadow(), cx, lay["table"] + 6, scale * 1.5, 0.8) + put_c(img, phone(key, camera), cx, cy, scale, 1.0, angle) + img.alpha_composite(vignette()) + clock(img, t) + return img + + +def frame_at(t: float) -> Image.Image: + if t < T_CAT - 0.35: + img = scene(t) + else: + cat = R.frame_at(max(0.25, t - CAT_OFFSET), CAT_LINES).convert("RGBA") + k = in_out(seg(t, T_CAT - 0.35, T_CAT + 0.25)) + img = cat if k >= 1 else Image.blend(scene(min(t, T_CAT)), cat, k) + fade = clamp(t / 0.35) + if fade < 1: + img.alpha_composite(Image.new("RGBA", img.size, (0, 0, 0, int(255 * (1 - fade))))) + return img.convert("RGB").convert("RGBA") + + +# ---------------------------------------------------------------- the sound + +def thud(rng): + t = M.tt(0.07) + return M.lp(rng.standard_normal(len(t)), 420) * np.exp(-t * 55) * 1.4 + + +def buzzer(): + t = M.tt(0.3) + f = 190 - 40 * (t / 0.3) + s = np.sign(np.sin(2 * math.pi * np.cumsum(f) / M.SR)) * 0.5 + return M.lp(s, 1800) * np.minimum(1, t / 0.01) * np.clip((0.3 - t) / 0.08, 0, 1) + + +def soundtrack(duration: float, path: Path) -> None: + rng = np.random.default_rng(11) + mix = M.Mix(duration + 0.5) + for k in range(int(T_DAY)): # the clock ticks in the night + mix.add(M.tick(1500), 0.4 + k * 1.0, 0.07, pan=-0.3) + for t0 in np.arange(0.7, 2.3, 0.42): # the thief comes in + mix.add(thud(rng), float(t0), 0.5, pan=-0.5) + for t0 in np.arange(6.1, 7.5, 0.42): # and goes away + mix.add(thud(rng), float(t0), 0.45, pan=-0.5) + mix.add(M.whoosh(0.4, True), 2.55, 0.25, pan=-0.3) + mix.add(M.pop(700, 250, 0.08), 2.9, 0.3, pan=-0.3) + for t0 in (3.4, 4.6): # the wrong finger, and the camera + mix.add(buzzer(), t0, 0.5) + mix.add(M.tick(2600), t0 + 0.15, 0.5, pan=0.4) + mix.add(M.pop(500, 200, 0.08), 5.75, 0.3, pan=-0.3) + for t0 in np.arange(8.2, 9.4, 0.42): # the owner comes in + mix.add(thud(rng), float(t0), 0.45, pan=0.5) + mix.add(M.whoosh(0.4, True), 9.55, 0.25, pan=0.3) + mix.add(M.bell(M.midi(88), 1.4), 10.6, 0.4, send=0.4) # the right finger + mix.add(M.sparkle(1.0, 6, 88, 3), 10.65, 0.35, send=0.4) + mix.add(M.whoosh(0.5, True), 11.3, 0.3) + mix.add(M.boing(), 12.55, 0.5) + mix.add(M.pop(1000, 300, 0.12), 12.6, 0.4) + for i, (t0, k, n) in enumerate(R.meow_times(CAT_LINES)): + base = [560.0, 610.0, 520.0, 590.0, 640.0][i % 5] * (1.0 - 0.07 * k) + length = R.MEOW * (1.12 if k == n - 1 and n > 1 else 1.0) + mix.add(R.meow(base, length, seed=i), CAT_OFFSET + t0, 0.9, pan=-0.2 + 0.1 * (k % 2), send=0.1) + end = CAT_OFFSET + R.starts(CAT_LINES)[-2] + mix.add(M.sparkle(1.6, 12, 84, 2), end + 0.9, 0.55, send=0.4) + mix.add(M.bell(M.midi(93), 1.8), end + 0.9, 0.3, send=0.5) + data = np.stack([mix.left, mix.right], axis=1)[: int((duration + 0.5) * M.SR)] + data = np.tanh(data * 1.1) + data /= max(1e-9, np.abs(data).max()) / 0.85 + M.write(path, data.astype(np.float32)) + + +# ---------------------------------------------------------------- the video + +def duration() -> float: + return CAT_OFFSET + R.total(CAT_LINES) + + +def _init(vertical: bool) -> None: + setup(vertical) + R.prepare() + + +def render_frame(index: int) -> bytes: + return frame_at(index / FPS).convert("RGB").tobytes() + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--vertical", action="store_true") + parser.add_argument("--still", type=float, nargs="*") + parser.add_argument("--no-music", action="store_true") + parser.add_argument("--jobs", type=int, default=6) + args = parser.parse_args() + setup(args.vertical) + OUT.mkdir(parents=True, exist_ok=True) + R.prepare() + tag = "_9x16" if args.vertical else "" + if args.still: + for t in args.still: + path = OUT / ("still%s_%05.2f.png" % (tag, t)) + frame_at(t).convert("RGB").save(path) + print(path) + return + total = duration() + wav = OUT / "sound.wav" + soundtrack(total, wav) + out = OUT / ("thief%s.mp4" % tag) + music = ROOT / "work" / "music" / "store.mp3" + command = [shutil.which("ffmpeg") or "ffmpeg", "-y", "-loglevel", "error", "-f", "rawvideo", "-pix_fmt", "rgb24", "-s", "%dx%d" % (W, H), + "-r", str(FPS), "-i", "-", "-i", str(wav)] + if args.no_music or not music.is_file(): + command += ["-af", "afade=t=out:st=%.2f:d=0.6" % (total - 0.6)] + else: + command += ["-i", str(music), "-filter_complex", + "[2:a]adelay=%d|%d,volume=0.2,afade=t=in:st=%.2f:d=1.0,afade=t=out:st=%.2f:d=1.0[b];[1:a][b]amix=inputs=2:duration=first:normalize=0," + "afade=t=out:st=%.2f:d=0.6[a]" % (int(T_DAY * 1000), int(T_DAY * 1000), T_DAY, total - 1.0, total - 0.6), "-map", "0:v", "-map", "[a]"] + command += ["-c:v", "libx264", "-preset", "medium", "-crf", "17", "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "192k", "-t", "%.2f" % total, str(out)] + proc = subprocess.Popen(command, stdin=subprocess.PIPE) + frames = int(round(total * FPS)) + with Pool(args.jobs, initializer=_init, initargs=(args.vertical,)) as pool: + for n, data in enumerate(pool.imap(render_frame, range(frames), chunksize=4)): + proc.stdin.write(data) + if n % 60 == 0: + print("frame %d/%d" % (n, frames), flush=True) + proc.stdin.close() + proc.wait() + print("done:", out) + + +if __name__ == "__main__": + main() diff --git a/scripts/stage_site.py b/scripts/stage_site.py index a0ec96f..a1dd0a1 100644 --- a/scripts/stage_site.py +++ b/scripts/stage_site.py @@ -25,9 +25,7 @@ PAYLOAD = [ ("src/web/members_index.html", "members/index.html"), ("src/web/pay_index.html", "pay/index.html"), ("src/web/pet_index.html", "pet/index.html"), - ("src/web/assets/pets/cat.png", "assets/pets/cat.png"), - ("src/web/assets/pets/dog.png", "assets/pets/dog.png"), - ("src/web/assets/pets/lion.png", "assets/pets/lion.png"), + ("src/web/assets/pets/index.json", "assets/pets/index.json"), ("src/web/assets/site/md3.css", "assets/site/md3.css"), ("src/web/assets/site/oa.css", "assets/site/oa.css"), ("src/web/assets/site/oa-md3.css", "assets/site/oa-md3.css"), @@ -36,6 +34,9 @@ PAYLOAD = [ ("src/web/assets/site/plugin_howto.svg", "assets/site/plugin_howto.svg"), ] +# The previews of the animals, then one strip of frames per animal, age and mood +for _preview in sorted((ROOT / "src" / "web" / "assets" / "pets").glob("*.png")): + PAYLOAD.append((_preview.relative_to(ROOT).as_posix(), "assets/pets/" + _preview.name)) # The animals of the Серийчик: one strip of frames per animal, age and mood (see scripts/make_pet_designs.py) for _strip in sorted((ROOT / "src" / "web" / "assets" / "pets" / "strips").glob("*.png")): PAYLOAD.append((_strip.relative_to(ROOT).as_posix(), "assets/pets/strips/" + _strip.name)) diff --git a/services/members/server.py b/services/members/server.py index 9608166..3509b38 100644 --- a/services/members/server.py +++ b/services/members/server.py @@ -46,7 +46,25 @@ GRANT = re.compile(r"[a-z0-9][a-z0-9_-]{0,23}\.(\*|[a-z0-9][a-z0-9_-]{0,23})\Z") # A frame a member made: "u." and the first 24 hex digits of the picture's SHA-256. CUSTOM = re.compile(r"u\.[0-9a-f]{24}\Z") ART_STATES = ("new", "review", "approved", "rejected") -SPECIES = ("cat", "dog", "lion") # the animals the mod can draw; a new one is added here and in the mod +SPECIES = ("cat", "dog", "lion") # the animals known when the site's catalog cannot be read +# The animals are listed in the site's catalog (assets/pets/index.json, made by scripts/build_pets_catalog.py); the service reads the same +# file where the site keeps it, so a new animal needs no change here and no restart. +PETS_INDEX = Path(os.environ.get("LIHONT_PETS_INDEX", "/var/www/lihont/assets/pets/index.json")) +SPECIES_ID = re.compile(r"[a-z][a-z0-9]{1,15}\Z") +_species_seen = [None, SPECIES] # the catalog file's modification time and the animals read from it + + +def species_list(): + """The animals a pair can be given: the catalog file when it can be read, else the last good list, else the three first ones.""" + try: + stamp = PETS_INDEX.stat().st_mtime + if _species_seen[0] != stamp: + data = json.loads(PETS_INDEX.read_text(encoding="utf-8")) + ids = tuple(a["id"] for a in data["animals"][:60] if isinstance(a, dict) and SPECIES_ID.match(str(a.get("id", "")))) + _species_seen[0], _species_seen[1] = stamp, (ids or SPECIES) + except (OSError, ValueError, KeyError, TypeError): + pass # a half-written or missing file: keep what was read last + return _species_seen[1] UPLOAD_BODY = 300_000 # Operations by how often one address may call them: reads, the account's own small writes, installs, uploads. ACCOUNTS = ("tg_start", "tg_poll", "tg_register", "tg_me", "tg_link_tiktok", "tg_logout", "tg_delete", "tg_notify", "follow", "unfollow", @@ -615,7 +633,7 @@ class Registry: key = self.pair_key(uid, peer) if not self._proven(uid, installation): raise ValueError("Prove the account first") - if kind not in SPECIES: + if kind not in species_list(): raise ValueError("Unknown animal") with self.connect() as db: if db.execute("SELECT 1 FROM active_blocked WHERE uid IN (?,?)", (uid, peer)).fetchone(): diff --git a/src/lihont/two/chat/Bubbles.java b/src/lihont/two/chat/Bubbles.java index 32c019a..ca97bd6 100644 --- a/src/lihont/two/chat/Bubbles.java +++ b/src/lihont/two/chat/Bubbles.java @@ -60,6 +60,38 @@ public final class Bubbles { return activity.getResources().getIdentifier(name, "id", activity.getPackageName()); } + /** The chat list of this screen, or null when the screen is not a chat. */ + private static ViewGroup chatList(Activity activity, View decor) { + if (listIdCache == 0) { + listIdCache = id(activity, LIST); + rowIdCache = id(activity, ROW); + bubbleIdCache = id(activity, BUBBLE); + } + if (listIdCache == 0 || rowIdCache == 0 || bubbleIdCache == 0) return null; + View found = decor.findViewById(listIdCache); + return found instanceof ViewGroup ? (ViewGroup) found : null; + } + + /** True while this screen is an open chat (used by the lock). */ + public static boolean chatOpen(Activity activity, View decor) { + return chatList(activity, decor) != null; + } + + /** The account number of the person this chat is with, or null while it is not known (used by the lock). */ + public static String chatPartner(Activity activity, View decor) { + ViewGroup list = chatList(activity, decor); + if (list == null) return null; + cachedName(activity, decor, list); + return partnerUid; + } + + /** A chat has just come to the front: what was found for the one before must not be taken for this one. */ + public static void forgetChat() { + name = null; + partnerUid = null; + nameAt = 0L; + } + private static void apply(Activity activity, View decor) { if (listIdCache == 0) { listIdCache = id(activity, LIST); diff --git a/src/lihont/two/look/Windows.java b/src/lihont/two/look/Windows.java index 2298ddf..43deb8e 100644 --- a/src/lihont/two/look/Windows.java +++ b/src/lihont/two/look/Windows.java @@ -35,6 +35,12 @@ public final class Windows implements Application.ActivityLifecycleCallbacks { public static void attach(Activity activity) { // the recovery mode first: it may reset the look and the plugins before any skin reads them DebugMode.check(activity); + try { + lihont.two.privacy.AppLock.watch(activity); + } catch (Throwable error) { + // the lock is an extra: a screen must open even if it fails; the reason goes to the log + Log.w(TAG, "lock: could not start: " + error); + } try { lihont.two.plugin.PluginScreen.attach(activity); } catch (Throwable ignored) { @@ -69,11 +75,15 @@ public final class Windows implements Application.ActivityLifecycleCallbacks { @Override public void onActivityCreated(Activity activity, Bundle state) {} - @Override public void onActivityStarted(Activity activity) {} + @Override public void onActivityStarted(Activity activity) { + lihont.two.privacy.AppLock.onStarted(activity); + } @Override public void onActivityPaused(Activity activity) {} - @Override public void onActivityStopped(Activity activity) {} + @Override public void onActivityStopped(Activity activity) { + lihont.two.privacy.AppLock.onStopped(activity); + } @Override public void onActivitySaveInstanceState(Activity activity, Bundle state) {} diff --git a/src/lihont/two/pet/GiftActivity.java b/src/lihont/two/pet/GiftActivity.java index 60948a2..dfb9d50 100644 --- a/src/lihont/two/pet/GiftActivity.java +++ b/src/lihont/two/pet/GiftActivity.java @@ -24,14 +24,32 @@ public final class GiftActivity extends Activity { String kind = uri == null ? null : uri.getQueryParameter("kind"); String from = uri == null ? null : uri.getQueryParameter("from"); NicheClaim.Account me = NicheClaim.account(); - if (!Species.known(kind) || from == null || !from.matches("\\d{6,24}")) { + Species.load(this); + if (kind == null || !kind.matches("[a-z][a-z0-9]{1,15}") || from == null || !from.matches("\\d{6,24}")) { end("Эта ссылка не подходит"); } else if (me == null || me.uid == null) { end("Сначала войдите в TikTok, потом откройте ссылку ещё раз"); } else if (from.equals(me.uid)) { end("Эту ссылку нужно отправить другу"); - } else { + } else if (Species.known(kind)) { ask(me.uid, from); + } else { + // a new animal: this phone has not read the catalog that has it yet + final String wanted = kind; + final String giver = from; + final String mine = me.uid; + new Thread(new Runnable() { + @Override public void run() { + Species.fetchCatalog(GiftActivity.this); + runOnUiThread(new Runnable() { + @Override public void run() { + if (isFinishing()) return; + if (Species.known(wanted)) ask(mine, giver); + else end("Такого зверя пока нет. Обновите LihonT или попробуйте позже"); + } + }); + } + }, "lihont-gift-catalog").start(); } } diff --git a/src/lihont/two/pet/Species.java b/src/lihont/two/pet/Species.java index 1bbf843..40ab71e 100644 --- a/src/lihont/two/pet/Species.java +++ b/src/lihont/two/pet/Species.java @@ -5,8 +5,13 @@ import android.content.SharedPreferences; import android.os.Handler; import android.os.Looper; +import org.json.JSONArray; +import org.json.JSONException; import org.json.JSONObject; +import java.io.File; +import java.util.ArrayList; + import lihont.two.avatar.Installation; import lihont.two.badge.MemberClient; @@ -16,9 +21,31 @@ import lihont.two.badge.MemberClient; * (species_offer / species_lookup / species_answer); the phone keeps the last answer, so the screens draw at once. */ public final class Species { - public static final String[] KINDS = {"cat", "dog", "lion"}; + /** One animal of the catalog: its word, what the small one is called and the same as "дарит вам ...". */ + public static final class Animal { + public final String id; + public final String label; + public final String gift; + + Animal(String id, String label, String gift) { + this.id = id; + this.label = label; + this.gift = gift; + } + } + + // What is known before the catalog has ever been read; the catalog of the site (assets/pets/index.json) replaces it, so a new animal + // reaches the phones without an update of the mod (the pictures come the same way, see PetArt). + private static final Animal[] BUILT_IN = {new Animal("cat", "котёнок", "котёнка"), new Animal("dog", "щенок", "щенка"), new Animal("lion", "львёнок", "львёнка")}; + private static final String CATALOG_URL = "https://lihont.space/assets/pets/index.json"; + private static final String CATALOG_FILE = "pet_catalog.json"; + private static final long CATALOG_EVERY_MS = 6L * 60L * 60L * 1000L; + private static final long CATALOG_GAP_MS = 60L * 1000L; private static final String PREFS = "lihont_pet_species"; private static final Handler MAIN = new Handler(Looper.getMainLooper()); + private static volatile Animal[] catalog = BUILT_IN; + private static boolean catalogLoaded; + private static long catalogAt; // when the catalog was last asked for (uptime), 0 = not yet in this run public interface Done { void done(boolean ok, String text); @@ -27,24 +54,119 @@ public final class Species { private Species() { } + /** Reads the catalog the phone kept from the last time, once per run. */ + public static synchronized void load(Context context) { + if (catalogLoaded) return; + catalogLoaded = true; + File file = new File(app(context).getFilesDir(), CATALOG_FILE); + if (!file.isFile()) return; + try { + Animal[] read = parse(new String(java.nio.file.Files.readAllBytes(file.toPath()), "UTF-8")); + if (read.length > 0) catalog = read; + } catch (Exception broken) { + // the built-in list stays + } + } + + /** Only well-formed animals are taken: a short lower-case id and two short words. */ + static Animal[] parse(String text) throws JSONException { + JSONArray list = new JSONObject(text).getJSONArray("animals"); + ArrayList out = new ArrayList(); + for (int i = 0; i < list.length() && i < 60; i++) { + JSONObject one = list.optJSONObject(i); + if (one == null) continue; + String id = one.optString("id", ""); + String label = one.optString("label", ""); + String gift = one.optString("gift", ""); + if (!id.matches("[a-z][a-z0-9]{1,15}") || label.isEmpty() || label.length() > 24 || gift.isEmpty() || gift.length() > 24) continue; + out.add(new Animal(id, label, gift)); + } + return out.toArray(new Animal[0]); + } + + /** Asks the site for the catalog in the background, at most once in six hours (and the first time in a run). */ + public static void refreshCatalog(final Context context) { + load(context); + synchronized (Species.class) { + long now = android.os.SystemClock.uptimeMillis(); + if (catalogAt != 0 && now - catalogAt < CATALOG_EVERY_MS) return; + catalogAt = now; + } + final Context app = app(context); + new Thread(new Runnable() { + @Override public void run() { + download(app); + } + }, "lihont-pet-catalog").start(); + } + + /** Asks for the catalog now (a worker thread only): used when something named an animal this phone has not heard of. */ + public static boolean fetchCatalog(Context context) { + load(context); + synchronized (Species.class) { + long now = android.os.SystemClock.uptimeMillis(); + if (catalogAt != 0 && now - catalogAt < CATALOG_GAP_MS) return false; + catalogAt = now; + } + return download(app(context)); + } + + private static boolean download(Context app) { + try { + java.net.HttpURLConnection connection = (java.net.HttpURLConnection) new java.net.URL(CATALOG_URL).openConnection(); + connection.setConnectTimeout(8000); + connection.setReadTimeout(15000); + if (connection.getResponseCode() != 200) return false; + java.io.InputStream in = connection.getInputStream(); + java.io.ByteArrayOutputStream bytes = new java.io.ByteArrayOutputStream(); + byte[] buffer = new byte[4096]; + int n; + while ((n = in.read(buffer)) > 0) { + bytes.write(buffer, 0, n); + if (bytes.size() > 32 * 1024) return false; + } + in.close(); + String text = bytes.toString("UTF-8"); + Animal[] read = parse(text); + if (read.length == 0) return false; + File file = new File(app.getFilesDir(), CATALOG_FILE); + File temp = new File(app.getFilesDir(), CATALOG_FILE + ".tmp"); + java.io.FileOutputStream out = new java.io.FileOutputStream(temp); + out.write(text.getBytes("UTF-8")); + out.close(); + if (!temp.renameTo(file)) { + file.delete(); + temp.renameTo(file); + } + catalog = read; + return true; + } catch (Exception unreachable) { + return false; + } + } + + /** The ids of the animals that can be given. */ + public static String[] kinds() { + Animal[] now = catalog; + String[] out = new String[now.length]; + for (int i = 0; i < now.length; i++) out[i] = now[i].id; + return out; + } + public static boolean known(String kind) { - for (String one : KINDS) if (one.equals(kind)) return true; + for (Animal one : catalog) if (one.id.equals(kind)) return true; return false; } /** What the animal is called when it is small. */ public static String label(String kind) { - if ("cat".equals(kind)) return "котёнок"; - if ("dog".equals(kind)) return "щенок"; - if ("lion".equals(kind)) return "львёнок"; + for (Animal one : catalog) if (one.id.equals(kind)) return one.label; return "питомец"; } /** The same, as "дарит вам ...". */ public static String gift(String kind) { - if ("cat".equals(kind)) return "котёнка"; - if ("dog".equals(kind)) return "щенка"; - if ("lion".equals(kind)) return "львёнка"; + for (Animal one : catalog) if (one.id.equals(kind)) return one.gift; return "питомца"; } @@ -75,6 +197,7 @@ public final class Species { /** Asks the service what the pair has, at most every ten minutes, so an animal given on the other phone turns up here by itself. */ public static synchronized void refresh(Context context, String mine, String peer) { + refreshCatalog(context); String key = key(mine, peer); long now = android.os.SystemClock.uptimeMillis(); Long last = ASKED.get(key); @@ -115,8 +238,9 @@ public final class Species { JSONObject reply = MemberClient.post("species_lookup", new JSONObject().put("uid", mine).put("peer", peer) .put("installation", Installation.secret(app))); String kind = reply.optString("kind", ""); - remember(app, mine, peer, known(kind) ? kind : ""); String offer = reply.optString("offer", ""); + if ((!kind.isEmpty() && !known(kind)) || (!offer.isEmpty() && !known(offer))) fetchCatalog(app); + remember(app, mine, peer, known(kind) ? kind : ""); text = known(offer) ? offer : ""; ok = true; } catch (Exception error) { @@ -138,6 +262,7 @@ public final class Species { JSONObject reply = MemberClient.post("species_answer", new JSONObject().put("uid", mine).put("peer", peer).put("accept", accept) .put("installation", Installation.secret(app))); String kind = reply.optString("kind", ""); + if (!kind.isEmpty() && !known(kind)) fetchCatalog(app); remember(app, mine, peer, known(kind) ? kind : ""); ok = true; text = kind; diff --git a/src/lihont/two/privacy/AppLock.java b/src/lihont/two/privacy/AppLock.java new file mode 100644 index 0000000..1ac988e --- /dev/null +++ b/src/lihont/two/privacy/AppLock.java @@ -0,0 +1,476 @@ +package lihont.two.privacy; + +import android.app.Activity; +import android.content.res.Configuration; +import android.graphics.Canvas; +import android.graphics.Color; +import android.graphics.Paint; +import android.graphics.RectF; +import android.graphics.Typeface; +import android.graphics.drawable.GradientDrawable; +import android.os.SystemClock; +import android.util.Log; +import android.view.Gravity; +import android.view.View; +import android.view.ViewGroup; +import android.view.ViewTreeObserver; +import android.view.WindowManager; +import android.widget.FrameLayout; +import android.widget.LinearLayout; +import android.widget.TextView; + +import java.util.HashMap; +import java.util.WeakHashMap; + +import lihont.two.chat.Bubbles; + +/** + * The lock: a solid cover over a screen of TikTok until the phone's own unlock (fingerprint, face or the lock-screen code, see + * Authenticator) says yes. It can cover the whole app, every chat, or the chats of chosen people (LockSettings). + * + * Nothing is remembered about the person: only "this key was open a moment ago" (the app, all chats, or one chat). A key stays open while + * its screen is in front, and for the chosen time after the screen was left (a change of screen inside the app is never "away": at least + * three seconds are always allowed). The check runs before every frame of a screen, so a screen is covered before it is first drawn. + */ +public final class AppLock { + private static final String TAG = "LIHONT"; + private static final long BOUNCE_MS = 3000L; // moving between two screens of the app, or a short look away + private static final long UNKNOWN_MS = 2500L; // how long a chat is held covered while the app works out who it is with + + private static final WeakHashMap SCREENS = new WeakHashMap(); + private static final HashMap OPEN = new HashMap(); // key -> uptime of the last frame it was open in view + private static int started; // screens of the app that are started: 0 means the app is in the background (or the phone is locked) + private static long backgroundAt; // when it last went to the background + private static final long NOW_MS = 600L; // "at once": away for longer than this (a turn of the phone recreates a screen in a blink) + private static boolean asking; + private static long attemptId; // the journal entry of the entry in progress (0: none) + private static String attemptKey = ""; + private static long attemptAt; + private static long sessionId; // the entry that was opened and has not been left: the chats opened meanwhile are written to it + private static long askingSince; + private static Activity askingIn; + private static android.os.CancellationSignal askSignal; + private static boolean broken; // the phone's window cannot be opened: the app is not locked out of its own screens because of it + + private AppLock() {} + + /** What one screen remembers between frames. */ + private static final class Screen { + boolean chat; + long chatSince; + Cover cover; + String lastTrace = ""; + boolean noteSeen; // a chat is in front and has been looked at for the journal + boolean noted; // and its person has been written down + } + + /** One line in the log when what the lock decided for a screen changes (the decision only: never a name or a message). */ + private static void trace(Screen screen, Activity activity, String what) { + if (what.equals(screen.lastTrace)) return; + screen.lastTrace = what; + try { + Log.i(TAG, "lock: " + what + " [" + activity.getClass().getSimpleName() + "]"); + } catch (Throwable noLogger) { + // diagnostic only + } + } + + /** A screen of the app was started. When the app comes back from the background after longer than the chosen time, everything is shut again. */ + public static void onStarted(Activity activity) { + try { + if (started == 0 && backgroundAt != 0) { + long away = SystemClock.uptimeMillis() - backgroundAt; + if (away > Math.max(LockSettings.timeoutMs(activity), NOW_MS) && !OPEN.isEmpty()) { + OPEN.clear(); + Log.i(TAG, "lock: back after " + (away / 1000) + " s, shut again"); + } + } + if (started == 0) { // back from the background: a cover that is still up asks for the phone's unlock again at once + asking = false; + for (Screen screen : SCREENS.values()) if (screen.cover != null) screen.cover.asked = false; + } + started++; + } catch (Throwable ignored) { + // the lock must never take a screen down + } + } + + public static void onStopped(Activity activity) { + started--; + if (started <= 0) { + started = 0; + backgroundAt = SystemClock.uptimeMillis(); + sessionId = 0L; // the visit is over + attemptId = 0L; + } + } + + public static void watch(final Activity activity) { + try { + secure(activity); + } catch (Throwable ignored) { + // an extra + } + final View decor = activity.getWindow().getDecorView(); + if (!(decor instanceof ViewGroup) || SCREENS.containsKey(decor)) return; + SCREENS.put(decor, new Screen()); + try { + Log.i(TAG, "lock: watching " + activity.getClass().getSimpleName() + ", mode " + LockSettings.mode(activity)); + } catch (Throwable noLogger) { + // diagnostic only + } + decor.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { + @Override public boolean onPreDraw() { + try { + tick(activity, (ViewGroup) decor); + } catch (Throwable ignored) { + // the lock must never take a screen down + } + return true; + } + }); + } + + /** "Hide from recents and screenshots" is a flag of the window. */ + private static void secure(Activity activity) { + boolean want = LockSettings.hideRecents(activity); + int flag = WindowManager.LayoutParams.FLAG_SECURE; + boolean has = (activity.getWindow().getAttributes().flags & flag) != 0; + if (want && !has) activity.getWindow().addFlags(flag); + else if (!want && has && SECURED.containsKey(activity.getWindow())) activity.getWindow().clearFlags(flag); + if (want) SECURED.put(activity.getWindow(), Boolean.TRUE); + } + + private static final WeakHashMap SECURED = new WeakHashMap(); + + private static void tick(Activity activity, ViewGroup decor) { + Screen screen = SCREENS.get(decor); + if (screen == null) return; + int mode = LockSettings.mode(activity); + if (mode == LockSettings.OFF || broken || !Authenticator.available(activity)) { + if (mode != LockSettings.OFF && !Authenticator.available(activity)) { + // the screen lock was taken off in the phone's settings: the lock cannot be answered, so it is switched off, not left shut + LockSettings.setMode(activity, LockSettings.OFF); + Log.i(TAG, "lock: the phone has no screen lock any more, the lock is switched off"); + } + uncover(screen); + return; + } + long now = SystemClock.uptimeMillis(); + noteChats(activity, decor, screen); + String key; + if (mode == LockSettings.APP) { + key = "app"; + } else { + boolean chat = Bubbles.chatOpen(activity, decor); + if (!chat) { + screen.chat = false; + uncover(screen); + return; + } + if (!screen.chat) { // a chat has just come to the front: whoever the last one was must not be taken for this one + screen.chat = true; + screen.chatSince = now; + Bubbles.forgetChat(); + } + // one key per person: opening another chat asks again, coming back to the same one within the time does not + String uid = Bubbles.chatPartner(activity, decor); + if (uid == null) { + if (now - screen.chatSince < UNKNOWN_MS) { + trace(screen, activity, "chat held shut, who is it?"); + cover(activity, decor, screen, "chat:?", true); // held shut while it is worked out who this is + return; + } + key = "chat:?"; // not told: shut, to be safe (a group chat or a person that cannot be recognised) + } else if (mode == LockSettings.CHOSEN && !LockSettings.chosen(activity).contains(uid)) { + trace(screen, activity, "chat not chosen, open"); + uncover(screen); + return; + } else { + key = "chat:" + uid; + } + } + long gap = Math.max(LockSettings.timeoutMs(activity), BOUNCE_MS); + Long seen = OPEN.get(key); + // the whole app stays open for as long as it is in front (coming back from the background shuts it, see onStarted); a chat also + // stays open for the chosen time after it was left + if (seen != null && (mode == LockSettings.APP || now - seen.longValue() <= gap)) { + OPEN.put(key, Long.valueOf(now)); + trace(screen, activity, key + " open"); + uncover(screen); + return; + } + trace(screen, activity, key + " shut"); + cover(activity, decor, screen, key, false); + } + + /** While a visit that was let in goes on, the people whose chats are opened are written down in its journal entry. */ + private static void noteChats(Activity activity, ViewGroup decor, Screen screen) { + if (sessionId == 0L || screen.cover != null) return; + if (!Bubbles.chatOpen(activity, decor)) { + screen.noteSeen = false; + screen.noted = false; + return; + } + if (!screen.noteSeen) { + screen.noteSeen = true; + Bubbles.forgetChat(); + } + if (screen.noted) return; + String uid = Bubbles.chatPartner(activity, decor); + if (uid == null) return; // worked out within a few seconds: asked again before the next frame + screen.noted = true; + LockJournal.chat(activity, sessionId, nameOf(activity, uid)); + } + + /** The name TikTok showed for the account number, or a short stand-in. */ + private static String nameOf(Activity activity, String uid) { + try { + String mine = lihont.two.account.CurrentAccount.uid(); + if (mine != null) { + android.content.Context app = activity.getApplicationContext() != null ? activity.getApplicationContext() : activity; + String name = lihont.two.widget.Contacts.all(app, mine).get(uid); + if (name != null && !name.isEmpty()) return name; + } + } catch (Throwable ignored) { + // a stand-in below + } + return "чат …" + (uid.length() > 4 ? uid.substring(uid.length() - 4) : uid); + } + + private static void uncover(Screen screen) { + if (screen.cover == null) return; + Cover gone = screen.cover; + screen.cover = null; + ViewGroup parent = (ViewGroup) gone.getParent(); + if (parent != null) parent.removeView(gone); + } + + private static void cover(final Activity activity, ViewGroup decor, final Screen screen, String key, boolean holding) { + Cover cover = screen.cover; + if (cover == null) { + cover = new Cover(activity); + screen.cover = cover; + decor.addView(cover, new FrameLayout.LayoutParams(-1, -1)); + } else if (decor.getChildAt(decor.getChildCount() - 1) != cover) { + cover.bringToFront(); // something of TikTok was added over it + } + cover.show(key, holding); + if (!holding && !cover.asked) { + long now = SystemClock.uptimeMillis(); + if (asking && (askingIn != activity || now - askingSince > 45_000L)) { + if (askSignal != null) { + try { + askSignal.cancel(); + } catch (Throwable ignored) { + // already gone + } + } + asking = false; + } + if (!asking) ask(activity, screen, cover); + } + } + + private static void ask(final Activity activity, final Screen screen, final Cover cover) { + asking = true; + askingSince = SystemClock.uptimeMillis(); + askingIn = activity; + cover.asked = true; + final String key = cover.key; + // one entry in the journal for one entry attempt: several screens may raise a cover for the same moment + boolean fresh = attemptId == 0L || !key.equals(attemptKey) || askingSince - attemptAt > 8000L; + if (fresh) { + attemptKey = key; + attemptAt = askingSince; + String name = key.startsWith("chat:") && key.length() > 6 ? nameOf(activity, key.substring(5)) : ""; + attemptId = LockJournal.begin(activity, key, name); + } + final long id = attemptId; + if (fresh && LockSettings.photoOn(activity) && IntruderCamera.allowed(activity)) { + trace(screen, activity, key + " taking a picture"); + IntruderCamera.snap(activity, id, new IntruderCamera.Done() { + @Override public void done(java.io.File photo) { + if (photo != null) LockJournal.photo(activity, id, photo.getName()); + trace(screen, activity, key + (photo != null ? " picture kept" : " no picture")); + if (screen.cover == cover && cover.getParent() != null) prompt(activity, screen, cover, id); + else asking = false; // the screen went away while the picture was taken + } + }); + } else { + prompt(activity, screen, cover, id); + } + } + + private static void prompt(final Activity activity, final Screen screen, final Cover cover, final long id) { + askingSince = SystemClock.uptimeMillis(); + trace(screen, activity, cover.key + " asking the phone"); + final String key = cover.key; + String what = "app".equals(key) ? "TikTok" : "chats".equals(key) ? "чаты" : "этот чат"; + askSignal = Authenticator.ask(activity, "LihonT: открыть " + what, "Отпечаток, лицо или пароль телефона", new Authenticator.Result() { + @Override public void ok() { + asking = false; + trace(screen, activity, key + " opened by the phone"); + LockJournal.result(activity, id, "opened", ""); + sessionId = id; + OPEN.put(key, Long.valueOf(SystemClock.uptimeMillis())); + if (screen.cover == cover) uncover(screen); + } + + @Override public void miss() { + LockJournal.miss(activity, id); + } + + @Override public void failed(String why) { + asking = false; + trace(screen, activity, key + " not opened: " + (why == null ? "" : why)); + if (why != null && why.startsWith("Не удалось открыть")) { + broken = true; // do not shut the person out of their own app because the phone's window does not open + Log.w(TAG, "lock: off for this run, the phone's window does not open"); + if (screen.cover == cover) uncover(screen); + return; + } + LockJournal.result(activity, id, "failed", why == null ? "" : why); + cover.note(why == null || why.isEmpty() ? "Не подтверждено" : why); + } + }); + } + + /** The cover itself: opaque, so nothing under it can be read, with the unlock button and a way out. */ + private static final class Cover extends FrameLayout { + String key = ""; + boolean asked; + private final TextView title; + private final TextView text; + private final TextView note; + private final TextView unlock; + private final TextView leave; + private final Activity activity; + private final float density; + + Cover(Activity activity) { + super(activity); + this.activity = activity; + density = activity.getResources().getDisplayMetrics().density; + boolean dark = (activity.getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES; + int ink = dark ? 0xFFF5F5F7 : 0xFF0D0D0F; + int muted = dark ? 0xFFA0A0A8 : 0xFF6B6B73; + setBackgroundColor(dark ? 0xFF0D0D0F : 0xFFFFFFFF); + setClickable(true); + setFocusable(true); + LinearLayout column = new LinearLayout(activity); + column.setOrientation(LinearLayout.VERTICAL); + column.setGravity(Gravity.CENTER_HORIZONTAL); + int pad = dp(28); + column.setPadding(pad, pad, pad, pad); + column.addView(new LockIcon(activity), new LinearLayout.LayoutParams(dp(88), dp(88))); + title = line(activity, 22, ink, true); + column.addView(title, margin(18)); + text = line(activity, 15, muted, false); + column.addView(text, margin(8)); + note = line(activity, 13, 0xFFE0457B, false); + column.addView(note, margin(10)); + unlock = button(activity, "Разблокировать", dark ? 0xFFF5F5F7 : 0xFF0D0D0F, dark ? 0xFF0D0D0F : 0xFFFFFFFF); + LinearLayout.LayoutParams unlockParams = margin(26); + unlockParams.width = dp(240); + column.addView(unlock, unlockParams); + leave = button(activity, "Выйти", 0x00000000, muted); + LinearLayout.LayoutParams leaveParams = margin(6); + leaveParams.width = dp(240); + column.addView(leave, leaveParams); + addView(column, new FrameLayout.LayoutParams(-2, -2, Gravity.CENTER)); + unlock.setOnClickListener(new OnClickListener() { + @Override public void onClick(View v) { + asked = false; // the next frame asks again + asking = false; + note.setText(""); + } + }); + leave.setOnClickListener(new OnClickListener() { + @Override public void onClick(View v) { + if ("app".equals(Cover.this.key)) Cover.this.activity.moveTaskToBack(true); + else Cover.this.activity.onBackPressed(); + } + }); + } + + void show(String newKey, boolean holding) { + if (!newKey.equals(key)) { + key = newKey; + asked = false; + } + boolean app = "app".equals(key); + title.setText(app ? "LihonT: TikTok закрыт" : "chats".equals(key) ? "Чаты закрыты" : "Чат закрыт"); + text.setText(holding ? "Проверяем, с кем этот чат…" : "Откройте отпечатком, лицом или паролем телефона"); + unlock.setVisibility(holding ? GONE : VISIBLE); + leave.setVisibility(holding ? GONE : VISIBLE); + leave.setText(app ? "Выйти из TikTok" : "Назад"); + } + + void note(String message) { + note.setText(message); + } + + private int dp(int value) { + return (int) (value * density + 0.5f); + } + + private LinearLayout.LayoutParams margin(int top) { + LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(-2, -2); + params.topMargin = dp(top); + return params; + } + + private TextView line(Activity activity, int sp, int color, boolean bold) { + TextView view = new TextView(activity); + view.setTextSize(sp); + view.setTextColor(color); + view.setGravity(Gravity.CENTER); + if (bold) view.setTypeface(Typeface.DEFAULT_BOLD); + view.setMaxWidth(dp(300)); + return view; + } + + private TextView button(Activity activity, String label, int fill, int color) { + TextView view = new TextView(activity); + view.setText(label); + view.setTextSize(15); + view.setTextColor(color); + view.setTypeface(Typeface.DEFAULT_BOLD); + view.setGravity(Gravity.CENTER); + view.setPadding(dp(20), dp(13), dp(20), dp(13)); + GradientDrawable shape = new GradientDrawable(); + shape.setColor(fill); + shape.setCornerRadius(dp(30)); + view.setBackground(shape); + view.setClickable(true); + return view; + } + } + + /** A padlock in the gold of the logo, drawn here so there is no picture to ship. */ + private static final class LockIcon extends View { + private final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); + + LockIcon(Activity activity) { + super(activity); + } + + @Override protected void onDraw(Canvas canvas) { + float w = getWidth(); + float h = getHeight(); + paint.setStyle(Paint.Style.STROKE); + paint.setStrokeWidth(w * 0.1f); + paint.setColor(0xFFD69634); + canvas.drawArc(new RectF(w * 0.27f, h * 0.06f, w * 0.73f, h * 0.62f), 180f, 180f, false, paint); + canvas.drawLine(w * 0.27f, h * 0.34f, w * 0.27f, h * 0.5f, paint); + canvas.drawLine(w * 0.73f, h * 0.34f, w * 0.73f, h * 0.5f, paint); + paint.setStyle(Paint.Style.FILL); + paint.setColor(0xFFEEBE6B); + canvas.drawRoundRect(new RectF(w * 0.14f, h * 0.44f, w * 0.86f, h * 0.92f), w * 0.14f, w * 0.14f, paint); + paint.setColor(0xFF5C1C28); + canvas.drawCircle(w * 0.5f, h * 0.62f, w * 0.07f, paint); + canvas.drawRect(w * 0.47f, h * 0.62f, w * 0.53f, h * 0.76f, paint); + } + } +} diff --git a/src/lihont/two/privacy/Authenticator.java b/src/lihont/two/privacy/Authenticator.java new file mode 100644 index 0000000..a485b52 --- /dev/null +++ b/src/lihont/two/privacy/Authenticator.java @@ -0,0 +1,85 @@ +package lihont.two.privacy; + +import android.app.Activity; +import android.app.KeyguardManager; +import android.content.Context; +import android.hardware.biometrics.BiometricManager; +import android.hardware.biometrics.BiometricPrompt; +import android.os.Build; +import android.os.CancellationSignal; +import android.util.Log; + +/** + * The phone's own unlock: the system window that takes a fingerprint (or face) and falls back to the PIN, pattern or password of the + * lock screen. The mod never sees or keeps a finger or a code; it only hears "yes" or "no" from Android. Needs Android 10 or newer + * and a screen lock set in the phone's settings. + */ +public final class Authenticator { + private static final String TAG = "LIHONT"; + + public interface Result { + void ok(); + + void failed(String why); + + /** A finger or face that did not match: the window stays and the person may try again. */ + default void miss() {} + } + + private Authenticator() {} + + /** True when this phone can do the check: Android 10+ and a screen lock (PIN, pattern, password or a finger) is set. */ + public static boolean available(Context context) { + if (Build.VERSION.SDK_INT < 29) return false; + try { + KeyguardManager keyguard = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE); + return keyguard != null && keyguard.isDeviceSecure(); + } catch (RuntimeException unknown) { + return false; + } + } + + /** Why the lock cannot be used here, in words for the person; null when it can. */ + public static String unavailableReason(Context context) { + if (Build.VERSION.SDK_INT < 29) return "Блокировка работает на Android 10 и новее"; + if (!available(context)) return "Сначала задайте блокировку экрана (отпечаток, PIN или пароль) в настройках телефона"; + return null; + } + + /** Shows the system window; one of the callbacks runs on the main thread. A wrong finger is not an answer: the window stays. */ + public static CancellationSignal ask(Activity activity, String title, String subtitle, final Result result) { + try { + BiometricPrompt.Builder builder = new BiometricPrompt.Builder(activity).setTitle(title); + if (subtitle != null) builder.setSubtitle(subtitle); + if (Build.VERSION.SDK_INT >= 30) { + builder.setAllowedAuthenticators(BiometricManager.Authenticators.BIOMETRIC_WEAK | BiometricManager.Authenticators.DEVICE_CREDENTIAL); + } else { + builder.setDeviceCredentialAllowed(true); + } + BiometricPrompt prompt = builder.build(); + CancellationSignal signal = new CancellationSignal(); + prompt.authenticate(signal, activity.getMainExecutor(), new BiometricPrompt.AuthenticationCallback() { + @Override public void onAuthenticationSucceeded(BiometricPrompt.AuthenticationResult answer) { + result.ok(); + } + + @Override public void onAuthenticationFailed() { + result.miss(); + } + + @Override public void onAuthenticationError(int code, CharSequence message) { + result.failed(message == null ? "" : message.toString()); + } + }); + return signal; + } catch (Throwable error) { + try { + Log.w(TAG, "lock: the phone's unlock window did not open: " + error); + } catch (Throwable noLogger) { + // diagnostic only + } + result.failed("Не удалось открыть проверку телефона"); + return null; + } + } +} diff --git a/src/lihont/two/privacy/IntruderCamera.java b/src/lihont/two/privacy/IntruderCamera.java new file mode 100644 index 0000000..a6f1d4d --- /dev/null +++ b/src/lihont/two/privacy/IntruderCamera.java @@ -0,0 +1,295 @@ +package lihont.two.privacy; + +import android.Manifest; +import android.app.Activity; +import android.content.Context; +import android.content.pm.PackageManager; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.graphics.ImageFormat; +import android.graphics.Matrix; +import android.graphics.Rect; +import android.graphics.YuvImage; +import android.hardware.camera2.CameraAccessException; +import android.hardware.camera2.CameraCaptureSession; +import android.hardware.camera2.CameraCharacteristics; +import android.hardware.camera2.CameraDevice; +import android.hardware.camera2.CameraManager; +import android.hardware.camera2.CaptureRequest; +import android.hardware.camera2.params.StreamConfigurationMap; +import android.media.Image; +import android.media.ImageReader; +import android.os.Handler; +import android.os.HandlerThread; +import android.os.Looper; +import android.os.SystemClock; +import android.util.Log; +import android.util.Size; +import android.view.Surface; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.nio.ByteBuffer; +import java.util.Collections; +import java.util.concurrent.atomic.AtomicBoolean; + +/** + * One quiet picture from the front camera, for the journal of entries: no preview, no shutter sound, a small JPEG into the private folder + * of the mod (never the gallery). The camera is asked for a moment so the exposure can settle, then one frame is kept. When the camera is + * busy (a face unlock, another app), the permission is missing or anything fails, the answer is simply "no picture": the lock never waits + * for it longer than a few seconds. + */ +public final class IntruderCamera { + private static final String TAG = "LIHONT"; + private static final long TIMEOUT_MS = 3500L; + + public interface Done { + /** The file of the picture, or null; runs on the main thread. */ + void done(File photo); + } + + private IntruderCamera() {} + + public static boolean allowed(Context context) { + return context.checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED; + } + + public static void snap(final Activity activity, final long id, final Done done) { + final Handler main = new Handler(Looper.getMainLooper()); + final AtomicBoolean finished = new AtomicBoolean(); + final Runnable[] cleanup = new Runnable[1]; + final Done once = new Done() { + @Override public void done(final File photo) { + if (!finished.compareAndSet(false, true)) return; + if (cleanup[0] != null) cleanup[0].run(); + main.post(new Runnable() { + @Override public void run() { + done.done(photo); + } + }); + } + }; + try { + if (!allowed(activity)) { + once.done(null); + return; + } + final Context app = activity.getApplicationContext() != null ? activity.getApplicationContext() : activity; + final CameraManager manager = (CameraManager) app.getSystemService(Context.CAMERA_SERVICE); + String front = null; + int sensor = 0; + CameraCharacteristics chosen = null; + for (String cameraId : manager.getCameraIdList()) { + CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId); + Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING); + if (facing != null && facing.intValue() == CameraCharacteristics.LENS_FACING_FRONT) { + front = cameraId; + chosen = characteristics; + Integer orientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION); + sensor = orientation == null ? 0 : orientation.intValue(); + break; + } + } + if (front == null) { + once.done(null); + return; + } + StreamConfigurationMap map = chosen.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP); + Size size = pick(map == null ? null : map.getOutputSizes(ImageFormat.YUV_420_888)); + if (size == null) { + once.done(null); + return; + } + int display = 0; + switch (activity.getWindowManager().getDefaultDisplay().getRotation()) { + case Surface.ROTATION_90: + display = 90; + break; + case Surface.ROTATION_180: + display = 180; + break; + case Surface.ROTATION_270: + display = 270; + break; + default: + display = 0; + } + final int turn = (sensor - display + 360) % 360; + final File file = new File(LockJournal.photoDir(app), "p" + id + ".jpg"); + final HandlerThread thread = new HandlerThread("lihont-lock-camera"); + thread.start(); + final Handler handler = new Handler(thread.getLooper()); + final ImageReader reader = ImageReader.newInstance(size.getWidth(), size.getHeight(), ImageFormat.YUV_420_888, 2); + final CameraDevice[] camera = new CameraDevice[1]; + final CameraCaptureSession[] session = new CameraCaptureSession[1]; + final long[] started = new long[1]; + final int[] frames = new int[1]; + cleanup[0] = new Runnable() { + @Override public void run() { + try { + if (session[0] != null) session[0].close(); + } catch (Throwable ignored) { + // already closed + } + try { + if (camera[0] != null) camera[0].close(); + } catch (Throwable ignored) { + // already closed + } + try { + reader.close(); + } catch (Throwable ignored) { + // already closed + } + thread.quitSafely(); + } + }; + reader.setOnImageAvailableListener(new ImageReader.OnImageAvailableListener() { + @Override public void onImageAvailable(ImageReader source) { + if (finished.get()) return; + Image image = null; + File result = null; + boolean keep = false; + try { + image = source.acquireLatestImage(); + if (image == null) return; + frames[0]++; + // the first frames are dark: the exposure needs a moment to settle + if (frames[0] < 6 || SystemClock.uptimeMillis() - started[0] < 600L) return; + keep = true; + result = save(image, turn, file); + } catch (Throwable error) { + keep = true; + result = null; + } finally { + try { + if (image != null) image.close(); + } catch (Throwable ignored) { + // already closed + } + } + if (keep) once.done(result); + } + }, handler); + handler.postDelayed(new Runnable() { + @Override public void run() { + once.done(null); + } + }, TIMEOUT_MS); + manager.openCamera(front, new CameraDevice.StateCallback() { + @Override public void onOpened(final CameraDevice device) { + camera[0] = device; + try { + device.createCaptureSession(Collections.singletonList(reader.getSurface()), new CameraCaptureSession.StateCallback() { + @Override public void onConfigured(CameraCaptureSession configured) { + session[0] = configured; + try { + CaptureRequest.Builder request = device.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW); + request.addTarget(reader.getSurface()); + request.set(CaptureRequest.CONTROL_MODE, CaptureRequest.CONTROL_MODE_AUTO); + started[0] = SystemClock.uptimeMillis(); + configured.setRepeatingRequest(request.build(), null, handler); + } catch (Throwable error) { + once.done(null); + } + } + + @Override public void onConfigureFailed(CameraCaptureSession failed) { + once.done(null); + } + }, handler); + } catch (Throwable error) { + once.done(null); + } + } + + @Override public void onDisconnected(CameraDevice device) { + once.done(null); + } + + @Override public void onError(CameraDevice device, int error) { + once.done(null); + } + }, handler); + } catch (CameraAccessException | SecurityException busy) { + once.done(null); + } catch (Throwable error) { + try { + Log.w(TAG, "lock: no picture: " + error); + } catch (Throwable noLogger) { + // diagnostic only + } + once.done(null); + } + } + + /** The smallest size that is at least 640 wide and not bigger than 1280, else the biggest below that. */ + private static Size pick(Size[] sizes) { + if (sizes == null || sizes.length == 0) return null; + Size best = null; + for (Size size : sizes) { + int w = Math.max(size.getWidth(), size.getHeight()); + if (w >= 640 && w <= 1280 && (best == null || w < Math.max(best.getWidth(), best.getHeight()))) best = size; + } + if (best != null) return best; + for (Size size : sizes) { + if (best == null || size.getWidth() > best.getWidth()) best = size; + } + return best; + } + + /** A frame of the camera into an upright, mirrored (like a mirror) JPEG of at most 640 pixels. */ + private static File save(Image image, int turn, File file) throws Exception { + int w = image.getWidth(); + int h = image.getHeight(); + YuvImage yuv = new YuvImage(nv21(image), ImageFormat.NV21, w, h, null); + ByteArrayOutputStream raw = new ByteArrayOutputStream(); + yuv.compressToJpeg(new Rect(0, 0, w, h), 85, raw); + Bitmap bitmap = BitmapFactory.decodeByteArray(raw.toByteArray(), 0, raw.size()); + if (bitmap == null) return null; + Matrix matrix = new Matrix(); + matrix.postRotate(turn); + matrix.postScale(-1f, 1f); + float scale = 640f / Math.max(w, h); + if (scale < 1f) matrix.postScale(scale, scale); + Bitmap upright = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); + FileOutputStream out = new FileOutputStream(file); + try { + upright.compress(Bitmap.CompressFormat.JPEG, 78, out); + } finally { + out.close(); + } + if (upright != bitmap) upright.recycle(); + bitmap.recycle(); + return file; + } + + private static byte[] nv21(Image image) { + int w = image.getWidth(); + int h = image.getHeight(); + Image.Plane[] planes = image.getPlanes(); + byte[] out = new byte[w * h * 3 / 2]; + ByteBuffer y = planes[0].getBuffer(); + int yStride = planes[0].getRowStride(); + int pos = 0; + for (int row = 0; row < h; row++) { + y.position(row * yStride); + y.get(out, pos, w); + pos += w; + } + ByteBuffer u = planes[1].getBuffer(); + ByteBuffer v = planes[2].getBuffer(); + int uRow = planes[1].getRowStride(); + int uPixel = planes[1].getPixelStride(); + int vRow = planes[2].getRowStride(); + int vPixel = planes[2].getPixelStride(); + for (int row = 0; row < h / 2; row++) { + for (int col = 0; col < w / 2; col++) { + out[pos++] = v.get(row * vRow + col * vPixel); // NV21 wants V before U + out[pos++] = u.get(row * uRow + col * uPixel); + } + } + return out; + } +} diff --git a/src/lihont/two/privacy/LockJournal.java b/src/lihont/two/privacy/LockJournal.java new file mode 100644 index 0000000..c03c308 --- /dev/null +++ b/src/lihont/two/privacy/LockJournal.java @@ -0,0 +1,196 @@ +package lihont.two.privacy; + +import android.content.Context; +import android.content.SharedPreferences; + +import org.json.JSONArray; +import org.json.JSONObject; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +/** + * The journal of entries: every time the lock stood in front of somebody, when it was, what came of it (opened, not opened, how many wrong + * fingers), which lock it was, which chats were opened during that visit and the front-camera picture, if the person asked for pictures. + * + * It lives only on the phone. The pictures are in a private folder of the mod (not in the gallery, no other app can see them); the + * journal keeps at most 100 entries and nothing older than 30 days, and "clear all" removes every entry and every picture at once. + */ +public final class LockJournal { + private static final String PREFS = "lihont_lock_journal"; + private static final String ENTRIES = "entries"; + private static final int MAX_ENTRIES = 100; + private static final long MAX_AGE_MS = 30L * 24L * 3600L * 1000L; + + private LockJournal() {} + + /** One entry as it is shown. */ + public static final class Entry { + public long id; + public long time; + public String key = ""; // "app", "chats", "chat:" + public String name = ""; // the person of a chat lock + public String result = "shown"; // shown, opened, cancelled, failed + public String why = ""; + public int misses; + public String photo = ""; // file name in the picture folder + public final List chats = new ArrayList(); + } + + private static SharedPreferences prefs(Context context) { + return context.getSharedPreferences(PREFS, Context.MODE_PRIVATE); + } + + public static File photoDir(Context context) { + File dir = new File(context.getFilesDir(), "lock_photos"); + if (!dir.isDirectory()) dir.mkdirs(); + return dir; + } + + private static JSONArray read(Context context) { + try { + return new JSONArray(prefs(context).getString(ENTRIES, "[]")); + } catch (Exception broken) { + return new JSONArray(); + } + } + + private static void write(Context context, JSONArray array) { + prefs(context).edit().putString(ENTRIES, array.toString()).apply(); + } + + /** A new entry: returns its id. Old ones are cleared away first. */ + public static synchronized long begin(Context context, String key, String name) { + prune(context); + JSONArray array = read(context); + long id = System.currentTimeMillis(); + try { + JSONObject one = new JSONObject(); + one.put("id", id).put("time", id).put("key", key).put("name", name == null ? "" : name).put("result", "shown"); + array.put(one); + write(context, array); + } catch (Exception ignored) { + // the journal is an extra + } + return id; + } + + private static void change(Context context, long id, String field, Object value) { + JSONArray array = read(context); + try { + for (int i = 0; i < array.length(); i++) { + JSONObject one = array.getJSONObject(i); + if (one.optLong("id") == id) { + one.put(field, value); + write(context, array); + return; + } + } + } catch (Exception ignored) { + // the journal is an extra + } + } + + public static synchronized void result(Context context, long id, String result, String why) { + change(context, id, "result", result); + change(context, id, "why", why == null ? "" : why); + } + + public static synchronized void miss(Context context, long id) { + JSONArray array = read(context); + try { + for (int i = 0; i < array.length(); i++) { + JSONObject one = array.getJSONObject(i); + if (one.optLong("id") == id) { + one.put("misses", one.optInt("misses") + 1); + write(context, array); + return; + } + } + } catch (Exception ignored) { + // the journal is an extra + } + } + + public static synchronized void photo(Context context, long id, String file) { + change(context, id, "photo", file); + } + + /** A chat that was opened during this visit (one name once). */ + public static synchronized void chat(Context context, long id, String name) { + JSONArray array = read(context); + try { + for (int i = 0; i < array.length(); i++) { + JSONObject one = array.getJSONObject(i); + if (one.optLong("id") != id) continue; + JSONArray chats = one.optJSONArray("chats"); + if (chats == null) chats = new JSONArray(); + for (int k = 0; k < chats.length(); k++) if (name.equals(chats.optString(k))) return; + if (chats.length() < 30) chats.put(name); + one.put("chats", chats); + write(context, array); + return; + } + } catch (Exception ignored) { + // the journal is an extra + } + } + + /** The entries, the newest first. */ + public static synchronized List list(Context context) { + List out = new ArrayList(); + JSONArray array = read(context); + for (int i = array.length() - 1; i >= 0; i--) { + JSONObject one = array.optJSONObject(i); + if (one == null) continue; + Entry entry = new Entry(); + entry.id = one.optLong("id"); + entry.time = one.optLong("time"); + entry.key = one.optString("key", ""); + entry.name = one.optString("name", ""); + entry.result = one.optString("result", "shown"); + entry.why = one.optString("why", ""); + entry.misses = one.optInt("misses"); + entry.photo = one.optString("photo", ""); + JSONArray chats = one.optJSONArray("chats"); + if (chats != null) for (int k = 0; k < chats.length(); k++) entry.chats.add(chats.optString(k)); + out.add(entry); + } + return out; + } + + public static synchronized int count(Context context) { + return read(context).length(); + } + + /** Everything goes: every entry and every picture. */ + public static synchronized void clearAll(Context context) { + prefs(context).edit().remove(ENTRIES).apply(); + File[] files = photoDir(context).listFiles(); + if (files != null) for (File file : files) file.delete(); + } + + /** At most 100 entries and none older than 30 days; a picture goes with its entry. */ + private static void prune(Context context) { + JSONArray array = read(context); + long now = System.currentTimeMillis(); + JSONArray kept = new JSONArray(); + List alive = new ArrayList(); + try { + int from = Math.max(0, array.length() - (MAX_ENTRIES - 1)); + for (int i = from; i < array.length(); i++) { + JSONObject one = array.getJSONObject(i); + if (now - one.optLong("time") > MAX_AGE_MS) continue; + kept.put(one); + String photo = one.optString("photo", ""); + if (!photo.isEmpty()) alive.add(photo); + } + } catch (Exception ignored) { + return; + } + if (kept.length() != array.length()) write(context, kept); + File[] files = photoDir(context).listFiles(); + if (files != null) for (File file : files) if (!alive.contains(file.getName())) file.delete(); + } +} diff --git a/src/lihont/two/privacy/LockSettings.java b/src/lihont/two/privacy/LockSettings.java new file mode 100644 index 0000000..7869665 --- /dev/null +++ b/src/lihont/two/privacy/LockSettings.java @@ -0,0 +1,119 @@ +package lihont.two.privacy; + +import android.content.Context; +import android.content.SharedPreferences; + +import java.util.HashSet; +import java.util.Set; + +/** + * What the lock covers and when it asks again. A choice about the app and not about one account, so it lives in a small file of its own + * (like the ghost switches). Off by default. + */ +public final class LockSettings { + public static final int OFF = 0; // nothing is locked + public static final int APP = 1; // the whole of TikTok + public static final int CHATS = 2; // every chat screen + public static final int CHOSEN = 3; // the chats of the people picked in the settings + + /** The ways to say "ask again": after this long away. The first is "at once"; a screen change inside the app is never "away". */ + public static final long[] TIMEOUTS = {0L, 60_000L, 5 * 60_000L, 15 * 60_000L}; + public static final String[] TIMEOUT_NAMES = {"сразу", "через минуту", "через 5 минут", "через 15 минут"}; + + private static final String PREFS = "lihont_lock"; + private static final String MODE = "mode"; + private static final String TIMEOUT = "timeout"; + private static final String CHOSEN_SET = "chosen"; + private static final String RECENTS = "recents"; + private static final String PHOTO = "photo"; + + private LockSettings() {} + + private static SharedPreferences prefs(Context context) { + return context.getSharedPreferences(PREFS, Context.MODE_PRIVATE); + } + + public static int mode(Context context) { + try { + int mode = prefs(context).getInt(MODE, OFF); + return mode >= OFF && mode <= CHOSEN ? mode : OFF; + } catch (RuntimeException unreadable) { + return OFF; + } + } + + public static void setMode(Context context, int mode) { + prefs(context).edit().putInt(MODE, mode).apply(); + } + + public static long timeoutMs(Context context) { + try { + long value = prefs(context).getLong(TIMEOUT, 60_000L); + for (long known : TIMEOUTS) if (known == value) return value; + } catch (RuntimeException unreadable) { + // the default below + } + return 60_000L; + } + + public static void setTimeoutMs(Context context, long value) { + prefs(context).edit().putLong(TIMEOUT, value).apply(); + } + + /** The people (account numbers) whose chats are locked while the mode is CHOSEN. */ + public static Set chosen(Context context) { + try { + return new HashSet(prefs(context).getStringSet(CHOSEN_SET, new HashSet())); + } catch (RuntimeException unreadable) { + return new HashSet(); + } + } + + public static void setChosen(Context context, String uid, boolean locked) { + Set now = chosen(context); + if (locked) now.add(uid); + else now.remove(uid); + prefs(context).edit().putStringSet(CHOSEN_SET, now).apply(); + } + + /** The screens are hidden from the list of recent apps and from screenshots (the window flag "secure"). */ + public static boolean hideRecents(Context context) { + try { + return prefs(context).getBoolean(RECENTS, false); + } catch (RuntimeException unreadable) { + return false; + } + } + + public static void setHideRecents(Context context, boolean on) { + prefs(context).edit().putBoolean(RECENTS, on).apply(); + } + + /** Every entry is photographed with the front camera into the private journal (never into the gallery). */ + public static boolean photoOn(Context context) { + try { + return prefs(context).getBoolean(PHOTO, false); + } catch (RuntimeException unreadable) { + return false; + } + } + + public static void setPhoto(Context context, boolean on) { + prefs(context).edit().putBoolean(PHOTO, on).apply(); + } + + /** One line for the settings row. */ + public static String summary(Context context) { + switch (mode(context)) { + case APP: + return "Весь TikTok: отпечаток или пароль телефона"; + case CHATS: + return "Все чаты: отпечаток или пароль телефона"; + case CHOSEN: + int n = chosen(context).size(); + return "Выбранные чаты (" + n + "): отпечаток или пароль телефона"; + default: + return "Выключена. Закрыть TikTok или чаты отпечатком и паролем телефона"; + } + } +} diff --git a/src/lihont/two/settings/LihonTSettingsActivity.java b/src/lihont/two/settings/LihonTSettingsActivity.java index 8975a22..1a545e3 100644 --- a/src/lihont/two/settings/LihonTSettingsActivity.java +++ b/src/lihont/two/settings/LihonTSettingsActivity.java @@ -46,13 +46,17 @@ import java.util.Locale; /** Material 3 settings screen for LihonT 2. */ public final class LihonTSettingsActivity extends Activity { - private static final String VERSION_LINE = "LihonT 3 · Luna pre-alpha"; + private static final String VERSION_LINE = "LihonT 3 · Luna alpha 1"; 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 = - "• Звери Серийчика: котёнок, щенок или львёнок вместо обычного Серийчика в чате и на экране серии. Растёт с серией (0, 7, 30, 100 дней), сереет, когда серия вот-вот сгорит, его можно перетаскивать. Зверя дарят ссылкой: Настройки мода → Серийчик." + "• Блокировка (Приватность): весь TikTok, все чаты или выбранные чаты открываются отпечатком, лицом или паролем телефона. Время «спрашивать снова» на выбор, превью в недавних можно скрыть." + + "\n" + + "• Журнал входов: когда и кто пытался открыть, сколько было неверных попыток, какие чаты открывали. По желанию фронтальная камера снимает каждый вход; снимки лежат только в закрытой папке мода (не в галерее), есть кнопка «Очистить всё»." + + "\n" + + "• Звери Серийчика: котёнок, щенок или львёнок вместо обычного Серийчика в чате и на экране серии. Растёт с серией (0, 7, 30, 100 дней), сереет, когда серия вот-вот сгорит, его можно перетаскивать. Зверя дарят ссылкой: Настройки мода → Серийчик." + "\n" + "• LihonT Store: отдельное приложение с каталогом рамок и пузырей чата от людей. Добавляете вещь кнопкой «+», и она появляется в моде (рамка в выборе рамок, пузырь в настройках чата). Свои работы публикуются там же, сначала их проверяют." + "\n" @@ -225,6 +229,8 @@ public final class LihonTSettingsActivity extends Activity { cardPrivacy.addView(ghostStoriesRow()); cardPrivacy.addView(Md3.cardDivider(this, palette)); cardPrivacy.addView(ghostMessagesRow()); + cardPrivacy.addView(Md3.cardDivider(this, palette)); + cardPrivacy.addView(lockRow()); addSection("Приватность", cardPrivacy, false); LinearLayout cardDebug = Md3.card(this, palette); @@ -692,6 +698,267 @@ public final class LihonTSettingsActivity extends Activity { return row; } + + // ---- the lock: TikTok, every chat or chosen chats, opened by the phone's own fingerprint / face / lock-screen code + + private TextView lockSummary; + + private View lockRow() { + lockSummary = null; + LinearLayout row = Md3.listItem(this, palette, + Md3.flowerIconAvatar(this, palette.primaryContainer, Md3Icon.LOCK, palette.onPrimaryContainer, 8), + "Блокировка", lihont.two.privacy.LockSettings.summary(this), Md3.chevron(this, palette), true); + row.setOnClickListener(v -> openLockSettings()); + return row; + } + + /** Opening the settings of a lock that is on needs the phone's unlock too, so nobody can simply switch it off. */ + private void openLockSettings() { + String why = lihont.two.privacy.Authenticator.unavailableReason(this); + if (why != null) { + Toast.makeText(this, why, Toast.LENGTH_LONG).show(); + return; + } + if (lihont.two.privacy.LockSettings.mode(this) == lihont.two.privacy.LockSettings.OFF) { + showLockSettings(); + return; + } + lihont.two.privacy.Authenticator.ask(this, "Настройки блокировки", "Подтвердите, что это вы", new lihont.two.privacy.Authenticator.Result() { + @Override public void ok() { + showLockSettings(); + } + + @Override public void failed(String reason) { + if (reason != null && !reason.isEmpty()) Toast.makeText(LihonTSettingsActivity.this, reason, Toast.LENGTH_SHORT).show(); + } + }); + } + + private void showLockSettings() { + final LinearLayout box = new LinearLayout(this); + box.setOrientation(LinearLayout.VERTICAL); + final Dialog[] shown = new Dialog[1]; + fillLock(box, shown); + ScrollView scroll = new ScrollView(this); + scroll.addView(box, new ScrollView.LayoutParams(-1, -2)); + shown[0] = bubbleDialog("Блокировка", scroll, null, null); + shown[0].setOnDismissListener(d -> recreate()); + } + + private void fillLock(final LinearLayout box, final Dialog[] shown) { + box.removeAllViews(); + final int mode = lihont.two.privacy.LockSettings.mode(this); + box.addView(Md3.text(this, "Что закрывать", Md3.LABEL_LARGE, false, palette.primary)); + String[] names = {"Выключена", "Весь TikTok", "Все чаты", "Выбранные чаты"}; + for (int i = 0; i < names.length; i++) { + final int choice = i; + box.addView(lockChoice(names[i], mode == i, v -> chooseLockMode(choice, box, shown))); + } + if (mode == lihont.two.privacy.LockSettings.CHOSEN) { + TextView pick = Md3.textButton(this, palette, "Выбрать чаты (" + lihont.two.privacy.LockSettings.chosen(this).size() + ")"); + pick.setOnClickListener(v -> askLockedChats(box, shown)); + box.addView(pick); + box.addView(Md3.text(this, "Если приложение не поймёт, с кем чат, оно закроет его на всякий случай. Человека в списке нет: откройте " + + "его чат один раз.", Md3.BODY_SMALL, false, palette.onSurfaceVariant)); + } + if (mode != lihont.two.privacy.LockSettings.OFF) { + TextView head = Md3.text(this, "Спрашивать снова", Md3.LABEL_LARGE, false, palette.primary); + head.setPadding(0, Md3.dp(this, 14), 0, 0); + box.addView(head); + long now = lihont.two.privacy.LockSettings.timeoutMs(this); + for (int i = 0; i < lihont.two.privacy.LockSettings.TIMEOUTS.length; i++) { + final long value = lihont.two.privacy.LockSettings.TIMEOUTS[i]; + box.addView(lockChoice(lihont.two.privacy.LockSettings.TIMEOUT_NAMES[i], now == value, v -> { + lihont.two.privacy.LockSettings.setTimeoutMs(this, value); + fillLock(box, shown); + })); + } + box.addView(Md3.text(this, "Время считается с того момента, как вы ушли с экрана. Переход между экранами внутри приложения " + + "не считается уходом.", Md3.BODY_SMALL, false, palette.onSurfaceVariant)); + Md3Switch hide = new Md3Switch(this, palette); + hide.setContentDescription("Скрывать в недавних"); + hide.setChecked(lihont.two.privacy.LockSettings.hideRecents(this), false); + hide.setOnCheckedChangeListener((view, value) -> lihont.two.privacy.LockSettings.setHideRecents(this, value)); + LinearLayout row = Md3.listItem(this, palette, null, "Скрывать в недавних", + "Превью TikTok не видно в списке запущенных приложений. Скриншоты и запись экрана тоже не работают", hide, true); + row.setOnClickListener(v -> hide.toggle()); + box.addView(row); + Md3Switch photo = new Md3Switch(this, palette); + photo.setContentDescription("Фото при входе"); + photo.setChecked(lihont.two.privacy.LockSettings.photoOn(this), false); + photo.setOnCheckedChangeListener((view, value) -> togglePhoto(value, box, shown)); + LinearLayout photoRow = Md3.listItem(this, palette, null, "Фото при входе", + "Фронтальная камера снимает каждый вход, и открывший, и не открывший. Снимки лежат только в закрытой папке мода, " + + "в галерею не попадают", photo, true); + photoRow.setOnClickListener(v -> photo.toggle()); + box.addView(photoRow); + TextView journal = Md3.textButton(this, palette, "Журнал входов (" + lihont.two.privacy.LockJournal.count(this) + ")"); + journal.setOnClickListener(v -> showLockJournal()); + box.addView(journal); + } + } + + private static final int REQUEST_LOCK_CAMERA = 4110; + private LinearLayout pendingLockBox; + private Dialog[] pendingLockShown; + + /** The pictures need the camera permission; it is asked for once, when the switch goes on. */ + private void togglePhoto(boolean on, LinearLayout box, Dialog[] shown) { + if (!on) { + lihont.two.privacy.LockSettings.setPhoto(this, false); + return; + } + if (lihont.two.privacy.IntruderCamera.allowed(this)) { + lihont.two.privacy.LockSettings.setPhoto(this, true); + return; + } + pendingLockBox = box; + pendingLockShown = shown; + requestPermissions(new String[] {android.Manifest.permission.CAMERA}, REQUEST_LOCK_CAMERA); + } + + @Override public void onRequestPermissionsResult(int code, String[] permissions, int[] results) { + super.onRequestPermissionsResult(code, permissions, results); + if (code != REQUEST_LOCK_CAMERA) return; + boolean granted = results.length > 0 && results[0] == android.content.pm.PackageManager.PERMISSION_GRANTED; + lihont.two.privacy.LockSettings.setPhoto(this, granted); + if (!granted) Toast.makeText(this, "Без разрешения камеры снимки не делаются", Toast.LENGTH_LONG).show(); + if (pendingLockBox != null && pendingLockShown != null) fillLock(pendingLockBox, pendingLockShown); + } + + /** Who stood in front of the lock: when, what came of it, the chats opened and the picture. Opening this window needed the unlock too. */ + private void showLockJournal() { + LinearLayout list = new LinearLayout(this); + list.setOrientation(LinearLayout.VERTICAL); + java.util.List entries = lihont.two.privacy.LockJournal.list(this); + if (entries.isEmpty()) { + list.addView(Md3.text(this, "Пока пусто. Записи появятся, когда замок встретит вход.", Md3.BODY_MEDIUM, false, palette.onSurfaceVariant)); + } + java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("d MMM, HH:mm", new java.util.Locale("ru")); + int shown = 0; + for (lihont.two.privacy.LockJournal.Entry entry : entries) { + if (shown++ >= 50) break; + list.addView(journalRow(entry, format)); + } + ScrollView scroll = new ScrollView(this); + scroll.addView(list, new ScrollView.LayoutParams(-1, -2)); + bubbleDialog("Журнал входов", scroll, entries.isEmpty() ? null : "Очистить всё", () -> basicDialog("Очистить журнал?", + "Все записи и все снимки будут удалены. Это нельзя отменить.", "Отмена", "Очистить", () -> { + lihont.two.privacy.LockJournal.clearAll(this); + Toast.makeText(this, "Журнал очищен", Toast.LENGTH_SHORT).show(); + })); + } + + private View journalRow(lihont.two.privacy.LockJournal.Entry entry, java.text.SimpleDateFormat format) { + LinearLayout row = new LinearLayout(this); + row.setOrientation(LinearLayout.HORIZONTAL); + row.setPadding(0, Md3.dp(this, 10), 0, Md3.dp(this, 10)); + final java.io.File file = entry.photo.isEmpty() ? null : new java.io.File(lihont.two.privacy.LockJournal.photoDir(this), entry.photo); + if (file != null && file.isFile()) { + android.graphics.BitmapFactory.Options options = new android.graphics.BitmapFactory.Options(); + options.inSampleSize = 4; + android.graphics.Bitmap small = android.graphics.BitmapFactory.decodeFile(file.getPath(), options); + if (small != null) { + android.widget.ImageView picture = new android.widget.ImageView(this); + picture.setImageBitmap(small); + picture.setScaleType(android.widget.ImageView.ScaleType.CENTER_CROP); + picture.setClipToOutline(true); + picture.setBackground(Md3.shape(palette.surfaceContainerHighest, Md3.dp(this, 12), this)); + picture.setOnClickListener(v -> showLockPhoto(file)); + row.addView(picture, new LinearLayout.LayoutParams(Md3.dp(this, 72), Md3.dp(this, 72))); + } + } + LinearLayout text = new LinearLayout(this); + text.setOrientation(LinearLayout.VERTICAL); + text.setPadding(Md3.dp(this, 12), 0, 0, 0); + String result = "opened".equals(entry.result) ? "Открыто" : "failed".equals(entry.result) ? "Не открыто" : "Не ответили"; + text.addView(Md3.text(this, format.format(new java.util.Date(entry.time)) + " · " + result, Md3.BODY_LARGE, false, palette.onSurface)); + String lock = "app".equals(entry.key) ? "Весь TikTok" : "chats".equals(entry.key) ? "Все чаты" + : entry.name.isEmpty() ? "Чат" : "Чат: " + entry.name; + text.addView(Md3.text(this, lock, Md3.BODY_SMALL, false, palette.onSurfaceVariant)); + if (entry.misses > 0) { + text.addView(Md3.text(this, "Неверных попыток: " + entry.misses, Md3.BODY_SMALL, false, palette.onSurfaceVariant)); + } + if (!entry.chats.isEmpty()) { + text.addView(Md3.text(this, "Открывал чаты: " + android.text.TextUtils.join(", ", entry.chats), Md3.BODY_SMALL, false, + palette.onSurfaceVariant)); + } + row.addView(text, new LinearLayout.LayoutParams(0, -2, 1f)); + return row; + } + + /** One picture, large. */ + private void showLockPhoto(java.io.File file) { + android.graphics.Bitmap bitmap = android.graphics.BitmapFactory.decodeFile(file.getPath()); + if (bitmap == null) return; + android.widget.ImageView view = new android.widget.ImageView(this); + view.setImageBitmap(bitmap); + view.setAdjustViewBounds(true); + bubbleDialog("Снимок", view, null, null); + } + + private View lockChoice(String label, boolean selected, View.OnClickListener onClick) { + TextView item = Md3.text(this, (selected ? "● " : "○ ") + label, Md3.BODY_LARGE, false, selected ? palette.primary : palette.onSurface); + item.setPadding(Md3.dp(this, 8), Md3.dp(this, 12), Md3.dp(this, 8), Md3.dp(this, 12)); + item.setBackground(Md3.stateLayer(this, Md3.SHAPE_EXTRA_SMALL, Md3.stateLayerColor(palette.onSurface))); + item.setClickable(true); + item.setOnClickListener(onClick); + return item; + } + + /** Turning the lock on is proved with the phone's unlock once, so a wrong choice cannot lock the person out. */ + private void chooseLockMode(final int choice, final LinearLayout box, final Dialog[] shown) { + if (choice == lihont.two.privacy.LockSettings.mode(this)) return; + if (choice == lihont.two.privacy.LockSettings.OFF) { + lihont.two.privacy.LockSettings.setMode(this, choice); + fillLock(box, shown); + return; + } + lihont.two.privacy.Authenticator.ask(this, "Включить блокировку", "Подтвердите, что это вы", new lihont.two.privacy.Authenticator.Result() { + @Override public void ok() { + lihont.two.privacy.LockSettings.setMode(LihonTSettingsActivity.this, choice); + fillLock(box, shown); + if (choice == lihont.two.privacy.LockSettings.CHOSEN && lihont.two.privacy.LockSettings.chosen(LihonTSettingsActivity.this).isEmpty()) { + askLockedChats(box, shown); + } + } + + @Override public void failed(String reason) { + if (reason != null && !reason.isEmpty()) Toast.makeText(LihonTSettingsActivity.this, reason, Toast.LENGTH_SHORT).show(); + } + }); + } + + /** The people whose chats are locked: a tick on each. */ + private void askLockedChats(final LinearLayout parentBox, final Dialog[] parent) { + LinearLayout list = new LinearLayout(this); + list.setOrientation(LinearLayout.VERTICAL); + final java.util.Set picked = lihont.two.privacy.LockSettings.chosen(this); + int count = 0; + for (final String[] candidate : pairCandidates()) { + final String uid = candidate[0]; + count++; + final TextView item = Md3.text(this, (picked.contains(uid) ? "☑ " : "☐ ") + candidate[1], Md3.BODY_LARGE, false, palette.onSurface); + item.setPadding(Md3.dp(this, 8), Md3.dp(this, 14), Md3.dp(this, 8), Md3.dp(this, 14)); + item.setBackground(Md3.stateLayer(this, Md3.SHAPE_EXTRA_SMALL, Md3.stateLayerColor(palette.onSurface))); + item.setClickable(true); + item.setOnClickListener(v -> { + boolean now = !lihont.two.privacy.LockSettings.chosen(this).contains(uid); + lihont.two.privacy.LockSettings.setChosen(this, uid, now); + item.setText((now ? "☑ " : "☐ ") + candidate[1]); + }); + list.addView(item); + } + if (count == 0) { + list.addView(Md3.text(this, "Пока никого. Откройте чат с человеком или полистайте список чатов, и он появится здесь.", Md3.BODY_MEDIUM, + false, palette.onSurfaceVariant)); + } + ScrollView scroll = new ScrollView(this); + scroll.addView(list, new ScrollView.LayoutParams(-1, -2)); + Dialog dialog = bubbleDialog("Какие чаты закрыть", scroll, null, null); + dialog.setOnDismissListener(d -> fillLock(parentBox, parent)); + } + private static final int REQUEST_BUBBLE = 4102; private static final int REQUEST_FRAME = 4103; private static final int REQUEST_PAIR = 4104; @@ -1363,7 +1630,8 @@ public final class LihonTSettingsActivity extends Activity { + "он нажмёт «Принять» (ему нужен мод).", Md3.BODY_SMALL, false, palette.onSurfaceVariant)); LinearLayout gifts = new LinearLayout(this); gifts.setOrientation(LinearLayout.HORIZONTAL); - for (final String kind : lihont.two.pet.Species.KINDS) { + lihont.two.pet.Species.refreshCatalog(this); + for (final String kind : lihont.two.pet.Species.kinds()) { TextView give = Md3.textButton(this, palette, Character.toUpperCase(lihont.two.pet.Species.label(kind).charAt(0)) + lihont.two.pet.Species.label(kind).substring(1)); give.setOnClickListener(v -> giveAnimal(peer, kind)); diff --git a/src/lihont/two/settings/Md3Icon.java b/src/lihont/two/settings/Md3Icon.java index 0b2ab65..1a54f15 100644 --- a/src/lihont/two/settings/Md3Icon.java +++ b/src/lihont/two/settings/Md3Icon.java @@ -39,6 +39,7 @@ public final class Md3Icon extends Drawable { public static final int SHOP = 19; public static final int CODE = 20; public static final int FLAME = 21; + public static final int LOCK = 22; /** Path data in the order of the constants above. */ static final String[] PATHS = { @@ -167,13 +168,17 @@ public final class Md3Icon extends Drawable { // 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", + // lock + "M240-80q-33 0-56.5-23.5T160-160v-400q0-33 23.5-56.5T240-640h40v-80q0-83 58.5-141.5T480-920q83 0 141.5 58.5T680-720v80h40q33 " + + "0 56.5 23.5T800-560v400q0 33-23.5 56.5T720-80H240Zm0-80h480v-400H240v400Zm240-120q33 0 56.5-23.5T560-360q0-33-23.5-56.5T480-440q-33 " + + "0-56.5 23.5T400-360q0 33 23.5 56.5T480-280ZM360-640h240v-80q0-50-35-85t-85-35q-50 0-85 35t-35 85v80ZM240-160v-400 400Z", }; /** 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}; + 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, 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}; + 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, -960f}; private final float density; private final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); diff --git a/src/web/assets/pets/index.json b/src/web/assets/pets/index.json new file mode 100644 index 0000000..003fc4d --- /dev/null +++ b/src/web/assets/pets/index.json @@ -0,0 +1,20 @@ +{ + "version": 1, + "animals": [ + { + "id": "cat", + "label": "котёнок", + "gift": "котёнка" + }, + { + "id": "dog", + "label": "щенок", + "gift": "щенка" + }, + { + "id": "lion", + "label": "львёнок", + "gift": "львёнка" + } + ] +} diff --git a/src/web/assets/site/oa.css b/src/web/assets/site/oa.css index c8eb759..57c2e44 100644 --- a/src/web/assets/site/oa.css +++ b/src/web/assets/site/oa.css @@ -162,6 +162,10 @@ section.block { padding: 72px 0; } .file:hover { background: var(--soft-2); transform: translateX(4px); } .file small { display: block; font-weight: 400; color: var(--muted); } +.versions { display: grid; gap: 10px; grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); } +.file .tag { font-style: normal; font-size: .72rem; font-weight: 700; padding: 2px 9px; border-radius: 999px; background: var(--candy); color: #fff; margin-left: 6px; vertical-align: 2px; } +.note__tag img { width: 44px; height: 44px; object-fit: contain; } + /* community */ .comments { display: grid; gap: 14px; } .comment { display: flex; gap: 14px; padding: 18px; align-items: flex-start; border-radius: 24px; } diff --git a/src/web/index.html b/src/web/index.html index c96efef..854879c 100644 --- a/src/web/index.html +++ b/src/web/index.html @@ -6,12 +6,12 @@ - - - + + + - LihonT 2 · Luna: TikTok в стиле Material 3 + LihonT 3 · Luna: TikTok в стиле Material 3 diff --git a/tests/java/lihont/two/settings/IconRenderTest.java b/tests/java/lihont/two/settings/IconRenderTest.java index ee8956a..b8b1dd1 100644 --- a/tests/java/lihont/two/settings/IconRenderTest.java +++ b/tests/java/lihont/two/settings/IconRenderTest.java @@ -17,7 +17,7 @@ import javax.imageio.ImageIO; 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", + "SEND", "TIKTOK", "ADD_PHOTO", "DELETE", "BOTTOM_BAR", "DOWNLOAD", "AD_OFF", "LIVE", "SHOP", "CODE", "FLAME", "LOCK", }; /** Where each icon appears in the app, for the preview sheet. */