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