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.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;
35 import androidx.annotation.NonNull;
36 import androidx.annotation.Nullable;
37 import androidx.fragment.app.Fragment;
38 import androidx.fragment.app.FragmentActivity;
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.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;
52 import org.jetbrains.annotations.NonNls;
53 import org.jetbrains.annotations.NotNull;
55 import java.net.MalformedURLException;
57 import java.util.ArrayList;
58 import java.util.Objects;
60 import static net.ktnx.mobileledger.utils.Logger.debug;
63 * A fragment representing a single Profile detail screen.
64 * a {@link ProfileDetailActivity}
67 public class ProfileDetailFragment extends Fragment implements HueRingDialog.HueSelectedListener {
69 * The fragment argument representing the item ID that this fragment
72 public static final String ARG_ITEM_ID = "item_id";
74 private static final String HTTPS_URL_START = "https://";
77 * The dummy content this fragment is presenting.
79 private MobileLedgerProfile mProfile;
81 private Switch postingPermitted;
82 private TextInputLayout urlLayout;
83 private LinearLayout authParams;
84 private Switch useAuthentication;
85 private TextView userName;
86 private TextInputLayout userNameLayout;
87 private TextView password;
88 private TextInputLayout passwordLayout;
89 private TextView profileName;
90 private TextInputLayout profileNameLayout;
91 private TextView preferredAccountsFilter;
92 private TextInputLayout preferredAccountsFilterLayout;
93 private View huePickerView;
94 private View insecureWarningText;
97 * Mandatory empty constructor for the fragment manager to instantiate the
98 * fragment (e.g. upon screen orientation changes).
100 public ProfileDetailFragment() {
103 public void onCreateOptionsMenu(@NotNull Menu menu, @NotNull MenuInflater inflater) {
104 debug("profiles", "[fragment] Creating profile details options menu");
105 super.onCreateOptionsMenu(menu, inflater);
106 inflater.inflate(R.menu.profile_details, menu);
107 final MenuItem menuDeleteProfile = menu.findItem(R.id.menuDelete);
108 menuDeleteProfile.setOnMenuItemClickListener(item -> {
109 AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
110 builder.setTitle(mProfile.getName());
111 builder.setMessage(R.string.remove_profile_dialog_message);
112 builder.setPositiveButton(R.string.Remove, (dialog, which) -> {
114 String.format("[fragment] removing profile %s", mProfile.getUuid()));
115 mProfile.removeFromDB();
116 ArrayList<MobileLedgerProfile> oldList = Data.profiles.getValue();
117 if (oldList == null) throw new AssertionError();
118 ArrayList<MobileLedgerProfile> newList = new ArrayList<>(oldList);
119 newList.remove(mProfile);
120 Data.profiles.setValue(newList);
121 if (mProfile.equals(Data.profile.getValue())) {
122 debug("profiles", "[fragment] setting current profile to 0");
123 Data.setCurrentProfile(newList.get(0));
126 final FragmentActivity activity = getActivity();
127 if (activity != null) activity.finish();
132 final ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
134 .setVisible((mProfile != null) && (profiles != null) && (profiles.size() > 1));
136 if (BuildConfig.DEBUG) {
137 final MenuItem menuWipeProfileData = menu.findItem(R.id.menuWipeData);
138 menuWipeProfileData.setOnMenuItemClickListener(ignored -> onWipeDataMenuClicked());
139 menuWipeProfileData.setVisible(mProfile != null);
142 private boolean onWipeDataMenuClicked() {
143 // this is a development option, so no confirmation
144 mProfile.wipeAllData();
145 if (mProfile.equals(Data.profile.getValue())) triggerProfileChange();
148 private void triggerProfileChange() {
149 int index = Data.getProfileIndex(mProfile);
150 MobileLedgerProfile newProfile = new MobileLedgerProfile(mProfile);
151 final ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
152 if (profiles == null) throw new AssertionError();
153 profiles.set(index, newProfile);
155 ProfilesRecyclerViewAdapter prva = ProfilesRecyclerViewAdapter.getInstance();
156 if (prva != null) prva.notifyItemChanged(index);
158 if (mProfile.equals(Data.profile.getValue())) Data.profile.setValue(newProfile);
161 public void onCreate(Bundle savedInstanceState) {
162 super.onCreate(savedInstanceState);
164 if ((getArguments() != null) && getArguments().containsKey(ARG_ITEM_ID)) {
165 int index = getArguments().getInt(ARG_ITEM_ID, -1);
166 ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
167 if ((profiles != null) && (index != -1) && (index < profiles.size()))
168 mProfile = profiles.get(index);
170 Activity activity = this.getActivity();
171 if (activity == null) throw new AssertionError();
172 CollapsingToolbarLayout appBarLayout = activity.findViewById(R.id.toolbar_layout);
173 if (appBarLayout != null) {
174 if (mProfile != null) appBarLayout.setTitle(mProfile.getName());
175 else appBarLayout.setTitle(getResources().getString(R.string.new_profile_title));
180 public void onActivityCreated(@Nullable Bundle savedInstanceState) {
181 super.onActivityCreated(savedInstanceState);
182 Activity context = getActivity();
183 if (context == null) return;
185 FloatingActionButton fab = context.findViewById(R.id.fab);
186 fab.setOnClickListener(v -> onSaveFabClicked());
188 profileName.requestFocus();
190 private void onSaveFabClicked() {
191 if (!checkValidity()) return;
193 if (mProfile != null) {
194 updateProfileFromUI();
195 // debug("profiles", String.format("Selected item is %d", mProfile.getThemeId()));
196 mProfile.storeInDB();
197 debug("profiles", "profile stored in DB");
198 triggerProfileChange();
201 mProfile = new MobileLedgerProfile();
202 updateProfileFromUI();
203 mProfile.storeInDB();
204 final ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
205 if (profiles == null) throw new AssertionError();
206 ArrayList<MobileLedgerProfile> newList = new ArrayList<>(profiles);
207 newList.add(mProfile);
208 Data.profiles.setValue(newList);
209 MobileLedgerProfile.storeProfilesOrder();
211 // first profile ever?
212 if (newList.size() == 1) Data.profile.setValue(mProfile);
215 Activity activity = getActivity();
216 if (activity != null) activity.finish();
218 private void updateProfileFromUI() {
219 mProfile.setName(profileName.getText());
220 mProfile.setUrl(url.getText());
221 mProfile.setPostingPermitted(postingPermitted.isChecked());
222 mProfile.setPreferredAccountsFilter(preferredAccountsFilter.getText());
223 mProfile.setAuthEnabled(useAuthentication.isChecked());
224 mProfile.setAuthUserName(userName.getText());
225 mProfile.setAuthPassword(password.getText());
226 mProfile.setThemeId(huePickerView.getTag());
229 public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
230 Bundle savedInstanceState) {
231 View rootView = inflater.inflate(R.layout.profile_detail, container, false);
233 profileName = rootView.findViewById(R.id.profile_name);
234 profileNameLayout = rootView.findViewById(R.id.profile_name_layout);
235 url = rootView.findViewById(R.id.url);
236 urlLayout = rootView.findViewById(R.id.url_layout);
237 postingPermitted = rootView.findViewById(R.id.profile_permit_posting);
238 authParams = rootView.findViewById(R.id.auth_params);
239 useAuthentication = rootView.findViewById(R.id.enable_http_auth);
240 userName = rootView.findViewById(R.id.auth_user_name);
241 userNameLayout = rootView.findViewById(R.id.auth_user_name_layout);
242 password = rootView.findViewById(R.id.password);
243 passwordLayout = rootView.findViewById(R.id.password_layout);
244 huePickerView = rootView.findViewById(R.id.btn_pick_ring_color);
245 preferredAccountsFilter = rootView.findViewById(R.id.preferred_accounts_filter_filter);
246 preferredAccountsFilterLayout =
247 rootView.findViewById(R.id.preferred_accounts_accounts_filter_layout);
248 insecureWarningText = rootView.findViewById(R.id.insecure_scheme_text);
250 useAuthentication.setOnCheckedChangeListener((buttonView, isChecked) -> {
251 debug("profiles", isChecked ? "auth enabled " : "auth disabled");
252 authParams.setVisibility(isChecked ? View.VISIBLE : View.GONE);
253 if (isChecked) userName.requestFocus();
254 checkInsecureSchemeWithAuth();
257 postingPermitted.setOnCheckedChangeListener(
258 ((buttonView, isChecked) -> preferredAccountsFilterLayout
259 .setVisibility(isChecked ? View.VISIBLE : View.GONE)));
261 hookClearErrorOnFocusListener(profileName, profileNameLayout);
262 hookClearErrorOnFocusListener(url, urlLayout);
263 hookClearErrorOnFocusListener(userName, userNameLayout);
264 hookClearErrorOnFocusListener(password, passwordLayout);
267 if (mProfile != null) {
268 profileName.setText(mProfile.getName());
269 postingPermitted.setChecked(mProfile.isPostingPermitted());
270 url.setText(mProfile.getUrl());
271 useAuthentication.setChecked(mProfile.isAuthEnabled());
272 authParams.setVisibility(mProfile.isAuthEnabled() ? View.VISIBLE : View.GONE);
273 userName.setText(mProfile.isAuthEnabled() ? mProfile.getAuthUserName() : "");
274 password.setText(mProfile.isAuthEnabled() ? mProfile.getAuthPassword() : "");
275 preferredAccountsFilter.setText(mProfile.getPreferredAccountsFilter());
276 profileThemeId = mProfile.getThemeId();
279 profileName.setText("");
280 url.setText(HTTPS_URL_START);
281 postingPermitted.setChecked(true);
282 useAuthentication.setChecked(false);
283 authParams.setVisibility(View.GONE);
284 userName.setText("");
285 password.setText("");
286 preferredAccountsFilter.setText(null);
290 checkInsecureSchemeWithAuth();
292 url.addTextChangedListener(new TextWatcher() {
294 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
298 public void onTextChanged(CharSequence s, int start, int before, int count) {
302 public void afterTextChanged(Editable s) {
303 checkInsecureSchemeWithAuth();
307 final int hue = (profileThemeId == -1) ? Colors.DEFAULT_HUE_DEG : profileThemeId;
308 final int profileColor = Colors.getPrimaryColorForHue(hue);
310 huePickerView.setBackgroundColor(profileColor);
311 huePickerView.setTag(profileThemeId);
312 huePickerView.setOnClickListener(v -> {
313 HueRingDialog d = new HueRingDialog(
314 Objects.requireNonNull(ProfileDetailFragment.this.getContext()), profileThemeId,
315 (Integer) v.getTag());
317 d.setColorSelectedListener(this);
321 private boolean checkUrlValidity() {
322 boolean valid = true;
324 String val = String.valueOf(url.getText()).trim();
327 urlLayout.setError(getResources().getText(R.string.err_profile_url_empty));
330 URL url = new URL(val);
331 String host = url.getHost();
332 if (host == null || host.isEmpty()) throw new MalformedURLException("Missing host");
333 String protocol = url.getProtocol().toUpperCase();
334 if (!protocol.equals("HTTP") && !protocol.equals("HTTPS")) {
336 urlLayout.setError(getResources().getText(R.string.err_invalid_url));
339 catch (MalformedURLException e) {
341 urlLayout.setError(getResources().getText(R.string.err_invalid_url));
346 private void checkInsecureSchemeWithAuth() {
347 boolean showWarning = false;
349 if (useAuthentication.isChecked()) {
350 String urlText = url.getText().toString();
351 if (urlText.startsWith("http") && !urlText.startsWith("https")) showWarning = true;
354 if (showWarning) insecureWarningText.setVisibility(View.VISIBLE);
355 else insecureWarningText.setVisibility(View.GONE);
357 private void hookClearErrorOnFocusListener(TextView view, TextInputLayout layout) {
358 view.setOnFocusChangeListener((v, hasFocus) -> {
359 if (hasFocus) layout.setError(null);
361 view.addTextChangedListener(new TextWatcher() {
363 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
366 public void onTextChanged(CharSequence s, int start, int before, int count) {
367 layout.setError(null);
370 public void afterTextChanged(Editable s) {
374 private boolean checkValidity() {
375 boolean valid = true;
377 String val = String.valueOf(profileName.getText());
378 if (val.trim().isEmpty()) {
380 profileNameLayout.setError(getResources().getText(R.string.err_profile_name_empty));
383 if (!checkUrlValidity()) valid = false;
385 if (useAuthentication.isChecked()) {
386 val = String.valueOf(userName.getText());
387 if (val.trim().isEmpty()) {
390 .setError(getResources().getText(R.string.err_profile_user_name_empty));
393 val = String.valueOf(password.getText());
394 if (val.trim().isEmpty()) {
397 .setError(getResources().getText(R.string.err_profile_password_empty));
404 public void onHueSelected(int hue) {
405 huePickerView.setBackgroundColor(Colors.getPrimaryColorForHue(hue));
406 huePickerView.setTag(hue);