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