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