]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/new_transaction/NewTransactionAccountRowItemHolder.java
5e930569e1afac281593d7a7d0d5cd51151b87e2
[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     //TODO multiple amounts with different currencies per posting?
57     NewTransactionAccountRowItemHolder(@NonNull NewTransactionAccountRowBinding b,
58                                        NewTransactionItemsAdapter adapter) {
59         super(b.getRoot(), adapter);
60         this.b = b;
61         new TextViewClearHelper().attachToTextView(b.comment);
62
63         b.accountRowAccName.setNextFocusForwardId(View.NO_ID);
64         b.accountRowAccAmounts.setNextFocusForwardId(View.NO_ID); // magic!
65
66         b.accountCommentButton.setOnClickListener(v -> {
67             b.comment.setVisibility(View.VISIBLE);
68             b.comment.requestFocus();
69         });
70
71         @SuppressLint("DefaultLocale") View.OnFocusChangeListener focusMonitor = (v, hasFocus) -> {
72             final int id = v.getId();
73             if (hasFocus) {
74                 boolean wasSyncing = syncingData;
75                 syncingData = true;
76                 try {
77                     final int pos = getBindingAdapterPosition();
78                     if (id == R.id.account_row_acc_name) {
79                         adapter.noteFocusIsOnAccount(pos);
80                     }
81                     else if (id == R.id.account_row_acc_amounts) {
82                         adapter.noteFocusIsOnAmount(pos);
83                     }
84                     else if (id == R.id.comment) {
85                         adapter.noteFocusIsOnComment(pos);
86                     }
87                     else
88                         throw new IllegalStateException("Where is the focus? " + id);
89                 }
90                 finally {
91                     syncingData = wasSyncing;
92                 }
93             }
94             else {  // lost focus
95                 if (id == R.id.account_row_acc_amounts) {
96                     try {
97                         String input = String.valueOf(b.accountRowAccAmounts.getText());
98                         input = input.replace(decimalSeparator, decimalDot);
99                         final String newText = String.format("%4.2f", Float.parseFloat(input));
100                         if (!newText.equals(input)) {
101                             boolean wasSyncingData = syncingData;
102                             syncingData = true;
103                             try {
104                                 b.accountRowAccAmounts.setText(newText);
105                             }
106                             finally {
107                                 syncingData = wasSyncingData;
108                             }
109                         }
110                     }
111                     catch (NumberFormatException ex) {
112                         // ignored
113                     }
114                 }
115             }
116
117             if (id == R.id.comment) {
118                 commentFocusChanged(b.comment, hasFocus);
119             }
120         };
121
122         b.accountRowAccName.setOnFocusChangeListener(focusMonitor);
123         b.accountRowAccAmounts.setOnFocusChangeListener(focusMonitor);
124         b.comment.setOnFocusChangeListener(focusMonitor);
125
126         NewTransactionActivity activity = (NewTransactionActivity) b.getRoot()
127                                                                     .getContext();
128
129         b.accountRowAccName.setAdapter(new AccountAutocompleteAdapter(b.getRoot()
130                                                                        .getContext(), 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             NewTransactionModel.TransactionAccount acc = getItem().toTransactionAccount();
229             switch (focusInfo.element) {
230                 case Amount:
231                     b.accountRowAccAmounts.requestFocus();
232                     break;
233                 case Comment:
234                     b.comment.setVisibility(View.VISIBLE);
235                     b.comment.requestFocus();
236                     break;
237                 case Account:
238                     boolean focused = b.accountRowAccName.requestFocus();
239 //                                         b.accountRowAccName.dismissDropDown();
240                     if (focused)
241                         Misc.showSoftKeyboard((NewTransactionActivity) b.getRoot()
242                                                                         .getContext());
243                     break;
244             }
245         }
246         finally {
247             ignoreFocusChanges = false;
248         }
249     }
250     public void checkAmountValid(String s) {
251         boolean valid = true;
252         try {
253             if (s.length() > 0) {
254                 float ignored = Float.parseFloat(s.replace(decimalSeparator, decimalDot));
255             }
256         }
257         catch (NumberFormatException ex) {
258             valid = false;
259         }
260
261         displayAmountValidity(valid);
262     }
263     private void displayAmountValidity(boolean valid) {
264         b.accountRowAccAmounts.setCompoundDrawablesRelativeWithIntrinsicBounds(
265                 valid ? 0 : R.drawable.ic_error_outline_black_24dp, 0, 0, 0);
266         b.accountRowAccAmounts.setMinEms(valid ? 4 : 5);
267     }
268     private void monitorComment(EditText editText) {
269         editText.addTextChangedListener(new TextWatcher() {
270             @Override
271             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
272             }
273             @Override
274             public void onTextChanged(CharSequence s, int start, int before, int count) {
275             }
276             @Override
277             public void afterTextChanged(Editable s) {
278 //                debug("input", "text changed");
279                 if (inUpdate)
280                     return;
281
282                 Logger.debug("textWatcher", "calling syncData()");
283                 syncData();
284                 Logger.debug("textWatcher",
285                         "syncData() returned, checking if transaction is submittable");
286                 styleComment(editText, s.toString());
287                 Logger.debug("textWatcher", "done");
288             }
289         });
290     }
291     private void commentFocusChanged(TextView textView, boolean hasFocus) {
292         @ColorInt int textColor;
293         textColor = b.dummyText.getTextColors()
294                                .getDefaultColor();
295         if (hasFocus) {
296             textView.setTypeface(null, Typeface.NORMAL);
297             textView.setHint(R.string.transaction_account_comment_hint);
298         }
299         else {
300             int alpha = (textColor >> 24 & 0xff);
301             alpha = 3 * alpha / 4;
302             textColor = (alpha << 24) | (0x00ffffff & textColor);
303             textView.setTypeface(null, Typeface.ITALIC);
304             textView.setHint("");
305             if (TextUtils.isEmpty(textView.getText())) {
306                 textView.setVisibility(View.INVISIBLE);
307             }
308         }
309         textView.setTextColor(textColor);
310
311     }
312     private void updateCurrencyPositionAndPadding(Currency.Position position, boolean hasGap) {
313         ConstraintLayout.LayoutParams amountLP =
314                 (ConstraintLayout.LayoutParams) b.accountRowAccAmounts.getLayoutParams();
315         ConstraintLayout.LayoutParams currencyLP =
316                 (ConstraintLayout.LayoutParams) b.currency.getLayoutParams();
317
318         if (position == Currency.Position.before) {
319             currencyLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
320             currencyLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
321
322             amountLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
323             amountLP.endToStart = ConstraintLayout.LayoutParams.UNSET;
324             amountLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
325             amountLP.startToEnd = b.currency.getId();
326
327             b.currency.setGravity(Gravity.END);
328         }
329         else {
330             currencyLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
331             currencyLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
332
333             amountLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
334             amountLP.startToEnd = ConstraintLayout.LayoutParams.UNSET;
335             amountLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
336             amountLP.endToStart = b.currency.getId();
337
338             b.currency.setGravity(Gravity.START);
339         }
340
341         amountLP.resolveLayoutDirection(b.accountRowAccAmounts.getLayoutDirection());
342         currencyLP.resolveLayoutDirection(b.currency.getLayoutDirection());
343
344         b.accountRowAccAmounts.setLayoutParams(amountLP);
345         b.currency.setLayoutParams(currencyLP);
346
347         // distance between the amount and the currency symbol
348         int gapSize = DimensionUtils.sp2px(b.currency.getContext(), 5);
349
350         if (position == Currency.Position.before) {
351             b.currency.setPaddingRelative(0, 0, hasGap ? gapSize : 0, 0);
352         }
353         else {
354             b.currency.setPaddingRelative(hasGap ? gapSize : 0, 0, 0, 0);
355         }
356     }
357     private void setCurrencyString(String currency) {
358         @ColorInt int textColor = b.dummyText.getTextColors()
359                                              .getDefaultColor();
360         if (TextUtils.isEmpty(currency)) {
361             b.currency.setText(R.string.currency_symbol);
362             int alpha = (textColor >> 24) & 0xff;
363             alpha = alpha * 3 / 4;
364             b.currency.setTextColor((alpha << 24) | (0x00ffffff & textColor));
365         }
366         else {
367             b.currency.setText(currency);
368             b.currency.setTextColor(textColor);
369         }
370     }
371     private void setCurrency(Currency currency) {
372         setCurrencyString((currency == null) ? null : currency.getName());
373     }
374     private void setEditable(Boolean editable) {
375         b.accountRowAccName.setEnabled(editable);
376         b.accountRowAccAmounts.setEnabled(editable);
377     }
378     private void beginUpdates() {
379         if (inUpdate)
380             throw new RuntimeException("Already in update mode");
381         inUpdate = true;
382     }
383     private void endUpdates() {
384         if (!inUpdate)
385             throw new RuntimeException("Not in update mode");
386         inUpdate = false;
387     }
388     /**
389      * syncData()
390      * <p>
391      * Stores the data from the UI elements into the model item
392      * Returns true if there were changes made that suggest transaction has to be
393      * checked for being submittable
394      */
395     private boolean syncData() {
396         if (syncingData) {
397             Logger.debug("new-trans", "skipping syncData() loop");
398             return false;
399         }
400
401         if (getBindingAdapterPosition() == RecyclerView.NO_POSITION) {
402             // probably the row was swiped out
403             Logger.debug("new-trans", "Ignoring request to suncData(): adapter position negative");
404             return false;
405         }
406
407         NewTransactionModel.Item item = getItem();
408
409         syncingData = true;
410
411         boolean significantChange = false;
412
413         try {
414             NewTransactionModel.TransactionAccount acc = item.toTransactionAccount();
415
416             // having account name is important
417             final Editable incomingAccountName = b.accountRowAccName.getText();
418             if (TextUtils.isEmpty(acc.getAccountName()) != TextUtils.isEmpty(incomingAccountName))
419                 significantChange = true;
420
421             acc.setAccountName(String.valueOf(incomingAccountName));
422             final int accNameSelEnd = b.accountRowAccName.getSelectionEnd();
423             final int accNameSelStart = b.accountRowAccName.getSelectionStart();
424             acc.setAccountNameCursorPosition(accNameSelEnd);
425
426             acc.setComment(String.valueOf(b.comment.getText()));
427
428             String amount = String.valueOf(b.accountRowAccAmounts.getText());
429             amount = amount.trim();
430
431             if (amount.isEmpty()) {
432                 if (acc.isAmountSet())
433                     significantChange = true;
434                 acc.resetAmount();
435                 acc.setAmountValid(true);
436             }
437             else {
438                 try {
439                     amount = amount.replace(decimalSeparator, decimalDot);
440                     final float parsedAmount = Float.parseFloat(amount);
441                     if (!acc.isAmountSet() || !Misc.equalFloats(parsedAmount, acc.getAmount()))
442                         significantChange = true;
443                     acc.setAmount(parsedAmount);
444                     acc.setAmountValid(true);
445                 }
446                 catch (NumberFormatException e) {
447                     Logger.debug("new-trans", String.format(
448                             "assuming amount is not set due to number format exception. " +
449                             "input was '%s'", amount));
450                     if (acc.isAmountValid())
451                         significantChange = true;
452                     acc.setAmountValid(false);
453                 }
454                 final String curr = String.valueOf(b.currency.getText());
455                 final String currValue;
456                 if (curr.equals(b.currency.getContext()
457                                           .getResources()
458                                           .getString(R.string.currency_symbol)) || curr.isEmpty())
459                     currValue = null;
460                 else
461                     currValue = curr;
462
463                 if (!significantChange && !Misc.equalStrings(acc.getCurrency(), currValue))
464                     significantChange = true;
465                 acc.setCurrency(currValue);
466             }
467
468             return significantChange;
469         }
470         finally {
471             syncingData = false;
472         }
473     }
474     /**
475      * bind
476      *
477      * @param item updates the UI elements with the data from the model item
478      */
479     @SuppressLint("DefaultLocale")
480     public void bind(@NonNull NewTransactionModel.Item item) {
481         beginUpdates();
482         try {
483             syncingData = true;
484             try {
485                 NewTransactionModel.TransactionAccount acc = item.toTransactionAccount();
486
487                 final String incomingAccountName = acc.getAccountName();
488                 final String presentAccountName = String.valueOf(b.accountRowAccName.getText());
489                 if (!Misc.equalStrings(incomingAccountName, presentAccountName)) {
490                     Logger.debug("bind",
491                             String.format("Setting account name from '%s' to '%s' (| @ %d)",
492                                     presentAccountName, incomingAccountName,
493                                     acc.getAccountNameCursorPosition()));
494                     // avoid triggering completion pop-up
495                     AccountAutocompleteAdapter a =
496                             (AccountAutocompleteAdapter) b.accountRowAccName.getAdapter();
497                     try {
498                         b.accountRowAccName.setAdapter(null);
499                         b.accountRowAccName.setText(incomingAccountName);
500                         b.accountRowAccName.setSelection(acc.getAccountNameCursorPosition());
501                     }
502                     finally {
503                         b.accountRowAccName.setAdapter(a);
504                     }
505                 }
506
507                 final String amountHint = acc.getAmountHint();
508                 if (amountHint == null) {
509                     b.accountRowAccAmounts.setHint(R.string.zero_amount);
510                 }
511                 else {
512                     b.accountRowAccAmounts.setHint(amountHint);
513                 }
514
515                 b.accountRowAccAmounts.setImeOptions(
516                         acc.isLast() ? EditorInfo.IME_ACTION_DONE : EditorInfo.IME_ACTION_NEXT);
517
518                 setCurrencyString(acc.getCurrency());
519                 b.accountRowAccAmounts.setText(
520                         acc.isAmountSet() ? String.format("%4.2f", acc.getAmount()) : null);
521                 displayAmountValidity(true);
522
523                 b.comment.setText(acc.getComment());
524
525                 setEditable(true);
526
527                 applyFocus(mAdapter.model.getFocusInfo()
528                                          .getValue());
529             }
530             finally {
531                 syncingData = false;
532             }
533         }
534         finally {
535             endUpdates();
536         }
537     }
538     private void styleComment(EditText editText, String comment) {
539         final View focusedView = editText.findFocus();
540         editText.setTypeface(null, (focusedView == editText) ? Typeface.NORMAL : Typeface.ITALIC);
541         editText.setVisibility(
542                 ((focusedView != editText) && TextUtils.isEmpty(comment)) ? View.INVISIBLE
543                                                                           : View.VISIBLE);
544     }
545 }