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 final String newText = String.format("%4.2f", Float.parseFloat(input));
128 if (!newText.equals(input)) {
129 boolean wasSyncingData = syncingData;
132 b.accountRowAccAmounts.setText(newText);
135 syncingData = wasSyncingData;
139 catch (NumberFormatException ex) {
145 if (id == R.id.comment) {
146 commentFocusChanged(b.comment, hasFocus);
148 else if (id == R.id.transaction_comment) {
149 commentFocusChanged(b.transactionComment, hasFocus);
153 b.newTransactionDescription.setOnFocusChangeListener(focusMonitor);
154 b.accountRowAccName.setOnFocusChangeListener(focusMonitor);
155 b.accountRowAccAmounts.setOnFocusChangeListener(focusMonitor);
156 b.comment.setOnFocusChangeListener(focusMonitor);
157 b.transactionComment.setOnFocusChangeListener(focusMonitor);
159 NewTransactionActivity activity = (NewTransactionActivity) b.getRoot()
162 MLDB.hookAutocompletionAdapter(activity, b.newTransactionDescription,
163 MLDB.DESCRIPTION_HISTORY_TABLE, "description", false, activity, mProfile);
164 b.accountRowAccName.setAdapter(new AccountAutocompleteAdapter(b.getRoot()
165 .getContext(), mProfile));
167 decimalSeparator = "";
168 Data.locale.observe(activity, locale -> decimalSeparator = String.valueOf(
169 DecimalFormatSymbols.getInstance(locale)
170 .getMonetaryDecimalSeparator()));
172 final TextWatcher tw = new TextWatcher() {
174 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
178 public void onTextChanged(CharSequence s, int start, int before, int count) {
182 public void afterTextChanged(Editable s) {
183 // debug("input", "text changed");
187 Logger.debug("textWatcher", "calling syncData()");
189 Logger.debug("textWatcher",
190 "syncData() returned, checking if transaction is submittable");
191 adapter.model.checkTransactionSubmittable(null);
193 Logger.debug("textWatcher", "done");
196 final TextWatcher amountWatcher = new TextWatcher() {
198 public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
200 public void onTextChanged(CharSequence s, int start, int before, int count) {}
202 public void afterTextChanged(Editable s) {
203 checkAmountValid(s.toString());
206 adapter.model.checkTransactionSubmittable(null);
209 b.newTransactionDescription.addTextChangedListener(tw);
210 monitorComment(b.transactionComment);
211 b.accountRowAccName.addTextChangedListener(tw);
212 monitorComment(b.comment);
213 b.accountRowAccAmounts.addTextChangedListener(amountWatcher);
215 b.currencyButton.setOnClickListener(v -> {
216 CurrencySelectorFragment cpf = new CurrencySelectorFragment();
217 cpf.showPositionAndPadding();
218 cpf.setOnCurrencySelectedListener(c -> adapter.setItemCurrency(getAdapterPosition(),
219 (c == null) ? null : c.getName()));
220 cpf.show(activity.getSupportFragmentManager(), "currency-selector");
223 commentFocusChanged(b.transactionComment, false);
224 commentFocusChanged(b.comment, false);
226 adapter.model.getFocusInfo()
227 .observe(activity, this::applyFocus);
229 Data.currencyGap.observe(activity,
230 hasGap -> updateCurrencyPositionAndPadding(Data.currencySymbolPosition.getValue(),
233 Data.currencySymbolPosition.observe(activity,
234 position -> updateCurrencyPositionAndPadding(position,
235 Data.currencyGap.getValue()));
237 adapter.model.getShowCurrency()
238 .observe(activity, showCurrency -> {
240 b.currency.setVisibility(View.VISIBLE);
241 b.currencyButton.setVisibility(View.VISIBLE);
242 setCurrencyString(mProfile.getDefaultCommodity());
245 b.currency.setVisibility(View.GONE);
246 b.currencyButton.setVisibility(View.GONE);
247 setCurrencyString(null);
251 adapter.model.getShowComments()
252 .observe(activity, show -> {
253 ConstraintLayout.LayoutParams amountLayoutParams =
254 (ConstraintLayout.LayoutParams) b.amountLayout.getLayoutParams();
255 ConstraintLayout.LayoutParams accountParams =
256 (ConstraintLayout.LayoutParams) b.accountRowAccName.getLayoutParams();
259 accountParams.endToStart = ConstraintLayout.LayoutParams.UNSET;
260 accountParams.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
262 amountLayoutParams.topToTop = ConstraintLayout.LayoutParams.UNSET;
263 amountLayoutParams.topToBottom = b.accountRowAccName.getId();
265 b.commentLayout.setVisibility(View.VISIBLE);
268 accountParams.endToStart = b.amountLayout.getId();
269 accountParams.endToEnd = ConstraintLayout.LayoutParams.UNSET;
271 amountLayoutParams.topToBottom = ConstraintLayout.LayoutParams.UNSET;
272 amountLayoutParams.topToTop = ConstraintLayout.LayoutParams.PARENT_ID;
274 b.commentLayout.setVisibility(View.GONE);
277 b.accountRowAccName.setLayoutParams(accountParams);
278 b.amountLayout.setLayoutParams(amountLayoutParams);
280 b.transactionCommentLayout.setVisibility(show ? View.VISIBLE : View.GONE);
283 private void applyFocus(NewTransactionModel.FocusInfo focusInfo) {
284 if (ignoreFocusChanges) {
285 Logger.debug("new-trans", "Ignoring focus change");
288 ignoreFocusChanges = true;
290 if (((focusInfo == null) || (focusInfo.element == null) ||
291 focusInfo.position != getAdapterPosition()))
294 NewTransactionModel.Item item = getItem();
295 if (item instanceof NewTransactionModel.TransactionHead) {
296 NewTransactionModel.TransactionHead head = item.toTransactionHead();
297 // bad idea - double pop-up, and not really necessary.
298 // the user can tap the input to get the calendar
299 //if (!tvDate.hasFocus()) tvDate.requestFocus();
300 switch (focusInfo.element) {
301 case TransactionComment:
302 b.transactionComment.setVisibility(View.VISIBLE);
303 b.transactionComment.requestFocus();
306 boolean focused = b.newTransactionDescription.requestFocus();
307 // tvDescription.dismissDropDown();
309 Misc.showSoftKeyboard((NewTransactionActivity) b.getRoot()
314 else if (item instanceof NewTransactionModel.TransactionAccount) {
315 NewTransactionModel.TransactionAccount acc = item.toTransactionAccount();
316 switch (focusInfo.element) {
318 b.accountRowAccAmounts.requestFocus();
321 b.comment.setVisibility(View.VISIBLE);
322 b.comment.requestFocus();
325 boolean focused = b.accountRowAccName.requestFocus();
326 // b.accountRowAccName.dismissDropDown();
328 Misc.showSoftKeyboard((NewTransactionActivity) b.getRoot()
335 ignoreFocusChanges = false;
338 public void checkAmountValid(String s) {
339 boolean valid = true;
341 if (s.length() > 0) {
342 float ignored = Float.parseFloat(s.replace(decimalSeparator, decimalDot));
345 catch (NumberFormatException ex) {
349 displayAmountValidity(valid);
351 private void displayAmountValidity(boolean valid) {
352 b.accountRowAccAmounts.setCompoundDrawablesRelativeWithIntrinsicBounds(
353 valid ? 0 : R.drawable.ic_error_outline_black_24dp, 0, 0, 0);
354 b.accountRowAccAmounts.setMinEms(valid ? 4 : 5);
356 private void monitorComment(EditText editText) {
357 editText.addTextChangedListener(new TextWatcher() {
359 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
362 public void onTextChanged(CharSequence s, int start, int before, int count) {
365 public void afterTextChanged(Editable s) {
366 // debug("input", "text changed");
370 Logger.debug("textWatcher", "calling syncData()");
372 Logger.debug("textWatcher",
373 "syncData() returned, checking if transaction is submittable");
374 styleComment(editText, s.toString());
375 Logger.debug("textWatcher", "done");
379 private void commentFocusChanged(TextView textView, boolean hasFocus) {
380 @ColorInt int textColor;
381 textColor = b.dummyText.getTextColors()
384 textView.setTypeface(null, Typeface.NORMAL);
385 textView.setHint(R.string.transaction_account_comment_hint);
388 int alpha = (textColor >> 24 & 0xff);
389 alpha = 3 * alpha / 4;
390 textColor = (alpha << 24) | (0x00ffffff & textColor);
391 textView.setTypeface(null, Typeface.ITALIC);
392 textView.setHint("");
393 if (TextUtils.isEmpty(textView.getText())) {
394 textView.setVisibility(View.INVISIBLE);
397 textView.setTextColor(textColor);
400 private void updateCurrencyPositionAndPadding(Currency.Position position, boolean hasGap) {
401 ConstraintLayout.LayoutParams amountLP =
402 (ConstraintLayout.LayoutParams) b.accountRowAccAmounts.getLayoutParams();
403 ConstraintLayout.LayoutParams currencyLP =
404 (ConstraintLayout.LayoutParams) b.currency.getLayoutParams();
406 if (position == Currency.Position.before) {
407 currencyLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
408 currencyLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
410 amountLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
411 amountLP.endToStart = ConstraintLayout.LayoutParams.UNSET;
412 amountLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
413 amountLP.startToEnd = b.currency.getId();
415 b.currency.setGravity(Gravity.END);
418 currencyLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
419 currencyLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
421 amountLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
422 amountLP.startToEnd = ConstraintLayout.LayoutParams.UNSET;
423 amountLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
424 amountLP.endToStart = b.currency.getId();
426 b.currency.setGravity(Gravity.START);
429 amountLP.resolveLayoutDirection(b.accountRowAccAmounts.getLayoutDirection());
430 currencyLP.resolveLayoutDirection(b.currency.getLayoutDirection());
432 b.accountRowAccAmounts.setLayoutParams(amountLP);
433 b.currency.setLayoutParams(currencyLP);
435 // distance between the amount and the currency symbol
436 int gapSize = DimensionUtils.sp2px(b.currency.getContext(), 5);
438 if (position == Currency.Position.before) {
439 b.currency.setPaddingRelative(0, 0, hasGap ? gapSize : 0, 0);
442 b.currency.setPaddingRelative(hasGap ? gapSize : 0, 0, 0, 0);
445 private void setCurrencyString(String currency) {
446 @ColorInt int textColor = b.dummyText.getTextColors()
448 if (TextUtils.isEmpty(currency)) {
449 b.currency.setText(R.string.currency_symbol);
450 int alpha = (textColor >> 24) & 0xff;
451 alpha = alpha * 3 / 4;
452 b.currency.setTextColor((alpha << 24) | (0x00ffffff & textColor));
455 b.currency.setText(currency);
456 b.currency.setTextColor(textColor);
459 private void setCurrency(Currency currency) {
460 setCurrencyString((currency == null) ? null : currency.getName());
462 private void setEditable(Boolean editable) {
463 b.newTransactionDate.setEnabled(editable);
464 b.newTransactionDescription.setEnabled(editable);
465 b.accountRowAccName.setEnabled(editable);
466 b.accountRowAccAmounts.setEnabled(editable);
468 private void beginUpdates() {
470 throw new RuntimeException("Already in update mode");
473 private void endUpdates() {
475 throw new RuntimeException("Not in update mode");
481 * Stores the data from the UI elements into the model item
482 * Returns true if there were changes made that suggest transaction has to be
483 * checked for being submittable
485 private boolean syncData() {
487 Logger.debug("new-trans", "skipping syncData() loop");
491 if (getAdapterPosition() < 0) {
492 // probably the row was swiped out
493 Logger.debug("new-trans", "Ignoring request to suncData(): adapter position negative");
497 NewTransactionModel.Item item = getItem();
501 boolean significantChange = false;
504 if (item instanceof NewTransactionModel.TransactionHead) {
505 NewTransactionModel.TransactionHead head = item.toTransactionHead();
507 head.setDate(String.valueOf(b.newTransactionDate.getText()));
509 // transaction description is required
510 if (TextUtils.isEmpty(head.getDescription()) !=
511 TextUtils.isEmpty(b.newTransactionDescription.getText()))
512 significantChange = true;
514 head.setDescription(String.valueOf(b.newTransactionDescription.getText()));
515 head.setComment(String.valueOf(b.transactionComment.getText()));
517 else if (item instanceof NewTransactionModel.TransactionAccount) {
518 NewTransactionModel.TransactionAccount acc = item.toTransactionAccount();
520 // having account name is important
521 final Editable incomingAccountName = b.accountRowAccName.getText();
522 if (TextUtils.isEmpty(acc.getAccountName()) !=
523 TextUtils.isEmpty(incomingAccountName))
524 significantChange = true;
526 acc.setAccountName(String.valueOf(incomingAccountName));
527 final int accNameSelEnd = b.accountRowAccName.getSelectionEnd();
528 final int accNameSelStart = b.accountRowAccName.getSelectionStart();
529 acc.setAccountNameCursorPosition(accNameSelEnd);
531 acc.setComment(String.valueOf(b.comment.getText()));
533 String amount = String.valueOf(b.accountRowAccAmounts.getText());
534 amount = amount.trim();
536 if (amount.isEmpty()) {
537 if (acc.isAmountSet())
538 significantChange = true;
540 acc.setAmountValid(true);
544 amount = amount.replace(decimalSeparator, decimalDot);
545 final float parsedAmount = Float.parseFloat(amount);
546 if (!acc.isAmountSet() || !Misc.equalFloats(parsedAmount, acc.getAmount()))
547 significantChange = true;
548 acc.setAmount(parsedAmount);
549 acc.setAmountValid(true);
551 catch (NumberFormatException e) {
552 Logger.debug("new-trans", String.format(
553 "assuming amount is not set due to number format exception. " +
554 "input was '%s'", amount));
555 if (acc.isAmountValid())
556 significantChange = true;
557 acc.setAmountValid(false);
559 final String curr = String.valueOf(b.currency.getText());
560 final String currValue;
561 if (curr.equals(b.currency.getContext()
563 .getString(R.string.currency_symbol)) ||
569 if (!significantChange && !TextUtils.equals(acc.getCurrency(), currValue))
570 significantChange = true;
571 acc.setCurrency(currValue);
575 throw new RuntimeException("Should not happen");
578 return significantChange;
580 catch (ParseException e) {
581 throw new RuntimeException("Should not happen", e);
587 private void pickTransactionDate() {
588 DatePickerFragment picker = new DatePickerFragment();
589 picker.setFutureDates(mProfile.getFutureDates());
590 picker.setOnDatePickedListener(this);
591 picker.setCurrentDateFromText(b.newTransactionDate.getText());
592 picker.show(((NewTransactionActivity) b.getRoot()
593 .getContext()).getSupportFragmentManager(), null);
598 * @param item updates the UI elements with the data from the model item
600 @SuppressLint("DefaultLocale")
601 public void bind(@NonNull NewTransactionModel.Item item) {
606 if (item instanceof NewTransactionModel.TransactionHead) {
607 NewTransactionModel.TransactionHead head = item.toTransactionHead();
608 b.newTransactionDate.setText(head.getFormattedDate());
610 // avoid triggering completion pop-up
611 SimpleCursorAdapter a =
612 (SimpleCursorAdapter) b.newTransactionDescription.getAdapter();
614 b.newTransactionDescription.setAdapter(null);
615 b.newTransactionDescription.setText(head.getDescription());
618 b.newTransactionDescription.setAdapter(a);
621 b.transactionComment.setText(head.getComment());
622 //styleComment(b.transactionComment, head.getComment());
624 b.ntrData.setVisibility(View.VISIBLE);
625 b.ntrAccount.setVisibility(View.GONE);
628 else if (item instanceof NewTransactionModel.TransactionAccount) {
629 NewTransactionModel.TransactionAccount acc = item.toTransactionAccount();
631 final String incomingAccountName = acc.getAccountName();
632 final String presentAccountName = String.valueOf(b.accountRowAccName.getText());
633 if (!TextUtils.equals(incomingAccountName, presentAccountName)) {
635 String.format("Setting account name from '%s' to '%s' (| @ %d)",
636 presentAccountName, incomingAccountName,
637 acc.getAccountNameCursorPosition()));
638 // avoid triggering completion pop-up
639 AccountAutocompleteAdapter a =
640 (AccountAutocompleteAdapter) b.accountRowAccName.getAdapter();
642 b.accountRowAccName.setAdapter(null);
643 b.accountRowAccName.setText(incomingAccountName);
644 b.accountRowAccName.setSelection(acc.getAccountNameCursorPosition());
647 b.accountRowAccName.setAdapter(a);
651 final String amountHint = acc.getAmountHint();
652 if (amountHint == null) {
653 b.accountRowAccAmounts.setHint(R.string.zero_amount);
656 b.accountRowAccAmounts.setHint(amountHint);
659 b.accountRowAccAmounts.setImeOptions(
660 acc.isLast() ? EditorInfo.IME_ACTION_DONE : EditorInfo.IME_ACTION_NEXT);
662 setCurrencyString(acc.getCurrency());
663 b.accountRowAccAmounts.setText(
664 acc.isAmountSet() ? String.format("%4.2f", acc.getAmount()) : null);
665 displayAmountValidity(true);
667 b.comment.setText(acc.getComment());
669 b.ntrData.setVisibility(View.GONE);
670 b.ntrAccount.setVisibility(View.VISIBLE);
675 throw new RuntimeException("Don't know how to handle " + item);
678 applyFocus(mAdapter.model.getFocusInfo()
689 private void styleComment(EditText editText, String comment) {
690 final View focusedView = editText.findFocus();
691 editText.setTypeface(null, (focusedView == editText) ? Typeface.NORMAL : Typeface.ITALIC);
692 editText.setVisibility(
693 ((focusedView != editText) && TextUtils.isEmpty(comment)) ? View.INVISIBLE
697 public void onDatePicked(int year, int month, int day) {
698 final NewTransactionModel.TransactionHead head = getItem().toTransactionHead();
699 head.setDate(new SimpleDate(year, month + 1, day));
700 b.newTransactionDate.setText(head.getFormattedDate());
702 boolean focused = b.newTransactionDescription.requestFocus();
704 Misc.showSoftKeyboard((NewTransactionActivity) b.getRoot()
708 private NewTransactionModel.Item getItem() {
709 return Objects.requireNonNull(mAdapter.model.getItems()
711 .get(getAdapterPosition());
714 public void descriptionSelected(String description) {
715 b.accountRowAccName.setText(description);
716 b.accountRowAccAmounts.requestFocus(View.FOCUS_FORWARD);