]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/profiles/ProfileDetailFragment.java
replace .clone() with a copy constructor
[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.os.Bundle;
23 import android.text.Editable;
24 import android.text.TextWatcher;
25 import android.view.LayoutInflater;
26 import android.view.Menu;
27 import android.view.MenuInflater;
28 import android.view.MenuItem;
29 import android.view.View;
30 import android.view.ViewGroup;
31 import android.widget.LinearLayout;
32 import android.widget.Switch;
33 import android.widget.TextView;
34
35 import androidx.annotation.NonNull;
36 import androidx.annotation.Nullable;
37 import androidx.fragment.app.Fragment;
38 import androidx.fragment.app.FragmentActivity;
39
40 import com.google.android.material.appbar.CollapsingToolbarLayout;
41 import com.google.android.material.floatingactionbutton.FloatingActionButton;
42 import com.google.android.material.textfield.TextInputLayout;
43
44 import net.ktnx.mobileledger.BuildConfig;
45 import net.ktnx.mobileledger.R;
46 import net.ktnx.mobileledger.model.Data;
47 import net.ktnx.mobileledger.model.MobileLedgerProfile;
48 import net.ktnx.mobileledger.ui.HueRingDialog;
49 import net.ktnx.mobileledger.ui.activity.ProfileDetailActivity;
50 import net.ktnx.mobileledger.utils.Colors;
51
52 import org.jetbrains.annotations.NotNull;
53
54 import java.net.MalformedURLException;
55 import java.net.URL;
56 import java.util.ArrayList;
57 import java.util.Objects;
58
59 import static net.ktnx.mobileledger.utils.Logger.debug;
60
61 /**
62  * A fragment representing a single Profile detail screen.
63  * a {@link ProfileDetailActivity}
64  * on handsets.
65  */
66 public class ProfileDetailFragment extends Fragment implements HueRingDialog.HueSelectedListener {
67     /**
68      * The fragment argument representing the item ID that this fragment
69      * represents.
70      */
71     public static final String ARG_ITEM_ID = "item_id";
72
73     /**
74      * The dummy content this fragment is presenting.
75      */
76     private MobileLedgerProfile mProfile;
77     private TextView url;
78     private Switch postingPermitted;
79     private TextInputLayout urlLayout;
80     private LinearLayout authParams;
81     private Switch useAuthentication;
82     private TextView userName;
83     private TextInputLayout userNameLayout;
84     private TextView password;
85     private TextInputLayout passwordLayout;
86     private TextView profileName;
87     private TextInputLayout profileNameLayout;
88     private TextView preferredAccountsFilter;
89     private TextInputLayout preferredAccountsFilterLayout;
90     private View huePickerView;
91     private View insecureWarningText;
92
93     /**
94      * Mandatory empty constructor for the fragment manager to instantiate the
95      * fragment (e.g. upon screen orientation changes).
96      */
97     public ProfileDetailFragment() {
98     }
99     @Override
100     public void onCreateOptionsMenu(@NotNull Menu menu, @NotNull MenuInflater inflater) {
101         debug("profiles", "[fragment] Creating profile details options menu");
102         super.onCreateOptionsMenu(menu, inflater);
103         inflater.inflate(R.menu.profile_details, menu);
104         final MenuItem menuDeleteProfile = menu.findItem(R.id.menuDelete);
105         menuDeleteProfile.setOnMenuItemClickListener(item -> {
106             AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
107             builder.setTitle(mProfile.getName());
108             builder.setMessage(R.string.remove_profile_dialog_message);
109             builder.setPositiveButton(R.string.Remove, (dialog, which) -> {
110                 debug("profiles",
111                         String.format("[fragment] removing profile %s", mProfile.getUuid()));
112                 mProfile.removeFromDB();
113                 ArrayList<MobileLedgerProfile> oldList = Data.profiles.getValue();
114                 if (oldList == null) throw new AssertionError();
115                 ArrayList<MobileLedgerProfile> newList = new ArrayList<>(oldList);
116                 newList.remove(mProfile);
117                 Data.profiles.setValue(newList);
118                 if (mProfile.equals(Data.profile.getValue())) {
119                     debug("profiles", "[fragment] setting current profile to 0");
120                     Data.setCurrentProfile(newList.get(0));
121                 }
122
123                 final FragmentActivity activity = getActivity();
124                 if (activity != null) activity.finish();
125             });
126             builder.show();
127             return false;
128         });
129         final ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
130         menuDeleteProfile
131                 .setVisible((mProfile != null) && (profiles != null) && (profiles.size() > 1));
132
133         if (BuildConfig.DEBUG) {
134             final MenuItem menuWipeProfileData = menu.findItem(R.id.menuWipeData);
135             menuWipeProfileData.setOnMenuItemClickListener(ignored -> onWipeDataMenuClicked());
136             menuWipeProfileData.setVisible(mProfile != null);
137         }
138     }
139     private boolean onWipeDataMenuClicked() {
140         // this is a development option, so no confirmation
141         mProfile.wipeAllData();
142         if (mProfile.equals(Data.profile.getValue())) triggerProfileChange();
143         return true;
144     }
145     private void triggerProfileChange() {
146         int index = Data.getProfileIndex(mProfile);
147         MobileLedgerProfile newProfile = new MobileLedgerProfile(mProfile);
148         final ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
149         if (profiles == null) throw new AssertionError();
150         profiles.set(index, newProfile);
151
152         ProfilesRecyclerViewAdapter prva = ProfilesRecyclerViewAdapter.getInstance();
153         if (prva != null) prva.notifyItemChanged(index);
154
155         if (mProfile.equals(Data.profile.getValue())) Data.profile.setValue(newProfile);
156     }
157     @Override
158     public void onCreate(Bundle savedInstanceState) {
159         super.onCreate(savedInstanceState);
160
161         if ((getArguments() != null) && getArguments().containsKey(ARG_ITEM_ID)) {
162             int index = getArguments().getInt(ARG_ITEM_ID, -1);
163             ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
164             if ((profiles != null) && (index != -1) && (index < profiles.size()))
165                 mProfile = profiles.get(index);
166
167             Activity activity = this.getActivity();
168             if (activity == null) throw new AssertionError();
169             CollapsingToolbarLayout appBarLayout = activity.findViewById(R.id.toolbar_layout);
170             if (appBarLayout != null) {
171                 if (mProfile != null) appBarLayout.setTitle(mProfile.getName());
172                 else appBarLayout.setTitle(getResources().getString(R.string.new_profile_title));
173             }
174         }
175     }
176     @Override
177     public void onActivityCreated(@Nullable Bundle savedInstanceState) {
178         super.onActivityCreated(savedInstanceState);
179         Activity context = getActivity();
180         if (context == null) return;
181
182         FloatingActionButton fab = context.findViewById(R.id.fab);
183         fab.setOnClickListener(v -> onSaveFabClicked());
184
185         profileName.requestFocus();
186     }
187     private void onSaveFabClicked() {
188         if (!checkValidity()) return;
189
190         if (mProfile != null) {
191             updateProfileFromUI();
192 //                debug("profiles", String.format("Selected item is %d", mProfile.getThemeId()));
193             mProfile.storeInDB();
194             debug("profiles", "profile stored in DB");
195             triggerProfileChange();
196         }
197         else {
198             mProfile = new MobileLedgerProfile();
199             updateProfileFromUI();
200             mProfile.storeInDB();
201             final ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
202             if (profiles == null) throw new AssertionError();
203             ArrayList<MobileLedgerProfile> newList = new ArrayList<>(profiles);
204             newList.add(mProfile);
205             Data.profiles.setValue(newList);
206             MobileLedgerProfile.storeProfilesOrder();
207
208             // first profile ever?
209             if (newList.size() == 1) Data.profile.setValue(mProfile);
210         }
211
212         Activity activity = getActivity();
213         if (activity != null) activity.finish();
214     }
215     private void updateProfileFromUI() {
216         mProfile.setName(profileName.getText());
217         mProfile.setUrl(url.getText());
218         mProfile.setPostingPermitted(postingPermitted.isChecked());
219         mProfile.setPreferredAccountsFilter(preferredAccountsFilter.getText());
220         mProfile.setAuthEnabled(useAuthentication.isChecked());
221         mProfile.setAuthUserName(userName.getText());
222         mProfile.setAuthPassword(password.getText());
223         mProfile.setThemeId(huePickerView.getTag());
224     }
225     @Override
226     public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
227                              Bundle savedInstanceState) {
228         View rootView = inflater.inflate(R.layout.profile_detail, container, false);
229
230         profileName = rootView.findViewById(R.id.profile_name);
231         profileNameLayout = rootView.findViewById(R.id.profile_name_layout);
232         url = rootView.findViewById(R.id.url);
233         urlLayout = rootView.findViewById(R.id.url_layout);
234         postingPermitted = rootView.findViewById(R.id.profile_permit_posting);
235         authParams = rootView.findViewById(R.id.auth_params);
236         useAuthentication = rootView.findViewById(R.id.enable_http_auth);
237         userName = rootView.findViewById(R.id.auth_user_name);
238         userNameLayout = rootView.findViewById(R.id.auth_user_name_layout);
239         password = rootView.findViewById(R.id.password);
240         passwordLayout = rootView.findViewById(R.id.password_layout);
241         huePickerView = rootView.findViewById(R.id.btn_pick_ring_color);
242         preferredAccountsFilter = rootView.findViewById(R.id.preferred_accounts_filter_filter);
243         preferredAccountsFilterLayout =
244                 rootView.findViewById(R.id.preferred_accounts_accounts_filter_layout);
245         insecureWarningText = rootView.findViewById(R.id.insecure_scheme_text);
246
247         useAuthentication.setOnCheckedChangeListener((buttonView, isChecked) -> {
248             debug("profiles", isChecked ? "auth enabled " : "auth disabled");
249             authParams.setVisibility(isChecked ? View.VISIBLE : View.GONE);
250             if (isChecked) userName.requestFocus();
251             checkInsecureSchemeWithAuth();
252         });
253
254         postingPermitted.setOnCheckedChangeListener(
255                 ((buttonView, isChecked) -> preferredAccountsFilterLayout
256                         .setVisibility(isChecked ? View.VISIBLE : View.GONE)));
257
258         hookClearErrorOnFocusListener(profileName, profileNameLayout);
259         hookClearErrorOnFocusListener(url, urlLayout);
260         hookClearErrorOnFocusListener(userName, userNameLayout);
261         hookClearErrorOnFocusListener(password, passwordLayout);
262
263         int profileThemeId;
264         if (mProfile != null) {
265             profileName.setText(mProfile.getName());
266             postingPermitted.setChecked(mProfile.isPostingPermitted());
267             url.setText(mProfile.getUrl());
268             useAuthentication.setChecked(mProfile.isAuthEnabled());
269             authParams.setVisibility(mProfile.isAuthEnabled() ? View.VISIBLE : View.GONE);
270             userName.setText(mProfile.isAuthEnabled() ? mProfile.getAuthUserName() : "");
271             password.setText(mProfile.isAuthEnabled() ? mProfile.getAuthPassword() : "");
272             preferredAccountsFilter.setText(mProfile.getPreferredAccountsFilter());
273             profileThemeId = mProfile.getThemeId();
274         }
275         else {
276             profileName.setText("");
277             url.setText("https://");
278             postingPermitted.setChecked(true);
279             useAuthentication.setChecked(false);
280             authParams.setVisibility(View.GONE);
281             userName.setText("");
282             password.setText("");
283             preferredAccountsFilter.setText(null);
284             profileThemeId = -1;
285         }
286
287         checkInsecureSchemeWithAuth();
288
289         url.addTextChangedListener(new TextWatcher() {
290             @Override
291             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
292
293             }
294             @Override
295             public void onTextChanged(CharSequence s, int start, int before, int count) {
296
297             }
298             @Override
299             public void afterTextChanged(Editable s) {
300                 checkInsecureSchemeWithAuth();
301             }
302         });
303
304         final int hue = (profileThemeId == -1) ? Colors.DEFAULT_HUE_DEG : profileThemeId;
305         final int profileColor = Colors.getPrimaryColorForHue(hue);
306
307         huePickerView.setBackgroundColor(profileColor);
308         huePickerView.setTag(profileThemeId);
309         huePickerView.setOnClickListener(v -> {
310             HueRingDialog d = new HueRingDialog(
311                     Objects.requireNonNull(ProfileDetailFragment.this.getContext()), profileThemeId,
312                     (Integer) v.getTag());
313             d.show();
314             d.setColorSelectedListener(this);
315         });
316         return rootView;
317     }
318     private boolean checkUrlValidity() {
319         boolean valid = true;
320
321         String val = String.valueOf(url.getText()).trim();
322         if (val.isEmpty()) {
323             valid = false;
324             urlLayout.setError(getResources().getText(R.string.err_profile_url_empty));
325         }
326         try {
327             URL url = new URL(val);
328             String host = url.getHost();
329             if (host == null || host.isEmpty()) throw new MalformedURLException("Missing host");
330             String protocol = url.getProtocol().toUpperCase();
331             if (!protocol.equals("HTTP") && !protocol.equals("HTTPS")) {
332                 valid = false;
333                 urlLayout.setError(getResources().getText(R.string.err_invalid_url));
334             }
335         }
336         catch (MalformedURLException e) {
337             valid = false;
338             urlLayout.setError(getResources().getText(R.string.err_invalid_url));
339         }
340
341         return valid;
342     }
343     private void checkInsecureSchemeWithAuth() {
344         boolean showWarning = false;
345
346         if (useAuthentication.isChecked()) {
347             String urlText = url.getText().toString();
348             if (urlText.startsWith("http") && !urlText.startsWith("https")) showWarning = true;
349         }
350
351         if (showWarning) insecureWarningText.setVisibility(View.VISIBLE);
352         else insecureWarningText.setVisibility(View.GONE);
353     }
354     private void hookClearErrorOnFocusListener(TextView view, TextInputLayout layout) {
355         view.setOnFocusChangeListener((v, hasFocus) -> {
356             if (hasFocus) layout.setError(null);
357         });
358         view.addTextChangedListener(new TextWatcher() {
359             @Override
360             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
361             }
362             @Override
363             public void onTextChanged(CharSequence s, int start, int before, int count) {
364                 layout.setError(null);
365             }
366             @Override
367             public void afterTextChanged(Editable s) {
368             }
369         });
370     }
371     private boolean checkValidity() {
372         boolean valid = true;
373
374         String val = String.valueOf(profileName.getText());
375         if (val.trim().isEmpty()) {
376             valid = false;
377             profileNameLayout.setError(getResources().getText(R.string.err_profile_name_empty));
378         }
379
380         if (!checkUrlValidity()) valid = false;
381
382         if (useAuthentication.isChecked()) {
383             val = String.valueOf(userName.getText());
384             if (val.trim().isEmpty()) {
385                 valid = false;
386                 userNameLayout
387                         .setError(getResources().getText(R.string.err_profile_user_name_empty));
388             }
389
390             val = String.valueOf(password.getText());
391             if (val.trim().isEmpty()) {
392                 valid = false;
393                 passwordLayout
394                         .setError(getResources().getText(R.string.err_profile_password_empty));
395             }
396         }
397
398         return valid;
399     }
400     @Override
401     public void onHueSelected(int hue) {
402         huePickerView.setBackgroundColor(Colors.getPrimaryColorForHue(hue));
403         huePickerView.setTag(hue);
404     }
405 }