]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/new_transaction/NewTransactionAccountRowItemHolder.java
fix a weird bug when an invalid amount is entered
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / ui / new_transaction / NewTransactionAccountRowItemHolder.java
1 /*
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.
8  *
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.
13  *
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/>.
16  */
17
18 package net.ktnx.mobileledger.ui.new_transaction;
19
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.TextView;
30
31 import androidx.annotation.ColorInt;
32 import androidx.annotation.NonNull;
33 import androidx.constraintlayout.widget.ConstraintLayout;
34 import androidx.recyclerview.widget.RecyclerView;
35
36 import net.ktnx.mobileledger.R;
37 import net.ktnx.mobileledger.databinding.NewTransactionAccountRowBinding;
38 import net.ktnx.mobileledger.db.AccountWithAmountsAutocompleteAdapter;
39 import net.ktnx.mobileledger.model.Currency;
40 import net.ktnx.mobileledger.model.Data;
41 import net.ktnx.mobileledger.ui.CurrencySelectorFragment;
42 import net.ktnx.mobileledger.ui.TextViewClearHelper;
43 import net.ktnx.mobileledger.utils.DimensionUtils;
44 import net.ktnx.mobileledger.utils.Logger;
45 import net.ktnx.mobileledger.utils.Misc;
46
47 import java.text.DecimalFormatSymbols;
48
49 class NewTransactionAccountRowItemHolder extends NewTransactionItemViewHolder {
50     private final String decimalDot = ".";
51     private final NewTransactionAccountRowBinding b;
52     private boolean ignoreFocusChanges = false;
53     private String decimalSeparator;
54     private boolean inUpdate = false;
55     private boolean syncingData = false;
56     NewTransactionAccountRowItemHolder(@NonNull NewTransactionAccountRowBinding b,
57                                        NewTransactionItemsAdapter adapter) {
58         super(b.getRoot());
59         this.b = b;
60         new TextViewClearHelper().attachToTextView(b.comment);
61
62         b.accountRowAccName.setNextFocusForwardId(View.NO_ID);
63         b.accountRowAccAmounts.setNextFocusForwardId(View.NO_ID); // magic!
64
65         b.accountCommentButton.setOnClickListener(v -> {
66             b.comment.setVisibility(View.VISIBLE);
67             b.comment.requestFocus();
68         });
69
70         @SuppressLint("DefaultLocale") View.OnFocusChangeListener focusMonitor = (v, hasFocus) -> {
71             final int id = v.getId();
72             if (hasFocus) {
73                 boolean wasSyncing = syncingData;
74                 syncingData = true;
75                 try {
76                     final int pos = getBindingAdapterPosition();
77                     if (id == R.id.account_row_acc_name) {
78                         adapter.noteFocusIsOnAccount(pos);
79                     }
80                     else if (id == R.id.account_row_acc_amounts) {
81                         adapter.noteFocusIsOnAmount(pos);
82                     }
83                     else if (id == R.id.comment) {
84                         adapter.noteFocusIsOnComment(pos);
85                     }
86                     else
87                         throw new IllegalStateException("Where is the focus? " + id);
88                 }
89                 finally {
90                     syncingData = wasSyncing;
91                 }
92             }
93             else {  // lost focus
94                 if (id == R.id.account_row_acc_amounts) {
95                     try {
96                         String input = String.valueOf(b.accountRowAccAmounts.getText());
97                         input = input.replace(decimalSeparator, decimalDot);
98                         final String newText = String.format("%4.2f", Float.parseFloat(input));
99                         if (!newText.equals(input)) {
100                             boolean wasSyncingData = syncingData;
101                             syncingData = true;
102                             try {
103                                 b.accountRowAccAmounts.setText(newText);
104                             }
105                             finally {
106                                 syncingData = wasSyncingData;
107                             }
108                         }
109                     }
110                     catch (NumberFormatException ex) {
111                         // ignored
112                     }
113                 }
114             }
115
116             if (id == R.id.comment) {
117                 commentFocusChanged(b.comment, hasFocus);
118             }
119         };
120
121         b.accountRowAccName.setOnFocusChangeListener(focusMonitor);
122         b.accountRowAccAmounts.setOnFocusChangeListener(focusMonitor);
123         b.comment.setOnFocusChangeListener(focusMonitor);
124
125         NewTransactionActivity activity = (NewTransactionActivity) b.getRoot()
126                                                                     .getContext();
127
128         b.accountRowAccName.setAdapter(new AccountWithAmountsAutocompleteAdapter(b.getRoot()
129                                                                                   .getContext(),
130                 mProfile));
131
132         decimalSeparator = "";
133         Data.locale.observe(activity, locale -> decimalSeparator = String.valueOf(
134                 DecimalFormatSymbols.getInstance(locale)
135                                     .getMonetaryDecimalSeparator()));
136
137         final TextWatcher tw = new TextWatcher() {
138             @Override
139             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
140             }
141
142             @Override
143             public void onTextChanged(CharSequence s, int start, int before, int count) {
144             }
145
146             @Override
147             public void afterTextChanged(Editable s) {
148 //                debug("input", "text changed");
149                 if (inUpdate)
150                     return;
151
152                 Logger.debug("textWatcher", "calling syncData()");
153                 if (syncData()) {
154                     Logger.debug("textWatcher",
155                             "syncData() returned, checking if transaction is submittable");
156                     adapter.model.checkTransactionSubmittable(null);
157                 }
158                 Logger.debug("textWatcher", "done");
159             }
160         };
161         final TextWatcher amountWatcher = new TextWatcher() {
162             @Override
163             public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
164             @Override
165             public void onTextChanged(CharSequence s, int start, int before, int count) {}
166             @Override
167             public void afterTextChanged(Editable s) {
168                 checkAmountValid(s.toString());
169
170                 if (syncData())
171                     adapter.model.checkTransactionSubmittable(null);
172             }
173         };
174         b.accountRowAccName.addTextChangedListener(tw);
175         monitorComment(b.comment);
176         b.accountRowAccAmounts.addTextChangedListener(amountWatcher);
177
178         b.currencyButton.setOnClickListener(v -> {
179             CurrencySelectorFragment cpf = new CurrencySelectorFragment();
180             cpf.showPositionAndPadding();
181             cpf.setOnCurrencySelectedListener(
182                     c -> adapter.setItemCurrency(getBindingAdapterPosition(), c));
183             cpf.show(activity.getSupportFragmentManager(), "currency-selector");
184         });
185
186         commentFocusChanged(b.comment, false);
187
188         adapter.model.getFocusInfo()
189                      .observe(activity, this::applyFocus);
190
191         Data.currencyGap.observe(activity,
192                 hasGap -> updateCurrencyPositionAndPadding(Data.currencySymbolPosition.getValue(),
193                         hasGap));
194
195         Data.currencySymbolPosition.observe(activity,
196                 position -> updateCurrencyPositionAndPadding(position,
197                         Data.currencyGap.getValue()));
198
199         adapter.model.getShowCurrency()
200                      .observe(activity, showCurrency -> {
201                          if (showCurrency) {
202                              b.currency.setVisibility(View.VISIBLE);
203                              b.currencyButton.setVisibility(View.VISIBLE);
204                              setCurrencyString(mProfile.getDefaultCommodity());
205                          }
206                          else {
207                              b.currency.setVisibility(View.GONE);
208                              b.currencyButton.setVisibility(View.GONE);
209                              setCurrencyString(null);
210                          }
211                      });
212
213         adapter.model.getShowComments()
214                      .observe(activity, show -> b.commentLayout.setVisibility(
215                              show ? View.VISIBLE : View.GONE));
216     }
217     private void applyFocus(NewTransactionModel.FocusInfo focusInfo) {
218         if (ignoreFocusChanges) {
219             Logger.debug("new-trans", "Ignoring focus change");
220             return;
221         }
222         ignoreFocusChanges = true;
223         try {
224             if (((focusInfo == null) || (focusInfo.element == null) ||
225                  focusInfo.position != getBindingAdapterPosition()))
226                 return;
227
228             final NewTransactionModel.Item item = getItem();
229             if (item == null)
230                 return;
231
232             NewTransactionModel.TransactionAccount acc = item.toTransactionAccount();
233             switch (focusInfo.element) {
234                 case Amount:
235                     b.accountRowAccAmounts.requestFocus();
236                     break;
237                 case Comment:
238                     b.comment.setVisibility(View.VISIBLE);
239                     b.comment.requestFocus();
240                     break;
241                 case Account:
242                     boolean focused = b.accountRowAccName.requestFocus();
243 //                                         b.accountRowAccName.dismissDropDown();
244                     if (focused)
245                         Misc.showSoftKeyboard((NewTransactionActivity) b.getRoot()
246                                                                         .getContext());
247                     break;
248             }
249         }
250         finally {
251             ignoreFocusChanges = false;
252         }
253     }
254     public void checkAmountValid(String s) {
255         boolean valid = true;
256         try {
257             if (s.length() > 0) {
258                 float ignored = Float.parseFloat(s.replace(decimalSeparator, decimalDot));
259             }
260         }
261         catch (NumberFormatException ex) {
262             valid = false;
263         }
264
265         displayAmountValidity(valid);
266     }
267     private void displayAmountValidity(boolean valid) {
268         b.accountRowAccAmounts.setCompoundDrawablesRelativeWithIntrinsicBounds(
269                 valid ? 0 : R.drawable.ic_error_outline_black_24dp, 0, 0, 0);
270         b.accountRowAccAmounts.setMinEms(valid ? 4 : 5);
271     }
272     private void monitorComment(EditText editText) {
273         editText.addTextChangedListener(new TextWatcher() {
274             @Override
275             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
276             }
277             @Override
278             public void onTextChanged(CharSequence s, int start, int before, int count) {
279             }
280             @Override
281             public void afterTextChanged(Editable s) {
282 //                debug("input", "text changed");
283                 if (inUpdate)
284                     return;
285
286                 Logger.debug("textWatcher", "calling syncData()");
287                 syncData();
288                 Logger.debug("textWatcher",
289                         "syncData() returned, checking if transaction is submittable");
290                 styleComment(editText, s.toString());
291                 Logger.debug("textWatcher", "done");
292             }
293         });
294     }
295     private void commentFocusChanged(TextView textView, boolean hasFocus) {
296         @ColorInt int textColor;
297         textColor = b.dummyText.getTextColors()
298                                .getDefaultColor();
299         if (hasFocus) {
300             textView.setTypeface(null, Typeface.NORMAL);
301             textView.setHint(R.string.transaction_account_comment_hint);
302         }
303         else {
304             int alpha = (textColor >> 24 & 0xff);
305             alpha = 3 * alpha / 4;
306             textColor = (alpha << 24) | (0x00ffffff & textColor);
307             textView.setTypeface(null, Typeface.ITALIC);
308             textView.setHint("");
309             if (TextUtils.isEmpty(textView.getText())) {
310                 textView.setVisibility(View.INVISIBLE);
311             }
312         }
313         textView.setTextColor(textColor);
314
315     }
316     private void updateCurrencyPositionAndPadding(Currency.Position position, boolean hasGap) {
317         ConstraintLayout.LayoutParams amountLP =
318                 (ConstraintLayout.LayoutParams) b.accountRowAccAmounts.getLayoutParams();
319         ConstraintLayout.LayoutParams currencyLP =
320                 (ConstraintLayout.LayoutParams) b.currency.getLayoutParams();
321
322         if (position == Currency.Position.before) {
323             currencyLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
324             currencyLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
325
326             amountLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
327             amountLP.endToStart = ConstraintLayout.LayoutParams.UNSET;
328             amountLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
329             amountLP.startToEnd = b.currency.getId();
330
331             b.currency.setGravity(Gravity.END);
332         }
333         else {
334             currencyLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
335             currencyLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
336
337             amountLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
338             amountLP.startToEnd = ConstraintLayout.LayoutParams.UNSET;
339             amountLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
340             amountLP.endToStart = b.currency.getId();
341
342             b.currency.setGravity(Gravity.START);
343         }
344
345         amountLP.resolveLayoutDirection(b.accountRowAccAmounts.getLayoutDirection());
346         currencyLP.resolveLayoutDirection(b.currency.getLayoutDirection());
347
348         b.accountRowAccAmounts.setLayoutParams(amountLP);
349         b.currency.setLayoutParams(currencyLP);
350
351         // distance between the amount and the currency symbol
352         int gapSize = DimensionUtils.sp2px(b.currency.getContext(), 5);
353
354         if (position == Currency.Position.before) {
355             b.currency.setPaddingRelative(0, 0, hasGap ? gapSize : 0, 0);
356         }
357         else {
358             b.currency.setPaddingRelative(hasGap ? gapSize : 0, 0, 0, 0);
359         }
360     }
361     private void setCurrencyString(String currency) {
362         @ColorInt int textColor = b.dummyText.getTextColors()
363                                              .getDefaultColor();
364         if (TextUtils.isEmpty(currency)) {
365             b.currency.setText(R.string.currency_symbol);
366             int alpha = (textColor >> 24) & 0xff;
367             alpha = alpha * 3 / 4;
368             b.currency.setTextColor((alpha << 24) | (0x00ffffff & textColor));
369         }
370         else {
371             b.currency.setText(currency);
372             b.currency.setTextColor(textColor);
373         }
374     }
375     private void setCurrency(Currency currency) {
376         setCurrencyString((currency == null) ? null : currency.getName());
377     }
378     private void setEditable(Boolean editable) {
379         b.accountRowAccName.setEnabled(editable);
380         b.accountRowAccAmounts.setEnabled(editable);
381     }
382     private void beginUpdates() {
383         if (inUpdate)
384             throw new RuntimeException("Already in update mode");
385         inUpdate = true;
386     }
387     private void endUpdates() {
388         if (!inUpdate)
389             throw new RuntimeException("Not in update mode");
390         inUpdate = false;
391     }
392     /**
393      * syncData()
394      * <p>
395      * Stores the data from the UI elements into the model item
396      * Returns true if there were changes made that suggest transaction has to be
397      * checked for being submittable
398      */
399     private boolean syncData() {
400         if (syncingData) {
401             Logger.debug("new-trans", "skipping syncData() loop");
402             return false;
403         }
404
405         if (getBindingAdapterPosition() == RecyclerView.NO_POSITION) {
406             // probably the row was swiped out
407             Logger.debug("new-trans", "Ignoring request to syncData(): adapter position negative");
408             return false;
409         }
410
411         final NewTransactionModel.Item item = getItem();
412         if (item == null)
413             return false;
414
415         syncingData = true;
416
417         boolean significantChange = false;
418
419         try {
420             NewTransactionModel.TransactionAccount acc = item.toTransactionAccount();
421
422             // having account name is important
423             final Editable incomingAccountName = b.accountRowAccName.getText();
424             if (TextUtils.isEmpty(acc.getAccountName()) != TextUtils.isEmpty(incomingAccountName))
425                 significantChange = true;
426
427             acc.setAccountName(String.valueOf(incomingAccountName));
428             final int accNameSelEnd = b.accountRowAccName.getSelectionEnd();
429             final int accNameSelStart = b.accountRowAccName.getSelectionStart();
430             acc.setAccountNameCursorPosition(accNameSelEnd);
431
432             acc.setComment(String.valueOf(b.comment.getText()));
433
434             String amount = String.valueOf(b.accountRowAccAmounts.getText());
435             amount = amount.trim();
436
437             if (amount.isEmpty()) {
438                 if (acc.isAmountSet())
439                     significantChange = true;
440                 acc.resetAmount();
441                 acc.setAmountValid(true);
442             }
443             else {
444                 try {
445                     amount = amount.replace(decimalSeparator, decimalDot);
446                     final float parsedAmount = Float.parseFloat(amount);
447                     if (!acc.isAmountSet() || !Misc.equalFloats(parsedAmount, acc.getAmount()))
448                         significantChange = true;
449                     acc.setAmount(parsedAmount);
450                     acc.setAmountValid(true);
451                 }
452                 catch (NumberFormatException e) {
453                     Logger.debug("new-trans", String.format(
454                             "assuming amount is not set due to number format exception. " +
455                             "input was '%s'", amount));
456                     if (acc.isAmountValid())
457                         significantChange = true;
458                     acc.resetAmount();
459                     acc.setAmountValid(false);
460                 }
461                 final String curr = String.valueOf(b.currency.getText());
462                 final String currValue;
463                 if (curr.equals(b.currency.getContext()
464                                           .getResources()
465                                           .getString(R.string.currency_symbol)) || curr.isEmpty())
466                     currValue = null;
467                 else
468                     currValue = curr;
469
470                 if (!significantChange && !Misc.equalStrings(acc.getCurrency(), currValue))
471                     significantChange = true;
472                 acc.setCurrency(currValue);
473             }
474
475             return significantChange;
476         }
477         finally {
478             syncingData = false;
479         }
480     }
481     /**
482      * bind
483      *
484      * @param item updates the UI elements with the data from the model item
485      */
486     @SuppressLint("DefaultLocale")
487     public void bind(@NonNull NewTransactionModel.Item item) {
488         beginUpdates();
489         try {
490             syncingData = true;
491             try {
492                 NewTransactionModel.TransactionAccount acc = item.toTransactionAccount();
493
494                 final String incomingAccountName = acc.getAccountName();
495                 final String presentAccountName = String.valueOf(b.accountRowAccName.getText());
496                 if (!Misc.equalStrings(incomingAccountName, presentAccountName)) {
497                     Logger.debug("bind",
498                             String.format("Setting account name from '%s' to '%s' (| @ %d)",
499                                     presentAccountName, incomingAccountName,
500                                     acc.getAccountNameCursorPosition()));
501                     // avoid triggering completion pop-up
502                     AccountWithAmountsAutocompleteAdapter a =
503                             (AccountWithAmountsAutocompleteAdapter) b.accountRowAccName.getAdapter();
504                     try {
505                         b.accountRowAccName.setAdapter(null);
506                         b.accountRowAccName.setText(incomingAccountName);
507                         b.accountRowAccName.setSelection(acc.getAccountNameCursorPosition());
508                     }
509                     finally {
510                         b.accountRowAccName.setAdapter(a);
511                     }
512                 }
513
514                 final String amountHint = acc.getAmountHint();
515                 if (amountHint == null) {
516                     b.accountRowAccAmounts.setHint(R.string.zero_amount);
517                 }
518                 else {
519                     b.accountRowAccAmounts.setHint(amountHint);
520                 }
521
522                 b.accountRowAccAmounts.setImeOptions(
523                         acc.isLast() ? EditorInfo.IME_ACTION_DONE : EditorInfo.IME_ACTION_NEXT);
524
525                 setCurrencyString(acc.getCurrency());
526                 b.accountRowAccAmounts.setText(
527                         acc.isAmountSet() ? String.format("%4.2f", acc.getAmount()) : null);
528                 displayAmountValidity(true);
529
530                 final String comment = acc.getComment();
531                 b.comment.setText(comment);
532                 styleComment(b.comment, comment);
533
534                 setEditable(true);
535
536                 NewTransactionItemsAdapter adapter =
537                         (NewTransactionItemsAdapter) getBindingAdapter();
538                 if (adapter != null)
539                     applyFocus(adapter.model.getFocusInfo()
540                                             .getValue());
541             }
542             finally {
543                 syncingData = false;
544             }
545         }
546         finally {
547             endUpdates();
548         }
549     }
550     private void styleComment(EditText editText, String comment) {
551         final View focusedView = editText.findFocus();
552         editText.setTypeface(null, (focusedView == editText) ? Typeface.NORMAL : Typeface.ITALIC);
553         editText.setVisibility(
554                 ((focusedView != editText) && TextUtils.isEmpty(comment)) ? View.INVISIBLE
555                                                                           : View.VISIBLE);
556     }
557 }