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.ui.transaction_list.TransactionListViewModel;
50 import net.ktnx.mobileledger.utils.Colors;
51 import net.ktnx.mobileledger.utils.MLDB;
53 import java.lang.ref.WeakReference;
54 import java.text.DateFormat;
55 import java.util.Date;
56 import java.util.Observable;
57 import java.util.Observer;
59 import androidx.appcompat.app.ActionBarDrawerToggle;
60 import androidx.appcompat.widget.Toolbar;
61 import androidx.core.view.GravityCompat;
62 import androidx.drawerlayout.widget.DrawerLayout;
63 import androidx.fragment.app.Fragment;
64 import androidx.fragment.app.FragmentManager;
65 import androidx.fragment.app.FragmentPagerAdapter;
66 import androidx.recyclerview.widget.LinearLayoutManager;
67 import androidx.recyclerview.widget.RecyclerView;
68 import androidx.viewpager.widget.ViewPager;
70 public class MainActivity extends ProfileThemedActivity {
71 private static final String STATE_CURRENT_PAGE = "current_page";
72 private static final String BUNDLE_SAVED_STATE = "bundle_savedState";
74 private LinearLayout profileListContainer;
75 private View profileListHeadArrow, profileListHeadMore, profileListHeadCancel;
76 private LinearLayout profileListHeadMoreAndCancel;
77 private FragmentManager fragmentManager;
78 private TextView tvLastUpdate;
79 private RetrieveTransactionsTask retrieveTransactionsTask;
80 private View bTransactionListCancelDownload;
81 private ProgressBar progressBar;
82 private LinearLayout progressLayout;
83 private SectionsPagerAdapter mSectionsPagerAdapter;
84 private ViewPager mViewPager;
85 private FloatingActionButton fab;
86 private boolean profileModificationEnabled = false;
87 private boolean profileListExpanded = false;
88 private ProfilesRecyclerViewAdapter mProfileListAdapter;
91 protected void onStart() {
94 Data.lastUpdateDate.set(null);
95 updateLastUpdateTextFromDB();
96 Date lastUpdate = Data.lastUpdateDate.get();
98 long now = new Date().getTime();
99 if ((lastUpdate == null) || (now > (lastUpdate.getTime() + (24 * 3600 * 1000)))) {
100 if (lastUpdate == null) Log.d("db::", "WEB data never fetched. scheduling a fetch");
102 String.format("WEB data last fetched at %1.3f and now is %1.3f. re-fetching",
103 lastUpdate.getTime() / 1000f, now / 1000f));
105 scheduleTransactionListRetrieval();
109 protected void onSaveInstanceState(Bundle outState) {
110 super.onSaveInstanceState(outState);
111 outState.putInt(STATE_CURRENT_PAGE, mViewPager.getCurrentItem());
114 protected void onCreate(Bundle savedInstanceState) {
115 super.onCreate(savedInstanceState);
117 setContentView(R.layout.activity_main);
119 fab = findViewById(R.id.btn_add_transaction);
120 profileListContainer = findViewById(R.id.nav_profile_list_container);
121 profileListHeadArrow = findViewById(R.id.nav_profiles_arrow);
122 profileListHeadMore = findViewById(R.id.nav_profiles_start_edit);
123 profileListHeadCancel = findViewById(R.id.nav_profiles_cancel_edit);
124 profileListHeadMoreAndCancel = findViewById(R.id.nav_profile_list_head_buttons);
125 drawer = findViewById(R.id.drawer_layout);
126 tvLastUpdate = findViewById(R.id.transactions_last_update);
127 bTransactionListCancelDownload = findViewById(R.id.transaction_list_cancel_download);
128 progressBar = findViewById(R.id.transaction_list_progress_bar);
129 progressLayout = findViewById(R.id.transaction_progress_layout);
130 fragmentManager = getSupportFragmentManager();
131 mSectionsPagerAdapter = new SectionsPagerAdapter(fragmentManager);
132 mViewPager = findViewById(R.id.root_frame);
134 Bundle extra = getIntent().getBundleExtra(BUNDLE_SAVED_STATE);
135 if (extra != null && savedInstanceState == null) savedInstanceState = extra;
138 Toolbar toolbar = findViewById(R.id.toolbar);
139 setSupportActionBar(toolbar);
141 Data.profile.addObserver((o, arg) -> {
142 MobileLedgerProfile profile = Data.profile.get();
143 runOnUiThread(() -> {
144 if (profile == null) setTitle(R.string.app_name);
145 else setTitle(profile.getName());
146 updateLastUpdateTextFromDB();
147 if (profile.isPostingPermitted()) {
148 toolbar.setSubtitle(null);
152 toolbar.setSubtitle(R.string.profile_subitlte_read_only);
156 int newProfileTheme = profile.getThemeId();
157 if (newProfileTheme != Colors.profileThemeId) {
158 Log.d("profiles", String.format("profile theme %d → %d", Colors.profileThemeId,
160 profileThemeChanged();
161 Colors.profileThemeId = newProfileTheme;
166 ActionBarDrawerToggle toggle =
167 new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open,
168 R.string.navigation_drawer_close);
169 drawer.addDrawerListener(toggle);
172 TextView ver = drawer.findViewById(R.id.drawer_version_text);
176 getApplicationContext().getPackageManager().getPackageInfo(getPackageName(), 0);
177 ver.setText(pi.versionName);
179 catch (Exception e) {
183 if (progressBar == null)
184 throw new RuntimeException("Can't get hold on the transaction value progress bar");
185 if (progressLayout == null) throw new RuntimeException(
186 "Can't get hold on the transaction value progress bar layout");
188 markDrawerItemCurrent(R.id.nav_account_summary);
190 mViewPager.setAdapter(mSectionsPagerAdapter);
191 mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
193 public void onPageSelected(int position) {
196 markDrawerItemCurrent(R.id.nav_account_summary);
199 markDrawerItemCurrent(R.id.nav_latest_transactions);
202 Log.e("MainActivity", String.format("Unexpected page index %d", position));
205 super.onPageSelected(position);
209 if (savedInstanceState != null) {
210 int currentPage = savedInstanceState.getInt(STATE_CURRENT_PAGE, -1);
211 if (currentPage != -1) {
212 mViewPager.setCurrentItem(currentPage, false);
216 Data.lastUpdateDate.addObserver((o, arg) -> {
217 Log.d("main", "lastUpdateDate changed");
218 runOnUiThread(() -> {
219 Date date = Data.lastUpdateDate.get();
221 tvLastUpdate.setText(R.string.transaction_last_update_never);
224 final String text = DateFormat.getDateTimeInstance().format(date);
225 tvLastUpdate.setText(text);
226 Log.d("despair", String.format("Date formatted: %s", text));
231 findViewById(R.id.btn_no_profiles_add)
232 .setOnClickListener(v -> startEditProfileActivity(null));
234 findViewById(R.id.btn_add_transaction).setOnClickListener(this::fabNewTransactionClicked);
236 findViewById(R.id.nav_new_profile_button)
237 .setOnClickListener(v -> startEditProfileActivity(null));
239 RecyclerView root = findViewById(R.id.nav_profile_list);
241 throw new RuntimeException("Can't get hold on the transaction value view");
243 mProfileListAdapter = new ProfilesRecyclerViewAdapter();
244 root.setAdapter(mProfileListAdapter);
246 mProfileListAdapter.addEditingProfilesObserver(new Observer() {
248 public void update(Observable o, Object arg) {
249 if (mProfileListAdapter.isEditingProfiles()) {
250 profileListHeadArrow.clearAnimation();
251 profileListHeadArrow.setVisibility(View.GONE);
252 profileListHeadMore.setVisibility(View.GONE);
253 profileListHeadCancel.setVisibility(View.VISIBLE);
256 profileListHeadArrow.setRotation(180f);
257 profileListHeadArrow.setVisibility(View.VISIBLE);
258 profileListHeadCancel.setVisibility(View.GONE);
259 profileListHeadMore.setVisibility(View.GONE);
261 .setVisibility(profileListExpanded ? View.VISIBLE : View.GONE);
266 LinearLayoutManager llm = new LinearLayoutManager(this);
268 llm.setOrientation(RecyclerView.VERTICAL);
269 root.setLayoutManager(llm);
271 profileListHeadMore.setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
272 profileListHeadCancel.setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
273 profileListHeadMoreAndCancel
274 .setOnClickListener((v) -> mProfileListAdapter.flipEditingProfiles());
276 drawer.addDrawerListener(new DrawerLayout.SimpleDrawerListener() {
278 public void onDrawerClosed(View drawerView) {
279 super.onDrawerClosed(drawerView);
280 collapseProfileList();
284 private void profileThemeChanged() {
285 setupProfileColors();
287 Bundle bundle = new Bundle();
288 onSaveInstanceState(bundle);
289 // restart activity to reflect theme change
291 Intent intent = new Intent(this, this.getClass());
292 intent.putExtra(BUNDLE_SAVED_STATE, bundle);
293 startActivity(intent);
296 protected void onResume() {
300 public void startEditProfileActivity(MobileLedgerProfile profile) {
301 Intent intent = new Intent(this, ProfileDetailActivity.class);
302 Bundle args = new Bundle();
303 if (profile != null) {
304 int index = Data.getProfileIndex(profile);
305 if (index != -1) intent.putExtra(ProfileDetailFragment.ARG_ITEM_ID, index);
307 intent.putExtras(args);
308 startActivity(intent, args);
310 private void setupProfile() {
311 String profileUUID = MLDB.getOption(MLDB.OPT_PROFILE_UUID, null);
312 MobileLedgerProfile profile;
314 profile = MobileLedgerProfile.loadAllFromDB(profileUUID);
316 if (Data.profiles.getList().isEmpty()) {
317 findViewById(R.id.no_profiles_layout).setVisibility(View.VISIBLE);
318 findViewById(R.id.pager_layout).setVisibility(View.GONE);
322 findViewById(R.id.pager_layout).setVisibility(View.VISIBLE);
323 findViewById(R.id.no_profiles_layout).setVisibility(View.GONE);
325 if (profile == null) profile = Data.profiles.get(0);
327 if (profile == null) throw new AssertionError("profile must have a value");
329 Data.setCurrentProfile(profile);
331 public void fabNewTransactionClicked(View view) {
332 Intent intent = new Intent(this, NewTransactionActivity.class);
333 startActivity(intent);
334 overridePendingTransition(R.anim.slide_in_right, R.anim.dummy);
336 public void navSettingsClicked(View view) {
337 Intent intent = new Intent(this, SettingsActivity.class);
338 startActivity(intent);
339 drawer.closeDrawers();
341 public void markDrawerItemCurrent(int id) {
342 TextView item = drawer.findViewById(id);
343 item.setBackgroundColor(Colors.tableRowDarkBG);
345 LinearLayout actions = drawer.findViewById(R.id.nav_actions);
346 for (int i = 0; i < actions.getChildCount(); i++) {
347 View view = actions.getChildAt(i);
348 if (view.getId() != id) {
349 view.setBackgroundColor(Color.TRANSPARENT);
353 public void onAccountSummaryClicked(View view) {
354 drawer.closeDrawers();
356 showAccountSummaryFragment();
358 private void showAccountSummaryFragment() {
359 mViewPager.setCurrentItem(0, true);
360 TransactionListFragment.accountFilter.set(null);
361 // FragmentTransaction ft = fragmentManager.beginTransaction();
362 // accountSummaryFragment = new AccountSummaryFragment();
363 // ft.replace(R.id.root_frame, accountSummaryFragment);
365 // currentFragment = accountSummaryFragment;
367 public void onLatestTransactionsClicked(View view) {
368 drawer.closeDrawers();
370 showTransactionsFragment(null);
372 private void resetFragmentBackStack() {
373 // fragmentManager.popBackStack(0, FragmentManager.POP_BACK_STACK_INCLUSIVE);
375 private void showTransactionsFragment(LedgerAccount account) {
376 if (account != null) TransactionListFragment.accountFilter.set(account.getName());
377 mViewPager.setCurrentItem(1, true);
378 // FragmentTransaction ft = fragmentManager.beginTransaction();
379 // if (transactionListFragment == null) {
380 // Log.d("flow", "MainActivity creating TransactionListFragment");
381 // transactionListFragment = new TransactionListFragment();
383 // Bundle bundle = new Bundle();
384 // if (account != null) {
385 // bundle.putString(TransactionListFragment.BUNDLE_KEY_FILTER_ACCOUNT_NAME,
386 // account.getName());
388 // transactionListFragment.setArguments(bundle);
389 // ft.replace(R.id.root_frame, transactionListFragment);
390 // if (account != null)
391 // ft.addToBackStack(getResources().getString(R.string.title_activity_transaction_list));
394 // currentFragment = transactionListFragment;
396 public void showAccountTransactions(LedgerAccount account) {
397 showTransactionsFragment(account);
400 public void onBackPressed() {
401 DrawerLayout drawer = findViewById(R.id.drawer_layout);
402 if (drawer.isDrawerOpen(GravityCompat.START)) {
403 drawer.closeDrawer(GravityCompat.START);
407 String.format("manager stack: %d", fragmentManager.getBackStackEntryCount()));
409 super.onBackPressed();
412 public void updateLastUpdateTextFromDB() {
414 final MobileLedgerProfile profile = Data.profile.get();
416 (profile != null) ? profile.getLongOption(MLDB.OPT_LAST_SCRAPE, 0L) : 0;
418 Log.d("transactions", String.format("Last update = %d", last_update));
419 if (last_update == 0) {
420 Data.lastUpdateDate.set(null);
423 Data.lastUpdateDate.set(new Date(last_update));
427 public void scheduleTransactionListRetrieval() {
428 if (Data.profile.get() == null) return;
430 retrieveTransactionsTask = new RetrieveTransactionsTask(new WeakReference<>(this));
432 retrieveTransactionsTask.execute();
434 public void onStopTransactionRefreshClick(View view) {
435 Log.d("interactive", "Cancelling transactions refresh");
436 if (retrieveTransactionsTask != null) retrieveTransactionsTask.cancel(false);
437 bTransactionListCancelDownload.setEnabled(false);
439 public void onRetrieveDone(String error) {
440 progressLayout.setVisibility(View.GONE);
443 updateLastUpdateTextFromDB();
445 new RefreshDescriptionsTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
446 TransactionListViewModel.scheduleTransactionListReload();
448 else Toast.makeText(this, error, Toast.LENGTH_LONG).show();
450 public void onRetrieveStart() {
451 bTransactionListCancelDownload.setEnabled(true);
452 progressBar.setIndeterminateTintList(ColorStateList.valueOf(Colors.primary));
453 progressBar.setProgressTintList(ColorStateList.valueOf(Colors.primary));
454 progressBar.setIndeterminate(true);
455 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) progressBar.setProgress(0, false);
456 else progressBar.setProgress(0);
457 progressLayout.setVisibility(View.VISIBLE);
459 public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
460 if ((progress.getTotal() == RetrieveTransactionsTask.Progress.INDETERMINATE) ||
461 (progress.getTotal() == 0))
463 progressBar.setIndeterminate(true);
466 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
467 progressBar.setMin(0);
469 progressBar.setMax(progress.getTotal());
470 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
471 progressBar.setProgress(progress.getProgress(), true);
473 else progressBar.setProgress(progress.getProgress());
474 progressBar.setIndeterminate(false);
477 public void fabShouldShow() {
478 MobileLedgerProfile profile = Data.profile.get();
479 if ((profile != null) && profile.isPostingPermitted()) fab.show();
481 public void navProfilesHeadClicked(View view) {
482 if (profileListExpanded) {
483 collapseProfileList();
489 private void expandProfileList() {
490 profileListExpanded = true;
493 profileListContainer.setVisibility(View.VISIBLE);
494 profileListContainer.startAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_down));
495 profileListHeadArrow.startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate_180));
496 profileListHeadMore.setVisibility(View.VISIBLE);
497 profileListHeadMore.startAnimation(AnimationUtils.loadAnimation(this, R.anim.fade_in));
498 findViewById(R.id.nav_profile_list).setMinimumHeight(
499 (int) (getResources().getDimension(R.dimen.thumb_row_height) *
500 Data.profiles.size()));
502 private void collapseProfileList() {
503 profileListExpanded = false;
505 final Animation animation = AnimationUtils.loadAnimation(this, R.anim.slide_up);
506 animation.setAnimationListener(new Animation.AnimationListener() {
508 public void onAnimationStart(Animation animation) {
512 public void onAnimationEnd(Animation animation) {
513 profileListContainer.setVisibility(View.GONE);
516 public void onAnimationRepeat(Animation animation) {
520 mProfileListAdapter.stopEditingProfiles();
522 profileListContainer.startAnimation(animation);
523 profileListHeadArrow.setRotation(0f);
525 .startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate_180_back));
526 profileListHeadMore.setVisibility(View.GONE);
528 public void onProfileRowClicked(View v) {
529 Data.setCurrentProfile((MobileLedgerProfile) v.getTag());
531 public void enableProfileModifications() {
532 profileModificationEnabled = true;
533 ViewGroup profileList = findViewById(R.id.nav_profile_list);
534 for (int i = 0; i < profileList.getChildCount(); i++) {
535 View aRow = profileList.getChildAt(i);
536 aRow.findViewById(R.id.profile_list_edit_button).setVisibility(View.VISIBLE);
537 aRow.findViewById(R.id.profile_list_rearrange_handle).setVisibility(View.VISIBLE);
539 // FIXME enable rearranging
542 public void disableProfileModifications() {
543 profileModificationEnabled = false;
544 ViewGroup profileList = findViewById(R.id.nav_profile_list);
545 for (int i = 0; i < profileList.getChildCount(); i++) {
546 View aRow = profileList.getChildAt(i);
547 aRow.findViewById(R.id.profile_list_edit_button).setVisibility(View.GONE);
548 aRow.findViewById(R.id.profile_list_rearrange_handle).setVisibility(View.INVISIBLE);
550 // FIXME disable rearranging
554 public class SectionsPagerAdapter extends FragmentPagerAdapter {
556 public SectionsPagerAdapter(FragmentManager fm) {
561 public Fragment getItem(int position) {
562 Log.d("main", String.format("Switching to fragment %d", position));
565 return new AccountSummaryFragment();
567 return new TransactionListFragment();
569 throw new IllegalStateException(
570 String.format("Unexpected fragment index: " + "%d", position));
575 public int getCount() {