v0.2.0: bubble for Android 0.2.0 — chat search, swipe for unread, faster chat opening

Desktop:
- Search lists chats whose own name matches first, so a named group
  isn't pushed out of the top 8 by chats that merely include a member.

Android (Rabbit R1) app, 0.2.0:
- Pull the chat list past its top for a search box (name, person,
  number, then group members; archived chats too; Back clears it).
- Swipe right to left marks a chat unread / read over a magenta band;
  left to right still archives (SwipeActions replaces SwipeArchive).
- Google Voice chats don't offer voice notes in the paperclip bubble.
- Chats open with their newest 60 messages, then the full history;
  marking read (and the Google Voice network call) waits until they're
  on screen. Cached pictures show at once, and one slow download no
  longer blocks the other images. Fixed a contacts reload race.
- Sandbox data gains filler chats, a named group and a 4,000-message chat.

Also: the Android app, Google Voice support, media, export, emoji and
the other work since the first commit, and a CLAUDE.md carrying the
privacy rule.
This commit is contained in:
2026-11-06 02:19:56 -08:00
parent a2b8f764db
commit 8c84feaa91
114 changed files with 12987 additions and 379 deletions
@@ -0,0 +1,799 @@
package me.teafry.voipmessages;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.util.Linkify;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONObject;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/** One conversation. */
public final class ChatActivity extends BaseActivity {
private static final int PICK = 1;
private static final int VOICE = 2;
private static final int CAMERA = 3;
/** A press on the paperclip shorter than this (ms), without dragging, is a tap: the bubble stays open. */
private static final int TAP_MS = 250;
private static final int MAX_PHOTOS = 3;
private String did, contact;
private boolean group;
private ListView list;
private TextView titleView, subView, counter, attach, send;
private EditText input;
private LinearLayout header, composerBox, tray, fromRow;
// The keyboard is up: the composer shrinks so what's being typed and the
// last few messages both fit above it (see setCompact).
private boolean compact;
private Spinner from;
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 Adapter adapter;
private boolean firstLoad = true;
/** How many messages to show first when a chat opens (a few screens' worth). */
private static final int RECENT = 60;
// Audio playing in the list: one at a time, keyed "id/index".
private android.media.MediaPlayer player;
private String playing;
// The bubble while a press on the paperclip is feeding it.
private AttachBubble bubble;
// Where the camera is writing the photo it's taking.
private Uri shot;
static Intent intent(Context c, String did, String contact) {
return new Intent(c, ChatActivity.class).putExtra("did", did).putExtra("contact", contact)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
@Override
protected void onCreate(Bundle b) {
super.onCreate(b);
did = getIntent().getStringExtra("did");
if (b != null) shot = b.getParcelable("shot");
contact = getIntent().getStringExtra("contact");
group = Phone.isGroup(contact);
LinearLayout root = new LinearLayout(this);
root.setOrientation(LinearLayout.VERTICAL);
header = new LinearLayout(this);
header.setOrientation(LinearLayout.VERTICAL);
header.setPadding(Ui.dp(this, 24), Ui.dp(this, 10), Ui.dp(this, 24), Ui.dp(this, 10));
header.setBackgroundColor(Ui.PANEL);
titleView = Ui.bold(Ui.text(this, "", Ui.T_NAME, Ui.TEXT));
titleView.setSingleLine();
titleView.setEllipsize(android.text.TextUtils.TruncateAt.END);
subView = Ui.text(this, "", Ui.T_TINY, Ui.MUTED);
subView.setSingleLine();
header.addView(titleView);
header.addView(subView);
if (group) header.setOnClickListener(v -> startActivity(InfoActivity.intent(this, did, contact)));
root.addView(header);
list = new ListView(this);
list.setDivider(null);
list.setSelector(android.R.color.transparent);
list.setStackFromBottom(true);
list.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_NORMAL);
list.setPadding(0, Ui.dp(this, 8), 0, Ui.dp(this, 8));
list.setClipToPadding(false);
adapter = new Adapter();
list.setAdapter(adapter);
root.addView(list, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1));
root.addView(composer());
setContentView(root);
root.getViewTreeObserver().addOnGlobalLayoutListener(() -> {
Rect r = new Rect();
root.getWindowVisibleDisplayFrame(r);
int screen = root.getRootView().getHeight();
boolean keyboard = screen - r.bottom > screen / 4;
if (keyboard != compact) setCompact(keyboard);
});
}
/**
* The R1 has 640 px of height and the keyboard takes about half: with a
* photo attached, the full-size composer would push the text box under
* it. So while it's up, the photos, text and padding all shrink and the
* subtitle goes, leaving the text box and a few messages in view.
*/
private void setCompact(boolean on) {
compact = on;
header.setPadding(Ui.dp(this, 24), Ui.dp(this, on ? 4 : 10), Ui.dp(this, 24), Ui.dp(this, on ? 4 : 10));
subView.setVisibility(on || subView.getText().length() == 0 ? View.GONE : View.VISIBLE);
composerBox.setPadding(Ui.dp(this, 12), Ui.dp(this, on ? 4 : 10), Ui.dp(this, 12), Ui.dp(this, on ? 4 : 10));
input.setTextSize(TypedValue.COMPLEX_UNIT_SP, on ? Ui.T_SMALL : Ui.T_BODY);
input.setPadding(Ui.dp(this, on ? 18 : 24), Ui.dp(this, on ? 8 : 14), Ui.dp(this, on ? 18 : 24), Ui.dp(this, on ? 8 : 14));
input.setMaxLines(on ? 3 : 4);
for (TextView b : new TextView[] {attach, send}) {
b.setMinWidth(Ui.dp(this, on ? 60 : 80));
b.setMinHeight(Ui.dp(this, on ? 56 : 80));
b.setTextSize(TypedValue.COMPLEX_UNIT_SP, on ? 28 : 34);
}
for (int i = 0; i < tray.getChildCount(); i++) tray.getChildAt(i).setLayoutParams(thumbParams());
if (on) list.post(this::showLatest);
}
/** The end of the last message at the bottom (setSelection alone shows its top). */
private void showLatest() {
list.setSelection(rows.size() - 1);
list.post(() -> {
View last = list.getChildAt(list.getChildCount() - 1);
if (last != null) list.scrollListBy(last.getBottom() - (list.getHeight() - list.getPaddingBottom()));
});
}
private LinearLayout.LayoutParams thumbParams() {
int s = Ui.dp(this, compact ? 64 : 120);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(s, s);
lp.rightMargin = Ui.dp(this, compact ? 6 : 10);
lp.bottomMargin = Ui.dp(this, compact ? 4 : 10);
return lp;
}
private View composer() {
LinearLayout box = composerBox = new LinearLayout(this);
box.setOrientation(LinearLayout.VERTICAL);
box.setBackgroundColor(Ui.PANEL);
box.setPadding(Ui.dp(this, 12), Ui.dp(this, 10), Ui.dp(this, 12), Ui.dp(this, 10));
// From-number picker, only for a conversation with nothing in it yet.
fromRow = new LinearLayout(this);
fromRow.setGravity(Gravity.CENTER_VERTICAL);
fromRow.addView(Ui.text(this, "From ", Ui.T_SMALL, Ui.MUTED));
from = new Spinner(this);
fromRow.addView(from);
fromRow.setVisibility(View.GONE);
box.addView(fromRow);
HorizontalScrollView trayScroll = new HorizontalScrollView(this);
tray = new LinearLayout(this);
trayScroll.addView(tray);
box.addView(trayScroll);
LinearLayout row = new LinearLayout(this);
row.setGravity(Gravity.BOTTOM);
attach = Ui.headerButton(this, "📎");
attach.setOnTouchListener((v, e) -> attachTouch(e));
input = new EditText(this);
input.setHint("Message");
input.setHintTextColor(Ui.FAINT);
input.setTextColor(Ui.TEXT);
input.setTextSize(TypedValue.COMPLEX_UNIT_SP, Ui.T_BODY);
input.setMaxLines(4);
input.setBackground(Ui.round(Ui.INPUT, Ui.dp(this, 36)));
input.setPadding(Ui.dp(this, 24), Ui.dp(this, 14), Ui.dp(this, 24), Ui.dp(this, 14));
send = Ui.headerButton(this, "➤");
send.setTextColor(Ui.ACCENT);
send.setOnClickListener(v -> submit());
row.addView(attach);
row.addView(input, new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1));
row.addView(send);
box.addView(row);
counter = Ui.text(this, "", Ui.T_TINY, Ui.MUTED);
counter.setGravity(Gravity.END);
counter.setVisibility(View.GONE);
box.addView(counter);
// An unsent message stays in the box, across app restarts, until sent or cleared.
String draft = drafts().getString(contact, "");
input.setText(draft);
input.setSelection(draft.length());
if (!draft.isEmpty()) updateCounter();
input.addTextChangedListener(new TextWatcher() {
public void beforeTextChanged(CharSequence s, int a, int b, int c) {}
public void onTextChanged(CharSequence s, int a, int b, int c) {}
public void afterTextChanged(Editable s) {
updateCounter();
saveDraft(s.toString());
}
});
return box;
}
private android.content.SharedPreferences drafts() {
return getSharedPreferences("drafts", MODE_PRIVATE);
}
private void saveDraft(String text) {
if (text.trim().isEmpty()) drafts().edit().remove(contact).apply();
else drafts().edit().putString(contact, text).apply();
}
private void updateCounter() {
int len = Phone.charCount(input.getText().toString().trim());
boolean gv = Config.get(this).isGv(did);
boolean show = !gv && len > 0;
counter.setVisibility(show ? View.VISIBLE : View.GONE);
if (show) counter.setText(len > Phone.SMS_TEXT_LIMIT || !photos.isEmpty() ? "MMS · " + len + "/2048" : len + "/160");
}
@Override
protected void onResume() {
super.onResume();
Notifier.clear(this, did, contact);
}
@Override
protected void onPause() {
super.onPause();
stopAudio();
}
@Override
public void changed() {
if (list == null) return;
boolean first = firstLoad;
MainActivity.bg.execute(() -> {
Store store = Store.get(this);
String name = store.getName(did, contact);
Contacts.all(this); // load names here, not on the main thread in show()
// Opening: the newest screenful first, so the chat appears at once
// however long its history; everything else follows right after.
if (first) {
List<Store.Msg> recent = store.recentMessages(did, contact, RECENT);
if (recent.size() == RECENT) post(recent, name, false);
}
post(store.messages(did, contact), name, true);
// Marking read (and telling Google Voice) waits until the messages are up.
if (store.hasUnread(did, contact)) {
StateSync.markRead(this, did, contact);
// Clear the badge on the phone / web too.
String thread = Config.get(this).isGv(did) ? store.gvThread(did, contact) : null;
if (thread != null) try {
new GVoice(Config.get(this)).markRead(thread);
} catch (Exception ignored) {
}
}
});
}
/** Off the main thread: fold the 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);
runOnUiThread(() -> {
reactions = folded;
show(msgs, name, complete);
});
}
/** `complete` is false for just the newest few, shown while the rest loads. */
private void show(List<Store.Msg> msgs, String name, boolean complete) {
titleView.setText(Contacts.title(this, contact, name));
String sub = group ? Phone.members(contact).size() + " people" : Contacts.lookup(this, contact) != null ? Phone.format(contact) : "";
if (Config.get(this).dids.size() > 1) sub += (sub.isEmpty() ? "" : " · ") + Ui.via(this, did);
subView.setText(sub);
subView.setVisibility(sub.isEmpty() || compact ? View.GONE : View.VISIBLE);
boolean atBottom = list.getLastVisiblePosition() >= rows.size() - 2;
// Not at the bottom: keep the message at the top of the screen where it is
// (older history may have just arrived above it).
int firstPos = list.getFirstVisiblePosition();
View firstView = list.getChildAt(0);
Object anchor = !atBottom && firstPos < rows.size() ? rows.get(firstPos) : null;
int anchorTop = firstView == null ? 0 : firstView.getTop();
rows.clear();
for (int i = 0; i < msgs.size(); i++) {
Store.Msg m = msgs.get(i);
if (i == 0 || !Ui.sameDay(msgs.get(i - 1).ts, m.ts)) rows.add(m.ts);
rows.add(m);
}
adapter.notifyDataSetChanged();
if (firstLoad || atBottom) list.setSelection(rows.size() - 1);
else if (anchor instanceof Store.Msg) {
long id = ((Store.Msg) anchor).id;
for (int i = 0; i < rows.size(); i++)
if (rows.get(i) instanceof Store.Msg && ((Store.Msg) rows.get(i)).id == id) {
list.setSelectionFromTop(i, anchorTop);
break;
}
}
if (complete) firstLoad = false;
// A conversation with nothing in it yet can still pick its number.
Config cfg = Config.get(this);
List<Config.Did> choices = new ArrayList<>();
for (Config.Did d : cfg.dids) if (!group || d.gv) choices.add(d);
if (msgs.isEmpty() && choices.size() > 1 && fromRow.getVisibility() != View.VISIBLE) {
List<String> labels = new ArrayList<>();
int sel = 0;
for (int i = 0; i < choices.size(); i++) {
labels.add(Phone.format(choices.get(i).did) + (choices.get(i).gv ? " — Google Voice" : ""));
if (choices.get(i).did.equals(did)) sel = i;
}
ArrayAdapter<String> a = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, labels);
from.setAdapter(a);
from.setSelection(sel);
from.setOnItemSelectedListener(new android.widget.AdapterView.OnItemSelectedListener() {
public void onItemSelected(android.widget.AdapterView<?> p, View v, int pos, long id) {
did = choices.get(pos).did;
updateCounter();
}
public void onNothingSelected(android.widget.AdapterView<?> p) {}
});
fromRow.setVisibility(View.VISIBLE);
} else if (!msgs.isEmpty()) {
fromRow.setVisibility(View.GONE);
}
}
private void submit() {
String text = input.getText().toString().trim();
if (text.isEmpty() && photos.isEmpty()) return;
if (!Config.get(this).isGv(did) && Phone.charCount(text) > 2048) {
Toast.makeText(this, "Too long for an MMS (2048 characters max).", Toast.LENGTH_SHORT).show();
return;
}
Sender.send(this, did, contact, text, new ArrayList<>(photos));
input.setText("");
photos.clear();
tray.removeAllViews();
fromRow.setVisibility(View.GONE);
list.setSelection(rows.size() - 1);
}
@Override
protected void onSaveInstanceState(Bundle out) {
super.onSaveInstanceState(out);
out.putParcelable("shot", shot);
}
/**
* Press the paperclip and the bubble is out at once: drag to a choice and
* let go. A quick tap leaves it open to tap a choice (or anywhere else to close).
*/
private boolean attachTouch(android.view.MotionEvent e) {
switch (e.getActionMasked()) {
case android.view.MotionEvent.ACTION_DOWN:
attach.getParent().requestDisallowInterceptTouchEvent(true);
// Google Voice only lets apps send photos: no voice-note choice there.
bubble = new AttachBubble(this, attach, composerBox, !Config.get(this).isGv(did), this::attachKind);
bubble.show(this);
return true;
case android.view.MotionEvent.ACTION_MOVE:
if (bubble != null) bubble.move(e.getRawX(), e.getRawY());
return true;
case android.view.MotionEvent.ACTION_UP:
if (bubble == null) return true;
if (e.getEventTime() - e.getDownTime() < TAP_MS && !bubble.dragged()) bubble.stay();
else bubble.release();
bubble = null;
return true;
case android.view.MotionEvent.ACTION_CANCEL:
if (bubble != null) bubble.dismiss();
bubble = null;
return true;
default:
return true;
}
}
private void attachKind(int which) {
if (which == AttachBubble.CAMERA) takePhoto();
else if (which == AttachBubble.PHOTO) pickPhotos();
else recordVoice();
}
// ---- voice notes ----
private void recordVoice() {
if (Config.get(this).isGv(did)) {
// sendsms only takes image types (see GVoice.mediaType).
new AlertDialog.Builder(this)
.setTitle("Voice note")
.setMessage("Google Voice only lets apps send photos, so voice notes can only go from a voip.ms number.")
.setPositiveButton("OK", null)
.show();
return;
}
startActivityForResult(new Intent(this, VoiceActivity.class), VOICE);
}
/** Play attachment `index` of message `id`, or stop it if it's the one playing. */
private void toggleAudio(long id, int index) {
String key = id + "/" + index;
boolean wasPlaying = key.equals(playing);
stopAudio();
if (wasPlaying) return;
playing = key;
adapter.notifyDataSetChanged();
MainActivity.bg.execute(() -> {
File f = Media.resolve(this, id, index);
runOnUiThread(() -> {
if (!key.equals(playing)) return;
android.media.MediaPlayer p = new android.media.MediaPlayer();
try {
if (f == null) throw new java.io.IOException();
p.setDataSource(f.getPath());
p.prepare();
} catch (Exception e) {
p.release();
stopAudio();
Toast.makeText(this, "Couldn't play that audio.", Toast.LENGTH_SHORT).show();
return;
}
p.setOnCompletionListener(x -> stopAudio());
p.start();
player = p;
});
});
}
private void stopAudio() {
if (player != null) player.release();
player = null;
if (playing != null) {
playing = null;
adapter.notifyDataSetChanged();
}
}
// ---- photos ----
private void pickPhotos() {
if (photos.size() >= MAX_PHOTOS) {
Toast.makeText(this, "At most " + MAX_PHOTOS + " photos per message.", Toast.LENGTH_SHORT).show();
return;
}
Intent i = new Intent(Intent.ACTION_GET_CONTENT).setType("image/*").addCategory(Intent.CATEGORY_OPENABLE)
.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
try {
startActivityForResult(Intent.createChooser(i, "Attach photos"), PICK);
} catch (Exception e) {
Toast.makeText(this, "No app on the Rabbit can pick photos.", Toast.LENGTH_SHORT).show();
}
}
/**
* The Rabbit's camera app, writing straight into a new MediaStore photo;
* once that's copied into the tray it's deleted again, so pictures taken
* for a message don't pile up in the gallery.
*/
private void takePhoto() {
if (photos.size() >= MAX_PHOTOS) {
Toast.makeText(this, "At most " + MAX_PHOTOS + " photos per message.", Toast.LENGTH_SHORT).show();
return;
}
android.content.ContentValues v = new android.content.ContentValues();
v.put(android.provider.MediaStore.Images.Media.DISPLAY_NAME, "bubble-" + System.currentTimeMillis() + ".jpg");
v.put(android.provider.MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
v.put(android.provider.MediaStore.Images.Media.RELATIVE_PATH, "Pictures/bubble");
try {
shot = getContentResolver().insert(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, v);
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE)
.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, shot)
.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivityForResult(i, CAMERA);
} catch (Exception e) {
deleteShot(shot);
shot = null;
Toast.makeText(this, "Couldn't open the camera.", Toast.LENGTH_SHORT).show();
}
}
private void deleteShot(Uri u) {
if (u != null) MainActivity.bg.execute(() -> {
try {
getContentResolver().delete(u, null, null);
} catch (Exception ignored) {
}
});
}
@Override
protected void onActivityResult(int req, int res, Intent data) {
super.onActivityResult(req, res, data);
if (req == CAMERA) {
Uri u = shot;
shot = null;
if (u == null) return;
if (res == RESULT_OK) attachPhoto(u, () -> deleteShot(u));
else deleteShot(u);
return;
}
if (req == VOICE && res == RESULT_OK && data != null) {
List<Sender.Photo> note = new ArrayList<>();
note.add(new Sender.Photo(data.getStringExtra("file"), data.getStringExtra("mime"), 0, 0));
Sender.send(this, did, contact, "", note);
fromRow.setVisibility(View.GONE);
list.setSelection(rows.size() - 1);
return;
}
if (req != PICK || res != RESULT_OK || data == null) return;
List<Uri> uris = new ArrayList<>();
ClipData clip = data.getClipData();
if (clip != null) for (int i = 0; i < clip.getItemCount(); i++) uris.add(clip.getItemAt(i).getUri());
else if (data.getData() != null) uris.add(data.getData());
for (Uri u : uris) {
if (photos.size() >= MAX_PHOTOS) break;
attachPhoto(u, null);
}
}
/** Shrink a photo to send, keep a copy, and put it in the tray; {@code after} runs (on the UI thread) either way. */
private void attachPhoto(Uri u, Runnable after) {
MainActivity.bg.execute(() -> {
try {
Object[] p = Media.prepare(this, u);
byte[] bytes = (byte[]) p[0];
String mime = (String) p[1];
String file = Media.save(this, bytes, mime);
android.graphics.BitmapFactory.Options o = new android.graphics.BitmapFactory.Options();
o.inJustDecodeBounds = true;
android.graphics.BitmapFactory.decodeByteArray(bytes, 0, bytes.length, o);
Sender.Photo photo = new Sender.Photo(file, mime, o.outWidth, o.outHeight);
runOnUiThread(() -> addToTray(photo));
} catch (Exception e) {
runOnUiThread(() -> Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show());
}
if (after != null) runOnUiThread(after);
});
}
private void addToTray(Sender.Photo p) {
if (photos.size() >= MAX_PHOTOS) return;
photos.add(p);
ImageView iv = new ImageView(this);
iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
iv.setImageBitmap(Media.bitmap(new File(Media.dir(this), p.file), Ui.dp(this, 120)));
iv.setOnClickListener(v -> {
photos.remove(p);
tray.removeView(iv);
updateCounter();
});
tray.addView(iv, thumbParams());
updateCounter();
}
// ---- the list ----
private final class Adapter extends BaseAdapter {
@Override
public int getCount() {
return rows.size();
}
@Override
public Object getItem(int i) {
return rows.get(i);
}
@Override
public long getItemId(int i) {
Object r = rows.get(i);
return r instanceof Store.Msg ? ((Store.Msg) r).id : -(Long) r;
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public int getViewTypeCount() {
return 2;
}
@Override
public int getItemViewType(int i) {
return rows.get(i) instanceof Store.Msg ? 1 : 0;
}
@Override
public boolean isEnabled(int i) {
return false;
}
@Override
public View getView(int i, View cv, ViewGroup parent) {
Object r = rows.get(i);
if (!(r instanceof Store.Msg)) {
TextView t = cv instanceof TextView ? (TextView) cv : Ui.bold(Ui.text(ChatActivity.this, "", Ui.T_TINY, Ui.MUTED));
t.setGravity(Gravity.CENTER);
t.setPadding(0, Ui.dp(ChatActivity.this, 18), 0, Ui.dp(ChatActivity.this, 10));
t.setText(Ui.dayLabel((Long) r));
return t;
}
Bubble b = cv instanceof Bubble ? (Bubble) cv : new Bubble(ChatActivity.this);
Store.Msg m = (Store.Msg) r;
Object prev = i > 0 ? rows.get(i - 1) : null;
boolean runStart = !(prev instanceof Store.Msg) || !((Store.Msg) prev).direction.equals(m.direction)
|| !java.util.Objects.equals(((Store.Msg) prev).sender, m.sender) || m.ts - ((Store.Msg) prev).ts > 5 * 60_000;
b.bind(m, group && m.in() && m.sender != null && runStart);
return b;
}
}
private final class Bubble extends LinearLayout {
final TextView sender, body, meta, failed, reacts;
final LinearLayout bubble, media;
Store.Msg m;
Bubble(Context c) {
super(c);
setOrientation(VERTICAL);
setPadding(Ui.dp(c, 16), Ui.dp(c, 3), Ui.dp(c, 16), Ui.dp(c, 3));
sender = Ui.text(c, "", Ui.T_TINY, Ui.MUTED);
sender.setPadding(Ui.dp(c, 14), Ui.dp(c, 10), 0, Ui.dp(c, 4));
bubble = new LinearLayout(c);
bubble.setOrientation(VERTICAL);
bubble.setPadding(Ui.dp(c, 20), Ui.dp(c, 12), Ui.dp(c, 20), Ui.dp(c, 12));
media = new LinearLayout(c);
media.setOrientation(VERTICAL);
body = Ui.text(c, "", Ui.T_BODY, Ui.TEXT);
body.setAutoLinkMask(Linkify.WEB_URLS);
body.setLinkTextColor(0xFFFFFFFF);
meta = Ui.text(c, "", Ui.T_TINY, 0xB3FFFFFF);
meta.setGravity(Gravity.END);
bubble.addView(media);
bubble.addView(body);
bubble.addView(meta);
failed = Ui.text(c, "", Ui.T_TINY, Ui.DANGER);
reacts = Ui.text(c, "", Ui.T_SMALL, Ui.TEXT);
reacts.setBackground(Ui.round(Ui.BUBBLE_IN, Ui.dp(c, 30)));
reacts.setPadding(Ui.dp(c, 14), Ui.dp(c, 4), Ui.dp(c, 14), Ui.dp(c, 4));
reacts.setOnClickListener(v -> showReactions(m));
addView(sender);
addView(bubble, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
LayoutParams rlp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
rlp.topMargin = -Ui.dp(c, 10);
rlp.leftMargin = Ui.dp(c, 16);
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 -> {
if (m == null) return true;
if (!m.body.isEmpty()) copyText(m.body);
else if ("failed".equals(m.status)) failedMenu(m);
return true;
};
bubble.setOnLongClickListener(copy);
body.setOnLongClickListener(copy);
bubble.setOnClickListener(v -> {
if (m != null && "failed".equals(m.status)) failedMenu(m);
});
}
void bind(Store.Msg msg, boolean showSender) {
m = msg;
Context c = getContext();
boolean out = !msg.in();
setGravity(out ? Gravity.END : Gravity.START);
((LayoutParams) bubble.getLayoutParams()).gravity = out ? Gravity.END : Gravity.START;
bubble.setBackground(Ui.round(out ? Ui.ACCENT : Ui.BUBBLE_IN, Ui.dp(c, 30)));
bubble.setAlpha("failed".equals(msg.status) ? 0.6f : 1f);
bubble.setMinimumWidth(0);
// Keep bubbles to ~80% of the width.
body.setMaxWidth(Math.round(getResources().getDisplayMetrics().widthPixels * 0.72f));
sender.setVisibility(showSender ? VISIBLE : GONE);
if (showSender) sender.setText(Contacts.name(c, msg.sender));
body.setText(msg.body);
body.setVisibility(msg.body.isEmpty() ? GONE : VISIBLE);
String status = "pending".equals(msg.status) ? " 🕓" : "";
meta.setText(Ui.timeOfDay(c, msg.ts) + status);
meta.setTextColor(out ? 0xB3FFFFFF : Ui.MUTED);
failed.setVisibility("failed".equals(msg.status) ? VISIBLE : GONE);
failed.setText("⚠ Not sent" + (msg.error != null ? ": " + msg.error : "") + " · tap to retry");
List<Reactions.Reaction> rs = reactions.get(msg.id);
reacts.setVisibility(rs == null ? GONE : VISIBLE);
if (rs != null) {
java.util.LinkedHashSet<String> emojis = new java.util.LinkedHashSet<>();
for (Reactions.Reaction r : rs) emojis.add(r.emoji);
reacts.setText(String.join("", emojis) + (rs.size() > 1 ? " " + rs.size() : ""));
((LayoutParams) reacts.getLayoutParams()).gravity = out ? Gravity.END : Gravity.START;
}
media.removeAllViews();
List<JSONObject> refs = msg.media();
for (int i = 0; i < refs.size(); i++) media.addView(image(msg.id, i, refs.get(i)));
}
private View image(long id, int index, JSONObject ref) {
Context c = getContext();
int maxW = Ui.dp(c, 300), maxH = Ui.dp(c, 360);
int w = ref.optInt("width"), h = ref.optInt("height");
float scale = w > 0 && h > 0 ? Math.min(1f, Math.min(maxW / (float) w, maxH / (float) h)) : 1f;
int bw = w > 0 ? Math.round(w * scale) : Ui.dp(c, 200), bh = h > 0 ? Math.round(h * scale) : Ui.dp(c, 200);
String mime = ref.optString("mime", "");
if (mime.startsWith("audio/")) {
TextView t = Ui.bold(Ui.text(c, ((id + "/" + index).equals(playing) ? "⏸" : "▶") + " Voice note",
Ui.T_SMALL, Ui.TEXT));
t.setPadding(0, Ui.dp(c, 10), Ui.dp(c, 20), Ui.dp(c, 10));
t.setOnClickListener(v -> toggleAudio(id, index));
return t;
}
if (!mime.isEmpty() && !mime.startsWith("image/")) {
TextView t = Ui.text(c, mime.startsWith("video/") ? "🎥 Video" : "📎 Attachment", Ui.T_SMALL, Ui.TEXT);
t.setPadding(0, Ui.dp(c, 6), 0, Ui.dp(c, 6));
return t;
}
ImageView iv = new ImageView(c);
iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
iv.setBackgroundColor(0x22FFFFFF);
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(bw, bh);
iv.setLayoutParams(new LinearLayout.LayoutParams(bw, bh));
String tag = id + "/" + index;
iv.setTag(tag);
// Seen already: show it now rather than blank-then-pop on every redraw.
Bitmap hit = Media.cached(ref, Math.max(maxW, maxH));
if (hit != null) {
iv.setImageBitmap(hit);
File f = new File(Media.dir(c), new File(ref.optString("file")).getName());
iv.setOnClickListener(v -> startActivity(new Intent(c, ImageActivity.class).putExtra("file", f.getPath())));
return iv;
}
MainActivity.bg.execute(() -> {
File f = Media.resolve(c, id, index);
Bitmap bm = f == null ? null : Media.bitmap(f, Math.max(maxW, maxH));
iv.post(() -> {
if (!tag.equals(iv.getTag())) return;
if (bm != null) {
iv.setImageBitmap(bm);
iv.setOnClickListener(v -> startActivity(new Intent(c, ImageActivity.class).putExtra("file", f.getPath())));
}
});
});
return iv;
}
}
/** Who reacted with what. */
private void showReactions(Store.Msg m) {
List<Reactions.Reaction> rs = m == null ? null : reactions.get(m.id);
if (rs == null) return;
String[] lines = new String[rs.size()];
for (int i = 0; i < rs.size(); i++)
lines[i] = rs.get(i).emoji + " " + ("me".equals(rs.get(i).from) ? "You" : Contacts.name(this, rs.get(i).from));
new AlertDialog.Builder(this).setTitle("Reactions").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);
cm.setPrimaryClip(ClipData.newPlainText("Message", text));
}
private void failedMenu(Store.Msg m) {
new AlertDialog.Builder(this)
.setTitle("Not sent")
.setMessage(m.error == null ? "This message didn't go out." : m.error)
.setPositiveButton("Retry", (d, w) -> MainActivity.bg.execute(() -> Sender.retry(this, m.id)))
.setNegativeButton("Delete", (d, w) -> {
Store.get(this).deleteMessage(m.id);
changed();
})
.setNeutralButton("Cancel", null)
.show();
}
}