2 * Copyright © 2020 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.graphics.Typeface;
23 import android.os.Bundle;
24 import android.text.Editable;
25 import android.text.TextWatcher;
26 import android.view.Menu;
27 import android.view.MenuInflater;
28 import android.view.MenuItem;
29 import android.view.View;
30 import android.widget.LinearLayout;
31 import android.widget.PopupMenu;
32 import android.widget.Switch;
33 import android.widget.TextView;
35 import androidx.annotation.NonNull;
36 import androidx.annotation.Nullable;
37 import androidx.appcompat.app.AppCompatActivity;
38 import androidx.fragment.app.Fragment;
39 import androidx.fragment.app.FragmentActivity;
40 import androidx.lifecycle.LifecycleOwner;
41 import androidx.lifecycle.ViewModelProvider;
43 import com.google.android.material.appbar.CollapsingToolbarLayout;
44 import com.google.android.material.floatingactionbutton.FloatingActionButton;
45 import com.google.android.material.textfield.TextInputLayout;
47 import net.ktnx.mobileledger.BuildConfig;
48 import net.ktnx.mobileledger.R;
49 import net.ktnx.mobileledger.async.SendTransactionTask;
50 import net.ktnx.mobileledger.model.Data;
51 import net.ktnx.mobileledger.model.MobileLedgerProfile;
52 import net.ktnx.mobileledger.ui.CurrencySelectorFragment;
53 import net.ktnx.mobileledger.ui.HueRingDialog;
54 import net.ktnx.mobileledger.ui.activity.ProfileDetailActivity;
55 import net.ktnx.mobileledger.utils.Colors;
56 import net.ktnx.mobileledger.utils.Misc;
58 import org.jetbrains.annotations.NonNls;
59 import org.jetbrains.annotations.NotNull;
61 import java.net.MalformedURLException;
63 import java.util.ArrayList;
64 import java.util.Objects;
65 import java.util.UUID;
67 import static net.ktnx.mobileledger.utils.Logger.debug;
70 * A fragment representing a single Profile detail screen.
71 * a {@link ProfileDetailActivity}
74 public class ProfileDetailFragment extends Fragment {
76 * The fragment argument representing the item ID that this fragment
79 public static final String ARG_ITEM_ID = "item_id";
80 public static final String ARG_HUE = "hue";
83 private MobileLedgerProfile mProfile;
85 private TextView defaultCommodity;
86 private boolean defaultCommoditySet;
87 private TextInputLayout urlLayout;
88 private LinearLayout authParams;
89 private Switch useAuthentication;
90 private TextView userName;
91 private TextInputLayout userNameLayout;
92 private TextView password;
93 private TextInputLayout passwordLayout;
94 private TextView profileName;
95 private TextInputLayout profileNameLayout;
96 private TextView preferredAccountsFilter;
97 private View huePickerView;
98 private View insecureWarningText;
99 private TextView futureDatesText;
100 private TextView apiVersionText;
101 private boolean syncingModelFromUI = false;
103 * Mandatory empty constructor for the fragment manager to instantiate the
104 * fragment (e.g. upon screen orientation changes).
106 public ProfileDetailFragment() {
107 super(R.layout.profile_detail);
110 public void onCreateOptionsMenu(@NotNull Menu menu, @NotNull MenuInflater inflater) {
111 debug("profiles", "[fragment] Creating profile details options menu");
112 super.onCreateOptionsMenu(menu, inflater);
113 inflater.inflate(R.menu.profile_details, menu);
114 final MenuItem menuDeleteProfile = menu.findItem(R.id.menuDelete);
115 menuDeleteProfile.setOnMenuItemClickListener(item -> onDeleteProfile());
116 final ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
118 if (BuildConfig.DEBUG) {
119 final MenuItem menuWipeProfileData = menu.findItem(R.id.menuWipeData);
120 menuWipeProfileData.setOnMenuItemClickListener(ignored -> onWipeDataMenuClicked());
121 menuWipeProfileData.setVisible(mProfile != null);
124 private boolean onDeleteProfile() {
125 AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
126 builder.setTitle(mProfile.getName());
127 builder.setMessage(R.string.remove_profile_dialog_message);
128 builder.setPositiveButton(R.string.Remove, (dialog, which) -> {
129 debug("profiles", String.format("[fragment] removing profile %s", mProfile.getUuid()));
130 mProfile.removeFromDB();
131 ArrayList<MobileLedgerProfile> oldList = Data.profiles.getValue();
133 throw new AssertionError();
134 ArrayList<MobileLedgerProfile> newList = new ArrayList<>(oldList);
135 newList.remove(mProfile);
136 Data.profiles.setValue(newList);
137 if (mProfile.equals(Data.getProfile())) {
138 debug("profiles", "[fragment] setting current profile to 0");
139 Data.setCurrentProfile(newList.get(0));
142 final FragmentActivity activity = getActivity();
143 if (activity != null)
149 private boolean onWipeDataMenuClicked() {
150 // this is a development option, so no confirmation
151 mProfile.wipeAllData();
152 if (mProfile.equals(Data.getProfile()))
153 triggerProfileChange();
156 private void triggerProfileChange() {
157 int index = Data.getProfileIndex(mProfile);
158 MobileLedgerProfile newProfile = new MobileLedgerProfile(mProfile);
159 final ArrayList<MobileLedgerProfile> profiles =
160 Objects.requireNonNull(Data.profiles.getValue());
161 profiles.set(index, newProfile);
163 ProfilesRecyclerViewAdapter viewAdapter = ProfilesRecyclerViewAdapter.getInstance();
164 if (viewAdapter != null)
165 viewAdapter.notifyItemChanged(index);
167 if (mProfile.equals(Data.getProfile()))
168 Data.setCurrentProfile(newProfile);
170 private void hookTextChangeSyncRoutine(TextView view, TextChangeSyncRoutine syncRoutine) {
171 view.addTextChangedListener(new TextWatcher() {
173 public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
175 public void onTextChanged(CharSequence s, int start, int before, int count) {}
177 public void afterTextChanged(Editable s) { syncRoutine.onTextChanged(s.toString());}
181 public void onActivityCreated(@Nullable Bundle savedInstanceState) {
182 super.onActivityCreated(savedInstanceState);
183 Activity context = getActivity();
187 if ((getArguments() != null) && getArguments().containsKey(ARG_ITEM_ID)) {
188 int index = getArguments().getInt(ARG_ITEM_ID, -1);
189 ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
190 if ((profiles != null) && (index != -1) && (index < profiles.size()))
191 mProfile = profiles.get(index);
193 Activity activity = this.getActivity();
194 if (activity == null)
195 throw new AssertionError();
196 CollapsingToolbarLayout appBarLayout = activity.findViewById(R.id.toolbar_layout);
197 if (appBarLayout != null) {
198 if (mProfile != null)
199 appBarLayout.setTitle(mProfile.getName());
201 appBarLayout.setTitle(getResources().getString(R.string.new_profile_title));
205 final LifecycleOwner viewLifecycleOwner = getViewLifecycleOwner();
206 final ProfileDetailModel model = getModel();
208 model.observeDefaultCommodity(viewLifecycleOwner, c -> {
210 setDefaultCommodity(c.getName());
212 resetDefaultCommodity();
215 FloatingActionButton fab = context.findViewById(R.id.fab);
216 fab.setOnClickListener(v -> onSaveFabClicked());
218 profileName = context.findViewById(R.id.profile_name);
219 hookTextChangeSyncRoutine(profileName, model::setProfileName);
220 model.observeProfileName(viewLifecycleOwner, pn -> {
221 if (!Misc.equalStrings(pn, profileName.getText()))
222 profileName.setText(pn);
225 profileNameLayout = context.findViewById(R.id.profile_name_layout);
227 url = context.findViewById(R.id.url);
228 hookTextChangeSyncRoutine(url, model::setUrl);
229 model.observeUrl(viewLifecycleOwner, u -> {
230 if (!Misc.equalStrings(u, url.getText()))
234 urlLayout = context.findViewById(R.id.url_layout);
236 context.findViewById(R.id.default_commodity_layout)
237 .setOnClickListener(v -> {
238 CurrencySelectorFragment cpf = CurrencySelectorFragment.newInstance(
239 CurrencySelectorFragment.DEFAULT_COLUMN_COUNT, false);
240 cpf.setOnCurrencySelectedListener(model::setDefaultCommodity);
241 final AppCompatActivity activity = (AppCompatActivity) v.getContext();
242 cpf.show(activity.getSupportFragmentManager(), "currency-selector");
245 Switch showCommodityByDefault = context.findViewById(R.id.profile_show_commodity);
246 showCommodityByDefault.setOnCheckedChangeListener(
247 (buttonView, isChecked) -> model.setShowCommodityByDefault(isChecked));
248 model.observeShowCommodityByDefault(viewLifecycleOwner, showCommodityByDefault::setChecked);
250 View postingSubItems = context.findViewById(R.id.posting_sub_items);
252 Switch postingPermitted = context.findViewById(R.id.profile_permit_posting);
253 model.observePostingPermitted(viewLifecycleOwner, isChecked -> {
254 postingPermitted.setChecked(isChecked);
255 postingSubItems.setVisibility(isChecked ? View.VISIBLE : View.GONE);
257 postingPermitted.setOnCheckedChangeListener(
258 ((buttonView, isChecked) -> model.setPostingPermitted(isChecked)));
260 Switch showCommentsByDefault = context.findViewById(R.id.profile_show_comments);
261 model.observeShowCommentsByDefault(viewLifecycleOwner, showCommentsByDefault::setChecked);
262 showCommentsByDefault.setOnCheckedChangeListener(
263 ((buttonView, isChecked) -> model.setShowCommentsByDefault(isChecked)));
265 defaultCommodity = context.findViewById(R.id.default_commodity_text);
267 futureDatesText = context.findViewById(R.id.future_dates_text);
268 context.findViewById(R.id.future_dates_layout)
269 .setOnClickListener(v -> {
270 MenuInflater mi = new MenuInflater(context);
271 PopupMenu menu = new PopupMenu(context, v);
272 menu.inflate(R.menu.future_dates);
273 menu.setOnMenuItemClickListener(item -> {
274 model.setFutureDates(futureDatesSettingFromMenuItemId(item.getItemId()));
279 model.observeFutureDates(viewLifecycleOwner,
280 v -> futureDatesText.setText(v.getText(getResources())));
282 apiVersionText = context.findViewById(R.id.api_version_text);
283 model.observeApiVersion(viewLifecycleOwner,
284 apiVer -> apiVersionText.setText(apiVer.getDescription(getResources())));
285 context.findViewById(R.id.api_version_label)
286 .setOnClickListener(this::chooseAPIVersion);
287 context.findViewById(R.id.api_version_text)
288 .setOnClickListener(this::chooseAPIVersion);
290 TextView detectedApiVersion = context.findViewById(R.id.detected_version_text);
291 model.observeDetectedVersion(viewLifecycleOwner, ver -> {
293 detectedApiVersion.setText(context.getResources()
294 .getString(R.string.api_version_unknown_label));
295 else if (ver.isPre_1_20())
296 detectedApiVersion.setText(context.getResources()
297 .getString(R.string.api_pre_1_19));
299 detectedApiVersion.setText(ver.toString());
301 detectedApiVersion.setOnClickListener(v -> model.triggerVersionDetection());
302 final View detectButton = context.findViewById(R.id.api_version_detect_button);
303 detectButton.setOnClickListener(v -> model.triggerVersionDetection());
304 model.observeDetectingHledgerVersion(viewLifecycleOwner, running -> {
305 detectButton.setVisibility(running ? View.VISIBLE : View.INVISIBLE);
308 authParams = context.findViewById(R.id.auth_params);
310 useAuthentication = context.findViewById(R.id.enable_http_auth);
311 useAuthentication.setOnCheckedChangeListener((buttonView, isChecked) -> {
312 model.setUseAuthentication(isChecked);
314 userName.requestFocus();
316 model.observeUseAuthentication(viewLifecycleOwner, isChecked -> {
317 useAuthentication.setChecked(isChecked);
318 authParams.setVisibility(isChecked ? View.VISIBLE : View.GONE);
319 checkInsecureSchemeWithAuth();
322 userName = context.findViewById(R.id.auth_user_name);
323 model.observeUserName(viewLifecycleOwner, text -> {
324 if (!Misc.equalStrings(text, userName.getText()))
325 userName.setText(text);
327 hookTextChangeSyncRoutine(userName, model::setAuthUserName);
328 userNameLayout = context.findViewById(R.id.auth_user_name_layout);
330 password = context.findViewById(R.id.password);
331 model.observePassword(viewLifecycleOwner, text -> {
332 if (!Misc.equalStrings(text, password.getText()))
333 password.setText(text);
335 hookTextChangeSyncRoutine(password, model::setAuthPassword);
336 passwordLayout = context.findViewById(R.id.password_layout);
338 huePickerView = context.findViewById(R.id.btn_pick_ring_color);
339 model.observeThemeId(viewLifecycleOwner, themeId -> {
340 final int hue = (themeId == -1) ? Colors.DEFAULT_HUE_DEG : themeId;
341 final int profileColor = Colors.getPrimaryColorForHue(hue);
342 huePickerView.setBackgroundColor(profileColor);
343 huePickerView.setTag(hue);
346 preferredAccountsFilter = context.findViewById(R.id.preferred_accounts_filter_filter);
347 model.observePreferredAccountsFilter(viewLifecycleOwner, text -> {
348 if (!Misc.equalStrings(text, preferredAccountsFilter.getText()))
349 preferredAccountsFilter.setText(text);
351 hookTextChangeSyncRoutine(preferredAccountsFilter, model::setPreferredAccountsFilter);
353 insecureWarningText = context.findViewById(R.id.insecure_scheme_text);
355 hookClearErrorOnFocusListener(profileName, profileNameLayout);
356 hookClearErrorOnFocusListener(url, urlLayout);
357 hookClearErrorOnFocusListener(userName, userNameLayout);
358 hookClearErrorOnFocusListener(password, passwordLayout);
360 if (savedInstanceState == null) {
361 model.setValuesFromProfile(mProfile, getArguments().getInt(ARG_HUE, -1));
363 checkInsecureSchemeWithAuth();
365 url.addTextChangedListener(new TextWatcher() {
367 public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
369 public void onTextChanged(CharSequence s, int start, int before, int count) {}
371 public void afterTextChanged(Editable s) {
372 checkInsecureSchemeWithAuth();
376 huePickerView.setOnClickListener(v -> {
377 HueRingDialog d = new HueRingDialog(ProfileDetailFragment.this.requireContext(),
378 model.initialThemeHue, (Integer) v.getTag());
380 d.setColorSelectedListener(model::setThemeId);
383 profileName.requestFocus();
385 private void chooseAPIVersion(View v) {
386 Activity context = getActivity();
387 ProfileDetailModel model = getModel();
388 MenuInflater mi = new MenuInflater(context);
389 PopupMenu menu = new PopupMenu(context, v);
390 menu.inflate(R.menu.api_version);
391 menu.setOnMenuItemClickListener(item -> {
392 SendTransactionTask.API apiVer;
393 switch (item.getItemId()) {
394 case R.id.api_version_menu_html:
395 apiVer = SendTransactionTask.API.html;
397 case R.id.api_version_menu_post_1_14:
398 apiVer = SendTransactionTask.API.post_1_14;
400 case R.id.api_version_menu_pre_1_15:
401 apiVer = SendTransactionTask.API.pre_1_15;
403 case R.id.api_version_menu_auto:
405 apiVer = SendTransactionTask.API.auto;
407 model.setApiVersion(apiVer);
408 apiVersionText.setText(apiVer.getDescription(getResources()));
413 private MobileLedgerProfile.FutureDates futureDatesSettingFromMenuItemId(int itemId) {
415 case R.id.menu_future_dates_7:
416 return MobileLedgerProfile.FutureDates.OneWeek;
417 case R.id.menu_future_dates_14:
418 return MobileLedgerProfile.FutureDates.TwoWeeks;
419 case R.id.menu_future_dates_30:
420 return MobileLedgerProfile.FutureDates.OneMonth;
421 case R.id.menu_future_dates_60:
422 return MobileLedgerProfile.FutureDates.TwoMonths;
423 case R.id.menu_future_dates_90:
424 return MobileLedgerProfile.FutureDates.ThreeMonths;
425 case R.id.menu_future_dates_180:
426 return MobileLedgerProfile.FutureDates.SixMonths;
427 case R.id.menu_future_dates_365:
428 return MobileLedgerProfile.FutureDates.OneYear;
429 case R.id.menu_future_dates_all:
430 return MobileLedgerProfile.FutureDates.All;
432 return MobileLedgerProfile.FutureDates.None;
436 private ProfileDetailModel getModel() {
437 return new ViewModelProvider(requireActivity()).get(ProfileDetailModel.class);
439 private void onSaveFabClicked() {
440 if (!checkValidity())
443 ProfileDetailModel model = getModel();
444 final ArrayList<MobileLedgerProfile> profiles =
445 Objects.requireNonNull(Data.profiles.getValue());
447 if (mProfile != null) {
448 int pos = Data.profiles.getValue()
450 mProfile = new MobileLedgerProfile(mProfile);
451 model.updateProfile(mProfile);
452 mProfile.storeInDB();
453 debug("profiles", "profile stored in DB");
454 profiles.set(pos, mProfile);
455 // debug("profiles", String.format("Selected item is %d", mProfile.getThemeHue()));
457 final MobileLedgerProfile currentProfile = Data.getProfile();
458 if (mProfile.getUuid()
459 .equals(currentProfile.getUuid()))
461 Data.setCurrentProfile(mProfile);
464 ProfilesRecyclerViewAdapter viewAdapter = ProfilesRecyclerViewAdapter.getInstance();
465 if (viewAdapter != null)
466 viewAdapter.notifyItemChanged(pos);
469 mProfile = new MobileLedgerProfile(String.valueOf(UUID.randomUUID()));
470 model.updateProfile(mProfile);
471 mProfile.storeInDB();
472 final ArrayList<MobileLedgerProfile> newList = new ArrayList<>(profiles);
473 newList.add(mProfile);
474 Data.profiles.setValue(newList);
475 MobileLedgerProfile.storeProfilesOrder();
477 // first profile ever?
478 if (newList.size() == 1)
479 Data.setCurrentProfile(mProfile);
482 Activity activity = getActivity();
483 if (activity != null)
486 private boolean checkUrlValidity() {
487 boolean valid = true;
489 ProfileDetailModel model = getModel();
491 String val = model.getUrl()
495 urlLayout.setError(getResources().getText(R.string.err_profile_url_empty));
498 URL url = new URL(val);
499 String host = url.getHost();
500 if (host == null || host.isEmpty())
501 throw new MalformedURLException("Missing host");
502 String protocol = url.getProtocol()
504 if (!protocol.equals("HTTP") && !protocol.equals("HTTPS")) {
506 urlLayout.setError(getResources().getText(R.string.err_invalid_url));
509 catch (MalformedURLException e) {
511 urlLayout.setError(getResources().getText(R.string.err_invalid_url));
516 private void checkInsecureSchemeWithAuth() {
517 boolean showWarning = false;
519 final ProfileDetailModel model = getModel();
521 if (model.getUseAuthentication()) {
522 String urlText = model.getUrl();
523 if (urlText.startsWith("http") && !urlText.startsWith("https"))
528 insecureWarningText.setVisibility(View.VISIBLE);
530 insecureWarningText.setVisibility(View.GONE);
532 private void hookClearErrorOnFocusListener(TextView view, TextInputLayout layout) {
533 view.setOnFocusChangeListener((v, hasFocus) -> {
535 layout.setError(null);
537 view.addTextChangedListener(new TextWatcher() {
539 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
542 public void onTextChanged(CharSequence s, int start, int before, int count) {
543 layout.setError(null);
546 public void afterTextChanged(Editable s) {
550 private void syncModelFromUI() {
551 if (syncingModelFromUI)
554 syncingModelFromUI = true;
557 ProfileDetailModel model = getModel();
559 model.setProfileName(profileName.getText());
560 model.setUrl(url.getText());
561 model.setPreferredAccountsFilter(preferredAccountsFilter.getText());
562 model.setAuthUserName(userName.getText());
563 model.setAuthPassword(password.getText());
566 syncingModelFromUI = false;
569 private boolean checkValidity() {
570 boolean valid = true;
572 String val = String.valueOf(profileName.getText());
577 profileNameLayout.setError(getResources().getText(R.string.err_profile_name_empty));
580 if (!checkUrlValidity())
583 if (useAuthentication.isChecked()) {
584 val = String.valueOf(userName.getText());
589 userNameLayout.setError(
590 getResources().getText(R.string.err_profile_user_name_empty));
593 val = String.valueOf(password.getText());
598 passwordLayout.setError(
599 getResources().getText(R.string.err_profile_password_empty));
605 private void resetDefaultCommodity() {
606 defaultCommoditySet = false;
607 defaultCommodity.setText(R.string.btn_no_currency);
608 defaultCommodity.setTypeface(defaultCommodity.getTypeface(), Typeface.ITALIC);
610 private void setDefaultCommodity(@NonNull @NotNull String name) {
611 defaultCommoditySet = true;
612 defaultCommodity.setText(name);
613 defaultCommodity.setTypeface(Typeface.DEFAULT);
615 interface TextChangeSyncRoutine {
616 void onTextChanged(String text);