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.AsyncTask;
24 import android.os.Bundle;
25 import android.text.Editable;
26 import android.text.TextWatcher;
27 import android.view.LayoutInflater;
28 import android.view.Menu;
29 import android.view.MenuInflater;
30 import android.view.MenuItem;
31 import android.view.View;
32 import android.view.ViewGroup;
33 import android.widget.PopupMenu;
34 import android.widget.TextView;
36 import androidx.annotation.NonNull;
37 import androidx.annotation.Nullable;
38 import androidx.appcompat.app.AppCompatActivity;
39 import androidx.fragment.app.Fragment;
40 import androidx.fragment.app.FragmentActivity;
41 import androidx.lifecycle.LifecycleOwner;
42 import androidx.lifecycle.ViewModelProvider;
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.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 AsyncTask.execute(() -> {
130 dao.deleteSync(profile);
131 dao.updateOrderSync(dao.getAllOrderedSync());
135 final FragmentActivity activity = getActivity();
136 if (activity != null)
142 private boolean onWipeDataMenuClicked() {
143 // this is a development option, so no confirmation
146 .getById(Objects.requireNonNull(getModel().getProfileId()
148 .observe(getViewLifecycleOwner(), profile -> {
150 profile.wipeAllData();
154 private void hookTextChangeSyncRoutine(TextView view, TextChangeSyncRoutine syncRoutine) {
155 view.addTextChangedListener(new TextWatcher() {
157 public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
159 public void onTextChanged(CharSequence s, int start, int before, int count) {}
161 public void afterTextChanged(Editable s) { syncRoutine.onTextChanged(s.toString());}
166 public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
167 @Nullable Bundle savedInstanceState) {
168 binding = ProfileDetailBinding.inflate(inflater, container, false);
170 return binding.getRoot();
173 public void onViewCreated(@NotNull View view, @Nullable Bundle savedInstanceState) {
174 super.onViewCreated(view, savedInstanceState);
175 Activity context = getActivity();
179 final LifecycleOwner viewLifecycleOwner = getViewLifecycleOwner();
180 final ProfileDetailModel model = getModel();
182 model.observeDefaultCommodity(viewLifecycleOwner, c -> {
184 setDefaultCommodity(c);
186 resetDefaultCommodity();
189 FloatingActionButton fab = context.findViewById(R.id.fabAdd);
190 fab.setOnClickListener(v -> onSaveFabClicked());
192 hookTextChangeSyncRoutine(binding.profileName, model::setProfileName);
193 model.observeProfileName(viewLifecycleOwner, pn -> {
194 if (!Misc.equalStrings(pn, Misc.nullIsEmpty(binding.profileName.getText())))
195 binding.profileName.setText(pn);
198 hookTextChangeSyncRoutine(binding.url, model::setUrl);
199 model.observeUrl(viewLifecycleOwner, u -> {
200 if (!Misc.equalStrings(u, Misc.nullIsEmpty(binding.url.getText())))
201 binding.url.setText(u);
204 binding.defaultCommodityLayout.setOnClickListener(v -> {
205 CurrencySelectorFragment cpf = CurrencySelectorFragment.newInstance(
206 CurrencySelectorFragment.DEFAULT_COLUMN_COUNT, false);
207 cpf.setOnCurrencySelectedListener(model::setDefaultCommodity);
208 final AppCompatActivity activity = (AppCompatActivity) v.getContext();
209 cpf.show(activity.getSupportFragmentManager(), "currency-selector");
212 binding.profileShowCommodity.setOnCheckedChangeListener(
213 (buttonView, isChecked) -> model.setShowCommodityByDefault(isChecked));
214 model.observeShowCommodityByDefault(viewLifecycleOwner,
215 binding.profileShowCommodity::setChecked);
217 model.observePostingPermitted(viewLifecycleOwner, isChecked -> {
218 binding.profilePermitPosting.setChecked(isChecked);
219 binding.postingSubItems.setVisibility(isChecked ? View.VISIBLE : View.GONE);
221 binding.profilePermitPosting.setOnCheckedChangeListener(
222 ((buttonView, isChecked) -> model.setPostingPermitted(isChecked)));
224 model.observeShowCommentsByDefault(viewLifecycleOwner,
225 binding.profileShowComments::setChecked);
226 binding.profileShowComments.setOnCheckedChangeListener(
227 ((buttonView, isChecked) -> model.setShowCommentsByDefault(isChecked)));
229 binding.futureDatesLayout.setOnClickListener(v -> {
230 MenuInflater mi = new MenuInflater(context);
231 PopupMenu menu = new PopupMenu(context, v);
232 menu.inflate(R.menu.future_dates);
233 menu.setOnMenuItemClickListener(item -> {
234 model.setFutureDates(futureDatesSettingFromMenuItemId(item.getItemId()));
239 model.observeFutureDates(viewLifecycleOwner,
240 v -> binding.futureDatesText.setText(v.getText(getResources())));
242 model.observeApiVersion(viewLifecycleOwner,
243 apiVer -> binding.apiVersionText.setText(apiVer.getDescription(getResources())));
244 binding.apiVersionLabel.setOnClickListener(this::chooseAPIVersion);
245 binding.apiVersionText.setOnClickListener(this::chooseAPIVersion);
247 binding.serverVersionLabel.setOnClickListener(v -> model.triggerVersionDetection());
248 model.observeDetectedVersion(viewLifecycleOwner, ver -> {
250 binding.detectedServerVersionText.setText(context.getResources()
252 R.string.server_version_unknown_label));
253 else if (ver.isPre_1_20_1())
254 binding.detectedServerVersionText.setText(context.getResources()
256 R.string.detected_server_pre_1_20_1));
258 binding.detectedServerVersionText.setText(ver.toString());
260 binding.detectedServerVersionText.setOnClickListener(v -> model.triggerVersionDetection());
261 binding.serverVersionDetectButton.setOnClickListener(v -> model.triggerVersionDetection());
262 model.observeDetectingHledgerVersion(viewLifecycleOwner,
263 running -> binding.serverVersionDetectButton.setVisibility(
264 running ? View.VISIBLE : View.INVISIBLE));
266 binding.enableHttpAuth.setOnCheckedChangeListener((buttonView, isChecked) -> {
267 boolean wasOn = model.getUseAuthentication();
268 model.setUseAuthentication(isChecked);
269 if (!wasOn && isChecked)
270 binding.authUserName.requestFocus();
272 model.observeUseAuthentication(viewLifecycleOwner, isChecked -> {
273 binding.enableHttpAuth.setChecked(isChecked);
274 binding.authParams.setVisibility(isChecked ? View.VISIBLE : View.GONE);
275 checkInsecureSchemeWithAuth();
278 model.observeUserName(viewLifecycleOwner, text -> {
279 if (!Misc.equalStrings(text, Misc.nullIsEmpty(binding.authUserName.getText())))
280 binding.authUserName.setText(text);
282 hookTextChangeSyncRoutine(binding.authUserName, model::setAuthUserName);
284 model.observePassword(viewLifecycleOwner, text -> {
285 if (!Misc.equalStrings(text, Misc.nullIsEmpty(binding.password.getText())))
286 binding.password.setText(text);
288 hookTextChangeSyncRoutine(binding.password, model::setAuthPassword);
290 model.observeThemeId(viewLifecycleOwner, themeId -> {
291 final int hue = (themeId == -1) ? Colors.DEFAULT_HUE_DEG : themeId;
292 final int profileColor = Colors.getPrimaryColorForHue(hue);
293 binding.btnPickRingColor.setBackgroundColor(profileColor);
294 binding.btnPickRingColor.setTag(hue);
297 model.observePreferredAccountsFilter(viewLifecycleOwner, text -> {
298 if (!Misc.equalStrings(text,
299 Misc.nullIsEmpty(binding.preferredAccountsFilter.getText())))
300 binding.preferredAccountsFilter.setText(text);
302 hookTextChangeSyncRoutine(binding.preferredAccountsFilter,
303 model::setPreferredAccountsFilter);
305 hookClearErrorOnFocusListener(binding.profileName, binding.profileNameLayout);
306 hookClearErrorOnFocusListener(binding.url, binding.urlLayout);
307 hookClearErrorOnFocusListener(binding.authUserName, binding.authUserNameLayout);
308 hookClearErrorOnFocusListener(binding.password, binding.passwordLayout);
310 binding.url.addTextChangedListener(new TextWatcher() {
312 public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
314 public void onTextChanged(CharSequence s, int start, int before, int count) {}
316 public void afterTextChanged(Editable s) {
317 checkInsecureSchemeWithAuth();
321 binding.btnPickRingColor.setOnClickListener(v -> {
322 HueRingDialog d = new HueRingDialog(ProfileDetailFragment.this.requireContext(),
323 model.initialThemeHue, (Integer) v.getTag());
325 d.setColorSelectedListener(model::setThemeId);
328 binding.profileName.requestFocus();
330 private void chooseAPIVersion(View v) {
331 Activity context = getActivity();
332 ProfileDetailModel model = getModel();
333 MenuInflater mi = new MenuInflater(context);
334 PopupMenu menu = new PopupMenu(context, v);
335 menu.inflate(R.menu.api_version);
336 menu.setOnMenuItemClickListener(item -> {
338 int itemId = item.getItemId();
339 if (itemId == R.id.api_version_menu_html) {
342 else if (itemId == R.id.api_version_menu_1_19_1) {
343 apiVer = API.v1_19_1;
345 else if (itemId == R.id.api_version_menu_1_15) {
348 else if (itemId == R.id.api_version_menu_1_14) {
354 model.setApiVersion(apiVer);
355 binding.apiVersionText.setText(apiVer.getDescription(getResources()));
360 private FutureDates futureDatesSettingFromMenuItemId(int itemId) {
361 if (itemId == R.id.menu_future_dates_7) {
362 return FutureDates.OneWeek;
364 else if (itemId == R.id.menu_future_dates_14) {
365 return FutureDates.TwoWeeks;
367 else if (itemId == R.id.menu_future_dates_30) {
368 return FutureDates.OneMonth;
370 else if (itemId == R.id.menu_future_dates_60) {
371 return FutureDates.TwoMonths;
373 else if (itemId == R.id.menu_future_dates_90) {
374 return FutureDates.ThreeMonths;
376 else if (itemId == R.id.menu_future_dates_180) {
377 return FutureDates.SixMonths;
379 else if (itemId == R.id.menu_future_dates_365) {
380 return FutureDates.OneYear;
382 else if (itemId == R.id.menu_future_dates_all) {
383 return FutureDates.All;
385 return FutureDates.None;
388 private ProfileDetailModel getModel() {
389 return new ViewModelProvider(requireActivity()).get(ProfileDetailModel.class);
391 private void onSaveFabClicked() {
392 if (!checkValidity())
395 ProfileDetailModel model = getModel();
396 ProfileDAO dao = DB.get()
399 Profile profile = new Profile();
400 model.updateProfile(profile);
401 if (profile.getId() > 0) {
403 debug("profiles", "profile stored in DB");
404 // debug("profiles", String.format("Selected item is %d", mProfile.getThemeHue()));
407 dao.insertLast(profile, null);
410 Activity activity = getActivity();
411 if (activity != null)
414 private boolean checkUrlValidity() {
415 boolean valid = true;
417 ProfileDetailModel model = getModel();
419 String val = model.getUrl()
423 binding.urlLayout.setError(getResources().getText(R.string.err_profile_url_empty));
426 URL url = new URL(val);
427 String host = url.getHost();
428 if (host == null || host.isEmpty())
429 throw new MalformedURLException("Missing host");
430 String protocol = url.getProtocol()
432 if (!protocol.equals("HTTP") && !protocol.equals("HTTPS")) {
434 binding.urlLayout.setError(getResources().getText(R.string.err_invalid_url));
437 catch (MalformedURLException e) {
439 binding.urlLayout.setError(getResources().getText(R.string.err_invalid_url));
444 private void checkInsecureSchemeWithAuth() {
445 boolean showWarning = false;
447 final ProfileDetailModel model = getModel();
449 if (model.getUseAuthentication()) {
450 String urlText = model.getUrl();
451 if (urlText.startsWith("http://") ||
452 urlText.length() >= 8 && !urlText.startsWith("https://"))
457 binding.insecureSchemeText.setVisibility(View.VISIBLE);
459 binding.insecureSchemeText.setVisibility(View.GONE);
461 private void hookClearErrorOnFocusListener(TextView view, TextInputLayout layout) {
462 view.setOnFocusChangeListener((v, hasFocus) -> {
464 layout.setError(null);
466 view.addTextChangedListener(new TextWatcher() {
468 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
471 public void onTextChanged(CharSequence s, int start, int before, int count) {
472 layout.setError(null);
475 public void afterTextChanged(Editable s) {
479 private void syncModelFromUI() {
480 if (syncingModelFromUI)
483 syncingModelFromUI = true;
486 ProfileDetailModel model = getModel();
488 model.setProfileName(binding.profileName.getText());
489 model.setUrl(binding.url.getText());
490 model.setPreferredAccountsFilter(binding.preferredAccountsFilter.getText());
491 model.setAuthUserName(binding.authUserName.getText());
492 model.setAuthPassword(binding.password.getText());
495 syncingModelFromUI = false;
498 private boolean checkValidity() {
499 boolean valid = true;
501 String val = String.valueOf(binding.profileName.getText());
506 binding.profileNameLayout.setError(
507 getResources().getText(R.string.err_profile_name_empty));
510 if (!checkUrlValidity())
513 if (binding.enableHttpAuth.isChecked()) {
514 val = String.valueOf(binding.authUserName.getText());
519 binding.authUserNameLayout.setError(
520 getResources().getText(R.string.err_profile_user_name_empty));
523 val = String.valueOf(binding.password.getText());
528 binding.passwordLayout.setError(
529 getResources().getText(R.string.err_profile_password_empty));
535 private void resetDefaultCommodity() {
536 defaultCommoditySet = false;
537 binding.defaultCommodityText.setText(R.string.btn_no_currency);
538 binding.defaultCommodityText.setTypeface(binding.defaultCommodityText.getTypeface(),
541 private void setDefaultCommodity(@NonNull @NotNull String name) {
542 defaultCommoditySet = true;
543 binding.defaultCommodityText.setText(name);
544 binding.defaultCommodityText.setTypeface(Typeface.DEFAULT);
546 interface TextChangeSyncRoutine {
547 void onTextChanged(String text);