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