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.model.Data;
48 import net.ktnx.mobileledger.model.MobileLedgerProfile;
49 import net.ktnx.mobileledger.ui.HueRingDialog;
50 import net.ktnx.mobileledger.ui.activity.ProfileDetailActivity;
51 import net.ktnx.mobileledger.utils.Colors;
53 import org.jetbrains.annotations.NonNls;
54 import org.jetbrains.annotations.NotNull;
56 import java.net.MalformedURLException;
58 import java.util.ArrayList;
59 import java.util.Objects;
61 import static net.ktnx.mobileledger.utils.Logger.debug;
64 * A fragment representing a single Profile detail screen.
65 * a {@link ProfileDetailActivity}
68 public class ProfileDetailFragment extends Fragment implements HueRingDialog.HueSelectedListener {
70 * The fragment argument representing the item ID that this fragment
73 public static final String ARG_ITEM_ID = "item_id";
75 private static final String HTTPS_URL_START = "https://";
78 * The dummy content this fragment is presenting.
80 private MobileLedgerProfile mProfile;
82 private Switch postingPermitted;
83 private TextInputLayout urlLayout;
84 private LinearLayout authParams;
85 private Switch useAuthentication;
86 private TextView userName;
87 private TextInputLayout userNameLayout;
88 private TextView password;
89 private TextInputLayout passwordLayout;
90 private TextView profileName;
91 private TextInputLayout profileNameLayout;
92 private TextView preferredAccountsFilter;
93 private TextInputLayout preferredAccountsFilterLayout;
94 private View huePickerView;
95 private View insecureWarningText;
96 private TextView futureDatesText;
97 private MobileLedgerProfile.FutureDates futureDates;
98 private View futureDatesLayout;
101 * Mandatory empty constructor for the fragment manager to instantiate the
102 * fragment (e.g. upon screen orientation changes).
104 public ProfileDetailFragment() {
107 public void onCreateOptionsMenu(@NotNull Menu menu, @NotNull MenuInflater inflater) {
108 debug("profiles", "[fragment] Creating profile details options menu");
109 super.onCreateOptionsMenu(menu, inflater);
110 inflater.inflate(R.menu.profile_details, menu);
111 final MenuItem menuDeleteProfile = menu.findItem(R.id.menuDelete);
112 menuDeleteProfile.setOnMenuItemClickListener(item -> {
113 AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
114 builder.setTitle(mProfile.getName());
115 builder.setMessage(R.string.remove_profile_dialog_message);
116 builder.setPositiveButton(R.string.Remove, (dialog, which) -> {
118 String.format("[fragment] removing profile %s", mProfile.getUuid()));
119 mProfile.removeFromDB();
120 ArrayList<MobileLedgerProfile> oldList = Data.profiles.getValue();
121 if (oldList == null) throw new AssertionError();
122 ArrayList<MobileLedgerProfile> newList = new ArrayList<>(oldList);
123 newList.remove(mProfile);
124 Data.profiles.setValue(newList);
125 if (mProfile.equals(Data.profile.getValue())) {
126 debug("profiles", "[fragment] setting current profile to 0");
127 Data.setCurrentProfile(newList.get(0));
130 final FragmentActivity activity = getActivity();
131 if (activity != null) activity.finish();
136 final ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
138 .setVisible((mProfile != null) && (profiles != null) && (profiles.size() > 1));
140 if (BuildConfig.DEBUG) {
141 final MenuItem menuWipeProfileData = menu.findItem(R.id.menuWipeData);
142 menuWipeProfileData.setOnMenuItemClickListener(ignored -> onWipeDataMenuClicked());
143 menuWipeProfileData.setVisible(mProfile != null);
146 private boolean onWipeDataMenuClicked() {
147 // this is a development option, so no confirmation
148 mProfile.wipeAllData();
149 if (mProfile.equals(Data.profile.getValue())) triggerProfileChange();
152 private void triggerProfileChange() {
153 int index = Data.getProfileIndex(mProfile);
154 MobileLedgerProfile newProfile = new MobileLedgerProfile(mProfile);
155 final ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
156 if (profiles == null) throw new AssertionError();
157 profiles.set(index, newProfile);
159 ProfilesRecyclerViewAdapter prva = ProfilesRecyclerViewAdapter.getInstance();
160 if (prva != null) prva.notifyItemChanged(index);
162 if (mProfile.equals(Data.profile.getValue())) Data.profile.setValue(newProfile);
165 public void onCreate(Bundle savedInstanceState) {
166 super.onCreate(savedInstanceState);
168 if ((getArguments() != null) && getArguments().containsKey(ARG_ITEM_ID)) {
169 int index = getArguments().getInt(ARG_ITEM_ID, -1);
170 ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
171 if ((profiles != null) && (index != -1) && (index < profiles.size()))
172 mProfile = profiles.get(index);
174 Activity activity = this.getActivity();
175 if (activity == null) throw new AssertionError();
176 CollapsingToolbarLayout appBarLayout = activity.findViewById(R.id.toolbar_layout);
177 if (appBarLayout != null) {
178 if (mProfile != null) appBarLayout.setTitle(mProfile.getName());
179 else appBarLayout.setTitle(getResources().getString(R.string.new_profile_title));
184 public void onActivityCreated(@Nullable Bundle savedInstanceState) {
185 super.onActivityCreated(savedInstanceState);
186 Activity context = getActivity();
187 if (context == null) return;
189 FloatingActionButton fab = context.findViewById(R.id.fab);
190 fab.setOnClickListener(v -> onSaveFabClicked());
192 profileName.requestFocus();
194 private void onSaveFabClicked() {
195 if (!checkValidity()) return;
197 if (mProfile != null) {
198 updateProfileFromUI();
199 // debug("profiles", String.format("Selected item is %d", mProfile.getThemeId()));
200 mProfile.storeInDB();
201 debug("profiles", "profile stored in DB");
202 triggerProfileChange();
205 mProfile = new MobileLedgerProfile();
206 updateProfileFromUI();
207 mProfile.storeInDB();
208 final ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
209 if (profiles == null) throw new AssertionError();
210 ArrayList<MobileLedgerProfile> newList = new ArrayList<>(profiles);
211 newList.add(mProfile);
212 Data.profiles.setValue(newList);
213 MobileLedgerProfile.storeProfilesOrder();
215 // first profile ever?
216 if (newList.size() == 1) Data.profile.setValue(mProfile);
219 Activity activity = getActivity();
220 if (activity != null) activity.finish();
222 private void updateProfileFromUI() {
223 mProfile.setName(profileName.getText());
224 mProfile.setUrl(url.getText());
225 mProfile.setPostingPermitted(postingPermitted.isChecked());
226 mProfile.setPreferredAccountsFilter(preferredAccountsFilter.getText());
227 mProfile.setAuthEnabled(useAuthentication.isChecked());
228 mProfile.setAuthUserName(userName.getText());
229 mProfile.setAuthPassword(password.getText());
230 mProfile.setThemeId(huePickerView.getTag());
231 mProfile.setFutureDates(futureDates);
234 public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
235 Bundle savedInstanceState) {
236 View rootView = inflater.inflate(R.layout.profile_detail, container, false);
238 profileName = rootView.findViewById(R.id.profile_name);
239 profileNameLayout = rootView.findViewById(R.id.profile_name_layout);
240 url = rootView.findViewById(R.id.url);
241 urlLayout = rootView.findViewById(R.id.url_layout);
242 postingPermitted = rootView.findViewById(R.id.profile_permit_posting);
243 futureDatesLayout = rootView.findViewById(R.id.future_dates_layout);
244 futureDatesText = rootView.findViewById(R.id.future_dates_text);
245 rootView.findViewById(R.id.future_dates_layout)
246 .setOnClickListener(v -> {
247 MenuInflater mi = new MenuInflater(getContext());
248 PopupMenu menu = new PopupMenu(getContext(), v);
249 menu.inflate(R.menu.future_dates);
250 menu.setOnMenuItemClickListener(item -> {
251 switch (item.getItemId()) {
252 case R.id.menu_future_dates_30:
253 futureDates = MobileLedgerProfile.FutureDates.OneMonth;
255 case R.id.menu_future_dates_60:
256 futureDates = MobileLedgerProfile.FutureDates.TwoMonths;
258 case R.id.menu_future_dates_90:
259 futureDates = MobileLedgerProfile.FutureDates.ThreeMonths;
261 case R.id.menu_future_dates_180:
262 futureDates = MobileLedgerProfile.FutureDates.SixMonths;
264 case R.id.menu_future_dates_365:
265 futureDates = MobileLedgerProfile.FutureDates.OneYear;
267 case R.id.menu_future_dates_all:
268 futureDates = MobileLedgerProfile.FutureDates.All;
271 futureDates = MobileLedgerProfile.FutureDates.None;
273 futureDatesText.setText(futureDates.getText(getResources()));
278 authParams = rootView.findViewById(R.id.auth_params);
279 useAuthentication = rootView.findViewById(R.id.enable_http_auth);
280 userName = rootView.findViewById(R.id.auth_user_name);
281 userNameLayout = rootView.findViewById(R.id.auth_user_name_layout);
282 password = rootView.findViewById(R.id.password);
283 passwordLayout = rootView.findViewById(R.id.password_layout);
284 huePickerView = rootView.findViewById(R.id.btn_pick_ring_color);
285 preferredAccountsFilter = rootView.findViewById(R.id.preferred_accounts_filter_filter);
286 preferredAccountsFilterLayout =
287 rootView.findViewById(R.id.preferred_accounts_accounts_filter_layout);
288 insecureWarningText = rootView.findViewById(R.id.insecure_scheme_text);
290 useAuthentication.setOnCheckedChangeListener((buttonView, isChecked) -> {
291 debug("profiles", isChecked ? "auth enabled " : "auth disabled");
292 authParams.setVisibility(isChecked ? View.VISIBLE : View.GONE);
293 if (isChecked) userName.requestFocus();
294 checkInsecureSchemeWithAuth();
297 postingPermitted.setOnCheckedChangeListener(((buttonView, isChecked) -> {
298 preferredAccountsFilterLayout.setVisibility(isChecked ? View.VISIBLE : View.GONE);
299 futureDatesLayout.setVisibility(isChecked ? View.VISIBLE : View.GONE);
302 hookClearErrorOnFocusListener(profileName, profileNameLayout);
303 hookClearErrorOnFocusListener(url, urlLayout);
304 hookClearErrorOnFocusListener(userName, userNameLayout);
305 hookClearErrorOnFocusListener(password, passwordLayout);
308 if (mProfile != null) {
309 profileName.setText(mProfile.getName());
310 postingPermitted.setChecked(mProfile.isPostingPermitted());
311 futureDates = mProfile.getFutureDates();
312 futureDatesText.setText(futureDates.getText(getResources()));
313 url.setText(mProfile.getUrl());
314 useAuthentication.setChecked(mProfile.isAuthEnabled());
315 authParams.setVisibility(mProfile.isAuthEnabled() ? View.VISIBLE : View.GONE);
316 userName.setText(mProfile.isAuthEnabled() ? mProfile.getAuthUserName() : "");
317 password.setText(mProfile.isAuthEnabled() ? mProfile.getAuthPassword() : "");
318 preferredAccountsFilter.setText(mProfile.getPreferredAccountsFilter());
319 profileThemeId = mProfile.getThemeId();
322 profileName.setText("");
323 url.setText(HTTPS_URL_START);
324 postingPermitted.setChecked(true);
325 futureDates = MobileLedgerProfile.FutureDates.None;
326 futureDatesText.setText(futureDates.getText(getResources()));
327 useAuthentication.setChecked(false);
328 authParams.setVisibility(View.GONE);
329 userName.setText("");
330 password.setText("");
331 preferredAccountsFilter.setText(null);
335 checkInsecureSchemeWithAuth();
337 url.addTextChangedListener(new TextWatcher() {
339 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
343 public void onTextChanged(CharSequence s, int start, int before, int count) {
347 public void afterTextChanged(Editable s) {
348 checkInsecureSchemeWithAuth();
352 final int hue = (profileThemeId == -1) ? Colors.DEFAULT_HUE_DEG : profileThemeId;
353 final int profileColor = Colors.getPrimaryColorForHue(hue);
355 huePickerView.setBackgroundColor(profileColor);
356 huePickerView.setTag(profileThemeId);
357 huePickerView.setOnClickListener(v -> {
358 HueRingDialog d = new HueRingDialog(
359 Objects.requireNonNull(ProfileDetailFragment.this.getContext()), profileThemeId,
360 (Integer) v.getTag());
362 d.setColorSelectedListener(this);
366 private boolean checkUrlValidity() {
367 boolean valid = true;
369 String val = String.valueOf(url.getText()).trim();
372 urlLayout.setError(getResources().getText(R.string.err_profile_url_empty));
375 URL url = new URL(val);
376 String host = url.getHost();
377 if (host == null || host.isEmpty()) throw new MalformedURLException("Missing host");
378 String protocol = url.getProtocol().toUpperCase();
379 if (!protocol.equals("HTTP") && !protocol.equals("HTTPS")) {
381 urlLayout.setError(getResources().getText(R.string.err_invalid_url));
384 catch (MalformedURLException e) {
386 urlLayout.setError(getResources().getText(R.string.err_invalid_url));
391 private void checkInsecureSchemeWithAuth() {
392 boolean showWarning = false;
394 if (useAuthentication.isChecked()) {
395 String urlText = url.getText().toString();
396 if (urlText.startsWith("http") && !urlText.startsWith("https")) showWarning = true;
399 if (showWarning) insecureWarningText.setVisibility(View.VISIBLE);
400 else insecureWarningText.setVisibility(View.GONE);
402 private void hookClearErrorOnFocusListener(TextView view, TextInputLayout layout) {
403 view.setOnFocusChangeListener((v, hasFocus) -> {
404 if (hasFocus) layout.setError(null);
406 view.addTextChangedListener(new TextWatcher() {
408 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
411 public void onTextChanged(CharSequence s, int start, int before, int count) {
412 layout.setError(null);
415 public void afterTextChanged(Editable s) {
419 private boolean checkValidity() {
420 boolean valid = true;
422 String val = String.valueOf(profileName.getText());
423 if (val.trim().isEmpty()) {
425 profileNameLayout.setError(getResources().getText(R.string.err_profile_name_empty));
428 if (!checkUrlValidity()) valid = false;
430 if (useAuthentication.isChecked()) {
431 val = String.valueOf(userName.getText());
432 if (val.trim().isEmpty()) {
435 .setError(getResources().getText(R.string.err_profile_user_name_empty));
438 val = String.valueOf(password.getText());
439 if (val.trim().isEmpty()) {
442 .setError(getResources().getText(R.string.err_profile_password_empty));
449 public void onHueSelected(int hue) {
450 huePickerView.setBackgroundColor(Colors.getPrimaryColorForHue(hue));
451 huePickerView.setTag(hue);