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