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.
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.
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/>.
18 package net.ktnx.mobileledger.ui.profiles;
20 import android.app.Activity;
21 import android.content.Context;
22 import android.os.Build;
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;
40 import com.google.android.material.appbar.CollapsingToolbarLayout;
41 import com.google.android.material.floatingactionbutton.FloatingActionButton;
42 import com.google.android.material.textfield.TextInputLayout;
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;
50 import org.jetbrains.annotations.NotNull;
52 import java.util.List;
54 import androidx.annotation.ColorInt;
55 import androidx.annotation.NonNull;
56 import androidx.annotation.Nullable;
57 import androidx.fragment.app.Fragment;
60 * A fragment representing a single Profile detail screen.
61 * a {@link ProfileDetailActivity}
64 public class ProfileDetailFragment extends Fragment {
66 * The fragment argument representing the item ID that this fragment
69 public static final String ARG_ITEM_ID = "item_id";
72 * The dummy content this fragment is presenting.
74 private MobileLedgerProfile mProfile;
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 FloatingActionButton fab;
87 private Spinner colorSpinner;
90 * Mandatory empty constructor for the fragment manager to instantiate the
91 * fragment (e.g. upon screen orientation changes).
93 public ProfileDetailFragment() {
96 public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
97 Log.d("profiles", "[fragment] Creating profile details options menu");
98 super.onCreateOptionsMenu(menu, inflater);
99 inflater.inflate(R.menu.profile_details, menu);
100 final MenuItem menuDeleteProfile = menu.findItem(R.id.menuDelete);
101 menuDeleteProfile.setOnMenuItemClickListener(item -> {
102 Log.d("profiles", String.format("[fragment] removing profile %s", mProfile.getUuid()));
103 mProfile.removeFromDB();
104 Data.profiles.remove(mProfile);
105 if (Data.profile.get().equals(mProfile)) {
106 Log.d("profiles", "[fragment] setting current profile to 0");
107 Data.setCurrentProfile(Data.profiles.get(0));
111 menuDeleteProfile.setVisible((mProfile != null) && (Data.profiles.size() > 1));
114 public void onCreate(Bundle savedInstanceState) {
115 super.onCreate(savedInstanceState);
117 if ((getArguments() != null) && getArguments().containsKey(ARG_ITEM_ID)) {
118 int index = getArguments().getInt(ARG_ITEM_ID, -1);
119 if (index != -1) mProfile = Data.profiles.get(index);
121 Activity activity = this.getActivity();
122 if (activity == null) throw new AssertionError();
123 CollapsingToolbarLayout appBarLayout = activity.findViewById(R.id.toolbar_layout);
124 if (appBarLayout != null) {
125 if (mProfile != null) appBarLayout.setTitle(mProfile.getName());
126 else appBarLayout.setTitle(getResources().getString(R.string.new_profile_title));
131 public void onActivityCreated(@Nullable Bundle savedInstanceState) {
132 super.onActivityCreated(savedInstanceState);
133 Activity context = getActivity();
134 if (context == null) return;
136 fab = context.findViewById(R.id.fab);
137 fab.setOnClickListener(v -> {
138 if (!checkValidity()) return;
140 if (mProfile != null) {
141 mProfile.setName(profileName.getText());
142 mProfile.setUrl(url.getText());
143 mProfile.setPostingPermitted(postingPermitted.isChecked());
144 mProfile.setAuthEnabled(useAuthentication.isChecked());
145 mProfile.setAuthUserName(userName.getText());
146 mProfile.setAuthPassword(password.getText());
147 mProfile.setThemeId(colorSpinner.getSelectedItem());
148 // Log.d("profiles", String.format("Selected item is %d", mProfile.getThemeId()));
149 mProfile.storeInDB();
150 Log.d("profiles", "profile stored in DB");
151 Data.profiles.triggerItemChangedNotification(mProfile);
154 if (mProfile.getUuid().equals(Data.profile.get().getUuid())) {
155 // dummy update to notify the observers of the possibly new name/URL
156 Data.profile.set(mProfile);
161 new MobileLedgerProfile(profileName.getText(), postingPermitted.isChecked(),
162 url.getText(), useAuthentication.isChecked(), userName.getText(),
164 Integer.valueOf((String) colorSpinner.getSelectedItem()));
165 mProfile.storeInDB();
166 Data.profiles.add(mProfile);
167 MobileLedgerProfile.storeProfilesOrder();
169 // first profile ever?
170 if (Data.profiles.getList().size() == 1) Data.profile.set(mProfile);
173 Activity activity = getActivity();
174 if (activity != null) activity.finish();
177 profileName.requestFocus();
180 public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
181 Bundle savedInstanceState) {
182 View rootView = inflater.inflate(R.layout.profile_detail, container, false);
184 profileName = rootView.findViewById(R.id.profile_name);
185 profileNameLayout = rootView.findViewById(R.id.profile_name_layout);
186 url = rootView.findViewById(R.id.url);
187 urlLayout = rootView.findViewById(R.id.url_layout);
188 postingPermitted = rootView.findViewById(R.id.profile_permit_posting);
189 authParams = rootView.findViewById(R.id.auth_params);
190 useAuthentication = rootView.findViewById(R.id.enable_http_auth);
191 userName = rootView.findViewById(R.id.auth_user_name);
192 userNameLayout = rootView.findViewById(R.id.auth_user_name_layout);
193 password = rootView.findViewById(R.id.password);
194 passwordLayout = rootView.findViewById(R.id.password_layout);
195 colorSpinner = rootView.findViewById(R.id.colorSpinner);
197 ArrayAdapter<CharSequence> adapter = ColorListAdapter
198 .createFromResource(rootView.getContext(), R.array.profile_colors,
199 R.layout.color_selector_item);
200 // Log.d("profiles", String.format("color count: %s", adapter.getCount()));
201 adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
202 colorSpinner.setAdapter(adapter);
203 colorSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
205 public void onNothingSelected(AdapterView<?> parent) {
209 public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
210 final int primaryColor;
212 Integer.valueOf((String) (parent.getAdapter().getItem(position)));
214 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
215 if (getActivity() != null) primaryColor = getResources()
216 .getColor(R.color.colorPrimary, getActivity().getTheme());
217 else primaryColor = Colors.getPrimaryColorForHue(Colors.DEFAULT_HUE_DEG);
220 primaryColor = getResources().getColor(R.color.colorPrimary);
223 else primaryColor = Colors.getPrimaryColorForHue(degrees);
225 if (colorSpinner != null) {
226 colorSpinner.setBackgroundColor(primaryColor);
227 // for (int i = 0; i < colorSpinner.getChildCount(); i++) {
228 // View v = colorSpinner.getChildAt(i);
230 // if (v instanceof TextView) {
231 // ((TextView) v).setTextColor(Color.TRANSPARENT);
238 useAuthentication.setOnCheckedChangeListener((buttonView, isChecked) -> {
239 Log.d("profiles", isChecked ? "auth enabled " : "auth disabled");
240 authParams.setVisibility(isChecked ? View.VISIBLE : View.GONE);
241 if (isChecked) userName.requestFocus();
244 hookClearErrorOnFocusListener(profileName, profileNameLayout);
245 hookClearErrorOnFocusListener(url, urlLayout);
246 hookClearErrorOnFocusListener(userName, userNameLayout);
247 hookClearErrorOnFocusListener(password, passwordLayout);
249 if (mProfile != null) {
250 profileName.setText(mProfile.getName());
251 postingPermitted.setChecked(mProfile.isPostingPermitted());
252 url.setText(mProfile.getUrl());
253 useAuthentication.setChecked(mProfile.isAuthEnabled());
254 authParams.setVisibility(mProfile.isAuthEnabled() ? View.VISIBLE : View.GONE);
255 userName.setText(mProfile.isAuthEnabled() ? mProfile.getAuthUserName() : "");
256 password.setText(mProfile.isAuthEnabled() ? mProfile.getAuthPassword() : "");
258 colorSpinner.setSelection(0);
260 int sought = mProfile.getThemeId();
261 // Log.d("profiles", String.format("Looking for %d",sought));
262 while (i < adapter.getCount()) {
263 int item = Integer.valueOf(String.valueOf(adapter.getItem(i)));
264 // Log.d("profiles", String.format("Item %d is %d", i, item));
265 if (item == sought) {
266 colorSpinner.setSelection(i);
274 profileName.setText("");
276 postingPermitted.setChecked(true);
277 useAuthentication.setChecked(false);
278 authParams.setVisibility(View.GONE);
279 userName.setText("");
280 password.setText("");
281 colorSpinner.setSelection(0);
286 private void hookClearErrorOnFocusListener(TextView view, TextInputLayout layout) {
287 view.setOnFocusChangeListener((v, hasFocus) -> {
288 if (hasFocus) layout.setError(null);
290 view.addTextChangedListener(new TextWatcher() {
292 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
295 public void onTextChanged(CharSequence s, int start, int before, int count) {
296 layout.setError(null);
299 public void afterTextChanged(Editable s) {
303 boolean checkValidity() {
304 boolean valid = true;
306 String val = String.valueOf(profileName.getText());
307 if (val.trim().isEmpty()) {
309 profileNameLayout.setError(getResources().getText(R.string.err_profile_name_empty));
312 val = String.valueOf(url.getText());
313 if (val.trim().isEmpty()) {
315 urlLayout.setError(getResources().getText(R.string.err_profile_url_empty));
317 if (useAuthentication.isChecked()) {
318 val = String.valueOf(userName.getText());
319 if (val.trim().isEmpty()) {
322 .setError(getResources().getText(R.string.err_profile_user_name_empty));
325 val = String.valueOf(password.getText());
326 if (val.trim().isEmpty()) {
329 .setError(getResources().getText(R.string.err_profile_password_empty));
335 private class ColorListAdapter extends ArrayAdapter<String> {
336 public ColorListAdapter(@NonNull Context context, int resource) {
337 super(context, resource);
339 public ColorListAdapter(@NonNull Context context, int resource, int textViewResourceId) {
340 super(context, resource, textViewResourceId);
342 public ColorListAdapter(@NonNull Context context, int resource, @NonNull String[] objects) {
343 super(context, resource, objects);
345 public ColorListAdapter(@NonNull Context context, int resource, int textViewResourceId,
346 @NonNull String[] objects) {
347 super(context, resource, textViewResourceId, objects);
349 public ColorListAdapter(@NonNull Context context, int resource,
350 @NonNull List<String> objects) {
351 super(context, resource, objects);
353 public ColorListAdapter(@NonNull Context context, int resource, int textViewResourceId,
354 @NonNull List<String> objects) {
355 super(context, resource, textViewResourceId, objects);
359 public View getView(int position, View convertView, @NotNull ViewGroup parent) {
360 String hueStr = getItem(position);
361 int hue = (hueStr == null) ? -1 : Integer.valueOf(hueStr);
362 @ColorInt int primaryColor = Colors.getPrimaryColorForHue(hue);
364 View view = convertView;
365 if (convertView == null) {
366 view = getLayoutInflater().inflate(R.layout.color_selector_item, parent);
369 view.setBackgroundColor(primaryColor);