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.LayoutInflater;
27 import android.view.Menu;
28 import android.view.MenuInflater;
29 import android.view.MenuItem;
30 import android.view.View;
31 import android.view.ViewGroup;
32 import android.widget.PopupMenu;
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.databinding.ProfileDetailBinding;
50 import net.ktnx.mobileledger.json.API;
51 import net.ktnx.mobileledger.model.Data;
52 import net.ktnx.mobileledger.model.MobileLedgerProfile;
53 import net.ktnx.mobileledger.ui.CurrencySelectorFragment;
54 import net.ktnx.mobileledger.ui.HueRingDialog;
55 import net.ktnx.mobileledger.ui.activity.ProfileDetailActivity;
56 import net.ktnx.mobileledger.utils.Colors;
57 import net.ktnx.mobileledger.utils.Misc;
59 import org.jetbrains.annotations.NonNls;
60 import org.jetbrains.annotations.NotNull;
62 import java.net.MalformedURLException;
64 import java.util.ArrayList;
65 import java.util.Objects;
66 import java.util.UUID;
68 import static net.ktnx.mobileledger.utils.Logger.debug;
71 * A fragment representing a single Profile detail screen.
72 * a {@link ProfileDetailActivity}
75 public class ProfileDetailFragment extends Fragment {
77 * The fragment argument representing the item ID that this fragment
80 public static final String ARG_ITEM_ID = "item_id";
81 public static final String ARG_HUE = "hue";
84 private MobileLedgerProfile mProfile;
85 private boolean defaultCommoditySet;
86 private boolean syncingModelFromUI = false;
87 private ProfileDetailBinding binding;
89 * Mandatory empty constructor for the fragment manager to instantiate the
90 * fragment (e.g. upon screen orientation changes).
92 public ProfileDetailFragment() {
93 super(R.layout.profile_detail);
96 public void onCreateOptionsMenu(@NotNull Menu menu, @NotNull MenuInflater inflater) {
97 debug("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 -> onDeleteProfile());
102 final ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
104 if (BuildConfig.DEBUG) {
105 final MenuItem menuWipeProfileData = menu.findItem(R.id.menuWipeData);
106 menuWipeProfileData.setOnMenuItemClickListener(ignored -> onWipeDataMenuClicked());
107 menuWipeProfileData.setVisible(mProfile != null);
110 private boolean onDeleteProfile() {
111 AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
112 builder.setTitle(mProfile.getName());
113 builder.setMessage(R.string.remove_profile_dialog_message);
114 builder.setPositiveButton(R.string.Remove, (dialog, which) -> {
115 debug("profiles", String.format("[fragment] removing profile %s", mProfile.getUuid()));
116 mProfile.removeFromDB();
117 ArrayList<MobileLedgerProfile> oldList = Data.profiles.getValue();
119 throw new AssertionError();
120 ArrayList<MobileLedgerProfile> newList = new ArrayList<>(oldList);
121 newList.remove(mProfile);
122 Data.profiles.setValue(newList);
123 if (mProfile.equals(Data.getProfile())) {
124 debug("profiles", "[fragment] setting current profile to 0");
125 Data.setCurrentProfile(newList.get(0));
128 final FragmentActivity activity = getActivity();
129 if (activity != null)
135 private boolean onWipeDataMenuClicked() {
136 // this is a development option, so no confirmation
137 mProfile.wipeAllData();
138 if (mProfile.equals(Data.getProfile()))
139 triggerProfileChange();
142 private void triggerProfileChange() {
143 int index = Data.getProfileIndex(mProfile);
144 MobileLedgerProfile newProfile = new MobileLedgerProfile(mProfile);
145 final ArrayList<MobileLedgerProfile> profiles =
146 Objects.requireNonNull(Data.profiles.getValue());
147 profiles.set(index, newProfile);
149 ProfilesRecyclerViewAdapter viewAdapter = ProfilesRecyclerViewAdapter.getInstance();
150 if (viewAdapter != null)
151 viewAdapter.notifyItemChanged(index);
153 if (mProfile.equals(Data.getProfile()))
154 Data.setCurrentProfile(newProfile);
156 private void hookTextChangeSyncRoutine(TextView view, TextChangeSyncRoutine syncRoutine) {
157 view.addTextChangedListener(new TextWatcher() {
159 public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
161 public void onTextChanged(CharSequence s, int start, int before, int count) {}
163 public void afterTextChanged(Editable s) { syncRoutine.onTextChanged(s.toString());}
168 public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
169 @Nullable Bundle savedInstanceState) {
170 binding = ProfileDetailBinding.inflate(inflater, container, false);
172 return binding.getRoot();
175 public void onViewCreated(@NotNull View view, @Nullable Bundle savedInstanceState) {
176 super.onViewCreated(view, savedInstanceState);
177 Activity context = getActivity();
181 if ((getArguments() != null) && getArguments().containsKey(ARG_ITEM_ID)) {
182 int index = getArguments().getInt(ARG_ITEM_ID, -1);
183 ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
184 if ((profiles != null) && (index != -1) && (index < profiles.size()))
185 mProfile = profiles.get(index);
187 Activity activity = this.getActivity();
188 if (activity == null)
189 throw new AssertionError();
190 CollapsingToolbarLayout appBarLayout = activity.findViewById(R.id.toolbar_layout);
191 if (appBarLayout != null) {
192 if (mProfile != null)
193 appBarLayout.setTitle(mProfile.getName());
195 appBarLayout.setTitle(getResources().getString(R.string.new_profile_title));
199 final LifecycleOwner viewLifecycleOwner = getViewLifecycleOwner();
200 final ProfileDetailModel model = getModel();
202 model.observeDefaultCommodity(viewLifecycleOwner, c -> {
204 setDefaultCommodity(c.getName());
206 resetDefaultCommodity();
209 FloatingActionButton fab = context.findViewById(R.id.fab);
210 fab.setOnClickListener(v -> onSaveFabClicked());
212 hookTextChangeSyncRoutine(binding.profileName, model::setProfileName);
213 model.observeProfileName(viewLifecycleOwner, pn -> {
214 if (!Misc.equalStrings(pn, Misc.nullIsEmpty(binding.profileName.getText())))
215 binding.profileName.setText(pn);
218 hookTextChangeSyncRoutine(binding.url, model::setUrl);
219 model.observeUrl(viewLifecycleOwner, u -> {
220 if (!Misc.equalStrings(u, Misc.nullIsEmpty(binding.url.getText())))
221 binding.url.setText(u);
224 binding.defaultCommodityLayout.setOnClickListener(v -> {
225 CurrencySelectorFragment cpf = CurrencySelectorFragment.newInstance(
226 CurrencySelectorFragment.DEFAULT_COLUMN_COUNT, false);
227 cpf.setOnCurrencySelectedListener(model::setDefaultCommodity);
228 final AppCompatActivity activity = (AppCompatActivity) v.getContext();
229 cpf.show(activity.getSupportFragmentManager(), "currency-selector");
232 binding.profileShowCommodity.setOnCheckedChangeListener(
233 (buttonView, isChecked) -> model.setShowCommodityByDefault(isChecked));
234 model.observeShowCommodityByDefault(viewLifecycleOwner,
235 binding.profileShowCommodity::setChecked);
237 model.observePostingPermitted(viewLifecycleOwner, isChecked -> {
238 binding.profilePermitPosting.setChecked(isChecked);
239 binding.postingSubItems.setVisibility(isChecked ? View.VISIBLE : View.GONE);
241 binding.profilePermitPosting.setOnCheckedChangeListener(
242 ((buttonView, isChecked) -> model.setPostingPermitted(isChecked)));
244 model.observeShowCommentsByDefault(viewLifecycleOwner,
245 binding.profileShowComments::setChecked);
246 binding.profileShowComments.setOnCheckedChangeListener(
247 ((buttonView, isChecked) -> model.setShowCommentsByDefault(isChecked)));
249 binding.futureDatesLayout.setOnClickListener(v -> {
250 MenuInflater mi = new MenuInflater(context);
251 PopupMenu menu = new PopupMenu(context, v);
252 menu.inflate(R.menu.future_dates);
253 menu.setOnMenuItemClickListener(item -> {
254 model.setFutureDates(futureDatesSettingFromMenuItemId(item.getItemId()));
259 model.observeFutureDates(viewLifecycleOwner,
260 v -> binding.futureDatesText.setText(v.getText(getResources())));
262 model.observeApiVersion(viewLifecycleOwner,
263 apiVer -> binding.apiVersionText.setText(apiVer.getDescription(getResources())));
264 binding.apiVersionLabel.setOnClickListener(this::chooseAPIVersion);
265 binding.apiVersionText.setOnClickListener(this::chooseAPIVersion);
267 binding.serverVersionLabel.setOnClickListener(v -> model.triggerVersionDetection());
268 model.observeDetectedVersion(viewLifecycleOwner, ver -> {
270 binding.detectedServerVersionText.setText(context.getResources()
272 R.string.server_version_unknown_label));
273 else if (ver.isPre_1_20_1())
274 binding.detectedServerVersionText.setText(context.getResources()
276 R.string.detected_server_pre_1_20_1));
278 binding.detectedServerVersionText.setText(ver.toString());
280 binding.detectedServerVersionText.setOnClickListener(v -> model.triggerVersionDetection());
281 binding.serverVersionDetectButton.setOnClickListener(v -> model.triggerVersionDetection());
282 model.observeDetectingHledgerVersion(viewLifecycleOwner,
283 running -> binding.serverVersionDetectButton.setVisibility(
284 running ? View.VISIBLE : View.INVISIBLE));
286 binding.enableHttpAuth.setOnCheckedChangeListener((buttonView, isChecked) -> {
287 boolean wasOn = model.getUseAuthentication();
288 model.setUseAuthentication(isChecked);
289 if (!wasOn && isChecked)
290 binding.authUserName.requestFocus();
292 model.observeUseAuthentication(viewLifecycleOwner, isChecked -> {
293 binding.enableHttpAuth.setChecked(isChecked);
294 binding.authParams.setVisibility(isChecked ? View.VISIBLE : View.GONE);
295 checkInsecureSchemeWithAuth();
298 model.observeUserName(viewLifecycleOwner, text -> {
299 if (!Misc.equalStrings(text, Misc.nullIsEmpty(binding.authUserName.getText())))
300 binding.authUserName.setText(text);
302 hookTextChangeSyncRoutine(binding.authUserName, model::setAuthUserName);
304 model.observePassword(viewLifecycleOwner, text -> {
305 if (!Misc.equalStrings(text, Misc.nullIsEmpty(binding.password.getText())))
306 binding.password.setText(text);
308 hookTextChangeSyncRoutine(binding.password, model::setAuthPassword);
310 model.observeThemeId(viewLifecycleOwner, themeId -> {
311 final int hue = (themeId == -1) ? Colors.DEFAULT_HUE_DEG : themeId;
312 final int profileColor = Colors.getPrimaryColorForHue(hue);
313 binding.btnPickRingColor.setBackgroundColor(profileColor);
314 binding.btnPickRingColor.setTag(hue);
317 model.observePreferredAccountsFilter(viewLifecycleOwner, text -> {
318 if (!Misc.equalStrings(text,
319 Misc.nullIsEmpty(binding.preferredAccountsFilter.getText())))
320 binding.preferredAccountsFilter.setText(text);
322 hookTextChangeSyncRoutine(binding.preferredAccountsFilter,
323 model::setPreferredAccountsFilter);
325 hookClearErrorOnFocusListener(binding.profileName, binding.profileNameLayout);
326 hookClearErrorOnFocusListener(binding.url, binding.urlLayout);
327 hookClearErrorOnFocusListener(binding.authUserName, binding.authUserNameLayout);
328 hookClearErrorOnFocusListener(binding.password, binding.passwordLayout);
330 if (savedInstanceState == null) {
331 model.setValuesFromProfile(mProfile, getArguments().getInt(ARG_HUE, -1));
333 checkInsecureSchemeWithAuth();
335 binding.url.addTextChangedListener(new TextWatcher() {
337 public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
339 public void onTextChanged(CharSequence s, int start, int before, int count) {}
341 public void afterTextChanged(Editable s) {
342 checkInsecureSchemeWithAuth();
346 binding.btnPickRingColor.setOnClickListener(v -> {
347 HueRingDialog d = new HueRingDialog(ProfileDetailFragment.this.requireContext(),
348 model.initialThemeHue, (Integer) v.getTag());
350 d.setColorSelectedListener(model::setThemeId);
353 binding.profileName.requestFocus();
355 private void chooseAPIVersion(View v) {
356 Activity context = getActivity();
357 ProfileDetailModel model = getModel();
358 MenuInflater mi = new MenuInflater(context);
359 PopupMenu menu = new PopupMenu(context, v);
360 menu.inflate(R.menu.api_version);
361 menu.setOnMenuItemClickListener(item -> {
363 switch (item.getItemId()) {
364 case R.id.api_version_menu_html:
367 case R.id.api_version_menu_1_19_1:
368 apiVer = API.v1_19_1;
370 case R.id.api_version_menu_1_15:
373 case R.id.api_version_menu_1_14:
376 case R.id.api_version_menu_auto:
380 model.setApiVersion(apiVer);
381 binding.apiVersionText.setText(apiVer.getDescription(getResources()));
386 private MobileLedgerProfile.FutureDates futureDatesSettingFromMenuItemId(int itemId) {
388 case R.id.menu_future_dates_7:
389 return MobileLedgerProfile.FutureDates.OneWeek;
390 case R.id.menu_future_dates_14:
391 return MobileLedgerProfile.FutureDates.TwoWeeks;
392 case R.id.menu_future_dates_30:
393 return MobileLedgerProfile.FutureDates.OneMonth;
394 case R.id.menu_future_dates_60:
395 return MobileLedgerProfile.FutureDates.TwoMonths;
396 case R.id.menu_future_dates_90:
397 return MobileLedgerProfile.FutureDates.ThreeMonths;
398 case R.id.menu_future_dates_180:
399 return MobileLedgerProfile.FutureDates.SixMonths;
400 case R.id.menu_future_dates_365:
401 return MobileLedgerProfile.FutureDates.OneYear;
402 case R.id.menu_future_dates_all:
403 return MobileLedgerProfile.FutureDates.All;
405 return MobileLedgerProfile.FutureDates.None;
409 private ProfileDetailModel getModel() {
410 return new ViewModelProvider(requireActivity()).get(ProfileDetailModel.class);
412 private void onSaveFabClicked() {
413 if (!checkValidity())
416 ProfileDetailModel model = getModel();
417 final ArrayList<MobileLedgerProfile> profiles =
418 Objects.requireNonNull(Data.profiles.getValue());
420 if (mProfile != null) {
421 int pos = Data.profiles.getValue()
423 mProfile = new MobileLedgerProfile(mProfile);
424 model.updateProfile(mProfile);
425 mProfile.storeInDB();
426 debug("profiles", "profile stored in DB");
427 profiles.set(pos, mProfile);
428 // debug("profiles", String.format("Selected item is %d", mProfile.getThemeHue()));
430 final MobileLedgerProfile currentProfile = Data.getProfile();
431 if (mProfile.getUuid()
432 .equals(currentProfile.getUuid()))
434 Data.setCurrentProfile(mProfile);
437 ProfilesRecyclerViewAdapter viewAdapter = ProfilesRecyclerViewAdapter.getInstance();
438 if (viewAdapter != null)
439 viewAdapter.notifyItemChanged(pos);
442 mProfile = new MobileLedgerProfile(String.valueOf(UUID.randomUUID()));
443 model.updateProfile(mProfile);
444 mProfile.storeInDB();
445 final ArrayList<MobileLedgerProfile> newList = new ArrayList<>(profiles);
446 newList.add(mProfile);
447 Data.profiles.setValue(newList);
448 MobileLedgerProfile.storeProfilesOrder();
450 // first profile ever?
451 if (newList.size() == 1)
452 Data.setCurrentProfile(mProfile);
455 Activity activity = getActivity();
456 if (activity != null)
459 private boolean checkUrlValidity() {
460 boolean valid = true;
462 ProfileDetailModel model = getModel();
464 String val = model.getUrl()
468 binding.urlLayout.setError(getResources().getText(R.string.err_profile_url_empty));
471 URL url = new URL(val);
472 String host = url.getHost();
473 if (host == null || host.isEmpty())
474 throw new MalformedURLException("Missing host");
475 String protocol = url.getProtocol()
477 if (!protocol.equals("HTTP") && !protocol.equals("HTTPS")) {
479 binding.urlLayout.setError(getResources().getText(R.string.err_invalid_url));
482 catch (MalformedURLException e) {
484 binding.urlLayout.setError(getResources().getText(R.string.err_invalid_url));
489 private void checkInsecureSchemeWithAuth() {
490 boolean showWarning = false;
492 final ProfileDetailModel model = getModel();
494 if (model.getUseAuthentication()) {
495 String urlText = model.getUrl();
496 if (urlText.startsWith("http") && !urlText.startsWith("https"))
501 binding.insecureSchemeText.setVisibility(View.VISIBLE);
503 binding.insecureSchemeText.setVisibility(View.GONE);
505 private void hookClearErrorOnFocusListener(TextView view, TextInputLayout layout) {
506 view.setOnFocusChangeListener((v, hasFocus) -> {
508 layout.setError(null);
510 view.addTextChangedListener(new TextWatcher() {
512 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
515 public void onTextChanged(CharSequence s, int start, int before, int count) {
516 layout.setError(null);
519 public void afterTextChanged(Editable s) {
523 private void syncModelFromUI() {
524 if (syncingModelFromUI)
527 syncingModelFromUI = true;
530 ProfileDetailModel model = getModel();
532 model.setProfileName(binding.profileName.getText());
533 model.setUrl(binding.url.getText());
534 model.setPreferredAccountsFilter(binding.preferredAccountsFilter.getText());
535 model.setAuthUserName(binding.authUserName.getText());
536 model.setAuthPassword(binding.password.getText());
539 syncingModelFromUI = false;
542 private boolean checkValidity() {
543 boolean valid = true;
545 String val = String.valueOf(binding.profileName.getText());
550 binding.profileNameLayout.setError(
551 getResources().getText(R.string.err_profile_name_empty));
554 if (!checkUrlValidity())
557 if (binding.enableHttpAuth.isChecked()) {
558 val = String.valueOf(binding.authUserName.getText());
563 binding.authUserNameLayout.setError(
564 getResources().getText(R.string.err_profile_user_name_empty));
567 val = String.valueOf(binding.password.getText());
572 binding.passwordLayout.setError(
573 getResources().getText(R.string.err_profile_password_empty));
579 private void resetDefaultCommodity() {
580 defaultCommoditySet = false;
581 binding.defaultCommodityText.setText(R.string.btn_no_currency);
582 binding.defaultCommodityText.setTypeface(binding.defaultCommodityText.getTypeface(),
585 private void setDefaultCommodity(@NonNull @NotNull String name) {
586 defaultCommoditySet = true;
587 binding.defaultCommodityText.setText(name);
588 binding.defaultCommodityText.setTypeface(Typeface.DEFAULT);
590 interface TextChangeSyncRoutine {
591 void onTextChanged(String text);