]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/profiles/ProfileDetailFragment.java
7a8dc50e6316c82fc08442a2682d6d5045684b81
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / ui / profiles / ProfileDetailFragment.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.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.Menu;
27 import android.view.MenuInflater;
28 import android.view.MenuItem;
29 import android.view.View;
30 import android.widget.LinearLayout;
31 import android.widget.PopupMenu;
32 import android.widget.Switch;
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.async.SendTransactionTask;
50 import net.ktnx.mobileledger.model.Data;
51 import net.ktnx.mobileledger.model.MobileLedgerProfile;
52 import net.ktnx.mobileledger.ui.CurrencySelectorFragment;
53 import net.ktnx.mobileledger.ui.HueRingDialog;
54 import net.ktnx.mobileledger.ui.activity.ProfileDetailActivity;
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
65 import static net.ktnx.mobileledger.utils.Logger.debug;
66
67 /**
68  * A fragment representing a single Profile detail screen.
69  * a {@link ProfileDetailActivity}
70  * on handsets.
71  */
72 public class ProfileDetailFragment extends Fragment {
73     /**
74      * The fragment argument representing the item ID that this fragment
75      * represents.
76      */
77     public static final String ARG_ITEM_ID = "item_id";
78     public static final String ARG_HUE = "hue";
79     @NonNls
80
81     /**
82      * The content this fragment is presenting.
83      */ private MobileLedgerProfile mProfile;
84     private TextView url;
85     private TextView defaultCommodity;
86     private View defaultCommodityLayout;
87     private boolean defaultCommoditySet;
88     private TextInputLayout urlLayout;
89     private LinearLayout authParams;
90     private Switch useAuthentication;
91     private TextView userName;
92     private TextInputLayout userNameLayout;
93     private TextView password;
94     private TextInputLayout passwordLayout;
95     private TextView profileName;
96     private TextInputLayout profileNameLayout;
97     private TextView preferredAccountsFilter;
98     private TextInputLayout preferredAccountsFilterLayout;
99     private View huePickerView;
100     private View insecureWarningText;
101     private TextView futureDatesText;
102     private View futureDatesLayout;
103     private TextView apiVersionText;
104     private boolean syncingModelFromUI = false;
105     /**
106      * Mandatory empty constructor for the fragment manager to instantiate the
107      * fragment (e.g. upon screen orientation changes).
108      */
109     public ProfileDetailFragment() {
110         super(R.layout.profile_detail);
111     }
112     @Override
113     public void onCreateOptionsMenu(@NotNull Menu menu, @NotNull MenuInflater inflater) {
114         debug("profiles", "[fragment] Creating profile details options menu");
115         super.onCreateOptionsMenu(menu, inflater);
116         inflater.inflate(R.menu.profile_details, menu);
117         final MenuItem menuDeleteProfile = menu.findItem(R.id.menuDelete);
118         menuDeleteProfile.setOnMenuItemClickListener(item -> {
119             AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
120             builder.setTitle(mProfile.getName());
121             builder.setMessage(R.string.remove_profile_dialog_message);
122             builder.setPositiveButton(R.string.Remove, (dialog, which) -> {
123                 debug("profiles",
124                         String.format("[fragment] removing profile %s", mProfile.getUuid()));
125                 mProfile.removeFromDB();
126                 ArrayList<MobileLedgerProfile> oldList = Data.profiles.getValue();
127                 if (oldList == null)
128                     throw new AssertionError();
129                 ArrayList<MobileLedgerProfile> newList = new ArrayList<>(oldList);
130                 newList.remove(mProfile);
131                 Data.profiles.setValue(newList);
132                 if (mProfile.equals(Data.profile.getValue())) {
133                     debug("profiles", "[fragment] setting current profile to 0");
134                     Data.setCurrentProfile(newList.get(0));
135                 }
136
137                 final FragmentActivity activity = getActivity();
138                 if (activity != null)
139                     activity.finish();
140             });
141             builder.show();
142             return false;
143         });
144         final ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
145         menuDeleteProfile.setVisible(
146                 (mProfile != null) && (profiles != null) && (profiles.size() > 1));
147
148         if (BuildConfig.DEBUG) {
149             final MenuItem menuWipeProfileData = menu.findItem(R.id.menuWipeData);
150             menuWipeProfileData.setOnMenuItemClickListener(ignored -> onWipeDataMenuClicked());
151             menuWipeProfileData.setVisible(mProfile != null);
152         }
153     }
154     private boolean onWipeDataMenuClicked() {
155         // this is a development option, so no confirmation
156         mProfile.wipeAllData();
157         if (mProfile.equals(Data.profile.getValue()))
158             triggerProfileChange();
159         return true;
160     }
161     private void triggerProfileChange() {
162         int index = Data.getProfileIndex(mProfile);
163         MobileLedgerProfile newProfile = new MobileLedgerProfile(mProfile);
164         final ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
165         if (profiles == null)
166             throw new AssertionError();
167         profiles.set(index, newProfile);
168
169         ProfilesRecyclerViewAdapter viewAdapter = ProfilesRecyclerViewAdapter.getInstance();
170         if (viewAdapter != null)
171             viewAdapter.notifyItemChanged(index);
172
173         if (mProfile.equals(Data.profile.getValue()))
174             Data.profile.setValue(newProfile);
175     }
176     private void hookTextChangeSyncRoutine(TextView view, TextChangeSyncProc syncRoutine) {
177         view.addTextChangedListener(new TextWatcher() {
178             @Override
179             public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
180             @Override
181             public void onTextChanged(CharSequence s, int start, int before, int count) {}
182             @Override
183             public void afterTextChanged(Editable s) { syncRoutine.onTextChanged(s.toString());}
184         });
185     }
186     @Override
187     public void onActivityCreated(@Nullable Bundle savedInstanceState) {
188         super.onActivityCreated(savedInstanceState);
189         Activity context = getActivity();
190         if (context == null)
191             return;
192
193         if ((getArguments() != null) && getArguments().containsKey(ARG_ITEM_ID)) {
194             int index = getArguments().getInt(ARG_ITEM_ID, -1);
195             ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
196             if ((profiles != null) && (index != -1) && (index < profiles.size()))
197                 mProfile = profiles.get(index);
198
199             Activity activity = this.getActivity();
200             if (activity == null)
201                 throw new AssertionError();
202             CollapsingToolbarLayout appBarLayout = activity.findViewById(R.id.toolbar_layout);
203             if (appBarLayout != null) {
204                 if (mProfile != null)
205                     appBarLayout.setTitle(mProfile.getName());
206                 else
207                     appBarLayout.setTitle(getResources().getString(R.string.new_profile_title));
208             }
209         }
210
211         final LifecycleOwner viewLifecycleOwner = getViewLifecycleOwner();
212         final ProfileDetailModel model = getModel();
213
214         model.observeDefaultCommodity(viewLifecycleOwner, c -> {
215             if (c != null)
216                 setDefaultCommodity(c.getName());
217             else
218                 resetDefaultCommodity();
219         });
220
221         FloatingActionButton fab = context.findViewById(R.id.fab);
222         fab.setOnClickListener(v -> onSaveFabClicked());
223
224         profileName = context.findViewById(R.id.profile_name);
225         hookTextChangeSyncRoutine(profileName, model::setProfileName);
226         model.observeProfileName(viewLifecycleOwner, pn -> {
227             if (!Misc.equalStrings(pn, profileName.getText()))
228                 profileName.setText(pn);
229         });
230
231         profileNameLayout = context.findViewById(R.id.profile_name_layout);
232
233         url = context.findViewById(R.id.url);
234         hookTextChangeSyncRoutine(url, model::setUrl);
235         model.observeUrl(viewLifecycleOwner, u -> {
236             if (!Misc.equalStrings(u, url.getText()))
237                 url.setText(u);
238         });
239
240         urlLayout = context.findViewById(R.id.url_layout);
241
242         defaultCommodityLayout = context.findViewById(R.id.default_commodity_layout);
243         defaultCommodityLayout.setOnClickListener(v -> {
244             CurrencySelectorFragment cpf = CurrencySelectorFragment.newInstance(
245                     CurrencySelectorFragment.DEFAULT_COLUMN_COUNT, false);
246             cpf.setOnCurrencySelectedListener(model::setDefaultCommodity);
247             final AppCompatActivity activity = (AppCompatActivity) v.getContext();
248             cpf.show(activity.getSupportFragmentManager(), "currency-selector");
249         });
250
251         Switch showCommodityByDefault = context.findViewById(R.id.profile_show_commodity);
252         showCommodityByDefault.setOnCheckedChangeListener(
253                 (buttonView, isChecked) -> model.setShowCommodityByDefault(isChecked));
254         model.observeShowCommodityByDefault(viewLifecycleOwner, showCommodityByDefault::setChecked);
255
256         View postingSubItems = context.findViewById(R.id.posting_sub_items);
257
258         Switch postingPermitted = context.findViewById(R.id.profile_permit_posting);
259         model.observePostingPermitted(viewLifecycleOwner, isChecked -> {
260             postingPermitted.setChecked(isChecked);
261             postingSubItems.setVisibility(isChecked ? View.VISIBLE : View.GONE);
262         });
263         postingPermitted.setOnCheckedChangeListener(
264                 ((buttonView, isChecked) -> model.setPostingPermitted(isChecked)));
265
266         Switch showCommentsByDefault = context.findViewById(R.id.profile_show_comments);
267         model.observeShowCommentsByDefault(viewLifecycleOwner, isChecked -> {
268             showCommentsByDefault.setChecked(isChecked);
269         });
270         showCommentsByDefault.setOnCheckedChangeListener(
271                 ((buttonView, isChecked) -> model.setShowCommentsByDefault(isChecked)));
272
273         defaultCommodity = context.findViewById(R.id.default_commodity_text);
274
275         futureDatesLayout = context.findViewById(R.id.future_dates_layout);
276         futureDatesText = context.findViewById(R.id.future_dates_text);
277         context.findViewById(R.id.future_dates_layout)
278                .setOnClickListener(v -> {
279                    MenuInflater mi = new MenuInflater(context);
280                    PopupMenu menu = new PopupMenu(context, v);
281                    menu.inflate(R.menu.future_dates);
282                    menu.setOnMenuItemClickListener(item -> {
283                        model.setFutureDates(futureDatesSettingFromMenuItemId(item.getItemId()));
284                        return true;
285                    });
286                    menu.show();
287                });
288         model.observeFutureDates(viewLifecycleOwner,
289                 v -> futureDatesText.setText(v.getText(getResources())));
290
291         apiVersionText = context.findViewById(R.id.api_version_text);
292         model.observeApiVersion(viewLifecycleOwner, apiVer -> {
293             apiVersionText.setText(apiVer.getDescription(getResources()));
294         });
295         context.findViewById(R.id.api_version_layout)
296                .setOnClickListener(v -> {
297                    MenuInflater mi = new MenuInflater(context);
298                    PopupMenu menu = new PopupMenu(context, v);
299                    menu.inflate(R.menu.api_version);
300                    menu.setOnMenuItemClickListener(item -> {
301                        SendTransactionTask.API apiVer;
302                        switch (item.getItemId()) {
303                            case R.id.api_version_menu_html:
304                                apiVer = SendTransactionTask.API.html;
305                                break;
306                            case R.id.api_version_menu_post_1_14:
307                                apiVer = SendTransactionTask.API.post_1_14;
308                                break;
309                            case R.id.api_version_menu_pre_1_15:
310                                apiVer = SendTransactionTask.API.pre_1_15;
311                                break;
312                            case R.id.api_version_menu_auto:
313                            default:
314                                apiVer = SendTransactionTask.API.auto;
315                        }
316                        model.setApiVersion(apiVer);
317                        apiVersionText.setText(apiVer.getDescription(getResources()));
318                        return true;
319                    });
320                    menu.show();
321                });
322         authParams = context.findViewById(R.id.auth_params);
323
324         useAuthentication = context.findViewById(R.id.enable_http_auth);
325         useAuthentication.setOnCheckedChangeListener((buttonView, isChecked) -> {
326             model.setUseAuthentication(isChecked);
327             if (isChecked)
328                 userName.requestFocus();
329         });
330         model.observeUseAuthentication(viewLifecycleOwner, isChecked -> {
331             useAuthentication.setChecked(isChecked);
332             authParams.setVisibility(isChecked ? View.VISIBLE : View.GONE);
333             checkInsecureSchemeWithAuth();
334         });
335
336         userName = context.findViewById(R.id.auth_user_name);
337         model.observeUserName(viewLifecycleOwner, text -> {
338             if (!Misc.equalStrings(text, userName.getText()))
339                 userName.setText(text);
340         });
341         hookTextChangeSyncRoutine(userName, model::setAuthUserName);
342         userNameLayout = context.findViewById(R.id.auth_user_name_layout);
343
344         password = context.findViewById(R.id.password);
345         model.observePassword(viewLifecycleOwner, text -> {
346             if (!Misc.equalStrings(text, password.getText()))
347                 password.setText(text);
348         });
349         hookTextChangeSyncRoutine(password, model::setAuthPassword);
350         passwordLayout = context.findViewById(R.id.password_layout);
351
352         huePickerView = context.findViewById(R.id.btn_pick_ring_color);
353         model.observeThemeId(viewLifecycleOwner, themeId -> {
354             final int hue = (themeId == -1) ? Colors.DEFAULT_HUE_DEG : themeId;
355             final int profileColor = Colors.getPrimaryColorForHue(hue);
356             huePickerView.setBackgroundColor(profileColor);
357             huePickerView.setTag(hue);
358         });
359
360         preferredAccountsFilter = context.findViewById(R.id.preferred_accounts_filter_filter);
361         model.observePreferredAccountsFilter(viewLifecycleOwner, text -> {
362             if (!Misc.equalStrings(text, preferredAccountsFilter.getText()))
363                 preferredAccountsFilter.setText(text);
364         });
365         hookTextChangeSyncRoutine(preferredAccountsFilter, model::setPreferredAccountsFilter);
366         preferredAccountsFilterLayout =
367                 context.findViewById(R.id.preferred_accounts_accounts_filter_layout);
368
369         insecureWarningText = context.findViewById(R.id.insecure_scheme_text);
370
371         hookClearErrorOnFocusListener(profileName, profileNameLayout);
372         hookClearErrorOnFocusListener(url, urlLayout);
373         hookClearErrorOnFocusListener(userName, userNameLayout);
374         hookClearErrorOnFocusListener(password, passwordLayout);
375
376         if (savedInstanceState == null) {
377             model.setValuesFromProfile(mProfile, getArguments().getInt(ARG_HUE, -1));
378         }
379         checkInsecureSchemeWithAuth();
380
381         url.addTextChangedListener(new TextWatcher() {
382             @Override
383             public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
384             @Override
385             public void onTextChanged(CharSequence s, int start, int before, int count) {}
386             @Override
387             public void afterTextChanged(Editable s) {
388                 checkInsecureSchemeWithAuth();
389             }
390         });
391
392         huePickerView.setOnClickListener(v -> {
393             HueRingDialog d = new HueRingDialog(ProfileDetailFragment.this.requireContext(),
394                     model.initialThemeHue,
395                     (Integer) v.getTag());
396             d.show();
397             d.setColorSelectedListener(model::setThemeId);
398         });
399
400         profileName.requestFocus();
401     }
402     private MobileLedgerProfile.FutureDates futureDatesSettingFromMenuItemId(int itemId) {
403         switch (itemId) {
404             case R.id.menu_future_dates_7:
405                 return MobileLedgerProfile.FutureDates.OneWeek;
406             case R.id.menu_future_dates_14:
407                 return MobileLedgerProfile.FutureDates.TwoWeeks;
408             case R.id.menu_future_dates_30:
409                 return MobileLedgerProfile.FutureDates.OneMonth;
410             case R.id.menu_future_dates_60:
411                 return MobileLedgerProfile.FutureDates.TwoMonths;
412             case R.id.menu_future_dates_90:
413                 return MobileLedgerProfile.FutureDates.ThreeMonths;
414             case R.id.menu_future_dates_180:
415                 return MobileLedgerProfile.FutureDates.SixMonths;
416             case R.id.menu_future_dates_365:
417                 return MobileLedgerProfile.FutureDates.OneYear;
418             case R.id.menu_future_dates_all:
419                 return MobileLedgerProfile.FutureDates.All;
420             default:
421                 return MobileLedgerProfile.FutureDates.None;
422         }
423     }
424     @NotNull
425     private ProfileDetailModel getModel() {
426         return new ViewModelProvider(requireActivity()).get(ProfileDetailModel.class);
427     }
428     private void onSaveFabClicked() {
429         if (!checkValidity())
430             return;
431
432         ProfileDetailModel model = getModel();
433
434         if (mProfile != null) {
435             model.updateProfile(mProfile);
436 //                debug("profiles", String.format("Selected item is %d", mProfile.getThemeHue()));
437             mProfile.storeInDB();
438             debug("profiles", "profile stored in DB");
439             triggerProfileChange();
440         }
441         else {
442             mProfile = new MobileLedgerProfile();
443             model.updateProfile(mProfile);
444             mProfile.storeInDB();
445             final ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
446             if (profiles == null)
447                 throw new AssertionError();
448             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.profile.setValue(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             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                 urlLayout.setError(getResources().getText(R.string.err_invalid_url));
483             }
484         }
485         catch (MalformedURLException e) {
486             valid = false;
487             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             insecureWarningText.setVisibility(View.VISIBLE);
505         else
506             insecureWarningText.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(profileName.getText());
536             model.setUrl(url.getText());
537             model.setPreferredAccountsFilter(preferredAccountsFilter.getText());
538             model.setAuthUserName(userName.getText());
539             model.setAuthPassword(password.getText());
540         }
541         finally {
542             syncingModelFromUI = false;
543         }
544     }
545     private boolean checkValidity() {
546         boolean valid = true;
547
548         String val = String.valueOf(profileName.getText());
549         if (val.trim()
550                .isEmpty())
551         {
552             valid = false;
553             profileNameLayout.setError(getResources().getText(R.string.err_profile_name_empty));
554         }
555
556         if (!checkUrlValidity())
557             valid = false;
558
559         if (useAuthentication.isChecked()) {
560             val = String.valueOf(userName.getText());
561             if (val.trim()
562                    .isEmpty())
563             {
564                 valid = false;
565                 userNameLayout.setError(
566                         getResources().getText(R.string.err_profile_user_name_empty));
567             }
568
569             val = String.valueOf(password.getText());
570             if (val.trim()
571                    .isEmpty())
572             {
573                 valid = false;
574                 passwordLayout.setError(
575                         getResources().getText(R.string.err_profile_password_empty));
576             }
577         }
578
579         return valid;
580     }
581     private void resetDefaultCommodity() {
582         defaultCommoditySet = false;
583         defaultCommodity.setText(R.string.btn_no_currency);
584         defaultCommodity.setTypeface(defaultCommodity.getTypeface(), Typeface.ITALIC);
585     }
586     private void setDefaultCommodity(@NonNull @NotNull String name) {
587         defaultCommoditySet = true;
588         defaultCommodity.setText(name);
589         defaultCommodity.setTypeface(Typeface.DEFAULT);
590     }
591     interface TextChangeSyncProc {
592         void onTextChanged(String text);
593     }
594 }