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.TextView;
30 import androidx.annotation.ColorInt;
31 import androidx.annotation.NonNull;
32 import androidx.appcompat.app.AppCompatActivity;
33 import androidx.constraintlayout.widget.ConstraintLayout;
34 import androidx.lifecycle.Observer;
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.model.Currency;
41 import net.ktnx.mobileledger.model.Data;
42 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
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.Date;
56 import java.util.Locale;
58 import static net.ktnx.mobileledger.ui.new_transaction.NewTransactionModel.ItemType;
60 class NewTransactionItemHolder extends RecyclerView.ViewHolder
61 implements DatePickerFragment.DatePickedListener, DescriptionSelectedCallback {
62 private final String decimalDot;
63 private final Observer<Boolean> showCommentsObserver;
64 private final MobileLedgerProfile mProfile;
65 private final Observer<SimpleDate> dateObserver;
66 private final Observer<String> descriptionObserver;
67 private final Observer<String> transactionCommentObserver;
68 private final Observer<String> hintObserver;
69 private final Observer<Integer> focusedAccountObserver;
70 private final Observer<Integer> accountCountObserver;
71 private final Observer<Boolean> editableObserver;
72 private final Observer<Currency.Position> currencyPositionObserver;
73 private final Observer<Boolean> currencyGapObserver;
74 private final Observer<Locale> localeObserver;
75 private final Observer<Currency> currencyObserver;
76 private final Observer<Boolean> showCurrencyObserver;
77 private final Observer<String> commentObserver;
78 private final Observer<Boolean> amountValidityObserver;
79 private final NewTransactionRowBinding b;
80 private String decimalSeparator;
81 private NewTransactionModel.Item item;
83 private boolean inUpdate = false;
84 private boolean syncingData = false;
85 //TODO multiple amounts with different currencies per posting
86 NewTransactionItemHolder(@NonNull NewTransactionRowBinding b,
87 NewTransactionItemsAdapter adapter) {
90 new TextViewClearHelper().attachToTextView(b.comment);
92 b.newTransactionDescription.setNextFocusForwardId(View.NO_ID);
93 b.accountRowAccName.setNextFocusForwardId(View.NO_ID);
94 b.accountRowAccAmounts.setNextFocusForwardId(View.NO_ID); // magic!
96 b.newTransactionDate.setOnClickListener(v -> pickTransactionDate());
98 b.accountCommentButton.setOnClickListener(v -> {
99 b.comment.setVisibility(View.VISIBLE);
100 b.comment.requestFocus();
103 b.transactionCommentButton.setOnClickListener(v -> {
104 b.transactionComment.setVisibility(View.VISIBLE);
105 b.transactionComment.requestFocus();
108 mProfile = Data.getProfile();
110 View.OnFocusChangeListener focusMonitor = (v, hasFocus) -> {
111 final int id = v.getId();
113 boolean wasSyncing = syncingData;
116 final int pos = getAdapterPosition();
117 adapter.updateFocusedItem(pos);
118 if (id == R.id.account_row_acc_name) {
119 adapter.noteFocusIsOnAccount(pos);
121 else if (id == R.id.account_row_acc_amounts) {
122 adapter.noteFocusIsOnAmount(pos);
124 else if (id == R.id.comment) {
125 adapter.noteFocusIsOnComment(pos);
127 else if (id == R.id.transaction_comment) {
128 adapter.noteFocusIsOnTransactionComment(pos);
130 else if (id == R.id.new_transaction_description) {
131 adapter.noteFocusIsOnDescription(pos);
135 syncingData = wasSyncing;
139 if (id == R.id.comment) {
140 commentFocusChanged(b.comment, hasFocus);
142 else if (id == R.id.transaction_comment) {
143 commentFocusChanged(b.transactionComment, hasFocus);
147 b.newTransactionDescription.setOnFocusChangeListener(focusMonitor);
148 b.accountRowAccName.setOnFocusChangeListener(focusMonitor);
149 b.accountRowAccAmounts.setOnFocusChangeListener(focusMonitor);
150 b.comment.setOnFocusChangeListener(focusMonitor);
151 b.transactionComment.setOnFocusChangeListener(focusMonitor);
153 MLDB.hookAutocompletionAdapter(b.getRoot()
154 .getContext(), b.newTransactionDescription,
155 MLDB.DESCRIPTION_HISTORY_TABLE, "description", false, adapter, mProfile);
156 MLDB.hookAutocompletionAdapter(b.getRoot()
157 .getContext(), b.accountRowAccName, MLDB.ACCOUNTS_TABLE,
158 "name", true, this, mProfile);
160 decimalSeparator = String.valueOf(DecimalFormatSymbols.getInstance()
161 .getMonetaryDecimalSeparator());
162 localeObserver = locale -> decimalSeparator = String.valueOf(
163 DecimalFormatSymbols.getInstance(locale)
164 .getMonetaryDecimalSeparator());
168 final TextWatcher tw = new TextWatcher() {
170 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
174 public void onTextChanged(CharSequence s, int start, int before, int count) {
178 public void afterTextChanged(Editable s) {
179 // debug("input", "text changed");
183 Logger.debug("textWatcher", "calling syncData()");
185 Logger.debug("textWatcher",
186 "syncData() returned, checking if transaction is submittable");
187 adapter.checkTransactionSubmittable();
188 Logger.debug("textWatcher", "done");
191 final TextWatcher amountWatcher = new TextWatcher() {
193 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
195 String.format(Locale.US, "beforeTextChanged: start=%d, count=%d, after=%d",
196 start, count, after));
199 public void onTextChanged(CharSequence s, int start, int before, int count) {}
201 public void afterTextChanged(Editable s) {
204 adapter.checkTransactionSubmittable();
207 b.newTransactionDescription.addTextChangedListener(tw);
208 b.transactionComment.addTextChangedListener(tw);
209 b.accountRowAccName.addTextChangedListener(tw);
210 b.comment.addTextChangedListener(tw);
211 b.accountRowAccAmounts.addTextChangedListener(amountWatcher);
213 b.currencyButton.setOnClickListener(v -> {
214 CurrencySelectorFragment cpf = new CurrencySelectorFragment();
215 cpf.showPositionAndPadding();
216 cpf.setOnCurrencySelectedListener(c -> item.setCurrency(c));
217 final AppCompatActivity activity = (AppCompatActivity) v.getContext();
218 cpf.show(activity.getSupportFragmentManager(), "currency-selector");
221 dateObserver = date -> {
226 b.newTransactionDate.setText(item.getFormattedDate());
232 descriptionObserver = description -> {
237 b.newTransactionDescription.setText(description);
243 transactionCommentObserver = transactionComment -> {
244 final View focusedView = b.transactionComment.findFocus();
245 b.transactionComment.setTypeface(null,
246 (focusedView == b.transactionComment) ? Typeface.NORMAL : Typeface.ITALIC);
247 b.transactionComment.setVisibility(
248 ((focusedView != b.transactionComment) && TextUtils.isEmpty(transactionComment))
249 ? View.INVISIBLE : View.VISIBLE);
252 hintObserver = hint -> {
258 b.accountRowAccAmounts.setHint(R.string.zero_amount);
260 b.accountRowAccAmounts.setHint(hint);
266 editableObserver = this::setEditable;
267 commentFocusChanged(b.transactionComment, false);
268 commentFocusChanged(b.comment, false);
269 focusedAccountObserver = index -> {
270 if ((index == null) || !index.equals(getAdapterPosition()) || itemView.hasFocus())
273 switch (item.getType()) {
275 // bad idea - double pop-up, and not really necessary.
276 // the user can tap the input to get the calendar
277 //if (!tvDate.hasFocus()) tvDate.requestFocus();
278 switch (item.getFocusedElement()) {
279 case TransactionComment:
280 b.transactionComment.setVisibility(View.VISIBLE);
281 b.transactionComment.requestFocus();
284 boolean focused = b.newTransactionDescription.requestFocus();
285 // tvDescription.dismissDropDown();
287 Misc.showSoftKeyboard((NewTransactionActivity) b.getRoot()
293 switch (item.getFocusedElement()) {
295 b.accountRowAccAmounts.requestFocus();
298 b.comment.setVisibility(View.VISIBLE);
299 b.comment.requestFocus();
302 boolean focused = b.accountRowAccName.requestFocus();
303 b.accountRowAccName.dismissDropDown();
305 Misc.showSoftKeyboard((NewTransactionActivity) b.getRoot()
313 accountCountObserver = count -> {
314 final int adapterPosition = getAdapterPosition();
315 final int layoutPosition = getLayoutPosition();
316 Logger.debug("holder",
317 String.format(Locale.US, "count=%d; pos=%d, layoutPos=%d [%s]", count,
318 adapterPosition, layoutPosition, item.getType()
320 .concat(item.getType() ==
321 ItemType.transactionRow
322 ? String.format(Locale.US,
328 ? String.format(Locale.US,
333 if (adapterPosition == count)
334 b.accountRowAccAmounts.setImeOptions(EditorInfo.IME_ACTION_DONE);
336 b.accountRowAccAmounts.setImeOptions(EditorInfo.IME_ACTION_NEXT);
339 currencyObserver = currency -> {
340 setCurrency(currency);
341 adapter.checkTransactionSubmittable();
344 currencyGapObserver =
345 hasGap -> updateCurrencyPositionAndPadding(Data.currencySymbolPosition.getValue(),
348 currencyPositionObserver =
349 position -> updateCurrencyPositionAndPadding(position, Data.currencyGap.getValue());
351 showCurrencyObserver = showCurrency -> {
353 b.currency.setVisibility(View.VISIBLE);
354 b.currencyButton.setVisibility(View.VISIBLE);
355 String defaultCommodity = mProfile.getDefaultCommodity();
357 (defaultCommodity == null) ? null : Currency.loadByName(defaultCommodity));
360 b.currency.setVisibility(View.GONE);
361 b.currencyButton.setVisibility(View.GONE);
362 item.setCurrency(null);
366 commentObserver = comment -> {
367 final View focusedView = b.comment.findFocus();
368 b.comment.setTypeface(null,
369 (focusedView == b.comment) ? Typeface.NORMAL : Typeface.ITALIC);
370 b.comment.setVisibility(
371 ((focusedView != b.comment) && TextUtils.isEmpty(comment)) ? View.INVISIBLE
375 showCommentsObserver = show -> {
376 ConstraintLayout.LayoutParams amountLayoutParams =
377 (ConstraintLayout.LayoutParams) b.amountLayout.getLayoutParams();
378 ConstraintLayout.LayoutParams accountParams =
379 (ConstraintLayout.LayoutParams) b.accountRowAccName.getLayoutParams();
381 accountParams.endToStart = ConstraintLayout.LayoutParams.UNSET;
382 accountParams.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
384 amountLayoutParams.topToTop = ConstraintLayout.LayoutParams.UNSET;
385 amountLayoutParams.topToBottom = b.accountRowAccName.getId();
387 b.commentLayout.setVisibility(View.VISIBLE);
390 accountParams.endToStart = b.amountLayout.getId();
391 accountParams.endToEnd = ConstraintLayout.LayoutParams.UNSET;
393 amountLayoutParams.topToBottom = ConstraintLayout.LayoutParams.UNSET;
394 amountLayoutParams.topToTop = ConstraintLayout.LayoutParams.PARENT_ID;
396 b.commentLayout.setVisibility(View.GONE);
399 b.accountRowAccName.setLayoutParams(accountParams);
400 b.amountLayout.setLayoutParams(amountLayoutParams);
402 b.transactionCommentLayout.setVisibility(show ? View.VISIBLE : View.GONE);
405 amountValidityObserver = valid -> {
406 b.accountRowAccAmounts.setCompoundDrawablesRelativeWithIntrinsicBounds(
407 valid ? 0 : R.drawable.ic_error_outline_black_24dp, 0, 0, 0);
408 b.accountRowAccAmounts.setMinEms(valid ? 4 : 5);
411 private void commentFocusChanged(TextView textView, boolean hasFocus) {
412 @ColorInt int textColor;
413 textColor = b.dummyText.getTextColors()
416 textView.setTypeface(null, Typeface.NORMAL);
417 textView.setHint(R.string.transaction_account_comment_hint);
420 int alpha = (textColor >> 24 & 0xff);
421 alpha = 3 * alpha / 4;
422 textColor = (alpha << 24) | (0x00ffffff & textColor);
423 textView.setTypeface(null, Typeface.ITALIC);
424 textView.setHint("");
425 if (TextUtils.isEmpty(textView.getText())) {
426 textView.setVisibility(View.INVISIBLE);
429 textView.setTextColor(textColor);
432 private void updateCurrencyPositionAndPadding(Currency.Position position, boolean hasGap) {
433 ConstraintLayout.LayoutParams amountLP =
434 (ConstraintLayout.LayoutParams) b.accountRowAccAmounts.getLayoutParams();
435 ConstraintLayout.LayoutParams currencyLP =
436 (ConstraintLayout.LayoutParams) b.currency.getLayoutParams();
438 if (position == Currency.Position.before) {
439 currencyLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
440 currencyLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
442 amountLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
443 amountLP.endToStart = ConstraintLayout.LayoutParams.UNSET;
444 amountLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
445 amountLP.startToEnd = b.currency.getId();
447 b.currency.setGravity(Gravity.END);
450 currencyLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
451 currencyLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
453 amountLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
454 amountLP.startToEnd = ConstraintLayout.LayoutParams.UNSET;
455 amountLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
456 amountLP.endToStart = b.currency.getId();
458 b.currency.setGravity(Gravity.START);
461 amountLP.resolveLayoutDirection(b.accountRowAccAmounts.getLayoutDirection());
462 currencyLP.resolveLayoutDirection(b.currency.getLayoutDirection());
464 b.accountRowAccAmounts.setLayoutParams(amountLP);
465 b.currency.setLayoutParams(currencyLP);
467 // distance between the amount and the currency symbol
468 int gapSize = DimensionUtils.sp2px(b.currency.getContext(), 5);
470 if (position == Currency.Position.before) {
471 b.currency.setPaddingRelative(0, 0, hasGap ? gapSize : 0, 0);
474 b.currency.setPaddingRelative(hasGap ? gapSize : 0, 0, 0, 0);
477 private void setCurrencyString(String currency) {
478 @ColorInt int textColor = b.dummyText.getTextColors()
480 if ((currency == null) || currency.isEmpty()) {
481 b.currency.setText(R.string.currency_symbol);
482 int alpha = (textColor >> 24) & 0xff;
483 alpha = alpha * 3 / 4;
484 b.currency.setTextColor((alpha << 24) | (0x00ffffff & textColor));
487 b.currency.setText(currency);
488 b.currency.setTextColor(textColor);
491 private void setCurrency(Currency currency) {
492 setCurrencyString((currency == null) ? null : currency.getName());
494 private void setEditable(Boolean editable) {
495 b.newTransactionDate.setEnabled(editable);
496 b.newTransactionDescription.setEnabled(editable);
497 b.accountRowAccName.setEnabled(editable);
498 b.accountRowAccAmounts.setEnabled(editable);
500 private void beginUpdates() {
502 throw new RuntimeException("Already in update mode");
505 private void endUpdates() {
507 throw new RuntimeException("Not in update mode");
513 * Stores the data from the UI elements into the model item
514 * Returns true if there were changes made that suggest transaction has to be
515 * checked for being submittable
517 private boolean syncData() {
522 Logger.debug("new-trans", "skipping syncData() loop");
529 switch (item.getType()) {
531 item.setDate(String.valueOf(b.newTransactionDate.getText()));
532 item.setDescription(String.valueOf(b.newTransactionDescription.getText()));
533 item.setTransactionComment(String.valueOf(b.transactionComment.getText()));
536 final LedgerTransactionAccount account = item.getAccount();
537 account.setAccountName(String.valueOf(b.accountRowAccName.getText()));
539 item.setComment(String.valueOf(b.comment.getText()));
541 String amount = String.valueOf(b.accountRowAccAmounts.getText());
542 amount = amount.trim();
544 if (amount.isEmpty()) {
545 account.resetAmount();
546 item.validateAmount();
550 amount = amount.replace(decimalSeparator, decimalDot);
551 account.setAmount(Float.parseFloat(amount));
552 item.validateAmount();
554 catch (NumberFormatException e) {
555 Logger.debug("new-trans", String.format(
556 "assuming amount is not set due to number format exception. " +
557 "input was '%s'", amount));
558 account.invalidateAmount();
559 item.invalidateAmount();
561 final String curr = String.valueOf(b.currency.getText());
562 if (curr.equals(b.currency.getContext()
564 .getString(R.string.currency_symbol)) ||
566 account.setCurrency(null);
568 account.setCurrency(curr);
573 throw new RuntimeException("Should not happen");
578 catch (ParseException e) {
579 throw new RuntimeException("Should not happen", e);
585 private void pickTransactionDate() {
586 DatePickerFragment picker = new DatePickerFragment();
587 picker.setFutureDates(mProfile.getFutureDates());
588 picker.setOnDatePickedListener(this);
589 picker.setCurrentDateFromText(b.newTransactionDate.getText());
590 picker.show(((NewTransactionActivity) b.getRoot()
591 .getContext()).getSupportFragmentManager(), null);
596 * @param item updates the UI elements with the data from the model item
598 @SuppressLint("DefaultLocale")
599 public void setData(NewTransactionModel.Item item) {
602 if (this.item != null && !this.item.equals(item)) {
603 this.item.stopObservingDate(dateObserver);
604 this.item.stopObservingDescription(descriptionObserver);
605 this.item.stopObservingTransactionComment(transactionCommentObserver);
606 this.item.stopObservingAmountHint(hintObserver);
607 this.item.stopObservingEditableFlag(editableObserver);
609 .stopObservingFocusedItem(focusedAccountObserver);
611 .stopObservingAccountCount(accountCountObserver);
612 Data.currencySymbolPosition.removeObserver(currencyPositionObserver);
613 Data.currencyGap.removeObserver(currencyGapObserver);
614 Data.locale.removeObserver(localeObserver);
615 this.item.stopObservingCurrency(currencyObserver);
616 this.item.getModel().showCurrency.removeObserver(showCurrencyObserver);
617 this.item.stopObservingComment(commentObserver);
618 this.item.getModel().showComments.removeObserver(showCommentsObserver);
619 this.item.stopObservingAmountValidity(amountValidityObserver);
624 switch (item.getType()) {
626 b.newTransactionDate.setText(item.getFormattedDate());
627 b.newTransactionDescription.setText(item.getDescription());
628 b.transactionComment.setText(item.getTransactionComment());
629 b.ntrData.setVisibility(View.VISIBLE);
630 b.ntrAccount.setVisibility(View.GONE);
631 b.ntrPadding.setVisibility(View.GONE);
635 LedgerTransactionAccount acc = item.getAccount();
636 b.accountRowAccName.setText(acc.getAccountName());
637 b.comment.setText(acc.getComment());
638 if (acc.isAmountSet()) {
639 b.accountRowAccAmounts.setText(String.format("%1.2f", acc.getAmount()));
642 b.accountRowAccAmounts.setText("");
643 // tvAmount.setHint(R.string.zero_amount);
645 b.accountRowAccAmounts.setHint(item.getAmountHint());
646 setCurrencyString(acc.getCurrency());
647 b.ntrData.setVisibility(View.GONE);
648 b.ntrAccount.setVisibility(View.VISIBLE);
649 b.ntrPadding.setVisibility(View.GONE);
653 b.ntrData.setVisibility(View.GONE);
654 b.ntrAccount.setVisibility(View.GONE);
655 b.ntrPadding.setVisibility(View.VISIBLE);
659 if (this.item == null) { // was null or has changed
661 final NewTransactionActivity activity = (NewTransactionActivity) b.getRoot()
664 if (!item.isBottomFiller()) {
665 item.observeEditableFlag(activity, editableObserver);
667 .observeFocusedItem(activity, focusedAccountObserver);
669 .observeShowComments(activity, showCommentsObserver);
671 switch (item.getType()) {
673 item.observeDate(activity, dateObserver);
674 item.observeDescription(activity, descriptionObserver);
675 item.observeTransactionComment(activity, transactionCommentObserver);
678 item.observeAmountHint(activity, hintObserver);
679 Data.currencySymbolPosition.observe(activity, currencyPositionObserver);
680 Data.currencyGap.observe(activity, currencyGapObserver);
681 Data.locale.observe(activity, localeObserver);
682 item.observeCurrency(activity, currencyObserver);
683 item.getModel().showCurrency.observe(activity, showCurrencyObserver);
684 item.observeComment(activity, commentObserver);
686 .observeAccountCount(activity, accountCountObserver);
687 item.observeAmountValidity(activity, amountValidityObserver);
697 public void onDatePicked(int year, int month, int day) {
698 item.setDate(new SimpleDate(year, month + 1, day));
699 boolean focused = b.newTransactionDescription.requestFocus();
701 Misc.showSoftKeyboard((NewTransactionActivity) b.getRoot()
706 public void descriptionSelected(String description) {
707 b.accountRowAccName.setText(description);
708 b.accountRowAccAmounts.requestFocus(View.FOCUS_FORWARD);