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.Build;
25 import android.os.Bundle;
26 import android.support.design.widget.FloatingActionButton;
27 import android.support.v4.app.Fragment;
28 import android.support.v4.app.FragmentManager;
29 import android.support.v4.app.FragmentPagerAdapter;
30 import android.support.v4.view.GravityCompat;
31 import android.support.v4.view.ViewPager;
32 import android.support.v4.widget.DrawerLayout;
33 import android.support.v7.app.ActionBarDrawerToggle;
34 import android.support.v7.widget.Toolbar;
35 import android.util.Log;
36 import android.view.View;
37 import android.widget.LinearLayout;
38 import android.widget.ProgressBar;
39 import android.widget.TextView;
40 import android.widget.Toast;
42 import net.ktnx.mobileledger.R;
43 import net.ktnx.mobileledger.async.RefreshDescriptionsTask;
44 import net.ktnx.mobileledger.async.RetrieveTransactionsTask;
45 import net.ktnx.mobileledger.model.Data;
46 import net.ktnx.mobileledger.model.LedgerAccount;
47 import net.ktnx.mobileledger.model.MobileLedgerProfile;
48 import net.ktnx.mobileledger.ui.account_summary.AccountSummaryFragment;
49 import net.ktnx.mobileledger.ui.transaction_list.TransactionListFragment;
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;
57 public class MainActivity extends CrashReportingActivity {
59 private FragmentManager fragmentManager;
60 private TextView tvLastUpdate;
61 private RetrieveTransactionsTask retrieveTransactionsTask;
62 private View bTransactionListCancelDownload;
63 private ProgressBar progressBar;
64 private LinearLayout progressLayout;
65 private SectionsPagerAdapter mSectionsPagerAdapter;
66 private ViewPager mViewPager;
67 private FloatingActionButton fab;
70 protected void onStart() {
73 Data.lastUpdateDate.set(null);
74 updateLastUpdateTextFromDB();
75 Date lastUpdate = Data.lastUpdateDate.get();
77 long now = new Date().getTime();
78 if ((lastUpdate == null) || (now > (lastUpdate.getTime() + (24 * 3600 * 1000)))) {
79 if (lastUpdate == null) Log.d("db::", "WEB data never fetched. scheduling a fetch");
81 String.format("WEB data last fetched at %1.3f and now is %1.3f. re-fetching",
82 lastUpdate.getTime() / 1000f, now / 1000f));
84 scheduleTransactionListRetrieval();
88 protected void onCreate(Bundle savedInstanceState) {
89 super.onCreate(savedInstanceState);
90 setContentView(R.layout.activity_main);
91 Toolbar toolbar = findViewById(R.id.toolbar);
92 setSupportActionBar(toolbar);
93 fab = findViewById(R.id.btn_add_transaction);
95 Data.profile.addObserver((o, arg) -> {
96 MobileLedgerProfile profile = Data.profile.get();
98 if (profile == null) setTitle(R.string.app_name);
99 else setTitle(profile.getName());
100 updateLastUpdateTextFromDB();
101 if (profile.isPostingPermitted()) {
102 toolbar.setSubtitle(null);
106 toolbar.setSubtitle(R.string.profile_subitlte_read_only);
110 int newProfileTheme = profile.getThemeId();
111 if (newProfileTheme != Colors.profileThemeId) {
112 Log.d("profiles", String.format("profile theme %d → %d", Colors.profileThemeId,
114 profileThemeChanged();
115 Colors.profileThemeId = newProfileTheme;
120 drawer = findViewById(R.id.drawer_layout);
121 ActionBarDrawerToggle toggle =
122 new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open,
123 R.string.navigation_drawer_close);
124 drawer.addDrawerListener(toggle);
127 TextView ver = drawer.findViewById(R.id.drawer_version_text);
131 getApplicationContext().getPackageManager().getPackageInfo(getPackageName(), 0);
132 ver.setText(pi.versionName);
134 catch (Exception e) {
138 tvLastUpdate = findViewById(R.id.transactions_last_update);
140 bTransactionListCancelDownload = findViewById(R.id.transaction_list_cancel_download);
141 progressBar = findViewById(R.id.transaction_list_progress_bar);
142 if (progressBar == null)
143 throw new RuntimeException("Can't get hold on the transaction value progress bar");
144 progressLayout = findViewById(R.id.transaction_progress_layout);
145 if (progressLayout == null) throw new RuntimeException(
146 "Can't get hold on the transaction value progress bar layout");
148 fragmentManager = getSupportFragmentManager();
149 mSectionsPagerAdapter = new SectionsPagerAdapter(fragmentManager);
151 markDrawerItemCurrent(R.id.nav_account_summary);
153 mViewPager = findViewById(R.id.root_frame);
154 mViewPager.setAdapter(mSectionsPagerAdapter);
155 mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
157 public void onPageSelected(int position) {
160 markDrawerItemCurrent(R.id.nav_account_summary);
163 markDrawerItemCurrent(R.id.nav_latest_transactions);
166 Log.e("MainActivity", String.format("Unexpected page index %d", position));
169 super.onPageSelected(position);
173 Data.lastUpdateDate.addObserver((o, arg) -> {
174 Log.d("main", "lastUpdateDate changed");
175 runOnUiThread(() -> {
176 Date date = Data.lastUpdateDate.get();
178 tvLastUpdate.setText(R.string.transaction_last_update_never);
181 final String text = DateFormat.getDateTimeInstance().format(date);
182 tvLastUpdate.setText(text);
183 Log.d("despair", String.format("Date formatted: %s", text));
188 findViewById(R.id.btn_no_profiles_add).setOnClickListener(v -> startAddProfileActivity());
190 findViewById(R.id.btn_add_transaction).setOnClickListener(this::fabNewTransactionClicked);
192 private void profileThemeChanged() {
193 setupProfileColors();
195 // restart activity to reflect theme change
197 Intent intent = new Intent(this, this.getClass());
198 startActivity(intent);
201 protected void onResume() {
205 private void startAddProfileActivity() {
206 Intent intent = new Intent(this, ProfileListActivity.class);
207 Bundle args = new Bundle();
208 args.putInt(ProfileListActivity.ARG_ACTION, ProfileListActivity.ACTION_EDIT_PROFILE);
209 args.putInt(ProfileListActivity.ARG_PROFILE_INDEX, ProfileListActivity.PROFILE_INDEX_NONE);
210 intent.putExtras(args);
211 startActivity(intent, args);
213 private void setupProfile() {
214 String profileUUID = MLDB.getOption(MLDB.OPT_PROFILE_UUID, null);
215 MobileLedgerProfile profile;
217 profile = MobileLedgerProfile.loadAllFromDB(profileUUID);
219 if (Data.profiles.getList().isEmpty()) {
220 findViewById(R.id.no_profiles_layout).setVisibility(View.VISIBLE);
221 findViewById(R.id.pager_layout).setVisibility(View.GONE);
225 findViewById(R.id.pager_layout).setVisibility(View.VISIBLE);
226 findViewById(R.id.no_profiles_layout).setVisibility(View.GONE);
228 if (profile == null) profile = Data.profiles.get(0);
230 if (profile == null) throw new AssertionError("profile must have a value");
232 Data.setCurrentProfile(profile);
234 public void fabNewTransactionClicked(View view) {
235 Intent intent = new Intent(this, NewTransactionActivity.class);
236 startActivity(intent);
237 overridePendingTransition(R.anim.slide_in_right, R.anim.dummy);
239 public void navSettingsClicked(View view) {
240 Intent intent = new Intent(this, SettingsActivity.class);
241 startActivity(intent);
242 drawer.closeDrawers();
244 public void markDrawerItemCurrent(int id) {
245 TextView item = drawer.findViewById(id);
246 item.setBackgroundColor(Colors.tableRowDarkBG);
248 LinearLayout actions = drawer.findViewById(R.id.nav_actions);
249 for (int i = 0; i < actions.getChildCount(); i++) {
250 View view = actions.getChildAt(i);
251 if (view.getId() != id) {
252 view.setBackgroundColor(Color.TRANSPARENT);
256 public void onAccountSummaryClicked(View view) {
257 drawer.closeDrawers();
259 showAccountSummaryFragment();
261 private void showAccountSummaryFragment() {
262 mViewPager.setCurrentItem(0, true);
263 TransactionListFragment.accountFilter.set(null);
264 // FragmentTransaction ft = fragmentManager.beginTransaction();
265 // accountSummaryFragment = new AccountSummaryFragment();
266 // ft.replace(R.id.root_frame, accountSummaryFragment);
268 // currentFragment = accountSummaryFragment;
270 public void onLatestTransactionsClicked(View view) {
271 drawer.closeDrawers();
273 showTransactionsFragment(null);
275 private void resetFragmentBackStack() {
276 // fragmentManager.popBackStack(0, FragmentManager.POP_BACK_STACK_INCLUSIVE);
278 private void showTransactionsFragment(LedgerAccount account) {
279 if (account != null) TransactionListFragment.accountFilter.set(account.getName());
280 mViewPager.setCurrentItem(1, true);
281 // FragmentTransaction ft = fragmentManager.beginTransaction();
282 // if (transactionListFragment == null) {
283 // Log.d("flow", "MainActivity creating TransactionListFragment");
284 // transactionListFragment = new TransactionListFragment();
286 // Bundle bundle = new Bundle();
287 // if (account != null) {
288 // bundle.putString(TransactionListFragment.BUNDLE_KEY_FILTER_ACCOUNT_NAME,
289 // account.getName());
291 // transactionListFragment.setArguments(bundle);
292 // ft.replace(R.id.root_frame, transactionListFragment);
293 // if (account != null)
294 // ft.addToBackStack(getResources().getString(R.string.title_activity_transaction_list));
297 // currentFragment = transactionListFragment;
299 public void showAccountTransactions(LedgerAccount account) {
300 showTransactionsFragment(account);
303 public void onBackPressed() {
304 DrawerLayout drawer = findViewById(R.id.drawer_layout);
305 if (drawer.isDrawerOpen(GravityCompat.START)) {
306 drawer.closeDrawer(GravityCompat.START);
310 String.format("manager stack: %d", fragmentManager.getBackStackEntryCount()));
312 super.onBackPressed();
315 public void updateLastUpdateTextFromDB() {
317 final MobileLedgerProfile profile = Data.profile.get();
319 (profile != null) ? profile.getLongOption(MLDB.OPT_LAST_SCRAPE, 0L) : 0;
321 Log.d("transactions", String.format("Last update = %d", last_update));
322 if (last_update == 0) {
323 Data.lastUpdateDate.set(null);
326 Data.lastUpdateDate.set(new Date(last_update));
330 public void scheduleTransactionListRetrieval() {
331 if (Data.profile.get() == null) return;
333 retrieveTransactionsTask = new RetrieveTransactionsTask(new WeakReference<>(this));
335 retrieveTransactionsTask.execute();
336 bTransactionListCancelDownload.setEnabled(true);
338 public void onStopTransactionRefreshClick(View view) {
339 Log.d("interactive", "Cancelling transactions refresh");
340 if (retrieveTransactionsTask != null) retrieveTransactionsTask.cancel(false);
341 bTransactionListCancelDownload.setEnabled(false);
343 public void onRetrieveDone(String error) {
344 progressLayout.setVisibility(View.GONE);
347 updateLastUpdateTextFromDB();
349 new RefreshDescriptionsTask().execute();
351 else Toast.makeText(this, error, Toast.LENGTH_LONG).show();
353 public void onRetrieveStart() {
354 progressBar.setIndeterminateTintList(ColorStateList.valueOf(Colors.primary));
355 progressBar.setProgressTintList(ColorStateList.valueOf(Colors.primary));
356 progressBar.setIndeterminate(true);
357 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) progressBar.setProgress(0, false);
358 else progressBar.setProgress(0);
359 progressLayout.setVisibility(View.VISIBLE);
361 public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
362 if ((progress.getTotal() == RetrieveTransactionsTask.Progress.INDETERMINATE) ||
363 (progress.getTotal() == 0))
365 progressBar.setIndeterminate(true);
368 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
369 progressBar.setMin(0);
371 progressBar.setMax(progress.getTotal());
372 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
373 progressBar.setProgress(progress.getProgress(), true);
375 else progressBar.setProgress(progress.getProgress());
376 progressBar.setIndeterminate(false);
379 public void navProfilesClicked(View view) {
380 drawer.closeDrawers();
381 Intent intent = new Intent(this, ProfileListActivity.class);
382 startActivity(intent);
384 public class SectionsPagerAdapter extends FragmentPagerAdapter {
386 public SectionsPagerAdapter(FragmentManager fm) {
391 public Fragment getItem(int position) {
392 Log.d("main", String.format("Switching to fragment %d", position));
395 return new AccountSummaryFragment();
397 return new TransactionListFragment();
399 throw new IllegalStateException(
400 String.format("Unexpected fragment index: " + "%d", position));
405 public int getCount() {
409 public void fabShouldShow() {
410 MobileLedgerProfile profile = Data.profile.get();
411 if ((profile != null) && profile.isPostingPermitted()) fab.show();