]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/profiles/ProfileDetailFragment.java
whitespace
[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, TextChangeSyncRoutine 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, showCommentsByDefault::setChecked);
267         showCommentsByDefault.setOnCheckedChangeListener(
268                 ((buttonView, isChecked) -> model.setShowCommentsByDefault(isChecked)));
269
270         defaultCommodity = context.findViewById(R.id.default_commodity_text);
271
272         futureDatesLayout = context.findViewById(R.id.future_dates_layout);
273         futureDatesText = context.findViewById(R.id.future_dates_text);
274         context.findViewById(R.id.future_dates_layout)
275                .setOnClickListener(v -> {
276                    MenuInflater mi = new MenuInflater(context);
277                    PopupMenu menu = new PopupMenu(context, v);
278                    menu.inflate(R.menu.future_dates);
279                    menu.setOnMenuItemClickListener(item -> {
280                        model.setFutureDates(futureDatesSettingFromMenuItemId(item.getItemId()));
281                        return true;
282                    });
283                    menu.show();
284                });
285         model.observeFutureDates(viewLifecycleOwner,
286                 v -> futureDatesText.setText(v.getText(getResources())));
287
288         apiVersionText = context.findViewById(R.id.api_version_text);
289         model.observeApiVersion(viewLifecycleOwner,
290                 apiVer -> apiVersionText.setText(apiVer.getDescription(getResources())));
291         context.findViewById(R.id.api_version_layout)
292                .setOnClickListener(v -> {
293                    MenuInflater mi = new MenuInflater(context);
294                    PopupMenu menu = new PopupMenu(context, v);
295                    menu.inflate(R.menu.api_version);
296                    menu.setOnMenuItemClickListener(item -> {
297                        SendTransactionTask.API apiVer;
298                        switch (item.getItemId()) {
299                            case R.id.api_version_menu_html:
300                                apiVer = SendTransactionTask.API.html;
301                                break;
302                            case R.id.api_version_menu_post_1_14:
303                                apiVer = SendTransactionTask.API.post_1_14;
304                                break;
305                            case R.id.api_version_menu_pre_1_15:
306                                apiVer = SendTransactionTask.API.pre_1_15;
307                                break;
308                            case R.id.api_version_menu_auto:
309                            default:
310                                apiVer = SendTransactionTask.API.auto;
311                        }
312                        model.setApiVersion(apiVer);
313                        apiVersionText.setText(apiVer.getDescription(getResources()));
314                        return true;
315                    });
316                    menu.show();
317                });
318         authParams = context.findViewById(R.id.auth_params);
319
320         useAuthentication = context.findViewById(R.id.enable_http_auth);
321         useAuthentication.setOnCheckedChangeListener((buttonView, isChecked) -> {
322             model.setUseAuthentication(isChecked);
323             if (isChecked)
324                 userName.requestFocus();
325         });
326         model.observeUseAuthentication(viewLifecycleOwner, isChecked -> {
327             useAuthentication.setChecked(isChecked);
328             authParams.setVisibility(isChecked ? View.VISIBLE : View.GONE);
329             checkInsecureSchemeWithAuth();
330         });
331
332         userName = context.findViewById(R.id.auth_user_name);
333         model.observeUserName(viewLifecycleOwner, text -> {
334             if (!Misc.equalStrings(text, userName.getText()))
335                 userName.setText(text);
336         });
337         hookTextChangeSyncRoutine(userName, model::setAuthUserName);
338         userNameLayout = context.findViewById(R.id.auth_user_name_layout);
339
340         password = context.findViewById(R.id.password);
341         model.observePassword(viewLifecycleOwner, text -> {
342             if (!Misc.equalStrings(text, password.getText()))
343                 password.setText(text);
344         });
345         hookTextChangeSyncRoutine(password, model::setAuthPassword);
346         passwordLayout = context.findViewById(R.id.password_layout);
347
348         huePickerView = context.findViewById(R.id.btn_pick_ring_color);
349         model.observeThemeId(viewLifecycleOwner, themeId -> {
350             final int hue = (themeId == -1) ? Colors.DEFAULT_HUE_DEG : themeId;
351             final int profileColor = Colors.getPrimaryColorForHue(hue);
352             huePickerView.setBackgroundColor(profileColor);
353             huePickerView.setTag(hue);
354         });
355
356         preferredAccountsFilter = context.findViewById(R.id.preferred_accounts_filter_filter);
357         model.observePreferredAccountsFilter(viewLifecycleOwner, text -> {
358             if (!Misc.equalStrings(text, preferredAccountsFilter.getText()))
359                 preferredAccountsFilter.setText(text);
360         });
361         hookTextChangeSyncRoutine(preferredAccountsFilter, model::setPreferredAccountsFilter);
362         preferredAccountsFilterLayout =
363                 context.findViewById(R.id.preferred_accounts_accounts_filter_layout);
364
365         insecureWarningText = context.findViewById(R.id.insecure_scheme_text);
366
367         hookClearErrorOnFocusListener(profileName, profileNameLayout);
368         hookClearErrorOnFocusListener(url, urlLayout);
369         hookClearErrorOnFocusListener(userName, userNameLayout);
370         hookClearErrorOnFocusListener(password, passwordLayout);
371
372         if (savedInstanceState == null) {
373             model.setValuesFromProfile(mProfile, getArguments().getInt(ARG_HUE, -1));
374         }
375         checkInsecureSchemeWithAuth();
376
377         url.addTextChangedListener(new TextWatcher() {
378             @Override
379             public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
380             @Override
381             public void onTextChanged(CharSequence s, int start, int before, int count) {}
382             @Override
383             public void afterTextChanged(Editable s) {
384                 checkInsecureSchemeWithAuth();
385             }
386         });
387
388         huePickerView.setOnClickListener(v -> {
389             HueRingDialog d = new HueRingDialog(ProfileDetailFragment.this.requireContext(),
390                     model.initialThemeHue, (Integer) v.getTag());
391             d.show();
392             d.setColorSelectedListener(model::setThemeId);
393         });
394
395         profileName.requestFocus();
396     }
397     private MobileLedgerProfile.FutureDates futureDatesSettingFromMenuItemId(int itemId) {
398         switch (itemId) {
399             case R.id.menu_future_dates_7:
400                 return MobileLedgerProfile.FutureDates.OneWeek;
401             case R.id.menu_future_dates_14:
402                 return MobileLedgerProfile.FutureDates.TwoWeeks;
403             case R.id.menu_future_dates_30:
404                 return MobileLedgerProfile.FutureDates.OneMonth;
405             case R.id.menu_future_dates_60:
406                 return MobileLedgerProfile.FutureDates.TwoMonths;
407             case R.id.menu_future_dates_90:
408                 return MobileLedgerProfile.FutureDates.ThreeMonths;
409             case R.id.menu_future_dates_180:
410                 return MobileLedgerProfile.FutureDates.SixMonths;
411             case R.id.menu_future_dates_365:
412                 return MobileLedgerProfile.FutureDates.OneYear;
413             case R.id.menu_future_dates_all:
414                 return MobileLedgerProfile.FutureDates.All;
415             default:
416                 return MobileLedgerProfile.FutureDates.None;
417         }
418     }
419     @NotNull
420     private ProfileDetailModel getModel() {
421         return new ViewModelProvider(requireActivity()).get(ProfileDetailModel.class);
422     }
423     private void onSaveFabClicked() {
424         if (!checkValidity())
425             return;
426
427         ProfileDetailModel model = getModel();
428
429         if (mProfile != null) {
430             model.updateProfile(mProfile);
431 //                debug("profiles", String.format("Selected item is %d", mProfile.getThemeHue()));
432             mProfile.storeInDB();
433             debug("profiles", "profile stored in DB");
434             triggerProfileChange();
435         }
436         else {
437             mProfile = new MobileLedgerProfile(String.valueOf(UUID.randomUUID()));
438             model.updateProfile(mProfile);
439             mProfile.storeInDB();
440             final ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
441             if (profiles == null)
442                 throw new AssertionError();
443             ArrayList<MobileLedgerProfile> newList = new ArrayList<>(profiles);
444             newList.add(mProfile);
445             Data.profiles.setValue(newList);
446             MobileLedgerProfile.storeProfilesOrder();
447
448             // first profile ever?
449             if (newList.size() == 1)
450                 Data.setCurrentProfile(mProfile);
451         }
452
453         Activity activity = getActivity();
454         if (activity != null)
455             activity.finish();
456     }
457     private boolean checkUrlValidity() {
458         boolean valid = true;
459
460         ProfileDetailModel model = getModel();
461
462         String val = model.getUrl()
463                           .trim();
464         if (val.isEmpty()) {
465             valid = false;
466             urlLayout.setError(getResources().getText(R.string.err_profile_url_empty));
467         }
468         try {
469             URL url = new URL(val);
470             String host = url.getHost();
471             if (host == null || host.isEmpty())
472                 throw new MalformedURLException("Missing host");
473             String protocol = url.getProtocol()
474                                  .toUpperCase();
475             if (!protocol.equals("HTTP") && !protocol.equals("HTTPS")) {
476                 valid = false;
477                 urlLayout.setError(getResources().getText(R.string.err_invalid_url));
478             }
479         }
480         catch (MalformedURLException e) {
481             valid = false;
482             urlLayout.setError(getResources().getText(R.string.err_invalid_url));
483         }
484
485         return valid;
486     }
487     private void checkInsecureSchemeWithAuth() {
488         boolean showWarning = false;
489
490         final ProfileDetailModel model = getModel();
491
492         if (model.getUseAuthentication()) {
493             String urlText = model.getUrl();
494             if (urlText.startsWith("http") && !urlText.startsWith("https"))
495                 showWarning = true;
496         }
497
498         if (showWarning)
499             insecureWarningText.setVisibility(View.VISIBLE);
500         else
501             insecureWarningText.setVisibility(View.GONE);
502     }
503     private void hookClearErrorOnFocusListener(TextView view, TextInputLayout layout) {
504         view.setOnFocusChangeListener((v, hasFocus) -> {
505             if (hasFocus)
506                 layout.setError(null);
507         });
508         view.addTextChangedListener(new TextWatcher() {
509             @Override
510             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
511             }
512             @Override
513             public void onTextChanged(CharSequence s, int start, int before, int count) {
514                 layout.setError(null);
515             }
516             @Override
517             public void afterTextChanged(Editable s) {
518             }
519         });
520     }
521     private void syncModelFromUI() {
522         if (syncingModelFromUI)
523             return;
524
525         syncingModelFromUI = true;
526
527         try {
528             ProfileDetailModel model = getModel();
529
530             model.setProfileName(profileName.getText());
531             model.setUrl(url.getText());
532             model.setPreferredAccountsFilter(preferredAccountsFilter.getText());
533             model.setAuthUserName(userName.getText());
534             model.setAuthPassword(password.getText());
535         }
536         finally {
537             syncingModelFromUI = false;
538         }
539     }
540     private boolean checkValidity() {
541         boolean valid = true;
542
543         String val = String.valueOf(profileName.getText());
544         if (val.trim()
545                .isEmpty())
546         {
547             valid = false;
548             profileNameLayout.setError(getResources().getText(R.string.err_profile_name_empty));
549         }
550
551         if (!checkUrlValidity())
552             valid = false;
553
554         if (useAuthentication.isChecked()) {
555             val = String.valueOf(userName.getText());
556             if (val.trim()
557                    .isEmpty())
558             {
559                 valid = false;
560                 userNameLayout.setError(
561                         getResources().getText(R.string.err_profile_user_name_empty));
562             }
563
564             val = String.valueOf(password.getText());
565             if (val.trim()
566                    .isEmpty())
567             {
568                 valid = false;
569                 passwordLayout.setError(
570                         getResources().getText(R.string.err_profile_password_empty));
571             }
572         }
573
574         return valid;
575     }
576     private void resetDefaultCommodity() {
577         defaultCommoditySet = false;
578         defaultCommodity.setText(R.string.btn_no_currency);
579         defaultCommodity.setTypeface(defaultCommodity.getTypeface(), Typeface.ITALIC);
580     }
581     private void setDefaultCommodity(@NonNull @NotNull String name) {
582         defaultCommoditySet = true;
583         defaultCommodity.setText(name);
584         defaultCommodity.setTypeface(Typeface.DEFAULT);
585     }
586     interface TextChangeSyncRoutine {
587         void onTextChanged(String text);
588     }
589 }