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.os.Bundle;
23 import android.text.Editable;
24 import android.text.TextWatcher;
25 import android.view.LayoutInflater;
26 import android.view.Menu;
27 import android.view.MenuInflater;
28 import android.view.MenuItem;
29 import android.view.View;
30 import android.view.ViewGroup;
31 import android.widget.LinearLayout;
32 import android.widget.PopupMenu;
33 import android.widget.Switch;
34 import android.widget.TextView;
36 import androidx.annotation.NonNull;
37 import androidx.annotation.Nullable;
38 import androidx.fragment.app.Fragment;
39 import androidx.fragment.app.FragmentActivity;
41 import com.google.android.material.appbar.CollapsingToolbarLayout;
42 import com.google.android.material.floatingactionbutton.FloatingActionButton;
43 import com.google.android.material.textfield.TextInputLayout;
45 import net.ktnx.mobileledger.BuildConfig;
46 import net.ktnx.mobileledger.R;
47 import net.ktnx.mobileledger.async.SendTransactionTask;
48 import net.ktnx.mobileledger.model.Data;
49 import net.ktnx.mobileledger.model.MobileLedgerProfile;
50 import net.ktnx.mobileledger.ui.HueRingDialog;
51 import net.ktnx.mobileledger.ui.activity.ProfileDetailActivity;
52 import net.ktnx.mobileledger.utils.Colors;
54 import org.jetbrains.annotations.NonNls;
55 import org.jetbrains.annotations.NotNull;
57 import java.net.MalformedURLException;
59 import java.util.ArrayList;
60 import java.util.Objects;
62 import static net.ktnx.mobileledger.utils.Logger.debug;
65 * A fragment representing a single Profile detail screen.
66 * a {@link ProfileDetailActivity}
69 public class ProfileDetailFragment extends Fragment implements HueRingDialog.HueSelectedListener {
71 * The fragment argument representing the item ID that this fragment
74 public static final String ARG_ITEM_ID = "item_id";
76 private static final String HTTPS_URL_START = "https://";
79 * The dummy content this fragment is presenting.
81 private MobileLedgerProfile mProfile;
83 private Switch postingPermitted;
84 private TextInputLayout urlLayout;
85 private LinearLayout authParams;
86 private Switch useAuthentication;
87 private TextView userName;
88 private TextInputLayout userNameLayout;
89 private TextView password;
90 private TextInputLayout passwordLayout;
91 private TextView profileName;
92 private TextInputLayout profileNameLayout;
93 private TextView preferredAccountsFilter;
94 private TextInputLayout preferredAccountsFilterLayout;
95 private View huePickerView;
96 private View insecureWarningText;
97 private TextView futureDatesText;
98 private MobileLedgerProfile.FutureDates futureDates;
99 private View futureDatesLayout;
100 private TextView apiVersionText;
101 private SendTransactionTask.API apiVersion;
104 * Mandatory empty constructor for the fragment manager to instantiate the
105 * fragment (e.g. upon screen orientation changes).
107 public ProfileDetailFragment() {
110 public void onCreateOptionsMenu(@NotNull Menu menu, @NotNull MenuInflater inflater) {
111 debug("profiles", "[fragment] Creating profile details options menu");
112 super.onCreateOptionsMenu(menu, inflater);
113 inflater.inflate(R.menu.profile_details, menu);
114 final MenuItem menuDeleteProfile = menu.findItem(R.id.menuDelete);
115 menuDeleteProfile.setOnMenuItemClickListener(item -> {
116 AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
117 builder.setTitle(mProfile.getName());
118 builder.setMessage(R.string.remove_profile_dialog_message);
119 builder.setPositiveButton(R.string.Remove, (dialog, which) -> {
121 String.format("[fragment] removing profile %s", mProfile.getUuid()));
122 mProfile.removeFromDB();
123 ArrayList<MobileLedgerProfile> oldList = Data.profiles.getValue();
125 throw new AssertionError();
126 ArrayList<MobileLedgerProfile> newList = new ArrayList<>(oldList);
127 newList.remove(mProfile);
128 Data.profiles.setValue(newList);
129 if (mProfile.equals(Data.profile.getValue())) {
130 debug("profiles", "[fragment] setting current profile to 0");
131 Data.setCurrentProfile(newList.get(0));
134 final FragmentActivity activity = getActivity();
135 if (activity != null)
141 final ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
142 menuDeleteProfile.setVisible(
143 (mProfile != null) && (profiles != null) && (profiles.size() > 1));
145 if (BuildConfig.DEBUG) {
146 final MenuItem menuWipeProfileData = menu.findItem(R.id.menuWipeData);
147 menuWipeProfileData.setOnMenuItemClickListener(ignored -> onWipeDataMenuClicked());
148 menuWipeProfileData.setVisible(mProfile != null);
151 private boolean onWipeDataMenuClicked() {
152 // this is a development option, so no confirmation
153 mProfile.wipeAllData();
154 if (mProfile.equals(Data.profile.getValue()))
155 triggerProfileChange();
158 private void triggerProfileChange() {
159 int index = Data.getProfileIndex(mProfile);
160 MobileLedgerProfile newProfile = new MobileLedgerProfile(mProfile);
161 final ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
162 if (profiles == null)
163 throw new AssertionError();
164 profiles.set(index, newProfile);
166 ProfilesRecyclerViewAdapter viewAdapter = ProfilesRecyclerViewAdapter.getInstance();
167 if (viewAdapter != null)
168 viewAdapter.notifyItemChanged(index);
170 if (mProfile.equals(Data.profile.getValue()))
171 Data.profile.setValue(newProfile);
174 public void onActivityCreated(@Nullable Bundle savedInstanceState) {
175 super.onActivityCreated(savedInstanceState);
176 Activity context = getActivity();
180 if ((getArguments() != null) && getArguments().containsKey(ARG_ITEM_ID)) {
181 int index = getArguments().getInt(ARG_ITEM_ID, -1);
182 ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
183 if ((profiles != null) && (index != -1) && (index < profiles.size()))
184 mProfile = profiles.get(index);
186 Activity activity = this.getActivity();
187 if (activity == null)
188 throw new AssertionError();
189 CollapsingToolbarLayout appBarLayout = activity.findViewById(R.id.toolbar_layout);
190 if (appBarLayout != null) {
191 if (mProfile != null)
192 appBarLayout.setTitle(mProfile.getName());
194 appBarLayout.setTitle(getResources().getString(R.string.new_profile_title));
198 FloatingActionButton fab = context.findViewById(R.id.fab);
199 fab.setOnClickListener(v -> onSaveFabClicked());
200 profileName = context.findViewById(R.id.profile_name);
201 profileNameLayout = context.findViewById(R.id.profile_name_layout);
202 url = context.findViewById(R.id.url);
203 urlLayout = context.findViewById(R.id.url_layout);
204 postingPermitted = context.findViewById(R.id.profile_permit_posting);
205 futureDatesLayout = context.findViewById(R.id.future_dates_layout);
206 futureDatesText = context.findViewById(R.id.future_dates_text);
207 context.findViewById(R.id.future_dates_layout)
208 .setOnClickListener(v -> {
209 MenuInflater mi = new MenuInflater(context);
210 PopupMenu menu = new PopupMenu(context, v);
211 menu.inflate(R.menu.future_dates);
212 menu.setOnMenuItemClickListener(item -> {
213 switch (item.getItemId()) {
214 case R.id.menu_future_dates_30:
215 futureDates = MobileLedgerProfile.FutureDates.OneMonth;
217 case R.id.menu_future_dates_60:
218 futureDates = MobileLedgerProfile.FutureDates.TwoMonths;
220 case R.id.menu_future_dates_90:
221 futureDates = MobileLedgerProfile.FutureDates.ThreeMonths;
223 case R.id.menu_future_dates_180:
224 futureDates = MobileLedgerProfile.FutureDates.SixMonths;
226 case R.id.menu_future_dates_365:
227 futureDates = MobileLedgerProfile.FutureDates.OneYear;
229 case R.id.menu_future_dates_all:
230 futureDates = MobileLedgerProfile.FutureDates.All;
233 futureDates = MobileLedgerProfile.FutureDates.None;
235 futureDatesText.setText(futureDates.getText(getResources()));
240 apiVersionText = context.findViewById(R.id.api_version_text);
241 context.findViewById(R.id.api_version_layout)
242 .setOnClickListener(v -> {
243 MenuInflater mi = new MenuInflater(context);
244 PopupMenu menu = new PopupMenu(context, v);
245 menu.inflate(R.menu.api_version);
246 menu.setOnMenuItemClickListener(item -> {
247 switch (item.getItemId()) {
248 case R.id.api_version_menu_html:
249 apiVersion = SendTransactionTask.API.html;
251 case R.id.api_version_menu_post_1_14:
252 apiVersion = SendTransactionTask.API.post_1_14;
254 case R.id.api_version_menu_pre_1_15:
255 apiVersion = SendTransactionTask.API.pre_1_15;
257 case R.id.api_version_menu_auto:
259 apiVersion = SendTransactionTask.API.auto;
261 apiVersionText.setText(apiVersion.getDescription(getResources()));
266 authParams = context.findViewById(R.id.auth_params);
267 useAuthentication = context.findViewById(R.id.enable_http_auth);
268 userName = context.findViewById(R.id.auth_user_name);
269 userNameLayout = context.findViewById(R.id.auth_user_name_layout);
270 password = context.findViewById(R.id.password);
271 passwordLayout = context.findViewById(R.id.password_layout);
272 huePickerView = context.findViewById(R.id.btn_pick_ring_color);
273 preferredAccountsFilter = context.findViewById(R.id.preferred_accounts_filter_filter);
274 preferredAccountsFilterLayout =
275 context.findViewById(R.id.preferred_accounts_accounts_filter_layout);
276 insecureWarningText = context.findViewById(R.id.insecure_scheme_text);
278 useAuthentication.setOnCheckedChangeListener((buttonView, isChecked) -> {
279 debug("profiles", isChecked ? "auth enabled " : "auth disabled");
280 authParams.setVisibility(isChecked ? View.VISIBLE : View.GONE);
282 userName.requestFocus();
283 checkInsecureSchemeWithAuth();
286 postingPermitted.setOnCheckedChangeListener(((buttonView, isChecked) -> {
287 preferredAccountsFilterLayout.setVisibility(isChecked ? View.VISIBLE : View.GONE);
288 futureDatesLayout.setVisibility(isChecked ? View.VISIBLE : View.GONE);
291 hookClearErrorOnFocusListener(profileName, profileNameLayout);
292 hookClearErrorOnFocusListener(url, urlLayout);
293 hookClearErrorOnFocusListener(userName, userNameLayout);
294 hookClearErrorOnFocusListener(password, passwordLayout);
297 if (mProfile != null) {
298 profileName.setText(mProfile.getName());
299 postingPermitted.setChecked(mProfile.isPostingPermitted());
300 futureDates = mProfile.getFutureDates();
301 futureDatesText.setText(futureDates.getText(getResources()));
302 apiVersion = mProfile.getApiVersion();
303 apiVersionText.setText(apiVersion.getDescription(getResources()));
304 url.setText(mProfile.getUrl());
305 useAuthentication.setChecked(mProfile.isAuthEnabled());
306 authParams.setVisibility(mProfile.isAuthEnabled() ? View.VISIBLE : View.GONE);
307 userName.setText(mProfile.isAuthEnabled() ? mProfile.getAuthUserName() : "");
308 password.setText(mProfile.isAuthEnabled() ? mProfile.getAuthPassword() : "");
309 preferredAccountsFilter.setText(mProfile.getPreferredAccountsFilter());
310 profileThemeId = mProfile.getThemeId();
313 profileName.setText("");
314 url.setText(HTTPS_URL_START);
315 postingPermitted.setChecked(true);
316 futureDates = MobileLedgerProfile.FutureDates.None;
317 futureDatesText.setText(futureDates.getText(getResources()));
318 apiVersion = SendTransactionTask.API.auto;
319 apiVersionText.setText(apiVersion.getDescription(getResources()));
320 useAuthentication.setChecked(false);
321 authParams.setVisibility(View.GONE);
322 userName.setText("");
323 password.setText("");
324 preferredAccountsFilter.setText(null);
328 checkInsecureSchemeWithAuth();
330 url.addTextChangedListener(new TextWatcher() {
332 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
336 public void onTextChanged(CharSequence s, int start, int before, int count) {
340 public void afterTextChanged(Editable s) {
341 checkInsecureSchemeWithAuth();
345 final int hue = (profileThemeId == -1) ? Colors.DEFAULT_HUE_DEG : profileThemeId;
346 final int profileColor = Colors.getPrimaryColorForHue(hue);
348 huePickerView.setBackgroundColor(profileColor);
349 huePickerView.setTag(profileThemeId);
350 huePickerView.setOnClickListener(v -> {
351 HueRingDialog d = new HueRingDialog(
352 Objects.requireNonNull(ProfileDetailFragment.this.getContext()), profileThemeId,
353 (Integer) v.getTag());
355 d.setColorSelectedListener(this);
358 profileName.requestFocus();
360 private void onSaveFabClicked() {
361 if (!checkValidity())
364 if (mProfile != null) {
365 updateProfileFromUI();
366 // debug("profiles", String.format("Selected item is %d", mProfile.getThemeId()));
367 mProfile.storeInDB();
368 debug("profiles", "profile stored in DB");
369 triggerProfileChange();
372 mProfile = new MobileLedgerProfile();
373 updateProfileFromUI();
374 mProfile.storeInDB();
375 final ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
376 if (profiles == null)
377 throw new AssertionError();
378 ArrayList<MobileLedgerProfile> newList = new ArrayList<>(profiles);
379 newList.add(mProfile);
380 Data.profiles.setValue(newList);
381 MobileLedgerProfile.storeProfilesOrder();
383 // first profile ever?
384 if (newList.size() == 1)
385 Data.profile.setValue(mProfile);
388 Activity activity = getActivity();
389 if (activity != null)
392 private void updateProfileFromUI() {
393 mProfile.setName(profileName.getText());
394 mProfile.setUrl(url.getText());
395 mProfile.setPostingPermitted(postingPermitted.isChecked());
396 mProfile.setPreferredAccountsFilter(preferredAccountsFilter.getText());
397 mProfile.setAuthEnabled(useAuthentication.isChecked());
398 mProfile.setAuthUserName(userName.getText());
399 mProfile.setAuthPassword(password.getText());
400 mProfile.setThemeId(huePickerView.getTag());
401 mProfile.setFutureDates(futureDates);
402 mProfile.setApiVersion(apiVersion);
405 public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
406 Bundle savedInstanceState) {
408 return inflater.inflate(R.layout.profile_detail, container, false);
410 private boolean checkUrlValidity() {
411 boolean valid = true;
413 String val = String.valueOf(url.getText())
417 urlLayout.setError(getResources().getText(R.string.err_profile_url_empty));
420 URL url = new URL(val);
421 String host = url.getHost();
422 if (host == null || host.isEmpty())
423 throw new MalformedURLException("Missing host");
424 String protocol = url.getProtocol()
426 if (!protocol.equals("HTTP") && !protocol.equals("HTTPS")) {
428 urlLayout.setError(getResources().getText(R.string.err_invalid_url));
431 catch (MalformedURLException e) {
433 urlLayout.setError(getResources().getText(R.string.err_invalid_url));
438 private void checkInsecureSchemeWithAuth() {
439 boolean showWarning = false;
441 if (useAuthentication.isChecked()) {
442 String urlText = url.getText()
444 if (urlText.startsWith("http") && !urlText.startsWith("https"))
449 insecureWarningText.setVisibility(View.VISIBLE);
451 insecureWarningText.setVisibility(View.GONE);
453 private void hookClearErrorOnFocusListener(TextView view, TextInputLayout layout) {
454 view.setOnFocusChangeListener((v, hasFocus) -> {
456 layout.setError(null);
458 view.addTextChangedListener(new TextWatcher() {
460 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
463 public void onTextChanged(CharSequence s, int start, int before, int count) {
464 layout.setError(null);
467 public void afterTextChanged(Editable s) {
471 private boolean checkValidity() {
472 boolean valid = true;
474 String val = String.valueOf(profileName.getText());
479 profileNameLayout.setError(getResources().getText(R.string.err_profile_name_empty));
482 if (!checkUrlValidity())
485 if (useAuthentication.isChecked()) {
486 val = String.valueOf(userName.getText());
491 userNameLayout.setError(
492 getResources().getText(R.string.err_profile_user_name_empty));
495 val = String.valueOf(password.getText());
500 passwordLayout.setError(
501 getResources().getText(R.string.err_profile_password_empty));
508 public void onHueSelected(int hue) {
509 huePickerView.setBackgroundColor(Colors.getPrimaryColorForHue(hue));
510 huePickerView.setTag(hue);