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