v0.23.0: Routine, first public version

This commit is contained in:
2026-11-15 02:22:09 -08:00
commit 5ea848bddc
285 changed files with 23886 additions and 0 deletions
+117
View File
@@ -0,0 +1,117 @@
#!/usr/bin/env python3
"""Build the R1 app without Gradle (shared-resources rabbit.html#toolchain).
aapt2 compile/link -> javac --release 11 -> d8 -> zipalign -> apksigner, then copy the APK
to android/apk/routine.apk with its version in apk/routine-apk.json (the desktop installs it).
python3 android/build.py the real app -> android/apk/routine.apk (committed)
python3 android/build.py --dev me.teafry.routine.dev, "Routine dev", own storage -> build/routine-dev.apk
"""
import datetime as dt
import glob
import json
import os
import shutil
import subprocess
import sys
import zipfile
VERSION_NAME = "0.17.0"
PKG = "me.teafry.routine"
HERE = os.path.dirname(os.path.abspath(__file__))
REPO = os.path.dirname(HERE)
SDK = os.environ.get("ANDROID_HOME", os.path.expanduser("~/Android/Sdk"))
JAVA = os.environ.get("JAVA_HOME", "/usr/lib/jvm/java-21-openjdk")
BT = os.path.join(SDK, "build-tools", "34.0.0")
JAR = os.path.join(SDK, "platforms", "android-33", "android.jar")
B = os.path.join(HERE, "build")
KEYSTORE = os.path.join(HERE, "routine.keystore")
KS_PASS = "routine-r1" # a sideloaded app: nothing for the key to protect (rabbit.html)
def run(*cmd):
env = dict(os.environ, JAVA_HOME=JAVA, PATH=os.path.join(JAVA, "bin") + os.pathsep + os.environ["PATH"])
r = subprocess.run(cmd, env=env, capture_output=True, text=True)
if r.returncode:
sys.exit("FAILED: %s\n%s%s" % (" ".join(cmd), r.stdout, r.stderr))
return r.stdout
def main():
dev = "--dev" in sys.argv
pkg, label = (PKG + ".dev", "Routine dev") if dev else (PKG, "Routine")
shutil.rmtree(B, ignore_errors=True)
for d in ("assets/sounds", "gen", "classes", "dex"):
os.makedirs(os.path.join(B, d))
for f in ("schedule.json", "animations.json"):
shutil.copy(os.path.join(REPO, "shared", f), os.path.join(B, "assets", f))
for f in glob.glob(os.path.join(REPO, "shared", "sounds", "*.wav")):
shutil.copy(f, os.path.join(B, "assets", "sounds"))
os.makedirs(os.path.join(B, "assets", "fonts"))
for f in glob.glob(os.path.join(REPO, "shared", "fonts", "*.ttf")): # Caveat: the note's title
shutil.copy(f, os.path.join(B, "assets", "fonts"))
edition = os.path.expanduser("~/.local/share/fonts/edition_.ttf") # the light look's date, if
if os.path.exists(edition): # this machine has it (not in
shutil.copy(edition, os.path.join(B, "assets", "fonts", "Edition.ttf")) # the repo: its licence is unknown)
# the tasks' font, as on the desktop: Century Gothic if this machine has it (not in the repo,
# it's licensed), else URW Gothic (free, from Fedora's urw-base35 fonts), else the system's
for src, name in ((os.path.expanduser("~/.local/share/fonts/GOTHIC.TTF"), "Tasks.ttf"),
("/usr/share/fonts/urw-base35/URWGothic-Book.otf", "Tasks.otf")):
if os.path.exists(src):
shutil.copy(src, os.path.join(B, "assets", "fonts", name))
break
with open(os.path.join(HERE, "src/main/AndroidManifest.xml")) as f:
manifest = f.read().replace("@PKG@", pkg).replace("@LABEL@", label)
with open(B + "/AndroidManifest.xml", "w") as f:
f.write(manifest)
code = int((dt.datetime.now() - dt.datetime(2026, 1, 1)).total_seconds() // 60)
run(os.path.join(BT, "aapt2"), "compile", "--dir", os.path.join(HERE, "src/main/res"), "-o", B + "/res.zip")
run(os.path.join(BT, "aapt2"), "link", "-I", JAR, "--manifest", B + "/AndroidManifest.xml",
"--custom-package", PKG,
"-o", B + "/base.apk", "-A", B + "/assets", "--java", B + "/gen", "--min-sdk-version", "26",
"--target-sdk-version", "33", "--version-code", str(code), "--version-name", VERSION_NAME,
"-0", "wav", "-0", "json", B + "/res.zip")
srcs = glob.glob(os.path.join(HERE, "src/main/java/**/*.java"), recursive=True) + \
glob.glob(B + "/gen/**/*.java", recursive=True)
run(os.path.join(JAVA, "bin/javac"), "--release", "11", "-classpath", JAR, "-d", B + "/classes", "-Xlint:-options", *srcs)
# build-tools 34's d8 crashes on javac 21's nameless MethodParameters in inner-class constructors:
# only static nested classes and lambdas are allowed (rabbit.html#toolchain).
classes = glob.glob(B + "/classes/**/*.class", recursive=True)
bad = []
for c in classes:
if "$" not in os.path.basename(c):
continue
name = os.path.basename(c)[:-6].split("$")[-1]
if name.isdigit():
bad.append(c)
elif "MethodParameters" in run(os.path.join(JAVA, "bin/javap"), "-v", c):
bad.append(c)
if bad:
sys.exit("anonymous/inner classes are not allowed:\n " + "\n ".join(bad))
run(os.path.join(BT, "d8"), "--release", "--min-api", "26", "--lib", JAR, "--output", B + "/dex", *classes)
with zipfile.ZipFile(B + "/base.apk", "a") as z:
z.write(B + "/dex/classes.dex", "classes.dex")
run(os.path.join(BT, "zipalign"), "-f", "-p", "4", B + "/base.apk", B + "/aligned.apk")
if not os.path.exists(KEYSTORE):
run(os.path.join(JAVA, "bin/keytool"), "-genkeypair", "-keystore", KEYSTORE, "-storepass", KS_PASS,
"-keypass", KS_PASS, "-alias", "routine", "-keyalg", "RSA", "-keysize", "2048", "-validity", "36500",
"-dname", "CN=routine")
run(os.path.join(BT, "apksigner"), "sign", "--ks", KEYSTORE, "--ks-pass", "pass:" + KS_PASS,
"--out", B + "/routine.apk", B + "/aligned.apk")
if dev:
print("built android/build/routine.apk as %s (dev), %d" % (pkg, code))
return
os.makedirs(os.path.join(HERE, "apk"), exist_ok=True)
shutil.copy(B + "/routine.apk", os.path.join(HERE, "apk", "routine.apk"))
with open(os.path.join(HERE, "apk", "routine-apk.json"), "w") as f:
json.dump({"package": PKG, "versionName": VERSION_NAME, "versionCode": code}, f, indent=2)
print("built android/apk/routine.apk %s (%d), %d KiB" % (VERSION_NAME, code,
os.path.getsize(B + "/routine.apk") // 1024))
if __name__ == "__main__":
main()
+22
View File
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="@PKG@">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:label="@LABEL@"
android:icon="@drawable/ic_launcher"
android:allowBackup="false"
android:usesCleartextTraffic="true"
android:theme="@android:style/Theme.DeviceDefault.NoActionBar">
<activity
android:name="me.teafry.routine.MainActivity"
android:exported="true"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustResize"
android:configChanges="orientation|screenSize|keyboardHidden|keyboard|navigation">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
@@ -0,0 +1,374 @@
package me.teafry.routine;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.media.AudioAttributes;
import android.media.SoundPool;
import android.os.SystemClock;
import android.view.View;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Plays the stop-motion check-off animations (assets/animations.json, made by
* tools/gen_animations.py) out of a box, with their sounds. Frames are held 1/fps s each.
* A tick that reaches a streak level (Model.streakLevel) plays one of that level's streak
* animations instead (a calm task: a calm streak one), drawn with the streak number (Digits);
* a level with none yet falls back to the nearest lower level that has some (else the nearest
* higher), as on the desktop (routine/gui/overlay.py). A streak play also shows "<n> days!"
* (Digits.captionStrokes) under the animation, or over it when that keeps it bigger or nearer the
* box, from the frame its number first shows (Digits.captionStart) to the end; placement fits the animation and its caption together.
*/
final class AnimView extends View {
static final class Anim {
String name;
int color;
String sound;
float[][][] frames; // frame -> shape -> [kind(0 p, 1 l, 2 c, 3 colour, 4 number), w, coords...]
float x0, y0, x1, y1; // all it ever draws but the number, in box units from the box's centre
boolean hasNumber; // has "n" shapes
float maxN; // the tallest "n" shape's h (sizes the caption)
int firstN = -1; // the first frame with an "n" shape (starts the caption)
}
static final class Playing {
Anim a;
long t0;
View box;
float x, y, u; // where and how big: near the box, all of it on screen
int number; // the streak number its "n" shapes show (0: none)
float[] b; // x0, y0, x1, y1: all it draws, the number (and caption) included
float[] cap; // the caption's {cx, top} in box units, or null: none
float capH; // its height (Digits.captionH)
float bx, by; // the box's centre, as last seen
}
private final List<Anim> anims = new ArrayList<>();
private final java.util.Random random = new java.util.Random();
private final Map<String, Integer> palette = new HashMap<>();
private Anim star;
private final List<Anim> calm = new ArrayList<>();
private final List<List<Anim>> streakSets = new ArrayList<>(); // per level (animations.json "streak")
private final List<Anim> streakCalm = new ArrayList<>();
private int[] sets = new int[0];
private final List<Playing> playing = new ArrayList<>();
private final Map<String, Integer> sounds = new HashMap<>();
private final Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
private final Path path = new Path();
private final int[] loc = new int[2], me = new int[2];
private SoundPool pool;
private int fps = 12;
private final float unit;
AnimView(Context c, String json) {
super(c);
unit = Ui.dp(c, Ui.ANIM_UNIT);
p.setStrokeCap(Paint.Cap.ROUND);
p.setStrokeJoin(Paint.Join.ROUND);
try {
JSONObject d = new JSONObject(json);
fps = d.optInt("fps", 12);
JSONObject colors = d.getJSONObject("colors");
java.util.Iterator<String> names = colors.keys();
while (names.hasNext()) {
String n = names.next();
palette.put(n, Color.parseColor(colors.getString(n)));
}
JSONArray as = d.getJSONArray("animations");
for (int i = 0; i < as.length(); i++) anims.add(parse(as.getJSONObject(i)));
if (d.optJSONObject("star") != null) star = parse(d.getJSONObject("star"));
JSONArray cs = d.optJSONArray("calm");
if (cs != null) for (int i = 0; i < cs.length(); i++) calm.add(parse(cs.getJSONObject(i)));
JSONArray ss = d.optJSONArray("sets");
sets = new int[ss == null ? 1 : ss.length()];
if (ss == null) sets[0] = anims.size();
else for (int i = 0; i < ss.length(); i++) sets[i] = ss.getInt(i);
JSONObject st = d.optJSONObject("streak");
JSONArray sl = st == null ? null : st.optJSONArray("sets");
for (int i = 0; sl != null && i < sl.length(); i++) {
List<Anim> level = new ArrayList<>();
JSONArray la = sl.optJSONArray(i);
for (int k = 0; la != null && k < la.length(); k++) level.add(parse(la.getJSONObject(k)));
streakSets.add(level);
}
JSONArray sc = st == null ? null : st.optJSONArray("calm");
for (int i = 0; sc != null && i < sc.length(); i++) streakCalm.add(parse(sc.getJSONObject(i)));
} catch (JSONException e) {
android.util.Log.w("routine", "bad animations.json", e);
}
pool = new SoundPool.Builder().setMaxStreams(4).setAudioAttributes(new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_GAME).setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build()).build();
List<Anim> withStar = new ArrayList<>(anims);
if (star != null) withStar.add(star);
withStar.addAll(calm);
for (List<Anim> level : streakSets) withStar.addAll(level);
withStar.addAll(streakCalm);
for (Anim a : withStar) {
if (sounds.containsKey(a.sound)) continue;
try (AssetFileDescriptor fd = c.getAssets().openFd("sounds/" + a.sound)) {
sounds.put(a.sound, pool.load(fd, 1));
} catch (IOException e) {
android.util.Log.w("routine", "no sound " + a.sound, e);
}
}
}
private Anim parse(JSONObject o) throws JSONException {
Anim a = new Anim();
a.name = o.getString("name");
Integer c = palette.get(o.getString("color"));
a.color = c == null ? Ui.WHITE : c;
a.sound = o.getString("sound");
JSONArray fr = o.getJSONArray("frames");
a.frames = new float[fr.length()][][];
for (int f = 0; f < fr.length(); f++) {
JSONArray shapes = fr.getJSONArray(f);
a.frames[f] = new float[shapes.length()][];
for (int s = 0; s < shapes.length(); s++) {
JSONArray sh = shapes.getJSONArray(s);
String k = sh.getString(0);
float[] v;
if (k.equals("k")) { // ["k", colour name]: the shapes after it use that colour
Integer pc = palette.get(sh.getString(1));
v = new float[] {3, pc == null ? a.color : pc};
} else {
v = new float[sh.length()];
v[0] = k.equals("p") ? 0 : k.equals("l") ? 1 : k.equals("n") ? 4 : 2;
for (int n = 1; n < sh.length(); n++) v[n] = (float) sh.getDouble(n);
}
a.frames[f][s] = v;
if (v[0] == 4) {
a.hasNumber = true;
if (a.firstN < 0) a.firstN = f;
if (v.length > 4) a.maxN = Math.max(a.maxN, v[4]);
}
if (v[0] == 3 || v[0] == 4) continue; // everything it draws, for keeping it on screen
float pad = v[1] / 2;
if (v[0] == 2) {
float r = v[4] + pad;
a.x0 = Math.min(a.x0, v[2] - r);
a.x1 = Math.max(a.x1, v[2] + r);
a.y0 = Math.min(a.y0, v[3] - r);
a.y1 = Math.max(a.y1, v[3] + r);
} else {
for (int n = 2; n + 1 < v.length; n += 2) {
a.x0 = Math.min(a.x0, v[n] - pad);
a.x1 = Math.max(a.x1, v[n] + pad);
a.y0 = Math.min(a.y0, v[n + 1] - pad);
a.y1 = Math.max(a.y1, v[n + 1] + pad);
}
}
}
}
return a;
}
void release() {
if (pool != null) pool.release();
pool = null;
}
/** The streak animations for a level index: its own, else the nearest lower level's that has
* some (else the nearest higher); a calm task's: the calm streak ones. Empty = none at all. */
List<Anim> streakChoices(int level, boolean isCalm) {
if (isCalm && !streakCalm.isEmpty()) return streakCalm;
for (int k = Math.min(level, streakSets.size() - 1); k >= 0; k--) if (!streakSets.get(k).isEmpty()) return streakSets.get(k);
for (int k = level + 1; k < streakSets.size(); k++) if (!streakSets.get(k).isEmpty()) return streakSets.get(k);
return new ArrayList<>();
}
/** Play out of box; returns {name, set} pairs for the day's log (see Model.animSet).
* A calm task plays one of the calm set instead, never the star. streak: the streak this
* tick reached; a rewarded one plays a streak animation instead (set STREAK_SET / STREAK_CALM_SET). */
List<String[]> play(View box, int doneBefore, boolean isCalm, int streak) {
List<String[]> out = new ArrayList<>();
int level = streak > 0 ? Model.streakLevel(streak) : -1;
List<Anim> choices = level >= 0 ? streakChoices(level, isCalm) : new ArrayList<>();
if (anims.isEmpty() && choices.isEmpty()) return out;
int[] set = anims.isEmpty() ? new int[] {0, 0, 0, 0} : Model.animSet(doneBefore, sets);
List<Anim> chosen = new ArrayList<>();
int number = 0;
if (!choices.isEmpty()) {
chosen.add(choices.get(random.nextInt(choices.size())));
set[2] = isCalm && !streakCalm.isEmpty() ? Model.STREAK_CALM_SET : Model.STREAK_SET;
number = streak;
} else if (isCalm && !calm.isEmpty()) {
chosen.add(calm.get(random.nextInt(calm.size())));
set[2] = Model.CALM_SET;
} else {
chosen.add(anims.get(set[0] + random.nextInt(set[1] - set[0])));
if (set[3] == 1 && star != null) chosen.add(star);
}
long now = SystemClock.uptimeMillis();
for (Anim a : chosen) {
Playing pl = new Playing();
pl.a = a;
pl.t0 = now;
pl.box = box;
pl.u = unit;
pl.number = number;
pl.b = bounds(a, number);
if (number != 0) placeCaption(pl);
centre(pl);
playing.add(pl);
Integer id = sounds.get(a.sound);
if (id != null && pool != null) pool.play(id, 0.8f, 0.8f, 1, 0, 1f);
out.add(new String[] {a.name, Integer.toString(set[2])});
}
invalidate();
return out;
}
/** The caption under the animation, or above it if that draws it bigger, then nearer the box
* (anim_paint.caption_place; the desktop's overlay chooses the same way). */
private void placeCaption(Playing pl) {
float[] b = pl.b;
pl.capH = (float) Digits.captionH(pl.a.maxN);
float[] best = null;
float bestU = 0, bestMove = 0;
for (boolean above : new boolean[] {false, true}) {
float[] cp = Digits.captionPlace(b, pl.number, above, pl.capH);
pl.b = new float[] {cp[2], cp[3], cp[4], cp[5]};
if (!centre(pl)) {
best = cp;
break;
}
float move = Math.abs(pl.x - pl.bx) + Math.abs(pl.y - pl.by);
if (best == null || pl.u > bestU || (pl.u == bestU && move < bestMove)) {
best = cp;
bestU = pl.u;
bestMove = move;
}
}
pl.cap = new float[] {best[0], best[1]};
pl.b = new float[] {best[2], best[3], best[4], best[5]};
}
/** anim_paint.bounds: everything a draws over all its frames, the number's strokes (and their
* half widths) included when it has one to show. */
private static float[] bounds(Anim a, int number) {
float[] b = {a.x0, a.y0, a.x1, a.y1};
if (!a.hasNumber || number == 0) return b;
for (float[][] frame : a.frames) {
for (float[] sh : frame) {
if (sh[0] != 4 || sh.length < 6) continue;
float pad = sh[1] / 2;
for (float[] st : Digits.strokes(number, sh[2], sh[3], sh[4], sh[5])) {
for (int n = 0; n + 1 < st.length; n += 2) {
b[0] = Math.min(b[0], st[n] - pad);
b[2] = Math.max(b[2], st[n] + pad);
b[1] = Math.min(b[1], st[n + 1] - pad);
b[3] = Math.max(b[3], st[n + 1] + pad);
}
}
}
}
return b;
}
/** Out of the box's centre, moved as little as keeps all of it on screen; smaller only
* when it can't fit at full size. */
private boolean centre(Playing pl) {
if (pl.box == null || !pl.box.isShown()) return false;
pl.box.getLocationInWindow(loc);
getLocationInWindow(me);
pl.bx = loc[0] - me[0] + pl.box.getWidth() / 2f;
pl.by = loc[1] - me[1] + pl.box.getHeight() / 2f;
float[] b = pl.b;
float edge = Ui.dp(getContext(), 6);
pl.u = unit * Math.min(1f, Math.min((getWidth() - 2 * edge) / Math.max(1e-3f, (b[2] - b[0]) * unit),
(getHeight() - 2 * edge) / Math.max(1e-3f, (b[3] - b[1]) * unit)));
pl.x = fit(pl.bx, b[0] * pl.u, b[2] * pl.u, getWidth(), edge);
pl.y = fit(pl.by, b[1] * pl.u, b[3] * pl.u, getHeight(), edge);
return true;
}
private static float fit(float c, float lo, float hi, float size, float edge) {
if (hi - lo >= size - 2 * edge) return size / 2 - (lo + hi) / 2;
if (c + lo < edge) return edge - lo;
if (c + hi > size - edge) return size - edge - hi;
return c;
}
@Override
protected void onDraw(Canvas c) {
long now = SystemClock.uptimeMillis();
for (int i = playing.size() - 1; i >= 0; i--) {
Playing pl = playing.get(i);
int f = (int) ((now - pl.t0) * fps / 1000);
if (f >= pl.a.frames.length) {
playing.remove(i);
continue;
}
centre(pl);
p.setColor(pl.a.color);
for (float[] sh : pl.a.frames[f]) {
if (sh[0] == 3) p.setColor((int) sh[1]);
else if (sh[0] == 4) drawNumber(c, sh, pl.number, pl.x, pl.y, pl.u);
else draw(c, sh, pl.x, pl.y, pl.u);
}
if (pl.cap != null) drawCaption(c, pl, f);
}
if (!playing.isEmpty()) postInvalidateDelayed(1000 / fps);
}
/** ["n", w, cx, cy, h, rot]: the number's digit strokes, w wide, round caps and joins, never filled. */
private void drawNumber(Canvas c, float[] sh, int number, float cx, float cy, float unit) {
if (number == 0 || sh.length < 6) return;
p.setStyle(Paint.Style.STROKE);
p.setStrokeWidth(sh[1] * unit);
for (float[] st : Digits.strokes(number, sh[2], sh[3], sh[4], sh[5])) {
path.reset();
path.moveTo(cx + st[0] * unit, cy + st[1] * unit);
for (int k = 2; k + 1 < st.length; k += 2) path.lineTo(cx + st[k] * unit, cy + st[k + 1] * unit);
c.drawPath(path, p);
}
}
/** "<n> days!" in the animation's own colour, popping in over the first frames. */
private void drawCaption(Canvas c, Playing pl, int frame) {
double s = Digits.captionScale(frame, Digits.captionStart(pl.a.firstN, pl.a.frames.length));
if (s <= 0) return;
p.setColor(pl.a.color);
p.setStyle(Paint.Style.STROKE);
p.setStrokeWidth((float) (Digits.CAPTION_STROKE * pl.capH * s * pl.u));
for (float[] st : Digits.captionStrokes(pl.number, pl.cap[0], pl.cap[1], pl.capH, s)) {
path.reset();
path.moveTo(pl.x + st[0] * pl.u, pl.y + st[1] * pl.u);
for (int k = 2; k + 1 < st.length; k += 2) path.lineTo(pl.x + st[k] * pl.u, pl.y + st[k + 1] * pl.u);
c.drawPath(path, p);
}
}
private void draw(Canvas c, float[] sh, float cx, float cy, float unit) {
float w = sh[1];
if (w > 0) {
p.setStyle(Paint.Style.STROKE);
p.setStrokeWidth(w * unit);
} else {
p.setStyle(Paint.Style.FILL);
}
if (sh[0] == 2) {
c.drawCircle(cx + sh[2] * unit, cy + sh[3] * unit, sh[4] * unit, p);
return;
}
path.reset();
path.moveTo(cx + sh[2] * unit, cy + sh[3] * unit);
for (int k = 4; k + 1 < sh.length; k += 2) path.lineTo(cx + sh[k] * unit, cy + sh[k + 1] * unit);
if (sh[0] == 0) path.close();
c.drawPath(path, p);
}
}
@@ -0,0 +1,120 @@
package me.teafry.routine;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.graphics.Shader;
import android.view.View;
/**
* The checkbox. Dark: a white-rimmed square; done = filled with a check, skipped = a dash.
* Light: the desktop's (design.html#emboss): a softly embossed button-gray square, sunk while
* pressed; done = a check in the highlight colour, skipped = a gray dash.
*/
final class BoxView extends View {
String state = Model.PENDING;
private final Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
private final RectF r = new RectF();
private final Path check = new Path();
BoxView(Context c) {
super(c);
setClickable(true);
}
void setState(String s) {
state = s;
setContentDescription(Model.DONE.equals(s) ? "done" : Model.SKIPPED.equals(s) ? "skipped" : "not done");
invalidate();
}
/** Qt's darker(f) / lighter(f) on a gray-ish colour: each channel scaled by 100/f (or f/100). */
static int shade(int c, float f) {
float k = f >= 0 ? 100f / f : -f / 100f;
int a = c >>> 24, rr = Math.min(255, Math.round(((c >> 16) & 255) * k)),
g = Math.min(255, Math.round(((c >> 8) & 255) * k)), b = Math.min(255, Math.round((c & 255) * k));
return (a << 24) | (rr << 16) | (g << 8) | b;
}
static int darker(int c, int f) {
return shade(c, f);
}
static int lighter(int c, int f) {
return shade(c, -f);
}
@Override
protected void onDraw(Canvas c) {
if (Ui.light) {
drawLight(c);
return;
}
float w = getWidth(), h = getHeight(), s = Math.min(w, h), sw = s * 0.08f;
r.set((w - s) / 2 + sw, (h - s) / 2 + sw, (w + s) / 2 - sw, (h + s) / 2 - sw);
p.setShader(null);
p.setStrokeWidth(sw);
boolean done = Model.DONE.equals(state);
p.setStyle(done ? Paint.Style.FILL_AND_STROKE : Paint.Style.STROKE);
p.setColor(isPressed() ? Ui.HIGHLIGHT : Model.SKIPPED.equals(state) ? Ui.GRAY : Ui.WHITE);
c.drawRoundRect(r, s * 0.14f, s * 0.14f, p);
if (done) {
p.setStyle(Paint.Style.STROKE);
p.setColor(Ui.BLACK);
p.setStrokeWidth(s * 0.12f);
p.setStrokeCap(Paint.Cap.ROUND);
p.setStrokeJoin(Paint.Join.ROUND);
drawCheck(c);
} else if (Model.SKIPPED.equals(state)) {
p.setStrokeCap(Paint.Cap.ROUND);
c.drawLine(r.left + r.width() * 0.25f, r.centerY(), r.right - r.width() * 0.25f, r.centerY(), p);
}
}
private void drawLight(Canvas c) {
float w = getWidth(), h = getHeight(), s = Math.min(w, h) * 0.86f, rad = s * 0.18f;
r.set((w - s) / 2, (h - s) / 2, (w + s) / 2, (h + s) / 2);
boolean sunk = isPressed();
int face = sunk ? darker(Ui.BUTTON, 125) : Ui.BUTTON;
int top = sunk ? darker(face, 116) : lighter(face, 116), bot = sunk ? lighter(face, 116) : darker(face, 116);
int ftop = sunk ? darker(face, 103) : lighter(face, 103), fbot = sunk ? lighter(face, 103) : darker(face, 103);
p.setStyle(Paint.Style.FILL);
p.setShader(new LinearGradient(0, r.top, 0, r.bottom, new int[] {top, ftop, face, face, fbot, bot},
new float[] {0f, 0.08f, 0.3f, 0.7f, 0.92f, 1f}, Shader.TileMode.CLAMP));
c.drawRoundRect(r, rad, rad, p);
p.setShader(null);
p.setStyle(Paint.Style.STROKE);
p.setStrokeWidth(Math.max(1.5f, s * 0.03f));
p.setColor(darker(face, 135));
c.drawRoundRect(r, rad, rad, p);
if (Model.DONE.equals(state)) {
p.setColor(Ui.HIGHLIGHT);
p.setStrokeWidth(s * 0.13f);
p.setStrokeCap(Paint.Cap.ROUND);
p.setStrokeJoin(Paint.Join.ROUND);
drawCheck(c);
} else if (Model.SKIPPED.equals(state)) {
p.setColor(Ui.GRAY);
p.setStrokeWidth(s * 0.1f);
p.setStrokeCap(Paint.Cap.ROUND);
c.drawLine(r.left + r.width() * 0.28f, r.centerY(), r.right - r.width() * 0.28f, r.centerY(), p);
}
}
private void drawCheck(Canvas c) {
check.reset();
check.moveTo(r.left + r.width() * 0.22f, r.top + r.height() * 0.52f);
check.lineTo(r.left + r.width() * 0.42f, r.top + r.height() * 0.72f);
check.lineTo(r.left + r.width() * 0.78f, r.top + r.height() * 0.28f);
c.drawPath(check, p);
}
@Override
protected void drawableStateChanged() {
super.drawableStateChanged();
invalidate();
}
}
@@ -0,0 +1,45 @@
package me.teafry.routine;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.view.View;
/** The light look's date, like the desktop's: capitals of a set height on a fixed baseline,
* a set space above them and a little below; smaller only when the width runs out. */
final class DateView extends View {
private final String text;
private final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
private final int above, cap, below, side;
DateView(Context c, String text, Typeface face, int color, int above, int cap, int below, int side) {
super(c);
this.text = text;
this.above = above;
this.cap = cap;
this.below = below;
this.side = side;
paint.setTypeface(face);
paint.setColor(color);
setContentDescription(text);
}
@Override
protected void onMeasure(int w, int h) {
setMeasuredDimension(MeasureSpec.getSize(w), above + cap + below);
}
@Override
protected void onDraw(Canvas c) {
Rect r = new Rect();
paint.setTextSize(100);
paint.getTextBounds("HEMT", 0, 4, r); // the capitals' real height at 100 px
float size = 100f * cap / Math.max(1, r.height());
paint.setTextSize(size);
float room = getWidth() - 2 * side, w = paint.measureText(text);
if (w > room) paint.setTextSize(size * room / w);
c.drawText(text, side, above + cap, paint);
}
}
@@ -0,0 +1,150 @@
package me.teafry.routine;
/**
* The streak number shape ["n", w, cx, cy, h, rot] and the "<n> days!" caption under a streak
* animation: a port of routine/gui/anim_paint.py's number_strokes, DIGITS, LETTERS, caption_h,
* caption_strokes, caption_place and caption_scale (its docstring is the spec; keep the two in step).
* Pure, for android/test.
*/
final class Digits {
static final double DIGIT_W = 0.6, DIGIT_ADV = 0.82;
/** Hand-drawn strokes in a DIGIT_W x 1 cell, y down: DIGITS[d] = strokes, each x0, y0, x1, y1, ... */
static final double[][][] DIGITS = {
{{0.3, 0.0, 0.5, 0.07, 0.6, 0.3, 0.6, 0.7, 0.5, 0.93, 0.3, 1.0, 0.1, 0.93, 0.0, 0.7, 0.0, 0.3, 0.1, 0.07,
0.3, 0.0}},
{{0.1, 0.2, 0.34, 0.0, 0.34, 1.0}, {0.1, 1.0, 0.56, 1.0}},
{{0.02, 0.22, 0.12, 0.06, 0.3, 0.0, 0.48, 0.06, 0.58, 0.24, 0.52, 0.44, 0.02, 1.0, 0.6, 1.0}},
{{0.04, 0.1, 0.24, 0.0, 0.46, 0.04, 0.56, 0.2, 0.48, 0.38, 0.26, 0.46, 0.5, 0.54, 0.6, 0.74, 0.52, 0.92,
0.3, 1.0, 0.04, 0.9}},
{{0.46, 1.0, 0.46, 0.0, 0.0, 0.68, 0.6, 0.68}},
{{0.56, 0.0, 0.1, 0.0, 0.05, 0.44, 0.28, 0.38, 0.5, 0.46, 0.6, 0.68, 0.52, 0.9, 0.3, 1.0, 0.02, 0.92}},
{{0.52, 0.04, 0.32, 0.0, 0.12, 0.12, 0.02, 0.4, 0.02, 0.72, 0.12, 0.94, 0.3, 1.0, 0.5, 0.94, 0.6, 0.74,
0.52, 0.52, 0.3, 0.46, 0.1, 0.54, 0.02, 0.7}},
{{0.0, 0.0, 0.6, 0.0, 0.22, 1.0}},
{{0.3, 0.46, 0.1, 0.38, 0.06, 0.2, 0.16, 0.04, 0.3, 0.0, 0.44, 0.04, 0.54, 0.2, 0.5, 0.38, 0.3, 0.46,
0.06, 0.56, 0.0, 0.76, 0.1, 0.94, 0.3, 1.0, 0.5, 0.94, 0.6, 0.76, 0.54, 0.56, 0.3, 0.46}},
{{0.08, 0.96, 0.28, 1.0, 0.48, 0.88, 0.58, 0.6, 0.58, 0.28, 0.48, 0.06, 0.3, 0.0, 0.1, 0.06, 0.0, 0.26,
0.08, 0.48, 0.3, 0.54, 0.5, 0.46, 0.58, 0.3}},
};
/** The caption's letters (d, a, y, s, !): their widths, and strokes in the same cell as DIGITS. */
static final String LETTER_CHARS = "days!";
static final double[] LETTER_W = {0.5, 0.52, 0.5, 0.45, 0.16};
static final double[][][] LETTERS = {
{{0.5, 0.0, 0.5, 1.0}, {0.5, 0.58, 0.38, 0.45, 0.22, 0.43, 0.08, 0.52, 0.02, 0.72, 0.08, 0.92,
0.22, 1.0, 0.38, 0.98, 0.5, 0.86}},
{{0.46, 0.43, 0.46, 0.92, 0.52, 1.0}, {0.46, 0.58, 0.34, 0.45, 0.2, 0.43, 0.07, 0.52, 0.0, 0.72,
0.07, 0.92, 0.2, 1.0, 0.34, 0.97, 0.46, 0.84}},
{{0.0, 0.43, 0.26, 0.98}, {0.5, 0.43, 0.24, 1.12, 0.16, 1.28, 0.04, 1.32}},
{{0.44, 0.5, 0.32, 0.43, 0.16, 0.43, 0.04, 0.5, 0.04, 0.62, 0.16, 0.69, 0.32, 0.74, 0.45, 0.82,
0.45, 0.93, 0.32, 1.0, 0.14, 1.0, 0.0, 0.92}},
{{0.08, 0.0, 0.08, 0.7}, {0.08, 0.98, 0.08, 1.0}},
};
static final double CAPTION_H = 0.9, CAPTION_REL = 0.7, CAPTION_MIN = 0.6, CAPTION_STROKE = 0.16,
CAPTION_GAP = 0.18, CAPTION_SPACE = 0.32, CAPTION_SEP = 0.35, CAPTION_DEEP = 1.32;
static final double[] CAPTION_POP = {0.5, 0.8, 1.08};
static final int CAPTION_LAST = 10; // on screen at least this many frames (the last ones)
private Digits() {}
/** caption_h: from the tallest "n" shape's h in an animation (maxN; 0 = none). */
static double captionH(double maxN) {
return maxN > 0 ? Math.max(CAPTION_MIN, Math.min(CAPTION_H, CAPTION_REL * maxN)) : CAPTION_H;
}
/** caption_start: the first frame with an "n" shape (firstN; -1 = none: 0), at the latest CAPTION_LAST from the end. */
static int captionStart(int firstN, int frames) {
return Math.max(0, Math.min(Math.max(firstN, 0), frames - CAPTION_LAST));
}
/** caption_scale: 0 (not drawn) before start, then CAPTION_POP, then 1. */
static double captionScale(int frame, int start) {
int k = frame - start;
if (k < 0) return 0.0;
return k < CAPTION_POP.length ? CAPTION_POP[k] : 1.0;
}
/** caption_strokes: "<n> days!" in box units, centred on cx, its cell's top at top, scaled by scale. */
static float[][] captionStrokes(int number, double cx, double top, double h, double scale) {
String text = number + " days!";
double[] widths = new double[text.length()];
double[][][] glyphs = new double[text.length()][][];
for (int k = 0; k < text.length(); k++) {
char ch = text.charAt(k);
int li = LETTER_CHARS.indexOf(ch);
if (ch >= '0' && ch <= '9') {
widths[k] = DIGIT_W;
glyphs[k] = DIGITS[ch - '0'];
} else if (li >= 0) {
widths[k] = LETTER_W[li];
glyphs[k] = LETTERS[li];
} else {
widths[k] = CAPTION_SPACE;
glyphs[k] = new double[0][];
}
}
double[] starts = new double[text.length()];
double x = 0;
for (int k = 0; k < text.length(); k++) {
starts[k] = x;
x += widths[k] + CAPTION_GAP;
}
double W = x - CAPTION_GAP;
java.util.List<float[]> out = new java.util.ArrayList<>();
for (int k = 0; k < text.length(); k++) {
for (double[] stroke : glyphs[k]) {
float[] pts = new float[stroke.length];
for (int m = 0; m + 1 < stroke.length; m += 2) {
pts[m] = (float) (cx + (starts[k] + stroke[m] - W / 2) * h * scale);
pts[m + 1] = (float) (top + h / 2 + (stroke[m + 1] - 0.5) * h * scale);
}
out.add(pts);
}
}
return out.toArray(new float[0][]);
}
/** caption_place: {cx, top, x0, y0, x1, y1} = where the caption goes under (above) bounds b
* ({x0, y0, x1, y1}), and the union of b and the caption. */
static float[] captionPlace(float[] b, int number, boolean above, double h) {
double pad = CAPTION_STROKE * h / 2;
double cx = (b[0] + b[2]) / 2.0;
double top = above ? Math.min(b[1], -0.5) - CAPTION_SEP - pad - CAPTION_DEEP * h
: Math.max(b[3], 0.5) + CAPTION_SEP + pad;
double x0 = Double.MAX_VALUE, y0 = Double.MAX_VALUE, x1 = -Double.MAX_VALUE, y1 = -Double.MAX_VALUE;
for (float[] st : captionStrokes(number, cx, top, h, 1.0)) {
for (int m = 0; m + 1 < st.length; m += 2) {
x0 = Math.min(x0, st[m]);
x1 = Math.max(x1, st[m]);
y0 = Math.min(y0, st[m + 1]);
y1 = Math.max(y1, st[m + 1]);
}
}
return new float[] {(float) cx, (float) top, (float) Math.min(b[0], x0 - pad), (float) Math.min(b[1], y0 - pad),
(float) Math.max(b[2], x1 + pad), (float) Math.max(b[3], y1 + pad)};
}
/** The number's strokes in box units, [[x0, y0, x1, y1, ...], ...]: its digits left to right, each
* DIGIT_W * h wide, DIGIT_ADV * h apart, the row centred on (cx, cy) and turned by rot. */
static float[][] strokes(int number, double cx, double cy, double h, double rot) {
String text = Integer.toString(number);
double W = (text.length() - 1) * DIGIT_ADV + DIGIT_W;
double c = Math.cos(rot), s = Math.sin(rot);
java.util.List<float[]> out = new java.util.ArrayList<>();
for (int k = 0; k < text.length(); k++) {
int d = text.charAt(k) - '0';
if (d < 0 || d > 9) continue;
for (double[] stroke : DIGITS[d]) {
float[] pts = new float[stroke.length];
for (int m = 0; m + 1 < stroke.length; m += 2) {
double u = (k * DIGIT_ADV + stroke[m] - W / 2) * h;
double v = (stroke[m + 1] - 0.5) * h;
pts[m] = (float) (cx + u * c - v * s);
pts[m + 1] = (float) (cy + u * s + v * c);
}
out.add(pts);
}
}
return out.toArray(new float[0][]);
}
}
@@ -0,0 +1,69 @@
package me.teafry.routine;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.view.View;
/** The bottom bar's drawn icons: a shining sun (light look), a crescent moon (dark look),
* and the double chevron for Now. */
final class IconView extends View {
static final int SUN = 0, MOON = 1, CHEVRONS = 2;
int kind;
float stroke, tall; // the chevrons: line weight and height (0 = from the view's size)
private final Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
private final Path path = new Path(), cut = new Path();
IconView(Context c, int kind) {
super(c);
this.kind = kind;
setClickable(true);
}
@Override
protected void onDraw(Canvas c) {
float w = getWidth(), h = getHeight(), s = Math.min(w, h) * 0.62f, cx = w / 2, cy = h / 2;
p.setStrokeCap(Paint.Cap.ROUND);
p.setStrokeJoin(Paint.Join.ROUND);
if (kind == SUN) {
p.setStyle(Paint.Style.FILL);
p.setColor(Ui.SUN);
c.drawCircle(cx, cy, s * 0.24f, p);
p.setStyle(Paint.Style.STROKE);
p.setStrokeWidth(s * 0.09f);
for (int k = 0; k < 8; k++) {
double a = k * Math.PI / 4;
c.drawLine(cx + (float) (s * 0.36 * Math.cos(a)), cy + (float) (s * 0.36 * Math.sin(a)),
cx + (float) (s * 0.5 * Math.cos(a)), cy + (float) (s * 0.5 * Math.sin(a)), p);
}
} else if (kind == MOON) {
p.setStyle(Paint.Style.FILL);
p.setColor(0xFFFFE7A0);
path.reset();
path.addCircle(cx, cy, s * 0.42f, Path.Direction.CW);
cut.reset();
cut.addCircle(cx + s * 0.24f, cy - s * 0.16f, s * 0.36f, Path.Direction.CW);
path.op(cut, Path.Op.DIFFERENCE);
c.drawPath(path, p);
} else {
p.setStyle(Paint.Style.STROKE);
p.setColor(Ui.FG);
p.setStrokeWidth(stroke > 0 ? stroke : s * 0.13f);
float u = tall > 0 ? tall / 2.6f : s * 0.26f;
for (float dx : new float[] {-u * 0.9f, u * 0.9f}) {
path.reset();
path.moveTo(cx + dx - u * 0.6f, cy - u * 1.3f);
path.lineTo(cx + dx + u * 0.6f, cy);
path.lineTo(cx + dx - u * 0.6f, cy + u * 1.3f);
c.drawPath(path, p);
}
}
}
@Override
protected void drawableStateChanged() {
super.drawableStateChanged();
invalidate();
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,438 @@
package me.teafry.routine;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/** Line-for-line port of routine/model.py: the day record and how two copies merge. Keep in step. */
final class Model {
static final String DONE = "done", SKIPPED = "skipped", PENDING = "";
static final String STAR = "star_special";
static final int PER_SET = 5;
static final int CALM_SET = -1; // the play log's set number for the calm set
private Model() {}
static String slug(String label) {
String s = label.toLowerCase(Locale.ROOT).replaceAll("[^a-z0-9]+", "-").replaceAll("^-+|-+$", "");
return s.isEmpty() ? "item" : s;
}
static String fmt(Calendar c) {
return String.format(Locale.ROOT, "%04d-%02d-%02d", c.get(Calendar.YEAR), c.get(Calendar.MONTH) + 1,
c.get(Calendar.DAY_OF_MONTH));
}
static Calendar parse(String date) {
Calendar c = Calendar.getInstance();
c.clear();
c.set(Integer.parseInt(date.substring(0, 4)), Integer.parseInt(date.substring(5, 7)) - 1,
Integer.parseInt(date.substring(8, 10)), 12, 0);
return c;
}
/** The routine day now belongs to: before dayStartsAt it is still yesterday. */
static String routineDate(JSONObject schedule) {
Calendar c = Calendar.getInstance();
c.add(Calendar.HOUR_OF_DAY, -schedule.optInt("dayStartsAt", 4));
return fmt(c);
}
private static boolean has(JSONArray a, int v) {
for (int i = 0; i < a.length(); i++) if (a.optInt(i, -1) == v) return true;
return false;
}
static boolean onDay(JSONObject x, int weekday) {
JSONArray days = x.optJSONArray("days");
return days == null || has(days, weekday);
}
private static void flatten(JSONArray items, int weekday, String prefix, int depth, JSONArray out)
throws JSONException {
Set<String> seen = new HashSet<>();
for (int i = 0; i < items.length(); i++) {
JSONObject it = items.getJSONObject(i);
if (!onDay(it, weekday)) continue;
String id = prefix + "/" + (it.has("id") ? it.getString("id") : slug(it.getString("label")));
while (seen.contains(id)) id += "-2";
seen.add(id);
JSONObject o = new JSONObject();
o.put("id", id);
o.put("label", it.getString("label"));
o.put("depth", depth);
if (it.optBoolean("hint", false)) o.put("hint", true);
if (it.optBoolean("calm", false)) o.put("calm", true);
out.put(o);
JSONArray sub = it.optJSONArray("items");
if (sub != null) flatten(sub, weekday, id, depth + 1, out);
}
}
static JSONArray snapshot(JSONObject schedule, String date) throws JSONException {
int weekday = parse(date).get(Calendar.DAY_OF_WEEK) - 1; // 0 = Sunday
JSONArray blocks = new JSONArray();
JSONArray src = schedule.getJSONArray("blocks");
for (int i = 0; i < src.length(); i++) {
JSONObject b = src.getJSONObject(i);
if (!onDay(b, weekday)) continue;
JSONArray items = new JSONArray();
JSONArray bi = b.optJSONArray("items");
if (bi != null) flatten(bi, weekday, b.getString("id"), 0, items);
JSONObject o = new JSONObject();
o.put("id", b.getString("id"));
o.put("label", b.getString("label"));
o.put("start", b.getInt("start"));
o.put("end", b.getInt("end"));
o.put("color", b.getString("color"));
o.put("items", items);
blocks.put(o);
}
return blocks;
}
static JSONObject newDay(JSONObject schedule, String date) throws JSONException {
JSONObject d = new JSONObject();
d.put("date", date);
d.put("rev", schedule.optInt("rev", 1));
d.put("blocks", snapshot(schedule, date));
d.put("states", new JSONObject());
JSONObject note = new JSONObject();
note.put("text", "");
note.put("t", 0);
d.put("note", note);
return d;
}
static boolean refreshSnapshot(JSONObject schedule, JSONObject day) throws JSONException {
int rev = schedule.optInt("rev", 1);
if (day.optInt("rev", 0) >= rev) return false;
day.put("rev", rev);
day.put("blocks", snapshot(schedule, day.getString("date")));
return true;
}
static String state(JSONObject day, String id) {
JSONObject s = day.optJSONObject("states");
JSONObject v = s == null ? null : s.optJSONObject(id);
return v == null ? PENDING : v.optString("s", PENDING);
}
static void setState(JSONObject day, String id, String s) throws JSONException {
JSONObject v = new JSONObject();
v.put("s", s);
v.put("t", System.currentTimeMillis());
day.getJSONObject("states").put(id, v);
}
/** Tick or skip an item and give its still-pending sub-items (not suggestions) the same state; returns ids changed. */
static java.util.List<String> setWithChildren(JSONObject day, String id, String s) throws JSONException {
java.util.List<String> changed = new java.util.ArrayList<>();
changed.add(id);
setState(day, id, s);
if (!s.equals(PENDING)) {
JSONArray blocks = day.getJSONArray("blocks");
for (int i = 0; i < blocks.length(); i++) {
JSONArray items = blocks.getJSONObject(i).getJSONArray("items");
for (int k = 0; k < items.length(); k++) {
JSONObject it = items.getJSONObject(k);
String cid = it.getString("id");
if (cid.startsWith(id + "/") && !it.optBoolean("hint", false) && state(day, cid).equals(PENDING)) {
setState(day, cid, s);
changed.add(cid);
}
}
}
}
return changed;
}
/** Tasks ticked by hand and still ticked: distinct items in the play log that are done. */
static int ticks(JSONObject day) {
java.util.Set<String> ids = new java.util.HashSet<>();
JSONArray plays = day.optJSONArray("plays");
if (plays != null) {
for (int i = 0; i < plays.length(); i++) {
JSONObject p = plays.optJSONObject(i);
if (p == null || STAR.equals(p.optString("a"))) continue;
String id = p.optString("i");
if (DONE.equals(state(day, id))) ids.add(id);
}
}
return ids.size();
}
/** sets = each set's size (animations.json "sets"). {first, last+1, set number, star (1/0)}. */
static int[] animSet(int doneBefore, int[] sets) {
int k = doneBefore / PER_SET;
boolean star = k >= sets.length;
k = Math.min(k, sets.length - 1);
int lo = 0;
for (int i = 0; i < k; i++) lo += sets[i];
return new int[] {lo, lo + sets[k], k, star ? 1 : 0};
}
static void addPlay(JSONObject day, String name, String itemId, int setNo) throws JSONException {
addPlay(day, name, itemId, setNo, 0);
}
/** streak: the streak a streak animation celebrated (logged as "n"); 0 for any other play. */
static void addPlay(JSONObject day, String name, String itemId, int setNo, int streak) throws JSONException {
JSONArray plays = day.optJSONArray("plays");
if (plays == null) {
plays = new JSONArray();
day.put("plays", plays);
}
JSONObject p = new JSONObject();
p.put("t", System.currentTimeMillis());
p.put("a", name);
p.put("i", itemId);
p.put("s", setNo);
if (streak != 0) p.put("n", streak);
plays.put(p);
}
private static int comparePlays(JSONObject x, JSONObject y) {
int c = Long.compare(x.optLong("t"), y.optLong("t"));
if (c != 0) return c;
c = x.optString("a").compareTo(y.optString("a"));
return c != 0 ? c : x.optString("i").compareTo(y.optString("i"));
}
static void setNote(JSONObject day, String text) throws JSONException {
JSONObject n = new JSONObject();
n.put("text", text);
n.put("t", System.currentTimeMillis());
day.put("note", n);
}
private static JSONObject newer(JSONObject a, JSONObject b, String key) {
long ta = a.optLong("t", 0), tb = b.optLong("t", 0);
if (ta != tb) return ta > tb ? a : b;
return a.optString(key, "").compareTo(b.optString(key, "")) >= 0 ? a : b;
}
static JSONObject copy(JSONObject o) throws JSONException {
return new JSONObject(o.toString());
}
/** Merge two copies of the same day (either may be null). Pure. */
static JSONObject merge(JSONObject a, JSONObject b) throws JSONException {
if (a == null) return copy(b);
if (b == null) return copy(a);
JSONObject snap = a.optInt("rev", 0) >= b.optInt("rev", 0) ? a : b;
JSONObject states = copy(a.optJSONObject("states") == null ? new JSONObject() : a.getJSONObject("states"));
JSONObject bs = b.optJSONObject("states");
if (bs != null) {
Iterator<String> keys = bs.keys();
while (keys.hasNext()) {
String k = keys.next();
JSONObject v = bs.getJSONObject(k);
JSONObject cur = states.optJSONObject(k);
states.put(k, copy(cur == null ? v : newer(cur, v, "s")));
}
}
JSONObject empty = new JSONObject();
empty.put("text", "");
empty.put("t", 0);
JSONObject na = a.optJSONObject("note"), nb = b.optJSONObject("note");
JSONObject note = newer(na == null ? empty : na, nb == null ? empty : nb, "text");
JSONObject out = new JSONObject();
out.put("date", a.getString("date"));
out.put("rev", snap.optInt("rev", 0));
out.put("blocks", new JSONArray(snap.getJSONArray("blocks").toString()));
out.put("states", states);
out.put("note", copy(note));
java.util.TreeMap<String, JSONObject> plays = new java.util.TreeMap<>();
java.util.List<JSONObject> all = new java.util.ArrayList<>();
for (JSONObject d : new JSONObject[] {a, b}) {
JSONArray ps = d.optJSONArray("plays");
if (ps != null) for (int i = 0; i < ps.length(); i++) if (ps.optJSONObject(i) != null) all.add(ps.getJSONObject(i));
}
java.util.Map<String, JSONObject> byKey = new HashMap<>();
for (JSONObject p : all) byKey.put(p.optLong("t") + "\u0000" + p.optString("a") + "\u0000" + p.optString("i"), p);
java.util.List<JSONObject> sorted = new java.util.ArrayList<>(byKey.values());
java.util.Collections.sort(sorted, Model::comparePlays);
JSONArray outPlays = new JSONArray();
for (JSONObject p : sorted) outPlays.put(copy(p));
out.put("plays", outPlays);
return out;
}
// ── streaks (model.py's "Streaks"): the part a tick needs, the number it reaches ──
// (History, the block marks, run lists and totals are the desktop windows'; not ported)
static final int[] STREAK_LEVELS = {7, 21, 42, 66, 100, 150, 254, 365};
static final int STREAK_EVERY = 100; // past the last level, every 100 more days is the top level again
static final int CHEAT_AFTER = 7; // done days in a row that earn one cheat day (the default)
static final int STREAK_SET = -2; // the play log's set number for a streak animation
static final int STREAK_CALM_SET = -3; // ... and for a calm streak animation
static final String S_DONE = "done", S_MISS = "miss", S_OFF = "off", S_CHEAT = "cheat", S_OPEN = "open";
/** The level index (into STREAK_LEVELS) a streak number is rewarded at, or -1 (model.py: None). */
static int streakLevel(int n) {
for (int k = 0; k < STREAK_LEVELS.length; k++) if (n == STREAK_LEVELS[k]) return k;
int top = STREAK_LEVELS[STREAK_LEVELS.length - 1];
if (n > top && (n - top) % STREAK_EVERY == 0) return STREAK_LEVELS.length - 1;
return -1;
}
/** day_marks' items half: {item id: S_DONE | S_MISS | S_OPEN}; suggestions and absent items are left out. */
static Map<String, String> dayMarks(JSONObject day, String today) {
boolean past = day.optString("date").compareTo(today) < 0;
Map<String, String> items = new HashMap<>();
JSONArray blocks = day.optJSONArray("blocks");
for (int i = 0; blocks != null && i < blocks.length(); i++) {
JSONObject b = blocks.optJSONObject(i);
JSONArray its = b == null ? null : b.optJSONArray("items");
for (int k = 0; its != null && k < its.length(); k++) {
JSONObject it = its.optJSONObject(k);
if (it == null || it.optBoolean("hint", false)) continue;
String s = state(day, it.optString("id"));
items.put(it.optString("id"), DONE.equals(s) ? S_DONE : past || SKIPPED.equals(s) ? S_MISS : S_OPEN);
}
}
return items;
}
/** model.Run: one streak; length = its done days (its number). */
static final class Run {
String start, end;
int length;
final java.util.List<String> cheats = new java.util.ArrayList<>();
Run(String start) {
this.start = start;
this.end = start;
}
}
/** model.Streak: one item's record, fed its marks day by day in date order. */
static final class Streak {
final String key;
final int cheatAfter;
final Map<String, String> status = new HashMap<>();
private Run run; // the run going on (null: none)
private int since; // done days since the run began or the last cheat day
private boolean held; // a cheat day earned and not used yet
private String cheat; // the date of a cheat day not yet followed by a done day
Streak(String key, int cheatAfter) {
this.key = key;
this.cheatAfter = cheatAfter > 0 ? cheatAfter : 0;
}
void feed(String date, String mark) {
if (S_OPEN.equals(mark)) {
status.put(date, S_OPEN);
} else if (S_DONE.equals(mark)) {
if (run == null) {
run = new Run(date);
since = 0;
held = false;
}
cheat = null; // a cheat day followed by a done day: a rescue
run.length += 1;
run.end = date;
status.put(date, S_DONE);
since += 1;
if (cheatAfter > 0 && !held && since >= cheatAfter) held = true;
} else { // a miss
if (run != null && cheat != null) { // two misses running: no rescue after all
status.put(cheat, S_MISS);
run.cheats.remove(cheat);
cheat = null;
run = null;
status.put(date, S_MISS);
} else if (run != null && held) { // forgiven: the run goes on
held = false;
since = 0;
cheat = date;
run.cheats.add(date);
status.put(date, S_CHEAT);
} else {
run = null;
status.put(date, S_MISS);
}
}
}
/** The streak alive after the last day fed, else 0. */
int current() {
return run != null ? run.length : 0;
}
/** model.Streak.seed: start from base() = [length, since, held, cheat] as after asof (null: no run). */
void seed(JSONArray state, String asof) {
if (state == null || state.length() < 4 || state.optInt(0) <= 0) return;
run = new Run(asof);
run.length = state.optInt(0);
since = state.optInt(1);
held = state.optInt(2) != 0;
if (state.optInt(3) != 0) {
cheat = asof;
run.cheats.add(asof);
}
}
}
/** model.streak_ending: the streak itemId reaches if date is done, counting date and the days before
* it (date taken as today); 0 if it isn't done. base: a streak_base, used when date is after its asof
* (only the days after asof are read, and its cheat_after counts). days: any order. */
static int streakEnding(java.util.Collection<JSONObject> days, String itemId, String date, int cheatAfter,
JSONObject base) {
Streak st = new Streak(itemId, cheatAfter);
String after = "";
if (base != null && date.compareTo(base.optString("asof", "")) > 0) {
after = base.optString("asof");
st = new Streak(itemId, base.optInt("cheat_after", cheatAfter));
JSONObject items = base.optJSONObject("items");
st.seed(items == null ? null : items.optJSONArray(itemId), after);
}
java.util.TreeMap<String, JSONObject> sorted = new java.util.TreeMap<>();
for (JSONObject d : days) {
String dd = d.optString("date");
if (dd.compareTo(after) > 0 && dd.compareTo(date) <= 0) sorted.put(dd, d);
}
for (Map.Entry<String, JSONObject> e : sorted.entrySet()) {
String m = dayMarks(e.getValue(), date).get(itemId);
if (m != null) st.feed(e.getKey(), m);
}
return S_DONE.equals(st.status.get(date)) ? st.current() : 0;
}
/** Same content, whatever the key order. */
static boolean same(JSONObject a, JSONObject b) {
if (a == null || b == null) return a == b;
return canon(a).equals(canon(b));
}
private static String canon(Object o) {
if (o instanceof JSONObject) {
JSONObject j = (JSONObject) o;
java.util.TreeSet<String> keys = new java.util.TreeSet<>();
Iterator<String> it = j.keys();
while (it.hasNext()) keys.add(it.next());
StringBuilder sb = new StringBuilder("{");
for (String k : keys) sb.append(JSONObject.quote(k)).append(':').append(canon(j.opt(k))).append(',');
return sb.append('}').toString();
}
if (o instanceof JSONArray) {
JSONArray a = (JSONArray) o;
StringBuilder sb = new StringBuilder("[");
for (int i = 0; i < a.length(); i++) sb.append(canon(a.opt(i))).append(',');
return sb.append(']').toString();
}
if (o instanceof String) return JSONObject.quote((String) o);
if (o instanceof Number) return Long.toString(((Number) o).longValue());
return String.valueOf(o);
}
}
@@ -0,0 +1,171 @@
package me.teafry.routine;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* The phone's copy of the days: files/days/YYYY-MM-DD.json, plus files/sync.json
* ({"seq": n, "dirty": [dates]}). The desktop holds the full history; this keeps KEEP_DAYS.
* files/streaks.json: the desktop's streak base as the sync server last gave it (see Streaks).
*/
final class Store {
static final int KEEP_DAYS = 90;
private final File dir, syncFile;
private JSONObject sync;
private final Map<String, JSONObject> cache = new HashMap<>(); // parsed days, for counting streaks
Store(File filesDir) {
dir = new File(filesDir, "days");
dir.mkdirs();
syncFile = new File(filesDir, "sync.json");
try {
sync = new JSONObject(read(syncFile));
} catch (IOException | JSONException e) {
sync = new JSONObject();
}
prune();
}
static String read(File f) throws IOException {
byte[] b = new byte[(int) f.length()];
try (FileInputStream in = new FileInputStream(f)) {
int n = 0;
while (n < b.length) {
int r = in.read(b, n, b.length - n);
if (r < 0) break;
n += r;
}
}
return new String(b, StandardCharsets.UTF_8);
}
private static void write(File f, String s) throws IOException {
File tmp = new File(f.getPath() + ".tmp");
try (FileOutputStream out = new FileOutputStream(tmp)) {
out.write(s.getBytes(StandardCharsets.UTF_8));
out.getFD().sync();
}
if (!tmp.renameTo(f)) throw new IOException("rename " + f);
}
JSONObject get(String date) {
try {
return new JSONObject(read(new File(dir, date + ".json")));
} catch (IOException | JSONException e) {
return null;
}
}
void put(JSONObject day, boolean dirty) {
try {
String date = day.getString("date");
cache.remove(date);
write(new File(dir, date + ".json"), day.toString());
if (dirty) setDirty(date, true);
} catch (IOException | JSONException e) {
android.util.Log.w("routine", "can't save day", e);
}
}
/** Every day held, date -> record, read once and kept until put() changes it. Read only: don't edit. */
Map<String, JSONObject> all() {
Map<String, JSONObject> out = new HashMap<>();
for (String d : dates()) {
JSONObject o = cache.get(d);
if (o == null && (o = get(d)) != null) cache.put(d, o);
if (o != null) out.put(d, o);
}
return out;
}
/** The desktop's streak base (model.streak_base + "t", "anims"), or null before the server has sent one. */
JSONObject streakBase() {
try {
return new JSONObject(read(new File(syncFile.getParentFile(), "streaks.json")));
} catch (IOException | JSONException e) {
return null;
}
}
void saveStreakBase(JSONObject base) {
try {
write(new File(syncFile.getParentFile(), "streaks.json"), base.toString());
} catch (IOException e) {
android.util.Log.w("routine", "can't save streaks", e);
}
}
List<String> dates() {
List<String> out = new ArrayList<>();
String[] names = dir.list();
if (names != null) for (String n : names) if (n.endsWith(".json")) out.add(n.substring(0, n.length() - 5));
Collections.sort(out);
return out;
}
List<String> dirty() {
List<String> out = new ArrayList<>();
JSONArray a = sync.optJSONArray("dirty");
if (a != null) for (int i = 0; i < a.length(); i++) out.add(a.optString(i));
return out;
}
void setDirty(String date, boolean on) {
List<String> d = dirty();
d.remove(date);
if (on) d.add(date);
try {
sync.put("dirty", new JSONArray(d));
} catch (JSONException ignored) {
}
saveSync();
}
void saveSchedule(JSONObject sch) {
try {
write(new File(syncFile.getParentFile(), "schedule.json"), sch.toString());
} catch (IOException e) {
android.util.Log.w("routine", "can't save schedule", e);
}
}
long seq() {
return sync.optLong("seq", 0);
}
void setSeq(long s) {
try {
sync.put("seq", s);
} catch (JSONException ignored) {
}
saveSync();
}
private void saveSync() {
try {
write(syncFile, sync.toString());
} catch (IOException e) {
android.util.Log.w("routine", "can't save sync state", e);
}
}
private void prune() {
Calendar c = Calendar.getInstance();
c.add(Calendar.DAY_OF_MONTH, -KEEP_DAYS);
String cutoff = Model.fmt(c);
for (String d : dates()) if (d.compareTo(cutoff) < 0 && !dirty().contains(d)) new File(dir, d + ".json").delete();
}
}
@@ -0,0 +1,79 @@
package me.teafry.routine;
import java.util.Calendar;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
/**
* The streak a tick on the R1 reaches, from the days the R1 holds (the sync server relays only its last 60;
* Store keeps 90) and the desktop's streak base (model.streak_base, sent through the server and kept in
* files/streaks.json): the R1's own copy of what the desktop's app.streak_of works out.
*
* With a base whose asof is before the day ticked, and the R1 holding the day after asof (or an
* earlier one): carry on from the base over the days after asof. That is the desktop's number.
* Otherwise (no base yet, the server is an old one, the base is too old, or the tick is on a day
* before asof): count over the R1's own days, and trust the number only once two misses running
* (one when cheat days are off) have ended whatever came before them; a streak that may reach
* back past the oldest day held gives 0, so no streak animation, never a wrong number.
* A date missing in between counts as the routine's day with nothing ticked, as on the desktop
* (its Store fills in every day).
*
* Pure (org.json only), so android/test can run it on the JDK against model.py.
*/
final class Streaks {
private Streaks() {}
static String next(String date) {
Calendar c = Model.parse(date);
c.add(Calendar.DAY_OF_MONTH, 1);
return Model.fmt(c);
}
/** days: date -> the R1's copy of that day (the one being ticked, as edited, among them).
* schedule: the routine, for missing dates. cheatAfter: used when the base isn't. */
static int ending(Map<String, JSONObject> days, JSONObject schedule, String itemId, String date,
int cheatAfter, JSONObject base) {
String first = null;
for (String d : days.keySet()) if (first == null || d.compareTo(first) < 0) first = d;
if (first == null || first.compareTo(date) > 0) return 0;
String asof = base == null ? null : base.optString("asof", "");
boolean useBase = asof != null && !asof.isEmpty() && date.compareTo(asof) > 0
&& first.compareTo(next(asof)) <= 0;
Model.Streak st;
String d;
boolean sure;
if (useBase) {
st = new Model.Streak(itemId, base.optInt("cheat_after", cheatAfter));
JSONObject items = base.optJSONObject("items");
st.seed(items == null ? null : items.optJSONArray(itemId), asof);
d = next(asof);
sure = true;
} else {
st = new Model.Streak(itemId, cheatAfter);
d = first;
sure = false;
}
int misses = 0, ends = st.cheatAfter > 0 ? 2 : 1;
for (int guard = 0; d.compareTo(date) <= 0 && guard < 4000; d = next(d), guard++) {
JSONObject day = days.get(d);
if (day == null) {
try {
day = Model.newDay(schedule, d);
} catch (JSONException | RuntimeException e) {
continue;
}
}
String m = Model.dayMarks(day, date).get(itemId);
if (m == null) continue;
st.feed(d, m);
if (Model.S_DONE.equals(m)) {
misses = 0;
} else if (Model.S_MISS.equals(m) && ++misses >= ends) {
sure = true; // whatever ran before is over: from here it's all in view
}
}
return sure && Model.S_DONE.equals(st.status.get(date)) ? st.current() : 0;
}
}
@@ -0,0 +1,144 @@
package me.teafry.routine;
import android.content.Context;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.animation.DecelerateInterpolator;
import android.widget.FrameLayout;
/**
* Holds the day's scroll; a sideways drag moves to another day (finger right = an earlier day).
* While dragging, the neighbouring day (a preview from Peek) rides in alongside, following
* the finger; let go past the threshold and both glide the rest of the way, then Go swaps
* in the real day under the preview, and the preview is dropped. Short of the threshold, or with
* no day that way, everything springs back.
*/
final class SwipeFrame extends FrameLayout {
interface Peek {
/** A preview of the day that way (-1 earlier, +1 later), or null when there isn't one. */
View peek(int dir);
}
interface Go {
/** Show the day that way for real; call done once it's on screen. */
void go(int dir, Runnable done);
}
private static final long GLIDE_MS = 170;
private final int slop, min;
private float x0, y0;
private boolean dragging, busy;
private int peekDir;
private View peek;
Peek peeker; // lambdas, not an anonymous class: rabbit.html#toolchain
Go goer;
SwipeFrame(Context c) {
super(c);
slop = ViewConfiguration.get(c).getScaledTouchSlop();
min = Ui.dp(c, 90);
}
private View page() {
return getChildAt(0);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent e) {
if (busy) return true;
switch (e.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
x0 = e.getX();
y0 = e.getY();
dragging = false;
break;
case MotionEvent.ACTION_MOVE:
float dx = e.getX() - x0, dy = e.getY() - y0;
if (Math.abs(dx) > slop * 2 && Math.abs(dx) > Math.abs(dy) * 2) {
dragging = true;
return true;
}
break;
default:
break;
}
return false;
}
/** The preview for the way the finger is going (made once per direction). */
private void ensurePeek(int dir) {
if (peekDir == dir) return;
dropPeek();
peekDir = dir;
peek = peeker == null ? null : peeker.peek(dir);
if (peek != null) addView(peek, new FrameLayout.LayoutParams(-1, -1));
}
private void dropPeek() {
if (peek != null) removeView(peek);
peek = null;
peekDir = 0;
}
private void place(float dx) {
int w = getWidth();
float t = peek == null ? dx / 3f : dx; // nothing that way: a little give, no more
page().setTranslationX(t);
if (peek != null) peek.setTranslationX(t + (peekDir < 0 ? -w : w));
}
@Override
public boolean onTouchEvent(MotionEvent e) {
if (busy) return true;
float dx = e.getX() - x0;
switch (e.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
return true;
case MotionEvent.ACTION_MOVE:
if (dragging && dx != 0) {
ensurePeek(dx > 0 ? -1 : 1);
place(dx);
}
return true;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
boolean go = dragging && peek != null && Math.abs(dx) > min
&& e.getActionMasked() == MotionEvent.ACTION_UP;
dragging = false;
if (go) finish();
else back();
return true;
default:
return true;
}
}
private void finish() {
busy = true;
final int dir = peekDir, w = getWidth();
page().animate().translationX(dir < 0 ? w : -w).setDuration(GLIDE_MS)
.setInterpolator(new DecelerateInterpolator()).start();
peek.animate().translationX(0).setDuration(GLIDE_MS).setInterpolator(new DecelerateInterpolator())
.withEndAction(() -> goer.go(dir, () -> {
page().setTranslationX(0);
dropPeek();
busy = false;
})).start();
}
private void back() {
if (page().getTranslationX() == 0 && peek == null) return;
busy = true;
final int w = getWidth(), dir = peekDir;
page().animate().translationX(0).setDuration(GLIDE_MS).setInterpolator(new DecelerateInterpolator())
.withEndAction(() -> {
dropPeek();
busy = false;
}).start();
if (peek != null) {
peek.animate().translationX(dir < 0 ? -w : w).setDuration(GLIDE_MS)
.setInterpolator(new DecelerateInterpolator()).start();
}
}
}
@@ -0,0 +1,60 @@
package me.teafry.routine;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import android.os.Handler;
import org.json.JSONObject;
/** One POST /sync on a worker thread; the answer comes back on the main thread. */
final class Sync {
interface Done {
void done(JSONObject result, String error);
}
private Sync() {}
static void post(String base, String token, String body, Handler main, Done cb) {
new Thread(() -> {
JSONObject res = null;
String err = null;
HttpURLConnection c = null;
try {
c = (HttpURLConnection) new URL(base.replaceAll("/+$", "") + "/sync").openConnection();
c.setConnectTimeout(8000);
c.setReadTimeout(20000);
c.setRequestMethod("POST");
c.setDoOutput(true);
c.setRequestProperty("Authorization", "Bearer " + token);
c.setRequestProperty("Content-Type", "application/json");
try (OutputStream o = c.getOutputStream()) {
o.write(body.getBytes(StandardCharsets.UTF_8));
}
int code = c.getResponseCode();
if (code != 200) {
err = "the server said " + code + (code == 401 ? " (token?)" : "");
} else {
ByteArrayOutputStream buf = new ByteArrayOutputStream();
try (InputStream in = c.getInputStream()) {
byte[] b = new byte[8192];
int n;
while ((n = in.read(b)) > 0) buf.write(b, 0, n);
}
res = new JSONObject(buf.toString("UTF-8"));
}
} catch (Exception e) {
err = "can't reach the sync server";
} finally {
if (c != null) c.disconnect();
}
final JSONObject fr = res;
final String fe = err;
main.post(() -> cb.done(fr, fe));
}, "routine-sync").start();
}
}
@@ -0,0 +1,83 @@
package me.teafry.routine;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PixelFormat;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;
/**
* A button face in the light look, after shared-resources design.html: embossed (#emboss: rims
* lighter/darker(116) over 8 %, face 103, outline darker(135)), sunk at darker(125) while held
* (#states), chosen = sunk at darker(112) (#toggles). Tiles (#tiles) touch: corners square where
* they meet, and each later tile overlaps the one before by the outline, so they share one line.
*/
final class TileDrawable extends Drawable {
private final int face;
private final boolean sunk;
private final float[] radii;
private final float line;
private final Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
private final Path path = new Path();
private final RectF r = new RectF();
TileDrawable(int face, boolean sunk, float[] radii, float line) {
this.face = face;
this.sunk = sunk;
this.radii = radii;
this.line = line;
}
/** radius on the outer corners only: first/last say which ends are rounded. */
static float[] corners(float rad, boolean first, boolean last) {
float a = first ? rad : 0, b = last ? rad : 0;
return new float[] {a, a, b, b, b, b, a, a};
}
/** The button: idle, and sunk while pressed. chosen = a pick-one tile that's picked. */
static Drawable button(float[] radii, float line, boolean chosen) {
int f = chosen ? BoxView.darker(Ui.BUTTON, 112) : Ui.BUTTON;
StateListDrawable s = new StateListDrawable();
s.addState(new int[] {android.R.attr.state_pressed},
new TileDrawable(BoxView.darker(Ui.BUTTON, 125), true, radii, line));
s.addState(new int[] {}, new TileDrawable(f, chosen, radii, line));
return s;
}
@Override
public void draw(Canvas c) {
r.set(getBounds());
r.inset(line / 2, line / 2);
path.reset();
path.addRoundRect(r, radii, Path.Direction.CW);
int top = sunk ? BoxView.darker(face, 116) : BoxView.lighter(face, 116);
int bot = sunk ? BoxView.lighter(face, 116) : BoxView.darker(face, 116);
int ftop = sunk ? BoxView.darker(face, 103) : BoxView.lighter(face, 103);
int fbot = sunk ? BoxView.lighter(face, 103) : BoxView.darker(face, 103);
p.setStyle(Paint.Style.FILL);
p.setShader(new LinearGradient(0, r.top, 0, r.bottom, new int[] {top, ftop, face, face, fbot, bot},
new float[] {0f, 0.08f, 0.3f, 0.7f, 0.92f, 1f}, Shader.TileMode.CLAMP));
c.drawPath(path, p);
p.setShader(null);
p.setStyle(Paint.Style.STROKE);
p.setStrokeWidth(line);
p.setColor(BoxView.darker(face, 135));
c.drawPath(path, p);
}
@Override
public void setAlpha(int a) {}
@Override
public void setColorFilter(ColorFilter cf) {}
@Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
}
@@ -0,0 +1,53 @@
package me.teafry.routine;
import android.content.Context;
/**
* Every size and colour in one place, sizes already doubled for the R1 (rabbit.html#dp).
* Two looks: dark (white on black, the default: best in bright sunlight) and light (the
* desktop's: its grays, embossed boxes, block colours, the Edition date). setLight picks one;
* the colours below FG are set by it.
*/
final class Ui {
static final float TEXT_SMALL = 22, TEXT_BODY = 28, TEXT_BIG = 32, TEXT_SUB = 25;
static final int ROW_MIN = 88, BAR = 76, BOX = 52, INDENT = 40, ANIM_UNIT = 44;
static final int WHITE = 0xFFFFFFFF, BLACK = 0xFF000000, HIGHLIGHT = 0xFF3584E4, SUN = 0xFFFFC400;
static boolean light;
static int FG, BG, TASKS, BAR_BG, GRAY, DIM, NOTE_BG, NOTE_EDGE, BUTTON;
static {
setLight(false);
}
static void setLight(boolean on) {
light = on;
if (on) { // shared-resources design.html#colors light defaults
FG = BLACK;
BG = 0xFFEFEFEF; // 239: header and footer
TASKS = 0xFFF7F7F7; // 247: the tasks area, a little lighter
BAR_BG = 0xFFEFEFEF;
GRAY = 0xFF808080;
DIM = 0xFFA8A8A8;
NOTE_BG = WHITE;
NOTE_EDGE = 0xFFBDBDBD;
BUTTON = 0xFFF7F7F7; // 247
} else {
FG = WHITE;
BG = BLACK;
TASKS = BLACK;
BAR_BG = 0xFF111111;
GRAY = 0xFF8A8A8A;
DIM = 0xFF3A3A3A;
NOTE_BG = 0xFF161616;
NOTE_EDGE = DIM;
BUTTON = BLACK;
}
}
private Ui() {}
static int dp(Context c, float v) {
return Math.round(v * c.getResources().getDisplayMetrics().density);
}
}
@@ -0,0 +1,8 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp" android:height="108dp" android:viewportWidth="128" android:viewportHeight="128">
<path android:fillColor="#FFFFFF" android:pathData="M32,8h64a24,24 0 0 1 24,24v64a24,24 0 0 1 -24,24h-64a24,24 0 0 1 -24,-24v-64a24,24 0 0 1 24,-24z"/>
<path android:strokeColor="#000000" android:strokeWidth="5" android:pathData="M38,56h26a8,8 0 0 1 8,8v26a8,8 0 0 1 -8,8h-26a8,8 0 0 1 -8,-8v-26a8,8 0 0 1 8,-8z"/>
<path android:strokeColor="#3584E4" android:strokeWidth="7" android:strokeLineCap="round" android:strokeLineJoin="round" android:pathData="M39,77l9,9l16,-20"/>
<path android:strokeColor="#E8202A" android:strokeWidth="6" android:strokeLineCap="round" android:pathData="M80,48L94,34M66,40L68,22M88,62L106,60"/>
<path android:fillColor="#FFC400" android:pathData="M100,24m-6,0a6,6 0 1 1 12,0a6,6 0 1 1 -12,0"/>
</vector>
@@ -0,0 +1,123 @@
package me.teafry.routine;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONObject;
/**
* Runs the R1's pure streak / number / merge code on the JDK, for tests/test_r1.py (which compares
* the answers with routine/model.py and anim_paint.py). Reads a JSON file of cases, prints answers:
*
* in: {"ending": [{"days", "schedule", "item", "date", "cheat", "base"?}], "model": [same, the
* whole history], "digits": [[n, cx, cy, h, rot]], "merge": [[a, b]], "levels": [n, ...],
* "caption": [[n, cx, top, h, scale]], "place": [[x0, y0, x1, y1, n, above (0/1), h]],
* "captionh": [tallest n h], "pop": [[frame, start]],
* "start": [[first n frame, frames]]}
* out: {"ending": [Streaks.ending], "model": [Model.streakEnding], "digits": [strokes],
* "merge": [Model.merge], "levels": [Model.streakLevel], "caption": [strokes],
* "place": [Digits.captionPlace], "captionh": [Digits.captionH], "pop": [Digits.captionScale],
* "start": [Digits.captionStart]}
*/
public final class R1Check {
private R1Check() {}
public static void main(String[] args) throws Exception {
JSONObject in = new JSONObject(new String(Files.readAllBytes(Paths.get(args[0])), StandardCharsets.UTF_8));
JSONObject out = new JSONObject();
JSONArray r = new JSONArray();
JSONArray cases = in.optJSONArray("ending");
for (int i = 0; cases != null && i < cases.length(); i++) {
JSONObject c = cases.getJSONObject(i);
Map<String, JSONObject> days = new HashMap<>();
JSONArray ds = c.getJSONArray("days");
for (int k = 0; k < ds.length(); k++) days.put(ds.getJSONObject(k).getString("date"), ds.getJSONObject(k));
r.put(Streaks.ending(days, c.getJSONObject("schedule"), c.getString("item"), c.getString("date"),
c.optInt("cheat", Model.CHEAT_AFTER), c.optJSONObject("base")));
}
out.put("ending", r);
r = new JSONArray();
cases = in.optJSONArray("model");
for (int i = 0; cases != null && i < cases.length(); i++) {
JSONObject c = cases.getJSONObject(i);
List<JSONObject> days = new ArrayList<>();
JSONArray ds = c.getJSONArray("days");
for (int k = 0; k < ds.length(); k++) days.add(ds.getJSONObject(k));
r.put(Model.streakEnding(days, c.getString("item"), c.getString("date"),
c.optInt("cheat", Model.CHEAT_AFTER), c.optJSONObject("base")));
}
out.put("model", r);
r = new JSONArray();
JSONArray dg = in.optJSONArray("digits");
for (int i = 0; dg != null && i < dg.length(); i++) {
JSONArray a = dg.optJSONArray(i);
JSONArray strokes = new JSONArray();
for (float[] st : Digits.strokes(a.getInt(0), a.getDouble(1), a.getDouble(2), a.getDouble(3), a.getDouble(4))) {
JSONArray pts = new JSONArray();
for (float v : st) pts.put((double) v);
strokes.put(pts);
}
r.put(strokes);
}
out.put("digits", r);
r = new JSONArray();
JSONArray mg = in.optJSONArray("merge");
for (int i = 0; mg != null && i < mg.length(); i++) {
JSONArray ab = mg.optJSONArray(i);
r.put(Model.merge(ab.optJSONObject(0), ab.optJSONObject(1)));
}
out.put("merge", r);
r = new JSONArray();
JSONArray lv = in.optJSONArray("levels");
for (int i = 0; lv != null && i < lv.length(); i++) r.put(Model.streakLevel(lv.optInt(i)));
out.put("levels", r);
r = new JSONArray();
JSONArray cp = in.optJSONArray("caption");
for (int i = 0; cp != null && i < cp.length(); i++) {
JSONArray a = cp.optJSONArray(i);
r.put(strokes(Digits.captionStrokes(a.getInt(0), a.getDouble(1), a.getDouble(2), a.getDouble(3), a.getDouble(4))));
}
out.put("caption", r);
r = new JSONArray();
JSONArray pl = in.optJSONArray("place");
for (int i = 0; pl != null && i < pl.length(); i++) {
JSONArray a = pl.optJSONArray(i);
float[] b = {(float) a.getDouble(0), (float) a.getDouble(1), (float) a.getDouble(2), (float) a.getDouble(3)};
JSONArray res = new JSONArray();
for (float v : Digits.captionPlace(b, a.getInt(4), a.getInt(5) != 0, a.getDouble(6))) res.put((double) v);
r.put(res);
}
out.put("place", r);
r = new JSONArray();
JSONArray chs = in.optJSONArray("captionh");
for (int i = 0; chs != null && i < chs.length(); i++) r.put(Digits.captionH(chs.getDouble(i)));
out.put("captionh", r);
r = new JSONArray();
JSONArray pop = in.optJSONArray("pop");
for (int i = 0; pop != null && i < pop.length(); i++)
r.put(Digits.captionScale(pop.optJSONArray(i).optInt(0), pop.optJSONArray(i).optInt(1)));
out.put("pop", r);
r = new JSONArray();
JSONArray sts = in.optJSONArray("start");
for (int i = 0; sts != null && i < sts.length(); i++)
r.put(Digits.captionStart(sts.optJSONArray(i).optInt(0), sts.optJSONArray(i).optInt(1)));
out.put("start", r);
System.out.println(out);
}
private static JSONArray strokes(float[][] all) {
JSONArray strokes = new JSONArray();
for (float[] st : all) {
JSONArray pts = new JSONArray();
for (float v : st) pts.put((double) v);
strokes.put(pts);
}
return strokes;
}
}
@@ -0,0 +1,108 @@
package org.json;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/** Test-only stand-in for Android's org.json.JSONArray (see JSONException). */
public class JSONArray {
final List<Object> list = new ArrayList<>();
public JSONArray() {}
public JSONArray(Collection<?> c) {
list.addAll(c);
}
public JSONArray(String s) throws JSONException {
Object o = new JSONObject.Parser(s).value();
if (!(o instanceof JSONArray)) throw new JSONException("not an array");
list.addAll(((JSONArray) o).list);
}
public int length() {
return list.size();
}
public Object opt(int i) {
return i >= 0 && i < list.size() ? list.get(i) : null;
}
public JSONArray put(Object v) {
list.add(v);
return this;
}
public JSONArray put(int v) {
list.add((long) v);
return this;
}
public JSONArray put(long v) {
list.add(v);
return this;
}
public JSONArray put(double v) {
list.add(v);
return this;
}
public JSONObject optJSONObject(int i) {
Object o = opt(i);
return o instanceof JSONObject ? (JSONObject) o : null;
}
public JSONArray optJSONArray(int i) {
Object o = opt(i);
return o instanceof JSONArray ? (JSONArray) o : null;
}
public JSONObject getJSONObject(int i) throws JSONException {
JSONObject o = optJSONObject(i);
if (o == null) throw new JSONException("no object at " + i);
return o;
}
public int optInt(int i) {
return optInt(i, 0);
}
public int optInt(int i, int d) {
Object o = opt(i);
return o instanceof Number ? ((Number) o).intValue() : d;
}
public int getInt(int i) throws JSONException {
Object o = opt(i);
if (!(o instanceof Number)) throw new JSONException("no int at " + i);
return ((Number) o).intValue();
}
public double getDouble(int i) throws JSONException {
Object o = opt(i);
if (!(o instanceof Number)) throw new JSONException("no number at " + i);
return ((Number) o).doubleValue();
}
public String getString(int i) throws JSONException {
Object o = opt(i);
if (o == null) throw new JSONException("no value at " + i);
return o.toString();
}
public String optString(int i) {
Object o = opt(i);
return o == null ? "" : o.toString();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("[");
for (int i = 0; i < list.size(); i++) {
if (i > 0) sb.append(',');
sb.append(JSONObject.write(list.get(i)));
}
return sb.append(']').toString();
}
}
@@ -0,0 +1,8 @@
package org.json;
/** Test-only stand-in for Android's org.json (android.jar has only stubs): just what the app's pure classes use. */
public class JSONException extends Exception {
public JSONException(String m) {
super(m);
}
}
@@ -0,0 +1,249 @@
package org.json;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
/** Test-only stand-in for Android's org.json.JSONObject (see JSONException). */
public class JSONObject {
final Map<String, Object> map = new LinkedHashMap<>();
public static final Object NULL = new Object() {
@Override
public String toString() {
return "null";
}
};
public JSONObject() {}
public JSONObject(String s) throws JSONException {
Object o = new Parser(s).value();
if (!(o instanceof JSONObject)) throw new JSONException("not an object");
map.putAll(((JSONObject) o).map);
}
public boolean has(String k) {
return map.containsKey(k);
}
public Object opt(String k) {
return map.get(k);
}
public Iterator<String> keys() {
return map.keySet().iterator();
}
public JSONObject put(String k, Object v) {
if (v == null) map.remove(k);
else map.put(k, v instanceof Integer ? (Object) (long) (Integer) v : v);
return this;
}
public JSONObject put(String k, int v) {
map.put(k, (long) v);
return this;
}
public JSONObject put(String k, long v) {
map.put(k, v);
return this;
}
public JSONObject put(String k, boolean v) {
map.put(k, v);
return this;
}
public JSONObject put(String k, double v) {
map.put(k, v);
return this;
}
public JSONObject optJSONObject(String k) {
Object o = map.get(k);
return o instanceof JSONObject ? (JSONObject) o : null;
}
public JSONArray optJSONArray(String k) {
Object o = map.get(k);
return o instanceof JSONArray ? (JSONArray) o : null;
}
public JSONObject getJSONObject(String k) throws JSONException {
JSONObject o = optJSONObject(k);
if (o == null) throw new JSONException("no object " + k);
return o;
}
public JSONArray getJSONArray(String k) throws JSONException {
JSONArray o = optJSONArray(k);
if (o == null) throw new JSONException("no array " + k);
return o;
}
public String getString(String k) throws JSONException {
Object o = map.get(k);
if (o == null || o == NULL) throw new JSONException("no string " + k);
return o.toString();
}
public int getInt(String k) throws JSONException {
Object o = map.get(k);
if (!(o instanceof Number)) throw new JSONException("no int " + k);
return ((Number) o).intValue();
}
public String optString(String k) {
return optString(k, "");
}
public String optString(String k, String d) {
Object o = map.get(k);
return o == null || o == NULL ? d : o.toString();
}
public int optInt(String k) {
return optInt(k, 0);
}
public int optInt(String k, int d) {
Object o = map.get(k);
return o instanceof Number ? ((Number) o).intValue() : d;
}
public long optLong(String k) {
return optLong(k, 0);
}
public long optLong(String k, long d) {
Object o = map.get(k);
return o instanceof Number ? ((Number) o).longValue() : d;
}
public boolean optBoolean(String k, boolean d) {
Object o = map.get(k);
return o instanceof Boolean ? (Boolean) o : d;
}
public static String quote(String s) {
StringBuilder sb = new StringBuilder("\"");
for (char c : s.toCharArray()) {
if (c == '"' || c == '\\') sb.append('\\').append(c);
else if (c < 0x20) sb.append(String.format("\\u%04x", (int) c));
else sb.append(c);
}
return sb.append('"').toString();
}
static String write(Object o) {
if (o instanceof String) return quote((String) o);
if (o instanceof Double) {
double d = (Double) o;
return d == Math.rint(d) && Math.abs(d) < 1e15 ? Long.toString((long) d) : Double.toString(d);
}
return String.valueOf(o);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("{");
boolean first = true;
for (Map.Entry<String, Object> e : map.entrySet()) {
if (!first) sb.append(',');
first = false;
sb.append(quote(e.getKey())).append(':').append(write(e.getValue()));
}
return sb.append('}').toString();
}
static final class Parser {
final String s;
int i;
Parser(String s) {
this.s = s;
}
void ws() {
while (i < s.length() && Character.isWhitespace(s.charAt(i))) i++;
}
Object value() throws JSONException {
ws();
if (i >= s.length()) throw new JSONException("end of input");
char c = s.charAt(i);
if (c == '{') {
i++;
JSONObject o = new JSONObject();
ws();
if (s.charAt(i) == '}') {
i++;
return o;
}
while (true) {
ws();
String k = (String) value();
ws();
i++; // :
o.map.put(k, value());
ws();
if (s.charAt(i++) == '}') return o;
}
}
if (c == '[') {
i++;
JSONArray a = new JSONArray();
ws();
if (s.charAt(i) == ']') {
i++;
return a;
}
while (true) {
a.list.add(value());
ws();
if (s.charAt(i++) == ']') return a;
}
}
if (c == '"') {
StringBuilder sb = new StringBuilder();
i++;
while (s.charAt(i) != '"') {
char ch = s.charAt(i++);
if (ch == '\\') {
char e = s.charAt(i++);
if (e == 'u') {
sb.append((char) Integer.parseInt(s.substring(i, i + 4), 16));
i += 4;
} else {
sb.append(e == 'n' ? '\n' : e == 't' ? '\t' : e == 'r' ? '\r' : e == 'b' ? '\b'
: e == 'f' ? '\f' : e);
}
} else {
sb.append(ch);
}
}
i++;
return sb.toString();
}
if (s.startsWith("true", i)) {
i += 4;
return Boolean.TRUE;
}
if (s.startsWith("false", i)) {
i += 5;
return Boolean.FALSE;
}
if (s.startsWith("null", i)) {
i += 4;
return NULL;
}
int st = i;
while (i < s.length() && "+-0123456789.eE".indexOf(s.charAt(i)) >= 0) i++;
String num = s.substring(st, i);
if (num.isEmpty()) throw new JSONException("bad json at " + st);
if (num.contains(".") || num.contains("e") || num.contains("E")) return Double.parseDouble(num);
return Long.parseLong(num);
}
}
}