package me.teafry.voipmessages; import android.app.AlertDialog; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.util.TypedValue; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.widget.AbsListView; import android.widget.EditText; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** The conversation list. */ public final class MainActivity extends BaseActivity { static final ExecutorService bg = Executors.newCachedThreadPool(); private ListView list; private PullRefresh pull; private TextView status, title; private final List convs = new ArrayList<>(); // what the list shows private final List loaded = new ArrayList<>(); // every conversation, archived or not private EditText search; private View searchBox; private TextView noMatches; // Keep the search box tucked above the top until the list is next touched // (re-applied on every redraw, since a redraw before the list has laid out // would otherwise put it back where it was). private boolean hideSearch = true; private boolean archived; private Adapter adapter; @Override protected void onCreate(Bundle b) { super.onCreate(b); LinearLayout root = new LinearLayout(this); root.setOrientation(LinearLayout.VERTICAL); LinearLayout header = new LinearLayout(this); header.setGravity(Gravity.CENTER_VERTICAL); header.setPadding(Ui.dp(this, 24), Ui.dp(this, 8), Ui.dp(this, 8), Ui.dp(this, 8)); title = Ui.bold(Ui.text(this, "Messages", Ui.T_TITLE, Ui.TEXT)); header.addView(title, new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1)); TextView compose = Ui.headerButton(this, Glyph.Kind.COMPOSE); compose.setOnClickListener(v -> startActivity(new Intent(this, NewChatActivity.class))); TextView archive = Ui.headerButton(this, Glyph.Kind.ARCHIVE); archive.setOnClickListener(v -> { archived = !archived; hideSearch = true; changed(); }); TextView settings = Ui.headerButton(this, Glyph.Kind.GEAR); settings.setOnClickListener(v -> startActivity(new Intent(this, SettingsActivity.class))); header.addView(compose); header.addView(archive); header.addView(settings); root.addView(header); status = Ui.text(this, "", Ui.T_SMALL, Ui.DANGER); status.setPadding(Ui.dp(this, 24), 0, Ui.dp(this, 24), Ui.dp(this, 8)); status.setVisibility(View.GONE); root.addView(status); list = new ListView(this); list.setDivider(null); list.setSelector(android.R.color.transparent); adapter = new Adapter(); list.setItemsCanFocus(true); list.addHeaderView(searchBox(), null, false); FrameLayout footer = new FrameLayout(this); noMatches = Ui.text(this, "No chats match", Ui.T_SMALL, Ui.MUTED); noMatches.setGravity(Gravity.CENTER); noMatches.setPadding(0, Ui.dp(this, 40), 0, Ui.dp(this, 40)); noMatches.setVisibility(View.GONE); footer.addView(noMatches, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT)); list.addFooterView(footer, null, false); list.setAdapter(adapter); list.setOnItemClickListener((p, v, pos, id) -> { Store.Conv c = conv(pos); if (c != null) startActivity(ChatActivity.intent(this, c.did, c.contact)); }); list.setOnItemLongClickListener((p, v, pos, id) -> { Store.Conv c = conv(pos); if (c != null) menu(c); return c != null; }); list.setOnScrollListener(new AbsListView.OnScrollListener() { @Override public void onScrollStateChanged(AbsListView view, int state) { // Scrolling through results: the keyboard (half the R1's screen) gets out of the way. if (state == SCROLL_STATE_TOUCH_SCROLL) hideSearch = false; if (state == SCROLL_STATE_TOUCH_SCROLL && search.hasFocus()) hideKeyboard(); if (state == SCROLL_STATE_IDLE) snapSearch(); } @Override public void onScroll(AbsListView view, int first, int visible, int total) {} }); new SwipeActions(list, (pos, rightward) -> { Store.Conv c = conv(pos); if (c == null) return; if (rightward) StateSync.setArchived(this, c.did, c.contact, !c.archived); else if (c.unread > 0 || c.markedUnread) StateSync.markRead(this, c.did, c.contact); else StateSync.markUnread(this, c.did, c.contact); changed(); }); pull = new PullRefresh(this, list); pull.onRefresh = this::refresh; root.addView(pull, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1)); setContentView(root); // The screen holds focus, not the search box: a focused box would // scroll itself into view (and up comes the keyboard). root.setFocusableInTouchMode(true); root.requestFocus(); Alarms.schedule(this); if (!Config.get(this).configured()) { new AlertDialog.Builder(this) .setTitle("Not set up yet") .setMessage("Install from the desktop app (Settings → Rabbit → Install to Rabbit) to copy your accounts and history here." + " Or text from the Rabbit's own SIM card by making bubble its texting app.") .setPositiveButton("OK", null) .setNeutralButton("Use the SIM", (d, w) -> startActivity(new Intent(this, SettingsActivity.class))) .show(); } } @Override protected void onResume() { super.onResume(); Contacts.invalidate(); // Catch up whenever the app comes to the front. refresh(); } private static long lastRelay; private void refresh() { bg.execute(() -> { Sync.poll(this); runOnUiThread(() -> pull.setRefreshing(false)); }); } /** The conversation at a list position (which counts the search box above them), or null. */ private Store.Conv conv(int pos) { int i = pos - list.getHeaderViewsCount(); return i >= 0 && i < convs.size() ? convs.get(i) : null; } /** * Above the first chat, out of sight until the list is pulled down past * its top. Matches what a chat is called (your name for it, the person), * then group chats with a matching member, archived ones too. */ private View searchBox() { LinearLayout box = new LinearLayout(this); box.setPadding(Ui.dp(this, 20), Ui.dp(this, 6), Ui.dp(this, 20), Ui.dp(this, 10)); search = new EditText(this); search.setHint("Search"); search.setHintTextColor(Ui.MUTED); search.setTextColor(Ui.TEXT); search.setTextSize(TypedValue.COMPLEX_UNIT_SP, Ui.T_SMALL); search.setSingleLine(); search.setImeOptions(EditorInfo.IME_ACTION_SEARCH | EditorInfo.IME_FLAG_NO_EXTRACT_UI); search.setBackground(Ui.input(this, 30)); search.setPadding(Ui.dp(this, 24), Ui.dp(this, 12), Ui.dp(this, 24), Ui.dp(this, 12)); search.setOnEditorActionListener((v, action, e) -> { hideKeyboard(); return true; }); search.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) { filter(); } }); box.addView(search, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); searchBox = box; return box; } private String query() { return search.getText().toString().trim(); } private void hideKeyboard() { ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(search.getWindowToken(), 0); search.clearFocus(); } /** Let go with the search box half showing: all the way out, or back out of sight. */ private void snapSearch() { if (list.getFirstVisiblePosition() != 0 || !query().isEmpty() || search.hasFocus()) return; int top = searchBox.getTop(), bottom = searchBox.getBottom(); if (top >= 0 || bottom <= 0) return; list.smoothScrollBy(bottom > searchBox.getHeight() / 2 ? top : bottom, 150); } @Override public void onBackPressed() { if (!query().isEmpty() || search.hasFocus()) { hideSearch = true; search.setText(""); hideKeyboard(); return; } super.onBackPressed(); } /** Everything that starts with or contains each word typed; a number by its digits. */ static boolean matches(String query, String name, String number) { String q = query.trim().toLowerCase(); if (q.isEmpty()) return false; String digits = q.replaceAll("\\D", ""); if (digits.length() >= 3 && q.matches("[\\d\\s()+.-]+") && number.contains(digits.replaceFirst("^1(?=\\d{10}$)", ""))) return true; String n = name.toLowerCase(); for (String w : q.split("\\s+")) if (!n.contains(w)) return false; return true; } /** What the list shows: this view's chats, or everything matching the search. */ private void filter() { String q = query(); convs.clear(); if (q.isEmpty()) { for (Store.Conv c : loaded) if (c.archived == archived) convs.add(c); } else { // Chats whose own name matches come first, so one you named isn't // buried under every chat that merely includes a matching person. List byMember = new ArrayList<>(); for (Store.Conv c : loaded) { if (matches(q, Contacts.title(this, c.contact, c.name), c.contact)) { convs.add(c); continue; } for (String m : Phone.members(c.contact)) if (matches(q, Contacts.name(this, m), m)) { byMember.add(c); break; } } convs.addAll(byMember); } noMatches.setVisibility(!q.isEmpty() && convs.isEmpty() ? View.VISIBLE : View.GONE); adapter.notifyDataSetChanged(); if (hideSearch && q.isEmpty()) list.setSelection(list.getHeaderViewsCount()); } @Override public void changed() { if (list == null) return; bg.execute(() -> { StateSync.importPending(this); Sim.syncSoon(this); if (System.currentTimeMillis() - lastRelay > 60_000) { lastRelay = System.currentTimeMillis(); Relay.soon(this); } List fresh = Store.get(this).conversations(null); Contacts.all(this); // load names here, not on the main thread while drawing rows runOnUiThread(() -> { loaded.clear(); loaded.addAll(fresh); filter(); title.setText(archived ? "Archived" : "Messages"); String err = Sync.gvSignedOut ? "Google Voice signed out. Reconnect it on the desktop, then Sync to Rabbit." : Sync.voipError != null ? "voip.ms: " + Sync.voipError : Sync.gvError != null ? "Google Voice: " + Sync.gvError : null; status.setText(err == null ? "" : "⚠ " + err); status.setVisibility(err == null ? View.GONE : View.VISIBLE); }); }); } private void menu(Store.Conv c) { List labels = new ArrayList<>(); List actions = new ArrayList<>(); Store store = Store.get(this); if (Phone.isGroup(c.contact)) { labels.add("Get info"); actions.add(() -> startActivity(InfoActivity.intent(this, c.did, c.contact))); } labels.add(c.unread > 0 || c.markedUnread ? "Mark as read" : "Mark as unread"); actions.add(() -> { if (c.unread > 0 || c.markedUnread) StateSync.markRead(this, c.did, c.contact); else StateSync.markUnread(this, c.did, c.contact); changed(); }); labels.add(c.archived ? "Unarchive" : "Archive"); actions.add(() -> { StateSync.setArchived(this, c.did, c.contact, !c.archived); changed(); }); new AlertDialog.Builder(this) .setTitle(Contacts.title(this, c.contact, c.name)) .setItems(labels.toArray(new String[0]), (d, i) -> actions.get(i).run()) .show(); } private final class Adapter extends BaseAdapter { @Override public int getCount() { return convs.size(); } @Override public Object getItem(int i) { return convs.get(i); } @Override public long getItemId(int i) { return i; } @Override public View getView(int i, View convertView, ViewGroup parent) { Context ctx = MainActivity.this; Row row = convertView instanceof Row ? (Row) convertView : new Row(ctx); row.bind(convs.get(i)); return row; } } /** * One conversation: avatar, name + time, preview + unread badge, "via"; * over a band that a swipe uncovers (see SwipeActions). */ private final class Row extends FrameLayout implements SwipeActions.Row { Store.Conv conv; final LinearLayout front; final TextView under; final View avatar; final TextView name, time, preview, badge, via; Row(Context c) { super(c); under = Ui.bold(Ui.text(c, "", Ui.T_SMALL, 0xFFFFFFFF)); under.setGravity(Gravity.CENTER_VERTICAL); under.setPadding(Ui.dp(c, 28), 0, Ui.dp(c, 28), 0); addView(under, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT)); front = new LinearLayout(c); front.setBackgroundColor(Ui.BG); front.setGravity(Gravity.CENTER_VERTICAL); front.setPadding(Ui.dp(c, 20), Ui.dp(c, 14), Ui.dp(c, 20), Ui.dp(c, 14)); addView(front); avatar = new View(c); int size = Ui.dp(c, 84); LinearLayout.LayoutParams alp = new LinearLayout.LayoutParams(size, size); alp.rightMargin = Ui.dp(c, 18); front.addView(avatar, alp); LinearLayout main = new LinearLayout(c); main.setOrientation(LinearLayout.VERTICAL); LinearLayout top = new LinearLayout(c); name = Ui.bold(Ui.text(c, "", Ui.T_NAME, Ui.TEXT)); name.setSingleLine(); name.setEllipsize(TextUtils.TruncateAt.END); time = Ui.text(c, "", Ui.T_TINY, Ui.MUTED); time.setPadding(Ui.dp(c, 8), 0, 0, 0); top.addView(name, new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1)); top.addView(time); LinearLayout bottom = new LinearLayout(c); bottom.setGravity(Gravity.CENTER_VERTICAL); preview = Ui.text(c, "", Ui.T_SMALL, Ui.MUTED); preview.setMaxLines(2); preview.setEllipsize(TextUtils.TruncateAt.END); badge = Ui.bold(Ui.text(c, "", Ui.T_TINY, 0xFFFFFFFF)); badge.setGravity(Gravity.CENTER); badge.setMinWidth(Ui.dp(c, 40)); badge.setPadding(Ui.dp(c, 10), Ui.dp(c, 2), Ui.dp(c, 10), Ui.dp(c, 2)); badge.setBackground(Ui.round(Ui.ACCENT, Ui.dp(c, 20))); bottom.addView(preview, new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1)); LinearLayout.LayoutParams blp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); blp.leftMargin = Ui.dp(c, 8); bottom.addView(badge, blp); via = Ui.text(c, "", Ui.T_TINY, Ui.FAINT); main.addView(top); main.addView(bottom); main.addView(via); front.addView(main, new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1)); } @Override public View front() { return front; } @Override public View under() { return under; } @Override public void reveal(boolean rightward) { boolean unread = conv.unread > 0 || conv.markedUnread; under.setText(rightward ? (conv.archived ? "Unarchive" : "Archive") : unread ? "Read" : "Unread"); Ui.glyph(under, rightward ? (conv.archived ? Glyph.Kind.UNARCHIVE : Glyph.Kind.ARCHIVE) : unread ? Glyph.Kind.CHECK : Glyph.Kind.MAIL, false); under.setGravity(Gravity.CENTER_VERTICAL | (rightward ? Gravity.START : Gravity.END)); } void bind(Store.Conv c) { Context ctx = getContext(); conv = c; SwipeActions.reset(this); boolean group = Phone.isGroup(c.contact); String title = Contacts.title(ctx, c.contact, c.name); avatar.setBackground(Ui.avatar(c.contact, group ? null : Contacts.lookup(ctx, c.contact) == null ? null : title, group)); name.setText(title); time.setText(Ui.shortTime(ctx, c.lastTs)); String reaction = Reactions.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) + ": " : ""; preview.setText(who + body); boolean unread = c.unread > 0 || c.markedUnread; preview.setTextColor(unread ? Ui.TEXT : Ui.MUTED); badge.setVisibility(unread ? VISIBLE : GONE); badge.setText(c.unread > 99 ? "99+" : c.unread > 0 ? String.valueOf(c.unread) : "•"); via.setText(Config.get(ctx).dids.size() > 1 ? Ui.via(ctx, c.did) : ""); via.setVisibility(Config.get(ctx).dids.size() > 1 ? VISIBLE : GONE); } } }