forked from neobrain/citra
/
EmulationFragment.kt
1077 lines (932 loc) · 38.2 KB
/
EmulationFragment.kt
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
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2023 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
package org.citra.citra_emu.fragments
import android.annotation.SuppressLint
import android.content.Context
import android.content.DialogInterface
import android.content.SharedPreferences
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import android.view.Choreographer
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.Surface
import android.view.SurfaceHolder
import android.view.View
import android.view.ViewGroup
import android.widget.PopupMenu
import android.widget.TextView
import android.widget.Toast
import androidx.activity.OnBackPressedCallback
import androidx.core.content.res.ResourcesCompat
import androidx.core.graphics.Insets
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.drawerlayout.widget.DrawerLayout.DrawerListener
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.navigation.findNavController
import androidx.navigation.fragment.navArgs
import androidx.preference.PreferenceManager
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.slider.Slider
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import org.citra.citra_emu.CitraApplication
import org.citra.citra_emu.EmulationNavigationDirections
import org.citra.citra_emu.NativeLibrary
import org.citra.citra_emu.R
import org.citra.citra_emu.activities.EmulationActivity
import org.citra.citra_emu.databinding.DialogCheckboxBinding
import org.citra.citra_emu.databinding.DialogSliderBinding
import org.citra.citra_emu.databinding.FragmentEmulationBinding
import org.citra.citra_emu.display.ScreenAdjustmentUtil
import org.citra.citra_emu.display.ScreenLayout
import org.citra.citra_emu.features.settings.model.SettingsViewModel
import org.citra.citra_emu.features.settings.ui.SettingsActivity
import org.citra.citra_emu.features.settings.utils.SettingsFile
import org.citra.citra_emu.model.Game
import org.citra.citra_emu.utils.DirectoryInitialization
import org.citra.citra_emu.utils.DirectoryInitialization.DirectoryInitializationState
import org.citra.citra_emu.utils.EmulationLifecycleUtil
import org.citra.citra_emu.utils.EmulationMenuSettings
import org.citra.citra_emu.utils.FileUtil
import org.citra.citra_emu.utils.GameHelper
import org.citra.citra_emu.utils.GameIconUtils
import org.citra.citra_emu.utils.Log
import org.citra.citra_emu.utils.ViewUtils
import org.citra.citra_emu.viewmodel.EmulationViewModel
// -- leia --
import org.citra.citra_emu.LeiaHelper3D
import org.citra.citra_emu.LeiaSurfaceView;
class EmulationFragment : Fragment(), SurfaceHolder.Callback, Choreographer.FrameCallback {
private val preferences: SharedPreferences
get() = PreferenceManager.getDefaultSharedPreferences(CitraApplication.appContext)
private lateinit var emulationState: EmulationState
private var perfStatsUpdater: Runnable? = null
private lateinit var emulationActivity: EmulationActivity
private lateinit var leiaSurfaceView: LeiaSurfaceView
private var _binding: FragmentEmulationBinding? = null
private val binding get() = _binding!!
private val args by navArgs<EmulationFragmentArgs>()
private lateinit var game: Game
private lateinit var screenAdjustmentUtil: ScreenAdjustmentUtil
private val emulationViewModel: EmulationViewModel by activityViewModels()
private val settingsViewModel: SettingsViewModel by viewModels()
override fun onAttach(context: Context) {
super.onAttach(context)
if (context is EmulationActivity) {
emulationActivity = context
NativeLibrary.setEmulationActivity(context)
} else {
throw IllegalStateException("EmulationFragment must have EmulationActivity parent")
}
}
/**
* Initialize anything that doesn't depend on the layout / views in here.
*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val intent = requireActivity().intent
val intentUri: Uri? = intent.data
val oldIntentInfo = Pair(
intent.getStringExtra("SelectedGame"),
intent.getStringExtra("SelectedTitle")
)
var intentGame: Game? = null
if (intentUri != null) {
intentGame = if (Game.extensions.contains(FileUtil.getExtension(intentUri))) {
GameHelper.getGame(intentUri, isInstalled = false, addedToLibrary = false)
} else {
null
}
} else if (oldIntentInfo.first != null) {
val gameUri = Uri.parse(oldIntentInfo.first)
intentGame = if (Game.extensions.contains(FileUtil.getExtension(gameUri))) {
GameHelper.getGame(gameUri, isInstalled = false, addedToLibrary = false)
} else {
null
}
}
try {
game = args.game ?: intentGame!!
} catch (e: NullPointerException) {
Toast.makeText(
requireContext(),
R.string.no_game_present,
Toast.LENGTH_SHORT
).show()
requireActivity().finish()
return
}
// So this fragment doesn't restart on configuration changes; i.e. rotation.
retainInstance = true
emulationState = EmulationState(game.path)
emulationActivity = requireActivity() as EmulationActivity
screenAdjustmentUtil = ScreenAdjustmentUtil(emulationActivity.windowManager, settingsViewModel.settings)
EmulationLifecycleUtil.addShutdownHook(hook = { emulationState.stop() })
EmulationLifecycleUtil.addPauseResumeHook(hook = { togglePause() })
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentEmulationBinding.inflate(inflater)
return binding.root
}
// This is using the correct scope, lint is just acting up
@SuppressLint("UnsafeRepeatOnLifecycleDetector")
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
if (requireActivity().isFinishing) {
return
}
val sL = LeiaHelper3D.SurfaceListener{ surface ->
Log.debug("SurfaceListener onSurfaceChanged called") // Log debug warning
emulationState.newSurface(surface)
}
binding.surfaceEmulation.setSurfaceListener(sL)
/*try{
binding.surfaceEmulation.holder.addCallback(this);
}catch(e: Exception){
Log.debug("SurfaceListener error: $e") // Log debug warning
}*/
binding.doneControlConfig.setOnClickListener {
binding.doneControlConfig.visibility = View.GONE
binding.surfaceInputOverlay.setIsInEditMode(false)
}
// Show/hide the "Show FPS" overlay
updateShowFpsOverlay()
binding.drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
binding.drawerLayout.addDrawerListener(object : DrawerListener {
override fun onDrawerSlide(drawerView: View, slideOffset: Float) {
binding.surfaceInputOverlay.dispatchTouchEvent(
MotionEvent.obtain(
SystemClock.uptimeMillis(),
SystemClock.uptimeMillis() + 100,
MotionEvent.ACTION_UP,
0f,
0f,
0
)
)
}
override fun onDrawerOpened(drawerView: View) {
binding.drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED)
}
override fun onDrawerClosed(drawerView: View) {
binding.drawerLayout.setDrawerLockMode(EmulationMenuSettings.drawerLockMode)
}
override fun onDrawerStateChanged(newState: Int) {
// No op
}
})
binding.inGameMenu.menu.findItem(R.id.menu_lock_drawer).apply {
val titleId = if (EmulationMenuSettings.drawerLockMode == DrawerLayout.LOCK_MODE_LOCKED_CLOSED) {
R.string.unlock_drawer
} else {
R.string.lock_drawer
}
val iconId = if (EmulationMenuSettings.drawerLockMode == DrawerLayout.LOCK_MODE_UNLOCKED) {
R.drawable.ic_unlocked
} else {
R.drawable.ic_lock
}
title = getString(titleId)
icon = ResourcesCompat.getDrawable(
resources,
iconId,
requireContext().theme
)
}
binding.inGameMenu.getHeaderView(0).findViewById<TextView>(R.id.text_game_title).text =
game.title
binding.inGameMenu.setNavigationItemSelectedListener {
when (it.itemId) {
R.id.menu_emulation_pause -> {
LeiaHelper3D.update3dMode(binding.surfaceEmulation, !emulationState.isPaused, !emulationState.isPaused)
if (emulationState.isPaused) {
emulationState.unpause()
it.title = resources.getString(R.string.pause_emulation)
it.icon = ResourcesCompat.getDrawable(
resources,
R.drawable.ic_pause,
requireContext().theme
)
} else {
emulationState.pause()
it.title = resources.getString(R.string.resume_emulation)
it.icon = ResourcesCompat.getDrawable(
resources,
R.drawable.ic_play,
requireContext().theme
)
}
true
}
R.id.menu_emulation_savestates -> {
showSavestateMenu()
true
}
R.id.menu_overlay_options -> {
showOverlayMenu()
true
}
R.id.menu_amiibo -> {
showAmiiboMenu()
true
}
R.id.menu_landscape_screen_layout -> {
showScreenLayoutMenu()
true
}
R.id.menu_swap_screens -> {
screenAdjustmentUtil.swapScreen()
true
}
R.id.menu_lock_drawer -> {
when (EmulationMenuSettings.drawerLockMode) {
DrawerLayout.LOCK_MODE_UNLOCKED -> {
EmulationMenuSettings.drawerLockMode =
DrawerLayout.LOCK_MODE_LOCKED_CLOSED
it.title = resources.getString(R.string.unlock_drawer)
it.icon = ResourcesCompat.getDrawable(
resources,
R.drawable.ic_lock,
requireContext().theme
)
}
DrawerLayout.LOCK_MODE_LOCKED_CLOSED -> {
EmulationMenuSettings.drawerLockMode = DrawerLayout.LOCK_MODE_UNLOCKED
it.title = resources.getString(R.string.lock_drawer)
it.icon = ResourcesCompat.getDrawable(
resources,
R.drawable.ic_unlocked,
requireContext().theme
)
}
}
true
}
R.id.menu_cheats -> {
val action = EmulationNavigationDirections
.actionGlobalCheatsActivity(NativeLibrary.getRunningTitleId())
binding.root.findNavController().navigate(action)
true
}
R.id.menu_settings -> {
SettingsActivity.launch(
requireContext(),
SettingsFile.FILE_NAME_CONFIG,
""
)
true
}
R.id.menu_exit -> {
NativeLibrary.pauseEmulation()
MaterialAlertDialogBuilder(requireContext())
.setTitle(R.string.emulation_close_game)
.setMessage(R.string.emulation_close_game_message)
.setPositiveButton(android.R.string.ok) { _: DialogInterface?, _: Int ->
EmulationLifecycleUtil.closeGame()
}
.setNegativeButton(android.R.string.cancel) { _: DialogInterface?, _: Int ->
NativeLibrary.unPauseEmulation()
}
.setOnCancelListener { NativeLibrary.unPauseEmulation() }
.show()
true
}
else -> true
}
}
requireActivity().onBackPressedDispatcher.addCallback(
viewLifecycleOwner,
object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
if (!emulationViewModel.emulationStarted.value) {
return
}
LeiaHelper3D.update3dMode(binding.surfaceEmulation, false, false)
if (binding.drawerLayout.isOpen) {
binding.drawerLayout.close()
} else {
binding.drawerLayout.open()
}
}
}
)
GameIconUtils.loadGameIcon(requireActivity(), game, binding.loadingImage)
binding.loadingTitle.text = game.title
viewLifecycleOwner.lifecycleScope.apply {
launch {
repeatOnLifecycle(Lifecycle.State.CREATED) {
emulationViewModel.shaderProgress.collectLatest {
if (it > 0 && it != emulationViewModel.totalShaders.value) {
binding.loadingProgressIndicator.isIndeterminate = false
binding.loadingProgressText.visibility = View.VISIBLE
binding.loadingProgressText.text = String.format(
"%d/%d",
emulationViewModel.shaderProgress.value,
emulationViewModel.totalShaders.value
)
if (it < binding.loadingProgressIndicator.max) {
binding.loadingProgressIndicator.progress = it
}
}
if (it == emulationViewModel.totalShaders.value) {
binding.loadingText.setText(R.string.loading)
binding.loadingProgressIndicator.isIndeterminate = true
binding.loadingProgressText.visibility = View.GONE
}
}
}
}
launch {
repeatOnLifecycle(Lifecycle.State.CREATED) {
emulationViewModel.totalShaders.collectLatest {
binding.loadingProgressIndicator.max = it
}
}
}
launch {
repeatOnLifecycle(Lifecycle.State.CREATED) {
emulationViewModel.shaderMessage.collectLatest {
if (it != "") {
binding.loadingText.text = it
}
}
}
}
launch {
repeatOnLifecycle(Lifecycle.State.CREATED) {
emulationViewModel.emulationStarted.collectLatest { started ->
if (started) {
ViewUtils.hideView(binding.loadingIndicator)
ViewUtils.showView(binding.surfaceInputOverlay)
binding.inGameMenu.menu.findItem(R.id.menu_emulation_savestates)
.setVisible(NativeLibrary.getSavestateInfo() != null)
binding.drawerLayout.setDrawerLockMode(EmulationMenuSettings.drawerLockMode)
}
}
}
}
}
setInsets()
}
private fun togglePause() {
if(emulationState.isPaused) {
emulationState.unpause()
} else {
emulationState.pause()
}
}
override fun onResume() {
super.onResume()
LeiaHelper3D.update3dMode(binding.surfaceEmulation, true, true)
Choreographer.getInstance().postFrameCallback(this)
if (NativeLibrary.isRunning()) {
NativeLibrary.unPauseEmulation()
return
}
if (DirectoryInitialization.areCitraDirectoriesReady()) {
emulationState.run(emulationActivity.isActivityRecreated)
} else {
setupCitraDirectoriesThenStartEmulation()
}
}
override fun onPause() {
LeiaHelper3D.update3dMode(binding.surfaceEmulation, false, false)
if (NativeLibrary.isRunning()) {
emulationState.pause()
}
Choreographer.getInstance().removeFrameCallback(this)
super.onPause()
}
override fun onDetach() {
NativeLibrary.clearEmulationActivity()
super.onDetach()
}
private fun setupCitraDirectoriesThenStartEmulation() {
val directoryInitializationState = DirectoryInitialization.start()
if (directoryInitializationState ===
DirectoryInitializationState.CITRA_DIRECTORIES_INITIALIZED
) {
emulationState.run(emulationActivity.isActivityRecreated)
} else if (directoryInitializationState ===
DirectoryInitializationState.EXTERNAL_STORAGE_PERMISSION_NEEDED
) {
Toast.makeText(context, R.string.write_permission_needed, Toast.LENGTH_SHORT)
.show()
} else if (directoryInitializationState ===
DirectoryInitializationState.CANT_FIND_EXTERNAL_STORAGE
) {
Toast.makeText(
context,
R.string.external_storage_not_mounted,
Toast.LENGTH_SHORT
).show()
}
}
private fun showSavestateMenu() {
val popupMenu = PopupMenu(
requireContext(),
binding.inGameMenu.findViewById(R.id.menu_emulation_savestates)
)
popupMenu.menuInflater.inflate(R.menu.menu_savestates, popupMenu.menu)
popupMenu.setOnMenuItemClickListener {
when (it.itemId) {
R.id.menu_emulation_save_state -> {
showSaveStateSubmenu()
true
}
R.id.menu_emulation_load_state -> {
showLoadStateSubmenu()
true
}
else -> true
}
}
popupMenu.show()
}
private fun showSaveStateSubmenu() {
val savestates = NativeLibrary.getSavestateInfo()
val popupMenu = PopupMenu(
requireContext(),
binding.inGameMenu.findViewById(R.id.menu_emulation_savestates)
)
popupMenu.menu.apply {
for (i in 0 until NativeLibrary.SAVESTATE_SLOT_COUNT) {
val slot = i + 1
val text = getString(R.string.emulation_empty_state_slot, slot)
add(text).setEnabled(true).setOnMenuItemClickListener {
displaySavestateWarning()
NativeLibrary.saveState(slot)
true
}
}
}
savestates?.forEach {
val text = getString(R.string.emulation_occupied_state_slot, it.slot, it.time)
popupMenu.menu.getItem(it.slot - 1).setTitle(text)
}
popupMenu.show()
}
private fun showLoadStateSubmenu() {
val savestates = NativeLibrary.getSavestateInfo()
val popupMenu = PopupMenu(
requireContext(),
binding.inGameMenu.findViewById(R.id.menu_emulation_savestates)
)
popupMenu.menu.apply {
for (i in 0 until NativeLibrary.SAVESTATE_SLOT_COUNT) {
val slot = i + 1
val text = getString(R.string.emulation_empty_state_slot, slot)
add(text).setEnabled(false).setOnMenuItemClickListener {
NativeLibrary.loadState(slot)
true
}
}
}
savestates?.forEach {
val text = getString(R.string.emulation_occupied_state_slot, it.slot, it.time)
popupMenu.menu.getItem(it.slot - 1).setTitle(text).setEnabled(true)
}
popupMenu.show()
}
private fun displaySavestateWarning() {
if (preferences.getBoolean("savestateWarningShown", false)) {
return
}
val dialogCheckboxBinding = DialogCheckboxBinding.inflate(layoutInflater)
MaterialAlertDialogBuilder(requireContext())
.setTitle(R.string.savestates)
.setMessage(R.string.savestate_warning_message)
.setView(dialogCheckboxBinding.root)
.setPositiveButton(android.R.string.ok) { _: DialogInterface?, _: Int ->
preferences.edit()
.putBoolean("savestateWarningShown", dialogCheckboxBinding.checkBox.isChecked)
.apply()
}
.show()
}
private fun showOverlayMenu() {
val popupMenu = PopupMenu(
requireContext(),
binding.inGameMenu.findViewById(R.id.menu_overlay_options)
)
popupMenu.menuInflater.inflate(R.menu.menu_overlay_options, popupMenu.menu)
popupMenu.menu.apply {
findItem(R.id.menu_show_overlay).isChecked = EmulationMenuSettings.showOverlay
findItem(R.id.menu_show_fps).isChecked = EmulationMenuSettings.showFps
findItem(R.id.menu_emulation_joystick_rel_center).isChecked =
EmulationMenuSettings.joystickRelCenter
findItem(R.id.menu_emulation_dpad_slide_enable).isChecked =
EmulationMenuSettings.dpadSlide
}
popupMenu.setOnMenuItemClickListener {
when (it.itemId) {
R.id.menu_show_overlay -> {
EmulationMenuSettings.showOverlay = !EmulationMenuSettings.showOverlay
binding.surfaceInputOverlay.refreshControls()
true
}
R.id.menu_show_fps -> {
EmulationMenuSettings.showFps = !EmulationMenuSettings.showFps
updateShowFpsOverlay()
true
}
R.id.menu_emulation_edit_layout -> {
editControlsPlacement()
binding.drawerLayout.close()
true
}
R.id.menu_emulation_toggle_controls -> {
showToggleControlsDialog()
true
}
R.id.menu_emulation_adjust_scale -> {
showAdjustScaleDialog()
true
}
R.id.menu_emulation_joystick_rel_center -> {
EmulationMenuSettings.joystickRelCenter =
!EmulationMenuSettings.joystickRelCenter
true
}
R.id.menu_emulation_dpad_slide_enable -> {
EmulationMenuSettings.dpadSlide = !EmulationMenuSettings.dpadSlide
true
}
R.id.menu_emulation_reset_overlay -> {
showResetOverlayDialog()
true
}
else -> true
}
}
popupMenu.show()
}
private fun showAmiiboMenu() {
val popupMenu = PopupMenu(
requireContext(),
binding.inGameMenu.findViewById(R.id.menu_amiibo)
)
popupMenu.menuInflater.inflate(R.menu.menu_amiibo_options, popupMenu.menu)
popupMenu.setOnMenuItemClickListener {
when (it.itemId) {
R.id.menu_emulation_amiibo_load -> {
emulationActivity.openFileLauncher.launch(false)
true
}
R.id.menu_emulation_amiibo_remove -> {
NativeLibrary.removeAmiibo()
true
}
else -> true
}
}
popupMenu.show()
}
private fun showScreenLayoutMenu() {
val popupMenu = PopupMenu(
requireContext(),
binding.inGameMenu.findViewById(R.id.menu_landscape_screen_layout)
)
popupMenu.menuInflater.inflate(R.menu.menu_landscape_screen_layout, popupMenu.menu)
val layoutOptionMenuItem = when (EmulationMenuSettings.landscapeScreenLayout) {
ScreenLayout.SINGLE_SCREEN.int ->
R.id.menu_screen_layout_single
ScreenLayout.SIDE_SCREEN.int ->
R.id.menu_screen_layout_sidebyside
ScreenLayout.MOBILE_PORTRAIT.int ->
R.id.menu_screen_layout_portrait
ScreenLayout.HYBRID_SCREEN.int ->
R.id.menu_screen_layout_hybrid
else -> R.id.menu_screen_layout_landscape
}
popupMenu.menu.findItem(layoutOptionMenuItem).setChecked(true)
popupMenu.setOnMenuItemClickListener {
when (it.itemId) {
R.id.menu_screen_layout_landscape -> {
screenAdjustmentUtil.changeScreenOrientation(ScreenLayout.MOBILE_LANDSCAPE)
true
}
R.id.menu_screen_layout_portrait -> {
screenAdjustmentUtil.changeScreenOrientation(ScreenLayout.MOBILE_PORTRAIT)
true
}
R.id.menu_screen_layout_single -> {
screenAdjustmentUtil.changeScreenOrientation(ScreenLayout.SINGLE_SCREEN)
true
}
R.id.menu_screen_layout_sidebyside -> {
screenAdjustmentUtil.changeScreenOrientation(ScreenLayout.SIDE_SCREEN)
true
}
R.id.menu_screen_layout_hybrid -> {
screenAdjustmentUtil.changeScreenOrientation(ScreenLayout.HYBRID_SCREEN)
true
}
else -> true
}
}
popupMenu.show()
}
private fun editControlsPlacement() {
if (binding.surfaceInputOverlay.isInEditMode) {
binding.doneControlConfig.visibility = View.GONE
binding.surfaceInputOverlay.setIsInEditMode(false)
} else {
binding.doneControlConfig.visibility = View.VISIBLE
binding.surfaceInputOverlay.setIsInEditMode(true)
}
}
private fun showToggleControlsDialog() {
val editor = preferences.edit()
val enabledButtons = BooleanArray(14)
enabledButtons.forEachIndexed { i: Int, _: Boolean ->
// Buttons that are disabled by default
var defaultValue = true
when (i) {
6, 7, 12, 13 -> defaultValue = false
}
enabledButtons[i] = preferences.getBoolean("buttonToggle$i", defaultValue)
}
MaterialAlertDialogBuilder(requireContext())
.setTitle(R.string.emulation_toggle_controls)
.setMultiChoiceItems(
R.array.n3dsButtons, enabledButtons
) { _: DialogInterface?, indexSelected: Int, isChecked: Boolean ->
editor.putBoolean("buttonToggle$indexSelected", isChecked)
}
.setPositiveButton(android.R.string.ok) { _: DialogInterface?, _: Int ->
editor.apply()
binding.surfaceInputOverlay.refreshControls()
}
.show()
}
private fun showAdjustScaleDialog() {
val sliderBinding = DialogSliderBinding.inflate(layoutInflater)
sliderBinding.apply {
slider.valueTo = 150f
slider.value = preferences.getInt("controlScale", 50).toFloat()
slider.addOnChangeListener(
Slider.OnChangeListener { slider: Slider, progress: Float, _: Boolean ->
textValue.text = (progress.toInt() + 50).toString()
setControlScale(slider.value.toInt())
})
textValue.text = (sliderBinding.slider.value.toInt() + 50).toString()
textUnits.text = "%"
}
val previousProgress = sliderBinding.slider.value.toInt()
MaterialAlertDialogBuilder(requireContext())
.setTitle(R.string.emulation_control_scale)
.setView(sliderBinding.root)
.setNegativeButton(android.R.string.cancel) { _: DialogInterface?, _: Int ->
setControlScale(previousProgress)
}
.setPositiveButton(android.R.string.ok) { _: DialogInterface?, _: Int ->
setControlScale(sliderBinding.slider.value.toInt())
}
.setNeutralButton(R.string.slider_default) { _: DialogInterface?, _: Int ->
setControlScale(50)
}
.show()
}
private fun setControlScale(scale: Int) {
preferences.edit()
.putInt("controlScale", scale)
.apply()
binding.surfaceInputOverlay.refreshControls()
}
private fun showResetOverlayDialog() {
MaterialAlertDialogBuilder(requireContext())
.setTitle(getString(R.string.emulation_touch_overlay_reset))
.setPositiveButton(android.R.string.ok) { _: DialogInterface?, _: Int ->
resetInputOverlay()
}
.setNegativeButton(android.R.string.cancel, null)
.show()
}
private fun resetInputOverlay() {
preferences.edit()
.putInt("controlScale", 50)
.apply()
val editor = preferences.edit()
for (i in 0 until 14) {
var defaultValue = true
when (i) {
6, 7, 12, 13 -> defaultValue = false
}
editor.putBoolean("buttonToggle$i", defaultValue)
}
editor.apply()
binding.surfaceInputOverlay.resetButtonPlacement()
}
fun updateShowFpsOverlay() {
if (EmulationMenuSettings.showFps) {
val SYSTEM_FPS = 0
val FPS = 1
val FRAMETIME = 2
val SPEED = 3
perfStatsUpdater = Runnable {
val perfStats = NativeLibrary.getPerfStats()
if (perfStats[FPS] > 0) {
binding.showFpsText.text = String.format(
"FPS: %d Speed: %d%%",
(perfStats[FPS] + 0.5).toInt(),
(perfStats[SPEED] * 100.0 + 0.5).toInt()
)
}
perfStatsUpdateHandler.postDelayed(perfStatsUpdater!!, 3000)
}
perfStatsUpdateHandler.post(perfStatsUpdater!!)
binding.showFpsText.visibility = View.VISIBLE
} else {
if (perfStatsUpdater != null) {
perfStatsUpdateHandler.removeCallbacks(perfStatsUpdater!!)
}
binding.showFpsText.visibility = View.GONE
}
}
override fun surfaceCreated(holder: SurfaceHolder) {
Log.debug("[EmulationFragment] Surface Created")
}
override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
Log.debug("[EmulationFragment] Surface changed. Resolution: " + width + "x" + height)
emulationState.newSurface(holder.surface)
}
override fun surfaceDestroyed(holder: SurfaceHolder) {
emulationState.clearSurface()
LeiaHelper3D.update3dMode(binding.surfaceEmulation, false, false)
}
override fun doFrame(frameTimeNanos: Long) {
Choreographer.getInstance().postFrameCallback(this)
NativeLibrary.doFrame()
}
private fun setInsets() {
ViewCompat.setOnApplyWindowInsetsListener(
binding.inGameMenu
) { v: View, windowInsets: WindowInsetsCompat ->
val cutInsets: Insets = windowInsets.getInsets(WindowInsetsCompat.Type.displayCutout())
var left = 0
var right = 0
if (ViewCompat.getLayoutDirection(v) == ViewCompat.LAYOUT_DIRECTION_LTR) {
left = cutInsets.left
} else {
right = cutInsets.right
}
v.setPadding(left, cutInsets.top, right, 0)
// Ensure FPS text doesn't get cut off by rounded display corners
val sidePadding = resources.getDimensionPixelSize(R.dimen.spacing_large)
if (cutInsets.left == 0) {
binding.showFpsText.setPadding(
sidePadding,
cutInsets.top,
cutInsets.right,
cutInsets.bottom
)
} else {
binding.showFpsText.setPadding(
cutInsets.left,
cutInsets.top,
cutInsets.right,
cutInsets.bottom
)
}
windowInsets
}
}
private class EmulationState(private val gamePath: String) {
private var state: State
private var surface: Surface? = null
init {
// Starting state is stopped.
state = State.STOPPED
}
@get:Synchronized
val isStopped: Boolean
get() = state == State.STOPPED
@get:Synchronized
val isPaused: Boolean
// Getters for the current state
get() = state == State.PAUSED
@get:Synchronized
val isRunning: Boolean
get() = state == State.RUNNING
@Synchronized
fun stop() {
if (state != State.STOPPED) {
Log.debug("[EmulationFragment] Stopping emulation.")
state = State.STOPPED
NativeLibrary.stopEmulation()
} else {
Log.warning("[EmulationFragment] Stop called while already stopped.")
}
}
// State changing methods
@Synchronized
fun pause() {
if (state != State.PAUSED) {
state = State.PAUSED
Log.debug("[EmulationFragment] Pausing emulation.")
// Release the surface before pausing, since emulation has to be running for that.
NativeLibrary.surfaceDestroyed()
NativeLibrary.pauseEmulation()
} else {
Log.warning("[EmulationFragment] Pause called while already paused.")
}
}
@Synchronized
fun unpause() {
if (state != State.RUNNING) {
state = State.RUNNING
Log.debug("[EmulationFragment] Unpausing emulation.")
NativeLibrary.unPauseEmulation()
} else {
Log.warning("[EmulationFragment] Unpause called while already running.")
}
}
@Synchronized
fun run(isActivityRecreated: Boolean) {
if (isActivityRecreated) {
if (NativeLibrary.isRunning()) {
state = State.PAUSED