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;
268 Data.currencyGap.observe(activity,
269 hasGap -> updateCurrencyPositionAndPadding(Data.currencySymbolPosition.getValue(),
272 Data.currencySymbolPosition.observe(activity,
273 position -> updateCurrencyPositionAndPadding(position,
274 Data.currencyGap.getValue()));
276 adapter.model.getShowCurrency()
277 .observe(activity, showCurrency -> {
279 b.currency.setVisibility(View.VISIBLE);
280 b.currencyButton.setVisibility(View.VISIBLE);
281 b.currency.setText(mProfile.getDefaultCommodity());
284 b.currency.setVisibility(View.GONE);
285 b.currencyButton.setVisibility(View.GONE);
286 b.currency.setText(null);
290 adapter.model.getShowComments()
291 .observe(activity, show -> {
292 ConstraintLayout.LayoutParams amountLayoutParams =
293 (ConstraintLayout.LayoutParams) b.amountLayout.getLayoutParams();
294 ConstraintLayout.LayoutParams accountParams =
295 (ConstraintLayout.LayoutParams) b.accountRowAccName.getLayoutParams();
298 accountParams.endToStart = ConstraintLayout.LayoutParams.UNSET;
299 accountParams.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
301 amountLayoutParams.topToTop = ConstraintLayout.LayoutParams.UNSET;
302 amountLayoutParams.topToBottom = b.accountRowAccName.getId();
304 b.commentLayout.setVisibility(View.VISIBLE);
307 accountParams.endToStart = b.amountLayout.getId();
308 accountParams.endToEnd = ConstraintLayout.LayoutParams.UNSET;
310 amountLayoutParams.topToBottom = ConstraintLayout.LayoutParams.UNSET;
311 amountLayoutParams.topToTop = ConstraintLayout.LayoutParams.PARENT_ID;
313 b.commentLayout.setVisibility(View.GONE);
316 b.accountRowAccName.setLayoutParams(accountParams);
317 b.amountLayout.setLayoutParams(amountLayoutParams);
319 b.transactionCommentLayout.setVisibility(show ? View.VISIBLE : View.GONE);
322 public void checkAmountValid(String s) {
323 boolean valid = true;
325 if (s.length() > 0) {
326 float ignored = Float.parseFloat(s.replace(decimalSeparator, decimalDot));
329 catch (NumberFormatException ex) {
333 displayAmountValidity(valid);
335 private void displayAmountValidity(boolean valid) {
336 b.accountRowAccAmounts.setCompoundDrawablesRelativeWithIntrinsicBounds(
337 valid ? 0 : R.drawable.ic_error_outline_black_24dp, 0, 0, 0);
338 b.accountRowAccAmounts.setMinEms(valid ? 4 : 5);
340 private void monitorComment(EditText editText) {
341 editText.addTextChangedListener(new TextWatcher() {
343 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
346 public void onTextChanged(CharSequence s, int start, int before, int count) {
349 public void afterTextChanged(Editable s) {
350 // debug("input", "text changed");
354 Logger.debug("textWatcher", "calling syncData()");
356 Logger.debug("textWatcher",
357 "syncData() returned, checking if transaction is submittable");
358 styleComment(editText, s.toString());
359 Logger.debug("textWatcher", "done");
363 private void commentFocusChanged(TextView textView, boolean hasFocus) {
364 @ColorInt int textColor;
365 textColor = b.dummyText.getTextColors()
368 textView.setTypeface(null, Typeface.NORMAL);
369 textView.setHint(R.string.transaction_account_comment_hint);
372 int alpha = (textColor >> 24 & 0xff);
373 alpha = 3 * alpha / 4;
374 textColor = (alpha << 24) | (0x00ffffff & textColor);
375 textView.setTypeface(null, Typeface.ITALIC);
376 textView.setHint("");
377 if (TextUtils.isEmpty(textView.getText())) {
378 textView.setVisibility(View.INVISIBLE);
381 textView.setTextColor(textColor);
384 private void updateCurrencyPositionAndPadding(Currency.Position position, boolean hasGap) {
385 ConstraintLayout.LayoutParams amountLP =
386 (ConstraintLayout.LayoutParams) b.accountRowAccAmounts.getLayoutParams();
387 ConstraintLayout.LayoutParams currencyLP =
388 (ConstraintLayout.LayoutParams) b.currency.getLayoutParams();
390 if (position == Currency.Position.before) {
391 currencyLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
392 currencyLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
394 amountLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
395 amountLP.endToStart = ConstraintLayout.LayoutParams.UNSET;
396 amountLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
397 amountLP.startToEnd = b.currency.getId();
399 b.currency.setGravity(Gravity.END);
402 currencyLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
403 currencyLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
405 amountLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
406 amountLP.startToEnd = ConstraintLayout.LayoutParams.UNSET;
407 amountLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
408 amountLP.endToStart = b.currency.getId();
410 b.currency.setGravity(Gravity.START);
413 amountLP.resolveLayoutDirection(b.accountRowAccAmounts.getLayoutDirection());
414 currencyLP.resolveLayoutDirection(b.currency.getLayoutDirection());
416 b.accountRowAccAmounts.setLayoutParams(amountLP);
417 b.currency.setLayoutParams(currencyLP);
419 // distance between the amount and the currency symbol
420 int gapSize = DimensionUtils.sp2px(b.currency.getContext(), 5);
422 if (position == Currency.Position.before) {
423 b.currency.setPaddingRelative(0, 0, hasGap ? gapSize : 0, 0);
426 b.currency.setPaddingRelative(hasGap ? gapSize : 0, 0, 0, 0);
429 private void setCurrencyString(String currency) {
430 @ColorInt int textColor = b.dummyText.getTextColors()
432 if ((currency == null) || currency.isEmpty()) {
433 b.currency.setText(R.string.currency_symbol);
434 int alpha = (textColor >> 24) & 0xff;
435 alpha = alpha * 3 / 4;
436 b.currency.setTextColor((alpha << 24) | (0x00ffffff & textColor));
439 b.currency.setText(currency);
440 b.currency.setTextColor(textColor);
443 private void setCurrency(Currency currency) {
444 setCurrencyString((currency == null) ? null : currency.getName());
446 private void setEditable(Boolean editable) {
447 b.newTransactionDate.setEnabled(editable);
448 b.newTransactionDescription.setEnabled(editable);
449 b.accountRowAccName.setEnabled(editable);
450 b.accountRowAccAmounts.setEnabled(editable);
452 private void beginUpdates() {
454 throw new RuntimeException("Already in update mode");
457 private void endUpdates() {
459 throw new RuntimeException("Not in update mode");
465 * Stores the data from the UI elements into the model item
466 * Returns true if there were changes made that suggest transaction has to be
467 * checked for being submittable
469 private boolean syncData() {
471 Logger.debug("new-trans", "skipping syncData() loop");
475 NewTransactionModel.Item item = getItem();
480 if (item instanceof NewTransactionModel.TransactionHead) {
481 NewTransactionModel.TransactionHead head = item.toTransactionHead();
483 head.setDate(String.valueOf(b.newTransactionDate.getText()));
484 head.setDescription(String.valueOf(b.newTransactionDescription.getText()));
485 head.setComment(String.valueOf(b.transactionComment.getText()));
487 else if (item instanceof NewTransactionModel.TransactionAccount) {
488 NewTransactionModel.TransactionAccount acc = item.toTransactionAccount();
489 acc.setAccountName(String.valueOf(b.accountRowAccName.getText()));
491 acc.setComment(String.valueOf(b.comment.getText()));
493 String amount = String.valueOf(b.accountRowAccAmounts.getText());
494 amount = amount.trim();
496 if (amount.isEmpty()) {
498 acc.setAmountValid(true);
502 amount = amount.replace(decimalSeparator, decimalDot);
503 acc.setAmount(Float.parseFloat(amount));
504 acc.setAmountValid(true);
506 catch (NumberFormatException e) {
507 Logger.debug("new-trans", String.format(
508 "assuming amount is not set due to number format exception. " +
509 "input was '%s'", amount));
510 acc.setAmountValid(false);
512 final String curr = String.valueOf(b.currency.getText());
513 if (curr.equals(b.currency.getContext()
515 .getString(R.string.currency_symbol)) ||
517 acc.setCurrency(null);
519 acc.setCurrency(curr);
523 throw new RuntimeException("Should not happen");
528 catch (ParseException e) {
529 throw new RuntimeException("Should not happen", e);
535 private void pickTransactionDate() {
536 DatePickerFragment picker = new DatePickerFragment();
537 picker.setFutureDates(mProfile.getFutureDates());
538 picker.setOnDatePickedListener(this);
539 picker.setCurrentDateFromText(b.newTransactionDate.getText());
540 picker.show(((NewTransactionActivity) b.getRoot()
541 .getContext()).getSupportFragmentManager(), null);
546 * @param item updates the UI elements with the data from the model item
548 @SuppressLint("DefaultLocale")
549 public void bind(@NonNull NewTransactionModel.Item item) {
554 if (item instanceof NewTransactionModel.TransactionHead) {
555 NewTransactionModel.TransactionHead head = item.toTransactionHead();
556 b.newTransactionDate.setText(head.getFormattedDate());
558 // avoid triggering completion pop-up
559 SimpleCursorAdapter a =
560 (SimpleCursorAdapter) b.newTransactionDescription.getAdapter();
562 b.newTransactionDescription.setAdapter(null);
563 b.newTransactionDescription.setText(head.getDescription());
566 b.newTransactionDescription.setAdapter(a);
569 b.transactionComment.setText(head.getComment());
570 //styleComment(b.transactionComment, head.getComment());
572 b.ntrData.setVisibility(View.VISIBLE);
573 b.ntrAccount.setVisibility(View.GONE);
574 b.ntrPadding.setVisibility(View.GONE);
577 else if (item instanceof NewTransactionModel.TransactionAccount) {
578 NewTransactionModel.TransactionAccount acc = item.toTransactionAccount();
580 // avoid triggering completion pop-up
581 AccountAutocompleteAdapter a =
582 (AccountAutocompleteAdapter) b.accountRowAccName.getAdapter();
584 b.accountRowAccName.setAdapter(null);
585 b.accountRowAccName.setText(acc.getAccountName());
588 b.accountRowAccName.setAdapter(a);
591 final String amountHint = acc.getAmountHint();
592 if (amountHint == null) {
593 b.accountRowAccAmounts.setHint(R.string.zero_amount);
596 b.accountRowAccAmounts.setHint(amountHint);
599 b.accountRowAccAmounts.setImeOptions(
600 acc.isLast() ? EditorInfo.IME_ACTION_DONE : EditorInfo.IME_ACTION_NEXT);
602 setCurrencyString(acc.getCurrency());
603 b.accountRowAccAmounts.setText(
604 acc.isAmountSet() ? String.format("%4.2f", acc.getAmount()) : null);
605 displayAmountValidity(true);
607 b.comment.setText(acc.getComment());
609 b.ntrData.setVisibility(View.GONE);
610 b.ntrAccount.setVisibility(View.VISIBLE);
611 b.ntrPadding.setVisibility(View.GONE);
616 throw new RuntimeException("Don't know how to handle " + item);
627 private void styleComment(EditText editText, String comment) {
628 final View focusedView = editText.findFocus();
629 editText.setTypeface(null, (focusedView == editText) ? Typeface.NORMAL : Typeface.ITALIC);
630 editText.setVisibility(
631 ((focusedView != editText) && TextUtils.isEmpty(comment)) ? View.INVISIBLE
635 public void onDatePicked(int year, int month, int day) {
636 final NewTransactionModel.TransactionHead head = getItem().toTransactionHead();
637 head.setDate(new SimpleDate(year, month + 1, day));
638 b.newTransactionDate.setText(head.getFormattedDate());
640 boolean focused = b.newTransactionDescription.requestFocus();
642 Misc.showSoftKeyboard((NewTransactionActivity) b.getRoot()
646 private NewTransactionModel.Item getItem() {
647 return Objects.requireNonNull(mAdapter.model.getItems()
649 .get(getAdapterPosition());
652 public void descriptionSelected(String description) {
653 b.accountRowAccName.setText(description);
654 b.accountRowAccAmounts.requestFocus(View.FOCUS_FORWARD);