crumb = new HashMap<>();
crumb.put("draft", Long.toString(id));
crumb.put("reference", Long.toString(reference));
crumb.put("action", action);
Log.breadcrumb("compose", crumb);
EntityMessage draft;
DB db = DB.getInstance(context);
try {
db.beginTransaction();
draft = db.message().getMessage(id);
if (draft == null || draft.ui_hide != 0) {
// New draft
if ("edit".equals(action))
throw new MessageRemovedException("Draft for edit was deleted hide=" + (draft != null));
EntityFolder drafts;
EntityMessage ref = db.message().getMessage(reference);
if (ref == null) {
long aid = args.getLong("account", -1);
if (aid < 0)
drafts = db.folder().getPrimaryDrafts();
else {
drafts = db.folder().getFolderByType(aid, EntityFolder.DRAFTS);
if (drafts == null)
drafts = db.folder().getPrimaryDrafts();
}
if (drafts == null)
throw new IllegalArgumentException(context.getString(R.string.title_no_primary_drafts));
} else {
drafts = db.folder().getFolderByType(ref.account, EntityFolder.DRAFTS);
if (drafts == null)
drafts = db.folder().getPrimaryDrafts();
if (drafts == null)
throw new IllegalArgumentException(context.getString(R.string.title_no_primary_drafts));
}
String body = "";
draft = new EntityMessage();
draft.account = drafts.account;
draft.folder = drafts.id;
draft.msgid = EntityMessage.generateMessageId();
if (ref == null) {
draft.thread = draft.msgid;
try {
String to = args.getString("to");
draft.to = (TextUtils.isEmpty(to) ? null : InternetAddress.parse(to));
} catch (AddressException ex) {
Log.w(ex);
}
try {
String cc = args.getString("cc");
draft.cc = (TextUtils.isEmpty(cc) ? null : InternetAddress.parse(cc));
} catch (AddressException ex) {
Log.w(ex);
}
try {
String bcc = args.getString("bcc");
draft.bcc = (TextUtils.isEmpty(bcc) ? null : InternetAddress.parse(bcc));
} catch (AddressException ex) {
Log.w(ex);
}
draft.subject = args.getString("subject", "");
body = args.getString("body", "");
body = body.replaceAll("\\r?\\n", "
");
if (answer > 0) {
EntityAnswer a = db.answer().getAnswer(answer);
if (a != null) {
draft.subject = a.name;
body = EntityAnswer.getAnswerText(a, null) + body;
}
}
} else {
// Actions:
// - reply
// - reply_all
// - forward
// - editasnew
// - list
// - receipt
// - participation
if ("reply".equals(action) || "reply_all".equals(action) ||
"list".equals(action) ||
"receipt".equals(action) ||
"participation".equals(action)) {
if (ref.to != null && ref.to.length > 0) {
String to = ((InternetAddress) ref.to[0]).getAddress();
int at = to.indexOf('@');
if (at > 0)
draft.extra = to.substring(0, at);
}
draft.references = (ref.references == null ? "" : ref.references + " ") + ref.msgid;
draft.inreplyto = ref.msgid;
draft.thread = ref.thread;
String via = null;
if (ref.identity != null) {
EntityIdentity identity = db.identity().getIdentity(ref.identity);
draft.from = new Address[]{new InternetAddress(identity.email, identity.name)};
via = MessageHelper.canonicalAddress(identity.email);
}
if ("list".equals(action) && ref.list_post != null)
draft.to = ref.list_post;
else if ("receipt".equals(action) && ref.receipt_to != null)
draft.to = ref.receipt_to;
else {
// Prevent replying to self
if (ref.replySelf(via)) {
draft.to = ref.to;
draft.from = ref.from;
} else
draft.to = (ref.reply == null || ref.reply.length == 0 ? ref.from : ref.reply);
}
if ("reply_all".equals(action))
draft.cc = ref.getAllRecipients(via);
else if ("receipt".equals(action))
draft.receipt_request = true;
} else if ("forward".equals(action) || "editasnew".equals(action))
draft.thread = draft.msgid; // new thread
String subject = (ref.subject == null ? "" : ref.subject);
if ("reply".equals(action) || "reply_all".equals(action)) {
if (prefix_once) {
String re = context.getString(R.string.title_subject_reply, "");
subject = subject.replaceAll("(?i)" + Pattern.quote(re.trim()), "").trim();
}
draft.subject = context.getString(R.string.title_subject_reply, subject);
} else if ("forward".equals(action)) {
if (prefix_once) {
String fwd = context.getString(R.string.title_subject_forward, "");
subject = subject.replaceAll("(?i)" + Pattern.quote(fwd.trim()), "").trim();
}
draft.subject = context.getString(R.string.title_subject_forward, subject);
} else if ("editasnew".equals(action)) {
draft.subject = ref.subject;
if (ref.content) {
String html = Helper.readText(ref.getFile(context));
body = HtmlHelper.sanitize(context, html, true);
}
} else if ("list".equals(action)) {
draft.subject = ref.subject;
} else if ("receipt".equals(action)) {
draft.subject = context.getString(R.string.title_receipt_subject, subject);
Configuration configuration = new Configuration(context.getResources().getConfiguration());
configuration.setLocale(new Locale("en"));
Resources res = context.createConfigurationContext(configuration).getResources();
body = "" + context.getString(R.string.title_receipt_text) + "
";
if (!Locale.getDefault().getLanguage().equals("en"))
body += "" + res.getString(R.string.title_receipt_text) + "
";
} else if ("participation".equals(action))
draft.subject = status + ": " + ref.subject;
draft.plain_only = ref.plain_only;
if (answer > 0)
body = EntityAnswer.getAnswerText(context, answer, draft.to) + body;
EntityOperation.queue(context, ref, EntityOperation.SEEN, true);
}
if (plain_only)
draft.plain_only = true;
// Select identity matching from address
int icount = 0;
EntityIdentity first = null;
EntityIdentity primary = null;
List identities = db.identity().getComposableIdentities(null);
int iindex = -1;
do {
String from = null;
if (iindex >= 0)
from = MessageHelper.canonicalAddress(((InternetAddress) draft.from[iindex]).getAddress());
for (EntityIdentity identity : identities) {
String email = MessageHelper.canonicalAddress(identity.email);
if (email.equals(from)) {
draft.identity = identity.id;
draft.from = new InternetAddress[]{new InternetAddress(identity.email, identity.name)};
break;
}
if (identity.account.equals(draft.account)) {
icount++;
if (identity.primary)
primary = identity;
if (first == null)
first = identity;
}
}
if (draft.identity != null)
break;
iindex++;
} while (iindex < (draft.from == null ? -1 : draft.from.length));
// Select identity
if (draft.identity == null) {
if (primary != null) {
draft.identity = primary.id;
draft.from = new InternetAddress[]{new InternetAddress(primary.email, primary.name)};
} else if (first != null && icount == 1) {
draft.identity = first.id;
draft.from = new InternetAddress[]{new InternetAddress(first.email, first.name)};
}
}
draft.sender = MessageHelper.getSortKey(draft.from);
Uri lookupUri = ContactInfo.getLookupUri(context, draft.from);
draft.avatar = (lookupUri == null ? null : lookupUri.toString());
draft.received = new Date().getTime();
draft.seen = true;
draft.ui_seen = true;
draft.id = db.message().insertMessage(draft);
Helper.writeText(draft.getFile(context), body);
db.message().setMessageContent(draft.id,
true,
draft.plain_only,
HtmlHelper.getPreview(body),
null);
if ("participation".equals(action)) {
EntityAttachment attachment = new EntityAttachment();
attachment.message = draft.id;
attachment.sequence = 1;
attachment.name = "meeting.ics";
attachment.type = "text/calendar";
attachment.disposition = Part.ATTACHMENT;
attachment.size = ics.length();
attachment.progress = null;
attachment.available = true;
attachment.id = db.attachment().insertAttachment(attachment);
ics.renameTo(attachment.getFile(context));
}
// Write reference text
if (ref != null && ref.content &&
!"editasnew".equals(action) &&
!"list".equals(action) &&
!"receipt".equals(action)) {
String refBody = String.format("%s %s:
\n%s
",
Html.escapeHtml(new Date(ref.received).toString()),
Html.escapeHtml(MessageHelper.formatAddresses(ref.from)),
Helper.readText(ref.getFile(context)));
Helper.writeText(draft.getRefFile(context), refBody);
}
if ("new".equals(action)) {
ArrayList uris = args.getParcelableArrayList("attachments");
if (uris != null)
for (Uri uri : uris)
addAttachment(context, draft.id, uri, false);
} else if (ref != null &&
("reply".equals(action) || "reply_all".equals(action) ||
"forward".equals(action) || "editasnew".equals(action))) {
int sequence = 0;
List attachments = db.attachment().getAttachments(ref.id);
for (EntityAttachment attachment : attachments)
if (attachment.encryption != null &&
attachment.encryption.equals(EntityAttachment.PGP_MESSAGE)) {
draft.encrypt = true;
db.message().setMessageEncrypt(draft.id, true);
} else if (attachment.encryption == null &&
("forward".equals(action) || "editasnew".equals(action) ||
(attachment.isInline() && attachment.isImage()))) {
if (attachment.available) {
File source = attachment.getFile(context);
attachment.id = null;
attachment.message = draft.id;
attachment.sequence = ++sequence;
attachment.id = db.attachment().insertAttachment(attachment);
File target = attachment.getFile(context);
Helper.copy(source, target);
if (!"forward".equals(action))
resizeAttachment(context, attachment);
} else
args.putBoolean("incomplete", true);
}
}
EntityOperation.queue(context, draft, EntityOperation.ADD);
} else {
if (!draft.content) {
if (draft.uid == null)
throw new IllegalStateException("Draft without uid");
EntityOperation.queue(context, draft, EntityOperation.BODY);
}
List attachments = db.attachment().getAttachments(draft.id);
for (EntityAttachment attachment : attachments)
if (!attachment.available)
EntityOperation.queue(context, draft, EntityOperation.ATTACHMENT, attachment.id);
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
return draft;
}
@Override
protected void onExecuted(Bundle args, final EntityMessage draft) {
working = draft.id;
final String action = getArguments().getString("action");
Log.i("Loaded draft id=" + draft.id + " action=" + action);
etExtra.setText(draft.extra);
etTo.setText(MessageHelper.formatAddressesCompose(draft.to));
etCc.setText(MessageHelper.formatAddressesCompose(draft.cc));
etBcc.setText(MessageHelper.formatAddressesCompose(draft.bcc));
etSubject.setText(draft.subject);
long reference = args.getLong("reference", -1);
etTo.setTag(reference < 0 ? "" : etTo.getText().toString());
etSubject.setTag(reference < 0 ? "" : etSubject.getText().toString());
grpHeader.setVisibility(View.VISIBLE);
grpAddresses.setVisibility("reply_all".equals(action) ? View.VISIBLE : View.GONE);
ivCcBcc.setVisibility(View.VISIBLE);
bottom_navigation.getMenu().findItem(R.id.action_undo).setVisible(draft.revision != null && draft.revision > 1);
bottom_navigation.getMenu().findItem(R.id.action_redo).setVisible(draft.revision != null && !draft.revision.equals(draft.revisions));
plain_only = (draft.plain_only != null && draft.plain_only);
encrypt = (draft.encrypt != null && draft.encrypt);
getActivity().invalidateOptionsMenu();
if (args.getBoolean("incomplete"))
Snackbar.make(view, R.string.title_attachments_incomplete, Snackbar.LENGTH_LONG).show();
new SimpleTask>() {
@Override
protected List onExecute(Context context, Bundle args) {
DB db = DB.getInstance(context);
List identities = db.identity().getComposableIdentities(null);
if (identities == null)
identities = new ArrayList<>();
return identities;
}
@Override
protected void onExecuted(Bundle args, List identities) {
Log.i("Set identities=" + identities.size());
// Show identities
IdentityAdapter adapter = new IdentityAdapter(getContext(), identities);
spIdentity.setAdapter(adapter);
// Select identity
if (draft.identity != null)
for (int pos = 0; pos < identities.size(); pos++) {
if (identities.get(pos).id.equals(draft.identity)) {
spIdentity.setSelection(pos);
break;
}
}
}
@Override
protected void onException(Bundle args, Throwable ex) {
Helper.unexpectedError(getFragmentManager(), ex);
}
}.execute(FragmentCompose.this, new Bundle(), "compose:identities");
DB db = DB.getInstance(getContext());
db.attachment().liveAttachments(draft.id).observe(getViewLifecycleOwner(),
new Observer>() {
private int last_available = 0;
@Override
public void onChanged(@Nullable List attachments) {
if (attachments == null)
attachments = new ArrayList<>();
adapter.set(attachments);
grpAttachments.setVisibility(attachments.size() > 0 ? View.VISIBLE : View.GONE);
int available = 0;
boolean downloading = false;
for (EntityAttachment attachment : attachments) {
if (attachment.available)
available++;
if (attachment.progress != null) {
downloading = true;
break;
}
}
Log.i("Attachments=" + attachments.size() +
" available=" + available + " downloading=" + downloading);
// Attachment deleted
if (available < last_available)
onAction(R.id.action_save);
last_available = available;
rvAttachment.setTag(downloading);
checkInternet();
}
});
db.message().liveMessage(draft.id).observe(getViewLifecycleOwner(), new Observer() {
@Override
public void onChanged(EntityMessage draft) {
// Draft was deleted
if (draft == null || draft.ui_hide != 0)
finish();
else {
Log.i("Draft content=" + draft.content);
if (draft.content && state == State.NONE)
showDraft(draft);
tvNoInternet.setTag(draft.content);
checkInternet();
}
}
});
}
@Override
protected void onException(Bundle args, Throwable ex) {
pbWait.setVisibility(View.GONE);
// External app sending absolute file
if (ex instanceof MessageRemovedException)
finish();
else if (ex instanceof SecurityException)
handleFileShare();
else if (ex instanceof IllegalArgumentException)
Snackbar.make(view, ex.getMessage(), Snackbar.LENGTH_LONG).show();
else
Helper.unexpectedError(getFragmentManager(), ex);
}
};
private void handleFileShare() {
Snackbar sb = Snackbar.make(view, R.string.title_no_stream, Snackbar.LENGTH_INDEFINITE);
sb.setAction(R.string.title_info, new View.OnClickListener() {
@Override
public void onClick(View v) {
Helper.viewFAQ(getContext(), 49);
}
});
sb.show();
}
private SimpleTask actionLoader = new SimpleTask() {
int last_available = 0;
@Override
protected void onPreExecute(Bundle args) {
busy = true;
Helper.setViewsEnabled(view, false);
getActivity().invalidateOptionsMenu();
}
@Override
protected void onPostExecute(Bundle args) {
busy = false;
Helper.setViewsEnabled(view, true);
getActivity().invalidateOptionsMenu();
}
@Override
protected EntityMessage onExecute(final Context context, Bundle args) throws Throwable {
// Get data
long id = args.getLong("id");
int action = args.getInt("action");
long aid = args.getLong("account");
long iid = args.getLong("identity");
String extra = args.getString("extra");
String to = args.getString("to");
String cc = args.getString("cc");
String bcc = args.getString("bcc");
String subject = args.getString("subject");
String body = args.getString("body");
boolean plain_only = args.getBoolean("plain_only");
boolean encrypt = args.getBoolean("encrypt");
boolean empty = args.getBoolean("empty");
EntityMessage draft;
DB db = DB.getInstance(context);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
try {
db.beginTransaction();
// Get draft & selected identity
draft = db.message().getMessage(id);
EntityIdentity identity = db.identity().getIdentity(iid);
// Draft deleted by server
if (draft == null || draft.ui_hide != 0)
throw new MessageRemovedException("Draft for action was deleted hide=" + (draft != null));
Log.i("Load action id=" + draft.id + " action=" + getActionName(action));
if (action == R.id.action_delete) {
EntityFolder trash = db.folder().getFolderByType(draft.account, EntityFolder.TRASH);
if (empty || trash == null)
EntityOperation.queue(context, draft, EntityOperation.DELETE);
else
EntityOperation.queue(context, draft, EntityOperation.MOVE, trash.id);
if (!empty) {
Handler handler = new Handler(context.getMainLooper());
handler.post(new Runnable() {
public void run() {
ToastEx.makeText(context, R.string.title_draft_deleted, Toast.LENGTH_LONG).show();
}
});
}
} else {
// Move draft to new account
if (draft.account != aid && aid >= 0) {
Log.i("Account changed");
Long uid = draft.uid;
String msgid = draft.msgid;
boolean content = draft.content;
long ui_hide = draft.ui_hide;
// To prevent violating constraints
draft.uid = null;
draft.msgid = null;
db.message().updateMessage(draft);
// Create copy to delete
draft.id = null;
draft.uid = uid;
draft.msgid = msgid;
draft.content = false;
draft.ui_hide = new Date().getTime();
draft.id = db.message().insertMessage(draft);
EntityOperation.queue(context, draft, EntityOperation.DELETE);
// Restore original with new account, no uid and new msgid
draft.id = id;
draft.account = aid;
draft.folder = db.folder().getFolderByType(aid, EntityFolder.DRAFTS).id;
draft.uid = null;
draft.msgid = EntityMessage.generateMessageId();
draft.content = content;
draft.ui_hide = ui_hide;
db.message().updateMessage(draft);
if (content)
EntityOperation.queue(context, draft, EntityOperation.ADD);
}
Map crumb = new HashMap<>();
crumb.put("draft", draft.folder + ":" + draft.id);
crumb.put("content", Boolean.toString(draft.content));
crumb.put("file", Boolean.toString(draft.getFile(context).exists()));
crumb.put("action", getActionName(action));
Log.breadcrumb("compose", crumb);
List attachments = db.attachment().getAttachments(draft.id);
// Get data
InternetAddress afrom[] = (identity == null ? null : new InternetAddress[]{new InternetAddress(identity.email, identity.name)});
InternetAddress ato[] = null;
InternetAddress acc[] = null;
InternetAddress abcc[] = null;
boolean lookup_mx = prefs.getBoolean("lookup_mx", false);
if (!TextUtils.isEmpty(to))
try {
ato = InternetAddress.parse(to);
if (action == R.id.action_send) {
for (InternetAddress address : ato)
address.validate();
if (lookup_mx)
ConnectionHelper.lookupMx(ato, context);
}
} catch (AddressException ex) {
throw new AddressException(context.getString(R.string.title_address_parse_error,
Helper.ellipsize(to, ADDRESS_ELLIPSIZE), ex.getMessage()));
}
if (!TextUtils.isEmpty(cc))
try {
acc = InternetAddress.parse(cc);
if (action == R.id.action_send) {
for (InternetAddress address : acc)
address.validate();
if (lookup_mx)
ConnectionHelper.lookupMx(acc, context);
}
} catch (AddressException ex) {
throw new AddressException(context.getString(R.string.title_address_parse_error,
Helper.ellipsize(cc, ADDRESS_ELLIPSIZE), ex.getMessage()));
}
if (!TextUtils.isEmpty(bcc))
try {
abcc = InternetAddress.parse(bcc);
if (action == R.id.action_send) {
for (InternetAddress address : abcc)
address.validate();
if (lookup_mx)
ConnectionHelper.lookupMx(abcc, context);
}
} catch (AddressException ex) {
throw new AddressException(context.getString(R.string.title_address_parse_error,
Helper.ellipsize(bcc, ADDRESS_ELLIPSIZE), ex.getMessage()));
}
if (TextUtils.isEmpty(extra))
extra = null;
int available = 0;
for (EntityAttachment attachment : attachments)
if (attachment.available)
available++;
Long ident = (identity == null ? null : identity.id);
boolean dirty = (!Objects.equals(draft.identity, ident) ||
!Objects.equals(draft.extra, extra) ||
!MessageHelper.equal(draft.from, afrom) ||
!MessageHelper.equal(draft.to, ato) ||
!MessageHelper.equal(draft.cc, acc) ||
!MessageHelper.equal(draft.bcc, abcc) ||
!Objects.equals(draft.subject, subject) ||
((draft.encrypt != null && draft.encrypt) != encrypt) ||
last_available != available);
last_available = available;
if (dirty) {
// Update draft
draft.identity = ident;
draft.extra = extra;
draft.from = afrom;
draft.to = ato;
draft.cc = acc;
draft.bcc = abcc;
draft.subject = subject;
draft.encrypt = encrypt;
draft.received = new Date().getTime();
draft.sender = MessageHelper.getSortKey(draft.from);
Uri lookupUri = ContactInfo.getLookupUri(context, draft.from);
draft.avatar = (lookupUri == null ? null : lookupUri.toString());
db.message().updateMessage(draft);
}
if (action == R.id.action_undo || action == R.id.action_redo) {
if (draft.revision != null && draft.revisions != null) {
dirty = true;
if (action == R.id.action_undo) {
if (draft.revision > 1)
draft.revision--;
} else {
if (draft.revision < draft.revisions)
draft.revision++;
}
body = Helper.readText(draft.getFile(context, draft.revision));
Helper.writeText(draft.getFile(context), body);
db.message().setMessageRevision(draft.id, draft.revision);
db.message().setMessageContent(draft.id,
true,
draft.plain_only, // unchanged
HtmlHelper.getPreview(body),
null);
}
} else {
File file = draft.getFile(context);
if (!file.exists())
Helper.writeText(file, body);
String previous = Helper.readText(file);
if (!body.equals(previous) ||
plain_only != (draft.plain_only != null && draft.plain_only)) {
dirty = true;
if (draft.revisions == null)
draft.revisions = 1;
else
draft.revisions++;
draft.revision = draft.revisions;
Helper.writeText(draft.getFile(context), body);
Helper.writeText(draft.getFile(context, draft.revisions), body);
db.message().setMessageRevision(draft.id, draft.revision);
db.message().setMessageRevisions(draft.id, draft.revisions);
draft.plain_only = plain_only;
db.message().setMessageContent(draft.id,
true,
draft.plain_only,
HtmlHelper.getPreview(body),
null);
}
}
// Remove unused inline images
StringBuilder sb = new StringBuilder();
sb.append(body);
File rfile = draft.getRefFile(context);
if (rfile.exists())
sb.append(Helper.readText(rfile));
List cids = new ArrayList<>();
for (Element element : Jsoup.parse(sb.toString()).select("img")) {
String src = element.attr("src");
if (src.startsWith("cid:"))
cids.add("<" + src.substring(4) + ">");
}
for (EntityAttachment attachment : new ArrayList<>(attachments))
if (attachment.isInline() && !cids.contains(attachment.cid)) {
Log.i("Removing unused inline attachment cid=" + attachment.cid);
db.attachment().deleteAttachment(attachment.id);
}
// Execute action
if (action == R.id.action_save ||
action == R.id.action_undo ||
action == R.id.action_redo ||
action == R.id.menu_encrypt) {
if (BuildConfig.DEBUG || dirty)
EntityOperation.queue(context, draft, EntityOperation.ADD);
Handler handler = new Handler(context.getMainLooper());
handler.post(new Runnable() {
public void run() {
ToastEx.makeText(context, R.string.title_draft_saved, Toast.LENGTH_LONG).show();
}
});
} else if (action == R.id.action_send) {
// Check data
if (draft.identity == null)
throw new IllegalArgumentException(context.getString(R.string.title_from_missing));
if (draft.to == null && draft.cc == null && draft.bcc == null)
throw new IllegalArgumentException(context.getString(R.string.title_to_missing));
// Save attachments
for (EntityAttachment attachment : attachments)
if (!attachment.available)
throw new IllegalArgumentException(context.getString(R.string.title_attachments_missing));
// Delete draft (cannot move to outbox)
EntityOperation.queue(context, draft, EntityOperation.DELETE);
File refDraftFile = draft.getRefFile(context);
// Copy message to outbox
draft.id = null;
draft.folder = db.folder().getOutbox().id;
draft.uid = null;
draft.ui_hide = 0L;
draft.id = db.message().insertMessage(draft);
Helper.writeText(draft.getFile(context), body);
if (refDraftFile.exists()) {
File refFile = draft.getRefFile(context);
refDraftFile.renameTo(refFile);
}
// Move attachments
for (EntityAttachment attachment : attachments)
db.attachment().setMessage(attachment.id, draft.id);
// Delay sending message
int send_delayed = prefs.getInt("send_delayed", 0);
if (draft.ui_snoozed == null && send_delayed != 0) {
draft.ui_snoozed = new Date().getTime() + send_delayed * 1000L;
db.message().setMessageSnoozed(draft.id, draft.ui_snoozed);
}
// Send message
if (draft.ui_snoozed == null)
EntityOperation.queue(context, draft, EntityOperation.SEND);
final String feedback;
if (draft.ui_snoozed == null)
feedback = context.getString(R.string.title_queued);
else {
DateFormat DTF = Helper.getDateTimeInstance(context);
feedback = context.getString(R.string.title_queued_at, DTF.format(draft.ui_snoozed));
}
Handler handler = new Handler(context.getMainLooper());
handler.post(new Runnable() {
public void run() {
ToastEx.makeText(context, feedback, Toast.LENGTH_LONG).show();
}
});
}
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
if (action == R.id.action_send && draft.ui_snoozed != null) {
Log.i("Delayed send id=" + draft.id + " at " + new Date(draft.ui_snoozed));
EntityMessage.snooze(context, draft.id, draft.ui_snoozed);
}
return draft;
}
@Override
protected void onExecuted(Bundle args, EntityMessage draft) {
int action = args.getInt("action");
Log.i("Loaded action id=" + (draft == null ? null : draft.id) + " action=" + getActionName(action));
etTo.setText(MessageHelper.formatAddressesCompose(draft.to));
etCc.setText(MessageHelper.formatAddressesCompose(draft.cc));
etBcc.setText(MessageHelper.formatAddressesCompose(draft.bcc));
bottom_navigation.getMenu().findItem(R.id.action_undo).setVisible(draft.revision != null && draft.revision > 1);
bottom_navigation.getMenu().findItem(R.id.action_redo).setVisible(draft.revision != null && !draft.revision.equals(draft.revisions));
if (action == R.id.action_delete) {
autosave = false;
finish();
} else if (action == R.id.action_undo || action == R.id.action_redo) {
showDraft(draft);
} else if (action == R.id.action_save) {
// Do nothing
} else if (action == R.id.menu_encrypt) {
onEncrypt();
} else if (action == R.id.action_send) {
autosave = false;
finish();
}
}
@Override
protected void onException(Bundle args, Throwable ex) {
if (ex instanceof MessageRemovedException)
finish();
else if (ex instanceof IllegalArgumentException ||
ex instanceof AddressException || ex instanceof UnknownHostException)
Snackbar.make(view, ex.getMessage(), Snackbar.LENGTH_LONG).show();
else
Helper.unexpectedError(getFragmentManager(), ex);
}
private String getActionName(int id) {
switch (id) {
case R.id.action_delete:
return "delete";
case R.id.action_undo:
return "undo";
case R.id.action_redo:
return "redo";
case R.id.action_save:
return "save";
case R.id.menu_encrypt:
return "encrypt";
case R.id.action_send:
return "send";
default:
return Integer.toString(id);
}
}
};
private void showDraft(long id) {
Bundle args = new Bundle();
args.putLong("id", id);
new SimpleTask() {
@Override
protected EntityMessage onExecute(Context context, Bundle args) {
long id = args.getLong("id");
return DB.getInstance(context).message().getMessage(id);
}
@Override
protected void onExecuted(Bundle args, EntityMessage draft) {
showDraft(draft);
}
@Override
protected void onException(Bundle args, Throwable ex) {
Helper.unexpectedError(getFragmentManager(), ex);
}
}.execute(FragmentCompose.this, args, "compose:show");
}
private void showDraft(final EntityMessage draft) {
Bundle args = new Bundle();
args.putLong("id", draft.id);
args.putBoolean("show_images", show_images);
new SimpleTask() {
@Override
protected void onPostExecute(Bundle args) {
state = State.LOADED;
autosave = true;
pbWait.setVisibility(View.GONE);
edit_bar.setVisibility(style ? View.VISIBLE : View.GONE);
bottom_navigation.getMenu().findItem(R.id.action_undo).setVisible(draft.revision != null && draft.revision > 1);
bottom_navigation.getMenu().findItem(R.id.action_redo).setVisible(draft.revision != null && !draft.revision.equals(draft.revisions));
bottom_navigation.setVisibility(View.VISIBLE);
Helper.setViewsEnabled(view, true);
getActivity().invalidateOptionsMenu();
}
@Override
protected Spanned[] onExecute(final Context context, Bundle args) throws Throwable {
final long id = args.getLong("id");
final boolean show_images = args.getBoolean("show_images", false);
DB db = DB.getInstance(context);
EntityMessage draft = db.message().getMessage(id);
if (draft == null || !draft.content)
throw new IllegalArgumentException(context.getString(R.string.title_no_body));
String body = Helper.readText(draft.getFile(context));
Spanned spannedBody = HtmlHelper.fromHtml(body, cidGetter, null);
Spanned spannedRef = null;
File refFile = draft.getRefFile(context);
if (refFile.exists()) {
String quote = HtmlHelper.sanitize(context, Helper.readText(refFile), show_images);
Spanned spannedQuote = HtmlHelper.fromHtml(quote,
new Html.ImageGetter() {
@Override
public Drawable getDrawable(String source) {
return HtmlHelper.decodeImage(context, id, source, show_images, tvReference);
}
},
null);
int colorPrimary = Helper.resolveColor(context, R.attr.colorPrimary);
SpannableStringBuilder builder = new SpannableStringBuilder(spannedQuote);
QuoteSpan[] quoteSpans = builder.getSpans(0, builder.length(), QuoteSpan.class);
for (QuoteSpan quoteSpan : quoteSpans) {
builder.setSpan(
new StyledQuoteSpan(colorPrimary),
builder.getSpanStart(quoteSpan),
builder.getSpanEnd(quoteSpan),
builder.getSpanFlags(quoteSpan));
builder.removeSpan(quoteSpan);
}
spannedRef = builder;
}
args.putBoolean("ref_has_images", spannedRef != null &&
spannedRef.getSpans(0, spannedRef.length(), ImageSpan.class).length > 0);
return new Spanned[]{spannedBody, spannedRef};
}
@Override
protected void onExecuted(Bundle args, Spanned[] text) {
etBody.setText(text[0]);
etBody.setSelection(0);
grpBody.setVisibility(View.VISIBLE);
boolean ref_has_images = args.getBoolean("ref_has_images");
tvReference.setText(text[1]);
grpReference.setVisibility(text[1] == null ? View.GONE : View.VISIBLE);
ibReferenceEdit.setVisibility(text[1] == null ? View.GONE : View.VISIBLE);
ibReferenceImages.setVisibility(ref_has_images && !show_images ? View.VISIBLE : View.GONE);
final Context context = getContext();
new Handler().post(new Runnable() {
@Override
public void run() {
View target;
if (TextUtils.isEmpty(etTo.getText().toString().trim()))
target = etTo;
else if (TextUtils.isEmpty(etSubject.getText().toString()))
target = etSubject;
else
target = etBody;
target.requestFocus();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
boolean keyboard = prefs.getBoolean("keyboard", true);
if (keyboard) {
InputMethodManager imm =
(InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null)
imm.showSoftInput(target, InputMethodManager.SHOW_IMPLICIT);
}
}
});
}
@Override
protected void onException(Bundle args, Throwable ex) {
Helper.unexpectedError(getFragmentManager(), ex);
}
}.execute(FragmentCompose.this, args, "compose:show");
}
private Html.ImageGetter cidGetter = new Html.ImageGetter() {
@Override
public Drawable getDrawable(final String source) {
Log.i("Loading source=" + source);
final LevelListDrawable lld = new LevelListDrawable();
Resources res = getContext().getResources();
int px = Helper.dp2pixels(getContext(), 48);
// Level 0: broken image
Drawable broken = res.getDrawable(R.drawable.baseline_broken_image_24, getContext().getTheme());
broken.setBounds(0, 0, px, px);
lld.addLevel(0, 0, broken);
// Level 1: place holder
Drawable placeholder = res.getDrawable(R.drawable.baseline_image_24, getContext().getTheme());
placeholder.setBounds(0, 0, px, px);
lld.addLevel(1, 1, placeholder);
lld.setBounds(0, 0, px, px);
if (source != null && source.startsWith("cid:")) {
lld.setLevel(1); // placeholder
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
Bundle args = new Bundle();
args.putLong("id", working);
args.putString("cid", "<" + source.substring(4) + ">");
args.putInt("scaleToPixels", res.getDisplayMetrics().widthPixels);
new SimpleTask() {
@Override
protected Bitmap onExecute(Context context, Bundle args) {
long id = args.getLong("id");
String cid = args.getString("cid");
int scaleToPixels = args.getInt("scaleToPixels");
DB db = DB.getInstance(context);
EntityAttachment attachment = db.attachment().getAttachment(id, cid);
if (attachment == null)
return null;
File file = attachment.getFile(context);
return Helper.decodeImage(file, scaleToPixels);
}
@Override
protected void onExecuted(Bundle args, Bitmap bm) {
if (bm == null)
lld.setLevel(0); // broken
else {
Drawable image = new BitmapDrawable(res, bm);
DisplayMetrics dm = res.getDisplayMetrics();
image.setBounds(0, 0,
Math.round(bm.getWidth() * dm.density),
Math.round(bm.getHeight() * dm.density));
lld.addLevel(2, 2, image);
lld.setLevel(2); // image
float scale = 1.0f;
float width = etBody.getWidth();
if (image.getIntrinsicWidth() > width)
scale = width / image.getIntrinsicWidth();
lld.setBounds(0, 0,
Math.round(image.getIntrinsicWidth() * scale),
Math.round(image.getIntrinsicHeight() * scale));
}
etBody.requestLayout();
}
@Override
protected void onException(Bundle args, Throwable ex) {
Helper.unexpectedError(getFragmentManager(), ex);
}
}.execute(FragmentCompose.this, args, "compose:cid:" + source);
}
});
} else
lld.setLevel(1); // image place holder
return lld;
}
};
public class IdentityAdapter extends ArrayAdapter {
private Context context;
private List identities;
IdentityAdapter(@NonNull Context context, List identities) {
super(context, 0, identities);
this.context = context;
this.identities = identities;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
return getLayout(position, convertView, parent, R.layout.spinner_item2);
}
@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
return getLayout(position, convertView, parent, R.layout.spinner_item2_dropdown);
}
View getLayout(int position, View convertView, ViewGroup parent, int resid) {
View view = LayoutInflater.from(context).inflate(resid, parent, false);
TupleIdentityEx identity = identities.get(position);
View vwColor = view.findViewById(R.id.vwColor);
vwColor.setBackgroundColor(identity.color == null ? Color.TRANSPARENT : identity.color);
TextView text1 = view.findViewById(android.R.id.text1);
text1.setText(identity.accountName + "/" + identity.getDisplayName() + (identity.primary ? " ★" : ""));
TextView text2 = view.findViewById(android.R.id.text2);
text2.setText(identity.email);
return view;
}
}
private AdapterView.OnItemSelectedListener identitySelected = new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView> parent, View view, int position, long id) {
EntityIdentity identity = (EntityIdentity) parent.getAdapter().getItem(position);
if (identity != null && identity.encrypt) {
encrypt = true;
getActivity().invalidateOptionsMenu();
}
int at = (identity == null ? -1 : identity.email.indexOf('@'));
etExtra.setHint(at < 0 ? null : identity.email.substring(0, at));
tvDomain.setText(at < 0 ? null : identity.email.substring(at));
grpExtra.setVisibility(identity != null && identity.sender_extra ? View.VISIBLE : View.GONE);
Spanned signature = null;
if (identity != null && !TextUtils.isEmpty(identity.signature))
signature = HtmlHelper.fromHtml(identity.signature, new Html.ImageGetter() {
@Override
public Drawable getDrawable(String source) {
int px = Helper.dp2pixels(getContext(), 24);
Drawable d = getContext().getResources()
.getDrawable(R.drawable.baseline_image_24, getContext().getTheme());
d.setBounds(0, 0, px, px);
return d;
}
}, null);
tvSignature.setText(signature);
grpSignature.setVisibility(signature == null ? View.GONE : View.VISIBLE);
}
@Override
public void onNothingSelected(AdapterView> parent) {
encrypt = false;
getActivity().invalidateOptionsMenu();
etExtra.setHint("");
tvDomain.setText(null);
tvSignature.setText(null);
grpSignature.setVisibility(View.GONE);
}
};
private ActionMode.Callback actionCallback = new ActionMode.Callback() {
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
menu.add(1, R.string.title_style_bold, 1, R.string.title_style_bold).setIcon(R.drawable.baseline_format_bold_24);
menu.add(1, R.string.title_style_italic, 2, R.string.title_style_italic).setIcon(R.drawable.baseline_format_italic_24);
menu.add(1, R.string.title_style_underline, 3, R.string.title_style_underline).setIcon(R.drawable.baseline_format_underlined_24);
menu.add(1, R.string.title_style_size, 4, R.string.title_style_size).setIcon(R.drawable.baseline_format_size_24);
menu.add(1, R.string.title_style_color, 5, R.string.title_style_color).setIcon(R.drawable.baseline_format_color_text_24);
return true;
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
Log.i("Action=" + item.getGroupId() + ":" + item.getItemId());
if (item.getGroupId() != 1)
return false;
int start = etBody.getSelectionStart();
int end = etBody.getSelectionEnd();
if (start < 0)
start = 0;
if (end < 0)
end = 0;
if (start > end) {
int tmp = start;
start = end;
end = tmp;
}
SpannableString ss = new SpannableString(etBody.getText());
switch (item.getItemId()) {
case R.string.title_style_bold:
case R.string.title_style_italic: {
int style = (item.getItemId() == R.string.title_style_bold ? Typeface.BOLD : Typeface.ITALIC);
boolean has = false;
for (StyleSpan span : ss.getSpans(start, end, StyleSpan.class))
if (span.getStyle() == style) {
has = true;
ss.removeSpan(span);
}
if (!has)
ss.setSpan(new StyleSpan(style), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
etBody.setText(ss);
etBody.setSelection(end, end);
return true;
}
case R.string.title_style_underline: {
boolean has = false;
for (UnderlineSpan span : ss.getSpans(start, end, UnderlineSpan.class)) {
has = true;
ss.removeSpan(span);
}
if (!has)
ss.setSpan(new UnderlineSpan(), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
etBody.setText(ss);
etBody.setSelection(end, end);
return true;
}
case R.string.title_style_size: {
RelativeSizeSpan[] spans = ss.getSpans(start, end, RelativeSizeSpan.class);
float size = (spans.length > 0 ? spans[0].getSizeChange() : 1.0f);
// Match small/big
if (size == 0.8f)
size = 1.0f;
else if (size == 1.0)
size = 1.25f;
else
size = 0.8f;
for (RelativeSizeSpan span : spans)
ss.removeSpan(span);
if (size != 1.0f)
ss.setSpan(new RelativeSizeSpan(size), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
etBody.setText(ss);
etBody.setSelection(end, end);
return true;
}
case R.string.title_style_color: {
Bundle args = new Bundle();
args.putInt("start", start);
args.putInt("end", end);
ForegroundColorSpan[] spans = ss.getSpans(start, end, ForegroundColorSpan.class);
int color = (spans.length > 0 ? spans[0].getForegroundColor() : Color.TRANSPARENT);
FragmentDialogColor fragment = new FragmentDialogColor();
fragment.initialize(R.string.title_style_color, color, args, getContext());
fragment.setTargetFragment(FragmentCompose.this, REQUEST_COLOR);
fragment.show(getFragmentManager(), "account:color");
etBody.setSelection(end, end);
return true;
}
default:
return false;
}
}
@Override
public void onDestroyActionMode(ActionMode mode) {
}
};
private ViewTreeObserver.OnGlobalLayoutListener layoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
int bottom = view.getBottom()
- edit_bar.getHeight()
- Helper.dp2pixels(view.getContext(), 56); // full bottom navigation
int remain = bottom - etBody.getTop();
int threshold = Helper.dp2pixels(view.getContext(), 100);
Log.i("Reduce remain=" + remain + " threshold=" + threshold);
boolean reduce = (remain < threshold);
boolean reduced = (bottom_navigation.getLabelVisibilityMode() == LabelVisibilityMode.LABEL_VISIBILITY_UNLABELED);
if (reduce != reduced) {
bottom_navigation.setLabelVisibilityMode(reduce
? LabelVisibilityMode.LABEL_VISIBILITY_UNLABELED
: LabelVisibilityMode.LABEL_VISIBILITY_LABELED);
ViewGroup.LayoutParams params = bottom_navigation.getLayoutParams();
params.height = Helper.dp2pixels(view.getContext(), reduce ? 36 : 56);
bottom_navigation.setLayoutParams(params);
}
}
};
private ActivityBase.IBackPressedListener onBackPressedListener = new ActivityBase.IBackPressedListener() {
@Override
public boolean onBackPressed() {
if (getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.STARTED))
onExit();
return true;
}
};
public static class FragmentDialogContactGroup extends FragmentDialogEx {
@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
final long working = getArguments().getLong("working");
View dview = LayoutInflater.from(getContext()).inflate(R.layout.dialog_contact_group, null);
final ListView lvGroup = dview.findViewById(R.id.lvGroup);
final Spinner spTarget = dview.findViewById(R.id.spTarget);
Cursor groups = getContext().getContentResolver().query(
ContactsContract.Groups.CONTENT_URI,
new String[]{
ContactsContract.Groups._ID,
ContactsContract.Groups.TITLE
},
null, null, ContactsContract.Groups.TITLE
);
final SimpleCursorAdapter adapter = new SimpleCursorAdapter(
getContext(),
R.layout.spinner_item1_dropdown,
groups,
new String[]{ContactsContract.Groups.TITLE},
new int[]{android.R.id.text1},
0);
lvGroup.setAdapter(adapter);
final AlertDialog dialog = new AlertDialog.Builder(getContext())
.setView(dview)
.create();
lvGroup.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView> parent, View view, int position, long id) {
int target = spTarget.getSelectedItemPosition();
Cursor cursor = (Cursor) adapter.getItem(position);
long group = cursor.getLong(0);
Bundle args = getArguments();
args.putLong("id", working);
args.putInt("target", target);
args.putLong("group", group);
sendResult(Activity.RESULT_OK);
dismiss();
}
});
return dialog;
}
}
public static class FragmentDialogAnswer extends FragmentDialogEx {
@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
final ArrayAdapter adapter =
new ArrayAdapter<>(getContext(), R.layout.spinner_item1, android.R.id.text1);
// TODO: spinner
new SimpleTask>() {
@Override
protected List onExecute(Context context, Bundle args) {
DB db = DB.getInstance(getContext());
return db.answer().getAnswers(false);
}
@Override
protected void onExecuted(Bundle args, List answers) {
adapter.addAll(answers);
}
@Override
protected void onException(Bundle args, Throwable ex) {
Helper.unexpectedError(getFragmentManager(), ex);
}
}.execute(getContext(), getActivity(), new Bundle(), "compose:answer");
return new AlertDialog.Builder(getContext())
.setTitle(R.string.title_insert_template)
.setAdapter(adapter, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
EntityAnswer answer = adapter.getItem(which);
String text = EntityAnswer.replacePlaceholders(
answer.text, null, null, null, null);
getArguments().putString("answer", text);
sendResult(RESULT_OK);
}
})
.create();
}
}
public static class FragmentDialogLink extends FragmentDialogEx {
private EditText etLink;
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
outState.putString("fair:link", etLink.getText().toString());
super.onSaveInstanceState(outState);
}
@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
Uri uri = getArguments().getParcelable("uri");
View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_insert_link, null);
etLink = view.findViewById(R.id.etLink);
final TextView tvInsecure = view.findViewById(R.id.tvInsecure);
etLink.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
tvInsecure.setVisibility("http".equals(Uri.parse(s.toString()).getScheme()) ? View.VISIBLE : View.GONE);
}
@Override
public void afterTextChanged(Editable s) {
}
});
if (savedInstanceState == null)
etLink.setText(uri == null ? "https://" : uri.toString());
else
etLink.setText(savedInstanceState.getString("fair:link"));
return new AlertDialog.Builder(getContext())
.setView(view)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String link = etLink.getText().toString();
getArguments().putString("link", link);
sendResult(RESULT_OK);
}
})
.create();
}
}
}