]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/profiles/ProfileDetailFragment.java
shuffle some classes under proper packages
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / ui / profiles / ProfileDetailFragment.java
1 /*
2  * Copyright © 2021 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.profiles;
19
20 import android.app.Activity;
21 import android.app.AlertDialog;
22 import android.graphics.Typeface;
23 import android.os.Bundle;
24 import android.text.Editable;
25 import android.text.TextWatcher;
26 import android.view.LayoutInflater;
27 import android.view.Menu;
28 import android.view.MenuInflater;
29 import android.view.MenuItem;
30 import android.view.View;
31 import android.view.ViewGroup;
32 import android.widget.PopupMenu;
33 import android.widget.TextView;
34
35 import androidx.annotation.NonNull;
36 import androidx.annotation.Nullable;
37 import androidx.appcompat.app.AppCompatActivity;
38 import androidx.fragment.app.Fragment;
39 import androidx.fragment.app.FragmentActivity;
40 import androidx.lifecycle.LifecycleOwner;
41 import androidx.lifecycle.ViewModelProvider;
42
43 import com.google.android.material.appbar.CollapsingToolbarLayout;
44 import com.google.android.material.floatingactionbutton.FloatingActionButton;
45 import com.google.android.material.textfield.TextInputLayout;
46
47 import net.ktnx.mobileledger.BuildConfig;
48 import net.ktnx.mobileledger.R;
49 import net.ktnx.mobileledger.databinding.ProfileDetailBinding;
50 import net.ktnx.mobileledger.json.API;
51 import net.ktnx.mobileledger.model.Data;
52 import net.ktnx.mobileledger.model.MobileLedgerProfile;
53 import net.ktnx.mobileledger.ui.CurrencySelectorFragment;
54 import net.ktnx.mobileledger.ui.HueRingDialog;
55 import net.ktnx.mobileledger.utils.Colors;
56 import net.ktnx.mobileledger.utils.Misc;
57
58 import org.jetbrains.annotations.NonNls;
59 import org.jetbrains.annotations.NotNull;
60
61 import java.net.MalformedURLException;
62 import java.net.URL;
63 import java.util.ArrayList;
64 import java.util.Objects;
65 import java.util.UUID;
66
67 import static net.ktnx.mobileledger.utils.Logger.debug;
68
69 /**
70  * A fragment representing a single Profile detail screen.
71  * a {@link ProfileDetailActivity}
72  * on handsets.
73  */
74 public class ProfileDetailFragment extends Fragment {
75     /**
76      * The fragment argument representing the item ID that this fragment
77      * represents.
78      */
79     public static final String ARG_ITEM_ID = "item_id";
80     public static final String ARG_HUE = "hue";
81     @NonNls
82
83     private MobileLedgerProfile mProfile;
84     private boolean defaultCommoditySet;
85     private boolean syncingModelFromUI = false;
86     private ProfileDetailBinding binding;
87     /**
88      * Mandatory empty constructor for the fragment manager to instantiate the
89      * fragment (e.g. upon screen orientation changes).
90      */
91     public ProfileDetailFragment() {
92         super(R.layout.profile_detail);
93     }
94     @Override
95     public void onCreateOptionsMenu(@NotNull Menu menu, @NotNull MenuInflater inflater) {
96         debug("profiles", "[fragment] Creating profile details options menu");
97         super.onCreateOptionsMenu(menu, inflater);
98         inflater.inflate(R.menu.profile_details, menu);
99         final MenuItem menuDeleteProfile = menu.findItem(R.id.menuDelete);
100         menuDeleteProfile.setOnMenuItemClickListener(item -> onDeleteProfile());
101         final ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
102
103         if (BuildConfig.DEBUG) {
104             final MenuItem menuWipeProfileData = menu.findItem(R.id.menuWipeData);
105             menuWipeProfileData.setOnMenuItemClickListener(ignored -> onWipeDataMenuClicked());
106             menuWipeProfileData.setVisible(mProfile != null);
107         }
108     }
109     private boolean onDeleteProfile() {
110         AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
111         builder.setTitle(mProfile.getName());
112         builder.setMessage(R.string.remove_profile_dialog_message);
113         builder.setPositiveButton(R.string.Remove, (dialog, which) -> {
114             debug("profiles", String.format("[fragment] removing profile %s", mProfile.getUuid()));
115             mProfile.removeFromDB();
116             ArrayList<MobileLedgerProfile> oldList = Data.profiles.getValue();
117             if (oldList == null)
118                 throw new AssertionError();
119             ArrayList<MobileLedgerProfile> newList = new ArrayList<>(oldList);
120             newList.remove(mProfile);
121             Data.profiles.setValue(newList);
122             if (mProfile.equals(Data.getProfile())) {
123                 debug("profiles", "[fragment] setting current profile to 0");
124                 Data.setCurrentProfile(newList.get(0));
125             }
126
127             final FragmentActivity activity = getActivity();
128             if (activity != null)
129                 activity.finish();
130         });
131         builder.show();
132         return false;
133     }
134     private boolean onWipeDataMenuClicked() {
135         // this is a development option, so no confirmation
136         mProfile.wipeAllData();
137         if (mProfile.equals(Data.getProfile()))
138             triggerProfileChange();
139         return true;
140     }
141     private void triggerProfileChange() {
142         int index = Data.getProfileIndex(mProfile);
143         MobileLedgerProfile newProfile = new MobileLedgerProfile(mProfile);
144         final ArrayList<MobileLedgerProfile> profiles =
145                 Objects.requireNonNull(Data.profiles.getValue());
146         profiles.set(index, newProfile);
147
148         ProfilesRecyclerViewAdapter viewAdapter = ProfilesRecyclerViewAdapter.getInstance();
149         if (viewAdapter != null)
150             viewAdapter.notifyItemChanged(index);
151
152         if (mProfile.equals(Data.getProfile()))
153             Data.setCurrentProfile(newProfile);
154     }
155     private void hookTextChangeSyncRoutine(TextView view, TextChangeSyncRoutine syncRoutine) {
156         view.addTextChangedListener(new TextWatcher() {
157             @Override
158             public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
159             @Override
160             public void onTextChanged(CharSequence s, int start, int before, int count) {}
161             @Override
162             public void afterTextChanged(Editable s) { syncRoutine.onTextChanged(s.toString());}
163         });
164     }
165     @Nullable
166     @Override
167     public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
168                              @Nullable Bundle savedInstanceState) {
169         binding = ProfileDetailBinding.inflate(inflater, container, false);
170
171         return binding.getRoot();
172     }
173     @Override
174     public void onViewCreated(@NotNull View view, @Nullable Bundle savedInstanceState) {
175         super.onViewCreated(view, savedInstanceState);
176         Activity context = getActivity();
177         if (context == null)
178             return;
179
180         if ((getArguments() != null) && getArguments().containsKey(ARG_ITEM_ID)) {
181             int index = getArguments().getInt(ARG_ITEM_ID, -1);
182             ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
183             if ((profiles != null) && (index != -1) && (index < profiles.size()))
184                 mProfile = profiles.get(index);
185
186             Activity activity = this.getActivity();
187             if (activity == null)
188                 throw new AssertionError();
189             CollapsingToolbarLayout appBarLayout = activity.findViewById(R.id.toolbar_layout);
190             if (appBarLayout != null) {
191                 if (mProfile != null)
192                     appBarLayout.setTitle(mProfile.getName());
193                 else
194                     appBarLayout.setTitle(getResources().getString(R.string.new_profile_title));
195             }
196         }
197
198         final LifecycleOwner viewLifecycleOwner = getViewLifecycleOwner();
199         final ProfileDetailModel model = getModel();
200
201         model.observeDefaultCommodity(viewLifecycleOwner, c -> {
202             if (c != null)
203                 setDefaultCommodity(c.getName());
204             else
205                 resetDefaultCommodity();
206         });
207
208         FloatingActionButton fab = context.findViewById(R.id.fab);
209         fab.setOnClickListener(v -> onSaveFabClicked());
210
211         hookTextChangeSyncRoutine(binding.profileName, model::setProfileName);
212         model.observeProfileName(viewLifecycleOwner, pn -> {
213             if (!Misc.equalStrings(pn, Misc.nullIsEmpty(binding.profileName.getText())))
214                 binding.profileName.setText(pn);
215         });
216
217         hookTextChangeSyncRoutine(binding.url, model::setUrl);
218         model.observeUrl(viewLifecycleOwner, u -> {
219             if (!Misc.equalStrings(u, Misc.nullIsEmpty(binding.url.getText())))
220                 binding.url.setText(u);
221         });
222
223         binding.defaultCommodityLayout.setOnClickListener(v -> {
224             CurrencySelectorFragment cpf = CurrencySelectorFragment.newInstance(
225                     CurrencySelectorFragment.DEFAULT_COLUMN_COUNT, false);
226             cpf.setOnCurrencySelectedListener(model::setDefaultCommodity);
227             final AppCompatActivity activity = (AppCompatActivity) v.getContext();
228             cpf.show(activity.getSupportFragmentManager(), "currency-selector");
229         });
230
231         binding.profileShowCommodity.setOnCheckedChangeListener(
232                 (buttonView, isChecked) -> model.setShowCommodityByDefault(isChecked));
233         model.observeShowCommodityByDefault(viewLifecycleOwner,
234                 binding.profileShowCommodity::setChecked);
235
236         model.observePostingPermitted(viewLifecycleOwner, isChecked -> {
237             binding.profilePermitPosting.setChecked(isChecked);
238             binding.postingSubItems.setVisibility(isChecked ? View.VISIBLE : View.GONE);
239         });
240         binding.profilePermitPosting.setOnCheckedChangeListener(
241                 ((buttonView, isChecked) -> model.setPostingPermitted(isChecked)));
242
243         model.observeShowCommentsByDefault(viewLifecycleOwner,
244                 binding.profileShowComments::setChecked);
245         binding.profileShowComments.setOnCheckedChangeListener(
246                 ((buttonView, isChecked) -> model.setShowCommentsByDefault(isChecked)));
247
248         binding.futureDatesLayout.setOnClickListener(v -> {
249             MenuInflater mi = new MenuInflater(context);
250             PopupMenu menu = new PopupMenu(context, v);
251             menu.inflate(R.menu.future_dates);
252             menu.setOnMenuItemClickListener(item -> {
253                 model.setFutureDates(futureDatesSettingFromMenuItemId(item.getItemId()));
254                 return true;
255             });
256             menu.show();
257         });
258         model.observeFutureDates(viewLifecycleOwner,
259                 v -> binding.futureDatesText.setText(v.getText(getResources())));
260
261         model.observeApiVersion(viewLifecycleOwner,
262                 apiVer -> binding.apiVersionText.setText(apiVer.getDescription(getResources())));
263         binding.apiVersionLabel.setOnClickListener(this::chooseAPIVersion);
264         binding.apiVersionText.setOnClickListener(this::chooseAPIVersion);
265
266         binding.serverVersionLabel.setOnClickListener(v -> model.triggerVersionDetection());
267         model.observeDetectedVersion(viewLifecycleOwner, ver -> {
268             if (ver == null)
269                 binding.detectedServerVersionText.setText(context.getResources()
270                                                                  .getString(
271                                                                          R.string.server_version_unknown_label));
272             else if (ver.isPre_1_20_1())
273                 binding.detectedServerVersionText.setText(context.getResources()
274                                                                  .getString(
275                                                                          R.string.detected_server_pre_1_20_1));
276             else
277                 binding.detectedServerVersionText.setText(ver.toString());
278         });
279         binding.detectedServerVersionText.setOnClickListener(v -> model.triggerVersionDetection());
280         binding.serverVersionDetectButton.setOnClickListener(v -> model.triggerVersionDetection());
281         model.observeDetectingHledgerVersion(viewLifecycleOwner,
282                 running -> binding.serverVersionDetectButton.setVisibility(
283                         running ? View.VISIBLE : View.INVISIBLE));
284
285         binding.enableHttpAuth.setOnCheckedChangeListener((buttonView, isChecked) -> {
286             boolean wasOn = model.getUseAuthentication();
287             model.setUseAuthentication(isChecked);
288             if (!wasOn && isChecked)
289                 binding.authUserName.requestFocus();
290         });
291         model.observeUseAuthentication(viewLifecycleOwner, isChecked -> {
292             binding.enableHttpAuth.setChecked(isChecked);
293             binding.authParams.setVisibility(isChecked ? View.VISIBLE : View.GONE);
294             checkInsecureSchemeWithAuth();
295         });
296
297         model.observeUserName(viewLifecycleOwner, text -> {
298             if (!Misc.equalStrings(text, Misc.nullIsEmpty(binding.authUserName.getText())))
299                 binding.authUserName.setText(text);
300         });
301         hookTextChangeSyncRoutine(binding.authUserName, model::setAuthUserName);
302
303         model.observePassword(viewLifecycleOwner, text -> {
304             if (!Misc.equalStrings(text, Misc.nullIsEmpty(binding.password.getText())))
305                 binding.password.setText(text);
306         });
307         hookTextChangeSyncRoutine(binding.password, model::setAuthPassword);
308
309         model.observeThemeId(viewLifecycleOwner, themeId -> {
310             final int hue = (themeId == -1) ? Colors.DEFAULT_HUE_DEG : themeId;
311             final int profileColor = Colors.getPrimaryColorForHue(hue);
312             binding.btnPickRingColor.setBackgroundColor(profileColor);
313             binding.btnPickRingColor.setTag(hue);
314         });
315
316         model.observePreferredAccountsFilter(viewLifecycleOwner, text -> {
317             if (!Misc.equalStrings(text,
318                     Misc.nullIsEmpty(binding.preferredAccountsFilter.getText())))
319                 binding.preferredAccountsFilter.setText(text);
320         });
321         hookTextChangeSyncRoutine(binding.preferredAccountsFilter,
322                 model::setPreferredAccountsFilter);
323
324         hookClearErrorOnFocusListener(binding.profileName, binding.profileNameLayout);
325         hookClearErrorOnFocusListener(binding.url, binding.urlLayout);
326         hookClearErrorOnFocusListener(binding.authUserName, binding.authUserNameLayout);
327         hookClearErrorOnFocusListener(binding.password, binding.passwordLayout);
328
329         if (savedInstanceState == null) {
330             model.setValuesFromProfile(mProfile, getArguments().getInt(ARG_HUE, -1));
331         }
332         checkInsecureSchemeWithAuth();
333
334         binding.url.addTextChangedListener(new TextWatcher() {
335             @Override
336             public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
337             @Override
338             public void onTextChanged(CharSequence s, int start, int before, int count) {}
339             @Override
340             public void afterTextChanged(Editable s) {
341                 checkInsecureSchemeWithAuth();
342             }
343         });
344
345         binding.btnPickRingColor.setOnClickListener(v -> {
346             HueRingDialog d = new HueRingDialog(ProfileDetailFragment.this.requireContext(),
347                     model.initialThemeHue, (Integer) v.getTag());
348             d.show();
349             d.setColorSelectedListener(model::setThemeId);
350         });
351
352         binding.profileName.requestFocus();
353     }
354     private void chooseAPIVersion(View v) {
355         Activity context = getActivity();
356         ProfileDetailModel model = getModel();
357         MenuInflater mi = new MenuInflater(context);
358         PopupMenu menu = new PopupMenu(context, v);
359         menu.inflate(R.menu.api_version);
360         menu.setOnMenuItemClickListener(item -> {
361             API apiVer;
362             int itemId = item.getItemId();
363             if (itemId == R.id.api_version_menu_html) {
364                 apiVer = API.html;
365             }
366             else if (itemId == R.id.api_version_menu_1_19_1) {
367                 apiVer = API.v1_19_1;
368             }
369             else if (itemId == R.id.api_version_menu_1_15) {
370                 apiVer = API.v1_15;
371             }
372             else if (itemId == R.id.api_version_menu_1_14) {
373                 apiVer = API.v1_14;
374             }
375             else {
376                 apiVer = API.auto;
377             }
378             model.setApiVersion(apiVer);
379             binding.apiVersionText.setText(apiVer.getDescription(getResources()));
380             return true;
381         });
382         menu.show();
383     }
384     private MobileLedgerProfile.FutureDates futureDatesSettingFromMenuItemId(int itemId) {
385         if (itemId == R.id.menu_future_dates_7) {
386             return MobileLedgerProfile.FutureDates.OneWeek;
387         }
388         else if (itemId == R.id.menu_future_dates_14) {
389             return MobileLedgerProfile.FutureDates.TwoWeeks;
390         }
391         else if (itemId == R.id.menu_future_dates_30) {
392             return MobileLedgerProfile.FutureDates.OneMonth;
393         }
394         else if (itemId == R.id.menu_future_dates_60) {
395             return MobileLedgerProfile.FutureDates.TwoMonths;
396         }
397         else if (itemId == R.id.menu_future_dates_90) {
398             return MobileLedgerProfile.FutureDates.ThreeMonths;
399         }
400         else if (itemId == R.id.menu_future_dates_180) {
401             return MobileLedgerProfile.FutureDates.SixMonths;
402         }
403         else if (itemId == R.id.menu_future_dates_365) {
404             return MobileLedgerProfile.FutureDates.OneYear;
405         }
406         else if (itemId == R.id.menu_future_dates_all) {
407             return MobileLedgerProfile.FutureDates.All;
408         }
409         return MobileLedgerProfile.FutureDates.None;
410     }
411     @NotNull
412     private ProfileDetailModel getModel() {
413         return new ViewModelProvider(requireActivity()).get(ProfileDetailModel.class);
414     }
415     private void onSaveFabClicked() {
416         if (!checkValidity())
417             return;
418
419         ProfileDetailModel model = getModel();
420         final ArrayList<MobileLedgerProfile> profiles =
421                 Objects.requireNonNull(Data.profiles.getValue());
422
423         if (mProfile != null) {
424             int pos = Data.profiles.getValue()
425                                    .indexOf(mProfile);
426             mProfile = new MobileLedgerProfile(mProfile);
427             model.updateProfile(mProfile);
428             mProfile.storeInDB();
429             debug("profiles", "profile stored in DB");
430             profiles.set(pos, mProfile);
431 //                debug("profiles", String.format("Selected item is %d", mProfile.getThemeHue()));
432
433             final MobileLedgerProfile currentProfile = Data.getProfile();
434             if (mProfile.getUuid()
435                         .equals(currentProfile.getUuid()))
436             {
437                 Data.setCurrentProfile(mProfile);
438             }
439
440             ProfilesRecyclerViewAdapter viewAdapter = ProfilesRecyclerViewAdapter.getInstance();
441             if (viewAdapter != null)
442                 viewAdapter.notifyItemChanged(pos);
443         }
444         else {
445             mProfile = new MobileLedgerProfile(String.valueOf(UUID.randomUUID()));
446             model.updateProfile(mProfile);
447             mProfile.storeInDB();
448             final ArrayList<MobileLedgerProfile> newList = new ArrayList<>(profiles);
449             newList.add(mProfile);
450             Data.profiles.setValue(newList);
451             MobileLedgerProfile.storeProfilesOrder();
452
453             // first profile ever?
454             if (newList.size() == 1)
455                 Data.setCurrentProfile(mProfile);
456         }
457
458         Activity activity = getActivity();
459         if (activity != null)
460             activity.finish();
461     }
462     private boolean checkUrlValidity() {
463         boolean valid = true;
464
465         ProfileDetailModel model = getModel();
466
467         String val = model.getUrl()
468                           .trim();
469         if (val.isEmpty()) {
470             valid = false;
471             binding.urlLayout.setError(getResources().getText(R.string.err_profile_url_empty));
472         }
473         try {
474             URL url = new URL(val);
475             String host = url.getHost();
476             if (host == null || host.isEmpty())
477                 throw new MalformedURLException("Missing host");
478             String protocol = url.getProtocol()
479                                  .toUpperCase();
480             if (!protocol.equals("HTTP") && !protocol.equals("HTTPS")) {
481                 valid = false;
482                 binding.urlLayout.setError(getResources().getText(R.string.err_invalid_url));
483             }
484         }
485         catch (MalformedURLException e) {
486             valid = false;
487             binding.urlLayout.setError(getResources().getText(R.string.err_invalid_url));
488         }
489
490         return valid;
491     }
492     private void checkInsecureSchemeWithAuth() {
493         boolean showWarning = false;
494
495         final ProfileDetailModel model = getModel();
496
497         if (model.getUseAuthentication()) {
498             String urlText = model.getUrl();
499             if (urlText.startsWith("http") && !urlText.startsWith("https"))
500                 showWarning = true;
501         }
502
503         if (showWarning)
504             binding.insecureSchemeText.setVisibility(View.VISIBLE);
505         else
506             binding.insecureSchemeText.setVisibility(View.GONE);
507     }
508     private void hookClearErrorOnFocusListener(TextView view, TextInputLayout layout) {
509         view.setOnFocusChangeListener((v, hasFocus) -> {
510             if (hasFocus)
511                 layout.setError(null);
512         });
513         view.addTextChangedListener(new TextWatcher() {
514             @Override
515             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
516             }
517             @Override
518             public void onTextChanged(CharSequence s, int start, int before, int count) {
519                 layout.setError(null);
520             }
521             @Override
522             public void afterTextChanged(Editable s) {
523             }
524         });
525     }
526     private void syncModelFromUI() {
527         if (syncingModelFromUI)
528             return;
529
530         syncingModelFromUI = true;
531
532         try {
533             ProfileDetailModel model = getModel();
534
535             model.setProfileName(binding.profileName.getText());
536             model.setUrl(binding.url.getText());
537             model.setPreferredAccountsFilter(binding.preferredAccountsFilter.getText());
538             model.setAuthUserName(binding.authUserName.getText());
539             model.setAuthPassword(binding.password.getText());
540         }
541         finally {
542             syncingModelFromUI = false;
543         }
544     }
545     private boolean checkValidity() {
546         boolean valid = true;
547
548         String val = String.valueOf(binding.profileName.getText());
549         if (val.trim()
550                .isEmpty())
551         {
552             valid = false;
553             binding.profileNameLayout.setError(
554                     getResources().getText(R.string.err_profile_name_empty));
555         }
556
557         if (!checkUrlValidity())
558             valid = false;
559
560         if (binding.enableHttpAuth.isChecked()) {
561             val = String.valueOf(binding.authUserName.getText());
562             if (val.trim()
563                    .isEmpty())
564             {
565                 valid = false;
566                 binding.authUserNameLayout.setError(
567                         getResources().getText(R.string.err_profile_user_name_empty));
568             }
569
570             val = String.valueOf(binding.password.getText());
571             if (val.trim()
572                    .isEmpty())
573             {
574                 valid = false;
575                 binding.passwordLayout.setError(
576                         getResources().getText(R.string.err_profile_password_empty));
577             }
578         }
579
580         return valid;
581     }
582     private void resetDefaultCommodity() {
583         defaultCommoditySet = false;
584         binding.defaultCommodityText.setText(R.string.btn_no_currency);
585         binding.defaultCommodityText.setTypeface(binding.defaultCommodityText.getTypeface(),
586                 Typeface.ITALIC);
587     }
588     private void setDefaultCommodity(@NonNull @NotNull String name) {
589         defaultCommoditySet = true;
590         binding.defaultCommodityText.setText(name);
591         binding.defaultCommodityText.setTypeface(Typeface.DEFAULT);
592     }
593     interface TextChangeSyncRoutine {
594         void onTextChanged(String text);
595     }
596 }