]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/MainActivity.java
wide touch area for the profile list head gear icon
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / ui / activity / MainActivity.java
1 /*
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.
8  *
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.
13  *
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/>.
16  */
17
18 package net.ktnx.mobileledger.ui.activity;
19
20 import android.content.Intent;
21 import android.content.pm.PackageInfo;
22 import android.content.res.ColorStateList;
23 import android.graphics.Color;
24 import android.os.AsyncTask;
25 import android.os.Build;
26 import android.os.Bundle;
27 import android.util.Log;
28 import android.view.View;
29 import android.view.ViewGroup;
30 import android.view.animation.Animation;
31 import android.view.animation.AnimationUtils;
32 import android.widget.LinearLayout;
33 import android.widget.ProgressBar;
34 import android.widget.TextView;
35 import android.widget.Toast;
36
37 import com.google.android.material.floatingactionbutton.FloatingActionButton;
38
39 import net.ktnx.mobileledger.R;
40 import net.ktnx.mobileledger.async.RefreshDescriptionsTask;
41 import net.ktnx.mobileledger.async.RetrieveTransactionsTask;
42 import net.ktnx.mobileledger.model.Data;
43 import net.ktnx.mobileledger.model.LedgerAccount;
44 import net.ktnx.mobileledger.model.MobileLedgerProfile;
45 import net.ktnx.mobileledger.ui.account_summary.AccountSummaryFragment;
46 import net.ktnx.mobileledger.ui.profiles.ProfileDetailFragment;
47 import net.ktnx.mobileledger.ui.profiles.ProfilesRecyclerViewAdapter;
48 import net.ktnx.mobileledger.ui.transaction_list.TransactionListFragment;
49 import net.ktnx.mobileledger.utils.Colors;
50 import net.ktnx.mobileledger.utils.MLDB;
51
52 import java.lang.ref.WeakReference;
53 import java.text.DateFormat;
54 import java.util.Date;
55 import java.util.Observable;
56 import java.util.Observer;
57
58 import androidx.appcompat.app.ActionBarDrawerToggle;
59 import androidx.appcompat.widget.Toolbar;
60 import androidx.core.view.GravityCompat;
61 import androidx.drawerlayout.widget.DrawerLayout;
62 import androidx.fragment.app.Fragment;
63 import androidx.fragment.app.FragmentManager;
64 import androidx.fragment.app.FragmentPagerAdapter;
65 import androidx.recyclerview.widget.LinearLayoutManager;
66 import androidx.recyclerview.widget.RecyclerView;
67 import androidx.viewpager.widget.ViewPager;
68
69 public class MainActivity extends ProfileThemedActivity {
70     private static final String STATE_CURRENT_PAGE = "current_page";
71     private static final String BUNDLE_SAVED_STATE = "bundle_savedState";
72     DrawerLayout drawer;
73     private LinearLayout profileListContainer;
74     private View profileListHeadArrow, profileListHeadMore, profileListHeadCancel;
75     private LinearLayout profileListHeadMoreAndCancel;
76     private FragmentManager fragmentManager;
77     private TextView tvLastUpdate;
78     private RetrieveTransactionsTask retrieveTransactionsTask;
79     private View bTransactionListCancelDownload;
80     private ProgressBar progressBar;
81     private LinearLayout progressLayout;
82     private SectionsPagerAdapter mSectionsPagerAdapter;
83     private ViewPager mViewPager;
84     private FloatingActionButton fab;
85     private boolean profileModificationEnabled = false;
86     private boolean profileListExpanded = false;
87     private ProfilesRecyclerViewAdapter mProfileListAdapter;
88
89     @Override
90     protected void onStart() {
91         super.onStart();
92
93         Data.lastUpdateDate.set(null);
94         updateLastUpdateTextFromDB();
95         Date lastUpdate = Data.lastUpdateDate.get();
96
97         long now = new Date().getTime();
98         if ((lastUpdate == null) || (now > (lastUpdate.getTime() + (24 * 3600 * 1000)))) {
99             if (lastUpdate == null) Log.d("db::", "WEB data never fetched. scheduling a fetch");
100             else Log.d("db",
101                     String.format("WEB data last fetched at %1.3f and now is %1.3f. re-fetching",
102                             lastUpdate.getTime() / 1000f, now / 1000f));
103
104             scheduleTransactionListRetrieval();
105         }
106     }
107     @Override
108     protected void onSaveInstanceState(Bundle outState) {
109         super.onSaveInstanceState(outState);
110         outState.putInt(STATE_CURRENT_PAGE, mViewPager.getCurrentItem());
111     }
112     @Override
113     protected void onCreate(Bundle savedInstanceState) {
114         super.onCreate(savedInstanceState);
115
116         setContentView(R.layout.activity_main);
117
118         fab = findViewById(R.id.btn_add_transaction);
119         profileListContainer = findViewById(R.id.nav_profile_list_container);
120         profileListHeadArrow = findViewById(R.id.nav_profiles_arrow);
121         profileListHeadMore = findViewById(R.id.nav_profiles_start_edit);
122         profileListHeadCancel = findViewById(R.id.nav_profiles_cancel_edit);
123         profileListHeadMoreAndCancel = findViewById(R.id.nav_profile_list_head_buttons);
124         drawer = findViewById(R.id.drawer_layout);
125         tvLastUpdate = findViewById(R.id.transactions_last_update);
126         bTransactionListCancelDownload = findViewById(R.id.transaction_list_cancel_download);
127         progressBar = findViewById(R.id.transaction_list_progress_bar);
128         progressLayout = findViewById(R.id.transaction_progress_layout);
129         fragmentManager = getSupportFragmentManager();
130         mSectionsPagerAdapter = new SectionsPagerAdapter(fragmentManager);
131         mViewPager = findViewById(R.id.root_frame);
132
133         Bundle extra = getIntent().getBundleExtra(BUNDLE_SAVED_STATE);
134         if (extra != null && savedInstanceState == null) savedInstanceState = extra;
135
136
137         Toolbar toolbar = findViewById(R.id.toolbar);
138         setSupportActionBar(toolbar);
139
140         Data.profile.addObserver((o, arg) -> {
141             MobileLedgerProfile profile = Data.profile.get();
142             runOnUiThread(() -> {
143                 if (profile == null) setTitle(R.string.app_name);
144                 else setTitle(profile.getName());
145                 updateLastUpdateTextFromDB();
146                 if (profile.isPostingPermitted()) {
147                     toolbar.setSubtitle(null);
148                     fab.show();
149                 }
150                 else {
151                     toolbar.setSubtitle(R.string.profile_subitlte_read_only);
152                     fab.hide();
153                 }
154
155                 int newProfileTheme = profile.getThemeId();
156                 if (newProfileTheme != Colors.profileThemeId) {
157                     Log.d("profiles", String.format("profile theme %d → %d", Colors.profileThemeId,
158                             newProfileTheme));
159                     profileThemeChanged();
160                     Colors.profileThemeId = newProfileTheme;
161                 }
162             });
163         });
164
165         ActionBarDrawerToggle toggle =
166                 new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open,
167                         R.string.navigation_drawer_close);
168         drawer.addDrawerListener(toggle);
169         toggle.syncState();
170
171         TextView ver = drawer.findViewById(R.id.drawer_version_text);
172
173         try {
174             PackageInfo pi =
175                     getApplicationContext().getPackageManager().getPackageInfo(getPackageName(), 0);
176             ver.setText(pi.versionName);
177         }
178         catch (Exception e) {
179             e.printStackTrace();
180         }
181
182         if (progressBar == null)
183             throw new RuntimeException("Can't get hold on the transaction value progress bar");
184         if (progressLayout == null) throw new RuntimeException(
185                 "Can't get hold on the transaction value progress bar layout");
186
187         markDrawerItemCurrent(R.id.nav_account_summary);
188
189         mViewPager.setAdapter(mSectionsPagerAdapter);
190         mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
191             @Override
192             public void onPageSelected(int position) {
193                 switch (position) {
194                     case 0:
195                         markDrawerItemCurrent(R.id.nav_account_summary);
196                         break;
197                     case 1:
198                         markDrawerItemCurrent(R.id.nav_latest_transactions);
199                         break;
200                     default:
201                         Log.e("MainActivity", String.format("Unexpected page index %d", position));
202                 }
203
204                 super.onPageSelected(position);
205             }
206         });
207
208         if (savedInstanceState != null) {
209             int currentPage = savedInstanceState.getInt(STATE_CURRENT_PAGE, -1);
210             if (currentPage != -1) {
211                 mViewPager.setCurrentItem(currentPage, false);
212             }
213         }
214
215         Data.lastUpdateDate.addObserver((o, arg) -> {
216             Log.d("main", "lastUpdateDate changed");
217             runOnUiThread(() -> {
218                 Date date = Data.lastUpdateDate.get();
219                 if (date == null) {
220                     tvLastUpdate.setText(R.string.transaction_last_update_never);
221                 }
222                 else {
223                     final String text = DateFormat.getDateTimeInstance().format(date);
224                     tvLastUpdate.setText(text);
225                     Log.d("despair", String.format("Date formatted: %s", text));
226                 }
227             });
228         });
229
230         findViewById(R.id.btn_no_profiles_add)
231                 .setOnClickListener(v -> startEditProfileActivity(null));
232
233         findViewById(R.id.btn_add_transaction).setOnClickListener(this::fabNewTransactionClicked);
234
235         findViewById(R.id.nav_new_profile_button)
236                 .setOnClickListener(v -> startEditProfileActivity(null));
237
238         RecyclerView root = findViewById(R.id.nav_profile_list);
239         if (root == null)
240             throw new RuntimeException("Can't get hold on the transaction value view");
241
242         mProfileListAdapter = new ProfilesRecyclerViewAdapter();
243         root.setAdapter(mProfileListAdapter);
244
245         mProfileListAdapter.addEditingProfilesObserver(new Observer() {
246             @Override
247             public void update(Observable o, Object arg) {
248                 if (mProfileListAdapter.isEditingProfiles()) {
249                     profileListHeadArrow.clearAnimation();
250                     profileListHeadArrow.setVisibility(View.GONE);
251                     profileListHeadMore.setVisibility(View.GONE);
252                     profileListHeadCancel.setVisibility(View.VISIBLE);
253                 }
254                 else {
255                     profileListHeadArrow.setRotation(180f);
256                     profileListHeadArrow.setVisibility(View.VISIBLE);
257                     profileListHeadCancel.setVisibility(View.GONE);
258                     profileListHeadMore.setVisibility(View.GONE);
259                     profileListHeadMore
260                             .setVisibility(profileListExpanded ? View.VISIBLE : View.GONE);
261                 }
262             }
263         });
264
265         LinearLayoutManager llm = new LinearLayoutManager(this);
266
267         llm.setOrientation(RecyclerView.VERTICAL);
268         root.setLayoutManager(llm);
269
270         profileListHeadMore.setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
271         profileListHeadCancel.setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
272         profileListHeadMoreAndCancel.setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
273
274         drawer.addDrawerListener(new DrawerLayout.SimpleDrawerListener() {
275             @Override
276             public void onDrawerClosed(View drawerView) {
277                 super.onDrawerClosed(drawerView);
278                 collapseProfileList();
279             }
280         });
281     }
282     private void profileThemeChanged() {
283         setupProfileColors();
284
285         Bundle bundle = new Bundle();
286         onSaveInstanceState(bundle);
287         // restart activity to reflect theme change
288         finish();
289         Intent intent = new Intent(this, this.getClass());
290         intent.putExtra(BUNDLE_SAVED_STATE, bundle);
291         startActivity(intent);
292     }
293     @Override
294     protected void onResume() {
295         super.onResume();
296         setupProfile();
297     }
298     public void startEditProfileActivity(MobileLedgerProfile profile) {
299         Intent intent = new Intent(this, ProfileDetailActivity.class);
300         Bundle args = new Bundle();
301         if (profile != null) {
302             int index = Data.getProfileIndex(profile);
303             if (index != -1) intent.putExtra(ProfileDetailFragment.ARG_ITEM_ID, index);
304         }
305         intent.putExtras(args);
306         startActivity(intent, args);
307     }
308     private void setupProfile() {
309         String profileUUID = MLDB.getOption(MLDB.OPT_PROFILE_UUID, null);
310         MobileLedgerProfile profile;
311
312         profile = MobileLedgerProfile.loadAllFromDB(profileUUID);
313
314         if (Data.profiles.getList().isEmpty()) {
315             findViewById(R.id.no_profiles_layout).setVisibility(View.VISIBLE);
316             findViewById(R.id.pager_layout).setVisibility(View.GONE);
317             return;
318         }
319
320         findViewById(R.id.pager_layout).setVisibility(View.VISIBLE);
321         findViewById(R.id.no_profiles_layout).setVisibility(View.GONE);
322
323         if (profile == null) profile = Data.profiles.get(0);
324
325         if (profile == null) throw new AssertionError("profile must have a value");
326
327         Data.setCurrentProfile(profile);
328     }
329     public void fabNewTransactionClicked(View view) {
330         Intent intent = new Intent(this, NewTransactionActivity.class);
331         startActivity(intent);
332         overridePendingTransition(R.anim.slide_in_right, R.anim.dummy);
333     }
334     public void navSettingsClicked(View view) {
335         Intent intent = new Intent(this, SettingsActivity.class);
336         startActivity(intent);
337         drawer.closeDrawers();
338     }
339     public void markDrawerItemCurrent(int id) {
340         TextView item = drawer.findViewById(id);
341         item.setBackgroundColor(Colors.tableRowDarkBG);
342
343         LinearLayout actions = drawer.findViewById(R.id.nav_actions);
344         for (int i = 0; i < actions.getChildCount(); i++) {
345             View view = actions.getChildAt(i);
346             if (view.getId() != id) {
347                 view.setBackgroundColor(Color.TRANSPARENT);
348             }
349         }
350     }
351     public void onAccountSummaryClicked(View view) {
352         drawer.closeDrawers();
353
354         showAccountSummaryFragment();
355     }
356     private void showAccountSummaryFragment() {
357         mViewPager.setCurrentItem(0, true);
358         TransactionListFragment.accountFilter.set(null);
359 //        FragmentTransaction ft = fragmentManager.beginTransaction();
360 //        accountSummaryFragment = new AccountSummaryFragment();
361 //        ft.replace(R.id.root_frame, accountSummaryFragment);
362 //        ft.commit();
363 //        currentFragment = accountSummaryFragment;
364     }
365     public void onLatestTransactionsClicked(View view) {
366         drawer.closeDrawers();
367
368         showTransactionsFragment(null);
369     }
370     private void resetFragmentBackStack() {
371 //        fragmentManager.popBackStack(0, FragmentManager.POP_BACK_STACK_INCLUSIVE);
372     }
373     private void showTransactionsFragment(LedgerAccount account) {
374         if (account != null) TransactionListFragment.accountFilter.set(account.getName());
375         mViewPager.setCurrentItem(1, true);
376 //        FragmentTransaction ft = fragmentManager.beginTransaction();
377 //        if (transactionListFragment == null) {
378 //            Log.d("flow", "MainActivity creating TransactionListFragment");
379 //            transactionListFragment = new TransactionListFragment();
380 //        }
381 //        Bundle bundle = new Bundle();
382 //        if (account != null) {
383 //            bundle.putString(TransactionListFragment.BUNDLE_KEY_FILTER_ACCOUNT_NAME,
384 //                    account.getName());
385 //        }
386 //        transactionListFragment.setArguments(bundle);
387 //        ft.replace(R.id.root_frame, transactionListFragment);
388 //        if (account != null)
389 //            ft.addToBackStack(getResources().getString(R.string.title_activity_transaction_list));
390 //        ft.commit();
391 //
392 //        currentFragment = transactionListFragment;
393     }
394     public void showAccountTransactions(LedgerAccount account) {
395         showTransactionsFragment(account);
396     }
397     @Override
398     public void onBackPressed() {
399         DrawerLayout drawer = findViewById(R.id.drawer_layout);
400         if (drawer.isDrawerOpen(GravityCompat.START)) {
401             drawer.closeDrawer(GravityCompat.START);
402         }
403         else {
404             Log.d("fragments",
405                     String.format("manager stack: %d", fragmentManager.getBackStackEntryCount()));
406
407             super.onBackPressed();
408         }
409     }
410     public void updateLastUpdateTextFromDB() {
411         {
412             final MobileLedgerProfile profile = Data.profile.get();
413             long last_update =
414                     (profile != null) ? profile.getLongOption(MLDB.OPT_LAST_SCRAPE, 0L) : 0;
415
416             Log.d("transactions", String.format("Last update = %d", last_update));
417             if (last_update == 0) {
418                 Data.lastUpdateDate.set(null);
419             }
420             else {
421                 Data.lastUpdateDate.set(new Date(last_update));
422             }
423         }
424     }
425     public void scheduleTransactionListRetrieval() {
426         if (Data.profile.get() == null) return;
427
428         retrieveTransactionsTask = new RetrieveTransactionsTask(new WeakReference<>(this));
429
430         retrieveTransactionsTask.execute();
431     }
432     public void onStopTransactionRefreshClick(View view) {
433         Log.d("interactive", "Cancelling transactions refresh");
434         if (retrieveTransactionsTask != null) retrieveTransactionsTask.cancel(false);
435         bTransactionListCancelDownload.setEnabled(false);
436     }
437     public void onRetrieveDone(String error) {
438         progressLayout.setVisibility(View.GONE);
439
440         if (error == null) {
441             updateLastUpdateTextFromDB();
442
443             new RefreshDescriptionsTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
444         }
445         else Toast.makeText(this, error, Toast.LENGTH_LONG).show();
446     }
447     public void onRetrieveStart() {
448         bTransactionListCancelDownload.setEnabled(true);
449         progressBar.setIndeterminateTintList(ColorStateList.valueOf(Colors.primary));
450         progressBar.setProgressTintList(ColorStateList.valueOf(Colors.primary));
451         progressBar.setIndeterminate(true);
452         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) progressBar.setProgress(0, false);
453         else progressBar.setProgress(0);
454         progressLayout.setVisibility(View.VISIBLE);
455     }
456     public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
457         if ((progress.getTotal() == RetrieveTransactionsTask.Progress.INDETERMINATE) ||
458             (progress.getTotal() == 0))
459         {
460             progressBar.setIndeterminate(true);
461         }
462         else {
463             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
464                 progressBar.setMin(0);
465             }
466             progressBar.setMax(progress.getTotal());
467             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
468                 progressBar.setProgress(progress.getProgress(), true);
469             }
470             else progressBar.setProgress(progress.getProgress());
471             progressBar.setIndeterminate(false);
472         }
473     }
474     public void fabShouldShow() {
475         MobileLedgerProfile profile = Data.profile.get();
476         if ((profile != null) && profile.isPostingPermitted()) fab.show();
477     }
478     public void navProfilesHeadClicked(View view) {
479         if (profileListExpanded) {
480             collapseProfileList();
481         }
482         else {
483             expandProfileList();
484         }
485     }
486     private void expandProfileList() {
487         profileListExpanded = true;
488
489
490         profileListContainer.setVisibility(View.VISIBLE);
491         profileListContainer.startAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_down));
492         profileListHeadArrow.startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate_180));
493         profileListHeadMore.setVisibility(View.VISIBLE);
494         profileListHeadMore.startAnimation(AnimationUtils.loadAnimation(this, R.anim.fade_in));
495     }
496     private void collapseProfileList() {
497         profileListExpanded = false;
498
499         final Animation animation = AnimationUtils.loadAnimation(this, R.anim.slide_up);
500         animation.setAnimationListener(new Animation.AnimationListener() {
501             @Override
502             public void onAnimationStart(Animation animation) {
503
504             }
505             @Override
506             public void onAnimationEnd(Animation animation) {
507                 profileListContainer.setVisibility(View.GONE);
508             }
509             @Override
510             public void onAnimationRepeat(Animation animation) {
511
512             }
513         });
514         mProfileListAdapter.stopEditingProfiles();
515
516         profileListContainer.startAnimation(animation);
517         profileListHeadArrow.setRotation(0f);
518         profileListHeadArrow
519                 .startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate_180_back));
520         profileListHeadMore.setVisibility(View.GONE);
521     }
522     public void onProfileRowClicked(View v) {
523         Data.setCurrentProfile((MobileLedgerProfile) v.getTag());
524     }
525     public void enableProfileModifications() {
526         profileModificationEnabled = true;
527         ViewGroup profileList = findViewById(R.id.nav_profile_list);
528         for (int i = 0; i < profileList.getChildCount(); i++) {
529             View aRow = profileList.getChildAt(i);
530             aRow.findViewById(R.id.profile_list_edit_button).setVisibility(View.VISIBLE);
531             aRow.findViewById(R.id.profile_list_rearrange_handle).setVisibility(View.VISIBLE);
532         }
533         // FIXME enable rearranging
534
535     }
536     public void disableProfileModifications() {
537         profileModificationEnabled = false;
538         ViewGroup profileList = findViewById(R.id.nav_profile_list);
539         for (int i = 0; i < profileList.getChildCount(); i++) {
540             View aRow = profileList.getChildAt(i);
541             aRow.findViewById(R.id.profile_list_edit_button).setVisibility(View.GONE);
542             aRow.findViewById(R.id.profile_list_rearrange_handle).setVisibility(View.INVISIBLE);
543         }
544         // FIXME disable rearranging
545
546     }
547
548     public class SectionsPagerAdapter extends FragmentPagerAdapter {
549
550         public SectionsPagerAdapter(FragmentManager fm) {
551             super(fm);
552         }
553
554         @Override
555         public Fragment getItem(int position) {
556             Log.d("main", String.format("Switching to fragment %d", position));
557             switch (position) {
558                 case 0:
559                     return new AccountSummaryFragment();
560                 case 1:
561                     return new TransactionListFragment();
562                 default:
563                     throw new IllegalStateException(
564                             String.format("Unexpected fragment index: " + "%d", position));
565             }
566         }
567
568         @Override
569         public int getCount() {
570             return 2;
571         }
572     }
573
574 }