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 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.comment) {
124 commentFocusChanged(b.comment, hasFocus);
126 else if (id == R.id.transaction_comment) {
127 commentFocusChanged(b.transactionComment, hasFocus);
131 b.newTransactionDescription.setOnFocusChangeListener(focusMonitor);
132 b.accountRowAccName.setOnFocusChangeListener(focusMonitor);
133 b.accountRowAccAmounts.setOnFocusChangeListener(focusMonitor);
134 b.comment.setOnFocusChangeListener(focusMonitor);
135 b.transactionComment.setOnFocusChangeListener(focusMonitor);
137 NewTransactionActivity activity = (NewTransactionActivity) b.getRoot()
140 MLDB.hookAutocompletionAdapter(activity, b.newTransactionDescription,
141 MLDB.DESCRIPTION_HISTORY_TABLE, "description", false, activity, mProfile);
142 b.accountRowAccName.setAdapter(new AccountAutocompleteAdapter(b.getRoot()
143 .getContext(), mProfile));
145 decimalSeparator = "";
146 Data.locale.observe(activity, locale -> decimalSeparator = String.valueOf(
147 DecimalFormatSymbols.getInstance(locale)
148 .getMonetaryDecimalSeparator()));
152 final TextWatcher tw = new TextWatcher() {
154 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
158 public void onTextChanged(CharSequence s, int start, int before, int count) {
162 public void afterTextChanged(Editable s) {
163 // debug("input", "text changed");
167 Logger.debug("textWatcher", "calling syncData()");
169 Logger.debug("textWatcher",
170 "syncData() returned, checking if transaction is submittable");
171 adapter.model.checkTransactionSubmittable(null);
172 Logger.debug("textWatcher", "done");
175 final TextWatcher amountWatcher = new TextWatcher() {
177 public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
179 public void onTextChanged(CharSequence s, int start, int before, int count) {}
181 public void afterTextChanged(Editable s) {
182 checkAmountValid(s.toString());
185 adapter.model.checkTransactionSubmittable(null);
188 b.newTransactionDescription.addTextChangedListener(tw);
189 monitorComment(b.transactionComment);
190 b.accountRowAccName.addTextChangedListener(tw);
191 monitorComment(b.comment);
192 b.accountRowAccAmounts.addTextChangedListener(amountWatcher);
194 b.currencyButton.setOnClickListener(v -> {
195 CurrencySelectorFragment cpf = new CurrencySelectorFragment();
196 cpf.showPositionAndPadding();
197 cpf.setOnCurrencySelectedListener(
198 c -> adapter.setItemCurrency(getAdapterPosition(), c.getName()));
199 cpf.show(activity.getSupportFragmentManager(), "currency-selector");
202 commentFocusChanged(b.transactionComment, false);
203 commentFocusChanged(b.comment, false);
205 adapter.model.getFocusInfo()
206 .observe(activity, focusInfo -> {
207 if (ignoreFocusChanges) {
208 Logger.debug("new-trans", "Ignoring focus change");
211 ignoreFocusChanges = true;
213 if (((focusInfo == null) || (focusInfo.element == null) ||
214 focusInfo.position != getAdapterPosition()) ||
218 NewTransactionModel.Item item = getItem();
219 if (item instanceof NewTransactionModel.TransactionHead) {
220 NewTransactionModel.TransactionHead head =
221 item.toTransactionHead();
222 // bad idea - double pop-up, and not really necessary.
223 // the user can tap the input to get the calendar
224 //if (!tvDate.hasFocus()) tvDate.requestFocus();
225 switch (focusInfo.element) {
226 case TransactionComment:
227 b.transactionComment.setVisibility(View.VISIBLE);
228 b.transactionComment.requestFocus();
232 b.newTransactionDescription.requestFocus();
233 // tvDescription.dismissDropDown();
235 Misc.showSoftKeyboard(
236 (NewTransactionActivity) b.getRoot()
241 else if (item instanceof NewTransactionModel.TransactionAccount) {
242 NewTransactionModel.TransactionAccount acc =
243 item.toTransactionAccount();
244 switch (focusInfo.element) {
246 b.accountRowAccAmounts.requestFocus();
249 b.comment.setVisibility(View.VISIBLE);
250 b.comment.requestFocus();
253 boolean focused = b.accountRowAccName.requestFocus();
254 // b.accountRowAccName.dismissDropDown();
256 Misc.showSoftKeyboard(
257 (NewTransactionActivity) b.getRoot()
264 ignoreFocusChanges = false;
267 adapter.model.getAccountCount()
268 .observe(activity, count -> {
269 final int adapterPosition = getAdapterPosition();
270 final int layoutPosition = getLayoutPosition();
272 if (adapterPosition == count)
273 b.accountRowAccAmounts.setImeOptions(EditorInfo.IME_ACTION_DONE);
275 b.accountRowAccAmounts.setImeOptions(EditorInfo.IME_ACTION_NEXT);
278 Data.currencyGap.observe(activity,
279 hasGap -> updateCurrencyPositionAndPadding(Data.currencySymbolPosition.getValue(),
282 Data.currencySymbolPosition.observe(activity,
283 position -> updateCurrencyPositionAndPadding(position,
284 Data.currencyGap.getValue()));
286 adapter.model.getShowCurrency()
287 .observe(activity, showCurrency -> {
289 b.currency.setVisibility(View.VISIBLE);
290 b.currencyButton.setVisibility(View.VISIBLE);
291 b.currency.setText(mProfile.getDefaultCommodity());
294 b.currency.setVisibility(View.GONE);
295 b.currencyButton.setVisibility(View.GONE);
296 b.currency.setText(null);
300 adapter.model.getShowComments()
301 .observe(activity, show -> {
302 ConstraintLayout.LayoutParams amountLayoutParams =
303 (ConstraintLayout.LayoutParams) b.amountLayout.getLayoutParams();
304 ConstraintLayout.LayoutParams accountParams =
305 (ConstraintLayout.LayoutParams) b.accountRowAccName.getLayoutParams();
308 accountParams.endToStart = ConstraintLayout.LayoutParams.UNSET;
309 accountParams.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
311 amountLayoutParams.topToTop = ConstraintLayout.LayoutParams.UNSET;
312 amountLayoutParams.topToBottom = b.accountRowAccName.getId();
314 b.commentLayout.setVisibility(View.VISIBLE);
317 accountParams.endToStart = b.amountLayout.getId();
318 accountParams.endToEnd = ConstraintLayout.LayoutParams.UNSET;
320 amountLayoutParams.topToBottom = ConstraintLayout.LayoutParams.UNSET;
321 amountLayoutParams.topToTop = ConstraintLayout.LayoutParams.PARENT_ID;
323 b.commentLayout.setVisibility(View.GONE);
326 b.accountRowAccName.setLayoutParams(accountParams);
327 b.amountLayout.setLayoutParams(amountLayoutParams);
329 b.transactionCommentLayout.setVisibility(show ? View.VISIBLE : View.GONE);
332 public void checkAmountValid(String s) {
333 boolean valid = true;
335 if (s.length() > 0) {
336 float ignored = Float.parseFloat(s.replace(decimalSeparator, decimalDot));
339 catch (NumberFormatException ex) {
343 displayAmountValidity(valid);
345 private void displayAmountValidity(boolean valid) {
346 b.accountRowAccAmounts.setCompoundDrawablesRelativeWithIntrinsicBounds(
347 valid ? 0 : R.drawable.ic_error_outline_black_24dp, 0, 0, 0);
348 b.accountRowAccAmounts.setMinEms(valid ? 4 : 5);
350 private void monitorComment(EditText editText) {
351 editText.addTextChangedListener(new TextWatcher() {
353 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
356 public void onTextChanged(CharSequence s, int start, int before, int count) {
359 public void afterTextChanged(Editable s) {
360 // debug("input", "text changed");
364 Logger.debug("textWatcher", "calling syncData()");
366 Logger.debug("textWatcher",
367 "syncData() returned, checking if transaction is submittable");
368 styleComment(editText, s.toString());
369 Logger.debug("textWatcher", "done");
373 private void commentFocusChanged(TextView textView, boolean hasFocus) {
374 @ColorInt int textColor;
375 textColor = b.dummyText.getTextColors()
378 textView.setTypeface(null, Typeface.NORMAL);
379 textView.setHint(R.string.transaction_account_comment_hint);
382 int alpha = (textColor >> 24 & 0xff);
383 alpha = 3 * alpha / 4;
384 textColor = (alpha << 24) | (0x00ffffff & textColor);
385 textView.setTypeface(null, Typeface.ITALIC);
386 textView.setHint("");
387 if (TextUtils.isEmpty(textView.getText())) {
388 textView.setVisibility(View.INVISIBLE);
391 textView.setTextColor(textColor);
394 private void updateCurrencyPositionAndPadding(Currency.Position position, boolean hasGap) {
395 ConstraintLayout.LayoutParams amountLP =
396 (ConstraintLayout.LayoutParams) b.accountRowAccAmounts.getLayoutParams();
397 ConstraintLayout.LayoutParams currencyLP =
398 (ConstraintLayout.LayoutParams) b.currency.getLayoutParams();
400 if (position == Currency.Position.before) {
401 currencyLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
402 currencyLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
404 amountLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
405 amountLP.endToStart = ConstraintLayout.LayoutParams.UNSET;
406 amountLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
407 amountLP.startToEnd = b.currency.getId();
409 b.currency.setGravity(Gravity.END);
412 currencyLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
413 currencyLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
415 amountLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
416 amountLP.startToEnd = ConstraintLayout.LayoutParams.UNSET;
417 amountLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
418 amountLP.endToStart = b.currency.getId();
420 b.currency.setGravity(Gravity.START);
423 amountLP.resolveLayoutDirection(b.accountRowAccAmounts.getLayoutDirection());
424 currencyLP.resolveLayoutDirection(b.currency.getLayoutDirection());
426 b.accountRowAccAmounts.setLayoutParams(amountLP);
427 b.currency.setLayoutParams(currencyLP);
429 // distance between the amount and the currency symbol
430 int gapSize = DimensionUtils.sp2px(b.currency.getContext(), 5);
432 if (position == Currency.Position.before) {
433 b.currency.setPaddingRelative(0, 0, hasGap ? gapSize : 0, 0);
436 b.currency.setPaddingRelative(hasGap ? gapSize : 0, 0, 0, 0);
439 private void setCurrencyString(String currency) {
440 @ColorInt int textColor = b.dummyText.getTextColors()
442 if ((currency == null) || currency.isEmpty()) {
443 b.currency.setText(R.string.currency_symbol);
444 int alpha = (textColor >> 24) & 0xff;
445 alpha = alpha * 3 / 4;
446 b.currency.setTextColor((alpha << 24) | (0x00ffffff & textColor));
449 b.currency.setText(currency);
450 b.currency.setTextColor(textColor);
453 private void setCurrency(Currency currency) {
454 setCurrencyString((currency == null) ? null : currency.getName());
456 private void setEditable(Boolean editable) {
457 b.newTransactionDate.setEnabled(editable);
458 b.newTransactionDescription.setEnabled(editable);
459 b.accountRowAccName.setEnabled(editable);
460 b.accountRowAccAmounts.setEnabled(editable);
462 private void beginUpdates() {
464 throw new RuntimeException("Already in update mode");
467 private void endUpdates() {
469 throw new RuntimeException("Not in update mode");
475 * Stores the data from the UI elements into the model item
476 * Returns true if there were changes made that suggest transaction has to be
477 * checked for being submittable
479 private boolean syncData() {
481 Logger.debug("new-trans", "skipping syncData() loop");
485 NewTransactionModel.Item item = getItem();
490 if (item instanceof NewTransactionModel.TransactionHead) {
491 NewTransactionModel.TransactionHead head = item.toTransactionHead();
493 head.setDate(String.valueOf(b.newTransactionDate.getText()));
494 head.setDescription(String.valueOf(b.newTransactionDescription.getText()));
495 head.setComment(String.valueOf(b.transactionComment.getText()));
497 else if (item instanceof NewTransactionModel.TransactionAccount) {
498 NewTransactionModel.TransactionAccount acc = item.toTransactionAccount();
499 acc.setAccountName(String.valueOf(b.accountRowAccName.getText()));
501 acc.setComment(String.valueOf(b.comment.getText()));
503 String amount = String.valueOf(b.accountRowAccAmounts.getText());
504 amount = amount.trim();
506 if (amount.isEmpty()) {
508 acc.setAmountValid(true);
512 amount = amount.replace(decimalSeparator, decimalDot);
513 acc.setAmount(Float.parseFloat(amount));
514 acc.setAmountValid(true);
516 catch (NumberFormatException e) {
517 Logger.debug("new-trans", String.format(
518 "assuming amount is not set due to number format exception. " +
519 "input was '%s'", amount));
520 acc.setAmountValid(false);
522 final String curr = String.valueOf(b.currency.getText());
523 if (curr.equals(b.currency.getContext()
525 .getString(R.string.currency_symbol)) ||
527 acc.setCurrency(null);
529 acc.setCurrency(curr);
533 throw new RuntimeException("Should not happen");
538 catch (ParseException e) {
539 throw new RuntimeException("Should not happen", e);
545 private void pickTransactionDate() {
546 DatePickerFragment picker = new DatePickerFragment();
547 picker.setFutureDates(mProfile.getFutureDates());
548 picker.setOnDatePickedListener(this);
549 picker.setCurrentDateFromText(b.newTransactionDate.getText());
550 picker.show(((NewTransactionActivity) b.getRoot()
551 .getContext()).getSupportFragmentManager(), null);
556 * @param item updates the UI elements with the data from the model item
558 @SuppressLint("DefaultLocale")
559 public void bind(@NonNull NewTransactionModel.Item item) {
564 if (item instanceof NewTransactionModel.TransactionHead) {
565 NewTransactionModel.TransactionHead head = item.toTransactionHead();
566 b.newTransactionDate.setText(head.getFormattedDate());
568 // avoid triggering completion pop-up
569 SimpleCursorAdapter a =
570 (SimpleCursorAdapter) b.newTransactionDescription.getAdapter();
572 b.newTransactionDescription.setAdapter(null);
573 b.newTransactionDescription.setText(head.getDescription());
576 b.newTransactionDescription.setAdapter(a);
579 b.transactionComment.setText(head.getComment());
580 //styleComment(b.transactionComment, head.getComment());
582 b.ntrData.setVisibility(View.VISIBLE);
583 b.ntrAccount.setVisibility(View.GONE);
584 b.ntrPadding.setVisibility(View.GONE);
587 else if (item instanceof NewTransactionModel.TransactionAccount) {
588 NewTransactionModel.TransactionAccount acc = item.toTransactionAccount();
590 // avoid triggering completion pop-up
591 AccountAutocompleteAdapter a =
592 (AccountAutocompleteAdapter) b.accountRowAccName.getAdapter();
594 b.accountRowAccName.setAdapter(null);
595 b.accountRowAccName.setText(acc.getAccountName());
598 b.accountRowAccName.setAdapter(a);
601 final String amountHint = acc.getAmountHint();
602 if (amountHint == null) {
603 b.accountRowAccAmounts.setHint(R.string.zero_amount);
606 b.accountRowAccAmounts.setHint(amountHint);
609 setCurrencyString(acc.getCurrency());
610 b.accountRowAccAmounts.setText(
611 acc.isAmountSet() ? String.format("%4.2f", acc.getAmount()) : null);
612 displayAmountValidity(true);
614 b.comment.setText(acc.getComment());
616 b.ntrData.setVisibility(View.GONE);
617 b.ntrAccount.setVisibility(View.VISIBLE);
618 b.ntrPadding.setVisibility(View.GONE);
622 throw new RuntimeException("Don't know how to handle " + item);
633 private void styleComment(EditText editText, String comment) {
634 final View focusedView = editText.findFocus();
635 editText.setTypeface(null, (focusedView == editText) ? Typeface.NORMAL : Typeface.ITALIC);
636 editText.setVisibility(
637 ((focusedView != editText) && TextUtils.isEmpty(comment)) ? View.INVISIBLE
641 public void onDatePicked(int year, int month, int day) {
642 final NewTransactionModel.TransactionHead head = getItem().toTransactionHead();
643 head.setDate(new SimpleDate(year, month + 1, day));
644 b.newTransactionDate.setText(head.getFormattedDate());
646 boolean focused = b.newTransactionDescription.requestFocus();
648 Misc.showSoftKeyboard((NewTransactionActivity) b.getRoot()
652 private NewTransactionModel.Item getItem() {
653 return Objects.requireNonNull(mAdapter.model.getItems()
655 .get(getAdapterPosition());
658 public void descriptionSelected(String description) {
659 b.accountRowAccName.setText(description);
660 b.accountRowAccAmounts.requestFocus(View.FOCUS_FORWARD);