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