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