]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/MainActivity.java
whitespace
[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
273                 .setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
274
275         drawer.addDrawerListener(new DrawerLayout.SimpleDrawerListener() {
276             @Override
277             public void onDrawerClosed(View drawerView) {
278                 super.onDrawerClosed(drawerView);
279                 collapseProfileList();
280             }
281         });
282     }
283     private void profileThemeChanged() {
284         setupProfileColors();
285
286         Bundle bundle = new Bundle();
287         onSaveInstanceState(bundle);
288         // restart activity to reflect theme change
289         finish();
290         Intent intent = new Intent(this, this.getClass());
291         intent.putExtra(BUNDLE_SAVED_STATE, bundle);
292         startActivity(intent);
293     }
294     @Override
295     protected void onResume() {
296         super.onResume();
297         setupProfile();
298     }
299     public void startEditProfileActivity(MobileLedgerProfile profile) {
300         Intent intent = new Intent(this, ProfileDetailActivity.class);
301         Bundle args = new Bundle();
302         if (profile != null) {
303             int index = Data.getProfileIndex(profile);
304             if (index != -1) intent.putExtra(ProfileDetailFragment.ARG_ITEM_ID, index);
305         }
306         intent.putExtras(args);
307         startActivity(intent, args);
308     }
309     private void setupProfile() {
310         String profileUUID = MLDB.getOption(MLDB.OPT_PROFILE_UUID, null);
311         MobileLedgerProfile profile;
312
313         profile = MobileLedgerProfile.loadAllFromDB(profileUUID);
314
315         if (Data.profiles.getList().isEmpty()) {
316             findViewById(R.id.no_profiles_layout).setVisibility(View.VISIBLE);
317             findViewById(R.id.pager_layout).setVisibility(View.GONE);
318             return;
319         }
320
321         findViewById(R.id.pager_layout).setVisibility(View.VISIBLE);
322         findViewById(R.id.no_profiles_layout).setVisibility(View.GONE);
323
324         if (profile == null) profile = Data.profiles.get(0);
325
326         if (profile == null) throw new AssertionError("profile must have a value");
327
328         Data.setCurrentProfile(profile);
329     }
330     public void fabNewTransactionClicked(View view) {
331         Intent intent = new Intent(this, NewTransactionActivity.class);
332         startActivity(intent);
333         overridePendingTransition(R.anim.slide_in_right, R.anim.dummy);
334     }
335     public void navSettingsClicked(View view) {
336         Intent intent = new Intent(this, SettingsActivity.class);
337         startActivity(intent);
338         drawer.closeDrawers();
339     }
340     public void markDrawerItemCurrent(int id) {
341         TextView item = drawer.findViewById(id);
342         item.setBackgroundColor(Colors.tableRowDarkBG);
343
344         LinearLayout actions = drawer.findViewById(R.id.nav_actions);
345         for (int i = 0; i < actions.getChildCount(); i++) {
346             View view = actions.getChildAt(i);
347             if (view.getId() != id) {
348                 view.setBackgroundColor(Color.TRANSPARENT);
349             }
350         }
351     }
352     public void onAccountSummaryClicked(View view) {
353         drawer.closeDrawers();
354
355         showAccountSummaryFragment();
356     }
357     private void showAccountSummaryFragment() {
358         mViewPager.setCurrentItem(0, true);
359         TransactionListFragment.accountFilter.set(null);
360 //        FragmentTransaction ft = fragmentManager.beginTransaction();
361 //        accountSummaryFragment = new AccountSummaryFragment();
362 //        ft.replace(R.id.root_frame, accountSummaryFragment);
363 //        ft.commit();
364 //        currentFragment = accountSummaryFragment;
365     }
366     public void onLatestTransactionsClicked(View view) {
367         drawer.closeDrawers();
368
369         showTransactionsFragment(null);
370     }
371     private void resetFragmentBackStack() {
372 //        fragmentManager.popBackStack(0, FragmentManager.POP_BACK_STACK_INCLUSIVE);
373     }
374     private void showTransactionsFragment(LedgerAccount account) {
375         if (account != null) TransactionListFragment.accountFilter.set(account.getName());
376         mViewPager.setCurrentItem(1, true);
377 //        FragmentTransaction ft = fragmentManager.beginTransaction();
378 //        if (transactionListFragment == null) {
379 //            Log.d("flow", "MainActivity creating TransactionListFragment");
380 //            transactionListFragment = new TransactionListFragment();
381 //        }
382 //        Bundle bundle = new Bundle();
383 //        if (account != null) {
384 //            bundle.putString(TransactionListFragment.BUNDLE_KEY_FILTER_ACCOUNT_NAME,
385 //                    account.getName());
386 //        }
387 //        transactionListFragment.setArguments(bundle);
388 //        ft.replace(R.id.root_frame, transactionListFragment);
389 //        if (account != null)
390 //            ft.addToBackStack(getResources().getString(R.string.title_activity_transaction_list));
391 //        ft.commit();
392 //
393 //        currentFragment = transactionListFragment;
394     }
395     public void showAccountTransactions(LedgerAccount account) {
396         showTransactionsFragment(account);
397     }
398     @Override
399     public void onBackPressed() {
400         DrawerLayout drawer = findViewById(R.id.drawer_layout);
401         if (drawer.isDrawerOpen(GravityCompat.START)) {
402             drawer.closeDrawer(GravityCompat.START);
403         }
404         else {
405             Log.d("fragments",
406                     String.format("manager stack: %d", fragmentManager.getBackStackEntryCount()));
407
408             super.onBackPressed();
409         }
410     }
411     public void updateLastUpdateTextFromDB() {
412         {
413             final MobileLedgerProfile profile = Data.profile.get();
414             long last_update =
415                     (profile != null) ? profile.getLongOption(MLDB.OPT_LAST_SCRAPE, 0L) : 0;
416
417             Log.d("transactions", String.format("Last update = %d", last_update));
418             if (last_update == 0) {
419                 Data.lastUpdateDate.set(null);
420             }
421             else {
422                 Data.lastUpdateDate.set(new Date(last_update));
423             }
424         }
425     }
426     public void scheduleTransactionListRetrieval() {
427         if (Data.profile.get() == null) return;
428
429         retrieveTransactionsTask = new RetrieveTransactionsTask(new WeakReference<>(this));
430
431         retrieveTransactionsTask.execute();
432     }
433     public void onStopTransactionRefreshClick(View view) {
434         Log.d("interactive", "Cancelling transactions refresh");
435         if (retrieveTransactionsTask != null) retrieveTransactionsTask.cancel(false);
436         bTransactionListCancelDownload.setEnabled(false);
437     }
438     public void onRetrieveDone(String error) {
439         progressLayout.setVisibility(View.GONE);
440
441         if (error == null) {
442             updateLastUpdateTextFromDB();
443
444             new RefreshDescriptionsTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
445         }
446         else Toast.makeText(this, error, Toast.LENGTH_LONG).show();
447     }
448     public void onRetrieveStart() {
449         bTransactionListCancelDownload.setEnabled(true);
450         progressBar.setIndeterminateTintList(ColorStateList.valueOf(Colors.primary));
451         progressBar.setProgressTintList(ColorStateList.valueOf(Colors.primary));
452         progressBar.setIndeterminate(true);
453         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) progressBar.setProgress(0, false);
454         else progressBar.setProgress(0);
455         progressLayout.setVisibility(View.VISIBLE);
456     }
457     public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
458         if ((progress.getTotal() == RetrieveTransactionsTask.Progress.INDETERMINATE) ||
459             (progress.getTotal() == 0))
460         {
461             progressBar.setIndeterminate(true);
462         }
463         else {
464             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
465                 progressBar.setMin(0);
466             }
467             progressBar.setMax(progress.getTotal());
468             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
469                 progressBar.setProgress(progress.getProgress(), true);
470             }
471             else progressBar.setProgress(progress.getProgress());
472             progressBar.setIndeterminate(false);
473         }
474     }
475     public void fabShouldShow() {
476         MobileLedgerProfile profile = Data.profile.get();
477         if ((profile != null) && profile.isPostingPermitted()) fab.show();
478     }
479     public void navProfilesHeadClicked(View view) {
480         if (profileListExpanded) {
481             collapseProfileList();
482         }
483         else {
484             expandProfileList();
485         }
486     }
487     private void expandProfileList() {
488         profileListExpanded = true;
489
490
491         profileListContainer.setVisibility(View.VISIBLE);
492         profileListContainer.startAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_down));
493         profileListHeadArrow.startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate_180));
494         profileListHeadMore.setVisibility(View.VISIBLE);
495         profileListHeadMore.startAnimation(AnimationUtils.loadAnimation(this, R.anim.fade_in));
496     }
497     private void collapseProfileList() {
498         profileListExpanded = false;
499
500         final Animation animation = AnimationUtils.loadAnimation(this, R.anim.slide_up);
501         animation.setAnimationListener(new Animation.AnimationListener() {
502             @Override
503             public void onAnimationStart(Animation animation) {
504
505             }
506             @Override
507             public void onAnimationEnd(Animation animation) {
508                 profileListContainer.setVisibility(View.GONE);
509             }
510             @Override
511             public void onAnimationRepeat(Animation animation) {
512
513             }
514         });
515         mProfileListAdapter.stopEditingProfiles();
516
517         profileListContainer.startAnimation(animation);
518         profileListHeadArrow.setRotation(0f);
519         profileListHeadArrow
520                 .startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate_180_back));
521         profileListHeadMore.setVisibility(View.GONE);
522     }
523     public void onProfileRowClicked(View v) {
524         Data.setCurrentProfile((MobileLedgerProfile) v.getTag());
525     }
526     public void enableProfileModifications() {
527         profileModificationEnabled = true;
528         ViewGroup profileList = findViewById(R.id.nav_profile_list);
529         for (int i = 0; i < profileList.getChildCount(); i++) {
530             View aRow = profileList.getChildAt(i);
531             aRow.findViewById(R.id.profile_list_edit_button).setVisibility(View.VISIBLE);
532             aRow.findViewById(R.id.profile_list_rearrange_handle).setVisibility(View.VISIBLE);
533         }
534         // FIXME enable rearranging
535
536     }
537     public void disableProfileModifications() {
538         profileModificationEnabled = false;
539         ViewGroup profileList = findViewById(R.id.nav_profile_list);
540         for (int i = 0; i < profileList.getChildCount(); i++) {
541             View aRow = profileList.getChildAt(i);
542             aRow.findViewById(R.id.profile_list_edit_button).setVisibility(View.GONE);
543             aRow.findViewById(R.id.profile_list_rearrange_handle).setVisibility(View.INVISIBLE);
544         }
545         // FIXME disable rearranging
546
547     }
548
549     public class SectionsPagerAdapter extends FragmentPagerAdapter {
550
551         public SectionsPagerAdapter(FragmentManager fm) {
552             super(fm);
553         }
554
555         @Override
556         public Fragment getItem(int position) {
557             Log.d("main", String.format("Switching to fragment %d", position));
558             switch (position) {
559                 case 0:
560                     return new AccountSummaryFragment();
561                 case 1:
562                     return new TransactionListFragment();
563                 default:
564                     throw new IllegalStateException(
565                             String.format("Unexpected fragment index: " + "%d", position));
566             }
567         }
568
569         @Override
570         public int getCount() {
571             return 2;
572         }
573     }
574
575 }