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