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