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