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, focusInfo -> {
219 if (ignoreFocusChanges) {
220 Logger.debug("new-trans", "Ignoring focus change");
223 ignoreFocusChanges = true;
225 if (((focusInfo == null) || (focusInfo.element == null) ||
226 focusInfo.position != getAdapterPosition()) ||
230 NewTransactionModel.Item item = getItem();
231 if (item instanceof NewTransactionModel.TransactionHead) {
232 NewTransactionModel.TransactionHead head =
233 item.toTransactionHead();
234 // bad idea - double pop-up, and not really necessary.
235 // the user can tap the input to get the calendar
236 //if (!tvDate.hasFocus()) tvDate.requestFocus();
237 switch (focusInfo.element) {
238 case TransactionComment:
239 b.transactionComment.setVisibility(View.VISIBLE);
240 b.transactionComment.requestFocus();
244 b.newTransactionDescription.requestFocus();
245 // tvDescription.dismissDropDown();
247 Misc.showSoftKeyboard(
248 (NewTransactionActivity) b.getRoot()
253 else if (item instanceof NewTransactionModel.TransactionAccount) {
254 NewTransactionModel.TransactionAccount acc =
255 item.toTransactionAccount();
256 switch (focusInfo.element) {
258 b.accountRowAccAmounts.requestFocus();
261 b.comment.setVisibility(View.VISIBLE);
262 b.comment.requestFocus();
265 boolean focused = b.accountRowAccName.requestFocus();
266 // b.accountRowAccName.dismissDropDown();
268 Misc.showSoftKeyboard(
269 (NewTransactionActivity) b.getRoot()
276 ignoreFocusChanges = false;
280 Data.currencyGap.observe(activity,
281 hasGap -> updateCurrencyPositionAndPadding(Data.currencySymbolPosition.getValue(),
284 Data.currencySymbolPosition.observe(activity,
285 position -> updateCurrencyPositionAndPadding(position,
286 Data.currencyGap.getValue()));
288 adapter.model.getShowCurrency()
289 .observe(activity, showCurrency -> {
291 b.currency.setVisibility(View.VISIBLE);
292 b.currencyButton.setVisibility(View.VISIBLE);
293 b.currency.setText(mProfile.getDefaultCommodity());
296 b.currency.setVisibility(View.GONE);
297 b.currencyButton.setVisibility(View.GONE);
298 b.currency.setText(null);
302 adapter.model.getShowComments()
303 .observe(activity, show -> {
304 ConstraintLayout.LayoutParams amountLayoutParams =
305 (ConstraintLayout.LayoutParams) b.amountLayout.getLayoutParams();
306 ConstraintLayout.LayoutParams accountParams =
307 (ConstraintLayout.LayoutParams) b.accountRowAccName.getLayoutParams();
310 accountParams.endToStart = ConstraintLayout.LayoutParams.UNSET;
311 accountParams.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
313 amountLayoutParams.topToTop = ConstraintLayout.LayoutParams.UNSET;
314 amountLayoutParams.topToBottom = b.accountRowAccName.getId();
316 b.commentLayout.setVisibility(View.VISIBLE);
319 accountParams.endToStart = b.amountLayout.getId();
320 accountParams.endToEnd = ConstraintLayout.LayoutParams.UNSET;
322 amountLayoutParams.topToBottom = ConstraintLayout.LayoutParams.UNSET;
323 amountLayoutParams.topToTop = ConstraintLayout.LayoutParams.PARENT_ID;
325 b.commentLayout.setVisibility(View.GONE);
328 b.accountRowAccName.setLayoutParams(accountParams);
329 b.amountLayout.setLayoutParams(amountLayoutParams);
331 b.transactionCommentLayout.setVisibility(show ? View.VISIBLE : View.GONE);
334 public void checkAmountValid(String s) {
335 boolean valid = true;
337 if (s.length() > 0) {
338 float ignored = Float.parseFloat(s.replace(decimalSeparator, decimalDot));
341 catch (NumberFormatException ex) {
345 displayAmountValidity(valid);
347 private void displayAmountValidity(boolean valid) {
348 b.accountRowAccAmounts.setCompoundDrawablesRelativeWithIntrinsicBounds(
349 valid ? 0 : R.drawable.ic_error_outline_black_24dp, 0, 0, 0);
350 b.accountRowAccAmounts.setMinEms(valid ? 4 : 5);
352 private void monitorComment(EditText editText) {
353 editText.addTextChangedListener(new TextWatcher() {
355 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
358 public void onTextChanged(CharSequence s, int start, int before, int count) {
361 public void afterTextChanged(Editable s) {
362 // debug("input", "text changed");
366 Logger.debug("textWatcher", "calling syncData()");
368 Logger.debug("textWatcher",
369 "syncData() returned, checking if transaction is submittable");
370 styleComment(editText, s.toString());
371 Logger.debug("textWatcher", "done");
375 private void commentFocusChanged(TextView textView, boolean hasFocus) {
376 @ColorInt int textColor;
377 textColor = b.dummyText.getTextColors()
380 textView.setTypeface(null, Typeface.NORMAL);
381 textView.setHint(R.string.transaction_account_comment_hint);
384 int alpha = (textColor >> 24 & 0xff);
385 alpha = 3 * alpha / 4;
386 textColor = (alpha << 24) | (0x00ffffff & textColor);
387 textView.setTypeface(null, Typeface.ITALIC);
388 textView.setHint("");
389 if (TextUtils.isEmpty(textView.getText())) {
390 textView.setVisibility(View.INVISIBLE);
393 textView.setTextColor(textColor);
396 private void updateCurrencyPositionAndPadding(Currency.Position position, boolean hasGap) {
397 ConstraintLayout.LayoutParams amountLP =
398 (ConstraintLayout.LayoutParams) b.accountRowAccAmounts.getLayoutParams();
399 ConstraintLayout.LayoutParams currencyLP =
400 (ConstraintLayout.LayoutParams) b.currency.getLayoutParams();
402 if (position == Currency.Position.before) {
403 currencyLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
404 currencyLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
406 amountLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
407 amountLP.endToStart = ConstraintLayout.LayoutParams.UNSET;
408 amountLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
409 amountLP.startToEnd = b.currency.getId();
411 b.currency.setGravity(Gravity.END);
414 currencyLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
415 currencyLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
417 amountLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
418 amountLP.startToEnd = ConstraintLayout.LayoutParams.UNSET;
419 amountLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
420 amountLP.endToStart = b.currency.getId();
422 b.currency.setGravity(Gravity.START);
425 amountLP.resolveLayoutDirection(b.accountRowAccAmounts.getLayoutDirection());
426 currencyLP.resolveLayoutDirection(b.currency.getLayoutDirection());
428 b.accountRowAccAmounts.setLayoutParams(amountLP);
429 b.currency.setLayoutParams(currencyLP);
431 // distance between the amount and the currency symbol
432 int gapSize = DimensionUtils.sp2px(b.currency.getContext(), 5);
434 if (position == Currency.Position.before) {
435 b.currency.setPaddingRelative(0, 0, hasGap ? gapSize : 0, 0);
438 b.currency.setPaddingRelative(hasGap ? gapSize : 0, 0, 0, 0);
441 private void setCurrencyString(String currency) {
442 @ColorInt int textColor = b.dummyText.getTextColors()
444 if ((currency == null) || currency.isEmpty()) {
445 b.currency.setText(R.string.currency_symbol);
446 int alpha = (textColor >> 24) & 0xff;
447 alpha = alpha * 3 / 4;
448 b.currency.setTextColor((alpha << 24) | (0x00ffffff & textColor));
451 b.currency.setText(currency);
452 b.currency.setTextColor(textColor);
455 private void setCurrency(Currency currency) {
456 setCurrencyString((currency == null) ? null : currency.getName());
458 private void setEditable(Boolean editable) {
459 b.newTransactionDate.setEnabled(editable);
460 b.newTransactionDescription.setEnabled(editable);
461 b.accountRowAccName.setEnabled(editable);
462 b.accountRowAccAmounts.setEnabled(editable);
464 private void beginUpdates() {
466 throw new RuntimeException("Already in update mode");
469 private void endUpdates() {
471 throw new RuntimeException("Not in update mode");
477 * Stores the data from the UI elements into the model item
478 * Returns true if there were changes made that suggest transaction has to be
479 * checked for being submittable
481 private boolean syncData() {
483 Logger.debug("new-trans", "skipping syncData() loop");
487 NewTransactionModel.Item item = getItem();
491 boolean significantChange = false;
494 if (item instanceof NewTransactionModel.TransactionHead) {
495 NewTransactionModel.TransactionHead head = item.toTransactionHead();
497 head.setDate(String.valueOf(b.newTransactionDate.getText()));
499 // transaction description is required
500 if (!significantChange && TextUtils.isEmpty(head.getDescription()) !=
501 TextUtils.isEmpty(b.newTransactionDescription.getText()))
502 significantChange = true;
504 head.setDescription(String.valueOf(b.newTransactionDescription.getText()));
505 head.setComment(String.valueOf(b.transactionComment.getText()));
507 else if (item instanceof NewTransactionModel.TransactionAccount) {
508 NewTransactionModel.TransactionAccount acc = item.toTransactionAccount();
510 // having account name is important
511 if (!significantChange && TextUtils.isEmpty(acc.getAccountName()) !=
512 TextUtils.isEmpty(b.accountRowAccName.getText()))
513 significantChange = true;
515 acc.setAccountName(String.valueOf(b.accountRowAccName.getText()));
517 acc.setComment(String.valueOf(b.comment.getText()));
519 String amount = String.valueOf(b.accountRowAccAmounts.getText());
520 amount = amount.trim();
522 if (amount.isEmpty()) {
523 if (acc.isAmountSet())
524 significantChange = true;
526 acc.setAmountValid(true);
530 amount = amount.replace(decimalSeparator, decimalDot);
531 final float parsedAmount = Float.parseFloat(amount);
532 if (!acc.isAmountSet() || !Misc.equalFloats(parsedAmount, acc.getAmount()))
533 significantChange = true;
534 acc.setAmount(parsedAmount);
535 acc.setAmountValid(true);
537 catch (NumberFormatException e) {
538 Logger.debug("new-trans", String.format(
539 "assuming amount is not set due to number format exception. " +
540 "input was '%s'", amount));
541 if (acc.isAmountValid())
542 significantChange = true;
543 acc.setAmountValid(false);
545 final String curr = String.valueOf(b.currency.getText());
546 final String currValue;
547 if (curr.equals(b.currency.getContext()
549 .getString(R.string.currency_symbol)) ||
555 if (!significantChange && !TextUtils.equals(acc.getCurrency(), currValue))
556 significantChange = true;
557 acc.setCurrency(currValue);
561 throw new RuntimeException("Should not happen");
564 return significantChange;
566 catch (ParseException e) {
567 throw new RuntimeException("Should not happen", e);
573 private void pickTransactionDate() {
574 DatePickerFragment picker = new DatePickerFragment();
575 picker.setFutureDates(mProfile.getFutureDates());
576 picker.setOnDatePickedListener(this);
577 picker.setCurrentDateFromText(b.newTransactionDate.getText());
578 picker.show(((NewTransactionActivity) b.getRoot()
579 .getContext()).getSupportFragmentManager(), null);
584 * @param item updates the UI elements with the data from the model item
586 @SuppressLint("DefaultLocale")
587 public void bind(@NonNull NewTransactionModel.Item item) {
592 if (item instanceof NewTransactionModel.TransactionHead) {
593 NewTransactionModel.TransactionHead head = item.toTransactionHead();
594 b.newTransactionDate.setText(head.getFormattedDate());
596 // avoid triggering completion pop-up
597 SimpleCursorAdapter a =
598 (SimpleCursorAdapter) b.newTransactionDescription.getAdapter();
600 b.newTransactionDescription.setAdapter(null);
601 b.newTransactionDescription.setText(head.getDescription());
604 b.newTransactionDescription.setAdapter(a);
607 b.transactionComment.setText(head.getComment());
608 //styleComment(b.transactionComment, head.getComment());
610 b.ntrData.setVisibility(View.VISIBLE);
611 b.ntrAccount.setVisibility(View.GONE);
612 b.ntrPadding.setVisibility(View.GONE);
615 else if (item instanceof NewTransactionModel.TransactionAccount) {
616 NewTransactionModel.TransactionAccount acc = item.toTransactionAccount();
618 // avoid triggering completion pop-up
619 AccountAutocompleteAdapter a =
620 (AccountAutocompleteAdapter) b.accountRowAccName.getAdapter();
622 b.accountRowAccName.setAdapter(null);
623 b.accountRowAccName.setText(acc.getAccountName());
626 b.accountRowAccName.setAdapter(a);
629 final String amountHint = acc.getAmountHint();
630 if (amountHint == null) {
631 b.accountRowAccAmounts.setHint(R.string.zero_amount);
634 b.accountRowAccAmounts.setHint(amountHint);
637 b.accountRowAccAmounts.setImeOptions(
638 acc.isLast() ? EditorInfo.IME_ACTION_DONE : EditorInfo.IME_ACTION_NEXT);
640 setCurrencyString(acc.getCurrency());
641 b.accountRowAccAmounts.setText(
642 acc.isAmountSet() ? String.format("%4.2f", acc.getAmount()) : null);
643 displayAmountValidity(true);
645 b.comment.setText(acc.getComment());
647 b.ntrData.setVisibility(View.GONE);
648 b.ntrAccount.setVisibility(View.VISIBLE);
649 b.ntrPadding.setVisibility(View.GONE);
654 throw new RuntimeException("Don't know how to handle " + item);
665 private void styleComment(EditText editText, String comment) {
666 final View focusedView = editText.findFocus();
667 editText.setTypeface(null, (focusedView == editText) ? Typeface.NORMAL : Typeface.ITALIC);
668 editText.setVisibility(
669 ((focusedView != editText) && TextUtils.isEmpty(comment)) ? View.INVISIBLE
673 public void onDatePicked(int year, int month, int day) {
674 final NewTransactionModel.TransactionHead head = getItem().toTransactionHead();
675 head.setDate(new SimpleDate(year, month + 1, day));
676 b.newTransactionDate.setText(head.getFormattedDate());
678 boolean focused = b.newTransactionDescription.requestFocus();
680 Misc.showSoftKeyboard((NewTransactionActivity) b.getRoot()
684 private NewTransactionModel.Item getItem() {
685 return Objects.requireNonNull(mAdapter.model.getItems()
687 .get(getAdapterPosition());
690 public void descriptionSelected(String description) {
691 b.accountRowAccName.setText(description);
692 b.accountRowAccAmounts.requestFocus(View.FOCUS_FORWARD);