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, TextChangeSyncRoutine 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, showCommentsByDefault::setChecked);
267 showCommentsByDefault.setOnCheckedChangeListener(
268 ((buttonView, isChecked) -> model.setShowCommentsByDefault(isChecked)));
270 defaultCommodity = context.findViewById(R.id.default_commodity_text);
272 futureDatesLayout = context.findViewById(R.id.future_dates_layout);
273 futureDatesText = context.findViewById(R.id.future_dates_text);
274 context.findViewById(R.id.future_dates_layout)
275 .setOnClickListener(v -> {
276 MenuInflater mi = new MenuInflater(context);
277 PopupMenu menu = new PopupMenu(context, v);
278 menu.inflate(R.menu.future_dates);
279 menu.setOnMenuItemClickListener(item -> {
280 model.setFutureDates(futureDatesSettingFromMenuItemId(item.getItemId()));
285 model.observeFutureDates(viewLifecycleOwner,
286 v -> futureDatesText.setText(v.getText(getResources())));
288 apiVersionText = context.findViewById(R.id.api_version_text);
289 model.observeApiVersion(viewLifecycleOwner,
290 apiVer -> apiVersionText.setText(apiVer.getDescription(getResources())));
291 context.findViewById(R.id.api_version_layout)
292 .setOnClickListener(v -> {
293 MenuInflater mi = new MenuInflater(context);
294 PopupMenu menu = new PopupMenu(context, v);
295 menu.inflate(R.menu.api_version);
296 menu.setOnMenuItemClickListener(item -> {
297 SendTransactionTask.API apiVer;
298 switch (item.getItemId()) {
299 case R.id.api_version_menu_html:
300 apiVer = SendTransactionTask.API.html;
302 case R.id.api_version_menu_post_1_14:
303 apiVer = SendTransactionTask.API.post_1_14;
305 case R.id.api_version_menu_pre_1_15:
306 apiVer = SendTransactionTask.API.pre_1_15;
308 case R.id.api_version_menu_auto:
310 apiVer = SendTransactionTask.API.auto;
312 model.setApiVersion(apiVer);
313 apiVersionText.setText(apiVer.getDescription(getResources()));
318 authParams = context.findViewById(R.id.auth_params);
320 useAuthentication = context.findViewById(R.id.enable_http_auth);
321 useAuthentication.setOnCheckedChangeListener((buttonView, isChecked) -> {
322 model.setUseAuthentication(isChecked);
324 userName.requestFocus();
326 model.observeUseAuthentication(viewLifecycleOwner, isChecked -> {
327 useAuthentication.setChecked(isChecked);
328 authParams.setVisibility(isChecked ? View.VISIBLE : View.GONE);
329 checkInsecureSchemeWithAuth();
332 userName = context.findViewById(R.id.auth_user_name);
333 model.observeUserName(viewLifecycleOwner, text -> {
334 if (!Misc.equalStrings(text, userName.getText()))
335 userName.setText(text);
337 hookTextChangeSyncRoutine(userName, model::setAuthUserName);
338 userNameLayout = context.findViewById(R.id.auth_user_name_layout);
340 password = context.findViewById(R.id.password);
341 model.observePassword(viewLifecycleOwner, text -> {
342 if (!Misc.equalStrings(text, password.getText()))
343 password.setText(text);
345 hookTextChangeSyncRoutine(password, model::setAuthPassword);
346 passwordLayout = context.findViewById(R.id.password_layout);
348 huePickerView = context.findViewById(R.id.btn_pick_ring_color);
349 model.observeThemeId(viewLifecycleOwner, themeId -> {
350 final int hue = (themeId == -1) ? Colors.DEFAULT_HUE_DEG : themeId;
351 final int profileColor = Colors.getPrimaryColorForHue(hue);
352 huePickerView.setBackgroundColor(profileColor);
353 huePickerView.setTag(hue);
356 preferredAccountsFilter = context.findViewById(R.id.preferred_accounts_filter_filter);
357 model.observePreferredAccountsFilter(viewLifecycleOwner, text -> {
358 if (!Misc.equalStrings(text, preferredAccountsFilter.getText()))
359 preferredAccountsFilter.setText(text);
361 hookTextChangeSyncRoutine(preferredAccountsFilter, model::setPreferredAccountsFilter);
362 preferredAccountsFilterLayout =
363 context.findViewById(R.id.preferred_accounts_accounts_filter_layout);
365 insecureWarningText = context.findViewById(R.id.insecure_scheme_text);
367 hookClearErrorOnFocusListener(profileName, profileNameLayout);
368 hookClearErrorOnFocusListener(url, urlLayout);
369 hookClearErrorOnFocusListener(userName, userNameLayout);
370 hookClearErrorOnFocusListener(password, passwordLayout);
372 if (savedInstanceState == null) {
373 model.setValuesFromProfile(mProfile, getArguments().getInt(ARG_HUE, -1));
375 checkInsecureSchemeWithAuth();
377 url.addTextChangedListener(new TextWatcher() {
379 public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
381 public void onTextChanged(CharSequence s, int start, int before, int count) {}
383 public void afterTextChanged(Editable s) {
384 checkInsecureSchemeWithAuth();
388 huePickerView.setOnClickListener(v -> {
389 HueRingDialog d = new HueRingDialog(ProfileDetailFragment.this.requireContext(),
390 model.initialThemeHue, (Integer) v.getTag());
392 d.setColorSelectedListener(model::setThemeId);
395 profileName.requestFocus();
397 private MobileLedgerProfile.FutureDates futureDatesSettingFromMenuItemId(int itemId) {
399 case R.id.menu_future_dates_7:
400 return MobileLedgerProfile.FutureDates.OneWeek;
401 case R.id.menu_future_dates_14:
402 return MobileLedgerProfile.FutureDates.TwoWeeks;
403 case R.id.menu_future_dates_30:
404 return MobileLedgerProfile.FutureDates.OneMonth;
405 case R.id.menu_future_dates_60:
406 return MobileLedgerProfile.FutureDates.TwoMonths;
407 case R.id.menu_future_dates_90:
408 return MobileLedgerProfile.FutureDates.ThreeMonths;
409 case R.id.menu_future_dates_180:
410 return MobileLedgerProfile.FutureDates.SixMonths;
411 case R.id.menu_future_dates_365:
412 return MobileLedgerProfile.FutureDates.OneYear;
413 case R.id.menu_future_dates_all:
414 return MobileLedgerProfile.FutureDates.All;
416 return MobileLedgerProfile.FutureDates.None;
420 private ProfileDetailModel getModel() {
421 return new ViewModelProvider(requireActivity()).get(ProfileDetailModel.class);
423 private void onSaveFabClicked() {
424 if (!checkValidity())
427 ProfileDetailModel model = getModel();
429 if (mProfile != null) {
430 model.updateProfile(mProfile);
431 // debug("profiles", String.format("Selected item is %d", mProfile.getThemeHue()));
432 mProfile.storeInDB();
433 debug("profiles", "profile stored in DB");
434 triggerProfileChange();
437 mProfile = new MobileLedgerProfile(String.valueOf(UUID.randomUUID()));
438 model.updateProfile(mProfile);
439 mProfile.storeInDB();
440 final ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
441 if (profiles == null)
442 throw new AssertionError();
443 ArrayList<MobileLedgerProfile> newList = new ArrayList<>(profiles);
444 newList.add(mProfile);
445 Data.profiles.setValue(newList);
446 MobileLedgerProfile.storeProfilesOrder();
448 // first profile ever?
449 if (newList.size() == 1)
450 Data.setCurrentProfile(mProfile);
453 Activity activity = getActivity();
454 if (activity != null)
457 private boolean checkUrlValidity() {
458 boolean valid = true;
460 ProfileDetailModel model = getModel();
462 String val = model.getUrl()
466 urlLayout.setError(getResources().getText(R.string.err_profile_url_empty));
469 URL url = new URL(val);
470 String host = url.getHost();
471 if (host == null || host.isEmpty())
472 throw new MalformedURLException("Missing host");
473 String protocol = url.getProtocol()
475 if (!protocol.equals("HTTP") && !protocol.equals("HTTPS")) {
477 urlLayout.setError(getResources().getText(R.string.err_invalid_url));
480 catch (MalformedURLException e) {
482 urlLayout.setError(getResources().getText(R.string.err_invalid_url));
487 private void checkInsecureSchemeWithAuth() {
488 boolean showWarning = false;
490 final ProfileDetailModel model = getModel();
492 if (model.getUseAuthentication()) {
493 String urlText = model.getUrl();
494 if (urlText.startsWith("http") && !urlText.startsWith("https"))
499 insecureWarningText.setVisibility(View.VISIBLE);
501 insecureWarningText.setVisibility(View.GONE);
503 private void hookClearErrorOnFocusListener(TextView view, TextInputLayout layout) {
504 view.setOnFocusChangeListener((v, hasFocus) -> {
506 layout.setError(null);
508 view.addTextChangedListener(new TextWatcher() {
510 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
513 public void onTextChanged(CharSequence s, int start, int before, int count) {
514 layout.setError(null);
517 public void afterTextChanged(Editable s) {
521 private void syncModelFromUI() {
522 if (syncingModelFromUI)
525 syncingModelFromUI = true;
528 ProfileDetailModel model = getModel();
530 model.setProfileName(profileName.getText());
531 model.setUrl(url.getText());
532 model.setPreferredAccountsFilter(preferredAccountsFilter.getText());
533 model.setAuthUserName(userName.getText());
534 model.setAuthPassword(password.getText());
537 syncingModelFromUI = false;
540 private boolean checkValidity() {
541 boolean valid = true;
543 String val = String.valueOf(profileName.getText());
548 profileNameLayout.setError(getResources().getText(R.string.err_profile_name_empty));
551 if (!checkUrlValidity())
554 if (useAuthentication.isChecked()) {
555 val = String.valueOf(userName.getText());
560 userNameLayout.setError(
561 getResources().getText(R.string.err_profile_user_name_empty));
564 val = String.valueOf(password.getText());
569 passwordLayout.setError(
570 getResources().getText(R.string.err_profile_password_empty));
576 private void resetDefaultCommodity() {
577 defaultCommoditySet = false;
578 defaultCommodity.setText(R.string.btn_no_currency);
579 defaultCommodity.setTypeface(defaultCommodity.getTypeface(), Typeface.ITALIC);
581 private void setDefaultCommodity(@NonNull @NotNull String name) {
582 defaultCommoditySet = true;
583 defaultCommodity.setText(name);
584 defaultCommodity.setTypeface(Typeface.DEFAULT);
586 interface TextChangeSyncRoutine {
587 void onTextChanged(String text);