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