]> git.ktnx.net Git - mobile-ledger.git/blobdiff - app/src/main/java/net/ktnx/mobileledger/ui/activity/NewTransactionItemHolder.java
new transaction: hide currency/commodity selector by default; add menu item for showing
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / ui / activity / NewTransactionItemHolder.java
index e515690a0ef8586cab11550c8fc6fd35a1573be9..d7017e21a6816056c18a7fc104eff8639b2ac97a 100644 (file)
@@ -22,24 +22,34 @@ import android.os.Build;
 import android.text.Editable;
 import android.text.TextWatcher;
 import android.text.method.DigitsKeyListener;
+import android.view.Gravity;
 import android.view.View;
+import android.view.ViewGroup;
 import android.view.inputmethod.EditorInfo;
 import android.widget.AutoCompleteTextView;
+import android.widget.EditText;
 import android.widget.FrameLayout;
 import android.widget.LinearLayout;
 import android.widget.TextView;
 
 import androidx.annotation.NonNull;
+import androidx.appcompat.app.AppCompatActivity;
 import androidx.constraintlayout.widget.ConstraintLayout;
 import androidx.lifecycle.Observer;
 import androidx.recyclerview.widget.RecyclerView;
 
 import net.ktnx.mobileledger.R;
 import net.ktnx.mobileledger.async.DescriptionSelectedCallback;
+import net.ktnx.mobileledger.model.Currency;
 import net.ktnx.mobileledger.model.Data;
 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
 import net.ktnx.mobileledger.model.MobileLedgerProfile;
+import net.ktnx.mobileledger.ui.CurrencySelectorFragment;
 import net.ktnx.mobileledger.ui.DatePickerFragment;
+import net.ktnx.mobileledger.ui.OnCurrencySelectedListener;
+import net.ktnx.mobileledger.ui.TextViewClearHelper;
+import net.ktnx.mobileledger.utils.Colors;
+import net.ktnx.mobileledger.utils.DimensionUtils;
 import net.ktnx.mobileledger.utils.Logger;
 import net.ktnx.mobileledger.utils.MLDB;
 import net.ktnx.mobileledger.utils.Misc;
@@ -50,17 +60,22 @@ import java.util.Date;
 import java.util.GregorianCalendar;
 import java.util.Locale;
 
+import static net.ktnx.mobileledger.ui.activity.NewTransactionModel.ItemType;
+
 class NewTransactionItemHolder extends RecyclerView.ViewHolder
