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 b.accountRowAccAmounts.setText(newText);
131 catch (NumberFormatException ex) {
137 if (id == R.id.comment) {
138 commentFocusChanged(b.comment, hasFocus);
140 else if (id == R.id.transaction_comment) {
141 commentFocusChanged(b.transactionComment, hasFocus);
145 b.newTransactionDescription.setOnFocusChangeListener(focusMonitor);
146 b.accountRowAccName.setOnFocusChangeListener(focusMonitor);
147 b.accountRowAccAmounts.setOnFocusChangeListener(focusMonitor);
148 b.comment.setOnFocusChangeListener(focusMonitor);
149 b.transactionComment.setOnFocusChangeListener(focusMonitor);
151 NewTransactionActivity activity = (NewTransactionActivity) b.getRoot()
154 MLDB.hookAutocompletionAdapter(activity, b.newTransactionDescription,
155 MLDB.DESCRIPTION_HISTORY_TABLE, "description", false, activity, mProfile);
156 b.accountRowAccName.setAdapter(new AccountAutocompleteAdapter(b.getRoot()
157 .getContext(), mProfile));
159 decimalSeparator = "";
160 Data.locale.observe(activity, locale -> decimalSeparator = String.valueOf(
161 DecimalFormatSymbols.getInstance(locale)
162 .getMonetaryDecimalSeparator()));
164 final TextWatcher tw = new TextWatcher() {
166 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
170 public void onTextChanged(CharSequence s, int start, int before, int count) {
174 public void afterTextChanged(Editable s) {
175 // debug("input", "text changed");
179 Logger.debug("textWatcher", "calling syncData()");
181 Logger.debug("textWatcher",
182 "syncData() returned, checking if transaction is submittable");
183 adapter.model.checkTransactionSubmittable(null);
185 Logger.debug("textWatcher", "done");
188 final TextWatcher amountWatcher = new TextWatcher() {
190 public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
192 public void onTextChanged(CharSequence s, int start, int before, int count) {}
194 public void afterTextChanged(Editable s) {
195 checkAmountValid(s.toString());
198 adapter.model.checkTransactionSubmittable(null);
201 b.newTransactionDescription.addTextChangedListener(tw);
202 monitorComment(b.transactionComment);
203 b.accountRowAccName.addTextChangedListener(tw);
204 monitorComment(b.comment);
205 b.accountRowAccAmounts.addTextChangedListener(amountWatcher);
207 b.currencyButton.setOnClickListener(v -> {
208 CurrencySelectorFragment cpf = new CurrencySelectorFragment();
209 cpf.showPositionAndPadding();
210 cpf.setOnCurrencySelectedListener(
211 c -> adapter.setItemCurrency(getAdapterPosition(), c.getName()));
212 cpf.show(activity.getSupportFragmentManager(), "currency-selector");
215 commentFocusChanged(b.transactionComment, false);
216 commentFocusChanged(b.comment, false);
218 adapter.model.getFocusInfo()
219 .observe(activity, this::applyFocus);
221 Data.currencyGap.observe(activity,
222 hasGap -> updateCurrencyPositionAndPadding(Data.currencySymbolPosition.getValue(),
225 Data.currencySymbolPosition.observe(activity,
226 position -> updateCurrencyPositionAndPadding(position,
227 Data.currencyGap.getValue()));
229 adapter.model.getShowCurrency()
230 .observe(activity, showCurrency -> {
232 b.currency.setVisibility(View.VISIBLE);
233 b.currencyButton.setVisibility(View.VISIBLE);
234 setCurrencyString(mProfile.getDefaultCommodity());
237 b.currency.setVisibility(View.GONE);
238 b.currencyButton.setVisibility(View.GONE);
239 setCurrencyString(null);
243 adapter.model.getShowComments()
244 .observe(activity, show -> {
245 ConstraintLayout.LayoutParams amountLayoutParams =
246 (ConstraintLayout.LayoutParams) b.amountLayout.getLayoutParams();
247 ConstraintLayout.LayoutParams accountParams =
248 (ConstraintLayout.LayoutParams) b.accountRowAccName.getLayoutParams();
251 accountParams.endToStart = ConstraintLayout.LayoutParams.UNSET;
252 accountParams.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
254 amountLayoutParams.topToTop = ConstraintLayout.LayoutParams.UNSET;
255 amountLayoutParams.topToBottom = b.accountRowAccName.getId();
257 b.commentLayout.setVisibility(View.VISIBLE);
260 accountParams.endToStart = b.amountLayout.getId();
261 accountParams.endToEnd = ConstraintLayout.LayoutParams.UNSET;
263 amountLayoutParams.topToBottom = ConstraintLayout.LayoutParams.UNSET;
264 amountLayoutParams.topToTop = ConstraintLayout.LayoutParams.PARENT_ID;
266 b.commentLayout.setVisibility(View.GONE);
269 b.accountRowAccName.setLayoutParams(accountParams);
270 b.amountLayout.setLayoutParams(amountLayoutParams);
272 b.transactionCommentLayout.setVisibility(show ? View.VISIBLE : View.GONE);
275 private void applyFocus(NewTransactionModel.FocusInfo focusInfo) {
276 if (ignoreFocusChanges) {
277 Logger.debug("new-trans", "Ignoring focus change");
280 ignoreFocusChanges = true;
282 if (((focusInfo == null) || (focusInfo.element == null) ||
283 focusInfo.position != getAdapterPosition()))
286 NewTransactionModel.Item item = getItem();
287 if (item instanceof NewTransactionModel.TransactionHead) {
288 NewTransactionModel.TransactionHead head = item.toTransactionHead();
289 // bad idea - double pop-up, and not really necessary.
290 // the user can tap the input to get the calendar
291 //if (!tvDate.hasFocus()) tvDate.requestFocus();
292 switch (focusInfo.element) {
293 case TransactionComment:
294 b.transactionComment.setVisibility(View.VISIBLE);
295 b.transactionComment.requestFocus();
298 boolean focused = b.newTransactionDescription.requestFocus();
299 // tvDescription.dismissDropDown();
301 Misc.showSoftKeyboard((NewTransactionActivity) b.getRoot()
306 else if (item instanceof NewTransactionModel.TransactionAccount) {
307 NewTransactionModel.TransactionAccount acc = item.toTransactionAccount();
308 switch (focusInfo.element) {
310 b.accountRowAccAmounts.requestFocus();
313 b.comment.setVisibility(View.VISIBLE);
314 b.comment.requestFocus();
317 boolean focused = b.accountRowAccName.requestFocus();
318 // b.accountRowAccName.dismissDropDown();
320 Misc.showSoftKeyboard((NewTransactionActivity) b.getRoot()
327 ignoreFocusChanges = false;
330 public void checkAmountValid(String s) {
331 boolean valid = true;
333 if (s.length() > 0) {
334 float ignored = Float.parseFloat(s.replace(decimalSeparator, decimalDot));
337 catch (NumberFormatException ex) {
341 displayAmountValidity(valid);
343 private void displayAmountValidity(boolean valid) {
344 b.accountRowAccAmounts.setCompoundDrawablesRelativeWithIntrinsicBounds(
345 valid ? 0 : R.drawable.ic_error_outline_black_24dp, 0, 0, 0);
346 b.accountRowAccAmounts.setMinEms(valid ? 4 : 5);
348 private void monitorComment(EditText editText) {
349 editText.addTextChangedListener(new TextWatcher() {
351 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
354 public void onTextChanged(CharSequence s, int start, int before, int count) {
357 public void afterTextChanged(Editable s) {
358 // debug("input", "text changed");
362 Logger.debug("textWatcher", "calling syncData()");
364 Logger.debug("textWatcher",
365 "syncData() returned, checking if transaction is submittable");
366 styleComment(editText, s.toString());
367 Logger.debug("textWatcher", "done");
371 private void commentFocusChanged(TextView textView, boolean hasFocus) {
372 @ColorInt int textColor;
373 textColor = b.dummyText.getTextColors()
376 textView.setTypeface(null, Typeface.NORMAL);
377 textView.setHint(R.string.transaction_account_comment_hint);
380 int alpha = (textColor >> 24 & 0xff);
381 alpha = 3 * alpha / 4;
382 textColor = (alpha << 24) | (0x00ffffff & textColor);
383 textView.setTypeface(null, Typeface.ITALIC);
384 textView.setHint("");
385 if (TextUtils.isEmpty(textView.getText())) {
386 textView.setVisibility(View.INVISIBLE);
389 textView.setTextColor(textColor);
392 private void updateCurrencyPositionAndPadding(Currency.Position position, boolean hasGap) {
393 ConstraintLayout.LayoutParams amountLP =
394 (ConstraintLayout.LayoutParams) b.accountRowAccAmounts.getLayoutParams();
395 ConstraintLayout.LayoutParams currencyLP =
396 (ConstraintLayout.LayoutParams) b.currency.getLayoutParams();
398 if (position == Currency.Position.before) {
399 currencyLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
400 currencyLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
402 amountLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
403 amountLP.endToStart = ConstraintLayout.LayoutParams.UNSET;
404 amountLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
405 amountLP.startToEnd = b.currency.getId();
407 b.currency.setGravity(Gravity.END);
410 currencyLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
411 currencyLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
413 amountLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
414 amountLP.startToEnd = ConstraintLayout.LayoutParams.UNSET;
415 amountLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
416 amountLP.endToStart = b.currency.getId();
418 b.currency.setGravity(Gravity.START);
421 amountLP.resolveLayoutDirection(b.accountRowAccAmounts.getLayoutDirection());
422 currencyLP.resolveLayoutDirection(b.currency.getLayoutDirection());
424 b.accountRowAccAmounts.setLayoutParams(amountLP);
425 b.currency.setLayoutParams(currencyLP);
427 // distance between the amount and the currency symbol
428 int gapSize = DimensionUtils.sp2px(b.currency.getContext(), 5);
430 if (position == Currency.Position.before) {
431 b.currency.setPaddingRelative(0, 0, hasGap ? gapSize : 0, 0);
434 b.currency.setPaddingRelative(hasGap ? gapSize : 0, 0, 0, 0);
437 private void setCurrencyString(String currency) {
438 @ColorInt int textColor = b.dummyText.getTextColors()
440 if (TextUtils.isEmpty(currency)) {
441 b.currency.setText(R.string.currency_symbol);
442 int alpha = (textColor >> 24) & 0xff;
443 alpha = alpha * 3 / 4;
444 b.currency.setTextColor((alpha << 24) | (0x00ffffff & textColor));
447 b.currency.setText(currency);
448 b.currency.setTextColor(textColor);
451 private void setCurrency(Currency currency) {
452 setCurrencyString((currency == null) ? null : currency.getName());
454 private void setEditable(Boolean editable) {
455 b.newTransactionDate.setEnabled(editable);
456 b.newTransactionDescription.setEnabled(editable);
457 b.accountRowAccName.setEnabled(editable);
458 b.accountRowAccAmounts.setEnabled(editable);
460 private void beginUpdates() {
462 throw new RuntimeException("Already in update mode");
465 private void endUpdates() {
467 throw new RuntimeException("Not in update mode");
473 * Stores the data from the UI elements into the model item
474 * Returns true if there were changes made that suggest transaction has to be
475 * checked for being submittable
477 private boolean syncData() {
479 Logger.debug("new-trans", "skipping syncData() loop");
483 NewTransactionModel.Item item = getItem();
487 boolean significantChange = false;
490 if (item instanceof NewTransactionModel.TransactionHead) {
491 NewTransactionModel.TransactionHead head = item.toTransactionHead();
493 head.setDate(String.valueOf(b.newTransactionDate.getText()));
495 // transaction description is required
496 if (TextUtils.isEmpty(head.getDescription()) !=
497 TextUtils.isEmpty(b.newTransactionDescription.getText()))
498 significantChange = true;
500 head.setDescription(String.valueOf(b.newTransactionDescription.getText()));
501 head.setComment(String.valueOf(b.transactionComment.getText()));
503 else if (item instanceof NewTransactionModel.TransactionAccount) {
504 NewTransactionModel.TransactionAccount acc = item.toTransactionAccount();
506 // having account name is important
507 final Editable incomingAccountName = b.accountRowAccName.getText();
508 if (TextUtils.isEmpty(acc.getAccountName()) !=
509 TextUtils.isEmpty(incomingAccountName))
510 significantChange = true;
512 acc.setAccountName(String.valueOf(incomingAccountName));
513 final int accNameSelEnd = b.accountRowAccName.getSelectionEnd();
514 final int accNameSelStart = b.accountRowAccName.getSelectionStart();
515 acc.setAccountNameCursorPosition(accNameSelEnd);
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);
614 else if (item instanceof NewTransactionModel.TransactionAccount) {
615 NewTransactionModel.TransactionAccount acc = item.toTransactionAccount();
617 final String incomingAccountName = acc.getAccountName();
618 final String presentAccountName = String.valueOf(b.accountRowAccName.getText());
619 if (!TextUtils.equals(incomingAccountName, presentAccountName)) {
621 String.format("Setting account name from '%s' to '%s' (| @ %d)",
622 presentAccountName, incomingAccountName,
623 acc.getAccountNameCursorPosition()));
624 // avoid triggering completion pop-up
625 AccountAutocompleteAdapter a =
626 (AccountAutocompleteAdapter) b.accountRowAccName.getAdapter();
628 b.accountRowAccName.setAdapter(null);
629 b.accountRowAccName.setText(incomingAccountName);
630 b.accountRowAccName.setSelection(acc.getAccountNameCursorPosition());
633 b.accountRowAccName.setAdapter(a);
637 final String amountHint = acc.getAmountHint();
638 if (amountHint == null) {
639 b.accountRowAccAmounts.setHint(R.string.zero_amount);
642 b.accountRowAccAmounts.setHint(amountHint);
645 b.accountRowAccAmounts.setImeOptions(
646 acc.isLast() ? EditorInfo.IME_ACTION_DONE : EditorInfo.IME_ACTION_NEXT);
648 setCurrencyString(acc.getCurrency());
649 b.accountRowAccAmounts.setText(
650 acc.isAmountSet() ? String.format("%4.2f", acc.getAmount()) : null);
651 displayAmountValidity(true);
653 b.comment.setText(acc.getComment());
655 b.ntrData.setVisibility(View.GONE);
656 b.ntrAccount.setVisibility(View.VISIBLE);
661 throw new RuntimeException("Don't know how to handle " + item);
664 applyFocus(mAdapter.model.getFocusInfo()
675 private void styleComment(EditText editText, String comment) {
676 final View focusedView = editText.findFocus();
677 editText.setTypeface(null, (focusedView == editText) ? Typeface.NORMAL : Typeface.ITALIC);
678 editText.setVisibility(
679 ((focusedView != editText) && TextUtils.isEmpty(comment)) ? View.INVISIBLE
683 public void onDatePicked(int year, int month, int day) {
684 final NewTransactionModel.TransactionHead head = getItem().toTransactionHead();
685 head.setDate(new SimpleDate(year, month + 1, day));
686 b.newTransactionDate.setText(head.getFormattedDate());
688 boolean focused = b.newTransactionDescription.requestFocus();
690 Misc.showSoftKeyboard((NewTransactionActivity) b.getRoot()
694 private NewTransactionModel.Item getItem() {
695 return Objects.requireNonNull(mAdapter.model.getItems()
697 .get(getAdapterPosition());
700 public void descriptionSelected(String description) {
701 b.accountRowAccName.setText(description);
702 b.accountRowAccAmounts.requestFocus(View.FOCUS_FORWARD);