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;
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 drawer = findViewById(R.id.drawer_layout);
121 tvLastUpdate = findViewById(R.id.transactions_last_update);
122 bTransactionListCancelDownload = findViewById(R.id.transaction_list_cancel_download);
123 progressBar = findViewById(R.id.transaction_list_progress_bar);
124 progressLayout = findViewById(R.id.transaction_progress_layout);
125 fragmentManager = getSupportFragmentManager();
126 mSectionsPagerAdapter = new SectionsPagerAdapter(fragmentManager);
127 mViewPager = findViewById(R.id.root_frame);
129 Bundle extra = getIntent().getBundleExtra(BUNDLE_SAVED_STATE);
130 if (extra != null && savedInstanceState == null) savedInstanceState = extra;
133 Toolbar toolbar = findViewById(R.id.toolbar);
134 setSupportActionBar(toolbar);
136 Data.profile.addObserver((o, arg) -> {
137 MobileLedgerProfile profile = Data.profile.get();
138 runOnUiThread(() -> {
139 if (profile == null) setTitle(R.string.app_name);
140 else setTitle(profile.getName());
141 updateLastUpdateTextFromDB();
142 if (profile.isPostingPermitted()) {
143 toolbar.setSubtitle(null);
147 toolbar.setSubtitle(R.string.profile_subitlte_read_only);
151 int newProfileTheme = profile.getThemeId();
152 if (newProfileTheme != Colors.profileThemeId) {
153 Log.d("profiles", String.format("profile theme %d → %d", Colors.profileThemeId,
155 profileThemeChanged();
156 Colors.profileThemeId = newProfileTheme;
161 ActionBarDrawerToggle toggle =
162 new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open,
163 R.string.navigation_drawer_close);
164 drawer.addDrawerListener(toggle);
167 TextView ver = drawer.findViewById(R.id.drawer_version_text);
171 getApplicationContext().getPackageManager().getPackageInfo(getPackageName(), 0);
172 ver.setText(pi.versionName);
174 catch (Exception e) {
178 if (progressBar == null)
179 throw new RuntimeException("Can't get hold on the transaction value progress bar");
180 if (progressLayout == null) throw new RuntimeException(
181 "Can't get hold on the transaction value progress bar layout");
183 markDrawerItemCurrent(R.id.nav_account_summary);
185 mViewPager.setAdapter(mSectionsPagerAdapter);
186 mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
188 public void onPageSelected(int position) {
191 markDrawerItemCurrent(R.id.nav_account_summary);
194 markDrawerItemCurrent(R.id.nav_latest_transactions);
197 Log.e("MainActivity", String.format("Unexpected page index %d", position));
200 super.onPageSelected(position);
204 if (savedInstanceState != null) {
205 int currentPage = savedInstanceState.getInt(STATE_CURRENT_PAGE, -1);
206 if (currentPage != -1) {
207 mViewPager.setCurrentItem(currentPage, false);
211 Data.lastUpdateDate.addObserver((o, arg) -> {
212 Log.d("main", "lastUpdateDate changed");
213 runOnUiThread(() -> {
214 Date date = Data.lastUpdateDate.get();
216 tvLastUpdate.setText(R.string.transaction_last_update_never);
219 final String text = DateFormat.getDateTimeInstance().format(date);
220 tvLastUpdate.setText(text);
221 Log.d("despair", String.format("Date formatted: %s", text));
226 findViewById(R.id.btn_no_profiles_add)
227 .setOnClickListener(v -> startEditProfileActivity(null));
229 findViewById(R.id.btn_add_transaction).setOnClickListener(this::fabNewTransactionClicked);
231 findViewById(R.id.nav_new_profile_button)
232 .setOnClickListener(v -> startEditProfileActivity(null));
234 RecyclerView root = findViewById(R.id.nav_profile_list);
236 throw new RuntimeException("Can't get hold on the transaction value view");
238 mProfileListAdapter = new ProfilesRecyclerViewAdapter();
239 root.setAdapter(mProfileListAdapter);
241 mProfileListAdapter.addEditingProfilesObserver(new Observer() {
243 public void update(Observable o, Object arg) {
244 final View profilesArrow = findViewById(R.id.nav_profiles_arrow);
245 if (mProfileListAdapter.isEditingProfiles()) {
246 profilesArrow.clearAnimation();
247 profilesArrow.setVisibility(View.GONE);
248 // findViewById(R.id.nav_profiles_arrow).setAlpha(0f);
249 findViewById(R.id.nav_profiles_cancel_edit).setVisibility(View.VISIBLE);
252 profilesArrow.setVisibility(View.VISIBLE);
253 // findViewById(R.id.nav_profiles_arrow).setAlpha(1f);
254 findViewById(R.id.nav_profiles_cancel_edit).setVisibility(View.GONE);
259 findViewById(R.id.nav_profiles_cancel_edit).setOnClickListener((v) -> {
260 mProfileListAdapter.stopEditingProfiles();
262 LinearLayoutManager llm = new LinearLayoutManager(this);
264 llm.setOrientation(RecyclerView.VERTICAL);
265 root.setLayoutManager(llm);
267 private void profileThemeChanged() {
268 setupProfileColors();
270 Bundle bundle = new Bundle();
271 onSaveInstanceState(bundle);
272 // restart activity to reflect theme change
274 Intent intent = new Intent(this, this.getClass());
275 intent.putExtra(BUNDLE_SAVED_STATE, bundle);
276 startActivity(intent);
279 protected void onResume() {
283 public void startEditProfileActivity(MobileLedgerProfile profile) {
284 Intent intent = new Intent(this, ProfileDetailActivity.class);
285 Bundle args = new Bundle();
286 if (profile != null) {
287 int index = Data.getProfileIndex(profile);
288 if (index != -1) intent.putExtra(ProfileDetailFragment.ARG_ITEM_ID, index);
290 intent.putExtras(args);
291 startActivity(intent, args);
293 private void setupProfile() {
294 String profileUUID = MLDB.getOption(MLDB.OPT_PROFILE_UUID, null);
295 MobileLedgerProfile profile;
297 profile = MobileLedgerProfile.loadAllFromDB(profileUUID);
299 if (Data.profiles.getList().isEmpty()) {
300 findViewById(R.id.no_profiles_layout).setVisibility(View.VISIBLE);
301 findViewById(R.id.pager_layout).setVisibility(View.GONE);
305 findViewById(R.id.pager_layout).setVisibility(View.VISIBLE);
306 findViewById(R.id.no_profiles_layout).setVisibility(View.GONE);
308 if (profile == null) profile = Data.profiles.get(0);
310 if (profile == null) throw new AssertionError("profile must have a value");
312 Data.setCurrentProfile(profile);
314 public void fabNewTransactionClicked(View view) {
315 Intent intent = new Intent(this, NewTransactionActivity.class);
316 startActivity(intent);
317 overridePendingTransition(R.anim.slide_in_right, R.anim.dummy);
319 public void navSettingsClicked(View view) {
320 Intent intent = new Intent(this, SettingsActivity.class);
321 startActivity(intent);
322 drawer.closeDrawers();
324 public void markDrawerItemCurrent(int id) {
325 TextView item = drawer.findViewById(id);
326 item.setBackgroundColor(Colors.tableRowDarkBG);
328 LinearLayout actions = drawer.findViewById(R.id.nav_actions);
329 for (int i = 0; i < actions.getChildCount(); i++) {
330 View view = actions.getChildAt(i);
331 if (view.getId() != id) {
332 view.setBackgroundColor(Color.TRANSPARENT);
336 public void onAccountSummaryClicked(View view) {
337 drawer.closeDrawers();
339 showAccountSummaryFragment();
341 private void showAccountSummaryFragment() {
342 mViewPager.setCurrentItem(0, true);
343 TransactionListFragment.accountFilter.set(null);
344 // FragmentTransaction ft = fragmentManager.beginTransaction();
345 // accountSummaryFragment = new AccountSummaryFragment();
346 // ft.replace(R.id.root_frame, accountSummaryFragment);
348 // currentFragment = accountSummaryFragment;
350 public void onLatestTransactionsClicked(View view) {
351 drawer.closeDrawers();
353 showTransactionsFragment(null);
355 private void resetFragmentBackStack() {
356 // fragmentManager.popBackStack(0, FragmentManager.POP_BACK_STACK_INCLUSIVE);
358 private void showTransactionsFragment(LedgerAccount account) {
359 if (account != null) TransactionListFragment.accountFilter.set(account.getName());
360 mViewPager.setCurrentItem(1, true);
361 // FragmentTransaction ft = fragmentManager.beginTransaction();
362 // if (transactionListFragment == null) {
363 // Log.d("flow", "MainActivity creating TransactionListFragment");
364 // transactionListFragment = new TransactionListFragment();
366 // Bundle bundle = new Bundle();
367 // if (account != null) {
368 // bundle.putString(TransactionListFragment.BUNDLE_KEY_FILTER_ACCOUNT_NAME,
369 // account.getName());
371 // transactionListFragment.setArguments(bundle);
372 // ft.replace(R.id.root_frame, transactionListFragment);
373 // if (account != null)
374 // ft.addToBackStack(getResources().getString(R.string.title_activity_transaction_list));
377 // currentFragment = transactionListFragment;
379 public void showAccountTransactions(LedgerAccount account) {
380 showTransactionsFragment(account);
383 public void onBackPressed() {
384 DrawerLayout drawer = findViewById(R.id.drawer_layout);
385 if (drawer.isDrawerOpen(GravityCompat.START)) {
386 drawer.closeDrawer(GravityCompat.START);
390 String.format("manager stack: %d", fragmentManager.getBackStackEntryCount()));
392 super.onBackPressed();
395 public void updateLastUpdateTextFromDB() {
397 final MobileLedgerProfile profile = Data.profile.get();
399 (profile != null) ? profile.getLongOption(MLDB.OPT_LAST_SCRAPE, 0L) : 0;
401 Log.d("transactions", String.format("Last update = %d", last_update));
402 if (last_update == 0) {
403 Data.lastUpdateDate.set(null);
406 Data.lastUpdateDate.set(new Date(last_update));
410 public void scheduleTransactionListRetrieval() {
411 if (Data.profile.get() == null) return;
413 retrieveTransactionsTask = new RetrieveTransactionsTask(new WeakReference<>(this));
415 retrieveTransactionsTask.execute();
417 public void onStopTransactionRefreshClick(View view) {
418 Log.d("interactive", "Cancelling transactions refresh");
419 if (retrieveTransactionsTask != null) retrieveTransactionsTask.cancel(false);
420 bTransactionListCancelDownload.setEnabled(false);
422 public void onRetrieveDone(String error) {
423 progressLayout.setVisibility(View.GONE);
426 updateLastUpdateTextFromDB();
428 new RefreshDescriptionsTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
430 else Toast.makeText(this, error, Toast.LENGTH_LONG).show();
432 public void onRetrieveStart() {
433 bTransactionListCancelDownload.setEnabled(true);
434 progressBar.setIndeterminateTintList(ColorStateList.valueOf(Colors.primary));
435 progressBar.setProgressTintList(ColorStateList.valueOf(Colors.primary));
436 progressBar.setIndeterminate(true);
437 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) progressBar.setProgress(0, false);
438 else progressBar.setProgress(0);
439 progressLayout.setVisibility(View.VISIBLE);
441 public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
442 if ((progress.getTotal() == RetrieveTransactionsTask.Progress.INDETERMINATE) ||
443 (progress.getTotal() == 0))
445 progressBar.setIndeterminate(true);
448 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
449 progressBar.setMin(0);
451 progressBar.setMax(progress.getTotal());
452 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
453 progressBar.setProgress(progress.getProgress(), true);
455 else progressBar.setProgress(progress.getProgress());
456 progressBar.setIndeterminate(false);
459 public void fabShouldShow() {
460 MobileLedgerProfile profile = Data.profile.get();
461 if ((profile != null) && profile.isPostingPermitted()) fab.show();
463 public void navProfilesHeadClicked(View view) {
464 if (profileListExpanded) {
465 collapseProfileList();
471 private void expandProfileList() {
472 profileListExpanded = true;
475 profileListContainer.setVisibility(View.VISIBLE);
476 profileListContainer.startAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_down));
477 profileListHeadArrow.startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate_180));
479 private void collapseProfileList() {
480 profileListExpanded = false;
482 final Animation animation = AnimationUtils.loadAnimation(this, R.anim.slide_up);
483 animation.setAnimationListener(new Animation.AnimationListener() {
485 public void onAnimationStart(Animation animation) {
489 public void onAnimationEnd(Animation animation) {
490 profileListContainer.setVisibility(View.GONE);
493 public void onAnimationRepeat(Animation animation) {
497 profileListContainer.startAnimation(animation);
499 .startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate_180_back));
501 mProfileListAdapter.stopEditingProfiles();
503 public void onProfileRowClicked(View v) {
504 Data.setCurrentProfile((MobileLedgerProfile) v.getTag());
506 public void enableProfileModifications() {
507 profileModificationEnabled = true;
508 ViewGroup profileList = findViewById(R.id.nav_profile_list);
509 for (int i = 0; i < profileList.getChildCount(); i++) {
510 View aRow = profileList.getChildAt(i);
511 aRow.findViewById(R.id.profile_list_edit_button).setVisibility(View.VISIBLE);
512 aRow.findViewById(R.id.profile_list_rearrange_handle).setVisibility(View.VISIBLE);
514 // FIXME enable rearranging
517 public void disableProfileModifications() {
518 profileModificationEnabled = false;
519 ViewGroup profileList = findViewById(R.id.nav_profile_list);
520 for (int i = 0; i < profileList.getChildCount(); i++) {
521 View aRow = profileList.getChildAt(i);
522 aRow.findViewById(R.id.profile_list_edit_button).setVisibility(View.GONE);
523 aRow.findViewById(R.id.profile_list_rearrange_handle).setVisibility(View.GONE);
525 // FIXME disable rearranging
529 public class SectionsPagerAdapter extends FragmentPagerAdapter {
531 public SectionsPagerAdapter(FragmentManager fm) {
536 public Fragment getItem(int position) {
537 Log.d("main", String.format("Switching to fragment %d", position));
540 return new AccountSummaryFragment();
542 return new TransactionListFragment();
544 throw new IllegalStateException(
545 String.format("Unexpected fragment index: " + "%d", position));
550 public int getCount() {