]> git.ktnx.net Git - mobile-ledger.git/blobdiff - app/src/main/java/net/ktnx/mobileledger/ui/profiles/ProfileDetailFragment.java
Migrate from Switch to SwitchMaterial
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / ui / profiles / ProfileDetailFragment.java
index 68758402379ee5af316be287e0041861a2514618..672acf0ec4a58cb37d7ba0a897c8065b9433feae 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright © 2019 Damyan Ivanov.
+ * Copyright © 2020 Damyan Ivanov.
  * This file is part of MoLe.
  * MoLe is free software: you can distribute it and/or modify it
  * under the term of the GNU General Public License as published by
@@ -23,15 +23,12 @@ import android.graphics.Typeface;
 import android.os.Bundle;
 import android.text.Editable;
 import android.text.TextWatcher;
-import android.view.LayoutInflater;
 import android.view.Menu;
 import android.view.MenuInflater;
 import android.view.MenuItem;
 import android.view.View;
-import android.view.ViewGroup;
 import android.widget.LinearLayout;
 import android.widget.PopupMenu;
-import android.widget.Switch;
 import android.widget.TextView;
 
 import androidx.annotation.NonNull;
@@ -44,6 +41,7 @@ import androidx.lifecycle.ViewModelProvider;
 
 import com.google.android.material.appbar.CollapsingToolbarLayout;
 import com.google.android.material.floatingactionbutton.FloatingActionButton;
+import com.google.android.material.switchmaterial.SwitchMaterial;
 import com.google.android.material.textfield.TextInputLayout;
 
 import net.ktnx.mobileledger.BuildConfig;
@@ -63,6 +61,8 @@ import org.jetbrains.annotations.NotNull;
 import java.net.MalformedURLException;
 import java.net.URL;
 import java.util.ArrayList;
+import java.util.Objects;
+import java.util.UUID;
 
 import static net.ktnx.mobileledger.utils.Logger.debug;
 
