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.UUID;
66 import static net.ktnx.mobileledger.utils.Logger.debug;
69 * A fragment representing a single Profile detail screen.
70 * a {@link ProfileDetailActivity}
73 public class ProfileDetailFragment extends Fragment {
75 * The fragment argument representing the item ID that this fragment
78 public static final String ARG_ITEM_ID = "item_id";
79 public static final String ARG_HUE = "hue";
82 private MobileLedgerProfile mProfile;
84 private TextView defaultCommodity;
85 private View defaultCommodityLayout;
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 TextInputLayout preferredAccountsFilterLayout;
98 private View huePickerView;
99 private View insecureWarningText;
100 private TextView futureDatesText;
101 private View futureDatesLayout;
102 private TextView apiVersionText;
103 private boolean syncingModelFromUI = false;
105 * Mandatory empty constructor for the fragment manager to instantiate the
106 * fragment (e.g. upon screen orientation changes).
108 public ProfileDetailFragment() {
109 super(R.layout.profile_detail);
112 public void onCreateOptionsMenu(@NotNull Menu menu, @NotNull MenuInflater inflater) {
113 debug("profiles", "[fragment] Creating profile details options menu");
114 super.onCreateOptionsMenu(menu, inflater);
115 inflater.inflate(R.menu.profile_details, menu);
116 final MenuItem menuDeleteProfile = menu.findItem(R.id.menuDelete);
117 menuDeleteProfile.setOnMenuItemClickListener(item -> {
118 AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
119 builder.setTitle(mProfile.getName());
120 builder.setMessage(R.string.remove_profile_dialog_message);
121 builder.setPositiveButton(R.string.Remove, (dialog, which) -> {
123 String.format("[fragment] removing profile %s", mProfile.getUuid()));
124 mProfile.removeFromDB();
125 ArrayList<MobileLedgerProfile> oldList = Data.profiles.getValue();
127 throw new AssertionError();
128 ArrayList<MobileLedgerProfile> newList = new ArrayList<>(oldList);
129 newList.remove(mProfile);
130 Data.profiles.setValue(newList);
131 if (mProfile.equals(Data.getProfile())) {
132 debug("profiles", "[fragment] setting current profile to 0");
133 Data.setCurrentProfile(newList.get(0));
136 final FragmentActivity activity = getActivity();
137 if (activity != null)
143 final ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
144 menuDeleteProfile.setVisible(
145 (mProfile != null) && (profiles != null) && (profiles.size() > 1));
147 if (BuildConfig.DEBUG) {
148 final MenuItem menuWipeProfileData = menu.findItem(R.id.menuWipeData);
149 menuWipeProfileData.setOnMenuItemClickListener(ignored -> onWipeDataMenuClicked());
150 menuWipeProfileData.setVisible(mProfile != null);
153 private boolean onWipeDataMenuClicked() {
154 // this is a development option, so no confirmation
155 mProfile.wipeAllData();
156 if (mProfile.equals(Data.getProfile()))
157 triggerProfileChange();
160 private void triggerProfileChange() {
161 int index = Data.getProfileIndex(mProfile);
162 MobileLedgerProfile newProfile = new MobileLedgerProfile(mProfile);
163 final ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
164 if (profiles == null)
165 throw new AssertionError();
166 profiles.set(index, newProfile);
168 ProfilesRecyclerViewAdapter viewAdapter = ProfilesRecyclerViewAdapter.getInstance();
169 if (viewAdapter != null)
170 viewAdapter.notifyItemChanged(index);
172 if (mProfile.equals(Data.getProfile()))
173 Data.setCurrentProfile(newProfile);
175 private void hookTextChangeSyncRoutine(TextView view, TextChangeSyncProc syncRoutine) {
176 view.addTextChangedListener(new TextWatcher() {
178 public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
180 public void onTextChanged(CharSequence s, int start, int before, int count) {}
182 public void afterTextChanged(Editable s) { syncRoutine.onTextChanged(s.toString());}
186 public void onActivityCreated(@Nullable Bundle savedInstanceState) {
187 super.onActivityCreated(savedInstanceState);
188 Activity context = getActivity();
192 if ((getArguments() != null) && getArguments().containsKey(ARG_ITEM_ID)) {
193 int index = getArguments().getInt(ARG_ITEM_ID, -1);
194 ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
195 if ((profiles != null) && (index != -1) && (index < profiles.size()))
196 mProfile = profiles.get(index);
198 Activity activity = this.getActivity();
199 if (activity == null)
200 throw new AssertionError();
201 CollapsingToolbarLayout appBarLayout = activity.findViewById(R.id.toolbar_layout);
202 if (appBarLayout != null) {
203 if (mProfile != null)
204 appBarLayout.setTitle(mProfile.getName());
206 appBarLayout.setTitle(getResources().getString(R.string.new_profile_title));
210 final LifecycleOwner viewLifecycleOwner = getViewLifecycleOwner();
211 final ProfileDetailModel model = getModel();
213 model.observeDefaultCommodity(viewLifecycleOwner, c -> {
215 setDefaultCommodity(c.getName());
217 resetDefaultCommodity();
220 FloatingActionButton fab = context.findViewById(R.id.fab);
221 fab.setOnClickListener(v -> onSaveFabClicked());
223 profileName = context.findViewById(R.id.profile_name);
224 hookTextChangeSyncRoutine(profileName, model::setProfileName);
225 model.observeProfileName(viewLifecycleOwner, pn -> {
226 if (!Misc.equalStrings(pn, profileName.getText()))
227 profileName.setText(pn);
230 profileNameLayout = context.findViewById(R.id.profile_name_layout);
232 url = context.findViewById(R.id.url);
233 hookTextChangeSyncRoutine(url, model::setUrl);
234 model.observeUrl(viewLifecycleOwner, u -> {
235 if (!Misc.equalStrings(u, url.getText()))
239 urlLayout = context.findViewById(R.id.url_layout);
241 defaultCommodityLayout = context.findViewById(R.id.default_commodity_layout);
242 defaultCommodityLayout.setOnClickListener(v -> {
243 CurrencySelectorFragment cpf = CurrencySelectorFragment.newInstance(
244 CurrencySelectorFragment.DEFAULT_COLUMN_COUNT, false);
245 cpf.setOnCurrencySelectedListener(model::setDefaultCommodity);
246 final AppCompatActivity activity = (AppCompatActivity) v.getContext();
247 cpf.show(activity.getSupportFragmentManager(), "currency-selector");
250 Switch showCommodityByDefault = context.findViewById(R.id.profile_show_commodity);
251 showCommodityByDefault.setOnCheckedChangeListener(
252 (buttonView, isChecked) -> model.setShowCommodityByDefault(isChecked));
253 model.observeShowCommodityByDefault(viewLifecycleOwner, showCommodityByDefault::setChecked);
255 View postingSubItems = context.findViewById(R.id.posting_sub_items);
257 Switch postingPermitted = context.findViewById(R.id.profile_permit_posting);
258 model.observePostingPermitted(viewLifecycleOwner, isChecked -> {
259 postingPermitted.setChecked(isChecked);
260 postingSubItems.setVisibility(isChecked ? View.VISIBLE : View.GONE);
262 postingPermitted.setOnCheckedChangeListener(
263 ((buttonView, isChecked) -> model.setPostingPermitted(isChecked)));
265 Switch showCommentsByDefault = context.findViewById(R.id.profile_show_comments);
266 model.observeShowCommentsByDefault(viewLifecycleOwner, isChecked -> {
267 showCommentsByDefault.setChecked(isChecked);
269 showCommentsByDefault.setOnCheckedChangeListener(
270 ((buttonView, isChecked) -> model.setShowCommentsByDefault(isChecked)));
272 defaultCommodity = context.findViewById(R.id.default_commodity_text);
274 futureDatesLayout = context.findViewById(R.id.future_dates_layout);
275 futureDatesText = context.findViewById(R.id.future_dates_text);
276 context.findViewById(R.id.future_dates_layout)
277 .setOnClickListener(v -> {
278 MenuInflater mi = new MenuInflater(context);
279 PopupMenu menu = new PopupMenu(context, v);
280 menu.inflate(R.menu.future_dates);
281 menu.setOnMenuItemClickListener(item -> {
282 model.setFutureDates(futureDatesSettingFromMenuItemId(item.getItemId()));
287 model.observeFutureDates(viewLifecycleOwner,
288 v -> futureDatesText.setText(v.getText(getResources())));
290 apiVersionText = context.findViewById(R.id.api_version_text);
291 model.observeApiVersion(viewLifecycleOwner, apiVer -> {
292 apiVersionText.setText(apiVer.getDescription(getResources()));
294 context.findViewById(R.id.api_version_layout)
295 .setOnClickListener(v -> {
296 MenuInflater mi = new MenuInflater(context);
297 PopupMenu menu = new PopupMenu(context, v);
298 menu.inflate(R.menu.api_version);
299 menu.setOnMenuItemClickListener(item -> {
300 SendTransactionTask.API apiVer;
301 switch (item.getItemId()) {
302 case R.id.api_version_menu_html:
303 apiVer = SendTransactionTask.API.html;
305 case R.id.api_version_menu_post_1_14:
306 apiVer = SendTransactionTask.API.post_1_14;
308 case R.id.api_version_menu_pre_1_15:
309 apiVer = SendTransactionTask.API.pre_1_15;
311 case R.id.api_version_menu_auto:
313 apiVer = SendTransactionTask.API.auto;
315 model.setApiVersion(apiVer);
316 apiVersionText.setText(apiVer.getDescription(getResources()));
321 authParams = context.findViewById(R.id.auth_params);
323 useAuthentication = context.findViewById(R.id.enable_http_auth);
324 useAuthentication.setOnCheckedChangeListener((buttonView, isChecked) -> {
325 model.setUseAuthentication(isChecked);
327 userName.requestFocus();
329 model.observeUseAuthentication(viewLifecycleOwner, isChecked -> {
330 useAuthentication.setChecked(isChecked);
331 authParams.setVisibility(isChecked ? View.VISIBLE : View.GONE);
332 checkInsecureSchemeWithAuth();
335 userName = context.findViewById(R.id.auth_user_name);
336 model.observeUserName(viewLifecycleOwner, text -> {
337 if (!Misc.equalStrings(text, userName.getText()))
338 userName.setText(text);
340 hookTextChangeSyncRoutine(userName, model::setAuthUserName);
341 userNameLayout = context.findViewById(R.id.auth_user_name_layout);
343 password = context.findViewById(R.id.password);
344 model.observePassword(viewLifecycleOwner, text -> {
345 if (!Misc.equalStrings(text, password.getText()))
346 password.setText(text);
348 hookTextChangeSyncRoutine(password, model::setAuthPassword);
349 passwordLayout = context.findViewById(R.id.password_layout);
351 huePickerView = context.findViewById(R.id.btn_pick_ring_color);
352 model.observeThemeId(viewLifecycleOwner, themeId -> {
353 final int hue = (themeId == -1) ? Colors.DEFAULT_HUE_DEG : themeId;
354 final int profileColor = Colors.getPrimaryColorForHue(hue);
355 huePickerView.setBackgroundColor(profileColor);
356 huePickerView.setTag(hue);
359 preferredAccountsFilter = context.findViewById(R.id.preferred_accounts_filter_filter);
360 model.observePreferredAccountsFilter(viewLifecycleOwner, text -> {
361 if (!Misc.equalStrings(text, preferredAccountsFilter.getText()))
362 preferredAccountsFilter.setText(text);
364 hookTextChangeSyncRoutine(preferredAccountsFilter, model::setPreferredAccountsFilter);
365 preferredAccountsFilterLayout =
366 context.findViewById(R.id.preferred_accounts_accounts_filter_layout);
368 insecureWarningText = context.findViewById(R.id.insecure_scheme_text);
370 hookClearErrorOnFocusListener(profileName, profileNameLayout);
371 hookClearErrorOnFocusListener(url, urlLayout);
372 hookClearErrorOnFocusListener(userName, userNameLayout);
373 hookClearErrorOnFocusListener(password, passwordLayout);
375 if (savedInstanceState == null) {
376 model.setValuesFromProfile(mProfile, getArguments().getInt(ARG_HUE, -1));
378 checkInsecureSchemeWithAuth();
380 url.addTextChangedListener(new TextWatcher() {
382 public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
384 public void onTextChanged(CharSequence s, int start, int before, int count) {}
386 public void afterTextChanged(Editable s) {
387 checkInsecureSchemeWithAuth();
391 huePickerView.setOnClickListener(v -> {
392 HueRingDialog d = new HueRingDialog(ProfileDetailFragment.this.requireContext(),
393 model.initialThemeHue, (Integer) v.getTag());
395 d.setColorSelectedListener(model::setThemeId);
398 profileName.requestFocus();
400 private MobileLedgerProfile.FutureDates futureDatesSettingFromMenuItemId(int itemId) {
402 case R.id.menu_future_dates_7:
403 return MobileLedgerProfile.FutureDates.OneWeek;
404 case R.id.menu_future_dates_14:
405 return MobileLedgerProfile.FutureDates.TwoWeeks;
406 case R.id.menu_future_dates_30:
407 return MobileLedgerProfile.FutureDates.OneMonth;
408 case R.id.menu_future_dates_60:
409 return MobileLedgerProfile.FutureDates.TwoMonths;
410 case R.id.menu_future_dates_90:
411 return MobileLedgerProfile.FutureDates.ThreeMonths;
412 case R.id.menu_future_dates_180:
413 return MobileLedgerProfile.FutureDates.SixMonths;
414 case R.id.menu_future_dates_365:
415 return MobileLedgerProfile.FutureDates.OneYear;
416 case R.id.menu_future_dates_all:
417 return MobileLedgerProfile.FutureDates.All;
419 return MobileLedgerProfile.FutureDates.None;
423 private ProfileDetailModel getModel() {
424 return new ViewModelProvider(requireActivity()).get(ProfileDetailModel.class);
426 private void onSaveFabClicked() {
427 if (!checkValidity())
430 ProfileDetailModel model = getModel();
432 if (mProfile != null) {
433 model.updateProfile(mProfile);
434 // debug("profiles", String.format("Selected item is %d", mProfile.getThemeHue()));
435 mProfile.storeInDB();
436 debug("profiles", "profile stored in DB");
437 triggerProfileChange();
440 mProfile = new MobileLedgerProfile(String.valueOf(UUID.randomUUID()));
441 model.updateProfile(mProfile);
442 mProfile.storeInDB();
443 final ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
444 if (profiles == null)
445 throw new AssertionError();
446 ArrayList<MobileLedgerProfile> newList = new ArrayList<>(profiles);
447 newList.add(mProfile);
448 Data.profiles.setValue(newList);
449 MobileLedgerProfile.storeProfilesOrder();
451 // first profile ever?
452 if (newList.size() == 1)
453 Data.setCurrentProfile(mProfile);
456 Activity activity = getActivity();
457 if (activity != null)
460 private boolean checkUrlValidity() {
461 boolean valid = true;
463 ProfileDetailModel model = getModel();
465 String val = model.getUrl()
469 urlLayout.setError(getResources().getText(R.string.err_profile_url_empty));
472 URL url = new URL(val);
473 String host = url.getHost();
474 if (host == null || host.isEmpty())
475 throw new MalformedURLException("Missing host");
476 String protocol = url.getProtocol()
478 if (!protocol.equals("HTTP") && !protocol.equals("HTTPS")) {
480 urlLayout.setError(getResources().getText(R.string.err_invalid_url));
483 catch (MalformedURLException e) {
485 urlLayout.setError(getResources().getText(R.string.err_invalid_url));
490 private void checkInsecureSchemeWithAuth() {
491 boolean showWarning = false;
493 final ProfileDetailModel model = getModel();
495 if (model.getUseAuthentication()) {
496 String urlText = model.getUrl();
497 if (urlText.startsWith("http") && !urlText.startsWith("https"))
502 insecureWarningText.setVisibility(View.VISIBLE);
504 insecureWarningText.setVisibility(View.GONE);
506 private void hookClearErrorOnFocusListener(TextView view, TextInputLayout layout) {
507 view.setOnFocusChangeListener((v, hasFocus) -> {
509 layout.setError(null);
511 view.addTextChangedListener(new TextWatcher() {
513 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
516 public void onTextChanged(CharSequence s, int start, int before, int count) {
517 layout.setError(null);
520 public void afterTextChanged(Editable s) {
524 private void syncModelFromUI() {
525 if (syncingModelFromUI)
528 syncingModelFromUI = true;
531 ProfileDetailModel model = getModel();
533 model.setProfileName(profileName.getText());
534 model.setUrl(url.getText());
535 model.setPreferredAccountsFilter(preferredAccountsFilter.getText());
536 model.setAuthUserName(userName.getText());
537 model.setAuthPassword(password.getText());
540 syncingModelFromUI = false;
543 private boolean checkValidity() {
544 boolean valid = true;
546 String val = String.valueOf(profileName.getText());
551 profileNameLayout.setError(getResources().getText(R.string.err_profile_name_empty));
554 if (!checkUrlValidity())
557 if (useAuthentication.isChecked()) {
558 val = String.valueOf(userName.getText());
563 userNameLayout.setError(
564 getResources().getText(R.string.err_profile_user_name_empty));
567 val = String.valueOf(password.getText());
572 passwordLayout.setError(
573 getResources().getText(R.string.err_profile_password_empty));
579 private void resetDefaultCommodity() {
580 defaultCommoditySet = false;
581 defaultCommodity.setText(R.string.btn_no_currency);
582 defaultCommodity.setTypeface(defaultCommodity.getTypeface(), Typeface.ITALIC);
584 private void setDefaultCommodity(@NonNull @NotNull String name) {
585 defaultCommoditySet = true;
586 defaultCommodity.setText(name);
587 defaultCommodity.setTypeface(Typeface.DEFAULT);
589 interface TextChangeSyncProc {
590 void onTextChanged(String text);