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.
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.pm.PackageInfo;
22 import android.content.res.ColorStateList;
23 import android.graphics.Color;
24 import android.os.AsyncTask;
25 import android.os.Build;
26 import android.os.Bundle;
27 import android.util.Log;
28 import android.view.View;
29 import android.view.ViewGroup;
30 import android.view.animation.Animation;
31 import android.view.animation.AnimationUtils;
32 import android.widget.LinearLayout;
33 import android.widget.ProgressBar;
34 import android.widget.TextView;
35 import android.widget.Toast;
37 import com.google.android.material.floatingactionbutton.FloatingActionButton;
39 import net.ktnx.mobileledger.R;
40 import net.ktnx.mobileledger.async.RefreshDescriptionsTask;
41 import net.ktnx.mobileledger.async.RetrieveTransactionsTask;
42 import net.ktnx.mobileledger.model.Data;
43 import net.ktnx.mobileledger.model.LedgerAccount;
44 import net.ktnx.mobileledger.model.MobileLedgerProfile;
45 import net.ktnx.mobileledger.ui.account_summary.AccountSummaryFragment;
46 import net.ktnx.mobileledger.ui.profiles.ProfileDetailFragment;
47 import net.ktnx.mobileledger.ui.profiles.ProfilesRecyclerViewAdapter;
48 import net.ktnx.mobileledger.ui.transaction_list.TransactionListFragment;
49 import net.ktnx.mobileledger.utils.Colors;
50 import net.ktnx.mobileledger.utils.MLDB;
52 import java.lang.ref.WeakReference;
53 import java.text.DateFormat;
54 import java.util.Date;
55 import java.util.Observable;
56 import java.util.Observer;
58 import androidx.appcompat.app.ActionBarDrawerToggle;
59 import androidx.appcompat.widget.Toolbar;
60 import androidx.core.view.GravityCompat;
61 import androidx.drawerlayout.widget.DrawerLayout;
62 import androidx.fragment.app.Fragment;
63 import androidx.fragment.app.FragmentManager;
64 import androidx.fragment.app.FragmentPagerAdapter;
65 import androidx.recyclerview.widget.LinearLayoutManager;
66 import androidx.recyclerview.widget.RecyclerView;
67 import androidx.viewpager.widget.ViewPager;
69 public class MainActivity extends CrashReportingActivity {
70 private static final String STATE_CURRENT_PAGE = "current_page";
71 private static final String BUNDLE_SAVED_STATE = "bundle_savedState";
73 private LinearLayout profileListContainer;
74 private View profileListHeadArrow, profileListHeadMore, profileListHeadCancel;
75 private FragmentManager fragmentManager;
76 private TextView tvLastUpdate;
77 private RetrieveTransactionsTask retrieveTransactionsTask;
78 private View bTransactionListCancelDownload;
79 private ProgressBar progressBar;
80 private LinearLayout progressLayout;
81 private SectionsPagerAdapter mSectionsPagerAdapter;
82 private ViewPager mViewPager;
83 private FloatingActionButton fab;
84 private boolean profileModificationEnabled = false;
85 private boolean profileListExpanded = false;
86 private ProfilesRecyclerViewAdapter mProfileListAdapter;
89 protected void onStart() {
92 Data.lastUpdateDate.set(null);
93 updateLastUpdateTextFromDB();
94 Date lastUpdate = Data.lastUpdateDate.get();
96 long now = new Date().getTime();
97 if ((lastUpdate == null) || (now > (lastUpdate.getTime() + (24 * 3600 * 1000)))) {
98 if (lastUpdate == null) Log.d("db::", "WEB data never fetched. scheduling a fetch");
100 String.format("WEB data last fetched at %1.3f and now is %1.3f. re-fetching",
101 lastUpdate.getTime() / 1000f, now / 1000f));
103 scheduleTransactionListRetrieval();
107 protected void onSaveInstanceState(Bundle outState) {
108 super.onSaveInstanceState(outState);
109 outState.putInt(STATE_CURRENT_PAGE, mViewPager.getCurrentItem());
112 protected void onCreate(Bundle savedInstanceState) {
113 super.onCreate(savedInstanceState);
115 setContentView(R.layout.activity_main);
117 fab = findViewById(R.id.btn_add_transaction);
118 profileListContainer = findViewById(R.id.nav_profile_list_container);
119 profileListHeadArrow = findViewById(R.id.nav_profiles_arrow);
120 profileListHeadMore = findViewById(R.id.nav_profiles_start_edit);
121 profileListHeadCancel = findViewById(R.id.nav_profiles_cancel_edit);
122 drawer = findViewById(R.id.drawer_layout);
123 tvLastUpdate = findViewById(R.id.transactions_last_update);
124 bTransactionListCancelDownload = findViewById(R.id.transaction_list_cancel_download);
125 progressBar = findViewById(R.id.transaction_list_progress_bar);
126 progressLayout = findViewById(R.id.transaction_progress_layout);
127 fragmentManager = getSupportFragmentManager();
128 mSectionsPagerAdapter = new SectionsPagerAdapter(fragmentManager);
129 mViewPager = findViewById(R.id.root_frame);
131 Bundle extra = getIntent().getBundleExtra(BUNDLE_SAVED_STATE);
132 if (extra != null && savedInstanceState == null) savedInstanceState = extra;
135 Toolbar toolbar = findViewById(R.id.toolbar);
136 setSupportActionBar(toolbar);
138 Data.profile.addObserver((o, arg) -> {
139 MobileLedgerProfile profile = Data.profile.get();
140 runOnUiThread(() -> {
141 if (profile == null) setTitle(R.string.app_name);
142 else setTitle(profile.getName());
143 updateLastUpdateTextFromDB();
144 if (profile.isPostingPermitted()) {
145 toolbar.setSubtitle(null);
149 toolbar.setSubtitle(R.string.profile_subitlte_read_only);
153 int newProfileTheme = profile.getThemeId();
154 if (newProfileTheme != Colors.profileThemeId) {
155 Log.d("profiles", String.format("profile theme %d → %d", Colors.profileThemeId,
157 profileThemeChanged();
158 Colors.profileThemeId = newProfileTheme;
163 ActionBarDrawerToggle toggle =
164 new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open,
165 R.string.navigation_drawer_close);
166 drawer.addDrawerListener(toggle);
169 TextView ver = drawer.findViewById(R.id.drawer_version_text);
173 getApplicationContext().getPackageManager().getPackageInfo(getPackageName(), 0);
174 ver.setText(pi.versionName);
176 catch (Exception e) {
180 if (progressBar == null)
181 throw new RuntimeException("Can't get hold on the transaction value progress bar");
182 if (progressLayout == null) throw new RuntimeException(
183 "Can't get hold on the transaction value progress bar layout");
185 markDrawerItemCurrent(R.id.nav_account_summary);
187 mViewPager.setAdapter(mSectionsPagerAdapter);
188 mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
190 public void onPageSelected(int position) {
193 markDrawerItemCurrent(R.id.nav_account_summary);
196 markDrawerItemCurrent(R.id.nav_latest_transactions);
199 Log.e("MainActivity", String.format("Unexpected page index %d", position));
202 super.onPageSelected(position);
206 if (savedInstanceState != null) {
207 int currentPage = savedInstanceState.getInt(STATE_CURRENT_PAGE, -1);
208 if (currentPage != -1) {
209 mViewPager.setCurrentItem(currentPage, false);
213 Data.lastUpdateDate.addObserver((o, arg) -> {
214 Log.d("main", "lastUpdateDate changed");
215 runOnUiThread(() -> {
216 Date date = Data.lastUpdateDate.get();
218 tvLastUpdate.setText(R.string.transaction_last_update_never);
221 final String text = DateFormat.getDateTimeInstance().format(date);
222 tvLastUpdate.setText(text);
223 Log.d("despair", String.format("Date formatted: %s", text));
228 findViewById(R.id.btn_no_profiles_add)
229 .setOnClickListener(v -> startEditProfileActivity(null));
231 findViewById(R.id.btn_add_transaction).setOnClickListener(this::fabNewTransactionClicked);
233 findViewById(R.id.nav_new_profile_button)
234 .setOnClickListener(v -> startEditProfileActivity(null));
236 RecyclerView root = findViewById(R.id.nav_profile_list);
238 throw new RuntimeException("Can't get hold on the transaction value view");
240 mProfileListAdapter = new ProfilesRecyclerViewAdapter();
241 root.setAdapter(mProfileListAdapter);
243 mProfileListAdapter.addEditingProfilesObserver(new Observer() {
245 public void update(Observable o, Object arg) {
246 if (mProfileListAdapter.isEditingProfiles()) {
247 profileListHeadArrow.clearAnimation();
248 profileListHeadArrow.setVisibility(View.GONE);
249 profileListHeadMore.setVisibility(View.GONE);
250 // findViewById(R.id.nav_profiles_arrow).setAlpha(0f);
251 profileListHeadCancel.setVisibility(View.VISIBLE);
254 profileListHeadArrow.setVisibility(View.VISIBLE);
255 // findViewById(R.id.nav_profiles_arrow).setAlpha(1f);
256 profileListHeadCancel.setVisibility(View.GONE);
257 profileListHeadMore.setVisibility(View.GONE);
259 .setVisibility(profileListExpanded ? View.VISIBLE : View.GONE);
264 LinearLayoutManager llm = new LinearLayoutManager(this);
266 llm.setOrientation(RecyclerView.VERTICAL);
267 root.setLayoutManager(llm);
269 profileListHeadMore.setOnClickListener((v) -> mProfileListAdapter.startEditingProfiles());
270 profileListHeadCancel.setOnClickListener((v) -> mProfileListAdapter.stopEditingProfiles());
272 drawer.addDrawerListener(new DrawerLayout.SimpleDrawerListener() {
274 public void onDrawerClosed(View drawerView) {
275 super.onDrawerClosed(drawerView);
276 collapseProfileList();
280 private void profileThemeChanged() {
281 setupProfileColors();
283 Bundle bundle = new Bundle();
284 onSaveInstanceState(bundle);
285 // restart activity to reflect theme change
287 Intent intent = new Intent(this, this.getClass());
288 intent.putExtra(BUNDLE_SAVED_STATE, bundle);
289 startActivity(intent);
292 protected void onResume() {
296 public void startEditProfileActivity(MobileLedgerProfile profile) {
297 Intent intent = new Intent(this, ProfileDetailActivity.class);
298 Bundle args = new Bundle();
299 if (profile != null) {
300 int index = Data.getProfileIndex(profile);
301 if (index != -1) intent.putExtra(ProfileDetailFragment.ARG_ITEM_ID, index);
303 intent.putExtras(args);
304 startActivity(intent, args);
306 private void setupProfile() {
307 String profileUUID = MLDB.getOption(MLDB.OPT_PROFILE_UUID, null);
308 MobileLedgerProfile profile;
310 profile = MobileLedgerProfile.loadAllFromDB(profileUUID);
312 if (Data.profiles.getList().isEmpty()) {
313 findViewById(R.id.no_profiles_layout).setVisibility(View.VISIBLE);
314 findViewById(R.id.pager_layout).setVisibility(View.GONE);
318 findViewById(R.id.pager_layout).setVisibility(View.VISIBLE);
319 findViewById(R.id.no_profiles_layout).setVisibility(View.GONE);
321 if (profile == null) profile = Data.profiles.get(0);
323 if (profile == null) throw new AssertionError("profile must have a value");
325 Data.setCurrentProfile(profile);
327 public void fabNewTransactionClicked(View view) {
328 Intent intent = new Intent(this, NewTransactionActivity.class);
329 startActivity(intent);
330 overridePendingTransition(R.anim.slide_in_right, R.anim.dummy);
332 public void navSettingsClicked(View view) {
333 Intent intent = new Intent(this, SettingsActivity.class);
334 startActivity(intent);
335 drawer.closeDrawers();
337 public void markDrawerItemCurrent(int id) {
338 TextView item = drawer.findViewById(id);
339 item.setBackgroundColor(Colors.tableRowDarkBG);
341 LinearLayout actions = drawer.findViewById(R.id.nav_actions);
342 for (int i = 0; i < actions.getChildCount(); i++) {
343 View view = actions.getChildAt(i);
344 if (view.getId() != id) {
345 view.setBackgroundColor(Color.TRANSPARENT);
349 public void onAccountSummaryClicked(View view) {
350 drawer.closeDrawers();
352 showAccountSummaryFragment();
354 private void showAccountSummaryFragment() {
355 mViewPager.setCurrentItem(0, true);
356 TransactionListFragment.accountFilter.set(null);
357 // FragmentTransaction ft = fragmentManager.beginTransaction();
358 // accountSummaryFragment = new AccountSummaryFragment();
359 // ft.replace(R.id.root_frame, accountSummaryFragment);
361 // currentFragment = accountSummaryFragment;
363 public void onLatestTransactionsClicked(View view) {
364 drawer.closeDrawers();
366 showTransactionsFragment(null);
368 private void resetFragmentBackStack() {
369 // fragmentManager.popBackStack(0, FragmentManager.POP_BACK_STACK_INCLUSIVE);
371 private void showTransactionsFragment(LedgerAccount account) {
372 if (account != null) TransactionListFragment.accountFilter.set(account.getName());
373 mViewPager.setCurrentItem(1, true);
374 // FragmentTransaction ft = fragmentManager.beginTransaction();
375 // if (transactionListFragment == null) {
376 // Log.d("flow", "MainActivity creating TransactionListFragment");
377 // transactionListFragment = new TransactionListFragment();
379 // Bundle bundle = new Bundle();
380 // if (account != null) {
381 // bundle.putString(TransactionListFragment.BUNDLE_KEY_FILTER_ACCOUNT_NAME,
382 // account.getName());
384 // transactionListFragment.setArguments(bundle);
385 // ft.replace(R.id.root_frame, transactionListFragment);
386 // if (account != null)
387 // ft.addToBackStack(getResources().getString(R.string.title_activity_transaction_list));
390 // currentFragment = transactionListFragment;
392 public void showAccountTransactions(LedgerAccount account) {
393 showTransactionsFragment(account);
396 public void onBackPressed() {
397 DrawerLayout drawer = findViewById(R.id.drawer_layout);
398 if (drawer.isDrawerOpen(GravityCompat.START)) {
399 drawer.closeDrawer(GravityCompat.START);
403 String.format("manager stack: %d", fragmentManager.getBackStackEntryCount()));
405 super.onBackPressed();
408 public void updateLastUpdateTextFromDB() {
410 final MobileLedgerProfile profile = Data.profile.get();
412 (profile != null) ? profile.getLongOption(MLDB.OPT_LAST_SCRAPE, 0L) : 0;
414 Log.d("transactions", String.format("Last update = %d", last_update));
415 if (last_update == 0) {
416 Data.lastUpdateDate.set(null);
419 Data.lastUpdateDate.set(new Date(last_update));
423 public void scheduleTransactionListRetrieval() {
424 if (Data.profile.get() == null) return;
426 retrieveTransactionsTask = new RetrieveTransactionsTask(new WeakReference<>(this));
428 retrieveTransactionsTask.execute();
430 public void onStopTransactionRefreshClick(View view) {
431 Log.d("interactive", "Cancelling transactions refresh");
432 if (retrieveTransactionsTask != null) retrieveTransactionsTask.cancel(false);
433 bTransactionListCancelDownload.setEnabled(false);
435 public void onRetrieveDone(String error) {
436 progressLayout.setVisibility(View.GONE);
439 updateLastUpdateTextFromDB();
441 new RefreshDescriptionsTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
443 else Toast.makeText(this, error, Toast.LENGTH_LONG).show();
445 public void onRetrieveStart() {
446 bTransactionListCancelDownload.setEnabled(true);
447 progressBar.setIndeterminateTintList(ColorStateList.valueOf(Colors.primary));
448 progressBar.setProgressTintList(ColorStateList.valueOf(Colors.primary));
449 progressBar.setIndeterminate(true);
450 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) progressBar.setProgress(0, false);
451 else progressBar.setProgress(0);
452 progressLayout.setVisibility(View.VISIBLE);
454 public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
455 if ((progress.getTotal() == RetrieveTransactionsTask.Progress.INDETERMINATE) ||
456 (progress.getTotal() == 0))
458 progressBar.setIndeterminate(true);
461 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
462 progressBar.setMin(0);
464 progressBar.setMax(progress.getTotal());
465 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
466 progressBar.setProgress(progress.getProgress(), true);
468 else progressBar.setProgress(progress.getProgress());
469 progressBar.setIndeterminate(false);
472 public void fabShouldShow() {
473 MobileLedgerProfile profile = Data.profile.get();
474 if ((profile != null) && profile.isPostingPermitted()) fab.show();
476 public void navProfilesHeadClicked(View view) {
477 if (profileListExpanded) {
478 collapseProfileList();
484 private void expandProfileList() {
485 profileListExpanded = true;
488 profileListContainer.setVisibility(View.VISIBLE);
489 profileListContainer.startAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_down));
490 profileListHeadArrow.startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate_180));
491 profileListHeadMore.setVisibility(View.VISIBLE);
492 profileListHeadMore.startAnimation(AnimationUtils.loadAnimation(this, R.anim.fade_in));
494 private void collapseProfileList() {
495 profileListExpanded = false;
497 final Animation animation = AnimationUtils.loadAnimation(this, R.anim.slide_up);
498 animation.setAnimationListener(new Animation.AnimationListener() {
500 public void onAnimationStart(Animation animation) {
504 public void onAnimationEnd(Animation animation) {
505 profileListContainer.setVisibility(View.GONE);
508 public void onAnimationRepeat(Animation animation) {
512 profileListContainer.startAnimation(animation);
514 .startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate_180_back));
515 profileListHeadMore.setVisibility(View.GONE);
517 mProfileListAdapter.stopEditingProfiles();
519 public void onProfileRowClicked(View v) {
520 Data.setCurrentProfile((MobileLedgerProfile) v.getTag());
522 public void enableProfileModifications() {
523 profileModificationEnabled = true;
524 ViewGroup profileList = findViewById(R.id.nav_profile_list);
525 for (int i = 0; i < profileList.getChildCount(); i++) {
526 View aRow = profileList.getChildAt(i);
527 aRow.findViewById(R.id.profile_list_edit_button).setVisibility(View.VISIBLE);
528 aRow.findViewById(R.id.profile_list_rearrange_handle).setVisibility(View.VISIBLE);
530 // FIXME enable rearranging
533 public void disableProfileModifications() {
534 profileModificationEnabled = false;
535 ViewGroup profileList = findViewById(R.id.nav_profile_list);
536 for (int i = 0; i < profileList.getChildCount(); i++) {
537 View aRow = profileList.getChildAt(i);
538 aRow.findViewById(R.id.profile_list_edit_button).setVisibility(View.GONE);
539 aRow.findViewById(R.id.profile_list_rearrange_handle).setVisibility(View.GONE);
541 // FIXME disable rearranging
545 public class SectionsPagerAdapter extends FragmentPagerAdapter {
547 public SectionsPagerAdapter(FragmentManager fm) {
552 public Fragment getItem(int position) {
553 Log.d("main", String.format("Switching to fragment %d", position));
556 return new AccountSummaryFragment();
558 return new TransactionListFragment();
560 throw new IllegalStateException(
561 String.format("Unexpected fragment index: " + "%d", position));
566 public int getCount() {