@@ -80,16 +80,13 @@ public class ProfileDetailFragment extends Fragment {
     public static final String ARG_HUE = "hue";
     @NonNls
 
-    /**
-     * The content this fragment is presenting.
-     */ private MobileLedgerProfile mProfile;
+    private MobileLedgerProfile mProfile;
     private TextView url;
     private TextView defaultCommodity;
-    private View defaultCommodityLayout;
     private boolean defaultCommoditySet;
     private TextInputLayout urlLayout;
     private LinearLayout authParams;
-    private Switch useAuthentication;
+    private SwitchMaterial useAuthentication;
     private TextView userName;
     private TextInputLayout userNameLayout;
     private TextView password;
@@ -97,11 +94,9 @@ public class ProfileDetailFragment extends Fragment {
     private TextView profileName;
     private TextInputLayout profileNameLayout;
     private TextView preferredAccountsFilter;
-    private TextInputLayout preferredAccountsFilterLayout;
     private View huePickerView;
     private View insecureWarningText;
     private TextView futureDatesText;
-    private View futureDatesLayout;
     private TextView apiVersionText;
     private boolean syncingModelFromUI = false;
     /**
@@ -109,6 +104,7 @@ public class ProfileDetailFragment extends Fragment {
      * fragment (e.g. upon screen orientation changes).
      */
     public ProfileDetailFragment() {
+        super(R.layout.profile_detail);
     }
     @Override
     public void onCreateOptionsMenu(@NotNull Menu menu, @NotNull MenuInflater inflater) {
@@ -116,35 +112,8 @@ public class ProfileDetailFragment extends Fragment {
         super.onCreateOptionsMenu(menu, inflater);
         inflater.inflate(R.menu.profile_details, menu);
         final MenuItem menuDeleteProfile = menu.findItem(R.id.menuDelete);
-        menuDeleteProfile.setOnMenuItemClickListener(item -> {
-            AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
-            builder.setTitle(mProfile.getName());
-            builder.setMessage(R.string.remove_profile_dialog_message);
-            builder.setPositiveButton(R.string.Remove, (dialog, which) -> {
-                debug("profiles",
-                        String.format("[fragment] removing profile %s", mProfile.getUuid()));
-                mProfile.removeFromDB();
-                ArrayList<MobileLedgerProfile> oldList = Data.profiles.getValue();
-                if (oldList == null)
-                    throw new AssertionError();
-                ArrayList<MobileLedgerProfile> newList = new ArrayList<>(oldList);
-                newList.remove(mProfile);
-                Data.profiles.setValue(newList);
-                if (mProfile.equals(Data.profile.getValue())) {
-                    debug("profiles", "[fragment] setting current profile to 0");
-                    Data.setCurrentProfile(newList.get(0));
-                }
-
-                final FragmentActivity activity = getActivity();
-                if (activity != null)
-                    activity.finish();
-            });
-            builder.show();
-            return false;
-        });
+        menuDeleteProfile.setOnMenuItemClickListener(item -> onDeleteProfile());
         final ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
-        menuDeleteProfile.setVisible(
-                (mProfile != null) && (profiles != null) && (profiles.size() > 1));
 
         if (BuildConfig.DEBUG) {
             final MenuItem menuWipeProfileData = menu.findItem(R.id.menuWipeData);
@@ -152,29 +121,53 @@ public class ProfileDetailFragment extends Fragment {
             menuWipeProfileData.setVisible(mProfile != null);
         }
     }
+    private boolean onDeleteProfile() {
+        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
+        builder.setTitle(mProfile.getName());
+        builder.setMessage(R.string.remove_profile_dialog_message);
+        builder.setPositiveButton(R.string.Remove, (dialog, which) -> {
+            debug("profiles", String.format("[fragment] removing profile %s", mProfile.getUuid()));
+            mProfile.removeFromDB();
+            ArrayList<MobileLedgerProfile> oldList = Data.profiles.getValue();
+            if (oldList == null)
+                throw new AssertionError();
+            ArrayList<MobileLedgerProfile> newList = new ArrayList<>(oldList);
+            newList.remove(mProfile);
+            Data.profiles.setValue(newList);
+            if (mProfile.equals(Data.getProfile())) {
+                debug("profiles", "[fragment] setting current profile to 0");
+                Data.setCurrentProfile(newList.get(0));
+            }
+
+            final FragmentActivity activity = getActivity();
+            if (activity != null)
+                activity.finish();
+        });
+        builder.show();
+        return false;
+    }
     private boolean onWipeDataMenuClicked() {
         // this is a development option, so no confirmation
         mProfile.wipeAllData();
-        if (mProfile.equals(Data.profile.getValue()))
+        if (mProfile.equals(Data.getProfile()))
             triggerProfileChange();
         return true;
     }
     private void triggerProfileChange() {
         int index = Data.getProfileIndex(mProfile);
         MobileLedgerProfile newProfile = new MobileLedgerProfile(mProfile);
-        final ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
-        if (profiles == null)
-            throw new AssertionError();
+        final ArrayList<MobileLedgerProfile> profiles =
+                Objects.requireNonNull(Data.profiles.getValue());
         profiles.set(index, newProfile);
 
         ProfilesRecyclerViewAdapter viewAdapter = ProfilesRecyclerViewAdapter.getInstance();
         if (viewAdapter != null)
             viewAdapter.notifyItemChanged(index);
 
-        if (mProfile.equals(Data.profile.getValue()))
-            Data.profile.setValue(newProfile);
+        if (mProfile.equals(Data.getProfile()))
+            Data.setCurrentProfile(newProfile);
     }
-    private void hookTextChangeSyncRoutine(TextView view, TextChangeSyncProc syncRoutine) {
+    private void hookTextChangeSyncRoutine(TextView view, TextChangeSyncRoutine syncRoutine) {
         view.addTextChangedListener(new TextWatcher() {
             @Override
             public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@@ -185,8 +178,8 @@ public class ProfileDetailFragment extends Fragment {
         });
     }
     @Override
-    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
-        super.onActivityCreated(savedInstanceState);
+    public void onViewCreated(@NotNull View view, @Nullable Bundle savedInstanceState) {
+        super.onViewCreated(view, savedInstanceState);
         Activity context = getActivity();
         if (context == null)
             return;
@@ -240,23 +233,23 @@ public class ProfileDetailFragment extends Fragment {
 
         urlLayout = context.findViewById(R.id.url_layout);
 
-        defaultCommodityLayout = context.findViewById(R.id.default_commodity_layout);
-        defaultCommodityLayout.setOnClickListener(v -> {
-            CurrencySelectorFragment cpf = CurrencySelectorFragment.newInstance(
-                    CurrencySelectorFragment.DEFAULT_COLUMN_COUNT, false);
-            cpf.setOnCurrencySelectedListener(model::setDefaultCommodity);
-            final AppCompatActivity activity = (AppCompatActivity) v.getContext();
-            cpf.show(activity.getSupportFragmentManager(), "currency-selector");
-        });
+        context.findViewById(R.id.default_commodity_layout)
+               .setOnClickListener(v -> {
+                   CurrencySelectorFragment cpf = CurrencySelectorFragment.newInstance(
+                           CurrencySelectorFragment.DEFAULT_COLUMN_COUNT, false);
+                   cpf.setOnCurrencySelectedListener(model::setDefaultCommodity);
+                   final AppCompatActivity activity = (AppCompatActivity) v.getContext();
+                   cpf.show(activity.getSupportFragmentManager(), "currency-selector");
+               });
 
-        Switch showCommodityByDefault = context.findViewById(R.id.profile_show_commodity);
+        SwitchMaterial showCommodityByDefault = context.findViewById(R.id.profile_show_commodity);
         showCommodityByDefault.setOnCheckedChangeListener(
                 (buttonView, isChecked) -> model.setShowCommodityByDefault(isChecked));
         model.observeShowCommodityByDefault(viewLifecycleOwner, showCommodityByDefault::setChecked);
 
         View postingSubItems = context.findViewById(R.id.posting_sub_items);
 
-        Switch postingPermitted = context.findViewById(R.id.profile_permit_posting);
+        SwitchMaterial postingPermitted = context.findViewById(R.id.profile_permit_posting);
         model.observePostingPermitted(viewLifecycleOwner, isChecked -> {
             postingPermitted.setChecked(isChecked);
             postingSubItems.setVisibility(isChecked ? View.VISIBLE : View.GONE);
@@ -264,16 +257,13 @@ public class ProfileDetailFragment extends Fragment {
         postingPermitted.setOnCheckedChangeListener(
                 ((buttonView, isChecked) -> model.setPostingPermitted(isChecked)));
 
-        Switch showCommentsByDefault = context.findViewById(R.id.profile_show_comments);
-        model.observeShowCommentsByDefault(viewLifecycleOwner, isChecked -> {
-            showCommentsByDefault.setChecked(isChecked);
-        });
+        SwitchMaterial showCommentsByDefault = context.findViewById(R.id.profile_show_comments);
+        model.observeShowCommentsByDefault(viewLifecycleOwner, showCommentsByDefault::setChecked);
         showCommentsByDefault.setOnCheckedChangeListener(
                 ((buttonView, isChecked) -> model.setShowCommentsByDefault(isChecked)));
 
         defaultCommodity = context.findViewById(R.id.default_commodity_text);
 
-        futureDatesLayout = context.findViewById(R.id.future_dates_layout);
         futureDatesText = context.findViewById(R.id.future_dates_text);
         context.findViewById(R.id.future_dates_layout)
                .setOnClickListener(v -> {
@@ -290,36 +280,31 @@ public class ProfileDetailFragment extends Fragment {
                 v -> futureDatesText.setText(v.getText(getResources())));
 
         apiVersionText = context.findViewById(R.id.api_version_text);
-        model.observeApiVersion(viewLifecycleOwner, apiVer -> {
-            apiVersionText.setText(apiVer.getDescription(getResources()));
+        model.observeApiVersion(viewLifecycleOwner,
+                apiVer -> apiVersionText.setText(apiVer.getDescription(getResources())));
+        context.findViewById(R.id.api_version_label)
+               .setOnClickListener(this::chooseAPIVersion);
+        context.findViewById(R.id.api_version_text)
+               .setOnClickListener(this::chooseAPIVersion);
+
+        TextView detectedApiVersion = context.findViewById(R.id.detected_version_text);
+        model.observeDetectedVersion(viewLifecycleOwner, ver -> {
+            if (ver == null)
+                detectedApiVersion.setText(context.getResources()
+                                                  .getString(R.string.api_version_unknown_label));
+            else if (ver.isPre_1_20())
+                detectedApiVersion.setText(context.getResources()
+                                                  .getString(R.string.api_pre_1_19));
+            else
+                detectedApiVersion.setText(ver.toString());
         });
-        context.findViewById(R.id.api_version_layout)
-               .setOnClickListener(v -> {
-                   MenuInflater mi = new MenuInflater(context);
-                   PopupMenu menu = new PopupMenu(context, v);
-                   menu.inflate(R.menu.api_version);
-                   menu.setOnMenuItemClickListener(item -> {
-                       SendTransactionTask.API apiVer;
-                       switch (item.getItemId()) {
-                           case R.id.api_version_menu_html:
-                               apiVer = SendTransactionTask.API.html;
-                               break;
-                           case R.id.api_version_menu_post_1_14:
-                               apiVer = SendTransactionTask.API.post_1_14;
-                               break;
-                           case R.id.api_version_menu_pre_1_15:
-                               apiVer = SendTransactionTask.API.pre_1_15;
-                               break;
-                           case R.id.api_version_menu_auto:
-                           default:
-                               apiVer = SendTransactionTask.API.auto;
-                       }
-                       model.setApiVersion(apiVer);
-                       apiVersionText.setText(apiVer.getDescription(getResources()));
-                       return true;
-                   });
-                   menu.show();
-               });
+        detectedApiVersion.setOnClickListener(v -> model.triggerVersionDetection());
+        final View detectButton = context.findViewById(R.id.api_version_detect_button);
+        detectButton.setOnClickListener(v -> model.triggerVersionDetection());
+        model.observeDetectingHledgerVersion(viewLifecycleOwner, running -> {
+            detectButton.setVisibility(running ? View.VISIBLE : View.INVISIBLE);
+        });
+
         authParams = context.findViewById(R.id.auth_params);
 
         useAuthentication = context.findViewById(R.id.enable_http_auth);
@@ -364,8 +349,6 @@ public class ProfileDetailFragment extends Fragment {
                 preferredAccountsFilter.setText(text);
         });
         hookTextChangeSyncRoutine(preferredAccountsFilter, model::setPreferredAccountsFilter);
-        preferredAccountsFilterLayout =
-                context.findViewById(R.id.preferred_accounts_accounts_filter_layout);
 
         insecureWarningText = context.findViewById(R.id.insecure_scheme_text);
 
@@ -392,14 +375,41 @@ public class ProfileDetailFragment extends Fragment {
 
         huePickerView.setOnClickListener(v -> {
             HueRingDialog d = new HueRingDialog(ProfileDetailFragment.this.requireContext(),
-                    model.initialThemeHue,
-                    (Integer) v.getTag());
+                    model.initialThemeHue, (Integer) v.getTag());
             d.show();
             d.setColorSelectedListener(model::setThemeId);
         });
 
         profileName.requestFocus();
     }
+    private void chooseAPIVersion(View v) {
+        Activity context = getActivity();
+        ProfileDetailModel model = getModel();
+        MenuInflater mi = new MenuInflater(context);
+        PopupMenu menu = new PopupMenu(context, v);
+        menu.inflate(R.menu.api_version);
+        menu.setOnMenuItemClickListener(item -> {
+            SendTransactionTask.API apiVer;
+            switch (item.getItemId()) {
+                case R.id.api_version_menu_html:
+                    apiVer = SendTransactionTask.API.html;
+                    break;
+                case R.id.api_version_menu_post_1_14:
+                    apiVer = SendTransactionTask.API.post_1_14;
+                    break;
+                case R.id.api_version_menu_pre_1_15:
+                    apiVer = SendTransactionTask.API.pre_1_15;
+                    break;
+                case R.id.api_version_menu_auto:
+                default:
+                    apiVer = SendTransactionTask.API.auto;
+            }
+            model.setApiVersion(apiVer);
+            apiVersionText.setText(apiVer.getDescription(getResources()));
+            return true;
+        });
+        menu.show();
+    }
     private MobileLedgerProfile.FutureDates futureDatesSettingFromMenuItemId(int itemId) {
         switch (itemId) {
             case R.id.menu_future_dates_7:
@@ -431,41 +441,48 @@ public class ProfileDetailFragment extends Fragment {
             return;
 
         ProfileDetailModel model = getModel();
+        final ArrayList<MobileLedgerProfile> profiles =
+                Objects.requireNonNull(Data.profiles.getValue());
 
         if (mProfile != null) {
+            int pos = Data.profiles.getValue()
+                                   .indexOf(mProfile);
+            mProfile = new MobileLedgerProfile(mProfile);
             model.updateProfile(mProfile);
-//                debug("profiles", String.format("Selected item is %d", mProfile.getThemeHue()));
             mProfile.storeInDB();
             debug("profiles", "profile stored in DB");
-            triggerProfileChange();
+            profiles.set(pos, mProfile);
+//                debug("profiles", String.format("Selected item is %d", mProfile.getThemeHue()));
+
+            final MobileLedgerProfile currentProfile = Data.getProfile();
+            if (mProfile.getUuid()
+                        .equals(currentProfile.getUuid()))
+            {
+                Data.setCurrentProfile(mProfile);
+            }
+
+            ProfilesRecyclerViewAdapter viewAdapter = ProfilesRecyclerViewAdapter.getInstance();
+            if (viewAdapter != null)
+                viewAdapter.notifyItemChanged(pos);
         }
         else {
-            mProfile = new MobileLedgerProfile();
+            mProfile = new MobileLedgerProfile(String.valueOf(UUID.randomUUID()));
             model.updateProfile(mProfile);
             mProfile.storeInDB();
-            final ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
-            if (profiles == null)
-                throw new AssertionError();
-            ArrayList<MobileLedgerProfile> newList = new ArrayList<>(profiles);
+            final ArrayList<MobileLedgerProfile> newList = new ArrayList<>(profiles);
             newList.add(mProfile);
             Data.profiles.setValue(newList);
             MobileLedgerProfile.storeProfilesOrder();
 
             // first profile ever?
             if (newList.size() == 1)
-                Data.profile.setValue(mProfile);
+                Data.setCurrentProfile(mProfile);
         }
 
         Activity activity = getActivity();
         if (activity != null)
             activity.finish();
     }
-    @Override
-    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
-                             Bundle savedInstanceState) {
-
-        return inflater.inflate(R.layout.profile_detail, container, false);
-    }
     private boolean checkUrlValidity() {
         boolean valid = true;
 
@@ -593,9 +610,9 @@ public class ProfileDetailFragment extends Fragment {
     private void setDefaultCommodity(@NonNull @NotNull String name) {
         defaultCommoditySet = true;
         defaultCommodity.setText(name);
-        defaultCommodity.setTypeface(defaultCommodity.getTypeface(), Typeface.BOLD);
+        defaultCommodity.setTypeface(Typeface.DEFAULT);
     }
-    interface TextChangeSyncProc {
+    interface TextChangeSyncRoutine {
         void onTextChanged(String text);
     }
 }