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