-        implements DatePickerFragment.DatePickedListener, DescriptionSelectedCallback {
+        implements DatePickerFragment.DatePickedListener, DescriptionSelectedCallback,
+        OnCurrencySelectedListener {
     private final String decimalSeparator;
     private final String decimalDot;
+    private final TextView tvCurrency;
     private NewTransactionModel.Item item;
     private TextView tvDate;
     private AutoCompleteTextView tvDescription;
     private AutoCompleteTextView tvAccount;
-    private TextView tvAmount;
-    private ConstraintLayout lHead;
-    private LinearLayout lAccount;
+    private TextView tvComment;
+    private EditText tvAmount;
+    private LinearLayout lHead;
+    private ViewGroup lAccount;
     private FrameLayout lPadding;
     private MobileLedgerProfile mProfile;
     private Date date;
@@ -70,12 +85,25 @@ class NewTransactionItemHolder extends RecyclerView.ViewHolder
     private Observer<Integer> focusedAccountObserver;
     private Observer<Integer> accountCountObserver;
     private Observer<Boolean> editableObserver;
+    private Observer<Boolean> commentVisibleObserver;
+    private Observer<String> commentObserver;
+    private Observer<Currency.Position> currencyPositionObserver;
+    private Observer<Boolean> currencyGapObserver;
+    private Observer<Locale> localeObserver;
+    private Observer<Currency> currencyObserver;
+    private Observer<Boolean> showCurrencyObserver;
     private boolean inUpdate = false;
     private boolean syncingData = false;
+    private View commentButton;
+    //TODO multiple amounts with different currencies per posting
     NewTransactionItemHolder(@NonNull View itemView, NewTransactionItemsAdapter adapter) {
         super(itemView);
         tvAccount = itemView.findViewById(R.id.account_row_acc_name);
+        tvComment = itemView.findViewById(R.id.comment);
+        new TextViewClearHelper().attachToTextView((EditText) tvComment);
+        commentButton = itemView.findViewById(R.id.comment_button);
         tvAmount = itemView.findViewById(R.id.account_row_acc_amounts);
+        tvCurrency = itemView.findViewById(R.id.currency);
         tvDate = itemView.findViewById(R.id.new_transaction_date);
         tvDescription = itemView.findViewById(R.id.new_transaction_description);
         lHead = itemView.findViewById(R.id.ntr_data);
@@ -86,16 +114,46 @@ class NewTransactionItemHolder extends RecyclerView.ViewHolder
         tvAccount.setNextFocusForwardId(View.NO_ID);
         tvAmount.setNextFocusForwardId(View.NO_ID); // magic!
 
-        tvDate.setOnFocusChangeListener((v, hasFocus) -> {
-            if (hasFocus)
-                pickTransactionDate();
-        });
         tvDate.setOnClickListener(v -> pickTransactionDate());
 
         mProfile = Data.profile.getValue();
         if (mProfile == null)
             throw new AssertionError();
 
+        View.OnFocusChangeListener focusMonitor = (v, hasFocus) -> {
+            if (hasFocus) {
+                boolean wasSyncing = syncingData;
+                syncingData = true;
+                try {
+                    final int pos = getAdapterPosition();
+                    adapter.updateFocusedItem(pos);
+                    switch (v.getId()) {
+                        case R.id.account_row_acc_name:
+                            adapter.noteFocusIsOnAccount(pos);
+                            break;
+                        case R.id.account_row_acc_amounts:
+                            adapter.noteFocusIsOnAmount(pos);
+                            break;
+                        case R.id.comment:
+                            adapter.noteFocusIsOnComment(pos);
+                            break;
+                    }
+                }
+                finally {
+                    syncingData = wasSyncing;
+                }
+            }
+        };
+
+        tvDescription.setOnFocusChangeListener(focusMonitor);
+        tvAccount.setOnFocusChangeListener(focusMonitor);
+        tvAmount.setOnFocusChangeListener(focusMonitor);
+
+        itemView.findViewById(R.id.comment_button)
+                .setOnClickListener(v -> {
+                    final int pos = getAdapterPosition();
+                    adapter.toggleComment(pos);
+                });
         MLDB.hookAutocompletionAdapter(tvDescription.getContext(), tvDescription,
                 MLDB.DESCRIPTION_HISTORY_TABLE, "description", false, adapter, mProfile);
         MLDB.hookAutocompletionAdapter(tvAccount.getContext(), tvAccount, MLDB.ACCOUNTS_TABLE,
@@ -132,25 +190,29 @@ class NewTransactionItemHolder extends RecyclerView.ViewHolder
         final TextWatcher amountWatcher = new TextWatcher() {
             @Override
             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
+                Logger.debug("num",
+                        String.format(Locale.US, "beforeTextChanged: start=%d, count=%d, after=%d",
+                                start, count, after));
             }
             @Override
             public void onTextChanged(CharSequence s, int start, int before, int count) {
-
+                Logger.debug("num",
+                        String.format(Locale.US, "onTextChanged: start=%d, before=%d, count=%d",
+                                start, before, count));
             }
             @Override
             public void afterTextChanged(Editable s) {
                 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
                     // only one decimal separator is allowed
                     // plus and minus are allowed only at the beginning
+                    String allowed = "0123456789";
                     String val = s.toString();
-                    if (val.isEmpty())
-                        tvAmount.setKeyListener(DigitsKeyListener.getInstance(
-                                "0123456789+-" + decimalSeparator + decimalDot));
-                    else if (val.contains(decimalSeparator) || val.contains(decimalDot))
-                        tvAmount.setKeyListener(DigitsKeyListener.getInstance("0123456789"));
-                    else
-                        tvAmount.setKeyListener(DigitsKeyListener.getInstance(
-                                "0123456789" + decimalSeparator + decimalDot));
+                    if (val.isEmpty() || (tvAmount.getSelectionStart() == 0))
+                        allowed += "-";
+                    if (!val.contains(decimalSeparator) && !val.contains(decimalDot))
+                        allowed += decimalSeparator + decimalDot;
+
+                    tvAmount.setKeyListener(DigitsKeyListener.getInstance(allowed));
 
                     syncData();
                     adapter.model.checkTransactionSubmittable(adapter);
@@ -159,11 +221,19 @@ class NewTransactionItemHolder extends RecyclerView.ViewHolder
         };
         tvDescription.addTextChangedListener(tw);
         tvAccount.addTextChangedListener(tw);
+        tvComment.addTextChangedListener(tw);
         tvAmount.addTextChangedListener(amountWatcher);
 
-        // FIXME: react on locale changes
+        tvCurrency.setOnClickListener(v -> {
+            CurrencySelectorFragment cpf = new CurrencySelectorFragment();
+            cpf.setOnCurrencySelectedListener(this);
+            final AppCompatActivity activity = (AppCompatActivity) v.getContext();
+            cpf.show(activity.getSupportFragmentManager(), "currency-selector");
+        });
+
         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
-            tvAmount.setKeyListener(DigitsKeyListener.getInstance(Locale.getDefault(), true, true));
+            tvAmount.setKeyListener(
+                    DigitsKeyListener.getInstance(Data.locale.getValue(), true, true));
         else
             tvAmount.setKeyListener(
                     DigitsKeyListener.getInstance("0123456789+-" + decimalSeparator + decimalDot));
@@ -205,6 +275,8 @@ class NewTransactionItemHolder extends RecyclerView.ViewHolder
             }
         };
         editableObserver = this::setEditable;
+        commentVisibleObserver = this::setCommentVisible;
+        commentObserver = this::setComment;
         focusedAccountObserver = index -> {
             if ((index != null) && index.equals(getAdapterPosition())) {
                 switch (item.getType()) {
@@ -219,10 +291,24 @@ class NewTransactionItemHolder extends RecyclerView.ViewHolder
                                     (NewTransactionActivity) tvDescription.getContext());
                         break;
                     case transactionRow:
-                        focused = tvAccount.requestFocus();
-                        tvAccount.dismissDropDown();
-                        if (focused)
-                            Misc.showSoftKeyboard((NewTransactionActivity) tvAccount.getContext());
+                        // do nothing if a row element already has the focus
+                        if (!itemView.hasFocus()) {
+                            switch (item.getFocusedElement()) {
+                                case Amount:
+                                    tvAmount.requestFocus();
+                                    break;
+                                case Comment:
+                                    tvComment.requestFocus();
+                                    break;
+                                case Account:
+                                    focused = tvAccount.requestFocus();
+                                    tvAccount.dismissDropDown();
+                                    if (focused)
+                                        Misc.showSoftKeyboard(
+                                                (NewTransactionActivity) tvAccount.getContext());
+                                    break;
+                            }
+                        }
 
                         break;
                 }
@@ -236,7 +322,7 @@ class NewTransactionItemHolder extends RecyclerView.ViewHolder
                             adapterPosition, layoutPosition, item.getType()
                                                                  .toString()
                                                                  .concat(item.getType() ==
-                                                                         NewTransactionModel.ItemType.transactionRow
+                                                                         ItemType.transactionRow
                                                                          ? String.format(Locale.US,
                                                                          "'%s'=%s",
                                                                          item.getAccount()
@@ -253,6 +339,89 @@ class NewTransactionItemHolder extends RecyclerView.ViewHolder
             else
                 tvAmount.setImeOptions(EditorInfo.IME_ACTION_NEXT);
         };
+
+        currencyPositionObserver = position -> {
+            updateCurrencyPositionAndPadding(position, Data.currencyGap.getValue());
+        };
+
+        currencyGapObserver = hasGap -> {
+            updateCurrencyPositionAndPadding(Data.currencySymbolPosition.getValue(), hasGap);
+        };
+
+        localeObserver = locale -> {
+            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
+                tvAmount.setKeyListener(DigitsKeyListener.getInstance(locale, true, true));
+        };
+
+        currencyObserver = this::setCurrency;
+
+        showCurrencyObserver = showCurrency -> {
+              if (showCurrency) {
+                  tvCurrency.setVisibility(View.VISIBLE);
+              }
+            else {
+                tvCurrency.setVisibility(View.GONE);
+                setCurrencyString(null);
+              }
+        };
+    }
+    private void updateCurrencyPositionAndPadding(Currency.Position position, boolean hasGap) {
+        ConstraintLayout.LayoutParams amountLP =
+                (ConstraintLayout.LayoutParams) tvAmount.getLayoutParams();
+        ConstraintLayout.LayoutParams currencyLP =
+                (ConstraintLayout.LayoutParams) tvCurrency.getLayoutParams();
+
+        if (position == Currency.Position.before) {
+            currencyLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
+            currencyLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
+
+            amountLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
+            amountLP.endToStart = ConstraintLayout.LayoutParams.UNSET;
+            amountLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
+            amountLP.startToEnd = tvCurrency.getId();
+
+            tvCurrency.setGravity(Gravity.END);
+        }
+        else {
+            currencyLP.startToStart = ConstraintLayout.LayoutParams.UNSET;
+            currencyLP.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
+
+            amountLP.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
+            amountLP.startToEnd = ConstraintLayout.LayoutParams.UNSET;
+            amountLP.endToEnd = ConstraintLayout.LayoutParams.UNSET;
+            amountLP.endToStart = tvCurrency.getId();
+
+            tvCurrency.setGravity(Gravity.START);
+        }
+
+        amountLP.resolveLayoutDirection(tvAmount.getLayoutDirection());
+        currencyLP.resolveLayoutDirection(tvCurrency.getLayoutDirection());
+
+        tvAmount.setLayoutParams(amountLP);
+        tvCurrency.setLayoutParams(currencyLP);
+
+        // distance between the amount and the currency symbol
+        int gapSize = DimensionUtils.sp2px(tvCurrency.getContext(), 5);
+
+        if (position == Currency.Position.before) {
+            tvCurrency.setPaddingRelative(0, 0, hasGap ? gapSize : 0, 0);
+        }
+        else {
+            tvCurrency.setPaddingRelative(hasGap ? gapSize : 0, 0, 0, 0);
+        }
+    }
+    private void setCurrencyString(String currency) {
+        if ((currency == null) || currency.isEmpty()) {
+            tvCurrency.setText(R.string.currency_symbol);
+            tvCurrency.setTextColor(0x7f000000 + (0x00ffffff & Colors.defaultTextColor));
+        }
+        else {
+            tvCurrency.setText(currency);
+            tvCurrency.setTextColor(Colors.defaultTextColor);
+        }
+    }
+    private void setCurrency(Currency currency) {
+        setCurrencyString((currency == null) ? null : currency.getName());
     }
     private void setEditable(Boolean editable) {
         tvDate.setEnabled(editable);
@@ -260,6 +429,33 @@ class NewTransactionItemHolder extends RecyclerView.ViewHolder
         tvAccount.setEnabled(editable);
         tvAmount.setEnabled(editable);
     }
+    private void setCommentVisible(Boolean visible) {
+        if (visible) {
+            // showing; show the comment view and align the comment button to it
+            tvComment.setVisibility(View.VISIBLE);
+            tvComment.requestFocus();
+            ConstraintLayout.LayoutParams lp =
+                    (ConstraintLayout.LayoutParams) commentButton.getLayoutParams();
+            lp.bottomToBottom = R.id.comment;
+
+            commentButton.setLayoutParams(lp);
+        }
+        else {
+            // hiding; hide the comment comment view and align amounts layout under it
+            tvComment.setVisibility(View.GONE);
+            ConstraintLayout.LayoutParams lp =
+                    (ConstraintLayout.LayoutParams) commentButton.getLayoutParams();
+            lp.bottomToBottom = R.id.ntr_account;   // R.id.parent doesn't work here
+
+            commentButton.setLayoutParams(lp);
+        }
+    }
+    private void setComment(String comment) {
+        if ((comment != null) && !comment.isEmpty())
+            commentButton.setBackgroundResource(R.drawable.ic_comment_black_24dp);
+        else
+            commentButton.setBackgroundResource(R.drawable.ic_comment_gray_24dp);
+    }
     private void beginUpdates() {
         if (inUpdate)
             throw new RuntimeException("Already in update mode");
@@ -293,30 +489,38 @@ class NewTransactionItemHolder extends RecyclerView.ViewHolder
                     item.setDescription(String.valueOf(tvDescription.getText()));
                     break;
                 case transactionRow:
-                    item.getAccount()
-                        .setAccountName(String.valueOf(tvAccount.getText()));
+                    final LedgerTransactionAccount account = item.getAccount();
+                    account.setAccountName(String.valueOf(tvAccount.getText()));
+
+                    item.setComment(String.valueOf(tvComment.getText()));
 
                     // TODO: handle multiple amounts
                     String amount = String.valueOf(tvAmount.getText());
                     amount = amount.trim();
 
                     if (amount.isEmpty()) {
-                        item.getAccount()
-                            .resetAmount();
+                        account.resetAmount();
+                        account.setCurrency(null);
                     }
                     else {
                         try {
                             amount = amount.replace(decimalSeparator, decimalDot);
-                            item.getAccount()
-                                .setAmount(Float.parseFloat(amount));
+                            account.setAmount(Float.parseFloat(amount));
                         }
                         catch (NumberFormatException e) {
                             Logger.debug("new-trans", String.format(
                                     "assuming amount is not set due to number format exception. " +
                                     "input was '%s'", amount));
-                            item.getAccount()
-                                .resetAmount();
+                            account.resetAmount();
                         }
+                        final String curr = String.valueOf(tvCurrency.getText());
+                        if (curr.equals(tvCurrency.getContext()
+                                                  .getResources()
+                                                  .getString(R.string.currency_symbol)) ||
+                            curr.isEmpty())
+                            account.setCurrency(null);
+                        else
+                            account.setCurrency(curr);
                     }
 
                     break;
@@ -330,6 +534,7 @@ class NewTransactionItemHolder extends RecyclerView.ViewHolder
     }
     private void pickTransactionDate() {
         DatePickerFragment picker = new DatePickerFragment();
+        picker.setFutureDates(mProfile.getFutureDates());
         picker.setOnDatePickedListener(this);
         picker.show(((NewTransactionActivity) tvDate.getContext()).getSupportFragmentManager(),
                 "datePicker");
@@ -348,10 +553,17 @@ class NewTransactionItemHolder extends RecyclerView.ViewHolder
                 this.item.stopObservingDescription(descriptionObserver);
                 this.item.stopObservingAmountHint(hintObserver);
                 this.item.stopObservingEditableFlag(editableObserver);
+                this.item.stopObservingCommentVisible(commentVisibleObserver);
+                this.item.stopObservingComment(commentObserver);
                 this.item.getModel()
                          .stopObservingFocusedItem(focusedAccountObserver);
                 this.item.getModel()
                          .stopObservingAccountCount(accountCountObserver);
+                Data.currencySymbolPosition.removeObserver(currencyPositionObserver);
+                Data.currencyGap.removeObserver(currencyGapObserver);
+                Data.locale.removeObserver(localeObserver);
+                this.item.stopObservingCurrency(currencyObserver);
+                this.item.getModel().showCurrency.removeObserver(showCurrencyObserver);
 
                 this.item = null;
             }
@@ -368,6 +580,7 @@ class NewTransactionItemHolder extends RecyclerView.ViewHolder
                 case transactionRow:
                     LedgerTransactionAccount acc = item.getAccount();
                     tvAccount.setText(acc.getAccountName());
+                    tvComment.setText(acc.getComment());
                     if (acc.isAmountSet()) {
                         tvAmount.setText(String.format("%1.2f", acc.getAmount()));
                     }
@@ -376,6 +589,7 @@ class NewTransactionItemHolder extends RecyclerView.ViewHolder
 //                        tvAmount.setHint(R.string.zero_amount);
                     }
                     tvAmount.setHint(item.getAmountHint());
+                    setCurrencyString(acc.getCurrency());
                     lHead.setVisibility(View.GONE);
                     lAccount.setVisibility(View.VISIBLE);
                     lPadding.setVisibility(View.GONE);
@@ -397,10 +611,17 @@ class NewTransactionItemHolder extends RecyclerView.ViewHolder
                 item.observeDescription(activity, descriptionObserver);
                 item.observeAmountHint(activity, hintObserver);
                 item.observeEditableFlag(activity, editableObserver);
+                item.observeCommentVisible(activity, commentVisibleObserver);
+                item.observeComment(activity, commentObserver);
                 item.getModel()
                     .observeFocusedItem(activity, focusedAccountObserver);
                 item.getModel()
                     .observeAccountCount(activity, accountCountObserver);
+                Data.currencySymbolPosition.observe(activity, currencyPositionObserver);
+                Data.currencyGap.observe(activity, currencyGapObserver);
+                Data.locale.observe(activity, localeObserver);
+                item.observeCurrency(activity, currencyObserver);
+                item.getModel().showCurrency.observe(activity, showCurrencyObserver);
             }
         }
         finally {
@@ -418,6 +639,10 @@ class NewTransactionItemHolder extends RecyclerView.ViewHolder
 
     }
     @Override
+    public void onCurrencySelected(Currency item) {
+        this.item.setCurrency(item);
+    }
+    @Override
     public void descriptionSelected(String description) {
         tvAccount.setText(description);
         tvAmount.requestFocus(View.FOCUS_FORWARD);