2 * Copyright © 2021 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.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;
84 private boolean defaultCommoditySet;
85 private boolean syncingModelFromUI = false;
86 private ProfileDetailBinding binding;
88 * Mandatory empty constructor for the fragment manager to instantiate the
89 * fragment (e.g. upon screen orientation changes).
91 public ProfileDetailFragment() {
92 super(R.layout.profile_detail);
95 public void onCreateOptionsMenu(@NotNull Menu menu, @NotNull MenuInflater inflater) {
96 debug("profiles", "[fragment] Creating profile details options menu");
97 super.onCreateOptionsMenu(menu, inflater);
98 inflater.inflate(R.menu.profile_details, menu);
99 final MenuItem menuDeleteProfile = menu.findItem(R.id.menuDelete);
100 menuDeleteProfile.setOnMenuItemClickListener(item -> onDeleteProfile());
101 final ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
103 if (BuildConfig.DEBUG) {
104 final MenuItem menuWipeProfileData = menu.findItem(R.id.menuWipeData);
105 menuWipeProfileData.setOnMenuItemClickListener(ignored -> onWipeDataMenuClicked());
106 menuWipeProfileData.setVisible(mProfile != null);
109 private boolean onDeleteProfile() {
110 AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
111 builder.setTitle(mProfile.getName());
112 builder.setMessage(R.string.remove_profile_dialog_message);
113 builder.setPositiveButton(R.string.Remove, (dialog, which) -> {
114 debug("profiles", String.format("[fragment] removing profile %s", mProfile.getUuid()));
115 mProfile.removeFromDB();
116 ArrayList<MobileLedgerProfile> oldList = Data.profiles.getValue();
118 throw new AssertionError();
119 ArrayList<MobileLedgerProfile> newList = new ArrayList<>(oldList);
120 newList.remove(mProfile);
121 Data.profiles.setValue(newList);
122 if (mProfile.equals(Data.getProfile())) {
123 debug("profiles", "[fragment] setting current profile to 0");
124 Data.setCurrentProfile(newList.get(0));
127 final FragmentActivity activity = getActivity();
128 if (activity != null)
134 private boolean onWipeDataMenuClicked() {
135 // this is a development option, so no confirmation
136 mProfile.wipeAllData();
137 if (mProfile.equals(Data.getProfile()))
138 triggerProfileChange();
141 private void triggerProfileChange() {
142 int index = Data.getProfileIndex(mProfile);
143 MobileLedgerProfile newProfile = new MobileLedgerProfile(mProfile);
144 final ArrayList<MobileLedgerProfile> profiles =
145 Objects.requireNonNull(Data.profiles.getValue());
146 profiles.set(index, newProfile);
148 ProfilesRecyclerViewAdapter viewAdapter = ProfilesRecyclerViewAdapter.getInstance();
149 if (viewAdapter != null)
150 viewAdapter.notifyItemChanged(index);
152 if (mProfile.equals(Data.getProfile()))
153 Data.setCurrentProfile(newProfile);
155 private void hookTextChangeSyncRoutine(TextView view, TextChangeSyncRoutine syncRoutine) {
156 view.addTextChangedListener(new TextWatcher() {
158 public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
160 public void onTextChanged(CharSequence s, int start, int before, int count) {}
162 public void afterTextChanged(Editable s) { syncRoutine.onTextChanged(s.toString());}
167 public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
168 @Nullable Bundle savedInstanceState) {
169 binding = ProfileDetailBinding.inflate(inflater, container, false);
171 return binding.getRoot();
174 public void onViewCreated(@NotNull View view, @Nullable Bundle savedInstanceState) {
175 super.onViewCreated(view, savedInstanceState);
176 Activity context = getActivity();
180 if ((getArguments() != null) && getArguments().containsKey(ARG_ITEM_ID)) {
181 int index = getArguments().getInt(ARG_ITEM_ID, -1);
182 ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
183 if ((profiles != null) && (index != -1) && (index < profiles.size()))
184 mProfile = profiles.get(index);
186 Activity activity = this.getActivity();
187 if (activity == null)
188 throw new AssertionError();
189 CollapsingToolbarLayout appBarLayout = activity.findViewById(R.id.toolbar_layout);
190 if (appBarLayout != null) {
191 if (mProfile != null)
192 appBarLayout.setTitle(mProfile.getName());
194 appBarLayout.setTitle(getResources().getString(R.string.new_profile_title));
198 final LifecycleOwner viewLifecycleOwner = getViewLifecycleOwner();
199 final ProfileDetailModel model = getModel();
201 model.observeDefaultCommodity(viewLifecycleOwner, c -> {
203 setDefaultCommodity(c.getName());
205 resetDefaultCommodity();
208 FloatingActionButton fab = context.findViewById(R.id.fab);
209 fab.setOnClickListener(v -> onSaveFabClicked());
211 hookTextChangeSyncRoutine(binding.profileName, model::setProfileName);
212 model.observeProfileName(viewLifecycleOwner, pn -> {
213 if (!Misc.equalStrings(pn, Misc.nullIsEmpty(binding.profileName.getText())))
214 binding.profileName.setText(pn);
217 hookTextChangeSyncRoutine(binding.url, model::setUrl);
218 model.observeUrl(viewLifecycleOwner, u -> {
219 if (!Misc.equalStrings(u, Misc.nullIsEmpty(binding.url.getText())))
220 binding.url.setText(u);
223 binding.defaultCommodityLayout.setOnClickListener(v -> {
224 CurrencySelectorFragment cpf = CurrencySelectorFragment.newInstance(
225 CurrencySelectorFragment.DEFAULT_COLUMN_COUNT, false);
226 cpf.setOnCurrencySelectedListener(model::setDefaultCommodity);
227 final AppCompatActivity activity = (AppCompatActivity) v.getContext();
228 cpf.show(activity.getSupportFragmentManager(), "currency-selector");
231 binding.profileShowCommodity.setOnCheckedChangeListener(
232 (buttonView, isChecked) -> model.setShowCommodityByDefault(isChecked));
233 model.observeShowCommodityByDefault(viewLifecycleOwner,
234 binding.profileShowCommodity::setChecked);
236 model.observePostingPermitted(viewLifecycleOwner, isChecked -> {
237 binding.profilePermitPosting.setChecked(isChecked);
238 binding.postingSubItems.setVisibility(isChecked ? View.VISIBLE : View.GONE);
240 binding.profilePermitPosting.setOnCheckedChangeListener(
241 ((buttonView, isChecked) -> model.setPostingPermitted(isChecked)));
243 model.observeShowCommentsByDefault(viewLifecycleOwner,
244 binding.profileShowComments::setChecked);
245 binding.profileShowComments.setOnCheckedChangeListener(
246 ((buttonView, isChecked) -> model.setShowCommentsByDefault(isChecked)));
248 binding.futureDatesLayout.setOnClickListener(v -> {
249 MenuInflater mi = new MenuInflater(context);
250 PopupMenu menu = new PopupMenu(context, v);
251 menu.inflate(R.menu.future_dates);
252 menu.setOnMenuItemClickListener(item -> {
253 model.setFutureDates(futureDatesSettingFromMenuItemId(item.getItemId()));
258 model.observeFutureDates(viewLifecycleOwner,
259 v -> binding.futureDatesText.setText(v.getText(getResources())));
261 model.observeApiVersion(viewLifecycleOwner,
262 apiVer -> binding.apiVersionText.setText(apiVer.getDescription(getResources())));
263 binding.apiVersionLabel.setOnClickListener(this::chooseAPIVersion);
264 binding.apiVersionText.setOnClickListener(this::chooseAPIVersion);
266 binding.serverVersionLabel.setOnClickListener(v -> model.triggerVersionDetection());
267 model.observeDetectedVersion(viewLifecycleOwner, ver -> {
269 binding.detectedServerVersionText.setText(context.getResources()
271 R.string.server_version_unknown_label));
272 else if (ver.isPre_1_20_1())
273 binding.detectedServerVersionText.setText(context.getResources()
275 R.string.detected_server_pre_1_20_1));
277 binding.detectedServerVersionText.setText(ver.toString());
279 binding.detectedServerVersionText.setOnClickListener(v -> model.triggerVersionDetection());
280 binding.serverVersionDetectButton.setOnClickListener(v -> model.triggerVersionDetection());
281 model.observeDetectingHledgerVersion(viewLifecycleOwner,
282 running -> binding.serverVersionDetectButton.setVisibility(
283 running ? View.VISIBLE : View.INVISIBLE));
285 binding.enableHttpAuth.setOnCheckedChangeListener((buttonView, isChecked) -> {
286 boolean wasOn = model.getUseAuthentication();
287 model.setUseAuthentication(isChecked);
288 if (!wasOn && isChecked)
289 binding.authUserName.requestFocus();
291 model.observeUseAuthentication(viewLifecycleOwner, isChecked -> {
292 binding.enableHttpAuth.setChecked(isChecked);
293 binding.authParams.setVisibility(isChecked ? View.VISIBLE : View.GONE);
294 checkInsecureSchemeWithAuth();
297 model.observeUserName(viewLifecycleOwner, text -> {
298 if (!Misc.equalStrings(text, Misc.nullIsEmpty(binding.authUserName.getText())))
299 binding.authUserName.setText(text);
301 hookTextChangeSyncRoutine(binding.authUserName, model::setAuthUserName);
303 model.observePassword(viewLifecycleOwner, text -> {
304 if (!Misc.equalStrings(text, Misc.nullIsEmpty(binding.password.getText())))
305 binding.password.setText(text);
307 hookTextChangeSyncRoutine(binding.password, model::setAuthPassword);
309 model.observeThemeId(viewLifecycleOwner, themeId -> {
310 final int hue = (themeId == -1) ? Colors.DEFAULT_HUE_DEG : themeId;
311 final int profileColor = Colors.getPrimaryColorForHue(hue);
312 binding.btnPickRingColor.setBackgroundColor(profileColor);
313 binding.btnPickRingColor.setTag(hue);
316 model.observePreferredAccountsFilter(viewLifecycleOwner, text -> {
317 if (!Misc.equalStrings(text,
318 Misc.nullIsEmpty(binding.preferredAccountsFilter.getText())))
319 binding.preferredAccountsFilter.setText(text);
321 hookTextChangeSyncRoutine(binding.preferredAccountsFilter,
322 model::setPreferredAccountsFilter);
324 hookClearErrorOnFocusListener(binding.profileName, binding.profileNameLayout);
325 hookClearErrorOnFocusListener(binding.url, binding.urlLayout);
326 hookClearErrorOnFocusListener(binding.authUserName, binding.authUserNameLayout);
327 hookClearErrorOnFocusListener(binding.password, binding.passwordLayout);
329 if (savedInstanceState == null) {
330 model.setValuesFromProfile(mProfile, getArguments().getInt(ARG_HUE, -1));
332 checkInsecureSchemeWithAuth();
334 binding.url.addTextChangedListener(new TextWatcher() {
336 public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
338 public void onTextChanged(CharSequence s, int start, int before, int count) {}
340 public void afterTextChanged(Editable s) {
341 checkInsecureSchemeWithAuth();
345 binding.btnPickRingColor.setOnClickListener(v -> {
346 HueRingDialog d = new HueRingDialog(ProfileDetailFragment.this.requireContext(),
347 model.initialThemeHue, (Integer) v.getTag());
349 d.setColorSelectedListener(model::setThemeId);
352 binding.profileName.requestFocus();
354 private void chooseAPIVersion(View v) {
355 Activity context = getActivity();
356 ProfileDetailModel model = getModel();
357 MenuInflater mi = new MenuInflater(context);
358 PopupMenu menu = new PopupMenu(context, v);
359 menu.inflate(R.menu.api_version);
360 menu.setOnMenuItemClickListener(item -> {
362 int itemId = item.getItemId();
363 if (itemId == R.id.api_version_menu_html) {
366 else if (itemId == R.id.api_version_menu_1_19_1) {
367 apiVer = API.v1_19_1;
369 else if (itemId == R.id.api_version_menu_1_15) {
372 else if (itemId == R.id.api_version_menu_1_14) {
378 model.setApiVersion(apiVer);
379 binding.apiVersionText.setText(apiVer.getDescription(getResources()));
384 private MobileLedgerProfile.FutureDates futureDatesSettingFromMenuItemId(int itemId) {
385 if (itemId == R.id.menu_future_dates_7) {
386 return MobileLedgerProfile.FutureDates.OneWeek;
388 else if (itemId == R.id.menu_future_dates_14) {
389 return MobileLedgerProfile.FutureDates.TwoWeeks;
391 else if (itemId == R.id.menu_future_dates_30) {
392 return MobileLedgerProfile.FutureDates.OneMonth;
394 else if (itemId == R.id.menu_future_dates_60) {
395 return MobileLedgerProfile.FutureDates.TwoMonths;
397 else if (itemId == R.id.menu_future_dates_90) {
398 return MobileLedgerProfile.FutureDates.ThreeMonths;
400 else if (itemId == R.id.menu_future_dates_180) {
401 return MobileLedgerProfile.FutureDates.SixMonths;
403 else if (itemId == R.id.menu_future_dates_365) {
404 return MobileLedgerProfile.FutureDates.OneYear;
406 else if (itemId == R.id.menu_future_dates_all) {
407 return MobileLedgerProfile.FutureDates.All;
409 return MobileLedgerProfile.FutureDates.None;
412 private ProfileDetailModel getModel() {
413 return new ViewModelProvider(requireActivity()).get(ProfileDetailModel.class);
415 private void onSaveFabClicked() {
416 if (!checkValidity())
419 ProfileDetailModel model = getModel();
420 final ArrayList<MobileLedgerProfile> profiles =
421 Objects.requireNonNull(Data.profiles.getValue());
423 if (mProfile != null) {
424 int pos = Data.profiles.getValue()
426 mProfile = new MobileLedgerProfile(mProfile);
427 model.updateProfile(mProfile);
428 mProfile.storeInDB();
429 debug("profiles", "profile stored in DB");
430 profiles.set(pos, mProfile);
431 // debug("profiles", String.format("Selected item is %d", mProfile.getThemeHue()));
433 final MobileLedgerProfile currentProfile = Data.getProfile();
434 if (mProfile.getUuid()
435 .equals(currentProfile.getUuid()))
437 Data.setCurrentProfile(mProfile);
440 ProfilesRecyclerViewAdapter viewAdapter = ProfilesRecyclerViewAdapter.getInstance();
441 if (viewAdapter != null)
442 viewAdapter.notifyItemChanged(pos);
445 mProfile = new MobileLedgerProfile(String.valueOf(UUID.randomUUID()));
446 model.updateProfile(mProfile);
447 mProfile.storeInDB();
448 final ArrayList<MobileLedgerProfile> newList = new ArrayList<>(profiles);
449 newList.add(mProfile);
450 Data.profiles.setValue(newList);
451 MobileLedgerProfile.storeProfilesOrder();
453 // first profile ever?
454 if (newList.size() == 1)
455 Data.setCurrentProfile(mProfile);
458 Activity activity = getActivity();
459 if (activity != null)
462 private boolean checkUrlValidity() {
463 boolean valid = true;
465 ProfileDetailModel model = getModel();
467 String val = model.getUrl()
471 binding.urlLayout.setError(getResources().getText(R.string.err_profile_url_empty));
474 URL url = new URL(val);
475 String host = url.getHost();
476 if (host == null || host.isEmpty())
477 throw new MalformedURLException("Missing host");
478 String protocol = url.getProtocol()
480 if (!protocol.equals("HTTP") && !protocol.equals("HTTPS")) {
482 binding.urlLayout.setError(getResources().getText(R.string.err_invalid_url));
485 catch (MalformedURLException e) {
487 binding.urlLayout.setError(getResources().getText(R.string.err_invalid_url));
492 private void checkInsecureSchemeWithAuth() {
493 boolean showWarning = false;
495 final ProfileDetailModel model = getModel();
497 if (model.getUseAuthentication()) {
498 String urlText = model.getUrl();
499 if (urlText.startsWith("http") && !urlText.startsWith("https"))
504 binding.insecureSchemeText.setVisibility(View.VISIBLE);
506 binding.insecureSchemeText.setVisibility(View.GONE);
508 private void hookClearErrorOnFocusListener(TextView view, TextInputLayout layout) {
509 view.setOnFocusChangeListener((v, hasFocus) -> {
511 layout.setError(null);
513 view.addTextChangedListener(new TextWatcher() {
515 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
518 public void onTextChanged(CharSequence s, int start, int before, int count) {
519 layout.setError(null);
522 public void afterTextChanged(Editable s) {
526 private void syncModelFromUI() {
527 if (syncingModelFromUI)
530 syncingModelFromUI = true;
533 ProfileDetailModel model = getModel();
535 model.setProfileName(binding.profileName.getText());
536 model.setUrl(binding.url.getText());
537 model.setPreferredAccountsFilter(binding.preferredAccountsFilter.getText());
538 model.setAuthUserName(binding.authUserName.getText());
539 model.setAuthPassword(binding.password.getText());
542 syncingModelFromUI = false;
545 private boolean checkValidity() {
546 boolean valid = true;
548 String val = String.valueOf(binding.profileName.getText());
553 binding.profileNameLayout.setError(
554 getResources().getText(R.string.err_profile_name_empty));
557 if (!checkUrlValidity())
560 if (binding.enableHttpAuth.isChecked()) {
561 val = String.valueOf(binding.authUserName.getText());
566 binding.authUserNameLayout.setError(
567 getResources().getText(R.string.err_profile_user_name_empty));
570 val = String.valueOf(binding.password.getText());
575 binding.passwordLayout.setError(
576 getResources().getText(R.string.err_profile_password_empty));
582 private void resetDefaultCommodity() {
583 defaultCommoditySet = false;
584 binding.defaultCommodityText.setText(R.string.btn_no_currency);
585 binding.defaultCommodityText.setTypeface(binding.defaultCommodityText.getTypeface(),
588 private void setDefaultCommodity(@NonNull @NotNull String name) {
589 defaultCommoditySet = true;
590 binding.defaultCommodityText.setText(name);
591 binding.defaultCommodityText.setTypeface(Typeface.DEFAULT);
593 interface TextChangeSyncRoutine {
594 void onTextChanged(String text);