2 * Copyright © 2021 Damyan Ivanov.
3 * This file is part of MoLe.
4 * MoLe is free software: you can distribute it and/or modify it
5 * under the term of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your opinion), any later version.
9 * MoLe is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License terms for details.
14 * You should have received a copy of the GNU General Public License
15 * along with MoLe. If not, see <https://www.gnu.org/licenses/>.
18 package net.ktnx.mobileledger.ui.new_transaction;
20 import android.annotation.SuppressLint;
21 import android.graphics.Typeface;
22 import android.text.Editable;
23 import android.text.TextUtils;
24 import android.text.TextWatcher;
25 import android.view.Gravity;
26 import android.view.View;
27 import android.view.inputmethod.EditorInfo;
28 import android.widget.EditText;
29 import android.widget.SimpleCursorAdapter;
30 import android.widget.TextView;
32 import androidx.annotation.ColorInt;
33 import androidx.annotation.NonNull;
34 import androidx.constraintlayout.widget.ConstraintLayout;
35 import androidx.recyclerview.widget.RecyclerView;
37 import net.ktnx.mobileledger.R;
38 import net.ktnx.mobileledger.async.DescriptionSelectedCallback;
39 import net.ktnx.mobileledger.databinding.NewTransactionRowBinding;
40 import net.ktnx.mobileledger.db.AccountAutocompleteAdapter;
41 import net.ktnx.mobileledger.model.Currency;
42 import net.ktnx.mobileledger.model.Data;
43 import net.ktnx.mobileledger.model.MobileLedgerProfile;
44 import net.ktnx.mobileledger.ui.CurrencySelectorFragment;
45 import net.ktnx.mobileledger.ui.DatePickerFragment;
46 import net.ktnx.mobileledger.ui.TextViewClearHelper;
47 import net.ktnx.mobileledger.utils.DimensionUtils;
48 import net.ktnx.mobileledger.utils.Logger;
49 import net.ktnx.mobileledger.utils.MLDB;
50 import net.ktnx.mobileledger.utils.Misc;
51 import net.ktnx.mobileledger.utils.SimpleDate;
53 import java.text.DecimalFormatSymbols;
54 import java.text.ParseException;
55 import java.util.Objects;
57 class NewTransactionItemHolder extends RecyclerView.ViewHolder
58 implements DatePickerFragment.DatePickedListener, DescriptionSelectedCallback {
59 private final String decimalDot = ".";
60 private final MobileLedgerProfile mProfile;
61 private final NewTransactionRowBinding b;
62 private final NewTransactionItemsAdapter mAdapter;
63 private boolean ignoreFocusChanges = false;
64 private String decimalSeparator;
65 private boolean inUpdate = false;
66 private boolean syncingData = false;
67 //TODO multiple amounts with different currencies per posting?
68 NewTransactionItemHolder(@NonNull NewTransactionRowBinding b,
69 NewTransactionItemsAdapter adapter) {
72 this.mAdapter = adapter;
73 new TextViewClearHelper().attachToTextView(b.comment);
75 b.newTransactionDescription.setNextFocusForwardId(View.NO_ID);
76 b.accountRowAccName.setNextFocusForwardId(View.NO_ID);
77 b.accountRowAccAmounts.setNextFocusForwardId(View.NO_ID); // magic!
79 b.newTransactionDate.setOnClickListener(v -> pickTransactionDate());
81 b.accountCommentButton.setOnClickListener(v -> {
82 b.comment.setVisibility(View.VISIBLE);
83 b.comment.requestFocus();
86 b.transactionCommentButton.setOnClickListener(v -> {
87 b.transactionComment.setVisibility(View.VISIBLE);
88 b.transactionComment.requestFocus();
91 mProfile = Data.getProfile();
93 @SuppressLint("DefaultLocale") View.OnFocusChangeListener focusMonitor = (v, hasFocus) -> {
94 final int id = v.getId();
96 boolean wasSyncing = syncingData;
99 final int pos = getAdapterPosition();
100 if (id == R.id.account_row_acc_name) {
101 adapter.noteFocusIsOnAccount(pos);
103 else if (id == R.id.account_row_acc_amounts) {
104 adapter.noteFocusIsOnAmount(pos);
106 else if (id == R.id.comment) {
107 adapter.noteFocusIsOnComment(pos);
109 else if (id == R.id.transaction_comment) {
110 adapter.noteFocusIsOnTransactionComment(pos);
112 else if (id == R.id.new_transaction_description) {
113 adapter.noteFocusIsOnDescription(pos);
116 throw new IllegalStateException("Where is the focus?");
119 syncingData = wasSyncing;
123 if (id == R.id.account_row_acc_amounts) {
125 String input = String.valueOf(b.accountRowAccAmounts.getText());
126 input = input.replace(decimalSeparator, decimalDot);
127 b.accountRowAccAmounts.setText(
128 String.format("%4.2f", Float.parseFloat(input)));
130 catch (NumberFormatException ex) {
136 if (id == R.id.comment) {
137 commentFocusChanged(b.comment, hasFocus);
139 else if (id == R.id.transaction_comment) {
140 commentFocusChanged(b.transactionComment, hasFocus);
144 b.newTransactionDescription.setOnFocusChangeListener(focusMonitor);
145 b.accountRowAccName.setOnFocusChangeListener(focusMonitor);
146 b.accountRowAccAmounts.setOnFocusChangeListener(focusMonitor);
147 b.comment.setOnFocusChangeListener(focusMonitor);
148 b.transactionComment.setOnFocusChangeListener(focusMonitor);
150 NewTransactionActivity activity = (NewTransactionActivity) b.getRoot()
153 MLDB.hookAutocompletionAdapter(activity, b.newTransactionDescription,
154 MLDB.DESCRIPTION_HISTORY_TABLE, "description", false, activity, mProfile);
155 b.accountRowAccName.setAdapter(new AccountAutocompleteAdapter(b.getRoot()
156 .getContext(), mProfile));
158 decimalSeparator = "";
159 Data.locale.observe(activity, locale -> decimalSeparator = String.valueOf(
160 DecimalFormatSymbols.getInstance(locale)
161 .getMonetaryDecimalSeparator()));
163 final TextWatcher tw = new TextWatcher() {
165 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
169 public void onTextChanged(CharSequence s, int start, int before, int count) {
173 public void afterTextChanged(Editable s) {
174 // debug("input", "text changed");
178 Logger.debug("textWatcher", "calling syncData()");
180 Logger.debug("textWatcher",
181 "syncData() returned, checking if transaction is submittable");
182 adapter.model.checkTransactionSubmittable(null);
184 Logger.debug("textWatcher", "done");
187 final TextWatcher amountWatcher = new TextWatcher() {
189 public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
191 public void onTextChanged(CharSequence s, int start, int before, int count) {}
193 public void afterTextChanged(Editable s) {
194 checkAmountValid(s.toString());
197 adapter.model.checkTransactionSubmittable(null);
200 b.newTransactionDescription.addTextChangedListener(tw);
201 monitorComment(b.transactionComment);
202 b.accountRowAccName.addTextChangedListener(tw);
203 monitorComment(b.comment);
204 b.accountRowAccAmounts.addTextChangedListener(amountWatcher);
206 b.currencyButton.setOnClickListener(v -> {
207 CurrencySelectorFragment cpf = new CurrencySelectorFragment();
208 cpf.showPositionAndPadding();
209 cpf.setOnCurrencySelectedListener(
210 c -> adapter.setItemCurrency(getAdapterPosition(), c.getName()));
211 cpf.show(activity.getSupportFragmentManager(), "currency-selector");
214 commentFocusChanged(b.transactionComment, false);
215 commentFocusChanged(b.comment, false);
217 adapter.model.getFocusInfo()
218 .observe(activity, this::applyFocus);
220 Data.currencyGap.observe(activity,
221 hasGap -> updateCurrencyPositionAndPadding(Data.currencySymbolPosition.getValue(),
224 Data.currencySymbolPosition.observe(activity,
225 position -> updateCurrencyPositionAndPadding(position,
226 Data.currencyGap.getValue()));
228 adapter.model.getShowCurrency()
229 .observe(activity, showCurrency -> {
231 b.currency.setVisibility(View.VISIBLE);
232 b.currencyButton.setVisibility(View.VISIBLE);
233 b.currency.setText(mProfile.getDefaultCommodity());
236 b.currency.setVisibility(View.GONE);
237 b.currencyButton.setVisibility(View.GONE);
238 b.currency.setText(null);
242 adapter.model.getShowComments()
243 .observe(activity, show -> {
244 ConstraintLayout.LayoutParams amountLayoutParams =
245 (ConstraintLayout.LayoutParams) b.amountLayout.getLayoutParams();
246 ConstraintLayout.LayoutParams accountParams =
247 (ConstraintLayout.LayoutParams) b.accountRowAccName.getLayoutParams();
250 accountParams.endToStart = ConstraintLayout.LayoutParams.UNSET;
251 accountParams.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
253 amountLayoutParams.topToTop = ConstraintLayout.LayoutParams.UNSET;
254 amountLayoutParams.topToBottom = b.accountRowAccName.getId();
256 b.commentLayout.setVisibility(View.VISIBLE);
259 accountParams.endToStart = b.amountLayout.getId();
260 accountParams.endToEnd = ConstraintLayout.LayoutParams.UNSET;
262 amountLayoutParams.topToBottom = ConstraintLayout.LayoutParams.UNSET;
263 amountLayoutParams.topToTop = ConstraintLayout.LayoutParams.PARENT_ID;
265 b.commentLayout.setVisibility(View.GONE);
268 b.accountRowAccName.setLayoutParams(accountParams);
269 b.amountLayout.setLayoutParams(amountLayoutParams);
271 b.transactionCommentLayout.setVisibility(show ? View.VISIBLE : View.GONE);
274 private void applyFocus(NewTransactionModel.FocusInfo focusInfo) {
275 if (ignoreFocusChanges) {
276 Logger.debug("new-trans", "Ignoring focus change");
279 ignoreFocusChanges = true;
281 if (((focusInfo == null) || (focusInfo.element == null) ||
282 focusInfo.position != getAdapterPosition()))
285 NewTransactionModel.Item item = getItem();
286 if (item instanceof NewTransactionModel.TransactionHead) {
287 NewTransactionModel.TransactionHead head = item.toTransactionHead();
288 // bad idea - double pop-up, and not really necessary.
289 // the user can tap the input to get the calendar
290 //if (!tvDate.hasFocus()) tvDate.requestFocus();
291 switch (focusInfo.element) {
292 case TransactionComment:
293 b.transactionComment.setVisibility(View.VISIBLE);
294 b.transactionComment.requestFocus();
297 boolean focused = b.newTransactionDescription.requestFocus();
298 // tvDescription.dismissDropDown();
300 Misc.showSoftKeyboard((NewTransactionActivity) b.getRoot()
305 else if (item instanceof NewTransactionModel.TransactionAccount) {
306 NewTransactionModel.TransactionAccount acc = item.toTransactionAccount();
307 switch (focusInfo.element) {
309 b.accountRowAccAmounts.requestFocus();
312 b.comment.setVisibility(View.VISIBLE);
313 b.comment.requestFocus();
316 boolean focused = b.accountRowAccName.requestFocus();
317 // b.accountRowAccName.dismissDropDown();
319 Misc.showSoftKeyboard((NewTransactionActivity) b.getRoot()
326 ignoreFocusChanges = false;
329 public void checkAmountValid(String s) {
330 boolean valid = true;
332 if (s.length() > 0) {
333 float ignored = Float.parseFloat(s.replace(decimalSeparator, decimalDot));
336 catch (NumberFormatException ex) {
340 displayAmountValidity(valid);
342 private void displayAmountValidity(boolean valid) {
343 b.accountRowAccAmounts.setCompoundDrawablesRelativeWithIntrinsicBounds(
344 valid ? 0 : R.drawable.ic_error_outline_black_24dp, 0, 0, 0);
345 b.accountRowAccAmounts.setMinEms(valid ? 4 : 5);
347 private void monitorComment(EditText editText) {
348 editText.addTextChangedListener(new TextWatcher() {
350 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
353 public void onTextChanged(CharSequence s, int start, int before, int count) {
356 public void afterTextChanged(Editable s) {
357 // debug("input", "text changed");
361 Logger.debug("textWatcher", "calling syncData()");
363 Logger.debug("textWatcher",
364 "syncData() returned, checking if transaction is submittable");
365 styleComment(editText, s.toString());
366 Logger.debug("textWatcher", "done");
370 private void commentFocusChanged(TextView textView, boolean hasFocus) {
371 @ColorInt int textColor;
372 textColor = b.dummyText.getTextColors()
375 textView.setTypeface(null, Typeface.NORMAL);
376 textView.setHint(R.string.transaction_account_comment_hint);
379 int alpha = (textColor >> 24 & 0xff);
380 alpha = 3 * alpha / 4;
381 textColor = (alpha << 24) | (0x00ffffff & textColor);
382 textView.setTypeface(null, Typeface.ITALIC);
383 textView.setHint("");
384 if (TextUtils.isEmpty(textView.getText())) {
385 textView.setVisibility(View.INVISIBLE);
388 textView.setTextColor(textColor);
391 private void updateCurrencyPositionAndPadding(Currency.Position position, boolean hasGap) {
392 ConstraintLayout.LayoutParams amountLP =
393 (ConstraintLayout.LayoutParams) b.accountRowAccAmounts.getLayoutParams();
394 ConstraintLayout.LayoutParams currencyLP =
395 (ConstraintLayout.LayoutParams) b.currency.getLayoutParams();
397 if (position == Currency.Position.before) {
398 currencyLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
399 currencyLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
401 amountLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
402 amountLP.endToStart = ConstraintLayout.LayoutParams.UNSET;
403 amountLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
404 amountLP.startToEnd = b.currency.getId();
406 b.currency.setGravity(Gravity.END);
409 currencyLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
410 currencyLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
412 amountLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
413 amountLP.startToEnd = ConstraintLayout.LayoutParams.UNSET;
414 amountLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
415 amountLP.endToStart = b.currency.getId();
417 b.currency.setGravity(Gravity.START);
420 amountLP.resolveLayoutDirection(b.accountRowAccAmounts.getLayoutDirection());
421 currencyLP.resolveLayoutDirection(b.currency.getLayoutDirection());
423 b.accountRowAccAmounts.setLayoutParams(amountLP);
424 b.currency.setLayoutParams(currencyLP);
426 // distance between the amount and the currency symbol
427 int gapSize = DimensionUtils.sp2px(b.currency.getContext(), 5);
429 if (position == Currency.Position.before) {
430 b.currency.setPaddingRelative(0, 0, hasGap ? gapSize : 0, 0);
433 b.currency.setPaddingRelative(hasGap ? gapSize : 0, 0, 0, 0);
436 private void setCurrencyString(String currency) {
437 @ColorInt int textColor = b.dummyText.getTextColors()
439 if ((currency == null) || currency.isEmpty()) {
440 b.currency.setText(R.string.currency_symbol);
441 int alpha = (textColor >> 24) & 0xff;
442 alpha = alpha * 3 / 4;
443 b.currency.setTextColor((alpha << 24) | (0x00ffffff & textColor));
446 b.currency.setText(currency);
447 b.currency.setTextColor(textColor);
450 private void setCurrency(Currency currency) {
451 setCurrencyString((currency == null) ? null : currency.getName());
453 private void setEditable(Boolean editable) {
454 b.newTransactionDate.setEnabled(editable);
455 b.newTransactionDescription.setEnabled(editable);
456 b.accountRowAccName.setEnabled(editable);
457 b.accountRowAccAmounts.setEnabled(editable);
459 private void beginUpdates() {
461 throw new RuntimeException("Already in update mode");
464 private void endUpdates() {
466 throw new RuntimeException("Not in update mode");
472 * Stores the data from the UI elements into the model item
473 * Returns true if there were changes made that suggest transaction has to be
474 * checked for being submittable
476 private boolean syncData() {
478 Logger.debug("new-trans", "skipping syncData() loop");
482 NewTransactionModel.Item item = getItem();
486 boolean significantChange = false;
489 if (item instanceof NewTransactionModel.TransactionHead) {
490 NewTransactionModel.TransactionHead head = item.toTransactionHead();
492 head.setDate(String.valueOf(b.newTransactionDate.getText()));
494 // transaction description is required
495 if (TextUtils.isEmpty(head.getDescription()) !=
496 TextUtils.isEmpty(b.newTransactionDescription.getText()))
497 significantChange = true;
499 head.setDescription(String.valueOf(b.newTransactionDescription.getText()));
500 head.setComment(String.valueOf(b.transactionComment.getText()));
502 else if (item instanceof NewTransactionModel.TransactionAccount) {
503 NewTransactionModel.TransactionAccount acc = item.toTransactionAccount();
505 // having account name is important
506 final Editable incomingAccountName = b.accountRowAccName.getText();
507 if (TextUtils.isEmpty(acc.getAccountName()) !=
508 TextUtils.isEmpty(incomingAccountName))
509 significantChange = true;
511 acc.setAccountName(String.valueOf(incomingAccountName));
512 final int accNameSelEnd = b.accountRowAccName.getSelectionEnd();
513 final int accNameSelStart = b.accountRowAccName.getSelectionStart();
514 acc.setAccountNameCursorPosition(accNameSelEnd);
516 acc.setComment(String.valueOf(b.comment.getText()));
518 String amount = String.valueOf(b.accountRowAccAmounts.getText());
519 amount = amount.trim();
521 if (amount.isEmpty()) {
522 if (acc.isAmountSet())
523 significantChange = true;
525 acc.setAmountValid(true);
529 amount = amount.replace(decimalSeparator, decimalDot);
530 final float parsedAmount = Float.parseFloat(amount);
531 if (!acc.isAmountSet() || !Misc.equalFloats(parsedAmount, acc.getAmount()))
532 significantChange = true;
533 acc.setAmount(parsedAmount);
534 acc.setAmountValid(true);
536 catch (NumberFormatException e) {
537 Logger.debug("new-trans", String.format(
538 "assuming amount is not set due to number format exception. " +
539 "input was '%s'", amount));
540 if (acc.isAmountValid())
541 significantChange = true;
542 acc.setAmountValid(false);
544 final String curr = String.valueOf(b.currency.getText());
545 final String currValue;
546 if (curr.equals(b.currency.getContext()
548 .getString(R.string.currency_symbol)) ||
554 if (!significantChange && !TextUtils.equals(acc.getCurrency(), currValue))
555 significantChange = true;
556 acc.setCurrency(currValue);
560 throw new RuntimeException("Should not happen");
563 return significantChange;
565 catch (ParseException e) {
566 throw new RuntimeException("Should not happen", e);
572 private void pickTransactionDate() {
573 DatePickerFragment picker = new DatePickerFragment();
574 picker.setFutureDates(mProfile.getFutureDates());
575 picker.setOnDatePickedListener(this);
576 picker.setCurrentDateFromText(b.newTransactionDate.getText());
577 picker.show(((NewTransactionActivity) b.getRoot()
578 .getContext()).getSupportFragmentManager(), null);
583 * @param item updates the UI elements with the data from the model item
585 @SuppressLint("DefaultLocale")
586 public void bind(@NonNull NewTransactionModel.Item item) {
591 if (item instanceof NewTransactionModel.TransactionHead) {
592 NewTransactionModel.TransactionHead head = item.toTransactionHead();
593 b.newTransactionDate.setText(head.getFormattedDate());
595 // avoid triggering completion pop-up
596 SimpleCursorAdapter a =
597 (SimpleCursorAdapter) b.newTransactionDescription.getAdapter();
599 b.newTransactionDescription.setAdapter(null);
600 b.newTransactionDescription.setText(head.getDescription());
603 b.newTransactionDescription.setAdapter(a);
606 b.transactionComment.setText(head.getComment());
607 //styleComment(b.transactionComment, head.getComment());
609 b.ntrData.setVisibility(View.VISIBLE);
610 b.ntrAccount.setVisibility(View.GONE);
613 else if (item instanceof NewTransactionModel.TransactionAccount) {
614 NewTransactionModel.TransactionAccount acc = item.toTransactionAccount();
616 final String incomingAccountName = acc.getAccountName();
617 final String presentAccountName = String.valueOf(b.accountRowAccName.getText());
618 if (!TextUtils.equals(incomingAccountName, presentAccountName)) {
620 String.format("Setting account name from '%s' to '%s' (| @ %d)",
621 presentAccountName, incomingAccountName,
622 acc.getAccountNameCursorPosition()));
623 // avoid triggering completion pop-up
624 AccountAutocompleteAdapter a =
625 (AccountAutocompleteAdapter) b.accountRowAccName.getAdapter();
627 b.accountRowAccName.setAdapter(null);
628 b.accountRowAccName.setText(incomingAccountName);
629 b.accountRowAccName.setSelection(acc.getAccountNameCursorPosition());
632 b.accountRowAccName.setAdapter(a);
636 final String amountHint = acc.getAmountHint();
637 if (amountHint == null) {
638 b.accountRowAccAmounts.setHint(R.string.zero_amount);
641 b.accountRowAccAmounts.setHint(amountHint);
644 b.accountRowAccAmounts.setImeOptions(
645 acc.isLast() ? EditorInfo.IME_ACTION_DONE : EditorInfo.IME_ACTION_NEXT);
647 setCurrencyString(acc.getCurrency());
648 b.accountRowAccAmounts.setText(
649 acc.isAmountSet() ? String.format("%4.2f", acc.getAmount()) : null);
650 displayAmountValidity(true);
652 b.comment.setText(acc.getComment());
654 b.ntrData.setVisibility(View.GONE);
655 b.ntrAccount.setVisibility(View.VISIBLE);
660 throw new RuntimeException("Don't know how to handle " + item);
663 applyFocus(mAdapter.model.getFocusInfo()
674 private void styleComment(EditText editText, String comment) {
675 final View focusedView = editText.findFocus();
676 editText.setTypeface(null, (focusedView == editText) ? Typeface.NORMAL : Typeface.ITALIC);
677 editText.setVisibility(
678 ((focusedView != editText) && TextUtils.isEmpty(comment)) ? View.INVISIBLE
682 public void onDatePicked(int year, int month, int day) {
683 final NewTransactionModel.TransactionHead head = getItem().toTransactionHead();
684 head.setDate(new SimpleDate(year, month + 1, day));
685 b.newTransactionDate.setText(head.getFormattedDate());
687 boolean focused = b.newTransactionDescription.requestFocus();
689 Misc.showSoftKeyboard((NewTransactionActivity) b.getRoot()
693 private NewTransactionModel.Item getItem() {
694 return Objects.requireNonNull(mAdapter.model.getItems()
696 .get(getAdapterPosition());
699 public void descriptionSelected(String description) {
700 b.accountRowAccName.setText(description);
701 b.accountRowAccAmounts.requestFocus(View.FOCUS_FORWARD);