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.floatingactionbutton.FloatingActionButton;
44 import com.google.android.material.textfield.TextInputLayout;
46 import net.ktnx.mobileledger.BuildConfig;
47 import net.ktnx.mobileledger.R;
48 import net.ktnx.mobileledger.dao.BaseDAO;
49 import net.ktnx.mobileledger.dao.ProfileDAO;
50 import net.ktnx.mobileledger.databinding.ProfileDetailBinding;
51 import net.ktnx.mobileledger.db.DB;
52 import net.ktnx.mobileledger.db.Profile;
53 import net.ktnx.mobileledger.json.API;
54 import net.ktnx.mobileledger.model.Data;
55 import net.ktnx.mobileledger.model.FutureDates;
56 import net.ktnx.mobileledger.ui.CurrencySelectorFragment;
57 import net.ktnx.mobileledger.ui.HueRingDialog;
58 import net.ktnx.mobileledger.utils.Colors;
59 import net.ktnx.mobileledger.utils.Misc;
61 import org.jetbrains.annotations.NonNls;
62 import org.jetbrains.annotations.NotNull;
64 import java.net.MalformedURLException;
66 import java.util.List;
67 import java.util.Objects;
69 import static net.ktnx.mobileledger.utils.Logger.debug;
72 * A fragment representing a single Profile detail screen.
73 * a {@link ProfileDetailActivity}
76 public class ProfileDetailFragment extends Fragment {
78 * The fragment argument representing the item ID that this fragment
81 public static final String ARG_ITEM_ID = "item_id";
82 public static final String ARG_HUE = "hue";
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 List<Profile> profiles = Data.profiles.getValue();
104 final MenuItem menuWipeProfileData = menu.findItem(R.id.menuWipeData);
105 if (BuildConfig.DEBUG)
106 menuWipeProfileData.setOnMenuItemClickListener(ignored -> onWipeDataMenuClicked());
108 getModel().getProfileId()
109 .observe(getViewLifecycleOwner(), id -> {
110 menuDeleteProfile.setVisible(id > 0);
111 if (BuildConfig.DEBUG)
112 menuWipeProfileData.setVisible(id > 0);
115 private boolean onDeleteProfile() {
116 AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
117 @NotNull ProfileDetailModel model = getModel();
118 builder.setTitle(model.getProfileName());
119 builder.setMessage(R.string.remove_profile_dialog_message);
120 builder.setPositiveButton(R.string.Remove, (dialog, which) -> {
121 final long profileId = Objects.requireNonNull(model.getProfileId()
123 debug("profiles", String.format("[fragment] removing profile %s", profileId));
124 ProfileDAO dao = DB.get()
126 dao.getById(profileId)
127 .observe(getViewLifecycleOwner(), profile -> {
129 BaseDAO.runAsync(() -> DB.get()
130 .runInTransaction(() -> {
131 dao.deleteSync(profile);
132 dao.updateOrderSync(dao.getAllOrderedSync());
136 final FragmentActivity activity = getActivity();
137 if (activity != null)
143 private boolean onWipeDataMenuClicked() {
144 // this is a development option, so no confirmation
147 .getById(Objects.requireNonNull(getModel().getProfileId()
149 .observe(getViewLifecycleOwner(), profile -> {
151 profile.wipeAllData();
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 final LifecycleOwner viewLifecycleOwner = getViewLifecycleOwner();
181 final ProfileDetailModel model = getModel();
183 model.observeDefaultCommodity(viewLifecycleOwner, c -> {
185 setDefaultCommodity(c);
187 resetDefaultCommodity();
190 FloatingActionButton fab = context.findViewById(R.id.fabAdd);
191 fab.setOnClickListener(v -> onSaveFabClicked());
193 hookTextChangeSyncRoutine(binding.profileName, model::setProfileName);
194 model.observeProfileName(viewLifecycleOwner, pn -> {
195 if (!Misc.equalStrings(pn, Misc.nullIsEmpty(binding.profileName.getText())))
196 binding.profileName.setText(pn);
199 hookTextChangeSyncRoutine(binding.url, model::setUrl);
200 model.observeUrl(viewLifecycleOwner, u -> {
201 if (!Misc.equalStrings(u, Misc.nullIsEmpty(binding.url.getText())))
202 binding.url.setText(u);
205 binding.defaultCommodityLayout.setOnClickListener(v -> {
206 CurrencySelectorFragment cpf = CurrencySelectorFragment.newInstance(
207 CurrencySelectorFragment.DEFAULT_COLUMN_COUNT, false);
208 cpf.setOnCurrencySelectedListener(model::setDefaultCommodity);
209 final AppCompatActivity activity = (AppCompatActivity) v.getContext();
210 cpf.show(activity.getSupportFragmentManager(), "currency-selector");
213 binding.profileShowCommodity.setOnCheckedChangeListener(
214 (buttonView, isChecked) -> model.setShowCommodityByDefault(isChecked));
215 model.observeShowCommodityByDefault(viewLifecycleOwner,
216 binding.profileShowCommodity::setChecked);
218 model.observePostingPermitted(viewLifecycleOwner, isChecked -> {
219 binding.profilePermitPosting.setChecked(isChecked);
220 binding.postingSubItems.setVisibility(isChecked ? View.VISIBLE : View.GONE);
222 binding.profilePermitPosting.setOnCheckedChangeListener(
223 ((buttonView, isChecked) -> model.setPostingPermitted(isChecked)));
225 model.observeShowCommentsByDefault(viewLifecycleOwner,
226 binding.profileShowComments::setChecked);
227 binding.profileShowComments.setOnCheckedChangeListener(
228 ((buttonView, isChecked) -> model.setShowCommentsByDefault(isChecked)));
230 binding.futureDatesLayout.setOnClickListener(v -> {
231 MenuInflater mi = new MenuInflater(context);
232 PopupMenu menu = new PopupMenu(context, v);
233 menu.inflate(R.menu.future_dates);
234 menu.setOnMenuItemClickListener(item -> {
235 model.setFutureDates(futureDatesSettingFromMenuItemId(item.getItemId()));
240 model.observeFutureDates(viewLifecycleOwner,
241 v -> binding.futureDatesText.setText(v.getText(getResources())));
243 model.observeApiVersion(viewLifecycleOwner,
244 apiVer -> binding.apiVersionText.setText(apiVer.getDescription(getResources())));
245 binding.apiVersionLabel.setOnClickListener(this::chooseAPIVersion);
246 binding.apiVersionText.setOnClickListener(this::chooseAPIVersion);
248 binding.serverVersionLabel.setOnClickListener(v -> model.triggerVersionDetection());
249 model.observeDetectedVersion(viewLifecycleOwner, ver -> {
251 binding.detectedServerVersionText.setText(context.getResources()
253 R.string.server_version_unknown_label));
254 else if (ver.isPre_1_20_1())
255 binding.detectedServerVersionText.setText(context.getResources()
257 R.string.detected_server_pre_1_20_1));
259 binding.detectedServerVersionText.setText(ver.toString());
261 binding.detectedServerVersionText.setOnClickListener(v -> model.triggerVersionDetection());
262 binding.serverVersionDetectButton.setOnClickListener(v -> model.triggerVersionDetection());
263 model.observeDetectingHledgerVersion(viewLifecycleOwner,
264 running -> binding.serverVersionDetectButton.setVisibility(
265 running ? View.VISIBLE : View.INVISIBLE));
267 binding.enableHttpAuth.setOnCheckedChangeListener((buttonView, isChecked) -> {
268 boolean wasOn = model.getUseAuthentication();
269 model.setUseAuthentication(isChecked);
270 if (!wasOn && isChecked)
271 binding.authUserName.requestFocus();
273 model.observeUseAuthentication(viewLifecycleOwner, isChecked -> {
274 binding.enableHttpAuth.setChecked(isChecked);
275 binding.authParams.setVisibility(isChecked ? View.VISIBLE : View.GONE);
276 checkInsecureSchemeWithAuth();
279 model.observeUserName(viewLifecycleOwner, text -> {
280 if (!Misc.equalStrings(text, Misc.nullIsEmpty(binding.authUserName.getText())))
281 binding.authUserName.setText(text);
283 hookTextChangeSyncRoutine(binding.authUserName, model::setAuthUserName);
285 model.observePassword(viewLifecycleOwner, text -> {
286 if (!Misc.equalStrings(text, Misc.nullIsEmpty(binding.password.getText())))
287 binding.password.setText(text);
289 hookTextChangeSyncRoutine(binding.password, model::setAuthPassword);
291 model.observeThemeId(viewLifecycleOwner, themeId -> {
292 final int hue = (themeId == -1) ? Colors.DEFAULT_HUE_DEG : themeId;
293 final int profileColor = Colors.getPrimaryColorForHue(hue);
294 binding.btnPickRingColor.setBackgroundColor(profileColor);
295 binding.btnPickRingColor.setTag(hue);
298 model.observePreferredAccountsFilter(viewLifecycleOwner, text -> {
299 if (!Misc.equalStrings(text,
300 Misc.nullIsEmpty(binding.preferredAccountsFilter.getText())))
301 binding.preferredAccountsFilter.setText(text);
303 hookTextChangeSyncRoutine(binding.preferredAccountsFilter,
304 model::setPreferredAccountsFilter);
306 hookClearErrorOnFocusListener(binding.profileName, binding.profileNameLayout);
307 hookClearErrorOnFocusListener(binding.url, binding.urlLayout);
308 hookClearErrorOnFocusListener(binding.authUserName, binding.authUserNameLayout);
309 hookClearErrorOnFocusListener(binding.password, binding.passwordLayout);
311 binding.url.addTextChangedListener(new TextWatcher() {
313 public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
315 public void onTextChanged(CharSequence s, int start, int before, int count) {}
317 public void afterTextChanged(Editable s) {
318 checkInsecureSchemeWithAuth();
322 binding.btnPickRingColor.setOnClickListener(v -> {
323 HueRingDialog d = new HueRingDialog(ProfileDetailFragment.this.requireContext(),
324 model.initialThemeHue, (Integer) v.getTag());
326 d.setColorSelectedListener(model::setThemeId);
329 binding.profileName.requestFocus();
331 private void chooseAPIVersion(View v) {
332 Activity context = getActivity();
333 ProfileDetailModel model = getModel();
334 MenuInflater mi = new MenuInflater(context);
335 PopupMenu menu = new PopupMenu(context, v);
336 menu.inflate(R.menu.api_version);
337 menu.setOnMenuItemClickListener(item -> {
339 int itemId = item.getItemId();
340 if (itemId == R.id.api_version_menu_html) {
343 else if (itemId == R.id.api_version_menu_1_19_1) {
344 apiVer = API.v1_19_1;
346 else if (itemId == R.id.api_version_menu_1_15) {
349 else if (itemId == R.id.api_version_menu_1_14) {
355 model.setApiVersion(apiVer);
356 binding.apiVersionText.setText(apiVer.getDescription(getResources()));
361 private FutureDates futureDatesSettingFromMenuItemId(int itemId) {
362 if (itemId == R.id.menu_future_dates_7) {
363 return FutureDates.OneWeek;
365 else if (itemId == R.id.menu_future_dates_14) {
366 return FutureDates.TwoWeeks;
368 else if (itemId == R.id.menu_future_dates_30) {
369 return FutureDates.OneMonth;
371 else if (itemId == R.id.menu_future_dates_60) {
372 return FutureDates.TwoMonths;
374 else if (itemId == R.id.menu_future_dates_90) {
375 return FutureDates.ThreeMonths;
377 else if (itemId == R.id.menu_future_dates_180) {
378 return FutureDates.SixMonths;
380 else if (itemId == R.id.menu_future_dates_365) {
381 return FutureDates.OneYear;
383 else if (itemId == R.id.menu_future_dates_all) {
384 return FutureDates.All;
386 return FutureDates.None;
389 private ProfileDetailModel getModel() {
390 return new ViewModelProvider(requireActivity()).get(ProfileDetailModel.class);
392 private void onSaveFabClicked() {
393 if (!checkValidity())
396 ProfileDetailModel model = getModel();
397 ProfileDAO dao = DB.get()
400 Profile profile = new Profile();
401 model.updateProfile(profile);
402 if (profile.getId() > 0) {
404 debug("profiles", "profile stored in DB");
405 // debug("profiles", String.format("Selected item is %d", mProfile.getThemeHue()));
408 dao.insertLast(profile, null);
411 Activity activity = getActivity();
412 if (activity != null)
415 private boolean checkUrlValidity() {
416 boolean valid = true;
418 ProfileDetailModel model = getModel();
420 String val = model.getUrl()
424 binding.urlLayout.setError(getResources().getText(R.string.err_profile_url_empty));
427 URL url = new URL(val);
428 String host = url.getHost();
429 if (host == null || host.isEmpty())
430 throw new MalformedURLException("Missing host");
431 String protocol = url.getProtocol()
433 if (!protocol.equals("HTTP") && !protocol.equals("HTTPS")) {
435 binding.urlLayout.setError(getResources().getText(R.string.err_invalid_url));
438 catch (MalformedURLException e) {
440 binding.urlLayout.setError(getResources().getText(R.string.err_invalid_url));
445 private void checkInsecureSchemeWithAuth() {
446 boolean showWarning = false;
448 final ProfileDetailModel model = getModel();
450 if (model.getUseAuthentication()) {
451 String urlText = model.getUrl();
452 if (urlText.startsWith("http://") ||
453 urlText.length() >= 8 && !urlText.startsWith("https://"))
458 binding.insecureSchemeText.setVisibility(View.VISIBLE);
460 binding.insecureSchemeText.setVisibility(View.GONE);
462 private void hookClearErrorOnFocusListener(TextView view, TextInputLayout layout) {
463 view.setOnFocusChangeListener((v, hasFocus) -> {
465 layout.setError(null);
467 view.addTextChangedListener(new TextWatcher() {
469 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
472 public void onTextChanged(CharSequence s, int start, int before, int count) {
473 layout.setError(null);
476 public void afterTextChanged(Editable s) {
480 private void syncModelFromUI() {
481 if (syncingModelFromUI)
484 syncingModelFromUI = true;
487 ProfileDetailModel model = getModel();
489 model.setProfileName(binding.profileName.getText());
490 model.setUrl(binding.url.getText());
491 model.setPreferredAccountsFilter(binding.preferredAccountsFilter.getText());
492 model.setAuthUserName(binding.authUserName.getText());
493 model.setAuthPassword(binding.password.getText());
496 syncingModelFromUI = false;
499 private boolean checkValidity() {
500 boolean valid = true;
502 String val = String.valueOf(binding.profileName.getText());
507 binding.profileNameLayout.setError(
508 getResources().getText(R.string.err_profile_name_empty));
511 if (!checkUrlValidity())
514 if (binding.enableHttpAuth.isChecked()) {
515 val = String.valueOf(binding.authUserName.getText());
520 binding.authUserNameLayout.setError(
521 getResources().getText(R.string.err_profile_user_name_empty));
524 val = String.valueOf(binding.password.getText());
529 binding.passwordLayout.setError(
530 getResources().getText(R.string.err_profile_password_empty));
536 private void resetDefaultCommodity() {
537 defaultCommoditySet = false;
538 binding.defaultCommodityText.setText(R.string.btn_no_currency);
539 binding.defaultCommodityText.setTypeface(binding.defaultCommodityText.getTypeface(),
542 private void setDefaultCommodity(@NonNull @NotNull String name) {
543 defaultCommoditySet = true;
544 binding.defaultCommodityText.setText(name);
545 binding.defaultCommodityText.setTypeface(Typeface.DEFAULT);
547 interface TextChangeSyncRoutine {
548 void onTextChanged(String text);