]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/NewTransactionItemHolder.java
slight improvement in allowing "-" only at the eginning of the amount
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / ui / activity / NewTransactionItemHolder.java
1 /*
2  * Copyright © 2019 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.activity;
19
20 import android.annotation.SuppressLint;
21 import android.os.Build;
22 import android.text.Editable;
23 import android.text.TextWatcher;
24 import android.text.method.DigitsKeyListener;
25 import android.view.View;
26 import android.view.ViewGroup;
27 import android.view.inputmethod.EditorInfo;
28 import android.widget.AutoCompleteTextView;
29 import android.widget.EditText;
30 import android.widget.FrameLayout;
31 import android.widget.LinearLayout;
32 import android.widget.TextView;
33
34 import androidx.annotation.NonNull;
35 import androidx.appcompat.app.AppCompatActivity;
36 import androidx.constraintlayout.widget.ConstraintLayout;
37 import androidx.lifecycle.Observer;
38 import androidx.recyclerview.widget.RecyclerView;
39
40 import net.ktnx.mobileledger.R;
41 import net.ktnx.mobileledger.async.DescriptionSelectedCallback;
42 import net.ktnx.mobileledger.model.Data;
43 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
44 import net.ktnx.mobileledger.model.MobileLedgerProfile;
45 import net.ktnx.mobileledger.ui.CurrencySelectorFragment;
46 import net.ktnx.mobileledger.ui.DatePickerFragment;
47 import net.ktnx.mobileledger.ui.TextViewClearHelper;
48 import net.ktnx.mobileledger.utils.Colors;
49 import net.ktnx.mobileledger.utils.Logger;
50 import net.ktnx.mobileledger.utils.MLDB;
51 import net.ktnx.mobileledger.utils.Misc;
52
53 import java.text.DecimalFormatSymbols;
54 import java.util.Calendar;
55 import java.util.Date;
56 import java.util.GregorianCalendar;
57 import java.util.Locale;
58
59 import static net.ktnx.mobileledger.ui.activity.NewTransactionModel.ItemType;
60
61 class NewTransactionItemHolder extends RecyclerView.ViewHolder
62         implements DatePickerFragment.DatePickedListener, DescriptionSelectedCallback {
63     private final String decimalSeparator;
64     private final String decimalDot;
65     private NewTransactionModel.Item item;
66     private TextView tvDate;
67     private AutoCompleteTextView tvDescription;
68     private AutoCompleteTextView tvAccount;
69     private TextView tvComment;
70     private EditText tvAmount;
71     private LinearLayout lHead;
72     private ViewGroup lAccount;
73     private FrameLayout lPadding;
74     private MobileLedgerProfile mProfile;
75     private Date date;
76     private Observer<Date> dateObserver;
77     private Observer<String> descriptionObserver;
78     private Observer<String> hintObserver;
79     private Observer<Integer> focusedAccountObserver;
80     private Observer<Integer> accountCountObserver;
81     private Observer<Boolean> editableObserver;
82     private Observer<Boolean> commentVisibleObserver;
83     private Observer<String> commentObserver;
84     private boolean inUpdate = false;
85     private boolean syncingData = false;
86     private View commentButton;
87     NewTransactionItemHolder(@NonNull View itemView, NewTransactionItemsAdapter adapter) {
88         super(itemView);
89         tvAccount = itemView.findViewById(R.id.account_row_acc_name);
90         tvComment = itemView.findViewById(R.id.comment);
91         new TextViewClearHelper().attachToTextView((EditText) tvComment);
92         commentButton = itemView.findViewById(R.id.comment_button);
93         tvAmount = itemView.findViewById(R.id.account_row_acc_amounts);
94         tvDate = itemView.findViewById(R.id.new_transaction_date);
95         tvDescription = itemView.findViewById(R.id.new_transaction_description);
96         lHead = itemView.findViewById(R.id.ntr_data);
97         lAccount = itemView.findViewById(R.id.ntr_account);
98         lPadding = itemView.findViewById(R.id.ntr_padding);
99
100         tvDescription.setNextFocusForwardId(View.NO_ID);
101         tvAccount.setNextFocusForwardId(View.NO_ID);
102         tvAmount.setNextFocusForwardId(View.NO_ID); // magic!
103
104         tvDate.setOnClickListener(v -> pickTransactionDate());
105
106         mProfile = Data.profile.getValue();
107         if (mProfile == null)
108             throw new AssertionError();
109
110         View.OnFocusChangeListener focusMonitor = (v, hasFocus) -> {
111             if (hasFocus) {
112                 boolean wasSyncing = syncingData;
113                 syncingData = true;
114                 try {
115                     final int pos = getAdapterPosition();
116                     adapter.updateFocusedItem(pos);
117                     switch (v.getId()) {
118                         case R.id.account_row_acc_name:
119                             adapter.noteFocusIsOnAccount(pos);
120                             break;
121                         case R.id.account_row_acc_amounts:
122                             adapter.noteFocusIsOnAmount(pos);
123                             break;
124                         case R.id.comment:
125                             adapter.noteFocusIsOnComment(pos);
126                             break;
127                     }
128                 }
129                 finally {
130                     syncingData = wasSyncing;
131                 }
132             }
133         };
134
135         tvDescription.setOnFocusChangeListener(focusMonitor);
136         tvAccount.setOnFocusChangeListener(focusMonitor);
137         tvAmount.setOnFocusChangeListener(focusMonitor);
138
139         itemView.findViewById(R.id.comment_button)
140                 .setOnClickListener(v -> {
141                     final int pos = getAdapterPosition();
142                     adapter.toggleComment(pos);
143                 });
144         MLDB.hookAutocompletionAdapter(tvDescription.getContext(), tvDescription,
145                 MLDB.DESCRIPTION_HISTORY_TABLE, "description", false, adapter, mProfile);
146         MLDB.hookAutocompletionAdapter(tvAccount.getContext(), tvAccount, MLDB.ACCOUNTS_TABLE,
147                 "name", true, this, mProfile);
148
149         // FIXME: react on configuration (locale) changes
150         decimalSeparator = String.valueOf(DecimalFormatSymbols.getInstance()
151                                                               .getMonetaryDecimalSeparator());
152         decimalDot = ".";
153
154         final TextWatcher tw = new TextWatcher() {
155             @Override
156             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
157             }
158
159             @Override
160             public void onTextChanged(CharSequence s, int start, int before, int count) {
161             }
162
163             @Override
164             public void afterTextChanged(Editable s) {
165 //                debug("input", "text changed");
166                 if (inUpdate)
167                     return;
168
169                 Logger.debug("textWatcher", "calling syncData()");
170                 syncData();
171                 Logger.debug("textWatcher",
172                         "syncData() returned, checking if transaction is submittable");
173                 adapter.model.checkTransactionSubmittable(adapter);
174                 Logger.debug("textWatcher", "done");
175             }
176         };
177         final TextWatcher amountWatcher = new TextWatcher() {
178             @Override
179             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
180             }
181             @Override
182             public void onTextChanged(CharSequence s, int start, int before, int count) {
183
184             }
185             @Override
186             public void afterTextChanged(Editable s) {
187                 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
188                     // only one decimal separator is allowed
189                     // plus and minus are allowed only at the beginning
190                     String allowed = "0123456789";
191                     String val = s.toString();
192                     if (val.isEmpty() || (tvAmount.getSelectionStart() == 0))
193                         allowed += "-";
194                     if (!val.contains(decimalSeparator) && !val.contains(decimalDot))
195                         allowed += decimalSeparator + decimalDot;
196
197                     tvAmount.setKeyListener(DigitsKeyListener.getInstance(allowed));
198
199                     syncData();
200                     adapter.model.checkTransactionSubmittable(adapter);
201                 }
202             }
203         };
204         tvDescription.addTextChangedListener(tw);
205         tvAccount.addTextChangedListener(tw);
206         tvComment.addTextChangedListener(tw);
207         tvAmount.addTextChangedListener(amountWatcher);
208
209         // FIXME: react on locale changes
210         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
211             tvAmount.setKeyListener(DigitsKeyListener.getInstance(Locale.getDefault(), true, true));
212         else
213             tvAmount.setKeyListener(
214                     DigitsKeyListener.getInstance("0123456789+-" + decimalSeparator + decimalDot));
215
216         dateObserver = date -> {
217             if (syncingData)
218                 return;
219             syncingData = true;
220             try {
221                 tvDate.setText(item.getFormattedDate());
222             }
223             finally {
224                 syncingData = false;
225             }
226         };
227         descriptionObserver = description -> {
228             if (syncingData)
229                 return;
230             syncingData = true;
231             try {
232                 tvDescription.setText(description);
233             }
234             finally {
235                 syncingData = false;
236             }
237         };
238         hintObserver = hint -> {
239             if (syncingData)
240                 return;
241             syncingData = true;
242             try {
243                 if (hint == null)
244                     tvAmount.setHint(R.string.zero_amount);
245                 else
246                     tvAmount.setHint(hint);
247             }
248             finally {
249                 syncingData = false;
250             }
251         };
252         editableObserver = this::setEditable;
253         commentVisibleObserver = this::setCommentVisible;
254         commentObserver = this::setComment;
255         focusedAccountObserver = index -> {
256             if ((index != null) && index.equals(getAdapterPosition())) {
257                 switch (item.getType()) {
258                     case generalData:
259                         // bad idea - double pop-up, and not really necessary.
260                         // the user can tap the input to get the calendar
261                         //if (!tvDate.hasFocus()) tvDate.requestFocus();
262                         boolean focused = tvDescription.requestFocus();
263                         tvDescription.dismissDropDown();
264                         if (focused)
265                             Misc.showSoftKeyboard(
266                                     (NewTransactionActivity) tvDescription.getContext());
267                         break;
268                     case transactionRow:
269                         // do nothing if a row element already has the focus
270                         if (!itemView.hasFocus()) {
271                             switch (item.getFocusedElement()) {
272                                 case Amount:
273                                     tvAmount.requestFocus();
274                                     break;
275                                 case Comment:
276                                     tvComment.requestFocus();
277                                     break;
278                                 case Account:
279                                     focused = tvAccount.requestFocus();
280                                     tvAccount.dismissDropDown();
281                                     if (focused)
282                                         Misc.showSoftKeyboard(
283                                                 (NewTransactionActivity) tvAccount.getContext());
284                                     break;
285                             }
286                         }
287
288                         break;
289                 }
290             }
291         };
292         accountCountObserver = count -> {
293             final int adapterPosition = getAdapterPosition();
294             final int layoutPosition = getLayoutPosition();
295             Logger.debug("holder",
296                     String.format(Locale.US, "count=%d; pos=%d, layoutPos=%d [%s]", count,
297                             adapterPosition, layoutPosition, item.getType()
298                                                                  .toString()
299                                                                  .concat(item.getType() ==
300                                                                          ItemType.transactionRow
301                                                                          ? String.format(Locale.US,
302                                                                          "'%s'=%s",
303                                                                          item.getAccount()
304                                                                              .getAccountName(),
305                                                                          item.getAccount()
306                                                                              .isAmountSet()
307                                                                          ? String.format(Locale.US,
308                                                                                  "%.2f",
309                                                                                  item.getAccount()
310                                                                                      .getAmount())
311                                                                          : "unset") : "")));
312             if (adapterPosition == count)
313                 tvAmount.setImeOptions(EditorInfo.IME_ACTION_DONE);
314             else
315                 tvAmount.setImeOptions(EditorInfo.IME_ACTION_NEXT);
316         };
317     }
318     private void setEditable(Boolean editable) {
319         tvDate.setEnabled(editable);
320         tvDescription.setEnabled(editable);
321         tvAccount.setEnabled(editable);
322         tvAmount.setEnabled(editable);
323     }
324     private void setCommentVisible(Boolean visible) {
325         if (visible) {
326             // showing; show the comment view and align the comment button to it
327             tvComment.setVisibility(View.VISIBLE);
328             tvComment.requestFocus();
329             ConstraintLayout.LayoutParams lp =
330                     (ConstraintLayout.LayoutParams) commentButton.getLayoutParams();
331             lp.bottomToBottom = R.id.comment;
332
333             commentButton.setLayoutParams(lp);
334         }
335         else {
336             // hiding; hide the comment comment view and align amounts layout under it
337             tvComment.setVisibility(View.GONE);
338             ConstraintLayout.LayoutParams lp =
339                     (ConstraintLayout.LayoutParams) commentButton.getLayoutParams();
340             lp.bottomToBottom = R.id.ntr_account;   // R.id.parent doesn't work here
341
342             commentButton.setLayoutParams(lp);
343         }
344     }
345     private void setComment(String comment) {
346         if ((comment != null) && !comment.isEmpty())
347             commentButton.setBackgroundResource(R.drawable.ic_comment_black_24dp);
348         else
349             commentButton.setBackgroundResource(R.drawable.ic_comment_gray_24dp);
350     }
351     private void beginUpdates() {
352         if (inUpdate)
353             throw new RuntimeException("Already in update mode");
354         inUpdate = true;
355     }
356     private void endUpdates() {
357         if (!inUpdate)
358             throw new RuntimeException("Not in update mode");
359         inUpdate = false;
360     }
361     /**
362      * syncData()
363      * <p>
364      * Stores the data from the UI elements into the model item
365      */
366     private void syncData() {
367         if (item == null)
368             return;
369
370         if (syncingData) {
371             Logger.debug("new-trans", "skipping syncData() loop");
372             return;
373         }
374
375         syncingData = true;
376
377         try {
378             switch (item.getType()) {
379                 case generalData:
380                     item.setDate(String.valueOf(tvDate.getText()));
381                     item.setDescription(String.valueOf(tvDescription.getText()));
382                     break;
383                 case transactionRow:
384                     final LedgerTransactionAccount account = item.getAccount();
385                     account.setAccountName(String.valueOf(tvAccount.getText()));
386
387                     item.setComment(String.valueOf(tvComment.getText()));
388
389                     // TODO: handle multiple amounts
390                     String amount = String.valueOf(tvAmount.getText());
391                     amount = amount.trim();
392
393                     if (amount.isEmpty()) {
394                         account.resetAmount();
395                     }
396                     else {
397                         try {
398                             amount = amount.replace(decimalSeparator, decimalDot);
399                             account.setAmount(Float.parseFloat(amount));
400                         }
401                         catch (NumberFormatException e) {
402                             Logger.debug("new-trans", String.format(
403                                     "assuming amount is not set due to number format exception. " +
404                                     "input was '%s'", amount));
405                             account.resetAmount();
406                         }
407                     }
408
409                     break;
410                 case bottomFiller:
411                     throw new RuntimeException("Should not happen");
412             }
413         }
414         finally {
415             syncingData = false;
416         }
417     }
418     private void pickTransactionDate() {
419         DatePickerFragment picker = new DatePickerFragment();
420         picker.setFutureDates(mProfile.getFutureDates());
421         picker.setOnDatePickedListener(this);
422         picker.show(((NewTransactionActivity) tvDate.getContext()).getSupportFragmentManager(),
423                 "datePicker");
424     }
425     /**
426      * setData
427      *
428      * @param item updates the UI elements with the data from the model item
429      */
430     @SuppressLint("DefaultLocale")
431     public void setData(NewTransactionModel.Item item) {
432         beginUpdates();
433         try {
434             if (this.item != null && !this.item.equals(item)) {
435                 this.item.stopObservingDate(dateObserver);
436                 this.item.stopObservingDescription(descriptionObserver);
437                 this.item.stopObservingAmountHint(hintObserver);
438                 this.item.stopObservingEditableFlag(editableObserver);
439                 this.item.stopObservingCommentVisible(commentVisibleObserver);
440                 this.item.stopObservingComment(commentObserver);
441                 this.item.getModel()
442                          .stopObservingFocusedItem(focusedAccountObserver);
443                 this.item.getModel()
444                          .stopObservingAccountCount(accountCountObserver);
445
446                 this.item = null;
447             }
448
449             switch (item.getType()) {
450                 case generalData:
451                     tvDate.setText(item.getFormattedDate());
452                     tvDescription.setText(item.getDescription());
453                     lHead.setVisibility(View.VISIBLE);
454                     lAccount.setVisibility(View.GONE);
455                     lPadding.setVisibility(View.GONE);
456                     setEditable(true);
457                     break;
458                 case transactionRow:
459                     LedgerTransactionAccount acc = item.getAccount();
460                     tvAccount.setText(acc.getAccountName());
461                     tvComment.setText(acc.getComment());
462                     if (acc.isAmountSet()) {
463                         tvAmount.setText(String.format("%1.2f", acc.getAmount()));
464                     }
465                     else {
466                         tvAmount.setText("");
467 //                        tvAmount.setHint(R.string.zero_amount);
468                     }
469                     tvAmount.setHint(item.getAmountHint());
470                     lHead.setVisibility(View.GONE);
471                     lAccount.setVisibility(View.VISIBLE);
472                     lPadding.setVisibility(View.GONE);
473                     setEditable(true);
474                     break;
475                 case bottomFiller:
476                     lHead.setVisibility(View.GONE);
477                     lAccount.setVisibility(View.GONE);
478                     lPadding.setVisibility(View.VISIBLE);
479                     setEditable(false);
480                     break;
481             }
482
483             if (this.item == null) { // was null or has changed
484                 this.item = item;
485                 final NewTransactionActivity activity =
486                         (NewTransactionActivity) tvDescription.getContext();
487                 item.observeDate(activity, dateObserver);
488                 item.observeDescription(activity, descriptionObserver);
489                 item.observeAmountHint(activity, hintObserver);
490                 item.observeEditableFlag(activity, editableObserver);
491                 item.observeCommentVisible(activity, commentVisibleObserver);
492                 item.observeComment(activity, commentObserver);
493                 item.getModel()
494                     .observeFocusedItem(activity, focusedAccountObserver);
495                 item.getModel()
496                     .observeAccountCount(activity, accountCountObserver);
497             }
498         }
499         finally {
500             endUpdates();
501         }
502     }
503     @Override
504     public void onDatePicked(int year, int month, int day) {
505         final Calendar c = GregorianCalendar.getInstance();
506         c.set(year, month, day);
507         item.setDate(c.getTime());
508         boolean focused = tvDescription.requestFocus();
509         if (focused)
510             Misc.showSoftKeyboard((NewTransactionActivity) tvAccount.getContext());
511
512     }
513     @Override
514     public void descriptionSelected(String description) {
515         tvAccount.setText(description);
516         tvAmount.requestFocus(View.FOCUS_FORWARD);
517     }
518 }