v0.7.0: bubble for Android 0.7.0 — react to messages, reactions in other languages, and edits

Android, ported from the desktop's reactions.ts / edits.ts (same readings:
checked side by side on the same 32 cases):
- Long-press a message: the quick reaction row (yours lit, tap again to take
  it back), + for every emoji (EmojiPicker, the desktop's emoji list as
  res/raw/emoji_list.txt, minus any the font can't draw), and Copy text.
- Settings → Reactions → Quick reactions: pick a spot, then its emoji; Reset.
- Tapbacks in other languages fold like the desktop's; "Edited to “…”" edits
  its message, which says "Edited · time"; tap it for the earlier texts.
- Chat list and notifications preview an edit as "✏️ new text".
- push_sandbox.py has a Spanish tapback and an edit to try it on.

Desktop: version 0.7.0; gen-emoji also writes the Android list.
This commit is contained in:
2026-11-10 17:38:09 -08:00
parent fcabae81e5
commit 09a46aa35c
16 changed files with 2421 additions and 43 deletions
@@ -56,6 +56,7 @@ public final class ChatActivity extends BaseActivity {
private final List<Object> rows = new ArrayList<>(); // Long day-start or Store.Msg
private final List<Sender.Photo> photos = new ArrayList<>();
private java.util.Map<Long, List<Reactions.Reaction>> reactions = new java.util.HashMap<>();
private java.util.Map<Long, List<Edits.Version>> versions = new java.util.HashMap<>();
private Adapter adapter;
private boolean firstLoad = true;
/** How many messages to show first when a chat opens (a few screens' worth). */
@@ -278,12 +279,15 @@ public final class ChatActivity extends BaseActivity {
});
}
/** Off the main thread: fold the tapbacks, then show. */
/** Off the main thread: fold the edits and tapbacks, then show. */
private void post(List<Store.Msg> msgs, String name, boolean complete) {
// iPhone tapbacks ("Loved “…”") become reactions on the message they quote.
java.util.Map<Long, List<Reactions.Reaction>> folded = Reactions.fold(msgs);
// "Edited to “…”" edits the message it's about; iPhone tapbacks
// ("Loved “…”") become reactions on the message they quote.
java.util.Map<Long, List<Edits.Version>> edited = Edits.fold(msgs);
java.util.Map<Long, List<Reactions.Reaction>> folded = Reactions.fold(msgs, Edits.earlier(edited));
runOnUiThread(() -> {
reactions = folded;
versions = edited;
show(msgs, name, complete);
});
}
@@ -670,18 +674,19 @@ public final class ChatActivity extends BaseActivity {
rlp.rightMargin = Ui.dp(c, 16);
addView(reacts, rlp);
addView(failed);
// Long-press copies the text. The body has its own listener because
// autolinked text takes its own touches and the bubble never sees them.
View.OnLongClickListener copy = v -> {
// Long-press: react or copy, like Signal. The body has its own listener
// because autolinked text takes its own touches and the bubble never sees them.
View.OnLongClickListener hold = v -> {
if (m == null) return true;
if (!m.body.isEmpty()) copyText(m.body);
else if ("failed".equals(m.status)) failedMenu(m);
if ("failed".equals(m.status)) failedMenu(m);
else messageMenu(m);
return true;
};
bubble.setOnLongClickListener(copy);
body.setOnLongClickListener(copy);
bubble.setOnLongClickListener(hold);
body.setOnLongClickListener(hold);
bubble.setOnClickListener(v -> {
if (m != null && "failed".equals(m.status)) failedMenu(m);
else if (m != null && versions.containsKey(m.id)) showEdits(m);
});
}
@@ -700,7 +705,8 @@ public final class ChatActivity extends BaseActivity {
if (showSender) sender.setText(Contacts.name(c, msg.sender));
body.setText(msg.body);
body.setVisibility(msg.body.isEmpty() ? GONE : VISIBLE);
meta.setText(Ui.timeOfDay(c, msg.ts));
// "Edited" like Signal's; a tap on the bubble shows the earlier texts.
meta.setText((versions.containsKey(msg.id) ? "Edited · " : "") + Ui.timeOfDay(c, msg.ts));
meta.setTextColor(out ? 0xB3FFFFFF : Ui.MUTED);
Ui.glyph(meta, "pending".equals(msg.status) ? Glyph.Kind.CLOCK : null, true);
failed.setVisibility("failed".equals(msg.status) ? VISIBLE : GONE);
@@ -778,6 +784,75 @@ public final class ChatActivity extends BaseActivity {
new AlertDialog.Builder(this).setTitle("Reactions").setItems(lines, null).setPositiveButton("OK", null).show();
}
/**
* Long-press on a message: the quick reactions (yours lit; tap it again to
* take it back), + for every emoji, and Copy. A reaction goes out as a
* text worded like an iPhone's ("Loved “…”").
*/
private void messageMenu(Store.Msg m) {
Context c = this;
String mine = null;
List<Reactions.Reaction> rs = reactions.get(m.id);
if (rs != null) for (Reactions.Reaction r : rs) if ("me".equals(r.from)) mine = r.emoji;
boolean canReact = "delivered".equals(m.status) && (!m.body.trim().isEmpty() || m.mediaJson != null);
if (!canReact && m.body.isEmpty()) return;
LinearLayout box = new LinearLayout(c);
box.setOrientation(LinearLayout.VERTICAL);
box.setPadding(Ui.dp(c, 12), Ui.dp(c, 16), Ui.dp(c, 12), Ui.dp(c, 8));
AlertDialog[] d = new AlertDialog[1];
if (canReact) {
LinearLayout row = new LinearLayout(c);
row.setGravity(Gravity.CENTER);
String[] quick = Config.quickReactions(c);
String[] cells = java.util.Arrays.copyOf(quick, quick.length + 1);
cells[quick.length] = "+";
final String current = mine;
for (String e : cells) {
boolean more = e.equals("+");
TextView t = Ui.text(c, e, more ? Ui.T_NAME : Ui.T_TITLE, more ? Ui.MUTED : Ui.TEXT);
t.setGravity(Gravity.CENTER);
t.setMinHeight(Ui.dp(c, 76));
if (!more && Reactions.same(current, e)) t.setBackground(Ui.round(Ui.ROW_ACTIVE, Ui.dp(c, 38)));
t.setContentDescription(more ? "More emoji" : Reactions.same(current, e) ? "Take back " + e : "React " + e);
t.setOnClickListener(v -> {
d[0].dismiss();
if (more) EmojiPicker.show(c, "React with", pick -> react(m, pick, current));
else react(m, e, current);
});
row.addView(t, new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1));
}
box.addView(row);
}
if (!m.body.isEmpty()) {
TextView copy = Ui.text(c, "Copy text", Ui.T_BODY, Ui.TEXT);
copy.setPadding(Ui.dp(c, 20), Ui.dp(c, 22), Ui.dp(c, 20), Ui.dp(c, 22));
copy.setOnClickListener(v -> {
d[0].dismiss();
copyText(m.body);
});
box.addView(copy);
}
d[0] = new AlertDialog.Builder(c).setView(box).show();
}
/** Sends `emoji` as a reaction to `m`, or takes it back if it's already yours. */
private void react(Store.Msg m, String emoji, String mine) {
Sender.send(this, did, contact, Reactions.text(emoji, m, Reactions.same(mine, emoji)), new ArrayList<>());
}
/** An edited message's texts, newest first, like Signal's edit history. */
private void showEdits(Store.Msg m) {
List<Edits.Version> vs = versions.get(m.id);
if (vs == null) return;
String[] lines = new String[vs.size()];
for (int i = 0; i < vs.size(); i++) {
Edits.Version v = vs.get(vs.size() - 1 - i);
String label = i == 0 ? "Now" : i == vs.size() - 1 ? "Original" : "Edited";
lines[i] = label + " · " + Ui.dayLabel(v.ts) + " " + Ui.timeOfDay(this, v.ts) + "\n" + v.body;
}
new AlertDialog.Builder(this).setTitle("Edit history").setItems(lines, null).setPositiveButton("OK", null).show();
}
/** Copies a message's text. Android 13 shows its own "copied" popup, so no toast of ours. */
private void copyText(String text) {
android.content.ClipboardManager cm = getSystemService(android.content.ClipboardManager.class);
@@ -185,4 +185,14 @@ final class Config {
static boolean notifications(Context c) {
return prefs(c).getBoolean("notifications", true);
}
/** The quick row a long-press on a message offers (Settings → Reactions). */
static String[] quickReactions(Context c) {
String s = prefs(c).getString("quickReactions", null);
return s == null || s.isEmpty() ? Reactions.DEFAULT_QUICK.clone() : s.split("\n");
}
static void setQuickReactions(Context c, String[] quick) {
prefs(c).edit().putString("quickReactions", String.join("\n", quick)).apply();
}
}
@@ -0,0 +1,147 @@
package me.teafry.voipmessages;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* "Edited to “…”" texts (an iPhone editing a message it sent us) applied to
* the message they're about -- a port of the desktop's src/shared/edits.ts:
* the same person's message from the last 20 minutes that reads most like
* the new text (or their only one there), or a near-copy within a day.
*/
final class Edits {
private Edits() {}
static final class Version {
final String body;
final long ts;
Version(String body, long ts) {
this.body = body;
this.ts = ts;
}
}
private static final Pattern EDIT = Pattern.compile(
"^(edited to|editado a|editó a|se editó a|editado para|editou para|a modifié en|modifié en|a été modifié en|bearbeitet zu|bearbeitet"
+ "|geändert in|geändert zu|modificato in|ha modificato in|bewerkt naar|gewijzigd in):?\\s*[“\"”«„‚]([\\s\\S]*)[”\"“»‘’]$",
Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
private static final long WINDOW = 20 * 60_000L, LATE_WINDOW = 24 * 60 * 60_000L;
private static final double LIKENESS = 0.4, LATE_LIKENESS = 0.6;
private static final int LOOK_BACK = 40;
/** The new text of an "Edited to “…”" message, or null. */
static String parse(String body) {
if (body == null) return null;
Matcher m = EDIT.matcher(body.trim());
if (!m.matches()) return null;
String text = m.group(2).replaceAll("^[\\s\\u00a0\\u202f]+|[\\s\\u00a0\\u202f]+$", "");
return text.isEmpty() ? null : text;
}
static String preview(String body) {
String t = parse(body);
return t == null ? null : "✏️ " + Reactions.norm(t);
}
/** 1 = the same, 0 = nothing in common (one minus edit distance over the longer length). */
static double likeness(String a, String b) {
int[] x = Reactions.norm(a).toLowerCase().codePoints().limit(600).toArray();
int[] y = Reactions.norm(b).toLowerCase().codePoints().limit(600).toArray();
if (x.length == 0 && y.length == 0) return 1;
int[] prev = new int[y.length + 1];
for (int j = 0; j <= y.length; j++) prev[j] = j;
for (int i = 1; i <= x.length; i++) {
int[] cur = new int[y.length + 1];
cur[0] = i;
for (int j = 1; j <= y.length; j++)
cur[j] = Math.min(Math.min(prev[j] + 1, cur[j - 1] + 1), prev[j - 1] + (x[i - 1] == y[j - 1] ? 0 : 1));
prev = cur;
}
return 1 - prev[y.length] / (double) Math.max(x.length, y.length);
}
private static String who(Store.Msg m) {
return m.in() ? (m.sender != null ? m.sender : m.contact) : "me";
}
/**
* Drops the "Edited to" texts it could place from `msgs` and gives their
* messages the new text; returns each edited message's texts, oldest first.
*/
static Map<Long, List<Version>> fold(List<Store.Msg> msgs) {
Set<Long> hidden = new HashSet<>();
Map<Long, String> current = new HashMap<>();
Map<Long, List<Version>> versions = new HashMap<>();
for (int i = 0; i < msgs.size(); i++) {
Store.Msg m = msgs.get(i);
if ("failed".equals(m.status)) continue;
String text = parse(m.body);
if (text == null) continue;
String from = who(m);
Store.Msg near = null, late = null;
double nearScore = -1, lateScore = -1;
int nearCount = 0;
for (int j = i - 1; j >= 0 && j >= i - LOOK_BACK; j--) {
Store.Msg c = msgs.get(j);
if (m.ts - c.ts > LATE_WINDOW) break;
if (hidden.contains(c.id) || !Objects.equals(who(c), from) || parse(c.body) != null || Reactions.isTapback(c.body)) continue;
String body = current.containsKey(c.id) ? current.get(c.id) : c.body;
if (body.trim().isEmpty()) continue;
double score = likeness(body, text);
if (m.ts - c.ts <= WINDOW) {
nearCount++;
if (score > nearScore) {
nearScore = score;
near = c;
}
} else if (score > lateScore) {
lateScore = score;
late = c;
}
}
Store.Msg hit = near != null && (nearScore >= LIKENESS || nearCount == 1) ? near : late != null && lateScore >= LATE_LIKENESS ? late : null;
if (hit == null) continue;
hidden.add(m.id);
List<Version> list = versions.get(hit.id);
if (list == null) {
list = new ArrayList<>();
list.add(new Version(hit.body, hit.ts));
versions.put(hit.id, list);
}
list.add(new Version(text, m.ts));
current.put(hit.id, text);
}
if (hidden.isEmpty()) return versions;
List<Store.Msg> shown = new ArrayList<>();
for (Store.Msg m : msgs) {
if (hidden.contains(m.id)) continue;
String now = current.get(m.id);
if (now != null) m.body = now; // a fresh copy from the database each load
shown.add(m);
}
msgs.clear();
msgs.addAll(shown);
return versions;
}
/** Edited messages' texts before the current one, for reactions that quote them. */
static Map<Long, List<String>> earlier(Map<Long, List<Version>> versions) {
Map<Long, List<String>> out = new HashMap<>();
for (Map.Entry<Long, List<Version>> e : versions.entrySet()) {
List<String> old = new ArrayList<>();
List<Version> v = e.getValue();
for (int i = 0; i < v.size() - 1; i++) old.add(v.get(i).body);
out.put(e.getKey(), old);
}
return out;
}
}
@@ -0,0 +1,78 @@
package me.teafry.voipmessages;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Paint;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
/**
* Every emoji in a grid (the list is the desktop's, res/raw/emoji_list.txt
* from scripts/gen-emoji.mjs), minus any this phone's font can't draw.
*/
final class EmojiPicker {
private EmojiPicker() {}
private static List<String> all;
private static synchronized List<String> all(Context c) {
if (all != null) return all;
List<String> out = new ArrayList<>();
Paint p = new Paint();
try (BufferedReader r = new BufferedReader(new InputStreamReader(c.getResources().openRawResource(R.raw.emoji_list), StandardCharsets.UTF_8))) {
for (String line; (line = r.readLine()) != null; ) if (!line.isEmpty() && p.hasGlyph(line)) out.add(line);
} catch (Exception ignored) {
}
return all = out;
}
/** A dialog of every emoji; a tap picks one and closes it. */
static void show(Context c, String title, Consumer<String> onPick) {
List<String> list = all(c);
GridView grid = new GridView(c);
int cell = Ui.dp(c, 64);
grid.setColumnWidth(cell);
grid.setNumColumns(GridView.AUTO_FIT);
grid.setStretchMode(GridView.STRETCH_COLUMN_WIDTH);
grid.setPadding(Ui.dp(c, 12), Ui.dp(c, 8), Ui.dp(c, 12), Ui.dp(c, 8));
grid.setSelector(android.R.color.transparent);
AlertDialog[] d = new AlertDialog[1];
grid.setAdapter(new BaseAdapter() {
public int getCount() {
return list.size();
}
public Object getItem(int i) {
return list.get(i);
}
public long getItemId(int i) {
return i;
}
public View getView(int i, View cv, ViewGroup parent) {
TextView t = cv instanceof TextView ? (TextView) cv : Ui.text(c, "", Ui.T_TITLE, Ui.TEXT);
t.setGravity(Gravity.CENTER);
t.setMinHeight(cell);
t.setText(list.get(i));
return t;
}
});
grid.setOnItemClickListener((parent, v, i, id) -> {
d[0].dismiss();
onPick.accept(list.get(i));
});
d[0] = new AlertDialog.Builder(c).setTitle(title).setView(grid).setNegativeButton("Cancel", null).show();
}
}
@@ -426,6 +426,7 @@ public final class MainActivity extends BaseActivity {
name.setText(title);
time.setText(Ui.shortTime(ctx, c.lastTs));
String reaction = Reactions.preview(c.lastBody);
if (reaction == null) reaction = Edits.preview(c.lastBody);
String body = reaction != null ? reaction : c.lastBody == null ? "" : c.lastBody.replaceAll("\\s+", " ").trim();
if (body.isEmpty() && c.lastMediaJson != null) body = "Photo";
String who = "out".equals(c.lastDirection) ? "You: " : group && c.lastSender != null ? Contacts.firstName(ctx, c.lastSender) + ": " : "";
@@ -39,6 +39,7 @@ final class Notifier {
for (Store.Msg m : list) if (m.ts > last.ts) last = m;
String title = Contacts.title(c, last.contact, store.getName(last.did, last.contact));
String reaction = Reactions.preview(last.body);
if (reaction == null) reaction = Edits.preview(last.body);
String body = reaction != null ? reaction : last.body.trim().isEmpty() && last.mediaJson != null ? "📷 Photo" : last.body.trim();
if (Phone.isGroup(last.contact) && last.sender != null) body = Contacts.firstName(c, last.sender) + ": " + body;
if (list.size() > 1) body += " (+" + (list.size() - 1) + " more)";
@@ -11,20 +11,24 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* iPhone tapbacks ("Loved “see you at 9”") folded into emoji reactions on the
* message they quote -- a port of the desktop's src/shared/reactions.ts.
* iPhone tapbacks ("Loved “see you at 9”", "Le encanta “…”") folded into emoji
* reactions on the message they quote, and the texts that send one -- a port
* of the desktop's src/shared/reactions.ts. English is read exactly; other
* languages loosely, from the words around the quote, and only count when the
* quote matches an earlier message.
*/
final class Reactions {
private Reactions() {}
static final class Parsed {
final String emoji, text; // text null = reacting to a photo
final boolean removed;
final boolean removed, loose;
Parsed(String emoji, String text, boolean removed) {
Parsed(String emoji, String text, boolean removed, boolean loose) {
this.emoji = emoji;
this.text = text;
this.removed = removed;
this.loose = loose;
}
}
@@ -64,6 +68,7 @@ final class Reactions {
private static final Pattern REMOVE = Pattern.compile("^Removed (an? .+?) from" + TAIL);
private static final Pattern MEDIA = Pattern.compile("^(?:an? )?(?:image|photo|picture|movie|video|attachment|audio message|gif|sticker)$",
Pattern.CASE_INSENSITIVE);
private static final String OPENS = "“\"”«„‚‘「『", CLOSES = "”\"“»«‘’」』";
/** [ok, text] where text null means media. */
private static Object[] target(Matcher m) {
@@ -72,34 +77,141 @@ final class Reactions {
return new Object[] {false, null};
}
static Parsed parse(String body) {
if (body == null) return null;
String s = body.trim();
private static Parsed strict(String s) {
Matcher m = VERB.matcher(s);
if (m.matches()) {
Object[] t = target(m);
return (boolean) t[0] ? new Parsed(VERBS.get(m.group(1).toLowerCase()), (String) t[1], false) : null;
return (boolean) t[0] ? new Parsed(VERBS.get(m.group(1).toLowerCase()), (String) t[1], false, false) : null;
}
m = REACTED.matcher(s);
if (m.matches() && m.group(1).codePointCount(0, m.group(1).length()) <= 4) {
if (m.matches() && m.group(1).codePointCount(0, m.group(1).length()) <= 8) {
Object[] t = target(m);
return (boolean) t[0] ? new Parsed(m.group(1), (String) t[1], false) : null;
return (boolean) t[0] ? new Parsed(m.group(1), (String) t[1], false, false) : null;
}
m = REMOVE.matcher(s);
if (m.matches()) {
String kind = m.group(1).toLowerCase();
String emoji = REMOVED.get(kind);
if (emoji == null) {
Matcher e = Pattern.compile("^an? (.{1,4})$").matcher(m.group(1));
// "Removed a 😂 from …" (newer iOS) names the emoji itself.
Matcher e = Pattern.compile("^an? (.{1,8})$").matcher(m.group(1));
if (e.matches()) emoji = e.group(1);
}
Object[] t = target(m);
return emoji != null && (boolean) t[0] ? new Parsed(emoji, (String) t[1], true) : null;
return emoji != null && (boolean) t[0] ? new Parsed(emoji, (String) t[1], true, false) : null;
}
return null;
}
private static String norm(String s) {
// ---- other languages (see LOOSE in reactions.ts) ----
/** A word (stem) that starts a word. */
private static Pattern w(String alts) {
return Pattern.compile("(?<!\\p{L})(?:" + alts + ")", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
}
private static final String[] LOOSE_EMOJI = {"👎", "❤️", "😂", "‼️", "❓", "👍"};
private static final Pattern[] LOOSE = {
w("no les? gust|não (?:curt|gost)|n['’]a pas (?:aimé|apprécié)|n['’]aime pas|nicht gemocht|mag\\b.{0,30}\\bnicht|gefällt\\b.{0,30}\\bnicht|nicht gefallen|non (?:gli |le )?piac|non mi piace|niet leuk|dislike|daumen runter|pulgar abajo"),
w("encant|amou|adorou|ama(?!\\p{L})|adora|adoré|adore|geliebt|liebt|herz|ha amato|amato|adorato|ama |coraz[oó]n|cora[cç][aã]o|c[oœ]ur|cuore|hart|houdt van|heart|love"),
w("ri[oó] de|r[ií]e de|se ri[oó]|se r[ií]e|gracia|riu|ri de|gra[cç]a|a ri|rit de|rire|dr[oô]le|gelacht|lacht|ha riso|riso|ride di|risata|risa|lach|laugh"),
w("emphasi|enfatiz|destac|resalt|real[cç]|soulign|mis en [ée]vidence|met en [ée]vidence|insist|hervorgehoben|hebt\\b.{0,30}\\bhervor|betont|evidenzi|sottoline|exclama|esclama|ausrufe|benadrukt|nadruk"),
w("question|cuestion|dud|d[uú]vida|doute|interrog|infrage|in frage|hinterfrag|fragezeichen|dubbio|domanda|vraagteken|twijfel"),
w("gust|curt|gost|aim[eé]|aime|gemocht|mag(?!\\p{L})|gef[aä]ll|piac|like|leuk|daumen")
};
private static final Pattern REMOVE_WORDS = w("removed|quit[oó]|elimin[oó]|retir[oó]|borr[oó]|removeu|retirou|tirou|excluiu|a retiré|a supprimé|a enlevé|retire|supprime|entfernt|ha rimosso|ha tolto|rimosso|tolto|verwijderd");
private static final Pattern PERSONAL = w("i(?!\\p{L})|i['’]m|me(?!\\p{L})|my(?!\\p{L})|you|yo(?!\\p{L})|tú(?!\\p{L})|eu(?!\\p{L})|je(?!\\p{L})|j['’]|moi(?!\\p{L})|ich(?!\\p{L})|du(?!\\p{L})|io(?!\\p{L})|ik(?!\\p{L})|jij(?!\\p{L})");
private static final Pattern QUOTED = Pattern.compile("[“\"”«„‚‘「『][^“\"”»«„‚‘’」』]*[”\"“»«‘’」』]");
private static final Pattern MEDIA_LOOSE = w("(?:an?|una?|uma?|une|ein(?:e[nm]?)?|un['’])\\s+(?:image|imagen|imagem|photo|foto|bild|immagine|picture|video|vídeo|vidéo|movie|película|filme|film|attachment|archivo adjunto|anexo|pièce jointe|anhang|allegato|audio message|mensaje de audio|mensagem de áudio|message audio|sprachnachricht|messaggio audio|gif|sticker|autocollant)(?!\\p{L})");
private static boolean pictographic(int cp) {
return (cp >= 0x1F000 && cp <= 0x1FAFF) || (cp >= 0x2600 && cp <= 0x27BF) || (cp >= 0x2300 && cp <= 0x23FF)
|| (cp >= 0x2B00 && cp <= 0x2BFF) || (cp >= 0x2190 && cp <= 0x21FF) || cp == 0x203C || cp == 0x2049
|| cp == 0x00A9 || cp == 0x00AE || cp == 0x2122 || cp == 0x3030 || cp == 0x303D || cp == 0x3297 || cp == 0x3299;
}
/** The first emoji in `s` (with its variation selector, skin tone and ZWJ parts), or null. */
static String firstEmoji(String s) {
for (int i = 0; i < s.length(); ) {
int cp = s.codePointAt(i);
if (!pictographic(cp) || (cp >= 0x1F3FB && cp <= 0x1F3FF)) {
i += Character.charCount(cp);
continue;
}
int end = i + Character.charCount(cp);
while (end < s.length()) {
int n = s.codePointAt(end);
if (n == 0xFE0F || (n >= 0x1F3FB && n <= 0x1F3FF)) end += Character.charCount(n);
else if (n == 0x200D && end + 1 < s.length() && pictographic(s.codePointAt(end + 1)))
end += 1 + Character.charCount(s.codePointAt(end + 1));
else break;
}
return s.substring(i, end);
}
return null;
}
/** {emoji, removed?} for a frame like "Le encanta" or "Hat … geliebt", or null. */
private static String[] classify(String frame) {
String f = frame.replaceAll("\\s+", " ").trim().replaceAll("[::]$", "").trim();
String own = QUOTED.matcher(f).replaceAll("");
if (f.isEmpty() || f.length() > 60 || f.split(" ").length > 8 || f.matches("(?s).*[\\n?.].*") || PERSONAL.matcher(own).find())
return null;
String emoji = firstEmoji(f);
for (int i = 0; emoji == null && i < LOOSE.length; i++) if (LOOSE[i].matcher(f).find()) emoji = LOOSE_EMOJI[i];
return emoji == null ? null : new String[] {emoji, REMOVE_WORDS.matcher(f).find() ? "1" : ""};
}
private static String trimSpace(String s) {
return s.replaceAll("^[\\s\\u00a0\\u202f]+|[\\s\\u00a0\\u202f]+$", "");
}
private static List<Parsed> loose(String s) {
List<Parsed> out = new ArrayList<>();
int close = -1;
for (int i = s.length() - 1; i >= 0; i--)
if (CLOSES.indexOf(s.charAt(i)) >= 0) {
close = i;
break;
}
for (int i = 0; i < close; i++) {
if (OPENS.indexOf(s.charAt(i)) < 0) continue;
String[] c = classify(s.substring(0, i) + " " + s.substring(close + 1));
String text = trimSpace(s.substring(i + 1, close));
if (c != null && !text.isEmpty()) out.add(new Parsed(c[0], text, !c[1].isEmpty(), true));
}
if (out.isEmpty() && s.length() <= 80) {
Matcher m = MEDIA_LOOSE.matcher(s);
if (m.find()) {
String[] c = classify(s.substring(0, m.start()) + " " + s.substring(m.end()));
if (c != null) out.add(new Parsed(c[0], null, !c[1].isEmpty(), true));
}
}
return out;
}
/** All plausible readings, the likeliest first. English ones are certain. */
static List<Parsed> parseAll(String body) {
if (body == null) return new ArrayList<>();
String s = body.trim();
Parsed r = strict(s);
if (r == null) return loose(s);
List<Parsed> one = new ArrayList<>();
one.add(r);
return one;
}
static Parsed parse(String body) {
List<Parsed> all = parseAll(body);
return all.isEmpty() ? null : all.get(0);
}
/** An English tapback: certain, unlike a loose reading. */
static boolean isTapback(String body) {
return body != null && strict(body.trim()) != null;
}
static String norm(String s) {
return s.replaceAll("[‘’]", "'").replaceAll("\\s+", " ").trim();
}
@@ -111,19 +223,35 @@ final class Reactions {
return !cut.equals(q) && cut.length() >= 8 && b.startsWith(cut);
}
/** Reaction texts we could place are dropped from `msgs`; returns reactions by message id. */
static Map<Long, List<Reaction>> fold(List<Store.Msg> msgs) {
/** "❤" and "❤️" are the same reaction. */
static boolean same(String a, String b) {
return a != null && b != null && a.replace("️", "").equals(b.replace("️", ""));
}
/**
* Reaction texts we could place are dropped from `msgs`; returns reactions
* by message id. `earlier` has edited messages' older texts, which a
* reaction may still quote.
*/
static Map<Long, List<Reaction>> fold(List<Store.Msg> msgs, Map<Long, List<String>> earlier) {
Set<Long> hidden = new HashSet<>();
Map<Long, LinkedHashMap<String, Reaction>> byTarget = new HashMap<>();
for (int i = 0; i < msgs.size(); i++) {
Store.Msg m = msgs.get(i);
Parsed r = parse(m.body);
if (r == null) continue;
// One that didn't go out stays in view, with its Retry.
if ("failed".equals(m.status)) continue;
Store.Msg found = null;
for (int j = i - 1; j >= 0 && found == null; j--) {
Store.Msg c = msgs.get(j);
if (hidden.contains(c.id) || parse(c.body) != null) continue;
if (r.text == null ? c.mediaJson != null : matches(c.body, r.text)) found = c;
Parsed r = null;
for (Parsed reading : parseAll(m.body)) {
for (int j = i - 1; j >= 0 && found == null; j--) {
Store.Msg c = msgs.get(j);
if (hidden.contains(c.id) || isTapback(c.body)) continue;
if (reading.text == null ? c.mediaJson != null : quotes(c, reading.text, earlier)) found = c;
}
if (found != null) {
r = reading;
break;
}
}
if (found == null) continue;
hidden.add(m.id);
@@ -131,7 +259,7 @@ final class Reactions {
LinkedHashMap<String, Reaction> mine = byTarget.computeIfAbsent(found.id, k -> new LinkedHashMap<>());
if (r.removed) {
Reaction cur = mine.get(from);
if (cur != null && cur.emoji.equals(r.emoji)) mine.remove(from);
if (cur != null && same(cur.emoji, r.emoji)) mine.remove(from);
} else {
mine.remove(from);
mine.put(from, new Reaction(r.emoji, from, m.ts));
@@ -144,11 +272,48 @@ final class Reactions {
return out;
}
/** "❤️ to “see you at 9”", or null for an ordinary text. */
private static boolean quotes(Store.Msg c, String text, Map<Long, List<String>> earlier) {
if (matches(c.body, text)) return true;
List<String> old = earlier == null ? null : earlier.get(c.id);
if (old != null) for (String b : old) if (matches(b, text)) return true;
return false;
}
/** "❤️ to “see you at 9”", or null for an ordinary text (or a loose reading, not yet known to be one). */
static String preview(String body) {
Parsed r = parse(body);
if (r == null) return null;
if (r == null || r.loose) return null;
String what = r.text == null ? "a photo" : "“" + norm(r.text) + "”";
return r.removed ? "Removed " + r.emoji + " from " + what : r.emoji + " to " + what;
}
// ---- sending ----
static final String[] DEFAULT_QUICK = {"❤️", "👍", "👎", "😂", "‼️", "❓"};
private static final Map<String, String[]> SEND = new HashMap<>();
private static final int MAX_QUOTE = 100;
static {
SEND.put("❤", new String[] {"Loved", "a heart"});
SEND.put("👍", new String[] {"Liked", "a like"});
SEND.put("👎", new String[] {"Disliked", "a dislike"});
SEND.put("😂", new String[] {"Laughed at", "a laugh"});
SEND.put("‼", new String[] {"Emphasized", "an exclamation"});
SEND.put("❓", new String[] {"Questioned", "a question mark"});
}
/** The text that reacts with `emoji` (or takes it back), worded like an iPhone's. */
static String text(String emoji, Store.Msg m, boolean removed) {
String body = norm(m.body);
String what;
if (!body.isEmpty()) {
int n = body.codePointCount(0, body.length());
what = "“" + (n > MAX_QUOTE ? body.substring(0, body.offsetByCodePoints(0, MAX_QUOTE)).trim() + "…" : body) + "”";
} else {
what = m.mediaJson != null ? "an image" : "“”";
}
String[] classic = SEND.get(emoji.replace("️", ""));
if (removed) return "Removed " + (classic != null ? classic[1] : "a " + emoji) + " from " + what;
return classic != null ? classic[0] + " " + what : "Reacted " + emoji + " to " + what;
}
}
@@ -81,6 +81,27 @@ public final class SettingsActivity extends BaseActivity {
notify.setOnCheckedChangeListener((v, on) -> Config.prefs(c).edit().putBoolean("notifications", on).apply());
box.addView(notify);
section("Reactions");
String[] quick = Config.quickReactions(c);
row("Quick reactions", String.join(" ", quick), v -> {
// Pick a spot, then the emoji for it.
new AlertDialog.Builder(c).setTitle("Change which one?")
.setItems(quick, (d, i) -> EmojiPicker.show(c, "Instead of " + quick[i], e -> {
String[] next = quick.clone();
// Already in the row: the two swap places.
for (int j = 0; j < next.length; j++) if (Reactions.same(next[j], e)) next[j] = next[i];
next[i] = e;
Config.setQuickReactions(c, next);
changed();
}))
.setNeutralButton("Reset", (d, w) -> {
Config.setQuickReactions(c, Reactions.DEFAULT_QUICK);
changed();
})
.setNegativeButton("Cancel", null).show();
});
note("Long-press a message to react. Tap yours again to take it back.");
section("Icon");
boolean inv = Icons.isInverted(c);
row("Launcher icon", inv ? "Inverted (lighter)" : "Dark", v -> {
File diff suppressed because it is too large Load Diff
+2 -2
View File
@@ -26,8 +26,8 @@ import sys
import zipfile
from pathlib import Path
VERSION_NAME = "0.6.0"
VERSION_CODE = 7
VERSION_NAME = "0.7.0"
VERSION_CODE = 8
PACKAGE = "me.teafry.voipmessages"
DEV_PACKAGE = PACKAGE + ".dev"
+4
View File
@@ -55,6 +55,10 @@ def main():
rows = [
(1001, VOIP, "5415550110", "in", "Are we still on for Saturday?", now - 300 * m, None),
(1002, VOIP, "5415550110", "out", "Yep! 10am at the market", now - 290 * m, None),
# A Spanish iPhone's tapback, and an edit (Reactions.java, Edits.java).
(1004, VOIP, "5415550110", "in", "Le encanta “Yep! 10am at the market”", now - 289 * m, None),
(1005, VOIP, "5415550110", "in", "Can you grab coffee on the way", now - 288 * m, None),
(1006, VOIP, "5415550110", "in", "Edited to “Can you grab coffee and bagels on the way?”", now - 286 * m, None),
(1003, VOIP, "5415550111", "in", "Your table is ready", now - 2000 * m, None),
(2**52 + 1, GV, "5415550120", "in", "Package left at the front door", now - 90 * m, None),
(2**52 + 2, GV, "5415550120", "out", "Thanks!", now - 85 * m, None),