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