]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/MainActivity.java
03617c5923c8fe9ef1f431bc35c86e13ebc0e2ac
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / ui / activity / MainActivity.java
1 /*
2  * Copyright © 2020 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.SharedPreferences;
22 import android.content.pm.PackageInfo;
23 import android.content.pm.ShortcutInfo;
24 import android.content.pm.ShortcutManager;
25 import android.content.res.ColorStateList;
26 import android.graphics.Color;
27 import android.graphics.drawable.Icon;
28 import android.os.Build;
29 import android.os.Bundle;
30 import android.text.format.DateUtils;
31 import android.util.Log;
32 import android.view.View;
33 import android.view.animation.AnimationUtils;
34 import android.widget.LinearLayout;
35 import android.widget.ProgressBar;
36 import android.widget.TextView;
37
38 import androidx.annotation.NonNull;
39 import androidx.appcompat.app.ActionBarDrawerToggle;
40 import androidx.appcompat.widget.Toolbar;
41 import androidx.core.view.GravityCompat;
42 import androidx.drawerlayout.widget.DrawerLayout;
43 import androidx.fragment.app.Fragment;
44 import androidx.fragment.app.FragmentManager;
45 import androidx.fragment.app.FragmentPagerAdapter;
46 import androidx.lifecycle.ViewModelProvider;
47 import androidx.recyclerview.widget.LinearLayoutManager;
48 import androidx.recyclerview.widget.RecyclerView;
49 import androidx.viewpager.widget.ViewPager;
50
51 import com.google.android.material.floatingactionbutton.FloatingActionButton;
52 import com.google.android.material.snackbar.Snackbar;
53
54 import net.ktnx.mobileledger.R;
55 import net.ktnx.mobileledger.async.RetrieveTransactionsTask;
56 import net.ktnx.mobileledger.model.Data;
57 import net.ktnx.mobileledger.model.MobileLedgerProfile;
58 import net.ktnx.mobileledger.ui.MainModel;
59 import net.ktnx.mobileledger.ui.account_summary.AccountSummaryFragment;
60 import net.ktnx.mobileledger.ui.profiles.ProfileDetailFragment;
61 import net.ktnx.mobileledger.ui.profiles.ProfilesRecyclerViewAdapter;
62 import net.ktnx.mobileledger.ui.transaction_list.TransactionListFragment;
63 import net.ktnx.mobileledger.utils.Colors;
64 import net.ktnx.mobileledger.utils.Logger;
65 import net.ktnx.mobileledger.utils.MLDB;
66
67 import org.jetbrains.annotations.NotNull;
68
69 import java.util.ArrayList;
70 import java.util.Date;
71 import java.util.List;
72 import java.util.Locale;
73 import java.util.Objects;
74
75 /*
76  * TODO: reports
77  *  */
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     private static final String PREF_THEME_ID = "themeId";
84     DrawerLayout drawer;
85     private View profileListHeadMore, profileListHeadCancel, profileListHeadAddProfile;
86     private View bTransactionListCancelDownload;
87     private SectionsPagerAdapter mSectionsPagerAdapter;
88     private ViewPager mViewPager;
89     private FloatingActionButton fab;
90     private ProfilesRecyclerViewAdapter mProfileListAdapter;
91     private int mCurrentPage;
92     private boolean mBackMeansToAccountList = false;
93     private Toolbar mToolbar;
94     private DrawerLayout.SimpleDrawerListener drawerListener;
95     private ActionBarDrawerToggle barDrawerToggle;
96     private ViewPager.SimpleOnPageChangeListener pageChangeListener;
97     private MobileLedgerProfile profile;
98     private MainModel mainModel;
99     @Override
100     protected void onStart() {
101         super.onStart();
102
103         Logger.debug("MainActivity", "onStart()");
104
105         mViewPager.setCurrentItem(mCurrentPage, false);
106     }
107     @Override
108     protected void onSaveInstanceState(@NotNull Bundle outState) {
109         super.onSaveInstanceState(outState);
110         outState.putInt(STATE_CURRENT_PAGE, mViewPager.getCurrentItem());
111         if (mainModel.getAccountFilter()
112                      .getValue() != null)
113             outState.putString(STATE_ACC_FILTER, mainModel.getAccountFilter()
114                                                           .getValue());
115     }
116     @Override
117     protected void onDestroy() {
118         mSectionsPagerAdapter = null;
119         RecyclerView root = findViewById(R.id.nav_profile_list);
120         if (root != null)
121             root.setAdapter(null);
122         if (drawer != null)
123             drawer.removeDrawerListener(drawerListener);
124         drawerListener = null;
125         if (drawer != null)
126             drawer.removeDrawerListener(barDrawerToggle);
127         barDrawerToggle = null;
128         if (mViewPager != null)
129             mViewPager.removeOnPageChangeListener(pageChangeListener);
130         pageChangeListener = null;
131         super.onDestroy();
132     }
133     @Override
134     protected void setupProfileColors() {
135         SharedPreferences prefs = getPreferences(MODE_PRIVATE);
136         int profileColor = prefs.getInt(PREF_THEME_ID, -2);
137         if (profileColor == -2)
138             profileColor = Data.retrieveCurrentThemeIdFromDb();
139         Colors.setupTheme(this, profileColor);
140         Colors.profileThemeId = profileColor;
141         storeThemeIdInPrefs(profileColor);
142     }
143     @Override
144     protected void onResume() {
145         super.onResume();
146         fabShouldShow();
147     }
148     @Override
149     protected void onCreate(Bundle savedInstanceState) {
150         Logger.debug("MainActivity", "onCreate()/entry");
151         super.onCreate(savedInstanceState);
152         Logger.debug("MainActivity", "onCreate()/after super");
153         setContentView(R.layout.activity_main);
154
155         mainModel = new ViewModelProvider(this).get(MainModel.class);
156
157         fab = findViewById(R.id.btn_add_transaction);
158         profileListHeadMore = findViewById(R.id.nav_profiles_start_edit);
159         profileListHeadCancel = findViewById(R.id.nav_profiles_cancel_edit);
160         LinearLayout profileListHeadMoreAndCancel =
161                 findViewById(R.id.nav_profile_list_head_buttons);
162         profileListHeadAddProfile = findViewById(R.id.nav_new_profile_button);
163         drawer = findViewById(R.id.drawer_layout);
164         bTransactionListCancelDownload = findViewById(R.id.transaction_list_cancel_download);
165         mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
166         mViewPager = findViewById(R.id.root_frame);
167
168         Bundle extra = getIntent().getBundleExtra(BUNDLE_SAVED_STATE);
169         if (extra != null && savedInstanceState == null)
170             savedInstanceState = extra;
171
172
173         mToolbar = findViewById(R.id.toolbar);
174         setSupportActionBar(mToolbar);
175
176         Data.observeProfile(this, this::onProfileChanged);
177
178         Data.profiles.observe(this, this::onProfileListChanged);
179         Data.backgroundTaskProgress.observe(this, this::onRetrieveProgress);
180         Data.backgroundTasksRunning.observe(this, this::onRetrieveRunningChanged);
181
182         if (barDrawerToggle == null) {
183             barDrawerToggle = new ActionBarDrawerToggle(this, drawer, mToolbar,
184                     R.string.navigation_drawer_open, R.string.navigation_drawer_close);
185             drawer.addDrawerListener(barDrawerToggle);
186         }
187         barDrawerToggle.syncState();
188
189         try {
190             PackageInfo pi = getApplicationContext().getPackageManager()
191                                                     .getPackageInfo(getPackageName(), 0);
192             ((TextView) findViewById(R.id.nav_upper).findViewById(
193                     R.id.drawer_version_text)).setText(pi.versionName);
194             ((TextView) findViewById(R.id.no_profiles_layout).findViewById(
195                     R.id.drawer_version_text)).setText(pi.versionName);
196         }
197         catch (Exception e) {
198             e.printStackTrace();
199         }
200
201         markDrawerItemCurrent(R.id.nav_account_summary);
202
203         mViewPager.setAdapter(mSectionsPagerAdapter);
204
205         if (pageChangeListener == null) {
206             pageChangeListener = new ViewPager.SimpleOnPageChangeListener() {
207                 @Override
208                 public void onPageSelected(int position) {
209                     mCurrentPage = position;
210                     switch (position) {
211                         case 0:
212                             markDrawerItemCurrent(R.id.nav_account_summary);
213                             break;
214                         case 1:
215                             markDrawerItemCurrent(R.id.nav_latest_transactions);
216                             break;
217                         default:
218                             Log.e("MainActivity",
219                                     String.format("Unexpected page index %d", position));
220                     }
221
222                     super.onPageSelected(position);
223                 }
224             };
225             mViewPager.addOnPageChangeListener(pageChangeListener);
226         }
227
228         mCurrentPage = 0;
229         if (savedInstanceState != null) {
230             int currentPage = savedInstanceState.getInt(STATE_CURRENT_PAGE, -1);
231             if (currentPage != -1) {
232                 mCurrentPage = currentPage;
233             }
234             mainModel.getAccountFilter()
235                      .setValue(savedInstanceState.getString(STATE_ACC_FILTER, null));
236         }
237
238         findViewById(R.id.btn_no_profiles_add).setOnClickListener(
239                 v -> startEditProfileActivity(null));
240
241         findViewById(R.id.btn_add_transaction).setOnClickListener(this::fabNewTransactionClicked);
242
243         findViewById(R.id.nav_new_profile_button).setOnClickListener(
244                 v -> startEditProfileActivity(null));
245
246         RecyclerView root = findViewById(R.id.nav_profile_list);
247         if (root == null)
248             throw new RuntimeException("Can't get hold on the transaction value view");
249
250         if (mProfileListAdapter == null)
251             mProfileListAdapter = new ProfilesRecyclerViewAdapter();
252         root.setAdapter(mProfileListAdapter);
253
254         mProfileListAdapter.editingProfiles.observe(this, newValue -> {
255             if (newValue) {
256                 profileListHeadMore.setVisibility(View.GONE);
257                 profileListHeadCancel.setVisibility(View.VISIBLE);
258                 profileListHeadAddProfile.setVisibility(View.VISIBLE);
259                 if (drawer.isDrawerOpen(GravityCompat.START)) {
260                     profileListHeadMore.startAnimation(
261                             AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_out));
262                     profileListHeadCancel.startAnimation(
263                             AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_in));
264                     profileListHeadAddProfile.startAnimation(
265                             AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_in));
266                 }
267             }
268             else {
269                 profileListHeadCancel.setVisibility(View.GONE);
270                 profileListHeadMore.setVisibility(View.VISIBLE);
271                 profileListHeadAddProfile.setVisibility(View.GONE);
272                 if (drawer.isDrawerOpen(GravityCompat.START)) {
273                     profileListHeadCancel.startAnimation(
274                             AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_out));
275                     profileListHeadMore.startAnimation(
276                             AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_in));
277                     profileListHeadAddProfile.startAnimation(
278                             AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_out));
279                 }
280             }
281
282             mProfileListAdapter.notifyDataSetChanged();
283         });
284
285         LinearLayoutManager llm = new LinearLayoutManager(this);
286
287         llm.setOrientation(RecyclerView.VERTICAL);
288         root.setLayoutManager(llm);
289
290         profileListHeadMore.setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
291         profileListHeadCancel.setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
292         profileListHeadMoreAndCancel.setOnClickListener(
293                 (v) -> mProfileListAdapter.flipEditingProfiles());
294         if (drawerListener == null) {
295             drawerListener = new DrawerLayout.SimpleDrawerListener() {
296                 @Override
297                 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
298                     if (slideOffset > 0.2)
299                         fabHide();
300                 }
301                 @Override
302                 public void onDrawerClosed(View drawerView) {
303                     super.onDrawerClosed(drawerView);
304                     mProfileListAdapter.setAnimationsEnabled(false);
305                     mProfileListAdapter.editingProfiles.setValue(false);
306                     Data.drawerOpen.setValue(false);
307                     fabShouldShow();
308                 }
309                 @Override
310                 public void onDrawerOpened(View drawerView) {
311                     super.onDrawerOpened(drawerView);
312                     mProfileListAdapter.setAnimationsEnabled(true);
313                     Data.drawerOpen.setValue(true);
314                     fabHide();
315                 }
316             };
317             drawer.addDrawerListener(drawerListener);
318         }
319
320         Data.drawerOpen.observe(this, open -> {
321             if (open)
322                 drawer.open();
323             else
324                 drawer.close();
325         });
326
327         mainModel.getUpdateError()
328                  .observe(this, (error) -> {
329                      if (error == null)
330                          return;
331
332                      Snackbar.make(mViewPager, error, Snackbar.LENGTH_LONG)
333                              .show();
334                      mainModel.clearUpdateError();
335                  });
336         Data.locale.observe(this, l -> refreshLastUpdateInfo());
337         Data.lastUpdateDate.observe(this, date -> refreshLastUpdateInfo());
338         Data.lastUpdateTransactionCount.observe(this, date -> refreshLastUpdateInfo());
339     }
340     private void scheduleDataRetrievalIfStale(long lastUpdate) {
341         long now = new Date().getTime();
342         if ((lastUpdate == 0) || (now > (lastUpdate + (24 * 3600 * 1000)))) {
343             if (lastUpdate == 0)
344                 Logger.debug("db::", "WEB data never fetched. scheduling a fetch");
345             else
346                 Logger.debug("db", String.format(Locale.ENGLISH,
347                         "WEB data last fetched at %1.3f and now is %1.3f. re-fetching",
348                         lastUpdate / 1000f, now / 1000f));
349
350             mainModel.scheduleTransactionListRetrieval();
351         }
352     }
353     private void createShortcuts(List<MobileLedgerProfile> list) {
354         if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N_MR1)
355             return;
356
357         ShortcutManager sm = getSystemService(ShortcutManager.class);
358         List<ShortcutInfo> shortcuts = new ArrayList<>();
359         int i = 0;
360         for (MobileLedgerProfile p : list) {
361             if (shortcuts.size() >= sm.getMaxShortcutCountPerActivity())
362                 break;
363
364             if (!p.isPostingPermitted())
365                 continue;
366
367             final ShortcutInfo.Builder builder =
368                     new ShortcutInfo.Builder(this, "new_transaction_" + p.getUuid());
369             ShortcutInfo si = builder.setShortLabel(p.getName())
370                                      .setIcon(Icon.createWithResource(this,
371                                              R.drawable.thick_plus_icon))
372                                      .setIntent(new Intent(Intent.ACTION_VIEW, null, this,
373                                              NewTransactionActivity.class).putExtra("profile_uuid",
374                                              p.getUuid()))
375                                      .setRank(i)
376                                      .build();
377             shortcuts.add(si);
378             i++;
379         }
380         sm.setDynamicShortcuts(shortcuts);
381     }
382     private void onProfileListChanged(List<MobileLedgerProfile> newList) {
383         if ((newList == null) || newList.isEmpty()) {
384             findViewById(R.id.no_profiles_layout).setVisibility(View.VISIBLE);
385             findViewById(R.id.main_app_layout).setVisibility(View.GONE);
386             return;
387         }
388
389         findViewById(R.id.main_app_layout).setVisibility(View.VISIBLE);
390         findViewById(R.id.no_profiles_layout).setVisibility(View.GONE);
391
392         findViewById(R.id.nav_profile_list).setMinimumHeight(
393                 (int) (getResources().getDimension(R.dimen.thumb_row_height) * newList.size()));
394
395         Logger.debug("profiles", "profile list changed");
396         mProfileListAdapter.notifyDataSetChanged();
397
398         createShortcuts(newList);
399     }
400     /**
401      * called when the current profile has changed
402      */
403     private void onProfileChanged(MobileLedgerProfile profile) {
404         if (this.profile == null) {
405             if (profile == null)
406                 return;
407         }
408         else {
409             if (this.profile.equals(profile))
410                 return;
411         }
412
413         boolean haveProfile = profile != null;
414
415         if (haveProfile)
416             setTitle(profile.getName());
417         else
418             setTitle(R.string.app_name);
419
420         mainModel.setProfile(profile);
421
422         this.profile = profile;
423
424         int newProfileTheme = haveProfile ? profile.getThemeHue() : -1;
425         if (newProfileTheme != Colors.profileThemeId) {
426             Logger.debug("profiles",
427                     String.format(Locale.ENGLISH, "profile theme %d → %d", Colors.profileThemeId,
428                             newProfileTheme));
429             Colors.profileThemeId = newProfileTheme;
430             profileThemeChanged();
431             // profileThemeChanged would restart the activity, so no need to reload the
432             // data sets below
433             return;
434         }
435
436         findViewById(R.id.no_profiles_layout).setVisibility(haveProfile ? View.GONE : View.VISIBLE);
437         findViewById(R.id.pager_layout).setVisibility(haveProfile ? View.VISIBLE : View.VISIBLE);
438
439         mProfileListAdapter.notifyDataSetChanged();
440
441         mainModel.clearTransactions();
442
443         if (haveProfile) {
444             mainModel.scheduleAccountListReload();
445             Logger.debug("transactions", "requesting list reload");
446             mainModel.scheduleTransactionListReload();
447
448             if (profile.isPostingPermitted()) {
449                 mToolbar.setSubtitle(null);
450                 fab.show();
451             }
452             else {
453                 mToolbar.setSubtitle(R.string.profile_subtitle_read_only);
454                 fab.hide();
455             }
456         }
457         else {
458             mToolbar.setSubtitle(null);
459             fab.hide();
460         }
461
462         updateLastUpdateTextFromDB();
463     }
464     private void profileThemeChanged() {
465         storeThemeIdInPrefs(profile.getThemeHue());
466
467         // un-hook all observed LiveData
468         Data.removeProfileObservers(this);
469         Data.profiles.removeObservers(this);
470         Data.lastUpdateTransactionCount.removeObservers(this);
471         Data.lastUpdateDate.removeObservers(this);
472
473         recreate();
474     }
475     private void storeThemeIdInPrefs(int themeId) {
476         // store the new theme id in the preferences
477         SharedPreferences prefs = getPreferences(MODE_PRIVATE);
478         SharedPreferences.Editor e = prefs.edit();
479         e.putInt(PREF_THEME_ID, themeId);
480         e.apply();
481     }
482     public void startEditProfileActivity(MobileLedgerProfile profile) {
483         Intent intent = new Intent(this, ProfileDetailActivity.class);
484         Bundle args = new Bundle();
485         if (profile != null) {
486             int index = Data.getProfileIndex(profile);
487             if (index != -1)
488                 intent.putExtra(ProfileDetailFragment.ARG_ITEM_ID, index);
489         }
490         intent.putExtras(args);
491         startActivity(intent, args);
492     }
493     public void fabNewTransactionClicked(View view) {
494         Intent intent = new Intent(this, NewTransactionActivity.class);
495         startActivity(intent);
496         overridePendingTransition(R.anim.slide_in_up, R.anim.dummy);
497     }
498     public void markDrawerItemCurrent(int id) {
499         TextView item = drawer.findViewById(id);
500         item.setBackgroundColor(Colors.tableRowDarkBG);
501
502         LinearLayout actions = drawer.findViewById(R.id.nav_actions);
503         for (int i = 0; i < actions.getChildCount(); i++) {
504             View view = actions.getChildAt(i);
505             if (view.getId() != id) {
506                 view.setBackgroundColor(Color.TRANSPARENT);
507             }
508         }
509     }
510     public void onAccountSummaryClicked(View view) {
511         drawer.closeDrawers();
512
513         showAccountSummaryFragment();
514     }
515     private void showAccountSummaryFragment() {
516         mViewPager.setCurrentItem(0, true);
517         mainModel.getAccountFilter()
518                  .setValue(null);
519     }
520     public void onLatestTransactionsClicked(View view) {
521         drawer.closeDrawers();
522
523         showTransactionsFragment(null);
524     }
525     public void showTransactionsFragment(String accName) {
526         mainModel.getAccountFilter()
527                  .setValue(accName);
528         mViewPager.setCurrentItem(1, true);
529     }
530     public void showAccountTransactions(String accountName) {
531         mBackMeansToAccountList = true;
532         showTransactionsFragment(accountName);
533     }
534     @Override
535     public void onBackPressed() {
536         DrawerLayout drawer = findViewById(R.id.drawer_layout);
537         if (drawer.isDrawerOpen(GravityCompat.START)) {
538             drawer.closeDrawer(GravityCompat.START);
539         }
540         else {
541             if (mBackMeansToAccountList && (mViewPager.getCurrentItem() == 1)) {
542                 mainModel.getAccountFilter()
543                          .setValue(null);
544                 showAccountSummaryFragment();
545                 mBackMeansToAccountList = false;
546             }
547             else {
548                 Logger.debug("fragments", String.format(Locale.ENGLISH, "manager stack: %d",
549                         getSupportFragmentManager().getBackStackEntryCount()));
550
551                 super.onBackPressed();
552             }
553         }
554     }
555     public void updateLastUpdateTextFromDB() {
556         if (profile == null)
557             return;
558
559         long lastUpdate = profile.getLongOption(MLDB.OPT_LAST_SCRAPE, 0L);
560
561         Logger.debug("transactions", String.format(Locale.ENGLISH, "Last update = %d", lastUpdate));
562         if (lastUpdate == 0) {
563             Data.lastUpdateDate.postValue(null);
564         }
565         else {
566             Data.lastUpdateDate.postValue(new Date(lastUpdate));
567         }
568
569         scheduleDataRetrievalIfStale(lastUpdate);
570
571     }
572     private void refreshLastUpdateInfo() {
573         final int formatFlags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR |
574                                 DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_NUMERIC_DATE;
575         String template = getResources().getString(R.string.transaction_count_summary);
576         Integer transactionCount = Data.lastUpdateTransactionCount.getValue();
577         Date lastUpdate = Data.lastUpdateDate.getValue();
578         Data.lastUpdateText.set((lastUpdate == null) ? "----" : String.format(
579                 Objects.requireNonNull(Data.locale.getValue()), template,
580                 (transactionCount == null) ? 0 : transactionCount,
581                 DateUtils.formatDateTime(this, lastUpdate.getTime(), formatFlags)));
582     }
583     public void onStopTransactionRefreshClick(View view) {
584         Logger.debug("interactive", "Cancelling transactions refresh");
585         mainModel.stopTransactionsRetrieval();
586         bTransactionListCancelDownload.setEnabled(false);
587     }
588     public void onRetrieveRunningChanged(Boolean running) {
589         final View progressLayout = findViewById(R.id.transaction_progress_layout);
590         if (running) {
591             ProgressBar progressBar = findViewById(R.id.transaction_list_progress_bar);
592             bTransactionListCancelDownload.setEnabled(true);
593             ColorStateList csl = Colors.getColorStateList();
594             progressBar.setIndeterminateTintList(csl);
595             progressBar.setProgressTintList(csl);
596             progressBar.setIndeterminate(true);
597             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
598                 progressBar.setProgress(0, false);
599             }
600             else {
601                 progressBar.setProgress(0);
602             }
603             progressLayout.setVisibility(View.VISIBLE);
604         }
605         else {
606             progressLayout.setVisibility(View.GONE);
607         }
608     }
609     public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
610         ProgressBar progressBar = findViewById(R.id.transaction_list_progress_bar);
611
612         if (progress.getState() == RetrieveTransactionsTask.ProgressState.FINISHED) {
613             Logger.debug("progress", "Done");
614             findViewById(R.id.transaction_progress_layout).setVisibility(View.GONE);
615
616             mainModel.transactionRetrievalDone();
617
618             if (progress.getError() != null) {
619                 Snackbar.make(mViewPager, progress.getError(), Snackbar.LENGTH_LONG)
620                         .show();
621                 return;
622             }
623
624             return;
625         }
626
627
628         bTransactionListCancelDownload.setEnabled(true);
629 //        ColorStateList csl = Colors.getColorStateList();
630 //        progressBar.setIndeterminateTintList(csl);
631 //        progressBar.setProgressTintList(csl);
632 //        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
633 //            progressBar.setProgress(0, false);
634 //        else
635 //            progressBar.setProgress(0);
636         findViewById(R.id.transaction_progress_layout).setVisibility(View.VISIBLE);
637
638         if (progress.isIndeterminate() || (progress.getTotal() <= 0)) {
639             progressBar.setIndeterminate(true);
640             Logger.debug("progress", "indeterminate");
641         }
642         else {
643             if (progressBar.isIndeterminate()) {
644                 progressBar.setIndeterminate(false);
645             }
646 //            Logger.debug("progress",
647 //                    String.format(Locale.US, "%d/%d", progress.getProgress(), progress.getTotal
648 //                    ()));
649             progressBar.setMax(progress.getTotal());
650             // for some reason animation doesn't work - no progress is shown (stick at 0)
651             // on lineageOS 14.1 (Nougat, 7.1.2)
652             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
653                 progressBar.setProgress(progress.getProgress(), false);
654             else
655                 progressBar.setProgress(progress.getProgress());
656         }
657     }
658     public void fabShouldShow() {
659         if ((profile != null) && profile.isPostingPermitted() && !drawer.isOpen())
660             fab.show();
661         else
662             fabHide();
663     }
664     public void fabHide() {
665         fab.hide();
666     }
667
668     public static class SectionsPagerAdapter extends FragmentPagerAdapter {
669
670         SectionsPagerAdapter(FragmentManager fm) {
671             super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
672         }
673
674         @NotNull
675         @Override
676         public Fragment getItem(int position) {
677             Logger.debug("main",
678                     String.format(Locale.ENGLISH, "Switching to fragment %d", position));
679             switch (position) {
680                 case 0:
681 //                    debug("flow", "Creating account summary fragment");
682                     return new AccountSummaryFragment();
683                 case 1:
684                     return new TransactionListFragment();
685                 default:
686                     throw new IllegalStateException(
687                             String.format("Unexpected fragment index: " + "%d", position));
688             }
689         }
690
691         @Override
692         public int getCount() {
693             return 2;
694         }
695     }
696 }