-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainActivity.java
More file actions
478 lines (404 loc) · 19.7 KB
/
Copy pathMainActivity.java
File metadata and controls
478 lines (404 loc) · 19.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
package com.gratus.workoutrepo;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ScrollView;
import android.widget.Toast;
import androidx.activity.EdgeToEdge;
import androidx.activity.OnBackPressedCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.constraintlayout.motion.widget.MotionLayout;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;
import java.util.Calendar;
import com.gratus.workoutrepo.adapters.GuideAdapter;
import com.gratus.workoutrepo.adapters.WeekPagerAdapter;
import com.gratus.workoutrepo.strava.utils.StravaArchiveManager;
public class MainActivity extends BaseActivity {
private long backPressedTime;
private Toast backToast;
private MotionLayout motionLayout;
// --- NEW: Keep a strong reference to the listener ---
private SharedPreferences.OnSharedPreferenceChangeListener prefListener;
private ActivityResultLauncher<String> exportLauncher;
private ActivityResultLauncher<String[]> importLauncher;
@SuppressLint("ClickableViewAccessibility")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// --- NEW: Fix SSL Handshake errors on older Emulators ---
// try {
// ProviderInstaller.installIfNeeded(this);
// } catch (Exception e) {
// e.printStackTrace();
// }
// --------------------------------------------------------
EdgeToEdge.enable(this);
setContentView(R.layout.activity_main);
motionLayout = findViewById(R.id.main);
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
return insets;
});
findViewById(R.id.browseWorkouts)
.setOnClickListener(v -> startActivity(new Intent(MainActivity.this, RoutinesActivity.class)));
ScrollView scrollView = findViewById(R.id.btn_scroll);
// Run after layout so child sizes are known
scrollView.post(() -> {
ViewGroup container = (ViewGroup) scrollView.getChildAt(0);
int itemHeight = container.getChildAt(0).getHeight();
// Scroll to the second item (index 1)
int targetY = 2 * itemHeight;
scrollView.scrollTo(0, targetY);
});
scrollView.setOnTouchListener((v, event) -> {
if (event.getAction() == MotionEvent.ACTION_UP) {
// Get the container (LinearLayout inside the scrollview)
ViewGroup container = (ViewGroup) scrollView.getChildAt(0);
// Each item has fixed width (58dp in your XML)
int itemHeight = container.getChildAt(0).getHeight();
int scrollY = scrollView.getScrollY();
// Decide which item we are closer to: 0 (GitHub) or 1 (Theme container)
int page = (scrollY + itemHeight / 2) / itemHeight;
int targetY = page * itemHeight;
scrollView.post(() -> scrollView.smoothScrollTo(0, targetY));
return false;
}
return false;
});
// Inside onCreate in MainActivity.java
exportLauncher = registerForActivityResult(new ActivityResultContracts.CreateDocument("application/json"), uri -> {
if (uri != null) {
StravaArchiveManager.exportData(this, uri);
}
});
importLauncher = registerForActivityResult(new ActivityResultContracts.OpenDocument(), uri -> {
if (uri != null) {
if (!com.gratus.workoutrepo.archive.data.ActivityArchiveManager.INSTANCE.getActivities(this).isEmpty()) {
android.app.Dialog dialog = new android.app.Dialog(this);
dialog.setContentView(R.layout.dialog_import_option);
if (dialog.getWindow() != null) {
dialog.getWindow().setLayout(android.view.ViewGroup.LayoutParams.MATCH_PARENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
}
com.google.android.material.button.MaterialButton btnMergeArchive = dialog.findViewById(R.id.btnMergeArchive);
com.google.android.material.button.MaterialButton btnReplaceArchive = dialog.findViewById(R.id.btnReplaceArchive);
com.google.android.material.button.MaterialButton btnCancel = dialog.findViewById(R.id.btnCancel);
if (btnMergeArchive != null) {
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
String activeSource = prefs.getString("ActiveSyncSource", "STRAVA");
int colorRes = "INTERVALS_ICU".equals(activeSource) ? R.color.intervals_icu_color : R.color.strava_color;
btnMergeArchive.setBackgroundTintList(androidx.core.content.ContextCompat.getColorStateList(this, colorRes));
btnMergeArchive.setOnClickListener(v -> {
dialog.dismiss();
StravaArchiveManager.importData(this, uri, true);
});
}
if (btnReplaceArchive != null) {
btnReplaceArchive.setOnClickListener(v -> {
dialog.dismiss();
StravaArchiveManager.importData(this, uri, false);
});
}
if (btnCancel != null) {
btnCancel.setOnClickListener(v -> dialog.dismiss());
}
dialog.show();
} else {
StravaArchiveManager.importData(this, uri, true);
}
}
});
setupGuideRecyclerView();
setupThemeButtons();
setupButtons();
setupWeekPager();
setupOnBackPressed();
handleWidgetIntent(getIntent());
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
handleWidgetIntent(intent);
}
private void handleWidgetIntent(Intent intent) {
if (intent != null && intent.hasExtra("EXTRA_DAY_INDEX")) {
int dayIndex = intent.getIntExtra("EXTRA_DAY_INDEX", 0);
ViewPager2 weekPager = findViewById(R.id.weekPager);
if (weekPager != null) {
// Find current middle position to align to Monday correctly, then add dayIndex
int middle = Integer.MAX_VALUE / 2;
int startPosition = middle - (middle % 7) + dayIndex;
weekPager.setCurrentItem(startPosition, false);
}
}
}
private void setupGuideRecyclerView() {
RecyclerView guideRv = findViewById(R.id.guide_container);
guideRv.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
GuideAdapter adapter = new GuideAdapter(new GuideAdapter.OnArchiveInteractionListener() {
@Override
public void onExportClicked() {
String fileName = "Strava_Archive_" + System.currentTimeMillis() + ".json";
exportLauncher.launch(fileName);
}
@Override
public void onImportClicked() {
importLauncher.launch(new String[]{"application/json"});
}
});
guideRv.setAdapter(adapter);
// FIX: Pre-calculate the height of the 'Usage Info' page (the tallest one)
// We inflate it effectively "off-screen" just to measure it.
View usageView = getLayoutInflater().inflate(R.layout.settings_usageinfo, guideRv, false);
// Measure it with the width of the screen (or parent) to see how tall it gets
int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(getResources().getDisplayMetrics().widthPixels,
View.MeasureSpec.AT_MOST);
int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
usageView.measure(widthMeasureSpec, heightMeasureSpec);
// Apply that measured height as the minimum height for the RecyclerView
int usageHeight = usageView.getMeasuredHeight();
guideRv.setMinimumHeight(usageHeight);
PagerSnapHelper snapHelper = new PagerSnapHelper();
snapHelper.attachToRecyclerView(guideRv);
}
private void setupButtons() {
ImageButton githubicon = findViewById(R.id.githubIcon);
ImageButton stravaaccess = findViewById(R.id.stravaAccess);
ImageButton intervalsICUAccess = findViewById(R.id.intervalsICUAccess);
githubicon.setOnClickListener(v -> {
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse("https://www.github.com/spewedprojects/WorkoutRepo"));
v.getContext().startActivity(intent);
});
// Define the actions
Runnable openSheetAction = () -> {
ViewPager2 weekPager = findViewById(R.id.weekPager);
if (weekPager != null) {
int currentItem = weekPager.getCurrentItem();
int dayIndex = currentItem % 7;
String dayName = getDayNameFromIndex(dayIndex);
ActivityBottomSheet bottomSheet = new ActivityBottomSheet(dayName);
bottomSheet.show(getSupportFragmentManager(), "StravaSheet");
}
};
Runnable openArchiveAction = () -> {
startActivity(new Intent(MainActivity.this, ArchiveActivity.class));
};
View.OnClickListener clickListener = v -> {
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
boolean longClickAction = prefs.getBoolean("StravaButtonLongClickAction", true);
if (longClickAction) {
openSheetAction.run();
} else {
openArchiveAction.run();
}
};
View.OnLongClickListener longClickListener = v -> {
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
boolean longClickAction = prefs.getBoolean("StravaButtonLongClickAction", true);
if (longClickAction) {
openArchiveAction.run();
} else {
openSheetAction.run();
}
return true;
};
if (stravaaccess != null) {
stravaaccess.setOnClickListener(clickListener);
stravaaccess.setOnLongClickListener(longClickListener);
}
if (intervalsICUAccess != null) {
intervalsICUAccess.setOnClickListener(clickListener);
intervalsICUAccess.setOnLongClickListener(longClickListener);
}
updateSyncButtonsVisibility();
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
prefListener = (sharedPreferences, key) -> {
if ("EnableStravaFeature".equals(key) || "ActiveSyncSource".equals(key)) {
runOnUiThread(this::updateSyncButtonsVisibility);
}
};
prefs.registerOnSharedPreferenceChangeListener(prefListener);
ImageButton guideBtn = findViewById(R.id.guide_btn);
guideBtn.setOnClickListener(v -> {
// Check current state by ID or Progress
if (motionLayout.getCurrentState() == R.id.end_visible) {
motionLayout.transitionToStart(); // Animates to guide_hidden
} else {
motionLayout.transitionToEnd(); // Animates to guide_visible
}
});
}
private void setupWeekPager() {
// inside onCreate(...)
ViewPager2 weekPager = findViewById(R.id.weekPager);
WeekPagerAdapter adapter = new WeekPagerAdapter(this);
weekPager.setAdapter(adapter);
// Calculate current day index (0 = Monday, 6 = Sunday)
Calendar calendar = Calendar.getInstance();
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
int dayIndex = switch (dayOfWeek) {
case Calendar.MONDAY -> 0;
case Calendar.TUESDAY -> 1;
case Calendar.WEDNESDAY -> 2;
case Calendar.THURSDAY -> 3;
case Calendar.FRIDAY -> 4;
case Calendar.SATURDAY -> 5;
case Calendar.SUNDAY -> 6;
default -> 0;
};
// Start near the middle so user can swipe in both directions; align to Monday
int middle = Integer.MAX_VALUE / 2;
int startPosition = middle - (middle % 7) + dayIndex; // makes it land on index 0 (MONDAY)
weekPager.setCurrentItem(startPosition, false);
// optional: page change callback (if you want to react to page changes)
weekPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
@Override
public void onPageSelected(int position) {
super.onPageSelected(position);
// if you want to show a toast or update other UI, compute day:
int dayIndex = position % 7;
// do something if needed...
}
});
}
/**
* Set up the theme toggle buttons.
*/
private void setupThemeButtons() {
ImageButton lightButton = findViewById(R.id.btn_light);
ImageButton darkButton = findViewById(R.id.btn_dark);
ImageButton autoButton = findViewById(R.id.btn_auto);
if (lightButton == null || darkButton == null || autoButton == null) {
return;
}
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
String currentTheme = prefs.getString(THEME_KEY, "auto");
updateButtonVisibility(currentTheme, lightButton, darkButton, autoButton);
lightButton.setOnClickListener(v -> setThemeAndSave("light"));
darkButton.setOnClickListener(v -> setThemeAndSave("dark"));
autoButton.setOnClickListener(v -> setThemeAndSave("auto"));
}
/**
* Update the visibility of the theme buttons based on the current theme.
*/
private void updateButtonVisibility(String currentTheme, ImageButton lightButton, ImageButton darkButton, ImageButton autoButton) {
switch (currentTheme) {
case "light":
lightButton.setVisibility(View.GONE);
darkButton.setVisibility(View.VISIBLE);
autoButton.setVisibility(View.GONE);
System.out.println("LIGHT mode - GONE (Light button and Auto button), VISIBLE (Dark button)");
break;
case "dark":
lightButton.setVisibility(View.GONE);
darkButton.setVisibility(View.GONE);
autoButton.setVisibility(View.VISIBLE);
System.out.println("DARK mode - GONE (Light button and Dark button), VISIBLE (Auto button)");
break;
case "auto":
lightButton.setVisibility(View.VISIBLE);
darkButton.setVisibility(View.GONE);
autoButton.setVisibility(View.GONE);
System.out.println("AUTO mode - GONE (Dark button and Auto button), VISIBLE (Light button)");
break;
}
}
private String getDayNameFromIndex(int index) {
switch (index) {
case 0: return "Monday";
case 1: return "Tuesday";
case 2: return "Wednesday";
case 3: return "Thursday";
case 4: return "Friday";
case 5: return "Saturday";
case 6: return "Sunday";
default: return "Monday"; // Fallback
}
}
private void updateSyncButtonsVisibility() {
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
boolean isSyncEnabled = prefs.getBoolean("EnableStravaFeature", false);
String activeSource = prefs.getString("ActiveSyncSource", "");
ImageButton stravaaccess = findViewById(R.id.stravaAccess);
ImageButton intervalsICUAccess = findViewById(R.id.intervalsICUAccess);
if (!isSyncEnabled || activeSource.isEmpty()) {
if (stravaaccess != null) stravaaccess.setVisibility(View.GONE);
if (intervalsICUAccess != null) intervalsICUAccess.setVisibility(View.GONE);
} else if ("STRAVA".equals(activeSource)) {
if (stravaaccess != null) stravaaccess.setVisibility(View.VISIBLE);
if (intervalsICUAccess != null) intervalsICUAccess.setVisibility(View.GONE);
} else if ("INTERVALS_ICU".equals(activeSource)) {
if (stravaaccess != null) stravaaccess.setVisibility(View.GONE);
if (intervalsICUAccess != null) intervalsICUAccess.setVisibility(View.VISIBLE);
}
}
@Override
protected void onResume() {
super.onResume();
updateSyncButtonsVisibility();
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
prefListener = (sharedPreferences, key) -> {
if ("EnableStravaFeature".equals(key) || "ActiveSyncSource".equals(key)) {
runOnUiThread(this::updateSyncButtonsVisibility);
}
};
prefs.registerOnSharedPreferenceChangeListener(prefListener);
// This forces the adapter to reload data from the JSON file which might have changed if you clicked "Apply" in the Routines screen
if (findViewById(R.id.weekPager) != null) {
androidx.viewpager2.widget.ViewPager2 vp = findViewById(R.id.weekPager);
if (vp.getAdapter() != null) {
vp.getAdapter().notifyDataSetChanged();
}
}
}
@Override
protected void onPause() {
super.onPause();
// 3. Unregister to prevent leaks and redundant updates
if (prefListener != null) {
getSharedPreferences(PREFS_NAME, MODE_PRIVATE)
.unregisterOnSharedPreferenceChangeListener(prefListener);
}
}
private void setupOnBackPressed() {
// --- IMPROVED IMPLEMENTATION for double back to exit the app ---
OnBackPressedCallback callback = new OnBackPressedCallback(true /* enabled by default */) {
@Override
public void handleOnBackPressed() {
// First check if MotionLayout is expanded
if (motionLayout.getCurrentState() == R.id.end_visible) {
// Collapse it instead of exiting
motionLayout.transitionToStart();
return; // consume back press here
}
if (backPressedTime + 2000 > System.currentTimeMillis()) {
backToast.cancel();
// Call finish() to close the activity
finish();
} else {
backToast = Toast.makeText(getBaseContext(), "Press BACK again to exit", Toast.LENGTH_SHORT);
backToast.show();
}
backPressedTime = System.currentTimeMillis();
}
};
// Add the callback to the dispatcher
getOnBackPressedDispatcher().addCallback(this, callback);
}
}