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