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