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