]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/MainActivity.java
Stop trying to create app shortcuts on pre 7.1 devices, fixing a crash
[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         setupProfile();
317         onProfileChanged(null);
318
319         updateLastUpdateTextFromDB();
320         Date lastUpdate = Data.lastUpdateDate.get();
321
322         long now = new Date().getTime();
323         if ((lastUpdate == null) || (now > (lastUpdate.getTime() + (24 * 3600 * 1000)))) {
324             if (lastUpdate == null) Log.d("db::", "WEB data never fetched. scheduling a fetch");
325             else Log.d("db",
326                     String.format("WEB data last fetched at %1.3f and now is %1.3f. re-fetching",
327                             lastUpdate.getTime() / 1000f, now / 1000f));
328
329             scheduleTransactionListRetrieval();
330         }
331     }
332     private void createShortcuts() {
333         if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) return;
334
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 }