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.Switch;
33 import android.widget.TextView;
35 import com.google.android.material.appbar.CollapsingToolbarLayout;
36 import com.google.android.material.floatingactionbutton.FloatingActionButton;
37 import com.google.android.material.textfield.TextInputLayout;
39 import net.ktnx.mobileledger.BuildConfig;
40 import net.ktnx.mobileledger.R;
41 import net.ktnx.mobileledger.model.Data;
42 import net.ktnx.mobileledger.model.MobileLedgerProfile;
43 import net.ktnx.mobileledger.ui.HueRingDialog;
44 import net.ktnx.mobileledger.ui.activity.ProfileDetailActivity;
45 import net.ktnx.mobileledger.utils.Colors;
47 import org.jetbrains.annotations.NotNull;
49 import java.net.MalformedURLException;
51 import java.util.ArrayList;
52 import java.util.Objects;
54 import androidx.annotation.NonNull;
55 import androidx.annotation.Nullable;
56 import androidx.fragment.app.Fragment;
57 import androidx.fragment.app.FragmentActivity;
59 import static net.ktnx.mobileledger.utils.Logger.debug;
62 * A fragment representing a single Profile detail screen.
63 * a {@link ProfileDetailActivity}
66 public class ProfileDetailFragment extends Fragment implements HueRingDialog.HueSelectedListener {
68 * The fragment argument representing the item ID that this fragment
71 public static final String ARG_ITEM_ID = "item_id";
74 * The dummy content this fragment is presenting.
76 private MobileLedgerProfile mProfile;
78 private Switch postingPermitted;
79 private TextInputLayout urlLayout;
80 private LinearLayout authParams;
81 private Switch useAuthentication;
82 private TextView userName;
83 private TextInputLayout userNameLayout;
84 private TextView password;
85 private TextInputLayout passwordLayout;
86 private TextView profileName;
87 private TextInputLayout profileNameLayout;
88 private TextView preferredAccountsFilter;
89 private TextInputLayout preferredAccountsFilterLayout;
90 private View huePickerView;
93 * Mandatory empty constructor for the fragment manager to instantiate the
94 * fragment (e.g. upon screen orientation changes).
96 public ProfileDetailFragment() {
99 public void onCreateOptionsMenu(@NotNull Menu menu, @NotNull MenuInflater inflater) {
100 debug("profiles", "[fragment] Creating profile details options menu");
101 super.onCreateOptionsMenu(menu, inflater);
102 inflater.inflate(R.menu.profile_details, menu);
103 final MenuItem menuDeleteProfile = menu.findItem(R.id.menuDelete);
104 menuDeleteProfile.setOnMenuItemClickListener(item -> {
105 AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
106 builder.setTitle(mProfile.getName());
107 builder.setMessage(R.string.remove_profile_dialog_message);
108 builder.setPositiveButton(R.string.Remove, (dialog, which) -> {
110 String.format("[fragment] removing profile %s", mProfile.getUuid()));
111 mProfile.removeFromDB();
112 ArrayList<MobileLedgerProfile> oldList = Data.profiles.getValue();
113 if (oldList == null) throw new AssertionError();
114 ArrayList<MobileLedgerProfile> newList =
115 (ArrayList<MobileLedgerProfile>) oldList.clone();
116 newList.remove(mProfile);
117 Data.profiles.setValue(newList);
118 if (mProfile.equals(Data.profile.getValue())) {
119 debug("profiles", "[fragment] setting current profile to 0");
120 Data.setCurrentProfile(newList.get(0));
123 final FragmentActivity activity = getActivity();
124 if (activity != null) activity.finish();
129 final ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
131 .setVisible((mProfile != null) && (profiles != null) && (profiles.size() > 1));
133 if (BuildConfig.DEBUG) {
134 final MenuItem menuWipeProfileData = menu.findItem(R.id.menuWipeData);
135 menuWipeProfileData.setOnMenuItemClickListener(ignored -> onWipeDataMenuClicked());
136 menuWipeProfileData.setVisible(mProfile != null);
139 private boolean onWipeDataMenuClicked() {
140 // this is a development option, so no confirmation
141 mProfile.wipeAllData();
142 if (mProfile.equals(Data.profile.getValue())) triggerProfileChange();
145 private void triggerProfileChange() {
146 int index = Data.getProfileIndex(mProfile);
147 MobileLedgerProfile newProfile = new MobileLedgerProfile(mProfile);
148 final ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
149 if (profiles == null) throw new AssertionError();
150 profiles.set(index, newProfile);
152 ProfilesRecyclerViewAdapter prva = ProfilesRecyclerViewAdapter.getInstance();
153 if (prva != null) prva.notifyItemChanged(index);
155 if (mProfile.equals(Data.profile.getValue())) Data.profile.setValue(newProfile);
158 public void onCreate(Bundle savedInstanceState) {
159 super.onCreate(savedInstanceState);
161 if ((getArguments() != null) && getArguments().containsKey(ARG_ITEM_ID)) {
162 int index = getArguments().getInt(ARG_ITEM_ID, -1);
163 ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
164 if ((profiles != null) && (index != -1) && (index < profiles.size()))
165 mProfile = profiles.get(index);
167 Activity activity = this.getActivity();
168 if (activity == null) throw new AssertionError();
169 CollapsingToolbarLayout appBarLayout = activity.findViewById(R.id.toolbar_layout);
170 if (appBarLayout != null) {
171 if (mProfile != null) appBarLayout.setTitle(mProfile.getName());
172 else appBarLayout.setTitle(getResources().getString(R.string.new_profile_title));
177 public void onActivityCreated(@Nullable Bundle savedInstanceState) {
178 super.onActivityCreated(savedInstanceState);
179 Activity context = getActivity();
180 if (context == null) return;
182 FloatingActionButton fab = context.findViewById(R.id.fab);
183 fab.setOnClickListener(v -> onSaveFabClicked());
185 profileName.requestFocus();
187 private void onSaveFabClicked() {
188 if (!checkValidity()) return;
190 if (mProfile != null) {
191 updateProfileFromUI();
192 // debug("profiles", String.format("Selected item is %d", mProfile.getThemeId()));
193 mProfile.storeInDB();
194 debug("profiles", "profile stored in DB");
195 triggerProfileChange();
198 mProfile = new MobileLedgerProfile();
199 updateProfileFromUI();
200 mProfile.storeInDB();
201 final ArrayList<MobileLedgerProfile> profiles = Data.profiles.getValue();
202 if (profiles == null) throw new AssertionError();
203 ArrayList<MobileLedgerProfile> newList =
204 (ArrayList<MobileLedgerProfile>) profiles.clone();
205 newList.add(mProfile);
206 Data.profiles.setValue(newList);
207 MobileLedgerProfile.storeProfilesOrder();
209 // first profile ever?
210 if (newList.size() == 1) Data.profile.setValue(mProfile);
213 Activity activity = getActivity();
214 if (activity != null) activity.finish();
216 private void updateProfileFromUI() {
217 mProfile.setName(profileName.getText());
218 mProfile.setUrl(url.getText());
219 mProfile.setPostingPermitted(postingPermitted.isChecked());
220 mProfile.setPreferredAccountsFilter(preferredAccountsFilter.getText());
221 mProfile.setAuthEnabled(useAuthentication.isChecked());
222 mProfile.setAuthUserName(userName.getText());
223 mProfile.setAuthPassword(password.getText());
224 mProfile.setThemeId(huePickerView.getTag());
227 public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
228 Bundle savedInstanceState) {
229 View rootView = inflater.inflate(R.layout.profile_detail, container, false);
231 profileName = rootView.findViewById(R.id.profile_name);
232 profileNameLayout = rootView.findViewById(R.id.profile_name_layout);
233 url = rootView.findViewById(R.id.url);
234 urlLayout = rootView.findViewById(R.id.url_layout);
235 postingPermitted = rootView.findViewById(R.id.profile_permit_posting);
236 authParams = rootView.findViewById(R.id.auth_params);
237 useAuthentication = rootView.findViewById(R.id.enable_http_auth);
238 userName = rootView.findViewById(R.id.auth_user_name);
239 userNameLayout = rootView.findViewById(R.id.auth_user_name_layout);
240 password = rootView.findViewById(R.id.password);
241 passwordLayout = rootView.findViewById(R.id.password_layout);
242 huePickerView = rootView.findViewById(R.id.btn_pick_ring_color);
243 preferredAccountsFilter = rootView.findViewById(R.id.preferred_accounts_filter_filter);
244 preferredAccountsFilterLayout =
245 rootView.findViewById(R.id.preferred_accounts_accounts_filter_layout);
247 useAuthentication.setOnCheckedChangeListener((buttonView, isChecked) -> {
248 debug("profiles", isChecked ? "auth enabled " : "auth disabled");
249 authParams.setVisibility(isChecked ? View.VISIBLE : View.GONE);
250 if (isChecked) userName.requestFocus();
253 postingPermitted.setOnCheckedChangeListener(
254 ((buttonView, isChecked) -> preferredAccountsFilterLayout
255 .setVisibility(isChecked ? View.VISIBLE : View.GONE)));
257 hookClearErrorOnFocusListener(profileName, profileNameLayout);
258 hookClearErrorOnFocusListener(url, urlLayout);
259 hookClearErrorOnFocusListener(userName, userNameLayout);
260 hookClearErrorOnFocusListener(password, passwordLayout);
263 if (mProfile != null) {
264 profileName.setText(mProfile.getName());
265 postingPermitted.setChecked(mProfile.isPostingPermitted());
266 url.setText(mProfile.getUrl());
267 useAuthentication.setChecked(mProfile.isAuthEnabled());
268 authParams.setVisibility(mProfile.isAuthEnabled() ? View.VISIBLE : View.GONE);
269 userName.setText(mProfile.isAuthEnabled() ? mProfile.getAuthUserName() : "");
270 password.setText(mProfile.isAuthEnabled() ? mProfile.getAuthPassword() : "");
271 preferredAccountsFilter.setText(mProfile.getPreferredAccountsFilter());
272 profileThemeId = mProfile.getThemeId();
275 profileName.setText("");
276 url.setText("https://");
277 postingPermitted.setChecked(true);
278 useAuthentication.setChecked(false);
279 authParams.setVisibility(View.GONE);
280 userName.setText("");
281 password.setText("");
282 preferredAccountsFilter.setText(null);
286 final int hue = (profileThemeId == -1) ? Colors.DEFAULT_HUE_DEG : profileThemeId;
287 final int profileColor = Colors.getPrimaryColorForHue(hue);
289 huePickerView.setBackgroundColor(profileColor);
290 huePickerView.setTag(profileThemeId);
291 huePickerView.setOnClickListener(v -> {
292 HueRingDialog d = new HueRingDialog(
293 Objects.requireNonNull(ProfileDetailFragment.this.getContext()), profileThemeId,
294 (Integer) v.getTag());
296 d.setColorSelectedListener(this);
300 private void hookClearErrorOnFocusListener(TextView view, TextInputLayout layout) {
301 view.setOnFocusChangeListener((v, hasFocus) -> {
302 if (hasFocus) layout.setError(null);
304 view.addTextChangedListener(new TextWatcher() {
306 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
309 public void onTextChanged(CharSequence s, int start, int before, int count) {
310 layout.setError(null);
313 public void afterTextChanged(Editable s) {
317 private boolean checkValidity() {
318 boolean valid = true;
320 String val = String.valueOf(profileName.getText());
321 if (val.trim().isEmpty()) {
323 profileNameLayout.setError(getResources().getText(R.string.err_profile_name_empty));
326 val = String.valueOf(url.getText()).trim();
329 urlLayout.setError(getResources().getText(R.string.err_profile_url_empty));
332 URL url = new URL(val);
333 String host = url.getHost();
334 if (host == null || host.isEmpty()) throw new MalformedURLException("Missing host");
336 catch (MalformedURLException e) {
338 urlLayout.setError(getResources().getText(R.string.err_invalid_url));
340 if (useAuthentication.isChecked()) {
341 val = String.valueOf(userName.getText());
342 if (val.trim().isEmpty()) {
345 .setError(getResources().getText(R.string.err_profile_user_name_empty));
348 val = String.valueOf(password.getText());
349 if (val.trim().isEmpty()) {
352 .setError(getResources().getText(R.string.err_profile_password_empty));
359 public void onHueSelected(int hue) {
360 huePickerView.setBackgroundColor(Colors.getPrimaryColorForHue(hue));
361 huePickerView.setTag(hue);