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.
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.
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/>.
18 package net.ktnx.mobileledger.ui.activity;
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.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.animation.AnimationUtils;
34 import android.widget.LinearLayout;
35 import android.widget.ProgressBar;
36 import android.widget.TextView;
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.recyclerview.widget.LinearLayoutManager;
47 import androidx.recyclerview.widget.RecyclerView;
48 import androidx.viewpager.widget.ViewPager;
50 import com.google.android.material.floatingactionbutton.FloatingActionButton;
51 import com.google.android.material.snackbar.Snackbar;
53 import net.ktnx.mobileledger.R;
54 import net.ktnx.mobileledger.async.RefreshDescriptionsTask;
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.account_summary.AccountSummaryFragment;
59 import net.ktnx.mobileledger.ui.profiles.ProfileDetailFragment;
60 import net.ktnx.mobileledger.ui.profiles.ProfilesRecyclerViewAdapter;
61 import net.ktnx.mobileledger.ui.transaction_list.TransactionListFragment;
62 import net.ktnx.mobileledger.ui.transaction_list.TransactionListViewModel;
63 import net.ktnx.mobileledger.utils.Colors;
64 import net.ktnx.mobileledger.utils.Logger;
65 import net.ktnx.mobileledger.utils.MLDB;
67 import org.jetbrains.annotations.NotNull;
69 import java.text.DateFormat;
70 import java.util.ArrayList;
71 import java.util.Date;
72 import java.util.List;
73 import java.util.Locale;
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";
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;
99 protected void onStart() {
102 Logger.debug("MainActivity", "onStart()");
104 mViewPager.setCurrentItem(mCurrentPage, false);
107 protected void onSaveInstanceState(@NotNull Bundle outState) {
108 super.onSaveInstanceState(outState);
109 outState.putInt(STATE_CURRENT_PAGE, mViewPager.getCurrentItem());
110 if (Data.accountFilter.getValue() != null)
111 outState.putString(STATE_ACC_FILTER, Data.accountFilter.getValue());
114 protected void onDestroy() {
115 mSectionsPagerAdapter = null;
116 RecyclerView root = findViewById(R.id.nav_profile_list);
118 root.setAdapter(null);
120 drawer.removeDrawerListener(drawerListener);
121 drawerListener = null;
123 drawer.removeDrawerListener(barDrawerToggle);
124 barDrawerToggle = null;
125 if (mViewPager != null)
126 mViewPager.removeOnPageChangeListener(pageChangeListener);
127 pageChangeListener = null;
131 protected void setupProfileColors() {
132 SharedPreferences prefs = getPreferences(MODE_PRIVATE);
133 int profileColor = prefs.getInt(PREF_THEME_ID, -2);
134 if (profileColor == -2)
135 profileColor = Data.retrieveCurrentThemeIdFromDb();
136 Colors.setupTheme(this, profileColor);
137 Colors.profileThemeId = profileColor;
138 storeThemeIdInPrefs(profileColor);
141 protected void onResume() {
146 protected void onCreate(Bundle savedInstanceState) {
147 Logger.debug("MainActivity", "onCreate()/entry");
148 super.onCreate(savedInstanceState);
149 Logger.debug("MainActivity", "onCreate()/after super");
150 setContentView(R.layout.activity_main);
152 fab = findViewById(R.id.btn_add_transaction);
153 profileListHeadMore = findViewById(R.id.nav_profiles_start_edit);
154 profileListHeadCancel = findViewById(R.id.nav_profiles_cancel_edit);
155 LinearLayout profileListHeadMoreAndCancel =
156 findViewById(R.id.nav_profile_list_head_buttons);
157 profileListHeadAddProfile = findViewById(R.id.nav_new_profile_button);
158 drawer = findViewById(R.id.drawer_layout);
159 bTransactionListCancelDownload = findViewById(R.id.transaction_list_cancel_download);
160 mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
161 mViewPager = findViewById(R.id.root_frame);
163 Bundle extra = getIntent().getBundleExtra(BUNDLE_SAVED_STATE);
164 if (extra != null && savedInstanceState == null)
165 savedInstanceState = extra;
168 mToolbar = findViewById(R.id.toolbar);
169 setSupportActionBar(mToolbar);
171 Data.observeProfile(this, this::onProfileChanged);
173 Data.profiles.observe(this, this::onProfileListChanged);
174 Data.backgroundTaskProgress.observe(this, this::onRetrieveProgress);
175 Data.backgroundTasksRunning.observe(this, this::onRetrieveRunningChanged);
177 if (barDrawerToggle == null) {
178 barDrawerToggle = new ActionBarDrawerToggle(this, drawer, mToolbar,
179 R.string.navigation_drawer_open, R.string.navigation_drawer_close);
180 drawer.addDrawerListener(barDrawerToggle);
182 barDrawerToggle.syncState();
185 PackageInfo pi = getApplicationContext().getPackageManager()
186 .getPackageInfo(getPackageName(), 0);
187 ((TextView) findViewById(R.id.nav_upper).findViewById(
188 R.id.drawer_version_text)).setText(pi.versionName);
189 ((TextView) findViewById(R.id.no_profiles_layout).findViewById(
190 R.id.drawer_version_text)).setText(pi.versionName);
192 catch (Exception e) {
196 markDrawerItemCurrent(R.id.nav_account_summary);
198 mViewPager.setAdapter(mSectionsPagerAdapter);
200 if (pageChangeListener == null) {
201 pageChangeListener = new ViewPager.SimpleOnPageChangeListener() {
203 public void onPageSelected(int position) {
204 mCurrentPage = position;
207 markDrawerItemCurrent(R.id.nav_account_summary);
210 markDrawerItemCurrent(R.id.nav_latest_transactions);
213 Log.e("MainActivity",
214 String.format("Unexpected page index %d", position));
217 super.onPageSelected(position);
220 mViewPager.addOnPageChangeListener(pageChangeListener);
224 if (savedInstanceState != null) {
225 int currentPage = savedInstanceState.getInt(STATE_CURRENT_PAGE, -1);
226 if (currentPage != -1) {
227 mCurrentPage = currentPage;
229 Data.accountFilter.setValue(savedInstanceState.getString(STATE_ACC_FILTER, null));
232 Data.lastUpdateDate.observe(this, this::updateLastUpdateDisplay);
234 findViewById(R.id.btn_no_profiles_add).setOnClickListener(
235 v -> startEditProfileActivity(null));
237 findViewById(R.id.btn_add_transaction).setOnClickListener(this::fabNewTransactionClicked);
239 findViewById(R.id.nav_new_profile_button).setOnClickListener(
240 v -> startEditProfileActivity(null));
242 RecyclerView root = findViewById(R.id.nav_profile_list);
244 throw new RuntimeException("Can't get hold on the transaction value view");
246 if (mProfileListAdapter == null)
247 mProfileListAdapter = new ProfilesRecyclerViewAdapter();
248 root.setAdapter(mProfileListAdapter);
250 mProfileListAdapter.editingProfiles.observe(this, newValue -> {
252 profileListHeadMore.setVisibility(View.GONE);
253 profileListHeadCancel.setVisibility(View.VISIBLE);
254 profileListHeadAddProfile.setVisibility(View.VISIBLE);
255 if (drawer.isDrawerOpen(GravityCompat.START)) {
256 profileListHeadMore.startAnimation(
257 AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_out));
258 profileListHeadCancel.startAnimation(
259 AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_in));
260 profileListHeadAddProfile.startAnimation(
261 AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_in));
265 profileListHeadCancel.setVisibility(View.GONE);
266 profileListHeadMore.setVisibility(View.VISIBLE);
267 profileListHeadAddProfile.setVisibility(View.GONE);
268 if (drawer.isDrawerOpen(GravityCompat.START)) {
269 profileListHeadCancel.startAnimation(
270 AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_out));
271 profileListHeadMore.startAnimation(
272 AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_in));
273 profileListHeadAddProfile.startAnimation(
274 AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_out));
278 mProfileListAdapter.notifyDataSetChanged();
281 LinearLayoutManager llm = new LinearLayoutManager(this);
283 llm.setOrientation(RecyclerView.VERTICAL);
284 root.setLayoutManager(llm);
286 profileListHeadMore.setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
287 profileListHeadCancel.setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
288 profileListHeadMoreAndCancel.setOnClickListener(
289 (v) -> mProfileListAdapter.flipEditingProfiles());
290 if (drawerListener == null) {
291 drawerListener = new DrawerLayout.SimpleDrawerListener() {
293 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
294 if (slideOffset > 0.2)
298 public void onDrawerClosed(View drawerView) {
299 super.onDrawerClosed(drawerView);
300 mProfileListAdapter.setAnimationsEnabled(false);
301 mProfileListAdapter.editingProfiles.setValue(false);
302 Data.drawerOpen.setValue(false);
306 public void onDrawerOpened(View drawerView) {
307 super.onDrawerOpened(drawerView);
308 mProfileListAdapter.setAnimationsEnabled(true);
309 Data.drawerOpen.setValue(true);
313 drawer.addDrawerListener(drawerListener);
316 Data.drawerOpen.observe(this, open -> {
323 private void scheduleDataRetrievalIfStale(Date lastUpdate) {
324 long now = new Date().getTime();
325 if ((lastUpdate == null) || (now > (lastUpdate.getTime() + (24 * 3600 * 1000)))) {
326 if (lastUpdate == null)
327 Logger.debug("db::", "WEB data never fetched. scheduling a fetch");
329 Logger.debug("db", String.format(Locale.ENGLISH,
330 "WEB data last fetched at %1.3f and now is %1.3f. re-fetching",
331 lastUpdate.getTime() / 1000f, now / 1000f));
333 scheduleDataRetrieval();
336 public void scheduleDataRetrieval() {
337 Data.scheduleTransactionListRetrieval();
339 private void createShortcuts(List<MobileLedgerProfile> list) {
340 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N_MR1)
343 ShortcutManager sm = getSystemService(ShortcutManager.class);
344 List<ShortcutInfo> shortcuts = new ArrayList<>();
346 for (MobileLedgerProfile p : list) {
347 if (shortcuts.size() >= sm.getMaxShortcutCountPerActivity())
350 if (!p.isPostingPermitted())
353 final ShortcutInfo.Builder builder =
354 new ShortcutInfo.Builder(this, "new_transaction_" + p.getUuid());
355 ShortcutInfo si = builder.setShortLabel(p.getName())
356 .setIcon(Icon.createWithResource(this,
357 R.drawable.thick_plus_icon))
358 .setIntent(new Intent(Intent.ACTION_VIEW, null, this,
359 NewTransactionActivity.class).putExtra("profile_uuid",
366 sm.setDynamicShortcuts(shortcuts);
368 private void onProfileListChanged(List<MobileLedgerProfile> newList) {
369 if ((newList == null) || newList.isEmpty()) {
370 findViewById(R.id.no_profiles_layout).setVisibility(View.VISIBLE);
371 findViewById(R.id.main_app_layout).setVisibility(View.GONE);
375 findViewById(R.id.main_app_layout).setVisibility(View.VISIBLE);
376 findViewById(R.id.no_profiles_layout).setVisibility(View.GONE);
378 findViewById(R.id.nav_profile_list).setMinimumHeight(
379 (int) (getResources().getDimension(R.dimen.thumb_row_height) * newList.size()));
381 Logger.debug("profiles", "profile list changed");
382 mProfileListAdapter.notifyDataSetChanged();
384 createShortcuts(newList);
387 * called when the current profile has changed
389 private void onProfileChanged(MobileLedgerProfile profile) {
390 if (this.profile == null) {
395 if (this.profile.equals(profile))
399 boolean haveProfile = profile != null;
402 setTitle(profile.getName());
404 setTitle(R.string.app_name);
406 if (this.profile != null)
407 this.profile.getDisplayedAccounts()
408 .removeObservers(this);
410 this.profile = profile;
412 int newProfileTheme = haveProfile ? profile.getThemeHue() : -1;
413 if (newProfileTheme != Colors.profileThemeId) {
414 Logger.debug("profiles",
415 String.format(Locale.ENGLISH, "profile theme %d → %d", Colors.profileThemeId,
417 Colors.profileThemeId = newProfileTheme;
418 profileThemeChanged();
419 // profileThemeChanged would restart the activity, so no need to reload the
424 findViewById(R.id.no_profiles_layout).setVisibility(haveProfile ? View.GONE : View.VISIBLE);
425 findViewById(R.id.pager_layout).setVisibility(haveProfile ? View.VISIBLE : View.VISIBLE);
427 mProfileListAdapter.notifyDataSetChanged();
429 Data.transactions.clear();
430 Logger.debug("transactions", "requesting list reload");
431 TransactionListViewModel.scheduleTransactionListReload();
434 profile.scheduleAccountListReload();
436 if (profile.isPostingPermitted()) {
437 mToolbar.setSubtitle(null);
441 mToolbar.setSubtitle(R.string.profile_subtitle_read_only);
446 mToolbar.setSubtitle(null);
450 updateLastUpdateTextFromDB();
452 private void updateLastUpdateDisplay(Date newValue) {
453 LinearLayout l = findViewById(R.id.transactions_last_update_layout);
454 TextView v = findViewById(R.id.transactions_last_update);
455 if (newValue == null) {
456 l.setVisibility(View.INVISIBLE);
457 Logger.debug("main", "no last update date :(");
460 final String text = DateFormat.getDateTimeInstance()
463 l.setVisibility(View.VISIBLE);
464 Logger.debug("main", String.format("Date formatted: %s", text));
467 scheduleDataRetrievalIfStale(newValue);
469 private void profileThemeChanged() {
470 storeThemeIdInPrefs(profile.getThemeHue());
472 // un-hook all observed LiveData
473 Data.removeProfileObservers(this);
474 Data.profiles.removeObservers(this);
475 Data.lastUpdateDate.removeObservers(this);
479 private void storeThemeIdInPrefs(int themeId) {
480 // store the new theme id in the preferences
481 SharedPreferences prefs = getPreferences(MODE_PRIVATE);
482 SharedPreferences.Editor e = prefs.edit();
483 e.putInt(PREF_THEME_ID, themeId);
486 public void startEditProfileActivity(MobileLedgerProfile profile) {
487 Intent intent = new Intent(this, ProfileDetailActivity.class);
488 Bundle args = new Bundle();
489 if (profile != null) {
490 int index = Data.getProfileIndex(profile);
492 intent.putExtra(ProfileDetailFragment.ARG_ITEM_ID, index);
494 intent.putExtras(args);
495 startActivity(intent, args);
497 public void fabNewTransactionClicked(View view) {
498 Intent intent = new Intent(this, NewTransactionActivity.class);
499 startActivity(intent);
500 overridePendingTransition(R.anim.slide_in_up, R.anim.dummy);
502 public void markDrawerItemCurrent(int id) {
503 TextView item = drawer.findViewById(id);
504 item.setBackgroundColor(Colors.tableRowDarkBG);
506 LinearLayout actions = drawer.findViewById(R.id.nav_actions);
507 for (int i = 0; i < actions.getChildCount(); i++) {
508 View view = actions.getChildAt(i);
509 if (view.getId() != id) {
510 view.setBackgroundColor(Color.TRANSPARENT);
514 public void onAccountSummaryClicked(View view) {
515 drawer.closeDrawers();
517 showAccountSummaryFragment();
519 private void showAccountSummaryFragment() {
520 mViewPager.setCurrentItem(0, true);
521 Data.accountFilter.setValue(null);
523 public void onLatestTransactionsClicked(View view) {
524 drawer.closeDrawers();
526 showTransactionsFragment(null);
528 public void showTransactionsFragment(String accName) {
529 Data.accountFilter.setValue(accName);
530 mViewPager.setCurrentItem(1, true);
532 public void showAccountTransactions(String accountName) {
533 mBackMeansToAccountList = true;
534 showTransactionsFragment(accountName);
537 public void onBackPressed() {
538 DrawerLayout drawer = findViewById(R.id.drawer_layout);
539 if (drawer.isDrawerOpen(GravityCompat.START)) {
540 drawer.closeDrawer(GravityCompat.START);
543 if (mBackMeansToAccountList && (mViewPager.getCurrentItem() == 1)) {
544 Data.accountFilter.setValue(null);
545 showAccountSummaryFragment();
546 mBackMeansToAccountList = false;
549 Logger.debug("fragments", String.format(Locale.ENGLISH, "manager stack: %d",
550 getSupportFragmentManager().getBackStackEntryCount()));
552 super.onBackPressed();
556 public void updateLastUpdateTextFromDB() {
560 long last_update = profile.getLongOption(MLDB.OPT_LAST_SCRAPE, 0L);
562 Logger.debug("transactions", String.format(Locale.ENGLISH, "Last update = %d", last_update));
563 if (last_update == 0) {
564 Data.lastUpdateDate.postValue(null);
567 Data.lastUpdateDate.postValue(new Date(last_update));
570 public void onStopTransactionRefreshClick(View view) {
571 Logger.debug("interactive", "Cancelling transactions refresh");
572 Data.stopTransactionsRetrieval();
573 bTransactionListCancelDownload.setEnabled(false);
575 public void onRetrieveRunningChanged(Boolean running) {
576 final View progressLayout = findViewById(R.id.transaction_progress_layout);
578 ProgressBar progressBar = findViewById(R.id.transaction_list_progress_bar);
579 bTransactionListCancelDownload.setEnabled(true);
580 ColorStateList csl = Colors.getColorStateList();
581 progressBar.setIndeterminateTintList(csl);
582 progressBar.setProgressTintList(csl);
583 progressBar.setIndeterminate(true);
584 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
585 progressBar.setProgress(0, false);
588 progressBar.setProgress(0);
590 progressLayout.setVisibility(View.VISIBLE);
593 progressLayout.setVisibility(View.GONE);
596 public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
597 ProgressBar progressBar = findViewById(R.id.transaction_list_progress_bar);
599 if (progress.getState() == RetrieveTransactionsTask.ProgressState.FINISHED) {
600 Logger.debug("progress", "Done");
601 findViewById(R.id.transaction_progress_layout).setVisibility(View.GONE);
603 Data.transactionRetrievalDone();
605 if (progress.getError() != null) {
606 Snackbar.make(mViewPager, progress.getError(), Snackbar.LENGTH_LONG)
611 updateLastUpdateTextFromDB();
613 new RefreshDescriptionsTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
614 TransactionListViewModel.scheduleTransactionListReload();
620 bTransactionListCancelDownload.setEnabled(true);
621 // ColorStateList csl = Colors.getColorStateList();
622 // progressBar.setIndeterminateTintList(csl);
623 // progressBar.setProgressTintList(csl);
624 // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
625 // progressBar.setProgress(0, false);
627 // progressBar.setProgress(0);
628 findViewById(R.id.transaction_progress_layout).setVisibility(View.VISIBLE);
630 if (progress.isIndeterminate() || (progress.getTotal() <= 0)) {
631 progressBar.setIndeterminate(true);
632 Logger.debug("progress", "indeterminate");
635 if (progressBar.isIndeterminate()) {
636 progressBar.setIndeterminate(false);
638 Logger.debug("progress",
639 String.format(Locale.US, "%d/%d", progress.getProgress(), progress.getTotal()));
640 progressBar.setMax(progress.getTotal());
641 // for some reason animation doesn't work - no progress is shown (stick at 0)
642 // on lineageOS 14.1 (Nougat, 7.1.2)
643 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
644 progressBar.setProgress(progress.getProgress(), false);
646 progressBar.setProgress(progress.getProgress());
649 public void fabShouldShow() {
650 if ((profile != null) && profile.isPostingPermitted() && !drawer.isOpen())
655 public void fabHide() {
659 public static class SectionsPagerAdapter extends FragmentPagerAdapter {
661 SectionsPagerAdapter(FragmentManager fm) {
662 super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
667 public Fragment getItem(int position) {
668 Logger.debug("main", String.format(Locale.ENGLISH, "Switching to fragment %d", position));
671 // debug("flow", "Creating account summary fragment");
672 return new AccountSummaryFragment();
674 return new TransactionListFragment();
676 throw new IllegalStateException(
677 String.format("Unexpected fragment index: " + "%d", position));
682 public int getCount() {