]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/NewTransactionItemHolder.java
NT: date input is no longer focusable
[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.inputmethod.EditorInfo;
27 import android.widget.AutoCompleteTextView;
28 import android.widget.FrameLayout;
29 import android.widget.LinearLayout;
30 import android.widget.TextView;
31
32 import androidx.annotation.NonNull;
33 import androidx.appcompat.widget.LinearLayoutCompat;
34 import androidx.lifecycle.Observer;
35 import androidx.recyclerview.widget.RecyclerView;
36
37 import net.ktnx.mobileledger.R;
38 import net.ktnx.mobileledger.async.DescriptionSelectedCallback;
39 import net.ktnx.mobileledger.model.Data;
40 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
41 import net.ktnx.mobileledger.model.MobileLedgerProfile;
42 import net.ktnx.mobileledger.ui.DatePickerFragment;
43 import net.ktnx.mobileledger.utils.Logger;
44 import net.ktnx.mobileledger.utils.MLDB;
45 import net.ktnx.mobileledger.utils.Misc;
46
47 import java.text.DecimalFormatSymbols;
48 import java.util.Calendar;
49 import java.util.Date;
50 import java.util.GregorianCalendar;
51 import java.util.Locale;
52
53 class NewTransactionItemHolder extends RecyclerView.ViewHolder
54         implements DatePickerFragment.DatePickedListener, DescriptionSelectedCallback {
55     private final String decimalSeparator;
56     private final String decimalDot;
57     private NewTransactionModel.Item item;
58     private TextView tvDate;
59     private AutoCompleteTextView tvDescription;
60     private AutoCompleteTextView tvAccount;
61     private TextView tvAmount;
62     private LinearLayoutCompat lHead;
63     private LinearLayout lAccount;
64     private FrameLayout lPadding;
65     private MobileLedgerProfile mProfile;
66     private Date date;
67     private Observer<Date> dateObserver;
68     private Observer<String> descriptionObserver;
69     private Observer<String> hintObserver;
70     private Observer<Integer> focusedAccountObserver;
71     private Observer<Integer> accountCountObserver;
72     private Observer<Boolean> editableObserver;
73     private boolean inUpdate = false;
74     private boolean syncingData = false;
75     NewTransactionItemHolder(@NonNull View itemView, NewTransactionItemsAdapter adapter) {
76         super(itemView);
77         tvAccount = itemView.findViewById(R.id.account_row_acc_name);
78         tvAmount = itemView.findViewById(R.id.account_row_acc_amounts);
79         tvDate = itemView.findViewById(R.id.new_transaction_date);
80         tvDescription = itemView.findViewById(R.id.new_transaction_description);
81         lHead = itemView.findViewById(R.id.ntr_data);
82         lAccount = itemView.findViewById(R.id.ntr_account);
83         lPadding = itemView.findViewById(R.id.ntr_padding);
84
85         tvDescription.setNextFocusForwardId(View.NO_ID);
86         tvAccount.setNextFocusForwardId(View.NO_ID);
87         tvAmount.setNextFocusForwardId(View.NO_ID); // magic!
88
89         tvDate.setOnClickListener(v -> pickTransactionDate());
90
91         mProfile = Data.profile.getValue();
92         if (mProfile == null)
93             throw new AssertionError();
94
95         MLDB.hookAutocompletionAdapter(tvDescription.getContext(), tvDescription,
96                 MLDB.DESCRIPTION_HISTORY_TABLE, "description", false, adapter, mProfile);
97         MLDB.hookAutocompletionAdapter(tvAccount.getContext(), tvAccount, MLDB.ACCOUNTS_TABLE,
98                 "name", true, this, mProfile);
99
100         // FIXME: react on configuration (locale) changes
101         decimalSeparator = String.valueOf(DecimalFormatSymbols.getInstance()
102                                                               .getMonetaryDecimalSeparator());
103         decimalDot = ".";
104
105         final TextWatcher tw = new TextWatcher() {
106             @Override
107             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
108             }
109
110             @Override
111             public void onTextChanged(CharSequence s, int start, int before, int count) {
112             }
113
114             @Override
115             public void afterTextChanged(Editable s) {
116 //                debug("input", "text changed");
117                 if (inUpdate)
118                     return;
119
120                 Logger.debug("textWatcher", "calling syncData()");
121                 syncData();
122                 Logger.debug("textWatcher",
123                         "syncData() returned, checking if transaction is submittable");
124                 adapter.model.checkTransactionSubmittable(adapter);
125                 Logger.debug("textWatcher", "done");
126             }
127         };
128         final TextWatcher amountWatcher = new TextWatcher() {
129             @Override
130             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
131             }
132             @Override
133             public void onTextChanged(CharSequence s, int start, int before, int count) {
134
135             }
136             @Override
137             public void afterTextChanged(Editable s) {
138                 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
139                     // only one decimal separator is allowed
140                     // plus and minus are allowed only at the beginning
141                     String val = s.toString();
142                     if (val.isEmpty())
143                         tvAmount.setKeyListener(DigitsKeyListener.getInstance(
144                                 "0123456789+-" + decimalSeparator + decimalDot));
145                     else if (val.contains(decimalSeparator) || val.contains(decimalDot))
146                         tvAmount.setKeyListener(DigitsKeyListener.getInstance("0123456789"));
147                     else
148                         tvAmount.setKeyListener(DigitsKeyListener.getInstance(
149                                 "0123456789" + decimalSeparator + decimalDot));
150
151                     syncData();
152                     adapter.model.checkTransactionSubmittable(adapter);
153                 }
154             }
155         };
156         tvDescription.addTextChangedListener(tw);
157         tvAccount.addTextChangedListener(tw);
158         tvAmount.addTextChangedListener(amountWatcher);
159
160         // FIXME: react on locale changes
161         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
162             tvAmount.setKeyListener(DigitsKeyListener.getInstance(Locale.getDefault(), true, true));
163         else
164             tvAmount.setKeyListener(
165                     DigitsKeyListener.getInstance("0123456789+-" + decimalSeparator + decimalDot));
166
167         dateObserver = date -> {
168             if (syncingData)
169                 return;
170             syncingData = true;
171             try {
172                 tvDate.setText(item.getFormattedDate());
173             }
174             finally {
175                 syncingData = false;
176             }
177         };
178         descriptionObserver = description -> {
179             if (syncingData)
180                 return;
181             syncingData = true;
182             try {
183                 tvDescription.setText(description);
184             }
185             finally {
186                 syncingData = false;
187             }
188         };
189         hintObserver = hint -> {
190             if (syncingData)
191                 return;
192             syncingData = true;
193             try {
194                 if (hint == null)
195                     tvAmount.setHint(R.string.zero_amount);
196                 else
197                     tvAmount.setHint(hint);
198             }
199             finally {
200                 syncingData = false;
201             }
202         };
203         editableObserver = this::setEditable;
204         focusedAccountObserver = index -> {
205             if ((index != null) && index.equals(getAdapterPosition())) {
206                 switch (item.getType()) {
207                     case generalData:
208                         // bad idea - double pop-up, and not really necessary.
209                         // the user can tap the input to get the calendar
210                         //if (!tvDate.hasFocus()) tvDate.requestFocus();
211                         boolean focused = tvDescription.requestFocus();
212                         tvDescription.dismissDropDown();
213                         if (focused)
214                             Misc.showSoftKeyboard(
215                                     (NewTransactionActivity) tvDescription.getContext());
216                         break;
217                     case transactionRow:
218                         focused = tvAccount.requestFocus();
219                         tvAccount.dismissDropDown();
220                         if (focused)
221                             Misc.showSoftKeyboard((NewTransactionActivity) tvAccount.getContext());
222
223                         break;
224                 }
225             }
226         };
227         accountCountObserver = count -> {
228             final int adapterPosition = getAdapterPosition();
229             final int layoutPosition = getLayoutPosition();
230             Logger.debug("holder",
231                     String.format(Locale.US, "count=%d; pos=%d, layoutPos=%d [%s]", count,
232                             adapterPosition, layoutPosition, item.getType()
233                                                                  .toString()
234                                                                  .concat(item.getType() ==
235                                                                          NewTransactionModel.ItemType.transactionRow
236                                                                          ? String.format(Locale.US,
237                                                                          "'%s'=%s",
238                                                                          item.getAccount()
239                                                                              .getAccountName(),
240                                                                          item.getAccount()
241                                                                              .isAmountSet()
242                                                                          ? String.format(Locale.US,
243                                                                                  "%.2f",
244                                                                                  item.getAccount()
245                                                                                      .getAmount())
246                                                                          : "unset") : "")));
247             if (adapterPosition == count)
248                 tvAmount.setImeOptions(EditorInfo.IME_ACTION_DONE);
249             else
250                 tvAmount.setImeOptions(EditorInfo.IME_ACTION_NEXT);
251         };
252     }
253     private void setEditable(Boolean editable) {
254         tvDate.setEnabled(editable);
255         tvDescription.setEnabled(editable);
256         tvAccount.setEnabled(editable);
257         tvAmount.setEnabled(editable);
258     }
259     private void beginUpdates() {
260         if (inUpdate)
261             throw new RuntimeException("Already in update mode");
262         inUpdate = true;
263     }
264     private void endUpdates() {
265         if (!inUpdate)
266             throw new RuntimeException("Not in update mode");
267         inUpdate = false;
268     }
269     /**
270      * syncData()
271      * <p>
272      * Stores the data from the UI elements into the model item
273      */
274     private void syncData() {
275         if (item == null)
276             return;
277
278         if (syncingData) {
279             Logger.debug("new-trans", "skipping syncData() loop");
280             return;
281         }
282
283         syncingData = true;
284
285         try {
286             switch (item.getType()) {
287                 case generalData:
288                     item.setDate(String.valueOf(tvDate.getText()));
289                     item.setDescription(String.valueOf(tvDescription.getText()));
290                     break;
291                 case transactionRow:
292                     item.getAccount()
293                         .setAccountName(String.valueOf(tvAccount.getText()));
294
295                     // TODO: handle multiple amounts
296                     String amount = String.valueOf(tvAmount.getText());
297                     amount = amount.trim();
298
299                     if (amount.isEmpty()) {
300                         item.getAccount()
301                             .resetAmount();
302                     }
303                     else {
304                         try {
305                             amount = amount.replace(decimalSeparator, decimalDot);
306                             item.getAccount()
307                                 .setAmount(Float.parseFloat(amount));
308                         }
309                         catch (NumberFormatException e) {
310                             Logger.debug("new-trans", String.format(
311                                     "assuming amount is not set due to number format exception. " +
312                                     "input was '%s'", amount));
313                             item.getAccount()
314                                 .resetAmount();
315                         }
316                     }
317
318                     break;
319                 case bottomFiller:
320                     throw new RuntimeException("Should not happen");
321             }
322         }
323         finally {
324             syncingData = false;
325         }
326     }
327     private void pickTransactionDate() {
328         DatePickerFragment picker = new DatePickerFragment();
329         picker.setOnDatePickedListener(this);
330         picker.show(((NewTransactionActivity) tvDate.getContext()).getSupportFragmentManager(),
331                 "datePicker");
332     }
333     /**
334      * setData
335      *
336      * @param item updates the UI elements with the data from the model item
337      */
338     @SuppressLint("DefaultLocale")
339     public void setData(NewTransactionModel.Item item) {
340         beginUpdates();
341         try {
342             if (this.item != null && !this.item.equals(item)) {
343                 this.item.stopObservingDate(dateObserver);
344                 this.item.stopObservingDescription(descriptionObserver);
345                 this.item.stopObservingAmountHint(hintObserver);
346                 this.item.stopObservingEditableFlag(editableObserver);
347                 this.item.getModel()
348                          .stopObservingFocusedItem(focusedAccountObserver);
349                 this.item.getModel()
350                          .stopObservingAccountCount(accountCountObserver);
351
352                 this.item = null;
353             }
354
355             switch (item.getType()) {
356                 case generalData:
357                     tvDate.setText(item.getFormattedDate());
358                     tvDescription.setText(item.getDescription());
359                     lHead.setVisibility(View.VISIBLE);
360                     lAccount.setVisibility(View.GONE);
361                     lPadding.setVisibility(View.GONE);
362                     setEditable(true);
363                     break;
364                 case transactionRow:
365                     LedgerTransactionAccount acc = item.getAccount();
366                     tvAccount.setText(acc.getAccountName());
367                     if (acc.isAmountSet()) {
368                         tvAmount.setText(String.format("%1.2f", acc.getAmount()));
369                     }
370                     else {
371                         tvAmount.setText("");
372 //                        tvAmount.setHint(R.string.zero_amount);
373                     }
374                     tvAmount.setHint(item.getAmountHint());
375                     lHead.setVisibility(View.GONE);
376                     lAccount.setVisibility(View.VISIBLE);
377                     lPadding.setVisibility(View.GONE);
378                     setEditable(true);
379                     break;
380                 case bottomFiller:
381                     lHead.setVisibility(View.GONE);
382                     lAccount.setVisibility(View.GONE);
383                     lPadding.setVisibility(View.VISIBLE);
384                     setEditable(false);
385                     break;
386             }
387
388             if (this.item == null) { // was null or has changed
389                 this.item = item;
390                 final NewTransactionActivity activity =
391                         (NewTransactionActivity) tvDescription.getContext();
392                 item.observeDate(activity, dateObserver);
393                 item.observeDescription(activity, descriptionObserver);
394                 item.observeAmountHint(activity, hintObserver);
395                 item.observeEditableFlag(activity, editableObserver);
396                 item.getModel()
397                     .observeFocusedItem(activity, focusedAccountObserver);
398                 item.getModel()
399                     .observeAccountCount(activity, accountCountObserver);
400             }
401         }
402         finally {
403             endUpdates();
404         }
405     }
406     @Override
407     public void onDatePicked(int year, int month, int day) {
408         final Calendar c = GregorianCalendar.getInstance();
409         c.set(year, month, day);
410         item.setDate(c.getTime());
411         boolean focused = tvDescription.requestFocus();
412         if (focused)
413             Misc.showSoftKeyboard((NewTransactionActivity) tvAccount.getContext());
414
415     }
416     @Override
417     public void descriptionSelected(String description) {
418         tvAccount.setText(description);
419         tvAmount.requestFocus(View.FOCUS_FORWARD);
420     }
421 }