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