2 * Copyright © 2019 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.LinearLayout;
33 import android.widget.PopupMenu;
34 import android.widget.Switch;
35 import android.widget.TextView;
37 import androidx.annotation.NonNull;
38 import androidx.annotation.Nullable;
39 import androidx.appcompat.app.AppCompatActivity;
40 import androidx.fragment.app.Fragment;
41 import androidx.fragment.app.FragmentActivity;
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.Currency;
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.ui.OnCurrencySelectedListener;
56 import net.ktnx.mobileledger.ui.activity.ProfileDetailActivity;
57 import net.ktnx.mobileledger.utils.Colors;
58 import net.ktnx.mobileledger.utils.Misc;
60 import org.jetbrains.annotations.NonNls;
61 import org.jetbrains.annotations.NotNull;
63 import java.net.MalformedURLException;
65 import java.util.ArrayList;
66 import java.util.Objects;
68 import static net.ktnx.mobileledger.utils.Logger.debug;
71 * A fragment representing a single Profile detail screen.
72 * a {@link ProfileDetailActivity}
75 public class ProfileDetailFragment extends Fragment
76 implements HueRingDialog.HueSelectedListener, OnCurrencySelectedListener {
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";
84 private static final String HTTPS_URL_START = "https://";
87 * The content this fragment is presenting.
89 private MobileLedgerProfile mProfile;
91 private Switch postingPermitted;
92 private Switch showCommodityByDefault;
93 private TextView defaultCommodity;
94 private boolean defaultCommoditySet;
95 private TextInputLayout urlLayout;
96 private LinearLayout authParams;
97 private Switch useAuthentication;
98 private TextView userName;
99 private TextInputLayout userNameLayout;
100 private TextView password;
101 private TextInputLayout passwordLayout;
102 private TextView profileName;
103 private TextInputLayout profileNameLayout;
104 private TextView preferredAccountsFilter;
105 private TextInputLayout preferredAccountsFilterLayout;
106 private View huePickerView;
107 private View insecureWarningText;
108 private TextView futureDatesText;
109 private MobileLedgerProfile.FutureDates futureDates;
110 private View futureDatesLayout;
111 private TextView apiVersionText;
112 private SendTransactionTask.API apiVersion;
115 * Mandatory empty constructor for the fragment manager to instantiate the
116 * fragment (e.g. upon screen orientation changes).
118 public ProfileDetailFragment() {
121 public void onCreateOptionsMenu(@NotNull Menu menu, @NotNull MenuInflater inflater) {
122 debug("profiles", "[fragment] Creating profile details options menu");
123 super.onCreateOptionsMenu(menu, inflater);
124 inflater.inflate(R.menu.profile_details, menu);
125 final MenuItem menuDeleteProfile = menu.findItem(R.id.menuDelete);
126 menuDeleteProfile.setOnMenuItemClickListener(item -> {
127 AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
128 builder.setTitle(mProfile.getName());
129 builder.setMessage(R.string.remove_profile_dialog_message);
130 builder.setPositiveButton(R.string.Remove, (dialog, which) -> {
132 String.format("[fragment] removing profile %s", mProfile.getUuid()));
133 mProfile.removeFromDB();
134 ArrayList<MobileLedgerProfile> oldList = Data.profiles.getValue();
136 throw new AssertionError();
137 ArrayList<MobileLedgerProfile> newList = new ArrayList<>(oldList);
138 newList.remove(mProfile);
139 Data.profiles.setValue(newList);
140 if (mProfile.equals(Data.profile.getValue())) {
141 debug("profiles", "[fragment] setting current profile to 0");
142 Data.setCurrentProfile(newList.get(0));
145 final FragmentActivity activity = getActivity();
146 if (activity != null)
152 final ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
153 menuDeleteProfile.setVisible(
154 (mProfile != null) && (profiles != null) && (profiles.size() > 1));
156 if (BuildConfig.DEBUG) {
157 final MenuItem menuWipeProfileData = menu.findItem(R.id.menuWipeData);
158 menuWipeProfileData.setOnMenuItemClickListener(ignored -> onWipeDataMenuClicked());
159 menuWipeProfileData.setVisible(mProfile != null);
162 private boolean onWipeDataMenuClicked() {
163 // this is a development option, so no confirmation
164 mProfile.wipeAllData();
165 if (mProfile.equals(Data.profile.getValue()))
166 triggerProfileChange();
169 private void triggerProfileChange() {
170 int index = Data.getProfileIndex(mProfile);
171 MobileLedgerProfile newProfile = new MobileLedgerProfile(mProfile);
172 final ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
173 if (profiles == null)
174 throw new AssertionError();
175 profiles.set(index, newProfile);
177 ProfilesRecyclerViewAdapter viewAdapter = ProfilesRecyclerViewAdapter.getInstance();
178 if (viewAdapter != null)
179 viewAdapter.notifyItemChanged(index);
181 if (mProfile.equals(Data.profile.getValue()))
182 Data.profile.setValue(newProfile);
185 public void onActivityCreated(@Nullable Bundle savedInstanceState) {
186 super.onActivityCreated(savedInstanceState);
187 Activity context = getActivity();
191 if ((getArguments() != null) && getArguments().containsKey(ARG_ITEM_ID)) {
192 int index = getArguments().getInt(ARG_ITEM_ID, -1);
193 ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
194 if ((profiles != null) && (index != -1) && (index < profiles.size()))
195 mProfile = profiles.get(index);
197 Activity activity = this.getActivity();
198 if (activity == null)
199 throw new AssertionError();
200 CollapsingToolbarLayout appBarLayout = activity.findViewById(R.id.toolbar_layout);
201 if (appBarLayout != null) {
202 if (mProfile != null)
203 appBarLayout.setTitle(mProfile.getName());
205 appBarLayout.setTitle(getResources().getString(R.string.new_profile_title));
209 FloatingActionButton fab = context.findViewById(R.id.fab);
210 fab.setOnClickListener(v -> onSaveFabClicked());
211 profileName = context.findViewById(R.id.profile_name);
212 profileNameLayout = context.findViewById(R.id.profile_name_layout);
213 url = context.findViewById(R.id.url);
214 urlLayout = context.findViewById(R.id.url_layout);
215 postingPermitted = context.findViewById(R.id.profile_permit_posting);
216 showCommodityByDefault = context.findViewById(R.id.profile_show_commodity);
217 defaultCommodity = context.findViewById(R.id.default_commodity_text);
218 futureDatesLayout = context.findViewById(R.id.future_dates_layout);
219 futureDatesText = context.findViewById(R.id.future_dates_text);
220 context.findViewById(R.id.future_dates_layout)
221 .setOnClickListener(v -> {
222 MenuInflater mi = new MenuInflater(context);
223 PopupMenu menu = new PopupMenu(context, v);
224 menu.inflate(R.menu.future_dates);
225 menu.setOnMenuItemClickListener(item -> {
226 switch (item.getItemId()) {
227 case R.id.menu_future_dates_7:
228 futureDates = MobileLedgerProfile.FutureDates.OneWeek;
230 case R.id.menu_future_dates_14:
231 futureDates = MobileLedgerProfile.FutureDates.TwoWeeks;
233 case R.id.menu_future_dates_30:
234 futureDates = MobileLedgerProfile.FutureDates.OneMonth;
236 case R.id.menu_future_dates_60:
237 futureDates = MobileLedgerProfile.FutureDates.TwoMonths;
239 case R.id.menu_future_dates_90:
240 futureDates = MobileLedgerProfile.FutureDates.ThreeMonths;
242 case R.id.menu_future_dates_180:
243 futureDates = MobileLedgerProfile.FutureDates.SixMonths;
245 case R.id.menu_future_dates_365:
246 futureDates = MobileLedgerProfile.FutureDates.OneYear;
248 case R.id.menu_future_dates_all:
249 futureDates = MobileLedgerProfile.FutureDates.All;
252 futureDates = MobileLedgerProfile.FutureDates.None;
254 futureDatesText.setText(futureDates.getText(getResources()));
259 apiVersionText = context.findViewById(R.id.api_version_text);
260 context.findViewById(R.id.api_version_layout)
261 .setOnClickListener(v -> {
262 MenuInflater mi = new MenuInflater(context);
263 PopupMenu menu = new PopupMenu(context, v);
264 menu.inflate(R.menu.api_version);
265 menu.setOnMenuItemClickListener(item -> {
266 switch (item.getItemId()) {
267 case R.id.api_version_menu_html:
268 apiVersion = SendTransactionTask.API.html;
270 case R.id.api_version_menu_post_1_14:
271 apiVersion = SendTransactionTask.API.post_1_14;
273 case R.id.api_version_menu_pre_1_15:
274 apiVersion = SendTransactionTask.API.pre_1_15;
276 case R.id.api_version_menu_auto:
278 apiVersion = SendTransactionTask.API.auto;
280 apiVersionText.setText(apiVersion.getDescription(getResources()));
285 authParams = context.findViewById(R.id.auth_params);
286 useAuthentication = context.findViewById(R.id.enable_http_auth);
287 userName = context.findViewById(R.id.auth_user_name);
288 userNameLayout = context.findViewById(R.id.auth_user_name_layout);
289 password = context.findViewById(R.id.password);
290 passwordLayout = context.findViewById(R.id.password_layout);
291 huePickerView = context.findViewById(R.id.btn_pick_ring_color);
292 preferredAccountsFilter = context.findViewById(R.id.preferred_accounts_filter_filter);
293 preferredAccountsFilterLayout =
294 context.findViewById(R.id.preferred_accounts_accounts_filter_layout);
295 insecureWarningText = context.findViewById(R.id.insecure_scheme_text);
297 useAuthentication.setOnCheckedChangeListener((buttonView, isChecked) -> {
298 debug("profiles", isChecked ? "auth enabled " : "auth disabled");
299 authParams.setVisibility(isChecked ? View.VISIBLE : View.GONE);
301 userName.requestFocus();
302 checkInsecureSchemeWithAuth();
305 postingPermitted.setOnCheckedChangeListener(((buttonView, isChecked) -> {
306 preferredAccountsFilterLayout.setVisibility(isChecked ? View.VISIBLE : View.GONE);
307 futureDatesLayout.setVisibility(isChecked ? View.VISIBLE : View.GONE);
310 hookClearErrorOnFocusListener(profileName, profileNameLayout);
311 hookClearErrorOnFocusListener(url, urlLayout);
312 hookClearErrorOnFocusListener(userName, userNameLayout);
313 hookClearErrorOnFocusListener(password, passwordLayout);
315 final int profileThemeId;
316 if (mProfile != null) {
317 profileName.setText(mProfile.getName());
318 postingPermitted.setChecked(mProfile.isPostingPermitted());
319 showCommodityByDefault.setChecked(mProfile.getShowCommodityByDefault());
321 String comm = mProfile.getDefaultCommodity();
322 if (Misc.isEmptyOrNull(comm))
323 resetDefaultCommodity();
325 setDefaultCommodity(comm);
327 futureDates = mProfile.getFutureDates();
328 futureDatesText.setText(futureDates.getText(getResources()));
329 apiVersion = mProfile.getApiVersion();
330 apiVersionText.setText(apiVersion.getDescription(getResources()));
331 url.setText(mProfile.getUrl());
332 useAuthentication.setChecked(mProfile.isAuthEnabled());
333 authParams.setVisibility(mProfile.isAuthEnabled() ? View.VISIBLE : View.GONE);
334 userName.setText(mProfile.isAuthEnabled() ? mProfile.getAuthUserName() : "");
335 password.setText(mProfile.isAuthEnabled() ? mProfile.getAuthPassword() : "");
336 preferredAccountsFilter.setText(mProfile.getPreferredAccountsFilter());
337 profileThemeId = mProfile.getThemeHue();
340 profileName.setText("");
341 url.setText(HTTPS_URL_START);
342 postingPermitted.setChecked(true);
343 showCommodityByDefault.setChecked(false);
344 resetDefaultCommodity();
345 futureDates = MobileLedgerProfile.FutureDates.None;
346 futureDatesText.setText(futureDates.getText(getResources()));
347 apiVersion = SendTransactionTask.API.auto;
348 apiVersionText.setText(apiVersion.getDescription(getResources()));
349 useAuthentication.setChecked(false);
350 authParams.setVisibility(View.GONE);
351 userName.setText("");
352 password.setText("");
353 preferredAccountsFilter.setText(null);
354 profileThemeId = getArguments().getInt(ARG_HUE, -1);
357 checkInsecureSchemeWithAuth();
359 url.addTextChangedListener(new TextWatcher() {
361 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
365 public void onTextChanged(CharSequence s, int start, int before, int count) {
369 public void afterTextChanged(Editable s) {
370 checkInsecureSchemeWithAuth();
374 final int hue = (profileThemeId == -1) ? Colors.DEFAULT_HUE_DEG : profileThemeId;
375 final int profileColor = Colors.getPrimaryColorForHue(hue);
377 huePickerView.setBackgroundColor(profileColor);
378 huePickerView.setTag(profileThemeId);
379 huePickerView.setOnClickListener(v -> {
380 HueRingDialog d = new HueRingDialog(
381 Objects.requireNonNull(ProfileDetailFragment.this.getContext()), profileThemeId,
382 (Integer) v.getTag());
384 d.setColorSelectedListener(this);
387 context.findViewById(R.id.default_commodity_layout).setOnClickListener(v -> {
388 CurrencySelectorFragment cpf = CurrencySelectorFragment.newInstance(CurrencySelectorFragment.DEFAULT_COLUMN_COUNT, false);
389 cpf.setOnCurrencySelectedListener(this);
390 final AppCompatActivity activity = (AppCompatActivity) v.getContext();
391 cpf.show(activity.getSupportFragmentManager(), "currency-selector");
393 profileName.requestFocus();
395 private void onSaveFabClicked() {
396 if (!checkValidity())
399 if (mProfile != null) {
400 updateProfileFromUI();
401 // debug("profiles", String.format("Selected item is %d", mProfile.getThemeHue()));
402 mProfile.storeInDB();
403 debug("profiles", "profile stored in DB");
404 triggerProfileChange();
407 mProfile = new MobileLedgerProfile();
408 updateProfileFromUI();
409 mProfile.storeInDB();
410 final ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
411 if (profiles == null)
412 throw new AssertionError();
413 ArrayList<MobileLedgerProfile> newList = new ArrayList<>(profiles);
414 newList.add(mProfile);
415 Data.profiles.setValue(newList);
416 MobileLedgerProfile.storeProfilesOrder();
418 // first profile ever?
419 if (newList.size() == 1)
420 Data.profile.setValue(mProfile);
423 Activity activity = getActivity();
424 if (activity != null)
427 private void updateProfileFromUI() {
428 mProfile.setName(profileName.getText());
429 mProfile.setUrl(url.getText());
430 mProfile.setPostingPermitted(postingPermitted.isChecked());
431 mProfile.setDefaultCommodity(defaultCommoditySet ? defaultCommodity.getText() : null);
432 mProfile.setShowCommodityByDefault(showCommodityByDefault.isChecked());
433 mProfile.setPreferredAccountsFilter(preferredAccountsFilter.getText());
434 mProfile.setAuthEnabled(useAuthentication.isChecked());
435 mProfile.setAuthUserName(userName.getText());
436 mProfile.setAuthPassword(password.getText());
437 mProfile.setThemeHue(huePickerView.getTag());
438 mProfile.setFutureDates(futureDates);
439 mProfile.setApiVersion(apiVersion);
442 public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
443 Bundle savedInstanceState) {
445 return inflater.inflate(R.layout.profile_detail, container, false);
447 private boolean checkUrlValidity() {
448 boolean valid = true;
450 String val = String.valueOf(url.getText())
454 urlLayout.setError(getResources().getText(R.string.err_profile_url_empty));
457 URL url = new URL(val);
458 String host = url.getHost();
459 if (host == null || host.isEmpty())
460 throw new MalformedURLException("Missing host");
461 String protocol = url.getProtocol()
463 if (!protocol.equals("HTTP") && !protocol.equals("HTTPS")) {
465 urlLayout.setError(getResources().getText(R.string.err_invalid_url));
468 catch (MalformedURLException e) {
470 urlLayout.setError(getResources().getText(R.string.err_invalid_url));
475 private void checkInsecureSchemeWithAuth() {
476 boolean showWarning = false;
478 if (useAuthentication.isChecked()) {
479 String urlText = url.getText()
481 if (urlText.startsWith("http") && !urlText.startsWith("https"))
486 insecureWarningText.setVisibility(View.VISIBLE);
488 insecureWarningText.setVisibility(View.GONE);
490 private void hookClearErrorOnFocusListener(TextView view, TextInputLayout layout) {
491 view.setOnFocusChangeListener((v, hasFocus) -> {
493 layout.setError(null);
495 view.addTextChangedListener(new TextWatcher() {
497 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
500 public void onTextChanged(CharSequence s, int start, int before, int count) {
501 layout.setError(null);
504 public void afterTextChanged(Editable s) {
508 private boolean checkValidity() {
509 boolean valid = true;
511 String val = String.valueOf(profileName.getText());
516 profileNameLayout.setError(getResources().getText(R.string.err_profile_name_empty));
519 if (!checkUrlValidity())
522 if (useAuthentication.isChecked()) {
523 val = String.valueOf(userName.getText());
528 userNameLayout.setError(
529 getResources().getText(R.string.err_profile_user_name_empty));
532 val = String.valueOf(password.getText());
537 passwordLayout.setError(
538 getResources().getText(R.string.err_profile_password_empty));
545 public void onHueSelected(int hue) {
546 huePickerView.setBackgroundColor(Colors.getPrimaryColorForHue(hue));
547 huePickerView.setTag(hue);
550 public void onCurrencySelected(Currency item) {
552 resetDefaultCommodity();
554 setDefaultCommodity(item.getName());
556 private void resetDefaultCommodity() {
557 defaultCommoditySet = false;
558 defaultCommodity.setText(R.string.btn_no_currency);
559 defaultCommodity.setTypeface(defaultCommodity.getTypeface(), Typeface.ITALIC);
561 private void setDefaultCommodity(@NonNull @NotNull String name) {
562 defaultCommoditySet = true;
563 defaultCommodity.setText(name);
564 defaultCommodity.setTypeface(defaultCommodity.getTypeface(), Typeface.BOLD);