]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/MainActivity.java
fix first run experience
[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.pm.ShortcutInfo;
23 import android.content.pm.ShortcutManager;
24 import android.content.res.ColorStateList;
25 import android.graphics.Color;
26 import android.graphics.drawable.Icon;
27 import android.os.AsyncTask;
28 import android.os.Build;
29 import android.os.Bundle;
30 import android.util.Log;
31 import android.view.View;
32 import android.view.ViewGroup;
33 import android.view.ViewPropertyAnimator;
34 import android.view.animation.Animation;
35 import android.view.animation.AnimationUtils;
36 import android.widget.LinearLayout;
37 import android.widget.ProgressBar;
38 import android.widget.TextView;
39 import android.widget.Toast;
40
41 import com.google.android.material.floatingactionbutton.FloatingActionButton;
42
43 import net.ktnx.mobileledger.R;
44 import net.ktnx.mobileledger.async.DbOpQueue;
45 import net.ktnx.mobileledger.async.RefreshDescriptionsTask;
46 import net.ktnx.mobileledger.async.RetrieveTransactionsTask;
47 import net.ktnx.mobileledger.model.Data;
48 import net.ktnx.mobileledger.model.LedgerAccount;
49 import net.ktnx.mobileledger.model.MobileLedgerProfile;
50 import net.ktnx.mobileledger.ui.account_summary.AccountSummaryAdapter;
51 import net.ktnx.mobileledger.ui.account_summary.AccountSummaryFragment;
52 import net.ktnx.mobileledger.ui.account_summary.AccountSummaryViewModel;
53 import net.ktnx.mobileledger.ui.profiles.ProfileDetailFragment;
54 import net.ktnx.mobileledger.ui.profiles.ProfilesRecyclerViewAdapter;
55 import net.ktnx.mobileledger.ui.transaction_list.TransactionListFragment;
56 import net.ktnx.mobileledger.ui.transaction_list.TransactionListViewModel;
57 import net.ktnx.mobileledger.utils.Colors;
58 import net.ktnx.mobileledger.utils.LockHolder;
59 import net.ktnx.mobileledger.utils.MLDB;
60
61 import java.lang.ref.WeakReference;
62 import java.text.DateFormat;
63 import java.util.ArrayList;
64 import java.util.Date;
65 import java.util.List;
66 import java.util.Observer;
67
68 import androidx.appcompat.app.ActionBarDrawerToggle;
69 import androidx.appcompat.widget.Toolbar;
70 import androidx.core.view.GravityCompat;
71 import androidx.drawerlayout.widget.DrawerLayout;
72 import androidx.fragment.app.Fragment;
73 import androidx.fragment.app.FragmentManager;
74 import androidx.fragment.app.FragmentPagerAdapter;
75 import androidx.recyclerview.widget.LinearLayoutManager;
76 import androidx.recyclerview.widget.RecyclerView;
77 import androidx.viewpager.widget.ViewPager;
78
79 public class MainActivity extends ProfileThemedActivity {
80     public static final String STATE_CURRENT_PAGE = "current_page";
81     public static final String BUNDLE_SAVED_STATE = "bundle_savedState";
82     public static final String STATE_ACC_FILTER = "account_filter";
83     public AccountSummaryFragment mAccountSummaryFragment;
84     DrawerLayout drawer;
85     private LinearLayout profileListContainer;
86     private View profileListHeadArrow, profileListHeadMore, profileListHeadCancel;
87     private LinearLayout profileListHeadMoreAndCancel;
88     private FragmentManager fragmentManager;
89     private TextView tvLastUpdate;
90     private RetrieveTransactionsTask retrieveTransactionsTask;
91     private View bTransactionListCancelDownload;
92     private ProgressBar progressBar;
93     private LinearLayout progressLayout;
94     private SectionsPagerAdapter mSectionsPagerAdapter;
95     private ViewPager mViewPager;
96     private FloatingActionButton fab;
97     private boolean profileModificationEnabled = false;
98     private boolean profileListExpanded = false;
99     private ProfilesRecyclerViewAdapter mProfileListAdapter;
100     private int mCurrentPage;
101     private String mAccountFilter;
102     private boolean mBackMeansToAccountList = false;
103     private Observer profileObserver;
104     private Observer profilesObserver;
105     private Observer lastUpdateDateObserver;
106     private Toolbar mToolbar;
107     private DrawerLayout.SimpleDrawerListener drawerListener;
108     private ActionBarDrawerToggle barDrawerToggle;
109     private ViewPager.SimpleOnPageChangeListener pageChangeListener;
110     private Observer editingProfilesObserver;
111     @Override
112     protected void onStart() {
113         super.onStart();
114
115         Log.d("flow", "MainActivity.onStart()");
116         mViewPager.setCurrentItem(mCurrentPage, false);
117         if (mAccountFilter != null) showTransactionsFragment(mAccountFilter);
118         else Data.accountFilter.set(null);
119
120     }
121     @Override
122     protected void onSaveInstanceState(Bundle outState) {
123         super.onSaveInstanceState(outState);
124         outState.putInt(STATE_CURRENT_PAGE, mViewPager.getCurrentItem());
125         if (Data.accountFilter.get() != null)
126             outState.putString(STATE_ACC_FILTER, Data.accountFilter.get());
127     }
128     @Override
129     protected void onDestroy() {
130         mSectionsPagerAdapter = null;
131         Data.profile.deleteObserver(profileObserver);
132         profileObserver = null;
133         Data.profiles.deleteObserver(profilesObserver);
134         profilesObserver = null;
135         Data.lastUpdateDate.deleteObserver(lastUpdateDateObserver);
136         lastUpdateDateObserver = null;
137         RecyclerView root = findViewById(R.id.nav_profile_list);
138         if (root != null) root.setAdapter(null);
139         if (drawer != null) drawer.removeDrawerListener(drawerListener);
140         drawerListener = null;
141         if (drawer != null) drawer.removeDrawerListener(barDrawerToggle);
142         barDrawerToggle = null;
143         if (mViewPager != null) mViewPager.removeOnPageChangeListener(pageChangeListener);
144         pageChangeListener = null;
145         if (mProfileListAdapter != null)
146             mProfileListAdapter.deleteEditingProfilesObserver(editingProfilesObserver);
147         editingProfilesObserver = null;
148         super.onDestroy();
149     }
150     @Override
151     protected void onCreate(Bundle savedInstanceState) {
152         super.onCreate(savedInstanceState);
153         Log.d("flow", "MainActivity.onCreate()");
154         int profileColor = Data.retrieveCurrentThemeIdFromDb();
155         Colors.setupTheme(this, profileColor);
156         Colors.profileThemeId = profileColor;
157         setContentView(R.layout.activity_main);
158
159         fab = findViewById(R.id.btn_add_transaction);
160         profileListContainer = findViewById(R.id.nav_profile_list_container);
161         profileListHeadArrow = findViewById(R.id.nav_profiles_arrow);
162         profileListHeadMore = findViewById(R.id.nav_profiles_start_edit);
163         profileListHeadCancel = findViewById(R.id.nav_profiles_cancel_edit);
164         profileListHeadMoreAndCancel = findViewById(R.id.nav_profile_list_head_buttons);
165         drawer = findViewById(R.id.drawer_layout);
166         tvLastUpdate = findViewById(R.id.transactions_last_update);
167         bTransactionListCancelDownload = findViewById(R.id.transaction_list_cancel_download);
168         progressBar = findViewById(R.id.transaction_list_progress_bar);
169         progressLayout = findViewById(R.id.transaction_progress_layout);
170         fragmentManager = getSupportFragmentManager();
171         mSectionsPagerAdapter = new SectionsPagerAdapter(fragmentManager);
172         mViewPager = findViewById(R.id.root_frame);
173
174         Bundle extra = getIntent().getBundleExtra(BUNDLE_SAVED_STATE);
175         if (extra != null && savedInstanceState == null) savedInstanceState = extra;
176
177
178         mToolbar = findViewById(R.id.toolbar);
179         setSupportActionBar(mToolbar);
180
181         if (profileObserver == null) {
182             profileObserver = (o, arg) -> onProfileChanged(arg);
183             Data.profile.addObserver(profileObserver);
184         }
185
186         if (profilesObserver == null) {
187             profilesObserver = (o, arg) -> onProfileListChanged(arg);
188             Data.profiles.addObserver(profilesObserver);
189         }
190
191         if (barDrawerToggle == null) {
192             barDrawerToggle = new ActionBarDrawerToggle(this, drawer, mToolbar,
193                     R.string.navigation_drawer_open, R.string.navigation_drawer_close);
194             drawer.addDrawerListener(barDrawerToggle);
195         }
196         barDrawerToggle.syncState();
197
198         TextView ver = drawer.findViewById(R.id.drawer_version_text);
199
200         try {
201             PackageInfo pi =
202                     getApplicationContext().getPackageManager().getPackageInfo(getPackageName(), 0);
203             ver.setText(pi.versionName);
204         }
205         catch (Exception e) {
206             e.printStackTrace();
207         }
208
209         if (progressBar == null)
210             throw new RuntimeException("Can't get hold on the transaction value progress bar");
211         if (progressLayout == null) throw new RuntimeException(
212                 "Can't get hold on the transaction value progress bar layout");
213
214         markDrawerItemCurrent(R.id.nav_account_summary);
215
216         mViewPager.setAdapter(mSectionsPagerAdapter);
217
218         if (pageChangeListener == null) {
219             pageChangeListener = new ViewPager.SimpleOnPageChangeListener() {
220                 @Override
221                 public void onPageSelected(int position) {
222                     switch (position) {
223                         case 0:
224                             markDrawerItemCurrent(R.id.nav_account_summary);
225                             break;
226                         case 1:
227                             markDrawerItemCurrent(R.id.nav_latest_transactions);
228                             break;
229                         default:
230                             Log.e("MainActivity",
231                                     String.format("Unexpected page index %d", position));
232                     }
233
234                     super.onPageSelected(position);
235                 }
236             };
237             mViewPager.addOnPageChangeListener(pageChangeListener);
238         }
239
240         mCurrentPage = 0;
241         if (savedInstanceState != null) {
242             int currentPage = savedInstanceState.getInt(STATE_CURRENT_PAGE, -1);
243             if (currentPage != -1) {
244                 mCurrentPage = currentPage;
245             }
246             mAccountFilter = savedInstanceState.getString(STATE_ACC_FILTER, null);
247         }
248         else mAccountFilter = null;
249
250         if (lastUpdateDateObserver == null) {
251             lastUpdateDateObserver = (o, arg) -> {
252                 Log.d("main", "lastUpdateDate changed");
253                 runOnUiThread(this::updateLastUpdateDisplay);
254             };
255             Data.lastUpdateDate.addObserver(lastUpdateDateObserver);
256         }
257
258         updateLastUpdateDisplay();
259
260         findViewById(R.id.btn_no_profiles_add)
261                 .setOnClickListener(v -> startEditProfileActivity(null));
262
263         findViewById(R.id.btn_add_transaction).setOnClickListener(this::fabNewTransactionClicked);
264
265         findViewById(R.id.nav_new_profile_button)
266                 .setOnClickListener(v -> startEditProfileActivity(null));
267
268         RecyclerView root = findViewById(R.id.nav_profile_list);
269         if (root == null)
270             throw new RuntimeException("Can't get hold on the transaction value view");
271
272         if (mProfileListAdapter == null) mProfileListAdapter = new ProfilesRecyclerViewAdapter();
273         root.setAdapter(mProfileListAdapter);
274
275         if (editingProfilesObserver == null) {
276             editingProfilesObserver = (o, arg) -> {
277                 if (mProfileListAdapter.isEditingProfiles()) {
278                     profileListHeadArrow.clearAnimation();
279                     profileListHeadArrow.setVisibility(View.GONE);
280                     profileListHeadMore.setVisibility(View.GONE);
281                     profileListHeadCancel.setVisibility(View.VISIBLE);
282                 }
283                 else {
284                     profileListHeadArrow.setRotation(180f);
285                     profileListHeadArrow.setVisibility(View.VISIBLE);
286                     profileListHeadCancel.setVisibility(View.GONE);
287                     profileListHeadMore.setVisibility(View.GONE);
288                     profileListHeadMore.setVisibility(profileListExpanded ? View.VISIBLE : View.GONE);
289                 }
290             };
291             mProfileListAdapter.addEditingProfilesObserver(editingProfilesObserver);
292         }
293
294         LinearLayoutManager llm = new LinearLayoutManager(this);
295
296         llm.setOrientation(RecyclerView.VERTICAL);
297         root.setLayoutManager(llm);
298
299         profileListHeadMore.setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
300         profileListHeadCancel.setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
301         profileListHeadMoreAndCancel
302                 .setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
303
304         if (drawerListener == null) {
305             drawerListener = new DrawerLayout.SimpleDrawerListener() {
306                 @Override
307                 public void onDrawerClosed(View drawerView) {
308                     super.onDrawerClosed(drawerView);
309                     collapseProfileList();
310                 }
311             };
312             drawer.addDrawerListener(drawerListener);
313         }
314
315         findViewById(R.id.nav_profile_list_head_layout)
316                 .setOnClickListener(this::navProfilesHeadClicked);
317         findViewById(R.id.nav_profiles_label).setOnClickListener(this::navProfilesHeadClicked);
318         setupProfile();
319         onProfileChanged(null);
320
321         updateLastUpdateTextFromDB();
322
323         scheduleDataRetrievalIfStale();
324     }
325     private void scheduleDataRetrievalIfStale() {
326         Date lastUpdate = Data.lastUpdateDate.get();
327         long now = new Date().getTime();
328         if ((lastUpdate == null) || (now > (lastUpdate.getTime() + (24 * 3600 * 1000)))) {
329             if (lastUpdate == null) Log.d("db::", "WEB data never fetched. scheduling a fetch");
330             else Log.d("db",
331                     String.format("WEB data last fetched at %1.3f and now is %1.3f. re-fetching",
332                             lastUpdate.getTime() / 1000f, now / 1000f));
333
334             scheduleTransactionListRetrieval();
335         }
336     }
337     private void createShortcuts() {
338         if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) return;
339
340         List<ShortcutInfo> shortcuts = new ArrayList<>();
341         try (LockHolder lh = Data.profiles.lockForReading()) {
342             for (int i = 0; i < Data.profiles.size(); i++) {
343                 MobileLedgerProfile p = Data.profiles.get(i);
344                 if (!p.isPostingPermitted()) continue;
345
346                 ShortcutInfo si = new ShortcutInfo.Builder(this, "new_transaction_" + p.getUuid())
347                         .setShortLabel(p.getName())
348                         .setIcon(Icon.createWithResource(this, R.drawable.svg_thick_plus_white))
349                         .setIntent(new Intent(Intent.ACTION_VIEW, null, this,
350                                 NewTransactionActivity.class).putExtra("profile_uuid", p.getUuid()))
351                         .setRank(i).build();
352                 shortcuts.add(si);
353             }
354         }
355         ShortcutManager sm = getSystemService(ShortcutManager.class);
356         sm.setDynamicShortcuts(shortcuts);
357     }
358     private void onProfileListChanged(Object arg) {
359         findViewById(R.id.nav_profile_list).setMinimumHeight(
360                 (int) (getResources().getDimension(R.dimen.thumb_row_height) *
361                        Data.profiles.size()));
362
363         Log.d("profiles", "profile list changed");
364         if (arg == null) mProfileListAdapter.notifyDataSetChanged();
365         else mProfileListAdapter.notifyItemChanged((int) arg);
366
367         createShortcuts();
368     }
369     private void onProfileChanged(Object arg) {
370         MobileLedgerProfile profile = Data.profile.get();
371         MainActivity.this.runOnUiThread(() -> {
372
373             boolean haveProfile = profile != null;
374             findViewById(R.id.no_profiles_layout).setVisibility(haveProfile ? View.GONE : View.VISIBLE);
375             findViewById(R.id.pager_layout)
376                     .setVisibility(haveProfile ? View.VISIBLE : View.VISIBLE);
377
378             Data.transactions.clear();
379             Log.d("transactions", "requesting list reload");
380             TransactionListViewModel.scheduleTransactionListReload();
381
382             Data.accounts.clear();
383             AccountSummaryViewModel.scheduleAccountListReload();
384
385             if (profile == null) MainActivity.this.setTitle(R.string.app_name);
386             else MainActivity.this.setTitle(profile.getName());
387             MainActivity.this.updateLastUpdateTextFromDB();
388             int old_index = -1;
389             int new_index = -1;
390             if (arg != null) {
391                 MobileLedgerProfile old = (MobileLedgerProfile) arg;
392                 old_index = Data.getProfileIndex(old);
393                 new_index = Data.getProfileIndex(profile);
394             }
395
396             if ((old_index != -1) && (new_index != -1)) {
397                 mProfileListAdapter.notifyItemChanged(old_index);
398                 mProfileListAdapter.notifyItemChanged(new_index);
399             }
400             else mProfileListAdapter.notifyDataSetChanged();
401
402             MainActivity.this.collapseProfileList();
403
404             int newProfileTheme = (profile == null) ? -1 : profile.getThemeId();
405             if (newProfileTheme != Colors.profileThemeId) {
406                 Log.d("profiles", String.format("profile theme %d → %d", Colors.profileThemeId,
407                         newProfileTheme));
408                 MainActivity.this.profileThemeChanged();
409                 Colors.profileThemeId = newProfileTheme;
410                 // profileThemeChanged would restart the activity, so no need to reload the
411                 // data sets below
412                 return;
413             }
414             drawer.closeDrawers();
415
416             if (profile == null) {
417                 mToolbar.setSubtitle(null);
418                 fab.hide();
419             }
420             else {
421                 if (profile.isPostingPermitted()) {
422                     mToolbar.setSubtitle(null);
423                     fab.show();
424                 }
425                 else {
426                     mToolbar.setSubtitle(R.string.profile_subitlte_read_only);
427                     fab.hide();
428                 }
429             }
430
431             updateLastUpdateTextFromDB();
432
433             scheduleDataRetrievalIfStale();
434         });
435     }
436     private void updateLastUpdateDisplay() {
437         LinearLayout l = findViewById(R.id.transactions_last_update_layout);
438         TextView v = findViewById(R.id.transactions_last_update);
439         Date date = Data.lastUpdateDate.get();
440         if (date == null) {
441             l.setVisibility(View.INVISIBLE);
442             Log.d("main", "no last update date :(");
443         }
444         else {
445             final String text = DateFormat.getDateTimeInstance().format(date);
446             v.setText(text);
447             l.setVisibility(View.VISIBLE);
448             Log.d("main", String.format("Date formatted: %s", text));
449         }
450     }
451     @Override
452     public void finish() {
453         if (profilesObserver != null) {
454             Data.profiles.deleteObserver(profilesObserver);
455             profilesObserver = null;
456         }
457
458         if (profileObserver != null) {
459             Data.profile.deleteObserver(profileObserver);
460             profileObserver = null;
461         }
462
463         super.finish();
464     }
465     private void profileThemeChanged() {
466         setupProfileColors();
467
468         Bundle bundle = new Bundle();
469         onSaveInstanceState(bundle);
470         // restart activity to reflect theme change
471         finish();
472         Intent intent = new Intent(this, this.getClass());
473         intent.putExtra(BUNDLE_SAVED_STATE, bundle);
474         startActivity(intent);
475     }
476     public void startEditProfileActivity(MobileLedgerProfile profile) {
477         Intent intent = new Intent(this, ProfileDetailActivity.class);
478         Bundle args = new Bundle();
479         if (profile != null) {
480             int index = Data.getProfileIndex(profile);
481             if (index != -1) intent.putExtra(ProfileDetailFragment.ARG_ITEM_ID, index);
482         }
483         intent.putExtras(args);
484         startActivity(intent, args);
485     }
486     private void setupProfile() {
487         String profileUUID = MLDB.getOption(MLDB.OPT_PROFILE_UUID, null);
488         MobileLedgerProfile profile;
489
490         profile = Data.getProfile(profileUUID);
491
492         if (Data.profiles.isEmpty()) {
493             findViewById(R.id.no_profiles_layout).setVisibility(View.VISIBLE);
494             findViewById(R.id.pager_layout).setVisibility(View.GONE);
495             return;
496         }
497
498         findViewById(R.id.pager_layout).setVisibility(View.VISIBLE);
499         findViewById(R.id.no_profiles_layout).setVisibility(View.GONE);
500
501         if (profile == null) profile = Data.profiles.get(0);
502
503         if (profile == null) throw new AssertionError("profile must have a value");
504
505         Data.setCurrentProfile(profile);
506     }
507     public void fabNewTransactionClicked(View view) {
508         Intent intent = new Intent(this, NewTransactionActivity.class);
509         startActivity(intent);
510         overridePendingTransition(R.anim.slide_in_right, R.anim.dummy);
511     }
512     public void navSettingsClicked(View view) {
513         Intent intent = new Intent(this, SettingsActivity.class);
514         startActivity(intent);
515         drawer.closeDrawers();
516     }
517     public void markDrawerItemCurrent(int id) {
518         TextView item = drawer.findViewById(id);
519         item.setBackgroundColor(Colors.tableRowDarkBG);
520
521         LinearLayout actions = drawer.findViewById(R.id.nav_actions);
522         for (int i = 0; i < actions.getChildCount(); i++) {
523             View view = actions.getChildAt(i);
524             if (view.getId() != id) {
525                 view.setBackgroundColor(Color.TRANSPARENT);
526             }
527         }
528     }
529     public void onAccountSummaryClicked(View view) {
530         drawer.closeDrawers();
531
532         showAccountSummaryFragment();
533     }
534     private void showAccountSummaryFragment() {
535         mViewPager.setCurrentItem(0, true);
536         Data.accountFilter.set(null);
537 //        FragmentTransaction ft = fragmentManager.beginTransaction();
538 //        accountSummaryFragment = new AccountSummaryFragment();
539 //        ft.replace(R.id.root_frame, accountSummaryFragment);
540 //        ft.commit();
541 //        currentFragment = accountSummaryFragment;
542     }
543     public void onLatestTransactionsClicked(View view) {
544         drawer.closeDrawers();
545
546         showTransactionsFragment((String) null);
547     }
548     private void resetFragmentBackStack() {
549 //        fragmentManager.popBackStack(0, FragmentManager.POP_BACK_STACK_INCLUSIVE);
550     }
551     private void showTransactionsFragment(String accName) {
552         Data.accountFilter.set(accName);
553         Data.accountFilter.notifyObservers();
554         mViewPager.setCurrentItem(1, true);
555     }
556     private void showTransactionsFragment(LedgerAccount account) {
557         showTransactionsFragment((account == null) ? (String) null : account.getName());
558 //        FragmentTransaction ft = fragmentManager.beginTransaction();
559 //        if (transactionListFragment == null) {
560 //            Log.d("flow", "MainActivity creating TransactionListFragment");
561 //            transactionListFragment = new TransactionListFragment();
562 //        }
563 //        Bundle bundle = new Bundle();
564 //        if (account != null) {
565 //            bundle.putString(TransactionListFragment.BUNDLE_KEY_FILTER_ACCOUNT_NAME,
566 //                    account.getName());
567 //        }
568 //        transactionListFragment.setArguments(bundle);
569 //        ft.replace(R.id.root_frame, transactionListFragment);
570 //        if (account != null)
571 //            ft.addToBackStack(getResources().getString(R.string.title_activity_transaction_list));
572 //        ft.commit();
573 //
574 //        currentFragment = transactionListFragment;
575     }
576     public void showAccountTransactions(LedgerAccount account) {
577         mBackMeansToAccountList = true;
578         showTransactionsFragment(account);
579     }
580     @Override
581     public void onBackPressed() {
582         DrawerLayout drawer = findViewById(R.id.drawer_layout);
583         if (drawer.isDrawerOpen(GravityCompat.START)) {
584             drawer.closeDrawer(GravityCompat.START);
585         }
586         else {
587             if (mBackMeansToAccountList && (mViewPager.getCurrentItem() == 1)) {
588                 Data.accountFilter.set(null);
589                 showAccountSummaryFragment();
590                 mBackMeansToAccountList = false;
591             }
592             else {
593                 Log.d("fragments", String.format("manager stack: %d",
594                         fragmentManager.getBackStackEntryCount()));
595
596                 super.onBackPressed();
597             }
598         }
599     }
600     public void updateLastUpdateTextFromDB() {
601         {
602             final MobileLedgerProfile profile = Data.profile.get();
603             long last_update =
604                     (profile != null) ? profile.getLongOption(MLDB.OPT_LAST_SCRAPE, 0L) : 0;
605
606             Log.d("transactions", String.format("Last update = %d", last_update));
607             if (last_update == 0) {
608                 Data.lastUpdateDate.set(null);
609             }
610             else {
611                 Data.lastUpdateDate.set(new Date(last_update));
612             }
613         }
614     }
615     public void scheduleTransactionListRetrieval() {
616         if (Data.profile.get() == null) return;
617
618         retrieveTransactionsTask = new RetrieveTransactionsTask(new WeakReference<>(this));
619
620         retrieveTransactionsTask.execute();
621     }
622     public void onStopTransactionRefreshClick(View view) {
623         Log.d("interactive", "Cancelling transactions refresh");
624         if (retrieveTransactionsTask != null) retrieveTransactionsTask.cancel(false);
625         bTransactionListCancelDownload.setEnabled(false);
626     }
627     public void onRetrieveDone(String error) {
628         progressLayout.setVisibility(View.GONE);
629
630         if (error == null) {
631             updateLastUpdateTextFromDB();
632
633             new RefreshDescriptionsTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
634             TransactionListViewModel.scheduleTransactionListReload();
635         }
636         else Toast.makeText(this, error, Toast.LENGTH_LONG).show();
637     }
638     public void onRetrieveStart() {
639         bTransactionListCancelDownload.setEnabled(true);
640         progressBar.setIndeterminateTintList(ColorStateList.valueOf(Colors.primary));
641         progressBar.setProgressTintList(ColorStateList.valueOf(Colors.primary));
642         progressBar.setIndeterminate(true);
643         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) progressBar.setProgress(0, false);
644         else progressBar.setProgress(0);
645         progressLayout.setVisibility(View.VISIBLE);
646     }
647     public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
648         if ((progress.getTotal() == RetrieveTransactionsTask.Progress.INDETERMINATE) ||
649             (progress.getTotal() == 0))
650         {
651             progressBar.setIndeterminate(true);
652         }
653         else {
654             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
655                 progressBar.setMin(0);
656             }
657             progressBar.setMax(progress.getTotal());
658             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
659                 progressBar.setProgress(progress.getProgress(), true);
660             }
661             else progressBar.setProgress(progress.getProgress());
662             progressBar.setIndeterminate(false);
663         }
664     }
665     public void fabShouldShow() {
666         MobileLedgerProfile profile = Data.profile.get();
667         if ((profile != null) && profile.isPostingPermitted()) fab.show();
668     }
669     public void navProfilesHeadClicked(View view) {
670         if (profileListExpanded) {
671             collapseProfileList();
672         }
673         else {
674             expandProfileList();
675         }
676     }
677     private void expandProfileList() {
678         profileListExpanded = true;
679
680
681         profileListContainer.setVisibility(View.VISIBLE);
682         profileListContainer.startAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_down));
683         profileListHeadArrow.startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate_180));
684         profileListHeadMore.setVisibility(View.VISIBLE);
685         profileListHeadMore.startAnimation(AnimationUtils.loadAnimation(this, R.anim.fade_in));
686         findViewById(R.id.nav_profile_list).setMinimumHeight(
687                 (int) (getResources().getDimension(R.dimen.thumb_row_height) *
688                        Data.profiles.size()));
689     }
690     private void collapseProfileList() {
691         profileListExpanded = false;
692
693         final Animation animation = AnimationUtils.loadAnimation(this, R.anim.slide_up);
694         animation.setAnimationListener(new Animation.AnimationListener() {
695             @Override
696             public void onAnimationStart(Animation animation) {
697
698             }
699             @Override
700             public void onAnimationEnd(Animation animation) {
701                 profileListContainer.setVisibility(View.GONE);
702             }
703             @Override
704             public void onAnimationRepeat(Animation animation) {
705
706             }
707         });
708         mProfileListAdapter.stopEditingProfiles();
709
710         profileListContainer.startAnimation(animation);
711         profileListHeadArrow.setRotation(0f);
712         profileListHeadArrow
713                 .startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate_180_back));
714         profileListHeadMore.setVisibility(View.GONE);
715     }
716     public void onProfileRowClicked(View v) {
717         Data.setCurrentProfile((MobileLedgerProfile) v.getTag());
718     }
719     public void enableProfileModifications() {
720         profileModificationEnabled = true;
721         ViewGroup profileList = findViewById(R.id.nav_profile_list);
722         for (int i = 0; i < profileList.getChildCount(); i++) {
723             View aRow = profileList.getChildAt(i);
724             aRow.findViewById(R.id.profile_list_edit_button).setVisibility(View.VISIBLE);
725             aRow.findViewById(R.id.profile_list_rearrange_handle).setVisibility(View.VISIBLE);
726         }
727         // FIXME enable rearranging
728
729     }
730     public void disableProfileModifications() {
731         profileModificationEnabled = false;
732         ViewGroup profileList = findViewById(R.id.nav_profile_list);
733         for (int i = 0; i < profileList.getChildCount(); i++) {
734             View aRow = profileList.getChildAt(i);
735             aRow.findViewById(R.id.profile_list_edit_button).setVisibility(View.GONE);
736             aRow.findViewById(R.id.profile_list_rearrange_handle).setVisibility(View.INVISIBLE);
737         }
738         // FIXME disable rearranging
739
740     }
741     public void onAccountSummaryRowViewClicked(View view) {
742         ViewGroup row;
743         if (view.getId() == R.id.account_expander) row = (ViewGroup) view.getParent().getParent();
744         else row = (ViewGroup) view.getParent();
745
746         LedgerAccount acc = (LedgerAccount) row.getTag();
747         switch (view.getId()) {
748             case R.id.account_row_acc_name:
749             case R.id.account_expander:
750             case R.id.account_expander_container:
751                 Log.d("accounts", "Account expander clicked");
752                 if (!acc.hasSubAccounts()) return;
753
754                 boolean wasExpanded = acc.isExpanded();
755
756                 View arrow = row.findViewById(R.id.account_expander_container);
757
758                 arrow.clearAnimation();
759                 ViewPropertyAnimator animator = arrow.animate();
760
761                 acc.toggleExpanded();
762                 DbOpQueue.add("update accounts set expanded=? where name=? and profile=?",
763                         new Object[]{acc.isExpanded(), acc.getName(), Data.profile.get().getUuid()
764                         });
765
766                 if (wasExpanded) {
767                     Log.d("accounts", String.format("Collapsing account '%s'", acc.getName()));
768                     arrow.setRotation(0);
769                     animator.rotationBy(180);
770
771                     // removing all child accounts from the view
772                     int start = -1, count = 0;
773                     try (LockHolder lh = Data.accounts.lockForWriting()) {
774                         for (int i = 0; i < Data.accounts.size(); i++) {
775                             if (acc.isParentOf(Data.accounts.get(i))) {
776 //                                Log.d("accounts", String.format("Found a child '%s' at position %d",
777 //                                        Data.accounts.get(i).getName(), i));
778                                 if (start == -1) {
779                                     start = i;
780                                 }
781                                 count++;
782                             }
783                             else {
784                                 if (start != -1) {
785 //                                    Log.d("accounts",
786 //                                            String.format("Found a non-child '%s' at position %d",
787 //                                                    Data.accounts.get(i).getName(), i));
788                                     break;
789                                 }
790                             }
791                         }
792
793                         if (start != -1) {
794                             for (int j = 0; j < count; j++) {
795 //                                Log.d("accounts", String.format("Removing item %d: %s", start + j,
796 //                                        Data.accounts.get(start).getName()));
797                                 Data.accounts.removeQuietly(start);
798                             }
799
800                             mAccountSummaryFragment.modelAdapter
801                                     .notifyItemRangeRemoved(start, count);
802                         }
803                     }
804                 }
805                 else {
806                     Log.d("accounts", String.format("Expanding account '%s'", acc.getName()));
807                     arrow.setRotation(180);
808                     animator.rotationBy(-180);
809                     List<LedgerAccount> children =
810                             Data.profile.get().loadVisibleChildAccountsOf(acc);
811                     try (LockHolder lh = Data.accounts.lockForWriting()) {
812                         int parentPos = Data.accounts.indexOf(acc);
813                         if (parentPos != -1) {
814                             // may have disappeared in a concurrent refresh operation
815                             Data.accounts.addAllQuietly(parentPos + 1, children);
816                             mAccountSummaryFragment.modelAdapter
817                                     .notifyItemRangeInserted(parentPos + 1, children.size());
818                         }
819                     }
820                 }
821                 break;
822             case R.id.account_row_acc_amounts:
823                 if (acc.getAmountCount() > AccountSummaryAdapter.AMOUNT_LIMIT) {
824                     acc.toggleAmountsExpanded();
825                     DbOpQueue
826                             .add("update accounts set amounts_expanded=? where name=? and profile=?",
827                                     new Object[]{acc.amountsExpanded(), acc.getName(),
828                                                  Data.profile.get().getUuid()
829                                     });
830                     Data.accounts.triggerItemChangedNotification(acc);
831                 }
832                 break;
833         }
834     }
835
836     public class SectionsPagerAdapter extends FragmentPagerAdapter {
837
838         public SectionsPagerAdapter(FragmentManager fm) {
839             super(fm);
840         }
841
842         @Override
843         public Fragment getItem(int position) {
844             Log.d("main", String.format("Switching to fragment %d", position));
845             switch (position) {
846                 case 0:
847 //                    Log.d("flow", "Creating account summary fragment");
848                     return mAccountSummaryFragment = new AccountSummaryFragment();
849                 case 1:
850                     return new TransactionListFragment();
851                 default:
852                     throw new IllegalStateException(
853                             String.format("Unexpected fragment index: " + "%d", position));
854             }
855         }
856
857         @Override
858         public int getCount() {
859             return 2;
860         }
861     }
862 }