-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMenuScreen.kt
More file actions
899 lines (843 loc) · 46.7 KB
/
MenuScreen.kt
File metadata and controls
899 lines (843 loc) · 46.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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
package com.google.ai.sample
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.ClickableText
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.platform.LocalUriHandler
import androidx.compose.ui.unit.sp
import android.widget.Toast
import android.Manifest // For Manifest.permission.POST_NOTIFICATIONS
import androidx.compose.material3.AlertDialog // For the rationale dialog
import androidx.compose.runtime.saveable.rememberSaveable
import android.util.Log
import android.os.Environment
import android.os.StatFs
import com.google.ai.sample.feature.multimodal.ModelDownloadManager
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.input.pointer.PointerEventPass
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.gestures.detectHorizontalDragGestures
import java.io.File
/**
* Modifier, der sicherstellt dass horizontale Touch-Events für Slider
* nicht von einer übergeordneten LazyColumn abgefangen werden.
* Behebt den Swipe-Bug wo das Wischen über Slider in LazyColumn hakelt.
*
* Konsumiert nur horizontale Drag-Events auf Main-Pass-Ebene,
* damit die LazyColumn nicht vorzeitig das Scrollen übernimmt.
* Der Slider selbst behält die volle Kontrolle über die Interaktion.
*/
fun Modifier.sliderFriendly(): Modifier = this.pointerInput(Unit) {
awaitEachGesture {
// Ersten Touch abwarten (keine Konsumation, nur beobachten)
val down = awaitFirstDown(requireUnconsumed = false)
var lastX = down.position.x
var isDraggingHorizontally = false
// Weitere Pointer-Events beobachten
do {
val event = awaitPointerEvent(pass = PointerEventPass.Main)
val change = event.changes.firstOrNull() ?: break
val dx = kotlin.math.abs(change.position.x - lastX)
val dy = kotlin.math.abs(change.position.y - change.previousPosition.y)
// Wenn horizontale Bewegung dominiert, konsumiere den Event
// damit die LazyColumn nicht vertikal scrollt
if (dx > dy || isDraggingHorizontally) {
isDraggingHorizontally = true
change.consume()
}
lastX = change.position.x
} while (event.changes.any { it.pressed })
}
}
data class MenuItem(
val routeId: String,
val titleResId: Int,
val descriptionResId: Int
)
private val STRIKETHROUGH_MODELS = listOf(
ModelOption.GEMMA_3_27B_IT,
ModelOption.MISTRAL_LARGE_3,
ModelOption.GEMINI_FLASH_LIVE_PREVIEW,
ModelOption.GEMINI_FLASH_LITE_PREVIEW,
ModelOption.QWEN3_5_4B_OFFLINE
)
@Composable
fun MenuScreen(
innerPadding: PaddingValues,
onItemClicked: (String) -> Unit = { },
onApiKeyButtonClicked: (ApiProvider?) -> Unit = { },
onDonationButtonClicked: () -> Unit = { },
isTrialExpired: Boolean = false, // New parameter to indicate trial status
isPurchased: Boolean = false
) {
val context = LocalContext.current
var showRationaleDialogForPhotoReasoning by rememberSaveable { mutableStateOf(false) }
val menuItems = listOf(
MenuItem("photo_reasoning", R.string.menu_reason_title, R.string.menu_reason_description)
)
// Get current model
val currentModel = GenerativeAiViewModelFactory.getCurrentModel()
var selectedModel by remember { mutableStateOf(currentModel) }
var expanded by remember { mutableStateOf(false) }
var showDownloadDialog by remember { mutableStateOf(false) }
var downloadDialogModel by remember { mutableStateOf<ModelOption?>(null) }
var showHumanExpertSupportDialog by remember { mutableStateOf(false) }
Column(
modifier = Modifier
.fillMaxSize()
.padding(innerPadding)
) {
LazyColumn(
modifier = Modifier.fillMaxSize()
) {
// API Key Management Button
item {
Card(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 8.dp)
) {
Row(
modifier = Modifier
.padding(all = 16.dp)
.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = "API Key Management",
style = MaterialTheme.typography.titleMedium,
modifier = Modifier.weight(1f)
)
Button(
onClick = { onApiKeyButtonClicked(null) },
enabled = true, // Always enabled
modifier = Modifier.padding(start = 8.dp)
) {
Text(text = "Change API Key")
}
}
}
}
// Model Selection
item {
Card(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 8.dp)
) {
Column(
modifier = Modifier
.padding(all = 16.dp)
.fillMaxWidth()
) {
Text(
text = "Model Selection",
style = MaterialTheme.typography.titleMedium
)
Spacer(modifier = Modifier.height(8.dp))
Text(
text = "Current model: ${selectedModel.displayName}",
style = MaterialTheme.typography.bodyMedium
)
Spacer(modifier = Modifier.height(8.dp))
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
Spacer(modifier = Modifier.weight(1f))
Button(
onClick = { expanded = true },
enabled = true // Always enabled
) {
Text("Change Model")
}
DropdownMenu(
expanded = expanded,
onDismissRequest = { expanded = false }
) {
val allModels = ModelOption.values().toList()
val vercelModels = allModels.filter {
it.apiProvider == ApiProvider.VERCEL && !STRIKETHROUGH_MODELS.contains(it)
}
val normalModels = allModels.filter {
it != ModelOption.MISTRAL_MEDIUM_3_1 &&
it.apiProvider != ApiProvider.VERCEL &&
!STRIKETHROUGH_MODELS.contains(it)
}
val orderedModels = listOf(ModelOption.MISTRAL_MEDIUM_3_1) +
normalModels +
vercelModels +
STRIKETHROUGH_MODELS
orderedModels.forEach { modelOption ->
DropdownMenuItem(
text = {
// Do not actually disable these models. They must remain selectable for testing/debug purposes.
val itemTextStyle = if (STRIKETHROUGH_MODELS.contains(modelOption)) {
MaterialTheme.typography.bodyLarge.copy(textDecoration = TextDecoration.LineThrough)
} else {
MaterialTheme.typography.bodyLarge
}
Text(
text = modelOption.displayName + (modelOption.size?.let { " - $it" } ?: ""),
style = itemTextStyle
)
},
onClick = {
expanded = false
val wasOfflineModel = selectedModel.isOfflineModel
if (modelOption.isOfflineModel) {
val isDownloaded = ModelDownloadManager.isModelDownloaded(context, modelOption)
if (!isDownloaded) {
downloadDialogModel = modelOption
showDownloadDialog = true
} else {
selectedModel = modelOption
GenerativeAiViewModelFactory.setModel(modelOption, context)
// Task 15: Initialize offline model upon selection
val mainActivity = context as? MainActivity
mainActivity?.getPhotoReasoningViewModel()?.reinitializeOfflineModel(context)
}
} else if (modelOption == ModelOption.HUMAN_EXPERT) {
if (isPurchased) {
selectedModel = modelOption
GenerativeAiViewModelFactory.setModel(modelOption, context)
if (wasOfflineModel) {
// Task 19: Close offline model to free RAM
val mainActivity = context as? MainActivity
mainActivity?.getPhotoReasoningViewModel()?.closeOfflineModel()
}
} else {
showHumanExpertSupportDialog = true
}
} else {
selectedModel = modelOption
GenerativeAiViewModelFactory.setModel(modelOption, context)
if (wasOfflineModel) {
// Task 19: Close offline model to free RAM
val mainActivity = context as? MainActivity
mainActivity?.getPhotoReasoningViewModel()?.closeOfflineModel()
}
}
},
enabled = true // Always enabled
)
}
}
}
val modelHint = when (selectedModel) {
ModelOption.GEMMA_3_27B_IT -> "Google doesn't support screenshots in the API for this model."
ModelOption.GPT_OSS_120B -> "This is a pure text model\nCerebras sometimes discontinues free access in the Free Tier, displaying an \"Error 404: gpt-oss-120b does not exist or you do not have access to it\" message, or changes the rate limits."
ModelOption.MISTRAL_LARGE_3 -> "Mistral AI rejects requests containing non-black images with a 429 Error: Rate limit exceeded response"
ModelOption.GEMINI_3_FLASH -> "Google often rejects requests to this model with a 503 Model is exhausted error"
ModelOption.PUTER_GLM5 -> "This model is expensive and uses up the free quota quickly. Consider GPT 5.4 nano"
ModelOption.GPT_5_1_CODEX_MAX,
ModelOption.GPT_5_1_CODEX_MINI,
ModelOption.GPT_5_NANO -> "Vercel requires a credit card"
else -> ""
}
if (modelHint.isNotBlank()) {
Spacer(modifier = Modifier.height(8.dp))
Text(
text = modelHint,
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
}
}
// CPU/GPU Selection - only visible when offline model is selected
if (selectedModel.isOfflineModel) {
item {
val currentBackend = remember { mutableStateOf(GenerativeAiViewModelFactory.getBackend()) }
// Load preference on first composition
androidx.compose.runtime.LaunchedEffect(Unit) {
GenerativeAiViewModelFactory.loadBackendPreference(context)
currentBackend.value = GenerativeAiViewModelFactory.getBackend()
}
Card(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 8.dp)
) {
Column(
modifier = Modifier
.padding(all = 16.dp)
.fillMaxWidth()
) {
Text(
text = "Prozessor-Auswahl (CPU / GPU)",
style = MaterialTheme.typography.titleMedium
)
Spacer(modifier = Modifier.height(8.dp))
Text(
text = "Aktuell: ${if (currentBackend.value == InferenceBackend.GPU) "GPU" else "CPU"}",
style = MaterialTheme.typography.bodyMedium
)
Spacer(modifier = Modifier.height(12.dp))
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(12.dp)
) {
Button(
onClick = {
GenerativeAiViewModelFactory.setBackend(InferenceBackend.GPU, context)
currentBackend.value = InferenceBackend.GPU
val mainActivity = context as? MainActivity
mainActivity?.getPhotoReasoningViewModel()?.closeOfflineModel()
Toast.makeText(context, "GPU selected – Model stopped. Will load on next generation", Toast.LENGTH_SHORT).show()
},
modifier = Modifier.weight(1f),
colors = if (currentBackend.value == InferenceBackend.GPU)
ButtonDefaults.buttonColors()
else
ButtonDefaults.outlinedButtonColors(),
shape = RoundedCornerShape(8.dp)
) {
Text("GPU")
}
Button(
onClick = {
GenerativeAiViewModelFactory.setBackend(InferenceBackend.CPU, context)
currentBackend.value = InferenceBackend.CPU
val mainActivity = context as? MainActivity
mainActivity?.getPhotoReasoningViewModel()?.closeOfflineModel()
Toast.makeText(context, "CPU selected – Model stopped. Will load on next generation", Toast.LENGTH_SHORT).show()
},
modifier = Modifier.weight(1f),
colors = if (currentBackend.value == InferenceBackend.CPU)
ButtonDefaults.buttonColors()
else
ButtonDefaults.outlinedButtonColors(),
shape = RoundedCornerShape(8.dp)
) {
Text("CPU")
}
}
Spacer(modifier = Modifier.height(12.dp))
Text(
text = "Models on the GPU require a lot of RAM, and ZRAM should be disabled, but they are faster and still consume significantly less power than on the CPU. " +
"The language model cannot use RAM swap with the GPU. However, for the stability of your phone, you should still use memory RAM swap. " +
"For models on the CPU, a cache file is written once and quickly available again, but in addition, it permanently uses half of the language model as memory consumption.",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
}
}
// Generation Settings (TopK, TopP, Temperature) for current model
if (selectedModel.supportsGenerationSettings) {
item {
val genSettings = remember(selectedModel) {
mutableStateOf(
com.google.ai.sample.util.GenerationSettingsPreferences.loadSettings(
context, selectedModel.modelName
)
)
}
var tempSlider by remember(selectedModel) { mutableStateOf(genSettings.value.temperature) }
var topPSlider by remember(selectedModel) { mutableStateOf(genSettings.value.topP) }
var topKSlider by remember(selectedModel) { mutableStateOf(genSettings.value.topK.toFloat()) }
Card(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 8.dp)
) {
Column(
modifier = Modifier
.padding(all = 16.dp)
.fillMaxWidth()
) {
Text(
text = "Generation Settings (${selectedModel.displayName})",
style = MaterialTheme.typography.titleMedium
)
Spacer(modifier = Modifier.height(12.dp))
// Temperature Slider (0.0 - 2.0)
Text(
text = "Temperature: ${"%.2f".format(tempSlider)}",
style = MaterialTheme.typography.bodyMedium
)
androidx.compose.material3.Slider(
value = tempSlider,
onValueChange = { newVal ->
tempSlider = newVal
},
onValueChangeFinished = {
genSettings.value = genSettings.value.copy(temperature = tempSlider)
com.google.ai.sample.util.GenerationSettingsPreferences.saveSettings(
context, selectedModel.modelName, genSettings.value
)
},
valueRange = 0f..2f,
steps = 0,
modifier = Modifier.fillMaxWidth().sliderFriendly()
)
Spacer(modifier = Modifier.height(8.dp))
// TopP Slider (0.0 - 1.0)
Text(
text = "Top P: ${"%.2f".format(topPSlider)}",
style = MaterialTheme.typography.bodyMedium
)
androidx.compose.material3.Slider(
value = topPSlider,
onValueChange = { newVal ->
topPSlider = newVal
},
onValueChangeFinished = {
genSettings.value = genSettings.value.copy(topP = topPSlider)
com.google.ai.sample.util.GenerationSettingsPreferences.saveSettings(
context, selectedModel.modelName, genSettings.value
)
},
valueRange = 0f..1f,
steps = 0,
modifier = Modifier.fillMaxWidth().sliderFriendly()
)
Spacer(modifier = Modifier.height(8.dp))
// TopK Slider (0 - 100)
Text(
text = "Top K: ${Math.round(topKSlider)}",
style = MaterialTheme.typography.bodyMedium
)
androidx.compose.material3.Slider(
value = topKSlider,
onValueChange = { newVal ->
topKSlider = newVal
},
onValueChangeFinished = {
genSettings.value = genSettings.value.copy(topK = Math.round(topKSlider))
com.google.ai.sample.util.GenerationSettingsPreferences.saveSettings(
context, selectedModel.modelName, genSettings.value
)
},
valueRange = 0f..100f,
steps = 0,
modifier = Modifier.fillMaxWidth().sliderFriendly()
)
if (selectedModel.isOfflineModel) {
Spacer(modifier = Modifier.height(4.dp))
Text(
text = "Note: Offline inference may not support all generation parameters.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
}
}
}
// Menu Items
items(menuItems) { menuItem ->
Card(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 8.dp)
) {
Column(
modifier = Modifier
.padding(all = 16.dp)
.fillMaxWidth()
) {
Text(
text = if (menuItem.routeId == "photo_reasoning" && selectedModel == ModelOption.HUMAN_EXPERT) "Operate with human expert" else stringResource(menuItem.titleResId),
style = MaterialTheme.typography.titleMedium
)
Text(
text = if (menuItem.routeId == "photo_reasoning" && selectedModel == ModelOption.HUMAN_EXPERT) "A human expert uses screen mirroring and operates with tap's" else stringResource(menuItem.descriptionResId),
style = MaterialTheme.typography.bodyMedium,
modifier = Modifier.padding(top = 8.dp)
)
TextButton(
onClick = {
if (isTrialExpired) {
Toast.makeText(context, "Please support the development of the app so that you can continue using it \uD83C\uDF89", Toast.LENGTH_LONG).show()
} else {
if (menuItem.routeId == "photo_reasoning") {
val mainActivity = context as? MainActivity
val activeModel = GenerativeAiViewModelFactory.getCurrentModel()
// Check API Key for online models
if (!activeModel.isOfflineModel && activeModel != ModelOption.HUMAN_EXPERT) {
val apiKey = mainActivity?.getCurrentApiKey(activeModel.apiProvider)
if (apiKey.isNullOrEmpty()) {
// Show API Key Dialog
onApiKeyButtonClicked(activeModel.apiProvider) // Or a specific callback to show dialog
return@TextButton
}
}
if (mainActivity != null) { // Ensure mainActivity is not null
if (!mainActivity.isNotificationPermissionGranted()) {
Log.d("MenuScreen", "Notification permission NOT granted.")
if (mainActivity.shouldShowRequestPermissionRationale(Manifest.permission.POST_NOTIFICATIONS) && !mainActivity.hasShownNotificationRationale()) {
Log.d("MenuScreen", "Showing notification rationale dialog.")
showRationaleDialogForPhotoReasoning = true
// onItemClicked will be called from dialog
} else {
Log.d("MenuScreen", "Rationale not needed or already handled. Requesting permission directly.")
// mainActivity.requestNotificationPermission()
onItemClicked(menuItem.routeId) // Proceed to navigate
}
} else {
Log.d("MenuScreen", "Notification permission ALREADY granted.")
onItemClicked(menuItem.routeId) // Proceed to navigate
}
} else {
Log.e("MenuScreen", "MainActivity instance is null. Cannot check/request permission.")
onItemClicked(menuItem.routeId) // Proceed to navigate anyway
}
} else {
// For other menu items, navigate directly
onItemClicked(menuItem.routeId)
}
}
},
enabled = !isTrialExpired, // Disable button if trial is expired
modifier = Modifier.align(Alignment.End)
) {
Text(text = stringResource(R.string.action_try))
}
}
}
}
// Donation Button Card (Should always be enabled)
item {
Card(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 8.dp)
) {
Row(
modifier = Modifier
.padding(all = 16.dp)
.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
if (isPurchased) {
Text(
text = "Thank you for supporting the development! 🎉💛",
style = MaterialTheme.typography.titleMedium,
modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp),
textAlign = TextAlign.Center
)
} else {
Text(
text = "Support Improvements\n \uD83C\uDF89",
style = MaterialTheme.typography.titleMedium,
modifier = Modifier.weight(1f)
)
Button(
onClick = onDonationButtonClicked,
modifier = Modifier.padding(start = 8.dp)
) {
Text(text = "Pro (2,90 €/Month)")
}
}
}
}
}
item {
Card(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 8.dp)
) {
val boldStyle = SpanStyle(fontWeight = FontWeight.Bold)
val annotatedText = buildAnnotatedString {
append("• ")
withStyle(boldStyle) { append("Preview Models") }
append(" could be deactivated by Google without being handed over to the final release.\n")
append("• ")
withStyle(boldStyle) { append("API Keys") }
append(" are automatically switched if multiple are inserted and one is exhausted.\n")
append("• Models with a line through them do not work properly.\n")
append("• GPT models (")
withStyle(boldStyle) { append("Vercel") }
append(") have a free budget of \$5 per month and a credit card is necessary.\n")
append("GPT-5.1 Input: \$1.25/M Output: \$10.00/M\n")
append("GPT-5.1 mini Input: \$0.25/M Output: \$2.00/M\n")
append("GPT-5 nano Input: \$0.05/M Output: \$0.40/M\n")
append("• When a language model repeats a token, Top K and Top P must be lowered.\n")
append("• Google has recently significantly tightened its rate limits and is fluctuating widely with its free quota. Try it for yourself. More information is available at ")
pushStringAnnotation(tag = "URL", annotation = "https://aistudio.google.com/rate-limit")
withStyle(style = SpanStyle(color = MaterialTheme.colorScheme.primary, textDecoration = TextDecoration.Underline)) {
append("https://aistudio.google.com/rate-limit")
}
pop()
}
val uriHandler = LocalUriHandler.current
ClickableText(
text = annotatedText,
modifier = Modifier
.fillMaxWidth()
.padding(all = 16.dp),
style = MaterialTheme.typography.bodyMedium.copy(
fontSize = 15.sp,
color = MaterialTheme.colorScheme.onSurface
),
onClick = { offset ->
// Allow clicking links even if trial is expired
annotatedText.getStringAnnotations(tag = "URL", start = offset, end = offset)
.firstOrNull()?.let { annotation ->
uriHandler.openUri(annotation.item)
}
}
)
}
}
}
}
if (showRationaleDialogForPhotoReasoning) {
val mainActivity = LocalContext.current as? MainActivity
AlertDialog(
onDismissRequest = {
showRationaleDialogForPhotoReasoning = false
// If dismissed, still proceed to the item, permission will be asked by OS if needed later by other flows, or user can try again.
// Or, we can choose not to navigate if they dismiss. For now, let's navigate.
mainActivity?.let { onItemClicked("photo_reasoning") }
},
title = { Text("Notification Permission") },
text = { Text("You can grant notification permission if you want to be able to stop Screen Operator via notifications.") },
confirmButton = {
TextButton(
onClick = {
Log.d("MenuScreen", "Rationale dialog OK clicked.")
showRationaleDialogForPhotoReasoning = false
mainActivity?.setNotificationRationaleShown(true)
Log.d("MenuScreen", "Requesting notification permission from rationale dialog.")
// mainActivity?.requestNotificationPermission()
// Log after to see if it's called immediately or if requestNotificationPermission is suspending (it's not)
Log.d("MenuScreen", "Navigating to photo_reasoning after rationale OK.")
mainActivity?.let { onItemClicked("photo_reasoning") }
}
) { Text("OK") }
},
dismissButton = {
TextButton(
onClick = {
Log.d("MenuScreen", "Rationale dialog Cancel clicked or dismissed.")
showRationaleDialogForPhotoReasoning = false
Log.d("MenuScreen", "Navigating to photo_reasoning after rationale cancel/dismiss.")
mainActivity?.let { onItemClicked("photo_reasoning") }
}
) { Text("Cancel") }
}
)
}
if (showDownloadDialog && downloadDialogModel != null) {
val statFs = StatFs(Environment.getExternalStorageDirectory().path)
val bytesAvailable = statFs.availableBlocksLong * statFs.blockSizeLong
val gbAvailable = bytesAvailable.toDouble() / (1024 * 1024 * 1024)
val formattedGbAvailable = String.format("%.2f", gbAvailable)
val dlState by ModelDownloadManager.downloadState.collectAsState()
AlertDialog(
onDismissRequest = {
if (dlState is ModelDownloadManager.DownloadState.Idle || dlState is ModelDownloadManager.DownloadState.Completed || dlState is ModelDownloadManager.DownloadState.Error) {
showDownloadDialog = false
}
// Don't dismiss while downloading/paused
},
title = { Text("Download Model (${downloadDialogModel?.size ?: "unknown size"})") },
text = {
Column {
when (val state = dlState) {
is ModelDownloadManager.DownloadState.Idle -> {
Text("Should ${downloadDialogModel?.displayName ?: "this model"} be downloaded?\n\n$formattedGbAvailable GB of storage available.")
}
is ModelDownloadManager.DownloadState.Downloading -> {
Text("Downloading...")
Spacer(modifier = Modifier.height(8.dp))
androidx.compose.material3.LinearProgressIndicator(
progress = { state.progress },
modifier = Modifier.fillMaxWidth()
)
Spacer(modifier = Modifier.height(4.dp))
Text(
text = "${ModelDownloadManager.formatBytes(state.bytesDownloaded)} / ${if (state.totalBytes > 0) ModelDownloadManager.formatBytes(state.totalBytes) else "?"}",
style = MaterialTheme.typography.bodySmall
)
Text(
text = "${"%.1f".format(state.progress * 100)}%",
style = MaterialTheme.typography.bodySmall
)
}
is ModelDownloadManager.DownloadState.Paused -> {
Text("Download paused.")
Spacer(modifier = Modifier.height(8.dp))
val progress = if (state.totalBytes > 0) state.bytesDownloaded.toFloat() / state.totalBytes else 0f
androidx.compose.material3.LinearProgressIndicator(
progress = { progress },
modifier = Modifier.fillMaxWidth()
)
Spacer(modifier = Modifier.height(4.dp))
Text(
text = "${ModelDownloadManager.formatBytes(state.bytesDownloaded)} / ${if (state.totalBytes > 0) ModelDownloadManager.formatBytes(state.totalBytes) else "?"}",
style = MaterialTheme.typography.bodySmall
)
}
is ModelDownloadManager.DownloadState.Completed -> {
Text("Download complete! ✅")
}
is ModelDownloadManager.DownloadState.Error -> {
Text("Error: ${state.message}")
}
}
}
},
confirmButton = {
when (dlState) {
is ModelDownloadManager.DownloadState.Idle -> {
TextButton(
onClick = {
downloadDialogModel?.let { model ->
model.downloadUrl?.let { url ->
ModelDownloadManager.downloadModel(context, model, url)
}
// Task 2: Request notification permission when download starts
val mainActivity = context as? MainActivity
if (mainActivity != null && !mainActivity.isNotificationPermissionGranted()) {
mainActivity.requestNotificationPermission()
}
}
}
) { Text("Download") }
}
is ModelDownloadManager.DownloadState.Downloading -> {
TextButton(onClick = { ModelDownloadManager.pauseDownload() }) { Text("Pause") }
}
is ModelDownloadManager.DownloadState.Paused -> {
TextButton(
onClick = {
downloadDialogModel?.let { model ->
model.downloadUrl?.let { url ->
ModelDownloadManager.resumeDownload(context, model, url)
}
}
}
) { Text("Resume") }
}
is ModelDownloadManager.DownloadState.Completed -> {
TextButton(onClick = {
// Set model only after download is completed (Point 17)
downloadDialogModel?.let {
selectedModel = it
GenerativeAiViewModelFactory.setModel(it, context)
}
showDownloadDialog = false
}) { Text("Close") }
}
is ModelDownloadManager.DownloadState.Error -> {
TextButton(
onClick = {
downloadDialogModel?.let { model ->
model.downloadUrl?.let { url ->
ModelDownloadManager.downloadModel(context, model, url)
}
}
}
) { Text("Retry") }
}
}
},
dismissButton = {
when (dlState) {
is ModelDownloadManager.DownloadState.Idle -> {
TextButton(onClick = { showDownloadDialog = false }) { Text("Cancel") }
}
is ModelDownloadManager.DownloadState.Downloading,
is ModelDownloadManager.DownloadState.Paused -> {
TextButton(
onClick = {
downloadDialogModel?.let { ModelDownloadManager.cancelDownload(context, it) }
showDownloadDialog = false
}
) { Text("Cancel Download") }
}
is ModelDownloadManager.DownloadState.Completed -> { /* No dismiss button */ }
is ModelDownloadManager.DownloadState.Error -> {
TextButton(onClick = { showDownloadDialog = false }) { Text("Close") }
}
}
}
)
}
// Human Expert Support Dialog (Task 4)
if (showHumanExpertSupportDialog) {
AlertDialog(
onDismissRequest = { showHumanExpertSupportDialog = false },
title = { Text("Human Expert") },
text = {
Text("To ensure that a human expert accepts the task, please support the expert.")
},
confirmButton = {
Button(
onClick = {
showHumanExpertSupportDialog = false
onDonationButtonClicked()
}
) {
Text("Support \uD83C\uDF89")
}
},
dismissButton = {
TextButton(onClick = { showHumanExpertSupportDialog = false }) {
Text("Cancel")
}
}
)
}
}
@Preview(showSystemUi = true)
@Composable
fun MenuScreenPreview() {
// Preview with trial not expired
MenuScreen(innerPadding = PaddingValues(), isTrialExpired = false, isPurchased = false)
}
@Preview(showSystemUi = true)
@Composable
fun MenuScreenPurchasedPreview() {
MenuScreen(innerPadding = PaddingValues(), isTrialExpired = false, isPurchased = true)
}
@Preview(showSystemUi = true)
@Composable
fun MenuScreenTrialExpiredPreview() {
// Preview with trial expired
MenuScreen(innerPadding = PaddingValues(), isTrialExpired = true, isPurchased = false)
}