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(c -> adapter.setItemCurrency(getAdapterPosition(),
211 (c == null) ? null : 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 if (getAdapterPosition() < 0) {
484 // probably the row was swiped out
485 Logger.debug("new-trans", "Ignoring request to suncData(): adapter position negative");
489 NewTransactionModel.Item item = getItem();
493 boolean significantChange = false;
496 if (item instanceof NewTransactionModel.TransactionHead) {
497 NewTransactionModel.TransactionHead head = item.toTransactionHead();
499 head.setDate(String.valueOf(b.newTransactionDate.getText()));
501 // transaction description is required
502 if (TextUtils.isEmpty(head.getDescription()) !=
503 TextUtils.isEmpty(b.newTransactionDescription.getText()))
504 significantChange = true;
506 head.setDescription(String.valueOf(b.newTransactionDescription.getText()));
507 head.setComment(String.valueOf(b.transactionComment.getText()));
509 else if (item instanceof NewTransactionModel.TransactionAccount) {
510 NewTransactionModel.TransactionAccount acc = item.toTransactionAccount();
512 // having account name is important
513 final Editable incomingAccountName = b.accountRowAccName.getText();
514 if (TextUtils.isEmpty(acc.getAccountName()) !=
515 TextUtils.isEmpty(incomingAccountName))
516 significantChange = true;
518 acc.setAccountName(String.valueOf(incomingAccountName));
519 final int accNameSelEnd = b.accountRowAccName.getSelectionEnd();
520 final int accNameSelStart = b.accountRowAccName.getSelectionStart();
521 acc.setAccountNameCursorPosition(accNameSelEnd);
523 acc.setComment(String.valueOf(b.comment.getText()));
525 String amount = String.valueOf(b.accountRowAccAmounts.getText());
526 amount = amount.trim();
528 if (amount.isEmpty()) {
529 if (acc.isAmountSet())
530 significantChange = true;
532 acc.setAmountValid(true);
536 amount = amount.replace(decimalSeparator, decimalDot);
537 final float parsedAmount = Float.parseFloat(amount);
538 if (!acc.isAmountSet() || !Misc.equalFloats(parsedAmount, acc.getAmount()))
539 significantChange = true;
540 acc.setAmount(parsedAmount);
541 acc.setAmountValid(true);
543 catch (NumberFormatException e) {
544 Logger.debug("new-trans", String.format(
545 "assuming amount is not set due to number format exception. " +
546 "input was '%s'", amount));
547 if (acc.isAmountValid())
548 significantChange = true;
549 acc.setAmountValid(false);
551 final String curr = String.valueOf(b.currency.getText());
552 final String currValue;
553 if (curr.equals(b.currency.getContext()
555 .getString(R.string.currency_symbol)) ||
561 if (!significantChange && !TextUtils.equals(acc.getCurrency(), currValue))
562 significantChange = true;
563 acc.setCurrency(currValue);
567 throw new RuntimeException("Should not happen");
570 return significantChange;
572 catch (ParseException e) {
573 throw new RuntimeException("Should not happen", e);
579 private void pickTransactionDate() {
580 DatePickerFragment picker = new DatePickerFragment();
581 picker.setFutureDates(mProfile.getFutureDates());
582 picker.setOnDatePickedListener(this);
583 picker.setCurrentDateFromText(b.newTransactionDate.getText());
584 picker.show(((NewTransactionActivity) b.getRoot()
585 .getContext()).getSupportFragmentManager(), null);
590 * @param item updates the UI elements with the data from the model item
592 @SuppressLint("DefaultLocale")
593 public void bind(@NonNull NewTransactionModel.Item item) {
598 if (item instanceof NewTransactionModel.TransactionHead) {
599 NewTransactionModel.TransactionHead head = item.toTransactionHead();
600 b.newTransactionDate.setText(head.getFormattedDate());
602 // avoid triggering completion pop-up
603 SimpleCursorAdapter a =
604 (SimpleCursorAdapter) b.newTransactionDescription.getAdapter();
606 b.newTransactionDescription.setAdapter(null);
607 b.newTransactionDescription.setText(head.getDescription());
610 b.newTransactionDescription.setAdapter(a);
613 b.transactionComment.setText(head.getComment());
614 //styleComment(b.transactionComment, head.getComment());
616 b.ntrData.setVisibility(View.VISIBLE);
617 b.ntrAccount.setVisibility(View.GONE);
620 else if (item instanceof NewTransactionModel.TransactionAccount) {
621 NewTransactionModel.TransactionAccount acc = item.toTransactionAccount();
623 final String incomingAccountName = acc.getAccountName();
624 final String presentAccountName = String.valueOf(b.accountRowAccName.getText());
625 if (!TextUtils.equals(incomingAccountName, presentAccountName)) {
627 String.format("Setting account name from '%s' to '%s' (| @ %d)",
628 presentAccountName, incomingAccountName,
629 acc.getAccountNameCursorPosition()));
630 // avoid triggering completion pop-up
631 AccountAutocompleteAdapter a =
632 (AccountAutocompleteAdapter) b.accountRowAccName.getAdapter();
634 b.accountRowAccName.setAdapter(null);
635 b.accountRowAccName.setText(incomingAccountName);
636 b.accountRowAccName.setSelection(acc.getAccountNameCursorPosition());
639 b.accountRowAccName.setAdapter(a);
643 final String amountHint = acc.getAmountHint();
644 if (amountHint == null) {
645 b.accountRowAccAmounts.setHint(R.string.zero_amount);
648 b.accountRowAccAmounts.setHint(amountHint);
651 b.accountRowAccAmounts.setImeOptions(
652 acc.isLast() ? EditorInfo.IME_ACTION_DONE : EditorInfo.IME_ACTION_NEXT);
654 setCurrencyString(acc.getCurrency());
655 b.accountRowAccAmounts.setText(
656 acc.isAmountSet() ? String.format("%4.2f", acc.getAmount()) : null);
657 displayAmountValidity(true);
659 b.comment.setText(acc.getComment());
661 b.ntrData.setVisibility(View.GONE);
662 b.ntrAccount.setVisibility(View.VISIBLE);
667 throw new RuntimeException("Don't know how to handle " + item);
670 applyFocus(mAdapter.model.getFocusInfo()
681 private void styleComment(EditText editText, String comment) {
682 final View focusedView = editText.findFocus();
683 editText.setTypeface(null, (focusedView == editText) ? Typeface.NORMAL : Typeface.ITALIC);
684 editText.setVisibility(
685 ((focusedView != editText) && TextUtils.isEmpty(comment)) ? View.INVISIBLE
689 public void onDatePicked(int year, int month, int day) {
690 final NewTransactionModel.TransactionHead head = getItem().toTransactionHead();
691 head.setDate(new SimpleDate(year, month + 1, day));
692 b.newTransactionDate.setText(head.getFormattedDate());
694 boolean focused = b.newTransactionDescription.requestFocus();
696 Misc.showSoftKeyboard((NewTransactionActivity) b.getRoot()
700 private NewTransactionModel.Item getItem() {
701 return Objects.requireNonNull(mAdapter.model.getItems()
703 .get(getAdapterPosition());
706 public void descriptionSelected(String description) {
707 b.accountRowAccName.setText(description);
708 b.accountRowAccAmounts.requestFocus(View.FOCUS_FORWARD);