]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/profiles/ProfileDetailFragment.java
fix profile color selector
[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.content.Context;
22 import android.graphics.drawable.ColorDrawable;
23 import android.os.Bundle;
24 import android.text.Editable;
25 import android.text.TextWatcher;
26 import android.util.Log;
27 import android.view.LayoutInflater;
28 import android.view.Menu;
29 import android.view.MenuInflater;
30 import android.view.MenuItem;
31 import android.view.View;
32 import android.view.ViewGroup;
33 import android.widget.AdapterView;
34 import android.widget.ArrayAdapter;
35 import android.widget.LinearLayout;
36 import android.widget.Spinner;
37 import android.widget.Switch;
38 import android.widget.TextView;
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.R;
45 import net.ktnx.mobileledger.model.Data;
46 import net.ktnx.mobileledger.model.MobileLedgerProfile;
47 import net.ktnx.mobileledger.ui.activity.ProfileDetailActivity;
48 import net.ktnx.mobileledger.utils.Colors;
49
50 import java.util.List;
51
52 import androidx.annotation.ColorInt;
53 import androidx.annotation.NonNull;
54 import androidx.annotation.Nullable;
55 import androidx.fragment.app.Fragment;
56
57 /**
58  * A fragment representing a single Profile detail screen.
59  *  a {@link ProfileDetailActivity}
60  * on handsets.
61  */
62 public class ProfileDetailFragment extends Fragment {
63     /**
64      * The fragment argument representing the item ID that this fragment
65      * represents.
66      */
67     public static final String ARG_ITEM_ID = "item_id";
68
69     /**
70      * The dummy content this fragment is presenting.
71      */
72     private MobileLedgerProfile mProfile;
73     private TextView url;
74     private Switch postingPermitted;
75     private TextInputLayout urlLayout;
76     private LinearLayout authParams;
77     private Switch useAuthentication;
78     private TextView userName;
79     private TextInputLayout userNameLayout;
80     private TextView password;
81     private TextInputLayout passwordLayout;
82     private TextView profileName;
83     private TextInputLayout profileNameLayout;
84     private FloatingActionButton fab;
85     private Spinner colorSpinner;
86
87     /**
88      * Mandatory empty constructor for the fragment manager to instantiate the
89      * fragment (e.g. upon screen orientation changes).
90      */
91     public ProfileDetailFragment() {
92     }
93     @Override
94     public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
95         Log.d("profiles", "[fragment] Creating profile details options menu");
96         super.onCreateOptionsMenu(menu, inflater);
97         inflater.inflate(R.menu.profile_details, menu);
98         final MenuItem menuDeleteProfile = menu.findItem(R.id.menuDelete);
99         menuDeleteProfile.setOnMenuItemClickListener(item -> {
100             Log.d("profiles", String.format("[fragment] removing profile %s", mProfile.getUuid()));
101             mProfile.removeFromDB();
102             Data.profiles.remove(mProfile);
103             if (Data.profile.get().equals(mProfile)) {
104                 Log.d("profiles", "[fragment] setting current profile to 0");
105                 Data.setCurrentProfile(Data.profiles.get(0));
106             }
107             return false;
108         });
109         menuDeleteProfile.setVisible((mProfile != null) && (Data.profiles.size() > 1));
110     }
111     @Override
112     public void onCreate(Bundle savedInstanceState) {
113         super.onCreate(savedInstanceState);
114
115         if ((getArguments() != null) && getArguments().containsKey(ARG_ITEM_ID)) {
116             int index = getArguments().getInt(ARG_ITEM_ID, -1);
117             if (index != -1) mProfile = Data.profiles.get(index);
118
119             Activity activity = this.getActivity();
120             if (activity == null) throw new AssertionError();
121             CollapsingToolbarLayout appBarLayout = activity.findViewById(R.id.toolbar_layout);
122             if (appBarLayout != null) {
123                 if (mProfile != null) appBarLayout.setTitle(mProfile.getName());
124                 else appBarLayout.setTitle(getResources().getString(R.string.new_profile_title));
125             }
126         }
127     }
128     @Override
129     public void onActivityCreated(@Nullable Bundle savedInstanceState) {
130         super.onActivityCreated(savedInstanceState);
131         Activity context = getActivity();
132         if (context == null) return;
133
134         fab = context.findViewById(R.id.fab);
135         fab.setOnClickListener(v -> {
136             if (!checkValidity()) return;
137
138             if (mProfile != null) {
139                 mProfile.setName(profileName.getText());
140                 mProfile.setUrl(url.getText());
141                 mProfile.setPostingPermitted(postingPermitted.isChecked());
142                 mProfile.setAuthEnabled(useAuthentication.isChecked());
143                 mProfile.setAuthUserName(userName.getText());
144                 mProfile.setAuthPassword(password.getText());
145                 mProfile.setThemeId(colorSpinner.getSelectedItem());
146 //                Log.d("profiles", String.format("Selected item is %d", mProfile.getThemeId()));
147                 mProfile.storeInDB();
148                 Log.d("profiles", "profile stored in DB");
149                 Data.profiles.triggerItemChangedNotification(mProfile);
150
151
152                 if (mProfile.getUuid().equals(Data.profile.get().getUuid())) {
153                     // dummy update to notify the observers of the possibly new name/URL
154                     Data.profile.set(mProfile);
155                 }
156             }
157             else {
158                 mProfile =
159                         new MobileLedgerProfile(profileName.getText(), postingPermitted.isChecked(),
160                                 url.getText(), useAuthentication.isChecked(), userName.getText(),
161                                 password.getText(),
162                                 Integer.valueOf((String) colorSpinner.getSelectedItem()));
163                 mProfile.storeInDB();
164                 Data.profiles.add(mProfile);
165                 MobileLedgerProfile.storeProfilesOrder();
166
167                 // first profile ever?
168                 if (Data.profiles.getList().size() == 1) Data.profile.set(mProfile);
169             }
170
171             Activity activity = getActivity();
172             if (activity != null) activity.finish();
173         });
174
175         profileName.requestFocus();
176     }
177     @Override
178     public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
179                              Bundle savedInstanceState) {
180         View rootView = inflater.inflate(R.layout.profile_detail, container, false);
181
182         profileName = rootView.findViewById(R.id.profile_name);
183         profileNameLayout = rootView.findViewById(R.id.profile_name_layout);
184         url = rootView.findViewById(R.id.url);
185         urlLayout = rootView.findViewById(R.id.url_layout);
186         postingPermitted = rootView.findViewById(R.id.profile_permit_posting);
187         authParams = rootView.findViewById(R.id.auth_params);
188         useAuthentication = rootView.findViewById(R.id.enable_http_auth);
189         userName = rootView.findViewById(R.id.auth_user_name);
190         userNameLayout = rootView.findViewById(R.id.auth_user_name_layout);
191         password = rootView.findViewById(R.id.password);
192         passwordLayout = rootView.findViewById(R.id.password_layout);
193         colorSpinner = rootView.findViewById(R.id.colorSpinner);
194
195         ColorListAdapter adapter =
196                 new ColorListAdapter(rootView.getContext(), R.layout.color_selector_item);
197         adapter.add(-1);
198         for (int i = 0; i < 360; i += 15) adapter.add(i);
199         Log.d("profiles", String.format("color count: %s", adapter.getCount()));
200 //        adapter.setDropDownViewResource(R.layout.color_selector_item);
201         colorSpinner.setAdapter(adapter);
202         colorSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
203             @Override
204             public void onNothingSelected(AdapterView<?> parent) {
205
206             }
207             @Override
208             public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
209                 final int primaryColor;
210                 final int degrees = (Integer) parent.getAdapter().getItem(position);
211                 if (degrees < 0) {
212                     primaryColor = Colors.getPrimaryColorForHue(Colors.DEFAULT_HUE_DEG);
213                 }
214                 else primaryColor = Colors.getPrimaryColorForHue(degrees);
215
216                 if (colorSpinner != null) {
217                     colorSpinner.setBackgroundColor(primaryColor);
218 //                    for (int i = 0; i < colorSpinner.getChildCount(); i++) {
219 //                        View v = colorSpinner.getChildAt(i);
220 //
221 //                        if (v instanceof TextView) {
222 //                            ((TextView) v).setTextColor(Color.TRANSPARENT);
223 //                        }
224 //                    }
225                 }
226             }
227         });
228
229         useAuthentication.setOnCheckedChangeListener((buttonView, isChecked) -> {
230             Log.d("profiles", isChecked ? "auth enabled " : "auth disabled");
231             authParams.setVisibility(isChecked ? View.VISIBLE : View.GONE);
232             if (isChecked) userName.requestFocus();
233         });
234
235         hookClearErrorOnFocusListener(profileName, profileNameLayout);
236         hookClearErrorOnFocusListener(url, urlLayout);
237         hookClearErrorOnFocusListener(userName, userNameLayout);
238         hookClearErrorOnFocusListener(password, passwordLayout);
239
240         if (mProfile != null) {
241             profileName.setText(mProfile.getName());
242             postingPermitted.setChecked(mProfile.isPostingPermitted());
243             url.setText(mProfile.getUrl());
244             useAuthentication.setChecked(mProfile.isAuthEnabled());
245             authParams.setVisibility(mProfile.isAuthEnabled() ? View.VISIBLE : View.GONE);
246             userName.setText(mProfile.isAuthEnabled() ? mProfile.getAuthUserName() : "");
247             password.setText(mProfile.isAuthEnabled() ? mProfile.getAuthPassword() : "");
248
249             colorSpinner.setSelection(0);
250             int i = 0;
251             int sought = mProfile.getThemeId();
252 //            Log.d("profiles", String.format("Looking for %d",sought));
253             while (i < adapter.getCount()) {
254                 int item = Integer.valueOf(String.valueOf(adapter.getItem(i)));
255 //                Log.d("profiles", String.format("Item %d is %d", i, item));
256                 if (item == sought) {
257                     colorSpinner.setSelection(i);
258                     break;
259                 }
260
261                 i++;
262             }
263         }
264         else {
265             profileName.setText("");
266             url.setText("");
267             postingPermitted.setChecked(true);
268             useAuthentication.setChecked(false);
269             authParams.setVisibility(View.GONE);
270             userName.setText("");
271             password.setText("");
272             colorSpinner.setSelection(0);
273         }
274
275         return rootView;
276     }
277     private void hookClearErrorOnFocusListener(TextView view, TextInputLayout layout) {
278         view.setOnFocusChangeListener((v, hasFocus) -> {
279             if (hasFocus) layout.setError(null);
280         });
281         view.addTextChangedListener(new TextWatcher() {
282             @Override
283             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
284             }
285             @Override
286             public void onTextChanged(CharSequence s, int start, int before, int count) {
287                 layout.setError(null);
288             }
289             @Override
290             public void afterTextChanged(Editable s) {
291             }
292         });
293     }
294     boolean checkValidity() {
295         boolean valid = true;
296
297         String val = String.valueOf(profileName.getText());
298         if (val.trim().isEmpty()) {
299             valid = false;
300             profileNameLayout.setError(getResources().getText(R.string.err_profile_name_empty));
301         }
302
303         val = String.valueOf(url.getText());
304         if (val.trim().isEmpty()) {
305             valid = false;
306             urlLayout.setError(getResources().getText(R.string.err_profile_url_empty));
307         }
308         if (useAuthentication.isChecked()) {
309             val = String.valueOf(userName.getText());
310             if (val.trim().isEmpty()) {
311                 valid = false;
312                 userNameLayout
313                         .setError(getResources().getText(R.string.err_profile_user_name_empty));
314             }
315
316             val = String.valueOf(password.getText());
317             if (val.trim().isEmpty()) {
318                 valid = false;
319                 passwordLayout
320                         .setError(getResources().getText(R.string.err_profile_password_empty));
321             }
322         }
323
324         return valid;
325     }
326     private class ColorListAdapter extends ArrayAdapter<Integer> {
327         public ColorListAdapter(@NonNull Context context, int resource) {
328             super(context, resource);
329         }
330         public ColorListAdapter(@NonNull Context context, int resource, int textViewResourceId) {
331             super(context, resource, textViewResourceId);
332         }
333         public ColorListAdapter(@NonNull Context context, int resource,
334                                 @NonNull Integer[] objects) {
335             super(context, resource, objects);
336         }
337         public ColorListAdapter(@NonNull Context context, int resource, int textViewResourceId,
338                                 @NonNull Integer[] objects) {
339             super(context, resource, textViewResourceId, objects);
340         }
341         public ColorListAdapter(@NonNull Context context, int resource,
342                                 @NonNull List<Integer> objects) {
343             super(context, resource, objects);
344         }
345         public ColorListAdapter(@NonNull Context context, int resource, int textViewResourceId,
346                                 @NonNull List<Integer> objects) {
347             super(context, resource, textViewResourceId, objects);
348         }
349         @Override
350         public @NonNull
351         View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
352             Integer hueDeg = getItem(position);
353             int hue = ((hueDeg == null) || (hueDeg == -1)) ? Colors.DEFAULT_HUE_DEG : hueDeg;
354             @ColorInt int primaryColor = Colors.getPrimaryColorForHue(hue);
355
356             View view = convertView;
357             if (convertView == null) {
358                 view = getLayoutInflater().inflate(R.layout.color_selector_item, null);
359             }
360
361             view.setBackground(new ColorDrawable(primaryColor));
362             return view;
363         }
364     }
365 }