diff options
Diffstat (limited to 'src')
85 files changed, 1120 insertions, 599 deletions
diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/NativeLibrary.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/NativeLibrary.kt index c8706d7a6..21f67f32a 100644 --- a/src/android/app/src/main/java/org/yuzu/yuzu_emu/NativeLibrary.kt +++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/NativeLibrary.kt @@ -308,21 +308,6 @@ object NativeLibrary { external fun isPaused(): Boolean /** - * Mutes emulation sound - */ - external fun muteAudio(): Boolean - - /** - * Unmutes emulation sound - */ - external fun unmuteAudio(): Boolean - - /** - * Returns true if emulation audio is muted. - */ - external fun isMuted(): Boolean - - /** * Returns the performance stats for the current game */ external fun getPerfStats(): DoubleArray diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/activities/EmulationActivity.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/activities/EmulationActivity.kt index bbd328c71..d4ae39661 100644 --- a/src/android/app/src/main/java/org/yuzu/yuzu_emu/activities/EmulationActivity.kt +++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/activities/EmulationActivity.kt @@ -332,7 +332,7 @@ class EmulationActivity : AppCompatActivity(), SensorEventListener { pictureInPictureActions.add(pauseRemoteAction) } - if (NativeLibrary.isMuted()) { + if (BooleanSetting.AUDIO_MUTED.boolean) { val unmuteIcon = Icon.createWithResource( this@EmulationActivity, R.drawable.ic_pip_unmute @@ -389,9 +389,9 @@ class EmulationActivity : AppCompatActivity(), SensorEventListener { if (!NativeLibrary.isPaused()) NativeLibrary.pauseEmulation() } if (intent.action == actionUnmute) { - if (NativeLibrary.isMuted()) NativeLibrary.unmuteAudio() + if (BooleanSetting.AUDIO_MUTED.boolean) BooleanSetting.AUDIO_MUTED.setBoolean(false) } else if (intent.action == actionMute) { - if (!NativeLibrary.isMuted()) NativeLibrary.muteAudio() + if (!BooleanSetting.AUDIO_MUTED.boolean) BooleanSetting.AUDIO_MUTED.setBoolean(true) } buildPictureInPictureParams() } @@ -417,7 +417,7 @@ class EmulationActivity : AppCompatActivity(), SensorEventListener { } catch (ignored: Exception) { } // Always resume audio, since there is no UI button - if (NativeLibrary.isMuted()) NativeLibrary.unmuteAudio() + if (BooleanSetting.AUDIO_MUTED.boolean) BooleanSetting.AUDIO_MUTED.setBoolean(false) } } diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/adapters/GameAdapter.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/adapters/GameAdapter.kt index 0013e8512..f9f88a1d2 100644 --- a/src/android/app/src/main/java/org/yuzu/yuzu_emu/adapters/GameAdapter.kt +++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/adapters/GameAdapter.kt @@ -4,7 +4,8 @@ package org.yuzu.yuzu_emu.adapters import android.content.Intent -import android.graphics.drawable.BitmapDrawable +import android.graphics.Bitmap +import android.graphics.drawable.LayerDrawable import android.net.Uri import android.text.TextUtils import android.view.LayoutInflater @@ -15,7 +16,10 @@ import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.core.content.pm.ShortcutInfoCompat import androidx.core.content.pm.ShortcutManagerCompat +import androidx.core.content.res.ResourcesCompat import androidx.core.graphics.drawable.IconCompat +import androidx.core.graphics.drawable.toBitmap +import androidx.core.graphics.drawable.toDrawable import androidx.documentfile.provider.DocumentFile import androidx.lifecycle.ViewModelProvider import androidx.navigation.findNavController @@ -87,11 +91,24 @@ class GameAdapter(private val activity: AppCompatActivity) : action = Intent.ACTION_VIEW data = Uri.parse(holder.game.path) } + + val layerDrawable = ResourcesCompat.getDrawable( + YuzuApplication.appContext.resources, + R.drawable.shortcut, + null + ) as LayerDrawable + layerDrawable.setDrawableByLayerId( + R.id.shortcut_foreground, + GameIconUtils.getGameIcon(holder.game).toDrawable(YuzuApplication.appContext.resources) + ) + val inset = YuzuApplication.appContext.resources + .getDimensionPixelSize(R.dimen.icon_inset) + layerDrawable.setLayerInset(1, inset, inset, inset, inset) val shortcut = ShortcutInfoCompat.Builder(YuzuApplication.appContext, holder.game.path) .setShortLabel(holder.game.title) .setIcon( - IconCompat.createWithBitmap( - (holder.binding.imageGameScreen.drawable as BitmapDrawable).bitmap + IconCompat.createWithAdaptiveBitmap( + layerDrawable.toBitmap(config = Bitmap.Config.ARGB_8888) ) ) .setIntent(openIntent) diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/adapters/HomeSettingAdapter.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/adapters/HomeSettingAdapter.kt index 8d87d3bd7..1675627a1 100644 --- a/src/android/app/src/main/java/org/yuzu/yuzu_emu/adapters/HomeSettingAdapter.kt +++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/adapters/HomeSettingAdapter.kt @@ -10,8 +10,12 @@ import android.view.ViewGroup import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import androidx.core.content.res.ResourcesCompat +import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleOwner +import androidx.lifecycle.lifecycleScope +import androidx.lifecycle.repeatOnLifecycle import androidx.recyclerview.widget.RecyclerView +import kotlinx.coroutines.launch import org.yuzu.yuzu_emu.R import org.yuzu.yuzu_emu.databinding.CardHomeOptionBinding import org.yuzu.yuzu_emu.fragments.MessageDialogFragment @@ -86,7 +90,11 @@ class HomeSettingAdapter( binding.optionIcon.alpha = 0.5f } - option.details.observe(viewLifecycle) { updateOptionDetails(it) } + viewLifecycle.lifecycleScope.launch { + viewLifecycle.repeatOnLifecycle(Lifecycle.State.CREATED) { + option.details.collect { updateOptionDetails(it) } + } + } binding.optionDetail.postDelayed( { binding.optionDetail.ellipsize = TextUtils.TruncateAt.MARQUEE diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/model/BooleanSetting.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/model/BooleanSetting.kt index e0c0538c7..8476ce867 100644 --- a/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/model/BooleanSetting.kt +++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/model/BooleanSetting.kt @@ -10,6 +10,7 @@ enum class BooleanSetting( override val category: Settings.Category, override val androidDefault: Boolean? = null ) : AbstractBooleanSetting { + AUDIO_MUTED("audio_muted", Settings.Category.Audio), CPU_DEBUG_MODE("cpu_debug_mode", Settings.Category.Cpu), FASTMEM("cpuopt_fastmem", Settings.Category.Cpu), FASTMEM_EXCLUSIVES("cpuopt_fastmem_exclusives", Settings.Category.Cpu), diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/model/Settings.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/model/Settings.kt index 0702236e8..08e2a973d 100644 --- a/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/model/Settings.kt +++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/model/Settings.kt @@ -80,6 +80,17 @@ object Settings { const val SECTION_THEME = "Theme" const val SECTION_DEBUG = "Debug" + enum class MenuTag(val titleId: Int) { + SECTION_ROOT(R.string.advanced_settings), + SECTION_GENERAL(R.string.preferences_general), + SECTION_SYSTEM(R.string.preferences_system), + SECTION_RENDERER(R.string.preferences_graphics), + SECTION_AUDIO(R.string.preferences_audio), + SECTION_CPU(R.string.cpu), + SECTION_THEME(R.string.preferences_theme), + SECTION_DEBUG(R.string.preferences_debug); + } + const val PREF_MEMORY_WARNING_SHOWN = "MemoryWarningShown" const val PREF_OVERLAY_VERSION = "OverlayVersion" diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/model/view/SubmenuSetting.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/model/view/SubmenuSetting.kt index 91c273964..b343e527e 100644 --- a/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/model/view/SubmenuSetting.kt +++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/model/view/SubmenuSetting.kt @@ -3,10 +3,12 @@ package org.yuzu.yuzu_emu.features.settings.model.view +import org.yuzu.yuzu_emu.features.settings.model.Settings + class SubmenuSetting( titleId: Int, descriptionId: Int, - val menuKey: String + val menuKey: Settings.MenuTag ) : SettingsItem(emptySetting, titleId, descriptionId) { override val type = TYPE_SUBMENU } diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/SettingsActivity.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/SettingsActivity.kt index 908c01265..4d2f2f604 100644 --- a/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/SettingsActivity.kt +++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/SettingsActivity.kt @@ -13,9 +13,14 @@ import androidx.appcompat.app.AppCompatActivity import androidx.core.view.ViewCompat import androidx.core.view.WindowCompat import androidx.core.view.WindowInsetsCompat +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.lifecycleScope +import androidx.lifecycle.repeatOnLifecycle import androidx.navigation.fragment.NavHostFragment import androidx.navigation.navArgs import com.google.android.material.color.MaterialColors +import kotlinx.coroutines.flow.collectLatest +import kotlinx.coroutines.launch import java.io.IOException import org.yuzu.yuzu_emu.R import org.yuzu.yuzu_emu.databinding.ActivitySettingsBinding @@ -66,25 +71,39 @@ class SettingsActivity : AppCompatActivity() { ) } - settingsViewModel.shouldRecreate.observe(this) { - if (it) { - settingsViewModel.setShouldRecreate(false) - recreate() + lifecycleScope.apply { + launch { + repeatOnLifecycle(Lifecycle.State.CREATED) { + settingsViewModel.shouldRecreate.collectLatest { + if (it) { + settingsViewModel.setShouldRecreate(false) + recreate() + } + } + } } - } - settingsViewModel.shouldNavigateBack.observe(this) { - if (it) { - settingsViewModel.setShouldNavigateBack(false) - navigateBack() + launch { + repeatOnLifecycle(Lifecycle.State.CREATED) { + settingsViewModel.shouldNavigateBack.collectLatest { + if (it) { + settingsViewModel.setShouldNavigateBack(false) + navigateBack() + } + } + } } - } - settingsViewModel.shouldShowResetSettingsDialog.observe(this) { - if (it) { - settingsViewModel.setShouldShowResetSettingsDialog(false) - ResetSettingsDialogFragment().show( - supportFragmentManager, - ResetSettingsDialogFragment.TAG - ) + launch { + repeatOnLifecycle(Lifecycle.State.CREATED) { + settingsViewModel.shouldShowResetSettingsDialog.collectLatest { + if (it) { + settingsViewModel.setShouldShowResetSettingsDialog(false) + ResetSettingsDialogFragment().show( + supportFragmentManager, + ResetSettingsDialogFragment.TAG + ) + } + } + } } } diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/SettingsFragment.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/SettingsFragment.kt index bc319714c..70d8ec14b 100644 --- a/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/SettingsFragment.kt +++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/SettingsFragment.kt @@ -3,6 +3,7 @@ package org.yuzu.yuzu_emu.features.settings.ui +import android.annotation.SuppressLint import android.os.Bundle import android.view.LayoutInflater import android.view.View @@ -13,14 +14,19 @@ import androidx.core.view.WindowInsetsCompat import androidx.core.view.updatePadding import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.lifecycleScope +import androidx.lifecycle.repeatOnLifecycle import androidx.navigation.findNavController import androidx.navigation.fragment.navArgs import androidx.recyclerview.widget.LinearLayoutManager import com.google.android.material.divider.MaterialDividerItemDecoration import com.google.android.material.transition.MaterialSharedAxis +import kotlinx.coroutines.flow.collectLatest +import kotlinx.coroutines.launch import org.yuzu.yuzu_emu.R import org.yuzu.yuzu_emu.databinding.FragmentSettingsBinding -import org.yuzu.yuzu_emu.features.settings.utils.SettingsFile +import org.yuzu.yuzu_emu.features.settings.model.Settings import org.yuzu.yuzu_emu.model.SettingsViewModel class SettingsFragment : Fragment() { @@ -51,15 +57,17 @@ class SettingsFragment : Fragment() { return binding.root } + // This is using the correct scope, lint is just acting up + @SuppressLint("UnsafeRepeatOnLifecycleDetector") override fun onViewCreated(view: View, savedInstanceState: Bundle?) { settingsAdapter = SettingsAdapter(this, requireContext()) presenter = SettingsFragmentPresenter( settingsViewModel, settingsAdapter!!, - args.menuTag, - args.game?.gameId ?: "" + args.menuTag ) + binding.toolbarSettingsLayout.title = getString(args.menuTag.titleId) val dividerDecoration = MaterialDividerItemDecoration( requireContext(), LinearLayoutManager.VERTICAL @@ -75,28 +83,31 @@ class SettingsFragment : Fragment() { settingsViewModel.setShouldNavigateBack(true) } - settingsViewModel.toolbarTitle.observe(viewLifecycleOwner) { - if (it.isNotEmpty()) binding.toolbarSettingsLayout.title = it - } - - settingsViewModel.shouldReloadSettingsList.observe(viewLifecycleOwner) { - if (it) { - settingsViewModel.setShouldReloadSettingsList(false) - presenter.loadSettingsList() + viewLifecycleOwner.lifecycleScope.apply { + launch { + repeatOnLifecycle(Lifecycle.State.CREATED) { + settingsViewModel.shouldReloadSettingsList.collectLatest { + if (it) { + settingsViewModel.setShouldReloadSettingsList(false) + presenter.loadSettingsList() + } + } + } } - } - - settingsViewModel.isUsingSearch.observe(viewLifecycleOwner) { - if (it) { - reenterTransition = MaterialSharedAxis(MaterialSharedAxis.Z, true) - exitTransition = MaterialSharedAxis(MaterialSharedAxis.Z, false) - } else { - reenterTransition = MaterialSharedAxis(MaterialSharedAxis.X, false) - exitTransition = MaterialSharedAxis(MaterialSharedAxis.X, true) + launch { + settingsViewModel.isUsingSearch.collectLatest { + if (it) { + reenterTransition = MaterialSharedAxis(MaterialSharedAxis.Z, true) + exitTransition = MaterialSharedAxis(MaterialSharedAxis.Z, false) + } else { + reenterTransition = MaterialSharedAxis(MaterialSharedAxis.X, false) + exitTransition = MaterialSharedAxis(MaterialSharedAxis.X, true) + } + } } } - if (args.menuTag == SettingsFile.FILE_NAME_CONFIG) { + if (args.menuTag == Settings.MenuTag.SECTION_ROOT) { binding.toolbarSettings.inflateMenu(R.menu.menu_settings) binding.toolbarSettings.setOnMenuItemClickListener { when (it.itemId) { diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/SettingsFragmentPresenter.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/SettingsFragmentPresenter.kt index 22a529b1b..766414a6c 100644 --- a/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/SettingsFragmentPresenter.kt +++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/SettingsFragmentPresenter.kt @@ -6,7 +6,6 @@ package org.yuzu.yuzu_emu.features.settings.ui import android.content.Context import android.content.SharedPreferences import android.os.Build -import android.text.TextUtils import android.widget.Toast import androidx.preference.PreferenceManager import org.yuzu.yuzu_emu.R @@ -20,15 +19,13 @@ import org.yuzu.yuzu_emu.features.settings.model.LongSetting import org.yuzu.yuzu_emu.features.settings.model.Settings import org.yuzu.yuzu_emu.features.settings.model.ShortSetting import org.yuzu.yuzu_emu.features.settings.model.view.* -import org.yuzu.yuzu_emu.features.settings.utils.SettingsFile import org.yuzu.yuzu_emu.model.SettingsViewModel import org.yuzu.yuzu_emu.utils.NativeConfig class SettingsFragmentPresenter( private val settingsViewModel: SettingsViewModel, private val adapter: SettingsAdapter, - private var menuTag: String, - private var gameId: String + private var menuTag: Settings.MenuTag ) { private var settingsList = ArrayList<SettingsItem>() @@ -53,24 +50,15 @@ class SettingsFragmentPresenter( } fun loadSettingsList() { - if (!TextUtils.isEmpty(gameId)) { - settingsViewModel.setToolbarTitle( - context.getString( - R.string.advanced_settings_game, - gameId - ) - ) - } - val sl = ArrayList<SettingsItem>() when (menuTag) { - SettingsFile.FILE_NAME_CONFIG -> addConfigSettings(sl) - Settings.SECTION_GENERAL -> addGeneralSettings(sl) - Settings.SECTION_SYSTEM -> addSystemSettings(sl) - Settings.SECTION_RENDERER -> addGraphicsSettings(sl) - Settings.SECTION_AUDIO -> addAudioSettings(sl) - Settings.SECTION_THEME -> addThemeSettings(sl) - Settings.SECTION_DEBUG -> addDebugSettings(sl) + Settings.MenuTag.SECTION_ROOT -> addConfigSettings(sl) + Settings.MenuTag.SECTION_GENERAL -> addGeneralSettings(sl) + Settings.MenuTag.SECTION_SYSTEM -> addSystemSettings(sl) + Settings.MenuTag.SECTION_RENDERER -> addGraphicsSettings(sl) + Settings.MenuTag.SECTION_AUDIO -> addAudioSettings(sl) + Settings.MenuTag.SECTION_THEME -> addThemeSettings(sl) + Settings.MenuTag.SECTION_DEBUG -> addDebugSettings(sl) else -> { val context = YuzuApplication.appContext Toast.makeText( @@ -86,13 +74,12 @@ class SettingsFragmentPresenter( } private fun addConfigSettings(sl: ArrayList<SettingsItem>) { - settingsViewModel.setToolbarTitle(context.getString(R.string.advanced_settings)) sl.apply { - add(SubmenuSetting(R.string.preferences_general, 0, Settings.SECTION_GENERAL)) - add(SubmenuSetting(R.string.preferences_system, 0, Settings.SECTION_SYSTEM)) - add(SubmenuSetting(R.string.preferences_graphics, 0, Settings.SECTION_RENDERER)) - add(SubmenuSetting(R.string.preferences_audio, 0, Settings.SECTION_AUDIO)) - add(SubmenuSetting(R.string.preferences_debug, 0, Settings.SECTION_DEBUG)) + add(SubmenuSetting(R.string.preferences_general, 0, Settings.MenuTag.SECTION_GENERAL)) + add(SubmenuSetting(R.string.preferences_system, 0, Settings.MenuTag.SECTION_SYSTEM)) + add(SubmenuSetting(R.string.preferences_graphics, 0, Settings.MenuTag.SECTION_RENDERER)) + add(SubmenuSetting(R.string.preferences_audio, 0, Settings.MenuTag.SECTION_AUDIO)) + add(SubmenuSetting(R.string.preferences_debug, 0, Settings.MenuTag.SECTION_DEBUG)) add( RunnableSetting(R.string.reset_to_default, 0, false) { settingsViewModel.setShouldShowResetSettingsDialog(true) @@ -102,7 +89,6 @@ class SettingsFragmentPresenter( } private fun addGeneralSettings(sl: ArrayList<SettingsItem>) { - settingsViewModel.setToolbarTitle(context.getString(R.string.preferences_general)) sl.apply { add(BooleanSetting.RENDERER_USE_SPEED_LIMIT.key) add(ShortSetting.RENDERER_SPEED_LIMIT.key) @@ -112,7 +98,6 @@ class SettingsFragmentPresenter( } private fun addSystemSettings(sl: ArrayList<SettingsItem>) { - settingsViewModel.setToolbarTitle(context.getString(R.string.preferences_system)) sl.apply { add(BooleanSetting.USE_DOCKED_MODE.key) add(IntSetting.REGION_INDEX.key) @@ -123,7 +108,6 @@ class SettingsFragmentPresenter( } private fun addGraphicsSettings(sl: ArrayList<SettingsItem>) { - settingsViewModel.setToolbarTitle(context.getString(R.string.preferences_graphics)) sl.apply { add(IntSetting.RENDERER_ACCURACY.key) add(IntSetting.RENDERER_RESOLUTION.key) @@ -140,7 +124,6 @@ class SettingsFragmentPresenter( } private fun addAudioSettings(sl: ArrayList<SettingsItem>) { - settingsViewModel.setToolbarTitle(context.getString(R.string.preferences_audio)) sl.apply { add(IntSetting.AUDIO_OUTPUT_ENGINE.key) add(ByteSetting.AUDIO_VOLUME.key) @@ -148,7 +131,6 @@ class SettingsFragmentPresenter( } private fun addThemeSettings(sl: ArrayList<SettingsItem>) { - settingsViewModel.setToolbarTitle(context.getString(R.string.preferences_theme)) sl.apply { val theme: AbstractIntSetting = object : AbstractIntSetting { override val int: Int @@ -261,7 +243,6 @@ class SettingsFragmentPresenter( } private fun addDebugSettings(sl: ArrayList<SettingsItem>) { - settingsViewModel.setToolbarTitle(context.getString(R.string.preferences_debug)) sl.apply { add(HeaderSetting(R.string.gpu)) add(IntSetting.RENDERER_BACKEND.key) diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/fragments/EmulationFragment.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/fragments/EmulationFragment.kt index 944ae652e..3e6c157c7 100644 --- a/src/android/app/src/main/java/org/yuzu/yuzu_emu/fragments/EmulationFragment.kt +++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/fragments/EmulationFragment.kt @@ -39,6 +39,7 @@ import androidx.window.layout.WindowLayoutInfo import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.slider.Slider import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch import org.yuzu.yuzu_emu.HomeNavigationDirections import org.yuzu.yuzu_emu.NativeLibrary @@ -49,7 +50,6 @@ import org.yuzu.yuzu_emu.databinding.DialogOverlayAdjustBinding import org.yuzu.yuzu_emu.databinding.FragmentEmulationBinding import org.yuzu.yuzu_emu.features.settings.model.IntSetting import org.yuzu.yuzu_emu.features.settings.model.Settings -import org.yuzu.yuzu_emu.features.settings.utils.SettingsFile import org.yuzu.yuzu_emu.model.Game import org.yuzu.yuzu_emu.model.EmulationViewModel import org.yuzu.yuzu_emu.overlay.InputOverlay @@ -129,6 +129,8 @@ class EmulationFragment : Fragment(), SurfaceHolder.Callback { return binding.root } + // This is using the correct scope, lint is just acting up + @SuppressLint("UnsafeRepeatOnLifecycleDetector") override fun onViewCreated(view: View, savedInstanceState: Bundle?) { binding.surfaceEmulation.holder.addCallback(this) binding.showFpsText.setTextColor(Color.YELLOW) @@ -163,7 +165,7 @@ class EmulationFragment : Fragment(), SurfaceHolder.Callback { R.id.menu_settings -> { val action = HomeNavigationDirections.actionGlobalSettingsActivity( null, - SettingsFile.FILE_NAME_CONFIG + Settings.MenuTag.SECTION_ROOT ) binding.root.findNavController().navigate(action) true @@ -205,59 +207,80 @@ class EmulationFragment : Fragment(), SurfaceHolder.Callback { } ) - viewLifecycleOwner.lifecycleScope.launch(Dispatchers.Main) { - lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { - WindowInfoTracker.getOrCreate(requireContext()) - .windowLayoutInfo(requireActivity()) - .collect { updateFoldableLayout(requireActivity() as EmulationActivity, it) } - } - } - GameIconUtils.loadGameIcon(game, binding.loadingImage) binding.loadingTitle.text = game.title binding.loadingTitle.isSelected = true binding.loadingText.isSelected = true - emulationViewModel.shaderProgress.observe(viewLifecycleOwner) { - if (it > 0 && it != emulationViewModel.totalShaders.value!!) { - binding.loadingProgressIndicator.isIndeterminate = false - - if (it < binding.loadingProgressIndicator.max) { - binding.loadingProgressIndicator.progress = it + viewLifecycleOwner.lifecycleScope.apply { + launch { + repeatOnLifecycle(Lifecycle.State.STARTED) { + WindowInfoTracker.getOrCreate(requireContext()) + .windowLayoutInfo(requireActivity()) + .collect { + updateFoldableLayout(requireActivity() as EmulationActivity, it) + } } } + launch { + repeatOnLifecycle(Lifecycle.State.CREATED) { + emulationViewModel.shaderProgress.collectLatest { + if (it > 0 && it != emulationViewModel.totalShaders.value) { + binding.loadingProgressIndicator.isIndeterminate = false + + if (it < binding.loadingProgressIndicator.max) { + binding.loadingProgressIndicator.progress = it + } + } - if (it == emulationViewModel.totalShaders.value!!) { - binding.loadingText.setText(R.string.loading) - binding.loadingProgressIndicator.isIndeterminate = true + if (it == emulationViewModel.totalShaders.value) { + binding.loadingText.setText(R.string.loading) + binding.loadingProgressIndicator.isIndeterminate = true + } + } + } } - } - emulationViewModel.totalShaders.observe(viewLifecycleOwner) { - binding.loadingProgressIndicator.max = it - } - emulationViewModel.shaderMessage.observe(viewLifecycleOwner) { - if (it.isNotEmpty()) { - binding.loadingText.text = it + launch { + repeatOnLifecycle(Lifecycle.State.CREATED) { + emulationViewModel.totalShaders.collectLatest { + binding.loadingProgressIndicator.max = it + } + } } - } - - emulationViewModel.emulationStarted.observe(viewLifecycleOwner) { started -> - if (started) { - binding.drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED) - ViewUtils.showView(binding.surfaceInputOverlay) - ViewUtils.hideView(binding.loadingIndicator) - - // Setup overlay - updateShowFpsOverlay() + launch { + repeatOnLifecycle(Lifecycle.State.CREATED) { + emulationViewModel.shaderMessage.collectLatest { + if (it.isNotEmpty()) { + binding.loadingText.text = it + } + } + } } - } + launch { + repeatOnLifecycle(Lifecycle.State.CREATED) { + emulationViewModel.emulationStarted.collectLatest { + if (it) { + binding.drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED) + ViewUtils.showView(binding.surfaceInputOverlay) + ViewUtils.hideView(binding.loadingIndicator) - emulationViewModel.isEmulationStopping.observe(viewLifecycleOwner) { - if (it) { - binding.loadingText.setText(R.string.shutting_down) - ViewUtils.showView(binding.loadingIndicator) - ViewUtils.hideView(binding.inputContainer) - ViewUtils.hideView(binding.showFpsText) + // Setup overlay + updateShowFpsOverlay() + } + } + } + } + launch { + repeatOnLifecycle(Lifecycle.State.CREATED) { + emulationViewModel.isEmulationStopping.collectLatest { + if (it) { + binding.loadingText.setText(R.string.shutting_down) + ViewUtils.showView(binding.loadingIndicator) + ViewUtils.hideView(binding.inputContainer) + ViewUtils.hideView(binding.showFpsText) + } + } + } } } } @@ -274,9 +297,7 @@ class EmulationFragment : Fragment(), SurfaceHolder.Callback { } } } else { - if (EmulationMenuSettings.showOverlay && - emulationViewModel.emulationStarted.value == true - ) { + if (EmulationMenuSettings.showOverlay && emulationViewModel.emulationStarted.value) { binding.surfaceInputOverlay.post { binding.surfaceInputOverlay.visibility = View.VISIBLE } diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/fragments/HomeSettingsFragment.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/fragments/HomeSettingsFragment.kt index cbbe14d22..c119e69c9 100644 --- a/src/android/app/src/main/java/org/yuzu/yuzu_emu/fragments/HomeSettingsFragment.kt +++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/fragments/HomeSettingsFragment.kt @@ -37,7 +37,6 @@ import org.yuzu.yuzu_emu.adapters.HomeSettingAdapter import org.yuzu.yuzu_emu.databinding.FragmentHomeSettingsBinding import org.yuzu.yuzu_emu.features.DocumentProvider import org.yuzu.yuzu_emu.features.settings.model.Settings -import org.yuzu.yuzu_emu.features.settings.utils.SettingsFile import org.yuzu.yuzu_emu.model.HomeSetting import org.yuzu.yuzu_emu.model.HomeViewModel import org.yuzu.yuzu_emu.ui.main.MainActivity @@ -78,7 +77,7 @@ class HomeSettingsFragment : Fragment() { { val action = HomeNavigationDirections.actionGlobalSettingsActivity( null, - SettingsFile.FILE_NAME_CONFIG + Settings.MenuTag.SECTION_ROOT ) binding.root.findNavController().navigate(action) } @@ -100,7 +99,7 @@ class HomeSettingsFragment : Fragment() { { val action = HomeNavigationDirections.actionGlobalSettingsActivity( null, - Settings.SECTION_THEME + Settings.MenuTag.SECTION_THEME ) binding.root.findNavController().navigate(action) } diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/fragments/IndeterminateProgressDialogFragment.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/fragments/IndeterminateProgressDialogFragment.kt index 181bd983a..ea8eb073a 100644 --- a/src/android/app/src/main/java/org/yuzu/yuzu_emu/fragments/IndeterminateProgressDialogFragment.kt +++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/fragments/IndeterminateProgressDialogFragment.kt @@ -9,8 +9,12 @@ import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.DialogFragment import androidx.fragment.app.activityViewModels +import androidx.lifecycle.Lifecycle import androidx.lifecycle.ViewModelProvider +import androidx.lifecycle.lifecycleScope +import androidx.lifecycle.repeatOnLifecycle import com.google.android.material.dialog.MaterialAlertDialogBuilder +import kotlinx.coroutines.launch import org.yuzu.yuzu_emu.databinding.DialogProgressBarBinding import org.yuzu.yuzu_emu.model.TaskViewModel @@ -28,21 +32,27 @@ class IndeterminateProgressDialogFragment : DialogFragment() { .create() dialog.setCanceledOnTouchOutside(false) - taskViewModel.isComplete.observe(this) { complete -> - if (complete) { - dialog.dismiss() - when (val result = taskViewModel.result.value) { - is String -> Toast.makeText(requireContext(), result, Toast.LENGTH_LONG).show() - is MessageDialogFragment -> result.show( - requireActivity().supportFragmentManager, - MessageDialogFragment.TAG - ) + viewLifecycleOwner.lifecycleScope.launch { + repeatOnLifecycle(Lifecycle.State.CREATED) { + taskViewModel.isComplete.collect { + if (it) { + dialog.dismiss() + when (val result = taskViewModel.result.value) { + is String -> Toast.makeText(requireContext(), result, Toast.LENGTH_LONG) + .show() + + is MessageDialogFragment -> result.show( + requireActivity().supportFragmentManager, + MessageDialogFragment.TAG + ) + } + taskViewModel.clear() + } } - taskViewModel.clear() } } - if (taskViewModel.isRunning.value == false) { + if (!taskViewModel.isRunning.value) { taskViewModel.runTask() } return dialog diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/fragments/SearchFragment.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/fragments/SearchFragment.kt index f54dccc69..2dbca76a5 100644 --- a/src/android/app/src/main/java/org/yuzu/yuzu_emu/fragments/SearchFragment.kt +++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/fragments/SearchFragment.kt @@ -3,6 +3,7 @@ package org.yuzu.yuzu_emu.fragments +import android.annotation.SuppressLint import android.content.Context import android.content.SharedPreferences import android.os.Bundle @@ -17,9 +18,13 @@ import androidx.core.view.updatePadding import androidx.core.widget.doOnTextChanged import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.lifecycleScope +import androidx.lifecycle.repeatOnLifecycle import androidx.preference.PreferenceManager import info.debatty.java.stringsimilarity.Jaccard import info.debatty.java.stringsimilarity.JaroWinkler +import kotlinx.coroutines.launch import java.util.Locale import org.yuzu.yuzu_emu.R import org.yuzu.yuzu_emu.YuzuApplication @@ -52,6 +57,8 @@ class SearchFragment : Fragment() { return binding.root } + // This is using the correct scope, lint is just acting up + @SuppressLint("UnsafeRepeatOnLifecycleDetector") override fun onViewCreated(view: View, savedInstanceState: Bundle?) { homeViewModel.setNavigationVisibility(visible = true, animated = false) preferences = PreferenceManager.getDefaultSharedPreferences(YuzuApplication.appContext) @@ -79,21 +86,32 @@ class SearchFragment : Fragment() { filterAndSearch() } - gamesViewModel.apply { - searchFocused.observe(viewLifecycleOwner) { searchFocused -> - if (searchFocused) { - focusSearch() - gamesViewModel.setSearchFocused(false) + viewLifecycleOwner.lifecycleScope.apply { + launch { + repeatOnLifecycle(Lifecycle.State.CREATED) { + gamesViewModel.searchFocused.collect { + if (it) { + focusSearch() + gamesViewModel.setSearchFocused(false) + } + } } } - - games.observe(viewLifecycleOwner) { filterAndSearch() } - searchedGames.observe(viewLifecycleOwner) { - (binding.gridGamesSearch.adapter as GameAdapter).submitList(it) - if (it.isEmpty()) { - binding.noResultsView.visibility = View.VISIBLE - } else { - binding.noResultsView.visibility = View.GONE + launch { + repeatOnLifecycle(Lifecycle.State.CREATED) { + gamesViewModel.games.collect { filterAndSearch() } + } + } + launch { + repeatOnLifecycle(Lifecycle.State.CREATED) { + gamesViewModel.searchedGames.collect { + (binding.gridGamesSearch.adapter as GameAdapter).submitList(it) + if (it.isEmpty()) { + binding.noResultsView.visibility = View.VISIBLE + } else { + binding.noResultsView.visibility = View.GONE + } + } } } } @@ -109,7 +127,7 @@ class SearchFragment : Fragment() { private inner class ScoredGame(val score: Double, val item: Game) private fun filterAndSearch() { - val baseList = gamesViewModel.games.value!! + val baseList = gamesViewModel.games.value val filteredList: List<Game> = when (binding.chipGroup.checkedChipId) { R.id.chip_recently_played -> { baseList.filter { diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/fragments/SettingsSearchFragment.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/fragments/SettingsSearchFragment.kt index 55b6a0367..9d0594c6e 100644 --- a/src/android/app/src/main/java/org/yuzu/yuzu_emu/fragments/SettingsSearchFragment.kt +++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/fragments/SettingsSearchFragment.kt @@ -15,10 +15,14 @@ import androidx.core.view.updatePadding import androidx.core.widget.doOnTextChanged import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.lifecycleScope +import androidx.lifecycle.repeatOnLifecycle import androidx.recyclerview.widget.LinearLayoutManager import com.google.android.material.divider.MaterialDividerItemDecoration import com.google.android.material.transition.MaterialSharedAxis import info.debatty.java.stringsimilarity.Cosine +import kotlinx.coroutines.launch import org.yuzu.yuzu_emu.R import org.yuzu.yuzu_emu.databinding.FragmentSettingsSearchBinding import org.yuzu.yuzu_emu.features.settings.model.view.SettingsItem @@ -79,10 +83,14 @@ class SettingsSearchFragment : Fragment() { search() binding.settingsList.smoothScrollToPosition(0) } - settingsViewModel.shouldReloadSettingsList.observe(viewLifecycleOwner) { - if (it) { - settingsViewModel.setShouldReloadSettingsList(false) - search() + viewLifecycleOwner.lifecycleScope.launch { + repeatOnLifecycle(Lifecycle.State.CREATED) { + settingsViewModel.shouldReloadSettingsList.collect { + if (it) { + settingsViewModel.setShouldReloadSettingsList(false) + search() + } + } } } diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/fragments/SetupFragment.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/fragments/SetupFragment.kt index d50c421a0..fbb2f6e18 100644 --- a/src/android/app/src/main/java/org/yuzu/yuzu_emu/fragments/SetupFragment.kt +++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/fragments/SetupFragment.kt @@ -22,10 +22,14 @@ import androidx.core.view.isVisible import androidx.core.view.updatePadding import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.lifecycleScope +import androidx.lifecycle.repeatOnLifecycle import androidx.navigation.findNavController import androidx.preference.PreferenceManager import androidx.viewpager2.widget.ViewPager2.OnPageChangeCallback import com.google.android.material.transition.MaterialFadeThrough +import kotlinx.coroutines.launch import java.io.File import org.yuzu.yuzu_emu.R import org.yuzu.yuzu_emu.YuzuApplication @@ -206,10 +210,14 @@ class SetupFragment : Fragment() { ) } - homeViewModel.shouldPageForward.observe(viewLifecycleOwner) { - if (it) { - pageForward() - homeViewModel.setShouldPageForward(false) + viewLifecycleOwner.lifecycleScope.launch { + repeatOnLifecycle(Lifecycle.State.CREATED) { + homeViewModel.shouldPageForward.collect { + if (it) { + pageForward() + homeViewModel.setShouldPageForward(false) + } + } } } diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/model/EmulationViewModel.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/model/EmulationViewModel.kt index e35f51bc3..f34870c2d 100644 --- a/src/android/app/src/main/java/org/yuzu/yuzu_emu/model/EmulationViewModel.kt +++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/model/EmulationViewModel.kt @@ -3,28 +3,28 @@ package org.yuzu.yuzu_emu.model -import androidx.lifecycle.LiveData -import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow class EmulationViewModel : ViewModel() { - private val _emulationStarted = MutableLiveData(false) - val emulationStarted: LiveData<Boolean> get() = _emulationStarted + val emulationStarted: StateFlow<Boolean> get() = _emulationStarted + private val _emulationStarted = MutableStateFlow(false) - private val _isEmulationStopping = MutableLiveData(false) - val isEmulationStopping: LiveData<Boolean> get() = _isEmulationStopping + val isEmulationStopping: StateFlow<Boolean> get() = _isEmulationStopping + private val _isEmulationStopping = MutableStateFlow(false) - private val _shaderProgress = MutableLiveData(0) - val shaderProgress: LiveData<Int> get() = _shaderProgress + val shaderProgress: StateFlow<Int> get() = _shaderProgress + private val _shaderProgress = MutableStateFlow(0) - private val _totalShaders = MutableLiveData(0) - val totalShaders: LiveData<Int> get() = _totalShaders + val totalShaders: StateFlow<Int> get() = _totalShaders + private val _totalShaders = MutableStateFlow(0) - private val _shaderMessage = MutableLiveData("") - val shaderMessage: LiveData<String> get() = _shaderMessage + val shaderMessage: StateFlow<String> get() = _shaderMessage + private val _shaderMessage = MutableStateFlow("") fun setEmulationStarted(started: Boolean) { - _emulationStarted.postValue(started) + _emulationStarted.value = started } fun setIsEmulationStopping(value: Boolean) { @@ -50,10 +50,18 @@ class EmulationViewModel : ViewModel() { } fun clear() { - _emulationStarted.value = false - _isEmulationStopping.value = false - _shaderProgress.value = 0 - _totalShaders.value = 0 - _shaderMessage.value = "" + setEmulationStarted(false) + setIsEmulationStopping(false) + setShaderProgress(0) + setTotalShaders(0) + setShaderMessage("") + } + + companion object { + const val KEY_EMULATION_STARTED = "EmulationStarted" + const val KEY_IS_EMULATION_STOPPING = "IsEmulationStarting" + const val KEY_SHADER_PROGRESS = "ShaderProgress" + const val KEY_TOTAL_SHADERS = "TotalShaders" + const val KEY_SHADER_MESSAGE = "ShaderMessage" } } diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/model/GamesViewModel.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/model/GamesViewModel.kt index 1fe42f922..6e09fa81d 100644 --- a/src/android/app/src/main/java/org/yuzu/yuzu_emu/model/GamesViewModel.kt +++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/model/GamesViewModel.kt @@ -5,13 +5,13 @@ package org.yuzu.yuzu_emu.model import android.net.Uri import androidx.documentfile.provider.DocumentFile -import androidx.lifecycle.LiveData -import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import androidx.preference.PreferenceManager import java.util.Locale import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import kotlinx.serialization.ExperimentalSerializationApi @@ -24,23 +24,23 @@ import org.yuzu.yuzu_emu.utils.GameHelper @OptIn(ExperimentalSerializationApi::class) class GamesViewModel : ViewModel() { - private val _games = MutableLiveData<List<Game>>(emptyList()) - val games: LiveData<List<Game>> get() = _games + val games: StateFlow<List<Game>> get() = _games + private val _games = MutableStateFlow(emptyList<Game>()) - private val _searchedGames = MutableLiveData<List<Game>>(emptyList()) - val searchedGames: LiveData<List<Game>> get() = _searchedGames + val searchedGames: StateFlow<List<Game>> get() = _searchedGames + private val _searchedGames = MutableStateFlow(emptyList<Game>()) - private val _isReloading = MutableLiveData(false) - val isReloading: LiveData<Boolean> get() = _isReloading + val isReloading: StateFlow<Boolean> get() = _isReloading + private val _isReloading = MutableStateFlow(false) - private val _shouldSwapData = MutableLiveData(false) - val shouldSwapData: LiveData<Boolean> get() = _shouldSwapData + val shouldSwapData: StateFlow<Boolean> get() = _shouldSwapData + private val _shouldSwapData = MutableStateFlow(false) - private val _shouldScrollToTop = MutableLiveData(false) - val shouldScrollToTop: LiveData<Boolean> get() = _shouldScrollToTop + val shouldScrollToTop: StateFlow<Boolean> get() = _shouldScrollToTop + private val _shouldScrollToTop = MutableStateFlow(false) - private val _searchFocused = MutableLiveData(false) - val searchFocused: LiveData<Boolean> get() = _searchFocused + val searchFocused: StateFlow<Boolean> get() = _searchFocused + private val _searchFocused = MutableStateFlow(false) init { // Ensure keys are loaded so that ROM metadata can be decrypted. @@ -79,36 +79,36 @@ class GamesViewModel : ViewModel() { ) ) - _games.postValue(sortedList) + _games.value = sortedList } fun setSearchedGames(games: List<Game>) { - _searchedGames.postValue(games) + _searchedGames.value = games } fun setShouldSwapData(shouldSwap: Boolean) { - _shouldSwapData.postValue(shouldSwap) + _shouldSwapData.value = shouldSwap } fun setShouldScrollToTop(shouldScroll: Boolean) { - _shouldScrollToTop.postValue(shouldScroll) + _shouldScrollToTop.value = shouldScroll } fun setSearchFocused(searchFocused: Boolean) { - _searchFocused.postValue(searchFocused) + _searchFocused.value = searchFocused } fun reloadGames(directoryChanged: Boolean) { - if (isReloading.value == true) { + if (isReloading.value) { return } - _isReloading.postValue(true) + _isReloading.value = true viewModelScope.launch { withContext(Dispatchers.IO) { NativeLibrary.resetRomMetadata() setGames(GameHelper.getGames()) - _isReloading.postValue(false) + _isReloading.value = false if (directoryChanged) { setShouldSwapData(true) diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/model/HomeSetting.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/model/HomeSetting.kt index 498c222fa..b32e19373 100644 --- a/src/android/app/src/main/java/org/yuzu/yuzu_emu/model/HomeSetting.kt +++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/model/HomeSetting.kt @@ -3,8 +3,8 @@ package org.yuzu.yuzu_emu.model -import androidx.lifecycle.LiveData -import androidx.lifecycle.MutableLiveData +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow data class HomeSetting( val titleId: Int, @@ -14,5 +14,5 @@ data class HomeSetting( val isEnabled: () -> Boolean = { true }, val disabledTitleId: Int = 0, val disabledMessageId: Int = 0, - val details: LiveData<String> = MutableLiveData("") + val details: StateFlow<String> = MutableStateFlow("") ) diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/model/HomeViewModel.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/model/HomeViewModel.kt index a48ef7a88..756f76721 100644 --- a/src/android/app/src/main/java/org/yuzu/yuzu_emu/model/HomeViewModel.kt +++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/model/HomeViewModel.kt @@ -5,47 +5,43 @@ package org.yuzu.yuzu_emu.model import android.net.Uri import androidx.fragment.app.FragmentActivity -import androidx.lifecycle.LiveData -import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.preference.PreferenceManager +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow import org.yuzu.yuzu_emu.YuzuApplication import org.yuzu.yuzu_emu.utils.GameHelper class HomeViewModel : ViewModel() { - private val _navigationVisible = MutableLiveData<Pair<Boolean, Boolean>>() - val navigationVisible: LiveData<Pair<Boolean, Boolean>> get() = _navigationVisible + val navigationVisible: StateFlow<Pair<Boolean, Boolean>> get() = _navigationVisible + private val _navigationVisible = MutableStateFlow(Pair(false, false)) - private val _statusBarShadeVisible = MutableLiveData(true) - val statusBarShadeVisible: LiveData<Boolean> get() = _statusBarShadeVisible + val statusBarShadeVisible: StateFlow<Boolean> get() = _statusBarShadeVisible + private val _statusBarShadeVisible = MutableStateFlow(true) - private val _shouldPageForward = MutableLiveData(false) - val shouldPageForward: LiveData<Boolean> get() = _shouldPageForward + val shouldPageForward: StateFlow<Boolean> get() = _shouldPageForward + private val _shouldPageForward = MutableStateFlow(false) - private val _gamesDir = MutableLiveData( + val gamesDir: StateFlow<String> get() = _gamesDir + private val _gamesDir = MutableStateFlow( Uri.parse( PreferenceManager.getDefaultSharedPreferences(YuzuApplication.appContext) .getString(GameHelper.KEY_GAME_PATH, "") ).path ?: "" ) - val gamesDir: LiveData<String> get() = _gamesDir var navigatedToSetup = false - init { - _navigationVisible.value = Pair(false, false) - } - fun setNavigationVisibility(visible: Boolean, animated: Boolean) { - if (_navigationVisible.value?.first == visible) { + if (navigationVisible.value.first == visible) { return } _navigationVisible.value = Pair(visible, animated) } fun setStatusBarShadeVisibility(visible: Boolean) { - if (_statusBarShadeVisible.value == visible) { + if (statusBarShadeVisible.value == visible) { return } _statusBarShadeVisible.value = visible diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/model/SettingsViewModel.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/model/SettingsViewModel.kt index d16d15fa6..53fa7a8de 100644 --- a/src/android/app/src/main/java/org/yuzu/yuzu_emu/model/SettingsViewModel.kt +++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/model/SettingsViewModel.kt @@ -3,48 +3,43 @@ package org.yuzu.yuzu_emu.model -import androidx.lifecycle.LiveData -import androidx.lifecycle.MutableLiveData -import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow import org.yuzu.yuzu_emu.R import org.yuzu.yuzu_emu.YuzuApplication import org.yuzu.yuzu_emu.features.settings.model.view.SettingsItem -class SettingsViewModel(private val savedStateHandle: SavedStateHandle) : ViewModel() { +class SettingsViewModel : ViewModel() { var game: Game? = null var shouldSave = false var clickedItem: SettingsItem? = null - private val _toolbarTitle = MutableLiveData("") - val toolbarTitle: LiveData<String> get() = _toolbarTitle + val shouldRecreate: StateFlow<Boolean> get() = _shouldRecreate + private val _shouldRecreate = MutableStateFlow(false) - private val _shouldRecreate = MutableLiveData(false) - val shouldRecreate: LiveData<Boolean> get() = _shouldRecreate + val shouldNavigateBack: StateFlow<Boolean> get() = _shouldNavigateBack + private val _shouldNavigateBack = MutableStateFlow(false) - private val _shouldNavigateBack = MutableLiveData(false) - val shouldNavigateBack: LiveData<Boolean> get() = _shouldNavigateBack + val shouldShowResetSettingsDialog: StateFlow<Boolean> get() = _shouldShowResetSettingsDialog + private val _shouldShowResetSettingsDialog = MutableStateFlow(false) - private val _shouldShowResetSettingsDialog = MutableLiveData(false) - val shouldShowResetSettingsDialog: LiveData<Boolean> get() = _shouldShowResetSettingsDialog + val shouldReloadSettingsList: StateFlow<Boolean> get() = _shouldReloadSettingsList + private val _shouldReloadSettingsList = MutableStateFlow(false) - private val _shouldReloadSettingsList = MutableLiveData(false) - val shouldReloadSettingsList: LiveData<Boolean> get() = _shouldReloadSettingsList + val isUsingSearch: StateFlow<Boolean> get() = _isUsingSearch + private val _isUsingSearch = MutableStateFlow(false) - private val _isUsingSearch = MutableLiveData(false) - val isUsingSearch: LiveData<Boolean> get() = _isUsingSearch + val sliderProgress: StateFlow<Int> get() = _sliderProgress + private val _sliderProgress = MutableStateFlow(-1) - val sliderProgress = savedStateHandle.getStateFlow(KEY_SLIDER_PROGRESS, -1) + val sliderTextValue: StateFlow<String> get() = _sliderTextValue + private val _sliderTextValue = MutableStateFlow("") - val sliderTextValue = savedStateHandle.getStateFlow(KEY_SLIDER_TEXT_VALUE, "") - - val adapterItemChanged = savedStateHandle.getStateFlow(KEY_ADAPTER_ITEM_CHANGED, -1) - - fun setToolbarTitle(value: String) { - _toolbarTitle.value = value - } + val adapterItemChanged: StateFlow<Int> get() = _adapterItemChanged + private val _adapterItemChanged = MutableStateFlow(-1) fun setShouldRecreate(value: Boolean) { _shouldRecreate.value = value @@ -67,8 +62,8 @@ class SettingsViewModel(private val savedStateHandle: SavedStateHandle) : ViewMo } fun setSliderTextValue(value: Float, units: String) { - savedStateHandle[KEY_SLIDER_PROGRESS] = value - savedStateHandle[KEY_SLIDER_TEXT_VALUE] = String.format( + _sliderProgress.value = value.toInt() + _sliderTextValue.value = String.format( YuzuApplication.appContext.getString(R.string.value_with_units), value.toInt().toString(), units @@ -76,21 +71,15 @@ class SettingsViewModel(private val savedStateHandle: SavedStateHandle) : ViewMo } fun setSliderProgress(value: Float) { - savedStateHandle[KEY_SLIDER_PROGRESS] = value + _sliderProgress.value = value.toInt() } fun setAdapterItemChanged(value: Int) { - savedStateHandle[KEY_ADAPTER_ITEM_CHANGED] = value + _adapterItemChanged.value = value } fun clear() { game = null shouldSave = false } - - companion object { - const val KEY_SLIDER_TEXT_VALUE = "SliderTextValue" - const val KEY_SLIDER_PROGRESS = "SliderProgress" - const val KEY_ADAPTER_ITEM_CHANGED = "AdapterItemChanged" - } } diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/model/TaskViewModel.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/model/TaskViewModel.kt index 27ea725a5..531c2aaf0 100644 --- a/src/android/app/src/main/java/org/yuzu/yuzu_emu/model/TaskViewModel.kt +++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/model/TaskViewModel.kt @@ -3,29 +3,25 @@ package org.yuzu.yuzu_emu.model -import androidx.lifecycle.LiveData -import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.launch class TaskViewModel : ViewModel() { - private val _result = MutableLiveData<Any>() - val result: LiveData<Any> = _result + val result: StateFlow<Any> get() = _result + private val _result = MutableStateFlow(Any()) - private val _isComplete = MutableLiveData<Boolean>() - val isComplete: LiveData<Boolean> = _isComplete + val isComplete: StateFlow<Boolean> get() = _isComplete + private val _isComplete = MutableStateFlow(false) - private val _isRunning = MutableLiveData<Boolean>() - val isRunning: LiveData<Boolean> = _isRunning + val isRunning: StateFlow<Boolean> get() = _isRunning + private val _isRunning = MutableStateFlow(false) lateinit var task: () -> Any - init { - clear() - } - fun clear() { _result.value = Any() _isComplete.value = false @@ -33,15 +29,16 @@ class TaskViewModel : ViewModel() { } fun runTask() { - if (_isRunning.value == true) { + if (isRunning.value) { return } _isRunning.value = true viewModelScope.launch(Dispatchers.IO) { val res = task() - _result.postValue(res) - _isComplete.postValue(true) + _result.value = res + _isComplete.value = true + _isRunning.value = false } } } diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/ui/GamesFragment.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/ui/GamesFragment.kt index b0156dca5..805b89b31 100644 --- a/src/android/app/src/main/java/org/yuzu/yuzu_emu/ui/GamesFragment.kt +++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/ui/GamesFragment.kt @@ -3,6 +3,7 @@ package org.yuzu.yuzu_emu.ui +import android.annotation.SuppressLint import android.os.Bundle import android.view.LayoutInflater import android.view.View @@ -14,8 +15,12 @@ import androidx.core.view.WindowInsetsCompat import androidx.core.view.updatePadding import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.lifecycleScope +import androidx.lifecycle.repeatOnLifecycle import com.google.android.material.color.MaterialColors import com.google.android.material.transition.MaterialFadeThrough +import kotlinx.coroutines.launch import org.yuzu.yuzu_emu.R import org.yuzu.yuzu_emu.adapters.GameAdapter import org.yuzu.yuzu_emu.databinding.FragmentGamesBinding @@ -44,6 +49,8 @@ class GamesFragment : Fragment() { return binding.root } + // This is using the correct scope, lint is just acting up + @SuppressLint("UnsafeRepeatOnLifecycleDetector") override fun onViewCreated(view: View, savedInstanceState: Bundle?) { homeViewModel.setNavigationVisibility(visible = true, animated = false) @@ -80,37 +87,48 @@ class GamesFragment : Fragment() { if (_binding == null) { return@post } - binding.swipeRefresh.isRefreshing = gamesViewModel.isReloading.value!! + binding.swipeRefresh.isRefreshing = gamesViewModel.isReloading.value } } - gamesViewModel.apply { - // Watch for when we get updates to any of our games lists - isReloading.observe(viewLifecycleOwner) { isReloading -> - binding.swipeRefresh.isRefreshing = isReloading + viewLifecycleOwner.lifecycleScope.apply { + launch { + repeatOnLifecycle(Lifecycle.State.RESUMED) { + gamesViewModel.isReloading.collect { binding.swipeRefresh.isRefreshing = it } + } } - games.observe(viewLifecycleOwner) { - (binding.gridGames.adapter as GameAdapter).submitList(it) - if (it.isEmpty()) { - binding.noticeText.visibility = View.VISIBLE - } else { - binding.noticeText.visibility = View.GONE + launch { + repeatOnLifecycle(Lifecycle.State.RESUMED) { + gamesViewModel.games.collect { + (binding.gridGames.adapter as GameAdapter).submitList(it) + if (it.isEmpty()) { + binding.noticeText.visibility = View.VISIBLE + } else { + binding.noticeText.visibility = View.GONE + } + } } } - shouldSwapData.observe(viewLifecycleOwner) { shouldSwapData -> - if (shouldSwapData) { - (binding.gridGames.adapter as GameAdapter).submitList( - gamesViewModel.games.value!! - ) - gamesViewModel.setShouldSwapData(false) + launch { + repeatOnLifecycle(Lifecycle.State.RESUMED) { + gamesViewModel.shouldSwapData.collect { + if (it) { + (binding.gridGames.adapter as GameAdapter).submitList( + gamesViewModel.games.value + ) + gamesViewModel.setShouldSwapData(false) + } + } } } - - // Check if the user reselected the games menu item and then scroll to top of the list - shouldScrollToTop.observe(viewLifecycleOwner) { shouldScroll -> - if (shouldScroll) { - scrollToTop() - gamesViewModel.setShouldScrollToTop(false) + launch { + repeatOnLifecycle(Lifecycle.State.RESUMED) { + gamesViewModel.shouldScrollToTop.collect { + if (it) { + scrollToTop() + gamesViewModel.setShouldScrollToTop(false) + } + } } } } diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/ui/main/MainActivity.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/ui/main/MainActivity.kt index 7d8e06ad8..b6b6c6c17 100644 --- a/src/android/app/src/main/java/org/yuzu/yuzu_emu/ui/main/MainActivity.kt +++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/ui/main/MainActivity.kt @@ -19,7 +19,9 @@ import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen import androidx.core.view.ViewCompat import androidx.core.view.WindowCompat import androidx.core.view.WindowInsetsCompat +import androidx.lifecycle.Lifecycle import androidx.lifecycle.lifecycleScope +import androidx.lifecycle.repeatOnLifecycle import androidx.navigation.NavController import androidx.navigation.fragment.NavHostFragment import androidx.navigation.ui.setupWithNavController @@ -40,7 +42,6 @@ import org.yuzu.yuzu_emu.activities.EmulationActivity import org.yuzu.yuzu_emu.databinding.ActivityMainBinding import org.yuzu.yuzu_emu.databinding.DialogProgressBarBinding import org.yuzu.yuzu_emu.features.settings.model.Settings -import org.yuzu.yuzu_emu.features.settings.utils.SettingsFile import org.yuzu.yuzu_emu.fragments.IndeterminateProgressDialogFragment import org.yuzu.yuzu_emu.fragments.MessageDialogFragment import org.yuzu.yuzu_emu.model.GamesViewModel @@ -107,7 +108,7 @@ class MainActivity : AppCompatActivity(), ThemeProvider { R.id.homeSettingsFragment -> { val action = HomeNavigationDirections.actionGlobalSettingsActivity( null, - SettingsFile.FILE_NAME_CONFIG + Settings.MenuTag.SECTION_ROOT ) navHostFragment.navController.navigate(action) } @@ -115,16 +116,22 @@ class MainActivity : AppCompatActivity(), ThemeProvider { } // Prevents navigation from being drawn for a short time on recreation if set to hidden - if (!homeViewModel.navigationVisible.value?.first!!) { + if (!homeViewModel.navigationVisible.value.first) { binding.navigationView.visibility = View.INVISIBLE binding.statusBarShade.visibility = View.INVISIBLE } - homeViewModel.navigationVisible.observe(this) { - showNavigation(it.first, it.second) - } - homeViewModel.statusBarShadeVisible.observe(this) { visible -> - showStatusBarShade(visible) + lifecycleScope.apply { + launch { + repeatOnLifecycle(Lifecycle.State.CREATED) { + homeViewModel.navigationVisible.collect { showNavigation(it.first, it.second) } + } + } + launch { + repeatOnLifecycle(Lifecycle.State.CREATED) { + homeViewModel.statusBarShadeVisible.collect { showStatusBarShade(it) } + } + } } // Dismiss previous notifications (should not happen unless a crash occurred) diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/utils/GameIconUtils.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/utils/GameIconUtils.kt index c0fe596d7..9fe99fab1 100644 --- a/src/android/app/src/main/java/org/yuzu/yuzu_emu/utils/GameIconUtils.kt +++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/utils/GameIconUtils.kt @@ -6,9 +6,11 @@ package org.yuzu.yuzu_emu.utils import android.graphics.Bitmap import android.graphics.BitmapFactory import android.widget.ImageView +import androidx.core.graphics.drawable.toBitmap import androidx.core.graphics.drawable.toDrawable import coil.ImageLoader import coil.decode.DataSource +import coil.executeBlocking import coil.fetch.DrawableResult import coil.fetch.FetchResult import coil.fetch.Fetcher @@ -74,4 +76,13 @@ object GameIconUtils { .build() imageLoader.enqueue(request) } + + fun getGameIcon(game: Game): Bitmap { + val request = ImageRequest.Builder(YuzuApplication.appContext) + .data(game) + .error(R.drawable.default_icon) + .build() + return imageLoader.executeBlocking(request) + .drawable!!.toBitmap(config = Bitmap.Config.ARGB_8888) + } } diff --git a/src/android/app/src/main/jni/config.cpp b/src/android/app/src/main/jni/config.cpp index 34b425cb4..81120ab0f 100644 --- a/src/android/app/src/main/jni/config.cpp +++ b/src/android/app/src/main/jni/config.cpp @@ -282,7 +282,7 @@ void Config::ReadValues() { std::stringstream ss(title_list); std::string line; while (std::getline(ss, line, '|')) { - const auto title_id = std::stoul(line, nullptr, 16); + const auto title_id = std::strtoul(line.c_str(), nullptr, 16); const auto disabled_list = config->Get("AddOns", "disabled_" + line, ""); std::stringstream inner_ss(disabled_list); diff --git a/src/android/app/src/main/jni/native.cpp b/src/android/app/src/main/jni/native.cpp index b9ecefa74..f31fe054b 100644 --- a/src/android/app/src/main/jni/native.cpp +++ b/src/android/app/src/main/jni/native.cpp @@ -262,9 +262,6 @@ public: Core::SystemResultStatus InitializeEmulation(const std::string& filepath) { std::scoped_lock lock(m_mutex); - // Loads the configuration. - Config{}; - // Create the render window. m_window = std::make_unique<EmuWindow_Android>(&m_input_subsystem, m_native_window, m_vulkan_library); @@ -330,12 +327,13 @@ public: m_system.ShutdownMainProcess(); m_detached_tasks.WaitForAllTasks(); m_load_result = Core::SystemResultStatus::ErrorNotInitialized; + m_window.reset(); + OnEmulationStopped(Core::SystemResultStatus::Success); + return; } // Tear down the render window. m_window.reset(); - - OnEmulationStopped(m_load_result); } void PauseEmulation() { @@ -672,18 +670,6 @@ jboolean Java_org_yuzu_yuzu_1emu_NativeLibrary_isPaused(JNIEnv* env, jclass claz return static_cast<jboolean>(EmulationSession::GetInstance().IsPaused()); } -void Java_org_yuzu_yuzu_1emu_NativeLibrary_muteAduio(JNIEnv* env, jclass clazz) { - Settings::values.audio_muted = true; -} - -void Java_org_yuzu_yuzu_1emu_NativeLibrary_unmuteAudio(JNIEnv* env, jclass clazz) { - Settings::values.audio_muted = false; -} - -jboolean Java_org_yuzu_yuzu_1emu_NativeLibrary_isMuted(JNIEnv* env, jclass clazz) { - return static_cast<jboolean>(Settings::values.audio_muted.GetValue()); -} - jboolean Java_org_yuzu_yuzu_1emu_NativeLibrary_isHandheldOnly(JNIEnv* env, jclass clazz) { return EmulationSession::GetInstance().IsHandheldOnly(); } diff --git a/src/android/app/src/main/res/drawable/shortcut.xml b/src/android/app/src/main/res/drawable/shortcut.xml new file mode 100644 index 000000000..c749e5d72 --- /dev/null +++ b/src/android/app/src/main/res/drawable/shortcut.xml @@ -0,0 +1,11 @@ +<?xml version="1.0" encoding="utf-8"?> +<layer-list xmlns:android="http://schemas.android.com/apk/res/android"> + + <item> + <color android:color="@android:color/white" /> + </item> + <item android:id="@+id/shortcut_foreground"> + <bitmap android:src="@drawable/default_icon" /> + </item> + +</layer-list> diff --git a/src/android/app/src/main/res/navigation/emulation_navigation.xml b/src/android/app/src/main/res/navigation/emulation_navigation.xml index c7be37f9b..cfc494b3f 100644 --- a/src/android/app/src/main/res/navigation/emulation_navigation.xml +++ b/src/android/app/src/main/res/navigation/emulation_navigation.xml @@ -27,7 +27,7 @@ app:nullable="true" /> <argument android:name="menuTag" - app:argType="string" /> + app:argType="org.yuzu.yuzu_emu.features.settings.model.Settings$MenuTag" /> </activity> <action diff --git a/src/android/app/src/main/res/navigation/home_navigation.xml b/src/android/app/src/main/res/navigation/home_navigation.xml index 2085430bf..2e0ce7a3d 100644 --- a/src/android/app/src/main/res/navigation/home_navigation.xml +++ b/src/android/app/src/main/res/navigation/home_navigation.xml @@ -82,7 +82,7 @@ app:nullable="true" /> <argument android:name="menuTag" - app:argType="string" /> + app:argType="org.yuzu.yuzu_emu.features.settings.model.Settings$MenuTag" /> </activity> <action diff --git a/src/android/app/src/main/res/navigation/settings_navigation.xml b/src/android/app/src/main/res/navigation/settings_navigation.xml index 88e1b4587..1d87d36b3 100644 --- a/src/android/app/src/main/res/navigation/settings_navigation.xml +++ b/src/android/app/src/main/res/navigation/settings_navigation.xml @@ -10,7 +10,7 @@ android:label="SettingsFragment"> <argument android:name="menuTag" - app:argType="string" /> + app:argType="org.yuzu.yuzu_emu.features.settings.model.Settings$MenuTag" /> <argument android:name="game" app:argType="org.yuzu.yuzu_emu.model.Game" diff --git a/src/android/app/src/main/res/values/dimens.xml b/src/android/app/src/main/res/values/dimens.xml index 00757e5e8..7b2296d95 100644 --- a/src/android/app/src/main/res/values/dimens.xml +++ b/src/android/app/src/main/res/values/dimens.xml @@ -12,6 +12,7 @@ <dimen name="spacing_refresh_end">72dp</dimen> <dimen name="menu_width">256dp</dimen> <dimen name="card_width">165dp</dimen> + <dimen name="icon_inset">24dp</dimen> <dimen name="dialog_margin">20dp</dimen> <dimen name="elevated_app_bar">3dp</dimen> diff --git a/src/common/fs/fs.cpp b/src/common/fs/fs.cpp index 36e67c145..174aed49b 100644 --- a/src/common/fs/fs.cpp +++ b/src/common/fs/fs.cpp @@ -528,38 +528,41 @@ void IterateDirEntriesRecursively(const std::filesystem::path& path, // Generic Filesystem Operations bool Exists(const fs::path& path) { + std::error_code ec; #ifdef ANDROID if (Android::IsContentUri(path)) { return Android::Exists(path); } else { - return fs::exists(path); + return fs::exists(path, ec); } #else - return fs::exists(path); + return fs::exists(path, ec); #endif } bool IsFile(const fs::path& path) { + std::error_code ec; #ifdef ANDROID if (Android::IsContentUri(path)) { return !Android::IsDirectory(path); } else { - return fs::is_regular_file(path); + return fs::is_regular_file(path, ec); } #else - return fs::is_regular_file(path); + return fs::is_regular_file(path, ec); #endif } bool IsDir(const fs::path& path) { + std::error_code ec; #ifdef ANDROID if (Android::IsContentUri(path)) { return Android::IsDirectory(path); } else { - return fs::is_directory(path); + return fs::is_directory(path, ec); } #else - return fs::is_directory(path); + return fs::is_directory(path, ec); #endif } diff --git a/src/common/logging/filter.cpp b/src/common/logging/filter.cpp index c95909561..4e3a614a4 100644 --- a/src/common/logging/filter.cpp +++ b/src/common/logging/filter.cpp @@ -112,7 +112,7 @@ bool ParseFilterRule(Filter& instance, Iterator begin, Iterator end) { SUB(Service, NCM) \ SUB(Service, NFC) \ SUB(Service, NFP) \ - SUB(Service, NGCT) \ + SUB(Service, NGC) \ SUB(Service, NIFM) \ SUB(Service, NIM) \ SUB(Service, NOTIF) \ diff --git a/src/common/logging/types.h b/src/common/logging/types.h index 8356e3183..08af50ee0 100644 --- a/src/common/logging/types.h +++ b/src/common/logging/types.h @@ -80,7 +80,7 @@ enum class Class : u8 { Service_NCM, ///< The NCM service Service_NFC, ///< The NFC (Near-field communication) service Service_NFP, ///< The NFP service - Service_NGCT, ///< The NGCT (No Good Content for Terra) service + Service_NGC, ///< The NGC (No Good Content) service Service_NIFM, ///< The NIFM (Network interface) service Service_NIM, ///< The NIM service Service_NOTIF, ///< The NOTIF (Notification) service diff --git a/src/common/polyfill_thread.h b/src/common/polyfill_thread.h index b5ef055db..41cbb9ed5 100644 --- a/src/common/polyfill_thread.h +++ b/src/common/polyfill_thread.h @@ -19,8 +19,8 @@ namespace Common { template <typename Condvar, typename Lock, typename Pred> -void CondvarWait(Condvar& cv, Lock& lock, std::stop_token token, Pred&& pred) { - cv.wait(lock, token, std::move(pred)); +void CondvarWait(Condvar& cv, std::unique_lock<Lock>& lk, std::stop_token token, Pred&& pred) { + cv.wait(lk, token, std::move(pred)); } template <typename Rep, typename Period> @@ -332,13 +332,17 @@ private: namespace Common { template <typename Condvar, typename Lock, typename Pred> -void CondvarWait(Condvar& cv, Lock& lock, std::stop_token token, Pred pred) { +void CondvarWait(Condvar& cv, std::unique_lock<Lock>& lk, std::stop_token token, Pred pred) { if (token.stop_requested()) { return; } - std::stop_callback callback(token, [&] { cv.notify_all(); }); - cv.wait(lock, [&] { return pred() || token.stop_requested(); }); + std::stop_callback callback(token, [&] { + { std::scoped_lock lk2{*lk.mutex()}; } + cv.notify_all(); + }); + + cv.wait(lk, [&] { return pred() || token.stop_requested(); }); } template <typename Rep, typename Period> @@ -353,8 +357,10 @@ bool StoppableTimedWait(std::stop_token token, const std::chrono::duration<Rep, std::stop_callback cb(token, [&] { // Wake up the waiting thread. - std::unique_lock lk{m}; - stop_requested = true; + { + std::scoped_lock lk{m}; + stop_requested = true; + } cv.notify_one(); }); diff --git a/src/common/settings.h b/src/common/settings.h index b15213bd7..82ec9077e 100644 --- a/src/common/settings.h +++ b/src/common/settings.h @@ -348,6 +348,8 @@ struct Values { Category::RendererDebug}; Setting<bool> disable_shader_loop_safety_checks{ linkage, false, "disable_shader_loop_safety_checks", Category::RendererDebug}; + Setting<bool> enable_renderdoc_hotkey{linkage, false, "renderdoc_hotkey", + Category::RendererDebug}; // System SwitchableSetting<Language, true> language_index{linkage, diff --git a/src/common/settings_common.h b/src/common/settings_common.h index 5b170dfd5..1800ab10d 100644 --- a/src/common/settings_common.h +++ b/src/common/settings_common.h @@ -225,6 +225,16 @@ public: */ [[nodiscard]] virtual constexpr u32 EnumIndex() const = 0; + /** + * @returns True if the underlying type is a floating point storage + */ + [[nodiscard]] virtual constexpr bool IsFloatingPoint() const = 0; + + /** + * @returns True if the underlying type is an integer storage + */ + [[nodiscard]] virtual constexpr bool IsIntegral() const = 0; + /* * Switchable settings */ diff --git a/src/common/settings_setting.h b/src/common/settings_setting.h index e10843c73..7be6f26f7 100644 --- a/src/common/settings_setting.h +++ b/src/common/settings_setting.h @@ -10,6 +10,7 @@ #include <string> #include <typeindex> #include <typeinfo> +#include <fmt/core.h> #include "common/common_types.h" #include "common/settings_common.h" #include "common/settings_enums.h" @@ -115,8 +116,12 @@ protected: } else if constexpr (std::is_same_v<Type, AudioEngine>) { // Compatibility with old AudioEngine setting being a string return CanonicalizeEnum(value_); + } else if constexpr (std::is_floating_point_v<Type>) { + return fmt::format("{:f}", value_); + } else if constexpr (std::is_enum_v<Type>) { + return std::to_string(static_cast<u32>(value_)); } else { - return std::to_string(static_cast<u64>(value_)); + return std::to_string(value_); } } @@ -180,13 +185,15 @@ public: this->SetValue(static_cast<u32>(std::stoul(input))); } else if constexpr (std::is_same_v<Type, bool>) { this->SetValue(input == "true"); - } else if constexpr (std::is_same_v<Type, AudioEngine>) { - this->SetValue(ToEnum<Type>(input)); + } else if constexpr (std::is_same_v<Type, float>) { + this->SetValue(std::stof(input)); } else { this->SetValue(static_cast<Type>(std::stoll(input))); } } catch (std::invalid_argument&) { this->SetValue(this->GetDefault()); + } catch (std::out_of_range&) { + this->SetValue(this->GetDefault()); } } @@ -215,11 +222,27 @@ public: } } + [[nodiscard]] constexpr bool IsFloatingPoint() const final { + return std::is_floating_point_v<Type>; + } + + [[nodiscard]] constexpr bool IsIntegral() const final { + return std::is_integral_v<Type>; + } + [[nodiscard]] std::string MinVal() const override final { - return this->ToString(minimum); + if constexpr (std::is_arithmetic_v<Type> && !ranged) { + return this->ToString(std::numeric_limits<Type>::min()); + } else { + return this->ToString(minimum); + } } [[nodiscard]] std::string MaxVal() const override final { - return this->ToString(maximum); + if constexpr (std::is_arithmetic_v<Type> && !ranged) { + return this->ToString(std::numeric_limits<Type>::max()); + } else { + return this->ToString(maximum); + } } [[nodiscard]] constexpr bool Ranged() const override { diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txt index c33910ade..30d2f7df6 100644 --- a/src/core/CMakeLists.txt +++ b/src/core/CMakeLists.txt @@ -627,8 +627,8 @@ add_library(core STATIC hle/service/nfp/nfp_interface.h hle/service/nfp/nfp_result.h hle/service/nfp/nfp_types.h - hle/service/ngct/ngct.cpp - hle/service/ngct/ngct.h + hle/service/ngc/ngc.cpp + hle/service/ngc/ngc.h hle/service/nifm/nifm.cpp hle/service/nifm/nifm.h hle/service/nim/nim.cpp @@ -864,6 +864,8 @@ add_library(core STATIC telemetry_session.h tools/freezer.cpp tools/freezer.h + tools/renderdoc.cpp + tools/renderdoc.h ) if (MSVC) @@ -879,6 +881,7 @@ else() -Werror=conversion -Wno-sign-conversion + -Wno-cast-function-type $<$<CXX_COMPILER_ID:Clang>:-fsized-deallocation> ) @@ -887,7 +890,7 @@ endif() create_target_directory_groups(core) target_link_libraries(core PUBLIC common PRIVATE audio_core network video_core nx_tzdb) -target_link_libraries(core PUBLIC Boost::headers PRIVATE fmt::fmt nlohmann_json::nlohmann_json mbedtls Opus::opus) +target_link_libraries(core PUBLIC Boost::headers PRIVATE fmt::fmt nlohmann_json::nlohmann_json mbedtls Opus::opus renderdoc) if (MINGW) target_link_libraries(core PRIVATE ${MSWSOCK_LIBRARY}) endif() diff --git a/src/core/core.cpp b/src/core/core.cpp index 2d6e61398..e8300cd05 100644 --- a/src/core/core.cpp +++ b/src/core/core.cpp @@ -51,6 +51,7 @@ #include "core/reporter.h" #include "core/telemetry_session.h" #include "core/tools/freezer.h" +#include "core/tools/renderdoc.h" #include "network/network.h" #include "video_core/host1x/host1x.h" #include "video_core/renderer_base.h" @@ -281,6 +282,10 @@ struct System::Impl { microprofile_cpu[2] = MICROPROFILE_TOKEN(ARM_CPU2); microprofile_cpu[3] = MICROPROFILE_TOKEN(ARM_CPU3); + if (Settings::values.enable_renderdoc_hotkey) { + renderdoc_api = std::make_unique<Tools::RenderdocAPI>(); + } + LOG_DEBUG(Core, "Initialized OK"); return SystemResultStatus::Success; @@ -521,6 +526,8 @@ struct System::Impl { std::unique_ptr<Tools::Freezer> memory_freezer; std::array<u8, 0x20> build_id{}; + std::unique_ptr<Tools::RenderdocAPI> renderdoc_api; + /// Frontend applets Service::AM::Applets::AppletManager applet_manager; @@ -1024,6 +1031,10 @@ const Network::RoomNetwork& System::GetRoomNetwork() const { return impl->room_network; } +Tools::RenderdocAPI& System::GetRenderdocAPI() { + return *impl->renderdoc_api; +} + void System::RunServer(std::unique_ptr<Service::ServerManager>&& server_manager) { return impl->kernel.RunServer(std::move(server_manager)); } diff --git a/src/core/core.h b/src/core/core.h index fba312125..df20f26f3 100644 --- a/src/core/core.h +++ b/src/core/core.h @@ -102,6 +102,10 @@ namespace Network { class RoomNetwork; } +namespace Tools { +class RenderdocAPI; +} + namespace Core { class ARM_Interface; @@ -413,6 +417,8 @@ public: /// Gets an immutable reference to the Room Network. [[nodiscard]] const Network::RoomNetwork& GetRoomNetwork() const; + [[nodiscard]] Tools::RenderdocAPI& GetRenderdocAPI(); + void SetExitLocked(bool locked); bool GetExitLocked() const; diff --git a/src/core/crypto/key_manager.cpp b/src/core/crypto/key_manager.cpp index e13c5cdc7..43a3c5ffd 100644 --- a/src/core/crypto/key_manager.cpp +++ b/src/core/crypto/key_manager.cpp @@ -724,14 +724,14 @@ void KeyManager::LoadFromFile(const std::filesystem::path& file_path, bool is_ti continue; } - const auto index = std::stoul(out[0].substr(8, 2), nullptr, 16); + const auto index = std::strtoul(out[0].substr(8, 2).c_str(), nullptr, 16); keyblobs[index] = Common::HexStringToArray<0x90>(out[1]); } else if (out[0].compare(0, 18, "encrypted_keyblob_") == 0) { if (!ValidCryptoRevisionString(out[0], 18, 2)) { continue; } - const auto index = std::stoul(out[0].substr(18, 2), nullptr, 16); + const auto index = std::strtoul(out[0].substr(18, 2).c_str(), nullptr, 16); encrypted_keyblobs[index] = Common::HexStringToArray<0xB0>(out[1]); } else if (out[0].compare(0, 20, "eticket_extended_kek") == 0) { eticket_extended_kek = Common::HexStringToArray<576>(out[1]); @@ -750,7 +750,7 @@ void KeyManager::LoadFromFile(const std::filesystem::path& file_path, bool is_ti } if (out[0].compare(0, kv.second.size(), kv.second) == 0) { const auto index = - std::stoul(out[0].substr(kv.second.size(), 2), nullptr, 16); + std::strtoul(out[0].substr(kv.second.size(), 2).c_str(), nullptr, 16); const auto sub = kv.first.second; if (sub == 0) { s128_keys[{kv.first.first, index, 0}] = @@ -770,7 +770,7 @@ void KeyManager::LoadFromFile(const std::filesystem::path& file_path, bool is_ti const auto& match = kak_names[j]; if (out[0].compare(0, std::strlen(match), match) == 0) { const auto index = - std::stoul(out[0].substr(std::strlen(match), 2), nullptr, 16); + std::strtoul(out[0].substr(std::strlen(match), 2).c_str(), nullptr, 16); s128_keys[{S128KeyType::KeyArea, index, j}] = Common::HexStringToArray<16>(out[1]); } diff --git a/src/core/file_sys/ips_layer.cpp b/src/core/file_sys/ips_layer.cpp index efdf18cee..7be1322cc 100644 --- a/src/core/file_sys/ips_layer.cpp +++ b/src/core/file_sys/ips_layer.cpp @@ -165,7 +165,7 @@ static std::string EscapeStringSequences(std::string in) { void IPSwitchCompiler::ParseFlag(const std::string& line) { if (StartsWith(line, "@flag offset_shift ")) { // Offset Shift Flag - offset_shift = std::stoll(line.substr(19), nullptr, 0); + offset_shift = std::strtoll(line.substr(19).c_str(), nullptr, 0); } else if (StartsWith(line, "@little-endian")) { // Set values to read as little endian is_little_endian = true; @@ -263,7 +263,7 @@ void IPSwitchCompiler::Parse() { // 11 - 8 hex digit offset + space + minimum two digit overwrite val if (patch_line.length() < 11) break; - auto offset = std::stoul(patch_line.substr(0, 8), nullptr, 16); + auto offset = std::strtoul(patch_line.substr(0, 8).c_str(), nullptr, 16); offset += static_cast<unsigned long>(offset_shift); std::vector<u8> replace; diff --git a/src/core/file_sys/patch_manager.cpp b/src/core/file_sys/patch_manager.cpp index a4baddb15..8e475f25a 100644 --- a/src/core/file_sys/patch_manager.cpp +++ b/src/core/file_sys/patch_manager.cpp @@ -294,11 +294,11 @@ std::vector<u8> PatchManager::PatchNSO(const std::vector<u8>& nso, const std::st return out; } -bool PatchManager::HasNSOPatch(const BuildID& build_id_) const { +bool PatchManager::HasNSOPatch(const BuildID& build_id_, std::string_view name) const { const auto build_id_raw = Common::HexToString(build_id_); const auto build_id = build_id_raw.substr(0, build_id_raw.find_last_not_of('0') + 1); - LOG_INFO(Loader, "Querying NSO patch existence for build_id={}", build_id); + LOG_INFO(Loader, "Querying NSO patch existence for build_id={}, name={}", build_id, name); const auto load_dir = fs_controller.GetModificationLoadRoot(title_id); if (load_dir == nullptr) { diff --git a/src/core/file_sys/patch_manager.h b/src/core/file_sys/patch_manager.h index adcde7b7d..03e9c7301 100644 --- a/src/core/file_sys/patch_manager.h +++ b/src/core/file_sys/patch_manager.h @@ -52,7 +52,7 @@ public: // Checks to see if PatchNSO() will have any effect given the NSO's build ID. // Used to prevent expensive copies in NSO loader. - [[nodiscard]] bool HasNSOPatch(const BuildID& build_id) const; + [[nodiscard]] bool HasNSOPatch(const BuildID& build_id, std::string_view name) const; // Creates a CheatList object with all [[nodiscard]] std::vector<Core::Memory::CheatEntry> CreateCheatList( diff --git a/src/core/hid/hid_core.cpp b/src/core/hid/hid_core.cpp index 7d6373414..cf53c04d9 100644 --- a/src/core/hid/hid_core.cpp +++ b/src/core/hid/hid_core.cpp @@ -154,6 +154,14 @@ NpadIdType HIDCore::GetFirstDisconnectedNpadId() const { return NpadIdType::Player1; } +void HIDCore::SetLastActiveController(NpadIdType npad_id) { + last_active_controller = npad_id; +} + +NpadIdType HIDCore::GetLastActiveController() const { + return last_active_controller; +} + void HIDCore::EnableAllControllerConfiguration() { player_1->EnableConfiguration(); player_2->EnableConfiguration(); diff --git a/src/core/hid/hid_core.h b/src/core/hid/hid_core.h index 5fe36551e..80abab18b 100644 --- a/src/core/hid/hid_core.h +++ b/src/core/hid/hid_core.h @@ -48,6 +48,12 @@ public: /// Returns the first disconnected npad id NpadIdType GetFirstDisconnectedNpadId() const; + /// Sets the npad id of the last active controller + void SetLastActiveController(NpadIdType npad_id); + + /// Returns the npad id of the last controller that pushed a button + NpadIdType GetLastActiveController() const; + /// Sets all emulated controllers into configuring mode. void EnableAllControllerConfiguration(); @@ -77,6 +83,7 @@ private: std::unique_ptr<EmulatedConsole> console; std::unique_ptr<EmulatedDevices> devices; NpadStyleTag supported_style_tag{NpadStyleSet::All}; + NpadIdType last_active_controller{NpadIdType::Handheld}; }; } // namespace Core::HID diff --git a/src/core/hle/kernel/k_process.cpp b/src/core/hle/kernel/k_process.cpp index 703049ede..4a099286b 100644 --- a/src/core/hle/kernel/k_process.cpp +++ b/src/core/hle/kernel/k_process.cpp @@ -96,6 +96,7 @@ Result KProcess::Initialize(KProcess* process, Core::System& system, std::string process->m_is_suspended = false; process->m_schedule_count = 0; process->m_is_handle_table_initialized = false; + process->m_is_hbl = false; // Open a reference to the resource limit. process->m_resource_limit->Open(); @@ -351,12 +352,14 @@ Result KProcess::SetActivity(ProcessActivity activity) { R_SUCCEED(); } -Result KProcess::LoadFromMetadata(const FileSys::ProgramMetadata& metadata, std::size_t code_size) { +Result KProcess::LoadFromMetadata(const FileSys::ProgramMetadata& metadata, std::size_t code_size, + bool is_hbl) { m_program_id = metadata.GetTitleID(); m_ideal_core = metadata.GetMainThreadCore(); m_is_64bit_process = metadata.Is64BitProgram(); m_system_resource_size = metadata.GetSystemResourceSize(); m_image_size = code_size; + m_is_hbl = is_hbl; if (metadata.GetAddressSpaceType() == FileSys::ProgramAddressSpaceType::Is39Bit) { // For 39-bit processes, the ASLR region starts at 0x800'0000 and is ~512GiB large. diff --git a/src/core/hle/kernel/k_process.h b/src/core/hle/kernel/k_process.h index 4fdeaf11a..146e07a57 100644 --- a/src/core/hle/kernel/k_process.h +++ b/src/core/hle/kernel/k_process.h @@ -338,7 +338,8 @@ public: * @returns ResultSuccess if all relevant metadata was able to be * loaded and parsed. Otherwise, an error code is returned. */ - Result LoadFromMetadata(const FileSys::ProgramMetadata& metadata, std::size_t code_size); + Result LoadFromMetadata(const FileSys::ProgramMetadata& metadata, std::size_t code_size, + bool is_hbl); /** * Starts the main application thread for this process. @@ -368,6 +369,10 @@ public: return GetProcessId(); } + bool IsHbl() const { + return m_is_hbl; + } + bool IsSignaled() const override; void DoWorkerTaskImpl(); @@ -525,6 +530,7 @@ private: bool m_is_immortal{}; bool m_is_handle_table_initialized{}; bool m_is_initialized{}; + bool m_is_hbl{}; std::atomic<u16> m_num_running_threads{}; diff --git a/src/core/hle/kernel/svc/svc_debug_string.cpp b/src/core/hle/kernel/svc/svc_debug_string.cpp index 4c14ce668..00b65429b 100644 --- a/src/core/hle/kernel/svc/svc_debug_string.cpp +++ b/src/core/hle/kernel/svc/svc_debug_string.cpp @@ -14,7 +14,7 @@ Result OutputDebugString(Core::System& system, u64 address, u64 len) { std::string str(len, '\0'); GetCurrentMemory(system.Kernel()).ReadBlock(address, str.data(), str.size()); - LOG_DEBUG(Debug_Emulated, "{}", str); + LOG_INFO(Debug_Emulated, "{}", str); R_SUCCEED(); } diff --git a/src/core/hle/kernel/svc/svc_exception.cpp b/src/core/hle/kernel/svc/svc_exception.cpp index 580cf2f75..c581c086b 100644 --- a/src/core/hle/kernel/svc/svc_exception.cpp +++ b/src/core/hle/kernel/svc/svc_exception.cpp @@ -3,6 +3,7 @@ #include "core/core.h" #include "core/debugger/debugger.h" +#include "core/hle/kernel/k_process.h" #include "core/hle/kernel/k_thread.h" #include "core/hle/kernel/svc.h" #include "core/hle/kernel/svc_types.h" @@ -107,7 +108,10 @@ void Break(Core::System& system, BreakReason reason, u64 info1, u64 info2) { system.ArmInterface(static_cast<std::size_t>(thread_processor_id)).LogBacktrace(); } - if (system.DebuggerEnabled()) { + const bool is_hbl = GetCurrentProcess(system.Kernel()).IsHbl(); + const bool should_break = is_hbl || !notification_only; + + if (system.DebuggerEnabled() && should_break) { auto* thread = system.Kernel().GetCurrentEmuThread(); system.GetDebugger().NotifyThreadStopped(thread); thread->RequestSuspend(Kernel::SuspendType::Debug); diff --git a/src/core/hle/service/am/am.cpp b/src/core/hle/service/am/am.cpp index f9c4f9678..8ffdd19e7 100644 --- a/src/core/hle/service/am/am.cpp +++ b/src/core/hle/service/am/am.cpp @@ -1386,7 +1386,7 @@ IApplicationFunctions::IApplicationFunctions(Core::System& system_) {25, &IApplicationFunctions::ExtendSaveData, "ExtendSaveData"}, {26, &IApplicationFunctions::GetSaveDataSize, "GetSaveDataSize"}, {27, &IApplicationFunctions::CreateCacheStorage, "CreateCacheStorage"}, - {28, nullptr, "GetSaveDataSizeMax"}, + {28, &IApplicationFunctions::GetSaveDataSizeMax, "GetSaveDataSizeMax"}, {29, nullptr, "GetCacheStorageMax"}, {30, &IApplicationFunctions::BeginBlockingHomeButtonShortAndLongPressed, "BeginBlockingHomeButtonShortAndLongPressed"}, {31, &IApplicationFunctions::EndBlockingHomeButtonShortAndLongPressed, "EndBlockingHomeButtonShortAndLongPressed"}, @@ -1821,6 +1821,18 @@ void IApplicationFunctions::CreateCacheStorage(HLERequestContext& ctx) { rb.PushRaw(resp); } +void IApplicationFunctions::GetSaveDataSizeMax(HLERequestContext& ctx) { + LOG_WARNING(Service_AM, "(STUBBED) called"); + + constexpr u64 size_max_normal = 0xFFFFFFF; + constexpr u64 size_max_journal = 0xFFFFFFF; + + IPC::ResponseBuilder rb{ctx, 6}; + rb.Push(ResultSuccess); + rb.Push(size_max_normal); + rb.Push(size_max_journal); +} + void IApplicationFunctions::QueryApplicationPlayStatistics(HLERequestContext& ctx) { LOG_WARNING(Service_AM, "(STUBBED) called"); diff --git a/src/core/hle/service/am/am.h b/src/core/hle/service/am/am.h index f75a665b2..f86841c60 100644 --- a/src/core/hle/service/am/am.h +++ b/src/core/hle/service/am/am.h @@ -316,6 +316,7 @@ private: void ExtendSaveData(HLERequestContext& ctx); void GetSaveDataSize(HLERequestContext& ctx); void CreateCacheStorage(HLERequestContext& ctx); + void GetSaveDataSizeMax(HLERequestContext& ctx); void BeginBlockingHomeButtonShortAndLongPressed(HLERequestContext& ctx); void EndBlockingHomeButtonShortAndLongPressed(HLERequestContext& ctx); void BeginBlockingHomeButton(HLERequestContext& ctx); diff --git a/src/core/hle/service/hid/controllers/npad.cpp b/src/core/hle/service/hid/controllers/npad.cpp index c744b0f87..146bb486d 100644 --- a/src/core/hle/service/hid/controllers/npad.cpp +++ b/src/core/hle/service/hid/controllers/npad.cpp @@ -193,7 +193,7 @@ void Controller_NPad::InitNewlyAddedController(Core::HID::NpadIdType npad_id) { shared_memory->system_properties.use_minus.Assign(1); shared_memory->system_properties.is_charging_joy_dual.Assign( battery_level.dual.is_charging); - shared_memory->applet_nfc_xcd.applet_footer.type = AppletFooterUiType::SwitchProController; + shared_memory->applet_footer_type = AppletFooterUiType::SwitchProController; shared_memory->sixaxis_fullkey_properties.is_newly_assigned.Assign(1); break; case Core::HID::NpadStyleIndex::Handheld: @@ -216,8 +216,7 @@ void Controller_NPad::InitNewlyAddedController(Core::HID::NpadIdType npad_id) { shared_memory->system_properties.is_charging_joy_right.Assign( battery_level.right.is_charging); shared_memory->assignment_mode = NpadJoyAssignmentMode::Dual; - shared_memory->applet_nfc_xcd.applet_footer.type = - AppletFooterUiType::HandheldJoyConLeftJoyConRight; + shared_memory->applet_footer_type = AppletFooterUiType::HandheldJoyConLeftJoyConRight; shared_memory->sixaxis_handheld_properties.is_newly_assigned.Assign(1); break; case Core::HID::NpadStyleIndex::JoyconDual: @@ -247,19 +246,19 @@ void Controller_NPad::InitNewlyAddedController(Core::HID::NpadIdType npad_id) { shared_memory->assignment_mode = NpadJoyAssignmentMode::Dual; if (controller.is_dual_left_connected && controller.is_dual_right_connected) { - shared_memory->applet_nfc_xcd.applet_footer.type = AppletFooterUiType::JoyDual; + shared_memory->applet_footer_type = AppletFooterUiType::JoyDual; shared_memory->fullkey_color.fullkey = body_colors.left; shared_memory->battery_level_dual = battery_level.left.battery_level; shared_memory->system_properties.is_charging_joy_dual.Assign( battery_level.left.is_charging); } else if (controller.is_dual_left_connected) { - shared_memory->applet_nfc_xcd.applet_footer.type = AppletFooterUiType::JoyDualLeftOnly; + shared_memory->applet_footer_type = AppletFooterUiType::JoyDualLeftOnly; shared_memory->fullkey_color.fullkey = body_colors.left; shared_memory->battery_level_dual = battery_level.left.battery_level; shared_memory->system_properties.is_charging_joy_dual.Assign( battery_level.left.is_charging); } else { - shared_memory->applet_nfc_xcd.applet_footer.type = AppletFooterUiType::JoyDualRightOnly; + shared_memory->applet_footer_type = AppletFooterUiType::JoyDualRightOnly; shared_memory->fullkey_color.fullkey = body_colors.right; shared_memory->battery_level_dual = battery_level.right.battery_level; shared_memory->system_properties.is_charging_joy_dual.Assign( @@ -278,7 +277,7 @@ void Controller_NPad::InitNewlyAddedController(Core::HID::NpadIdType npad_id) { shared_memory->system_properties.use_minus.Assign(1); shared_memory->system_properties.is_charging_joy_left.Assign( battery_level.left.is_charging); - shared_memory->applet_nfc_xcd.applet_footer.type = AppletFooterUiType::JoyLeftHorizontal; + shared_memory->applet_footer_type = AppletFooterUiType::JoyLeftHorizontal; shared_memory->sixaxis_left_properties.is_newly_assigned.Assign(1); break; case Core::HID::NpadStyleIndex::JoyconRight: @@ -293,7 +292,7 @@ void Controller_NPad::InitNewlyAddedController(Core::HID::NpadIdType npad_id) { shared_memory->system_properties.use_plus.Assign(1); shared_memory->system_properties.is_charging_joy_right.Assign( battery_level.right.is_charging); - shared_memory->applet_nfc_xcd.applet_footer.type = AppletFooterUiType::JoyRightHorizontal; + shared_memory->applet_footer_type = AppletFooterUiType::JoyRightHorizontal; shared_memory->sixaxis_right_properties.is_newly_assigned.Assign(1); break; case Core::HID::NpadStyleIndex::GameCube: @@ -314,12 +313,12 @@ void Controller_NPad::InitNewlyAddedController(Core::HID::NpadIdType npad_id) { case Core::HID::NpadStyleIndex::SNES: shared_memory->style_tag.lucia.Assign(1); shared_memory->device_type.fullkey.Assign(1); - shared_memory->applet_nfc_xcd.applet_footer.type = AppletFooterUiType::Lucia; + shared_memory->applet_footer_type = AppletFooterUiType::Lucia; break; case Core::HID::NpadStyleIndex::N64: shared_memory->style_tag.lagoon.Assign(1); shared_memory->device_type.fullkey.Assign(1); - shared_memory->applet_nfc_xcd.applet_footer.type = AppletFooterUiType::Lagon; + shared_memory->applet_footer_type = AppletFooterUiType::Lagon; break; case Core::HID::NpadStyleIndex::SegaGenesis: shared_memory->style_tag.lager.Assign(1); @@ -419,9 +418,17 @@ void Controller_NPad::RequestPadStateUpdate(Core::HID::NpadIdType npad_id) { std::scoped_lock lock{mutex}; auto& controller = GetControllerFromNpadIdType(npad_id); const auto controller_type = controller.device->GetNpadStyleIndex(); + + if (!controller.device->IsConnected() && controller.is_connected) { + DisconnectNpad(npad_id); + return; + } if (!controller.device->IsConnected()) { return; } + if (controller.device->IsConnected() && !controller.is_connected) { + InitNewlyAddedController(npad_id); + } // This function is unique to yuzu for the turbo buttons and motion to work properly controller.device->StatusUpdate(); @@ -468,6 +475,10 @@ void Controller_NPad::RequestPadStateUpdate(Core::HID::NpadIdType npad_id) { pad_entry.npad_buttons.l.Assign(button_state.zl); pad_entry.npad_buttons.r.Assign(button_state.zr); } + + if (pad_entry.npad_buttons.raw != Core::HID::NpadButton::None) { + hid_core.SetLastActiveController(npad_id); + } } void Controller_NPad::OnUpdate(const Core::Timing::CoreTiming& core_timing) { @@ -736,14 +747,6 @@ void Controller_NPad::SetSupportedStyleSet(Core::HID::NpadStyleTag style_set) { // Once SetSupportedStyleSet is called controllers are fully initialized is_controller_initialized = true; - - // Connect all active controllers - for (auto& controller : controller_data) { - const auto& device = controller.device; - if (device->IsConnected()) { - AddNewControllerAt(device->GetNpadStyleIndex(), device->GetNpadIdType()); - } - } } Core::HID::NpadStyleTag Controller_NPad::GetSupportedStyleSet() const { @@ -1116,7 +1119,7 @@ Result Controller_NPad::DisconnectNpad(Core::HID::NpadIdType npad_id) { .left = {}, .right = {}, }; - shared_memory->applet_nfc_xcd.applet_footer.type = AppletFooterUiType::None; + shared_memory->applet_footer_type = AppletFooterUiType::None; controller.is_dual_left_connected = true; controller.is_dual_right_connected = true; diff --git a/src/core/hle/service/hid/controllers/npad.h b/src/core/hle/service/hid/controllers/npad.h index 0e9f899a4..949e58a4c 100644 --- a/src/core/hle/service/hid/controllers/npad.h +++ b/src/core/hle/service/hid/controllers/npad.h @@ -362,7 +362,7 @@ private: enum class AppletFooterUiType : u8 { None = 0, HandheldNone = 1, - HandheldJoyConLeftOnly = 1, + HandheldJoyConLeftOnly = 2, HandheldJoyConRightOnly = 3, HandheldJoyConLeftJoyConRight = 4, JoyDual = 5, @@ -384,13 +384,6 @@ private: Lagon = 21, }; - struct AppletFooterUi { - AppletFooterUiAttributes attributes{}; - AppletFooterUiType type{AppletFooterUiType::None}; - INSERT_PADDING_BYTES(0x5B); // Reserved - }; - static_assert(sizeof(AppletFooterUi) == 0x60, "AppletFooterUi is an invalid size"); - // This is nn::hid::NpadLarkType enum class NpadLarkType : u32 { Invalid, @@ -421,13 +414,6 @@ private: U, }; - struct AppletNfcXcd { - union { - AppletFooterUi applet_footer{}; - Lifo<NfcXcdDeviceHandleStateImpl, 0x2> nfc_xcd_device_lifo; - }; - }; - // This is nn::hid::detail::NpadInternalState struct NpadInternalState { Core::HID::NpadStyleTag style_tag{Core::HID::NpadStyleSet::None}; @@ -454,7 +440,9 @@ private: Core::HID::NpadBatteryLevel battery_level_dual{}; Core::HID::NpadBatteryLevel battery_level_left{}; Core::HID::NpadBatteryLevel battery_level_right{}; - AppletNfcXcd applet_nfc_xcd{}; + AppletFooterUiAttributes applet_footer_attributes{}; + AppletFooterUiType applet_footer_type{AppletFooterUiType::None}; + INSERT_PADDING_BYTES(0x5B); // Reserved INSERT_PADDING_BYTES(0x20); // Unknown Lifo<NpadGcTriggerState, hid_entry_count> gc_trigger_lifo{}; NpadLarkType lark_type_l_and_main{}; diff --git a/src/core/hle/service/hid/hid.cpp b/src/core/hle/service/hid/hid.cpp index 6f711c0da..4d70006c1 100644 --- a/src/core/hle/service/hid/hid.cpp +++ b/src/core/hle/service/hid/hid.cpp @@ -2774,7 +2774,7 @@ private: IPC::ResponseBuilder rb{ctx, 3}; rb.Push(ResultSuccess); - rb.PushEnum(Core::HID::NpadIdType::Handheld); + rb.PushEnum(system.HIDCore().GetLastActiveController()); } void GetUniquePadsFromNpad(HLERequestContext& ctx) { diff --git a/src/core/hle/service/nfc/common/device.cpp b/src/core/hle/service/nfc/common/device.cpp index 5dda12343..674d2e4b2 100644 --- a/src/core/hle/service/nfc/common/device.cpp +++ b/src/core/hle/service/nfc/common/device.cpp @@ -874,17 +874,19 @@ Result NfcDevice::RestoreAmiibo() { } Result NfcDevice::Format() { - auto result1 = DeleteApplicationArea(); - auto result2 = DeleteRegisterInfo(); + Result result = ResultSuccess; - if (result1.IsError()) { - return result1; + if (device_state == DeviceState::TagFound) { + result = Mount(NFP::ModelType::Amiibo, NFP::MountTarget::All); } - if (result2.IsError()) { - return result2; + if (result.IsError()) { + return result; } + DeleteApplicationArea(); + DeleteRegisterInfo(); + return Flush(); } diff --git a/src/core/hle/service/ngc/ngc.cpp b/src/core/hle/service/ngc/ngc.cpp new file mode 100644 index 000000000..c26019ec0 --- /dev/null +++ b/src/core/hle/service/ngc/ngc.cpp @@ -0,0 +1,150 @@ +// SPDX-FileCopyrightText: Copyright 2021 yuzu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include "common/string_util.h" +#include "core/core.h" +#include "core/hle/service/ipc_helpers.h" +#include "core/hle/service/ngc/ngc.h" +#include "core/hle/service/server_manager.h" +#include "core/hle/service/service.h" + +namespace Service::NGC { + +class NgctServiceImpl final : public ServiceFramework<NgctServiceImpl> { +public: + explicit NgctServiceImpl(Core::System& system_) : ServiceFramework{system_, "ngct:u"} { + // clang-format off + static const FunctionInfo functions[] = { + {0, &NgctServiceImpl::Match, "Match"}, + {1, &NgctServiceImpl::Filter, "Filter"}, + }; + // clang-format on + + RegisterHandlers(functions); + } + +private: + void Match(HLERequestContext& ctx) { + const auto buffer = ctx.ReadBuffer(); + const auto text = Common::StringFromFixedZeroTerminatedBuffer( + reinterpret_cast<const char*>(buffer.data()), buffer.size()); + + LOG_WARNING(Service_NGC, "(STUBBED) called, text={}", text); + + IPC::ResponseBuilder rb{ctx, 3}; + rb.Push(ResultSuccess); + // Return false since we don't censor anything + rb.Push(false); + } + + void Filter(HLERequestContext& ctx) { + const auto buffer = ctx.ReadBuffer(); + const auto text = Common::StringFromFixedZeroTerminatedBuffer( + reinterpret_cast<const char*>(buffer.data()), buffer.size()); + + LOG_WARNING(Service_NGC, "(STUBBED) called, text={}", text); + + // Return the same string since we don't censor anything + ctx.WriteBuffer(buffer); + + IPC::ResponseBuilder rb{ctx, 2}; + rb.Push(ResultSuccess); + } +}; + +class NgcServiceImpl final : public ServiceFramework<NgcServiceImpl> { +public: + explicit NgcServiceImpl(Core::System& system_) : ServiceFramework(system_, "ngc:u") { + // clang-format off + static const FunctionInfo functions[] = { + {0, &NgcServiceImpl::GetContentVersion, "GetContentVersion"}, + {1, &NgcServiceImpl::Check, "Check"}, + {2, &NgcServiceImpl::Mask, "Mask"}, + {3, &NgcServiceImpl::Reload, "Reload"}, + }; + // clang-format on + + RegisterHandlers(functions); + } + +private: + static constexpr u32 NgcContentVersion = 1; + + // This is nn::ngc::detail::ProfanityFilterOption + struct ProfanityFilterOption { + INSERT_PADDING_BYTES_NOINIT(0x20); + }; + static_assert(sizeof(ProfanityFilterOption) == 0x20, + "ProfanityFilterOption has incorrect size"); + + void GetContentVersion(HLERequestContext& ctx) { + LOG_INFO(Service_NGC, "(STUBBED) called"); + + // This calls nn::ngc::ProfanityFilter::GetContentVersion + const u32 version = NgcContentVersion; + + IPC::ResponseBuilder rb{ctx, 3}; + rb.Push(ResultSuccess); + rb.Push(version); + } + + void Check(HLERequestContext& ctx) { + LOG_INFO(Service_NGC, "(STUBBED) called"); + + struct InputParameters { + u32 flags; + ProfanityFilterOption option; + }; + + IPC::RequestParser rp{ctx}; + [[maybe_unused]] const auto params = rp.PopRaw<InputParameters>(); + [[maybe_unused]] const auto input = ctx.ReadBuffer(0); + + // This calls nn::ngc::ProfanityFilter::CheckProfanityWords + const u32 out_flags = 0; + + IPC::ResponseBuilder rb{ctx, 3}; + rb.Push(ResultSuccess); + rb.Push(out_flags); + } + + void Mask(HLERequestContext& ctx) { + LOG_INFO(Service_NGC, "(STUBBED) called"); + + struct InputParameters { + u32 flags; + ProfanityFilterOption option; + }; + + IPC::RequestParser rp{ctx}; + [[maybe_unused]] const auto params = rp.PopRaw<InputParameters>(); + const auto input = ctx.ReadBuffer(0); + + // This calls nn::ngc::ProfanityFilter::MaskProfanityWordsInText + const u32 out_flags = 0; + ctx.WriteBuffer(input); + + IPC::ResponseBuilder rb{ctx, 3}; + rb.Push(ResultSuccess); + rb.Push(out_flags); + } + + void Reload(HLERequestContext& ctx) { + LOG_INFO(Service_NGC, "(STUBBED) called"); + + // This reloads the database. + + IPC::ResponseBuilder rb{ctx, 2}; + rb.Push(ResultSuccess); + } +}; + +void LoopProcess(Core::System& system) { + auto server_manager = std::make_unique<ServerManager>(system); + + server_manager->RegisterNamedService("ngct:u", std::make_shared<NgctServiceImpl>(system)); + server_manager->RegisterNamedService("ngc:u", std::make_shared<NgcServiceImpl>(system)); + ServerManager::RunServer(std::move(server_manager)); +} + +} // namespace Service::NGC diff --git a/src/core/hle/service/ngct/ngct.h b/src/core/hle/service/ngc/ngc.h index 27c34dad4..823b1aa81 100644 --- a/src/core/hle/service/ngct/ngct.h +++ b/src/core/hle/service/ngc/ngc.h @@ -7,8 +7,8 @@ namespace Core { class System; } -namespace Service::NGCT { +namespace Service::NGC { void LoopProcess(Core::System& system); -} // namespace Service::NGCT +} // namespace Service::NGC diff --git a/src/core/hle/service/ngct/ngct.cpp b/src/core/hle/service/ngct/ngct.cpp deleted file mode 100644 index 493c80ed2..000000000 --- a/src/core/hle/service/ngct/ngct.cpp +++ /dev/null @@ -1,62 +0,0 @@ -// SPDX-FileCopyrightText: Copyright 2021 yuzu Emulator Project -// SPDX-License-Identifier: GPL-2.0-or-later - -#include "common/string_util.h" -#include "core/core.h" -#include "core/hle/service/ipc_helpers.h" -#include "core/hle/service/ngct/ngct.h" -#include "core/hle/service/server_manager.h" -#include "core/hle/service/service.h" - -namespace Service::NGCT { - -class IService final : public ServiceFramework<IService> { -public: - explicit IService(Core::System& system_) : ServiceFramework{system_, "ngct:u"} { - // clang-format off - static const FunctionInfo functions[] = { - {0, &IService::Match, "Match"}, - {1, &IService::Filter, "Filter"}, - }; - // clang-format on - - RegisterHandlers(functions); - } - -private: - void Match(HLERequestContext& ctx) { - const auto buffer = ctx.ReadBuffer(); - const auto text = Common::StringFromFixedZeroTerminatedBuffer( - reinterpret_cast<const char*>(buffer.data()), buffer.size()); - - LOG_WARNING(Service_NGCT, "(STUBBED) called, text={}", text); - - IPC::ResponseBuilder rb{ctx, 3}; - rb.Push(ResultSuccess); - // Return false since we don't censor anything - rb.Push(false); - } - - void Filter(HLERequestContext& ctx) { - const auto buffer = ctx.ReadBuffer(); - const auto text = Common::StringFromFixedZeroTerminatedBuffer( - reinterpret_cast<const char*>(buffer.data()), buffer.size()); - - LOG_WARNING(Service_NGCT, "(STUBBED) called, text={}", text); - - // Return the same string since we don't censor anything - ctx.WriteBuffer(buffer); - - IPC::ResponseBuilder rb{ctx, 2}; - rb.Push(ResultSuccess); - } -}; - -void LoopProcess(Core::System& system) { - auto server_manager = std::make_unique<ServerManager>(system); - - server_manager->RegisterNamedService("ngct:u", std::make_shared<IService>(system)); - ServerManager::RunServer(std::move(server_manager)); -} - -} // namespace Service::NGCT diff --git a/src/core/hle/service/service.cpp b/src/core/hle/service/service.cpp index 69cdb5918..0ad607391 100644 --- a/src/core/hle/service/service.cpp +++ b/src/core/hle/service/service.cpp @@ -43,7 +43,7 @@ #include "core/hle/service/ncm/ncm.h" #include "core/hle/service/nfc/nfc.h" #include "core/hle/service/nfp/nfp.h" -#include "core/hle/service/ngct/ngct.h" +#include "core/hle/service/ngc/ngc.h" #include "core/hle/service/nifm/nifm.h" #include "core/hle/service/nim/nim.h" #include "core/hle/service/npns/npns.h" @@ -257,7 +257,7 @@ Services::Services(std::shared_ptr<SM::ServiceManager>& sm, Core::System& system kernel.RunOnGuestCoreProcess("NCM", [&] { NCM::LoopProcess(system); }); kernel.RunOnGuestCoreProcess("nfc", [&] { NFC::LoopProcess(system); }); kernel.RunOnGuestCoreProcess("nfp", [&] { NFP::LoopProcess(system); }); - kernel.RunOnGuestCoreProcess("ngct", [&] { NGCT::LoopProcess(system); }); + kernel.RunOnGuestCoreProcess("ngc", [&] { NGC::LoopProcess(system); }); kernel.RunOnGuestCoreProcess("nifm", [&] { NIFM::LoopProcess(system); }); kernel.RunOnGuestCoreProcess("nim", [&] { NIM::LoopProcess(system); }); kernel.RunOnGuestCoreProcess("npns", [&] { NPNS::LoopProcess(system); }); diff --git a/src/core/hle/service/sockets/bsd.cpp b/src/core/hle/service/sockets/bsd.cpp index d8509c1dd..85849d5f3 100644 --- a/src/core/hle/service/sockets/bsd.cpp +++ b/src/core/hle/service/sockets/bsd.cpp @@ -170,7 +170,7 @@ void BSD::Socket(HLERequestContext& ctx) { } void BSD::Select(HLERequestContext& ctx) { - LOG_WARNING(Service, "(STUBBED) called"); + LOG_DEBUG(Service, "(STUBBED) called"); IPC::ResponseBuilder rb{ctx, 4}; diff --git a/src/core/loader/deconstructed_rom_directory.cpp b/src/core/loader/deconstructed_rom_directory.cpp index f4eaf3331..5a42dea48 100644 --- a/src/core/loader/deconstructed_rom_directory.cpp +++ b/src/core/loader/deconstructed_rom_directory.cpp @@ -18,7 +18,7 @@ namespace Loader { AppLoader_DeconstructedRomDirectory::AppLoader_DeconstructedRomDirectory(FileSys::VirtualFile file_, bool override_update_) - : AppLoader(std::move(file_)), override_update(override_update_) { + : AppLoader(std::move(file_)), override_update(override_update_), is_hbl(false) { const auto file_dir = file->GetContainingDirectory(); // Title ID @@ -69,9 +69,9 @@ AppLoader_DeconstructedRomDirectory::AppLoader_DeconstructedRomDirectory(FileSys } AppLoader_DeconstructedRomDirectory::AppLoader_DeconstructedRomDirectory( - FileSys::VirtualDir directory, bool override_update_) + FileSys::VirtualDir directory, bool override_update_, bool is_hbl_) : AppLoader(directory->GetFile("main")), dir(std::move(directory)), - override_update(override_update_) {} + override_update(override_update_), is_hbl(is_hbl_) {} FileType AppLoader_DeconstructedRomDirectory::IdentifyType(const FileSys::VirtualFile& dir_file) { if (FileSys::IsDirectoryExeFS(dir_file->GetContainingDirectory())) { @@ -147,7 +147,7 @@ AppLoader_DeconstructedRomDirectory::LoadResult AppLoader_DeconstructedRomDirect } // Setup the process code layout - if (process.LoadFromMetadata(metadata, code_size).IsError()) { + if (process.LoadFromMetadata(metadata, code_size, is_hbl).IsError()) { return {ResultStatus::ErrorUnableToParseKernelMetadata, {}}; } diff --git a/src/core/loader/deconstructed_rom_directory.h b/src/core/loader/deconstructed_rom_directory.h index f7702225e..1e9f765c9 100644 --- a/src/core/loader/deconstructed_rom_directory.h +++ b/src/core/loader/deconstructed_rom_directory.h @@ -27,7 +27,8 @@ public: // Overload to accept exefs directory. Must contain 'main' and 'main.npdm' explicit AppLoader_DeconstructedRomDirectory(FileSys::VirtualDir directory, - bool override_update_ = false); + bool override_update_ = false, + bool is_hbl_ = false); /** * Identifies whether or not the given file is a deconstructed ROM directory. @@ -62,6 +63,7 @@ private: std::string name; u64 title_id{}; bool override_update; + bool is_hbl; Modules modules; }; diff --git a/src/core/loader/kip.cpp b/src/core/loader/kip.cpp index d722459c6..bf56a08b4 100644 --- a/src/core/loader/kip.cpp +++ b/src/core/loader/kip.cpp @@ -90,7 +90,8 @@ AppLoader::LoadResult AppLoader_KIP::Load(Kernel::KProcess& process, codeset.DataSegment().size += kip->GetBSSSize(); // Setup the process code layout - if (process.LoadFromMetadata(FileSys::ProgramMetadata::GetDefault(), program_image.size()) + if (process + .LoadFromMetadata(FileSys::ProgramMetadata::GetDefault(), program_image.size(), false) .IsError()) { return {ResultStatus::ErrorNotInitialized, {}}; } diff --git a/src/core/loader/nro.cpp b/src/core/loader/nro.cpp index d7562b4bc..69f1a54ed 100644 --- a/src/core/loader/nro.cpp +++ b/src/core/loader/nro.cpp @@ -196,7 +196,8 @@ static bool LoadNroImpl(Kernel::KProcess& process, const std::vector<u8>& data) program_image.resize(static_cast<u32>(program_image.size()) + bss_size); // Setup the process code layout - if (process.LoadFromMetadata(FileSys::ProgramMetadata::GetDefault(), program_image.size()) + if (process + .LoadFromMetadata(FileSys::ProgramMetadata::GetDefault(), program_image.size(), false) .IsError()) { return false; } diff --git a/src/core/loader/nso.cpp b/src/core/loader/nso.cpp index 549822506..1350da8dc 100644 --- a/src/core/loader/nso.cpp +++ b/src/core/loader/nso.cpp @@ -127,13 +127,14 @@ std::optional<VAddr> AppLoader_NSO::LoadModule(Kernel::KProcess& process, Core:: } // Apply patches if necessary - if (pm && (pm->HasNSOPatch(nso_header.build_id) || Settings::values.dump_nso)) { + const auto name = nso_file.GetName(); + if (pm && (pm->HasNSOPatch(nso_header.build_id, name) || Settings::values.dump_nso)) { std::vector<u8> pi_header(sizeof(NSOHeader) + program_image.size()); std::memcpy(pi_header.data(), &nso_header, sizeof(NSOHeader)); std::memcpy(pi_header.data() + sizeof(NSOHeader), program_image.data(), program_image.size()); - pi_header = pm->PatchNSO(pi_header, nso_file.GetName()); + pi_header = pm->PatchNSO(pi_header, name); std::copy(pi_header.begin() + sizeof(NSOHeader), pi_header.end(), program_image.data()); } diff --git a/src/core/loader/nsp.cpp b/src/core/loader/nsp.cpp index fe2af1ae6..f4ab75b77 100644 --- a/src/core/loader/nsp.cpp +++ b/src/core/loader/nsp.cpp @@ -30,7 +30,8 @@ AppLoader_NSP::AppLoader_NSP(FileSys::VirtualFile file_, } if (nsp->IsExtractedType()) { - secondary_loader = std::make_unique<AppLoader_DeconstructedRomDirectory>(nsp->GetExeFS()); + secondary_loader = std::make_unique<AppLoader_DeconstructedRomDirectory>( + nsp->GetExeFS(), false, file->GetName() == "hbl.nsp"); } else { const auto control_nca = nsp->GetNCA(nsp->GetProgramTitleID(), FileSys::ContentRecordType::Control); diff --git a/src/core/memory/cheat_engine.cpp b/src/core/memory/cheat_engine.cpp index 7b52f61a7..a06e99166 100644 --- a/src/core/memory/cheat_engine.cpp +++ b/src/core/memory/cheat_engine.cpp @@ -154,7 +154,7 @@ std::vector<CheatEntry> TextCheatParser::Parse(std::string_view data) const { return {}; } - const auto value = static_cast<u32>(std::stoul(hex, nullptr, 0x10)); + const auto value = static_cast<u32>(std::strtoul(hex.c_str(), nullptr, 0x10)); out[*current_entry].definition.opcodes[out[*current_entry].definition.num_opcodes++] = value; diff --git a/src/core/tools/renderdoc.cpp b/src/core/tools/renderdoc.cpp new file mode 100644 index 000000000..44d24822a --- /dev/null +++ b/src/core/tools/renderdoc.cpp @@ -0,0 +1,55 @@ +// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include <renderdoc_app.h> + +#include "common/assert.h" +#include "common/dynamic_library.h" +#include "core/tools/renderdoc.h" + +#ifdef WIN32 +#include <windows.h> +#else +#include <dlfcn.h> +#endif + +namespace Tools { + +RenderdocAPI::RenderdocAPI() { +#ifdef WIN32 + if (HMODULE mod = GetModuleHandleA("renderdoc.dll")) { + const auto RENDERDOC_GetAPI = + reinterpret_cast<pRENDERDOC_GetAPI>(GetProcAddress(mod, "RENDERDOC_GetAPI")); + const s32 ret = RENDERDOC_GetAPI(eRENDERDOC_API_Version_1_6_0, (void**)&rdoc_api); + ASSERT(ret == 1); + } +#else +#ifdef ANDROID + static constexpr const char RENDERDOC_LIB[] = "libVkLayer_GLES_RenderDoc.so"; +#else + static constexpr const char RENDERDOC_LIB[] = "librenderdoc.so"; +#endif + if (void* mod = dlopen(RENDERDOC_LIB, RTLD_NOW | RTLD_NOLOAD)) { + const auto RENDERDOC_GetAPI = + reinterpret_cast<pRENDERDOC_GetAPI>(dlsym(mod, "RENDERDOC_GetAPI")); + const s32 ret = RENDERDOC_GetAPI(eRENDERDOC_API_Version_1_6_0, (void**)&rdoc_api); + ASSERT(ret == 1); + } +#endif +} + +RenderdocAPI::~RenderdocAPI() = default; + +void RenderdocAPI::ToggleCapture() { + if (!rdoc_api) [[unlikely]] { + return; + } + if (!is_capturing) { + rdoc_api->StartFrameCapture(NULL, NULL); + } else { + rdoc_api->EndFrameCapture(NULL, NULL); + } + is_capturing = !is_capturing; +} + +} // namespace Tools diff --git a/src/core/tools/renderdoc.h b/src/core/tools/renderdoc.h new file mode 100644 index 000000000..0e5e43da5 --- /dev/null +++ b/src/core/tools/renderdoc.h @@ -0,0 +1,22 @@ +// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +struct RENDERDOC_API_1_6_0; + +namespace Tools { + +class RenderdocAPI { +public: + explicit RenderdocAPI(); + ~RenderdocAPI(); + + void ToggleCapture(); + +private: + RENDERDOC_API_1_6_0* rdoc_api{}; + bool is_capturing{false}; +}; + +} // namespace Tools diff --git a/src/shader_recompiler/backend/spirv/emit_spirv_image.cpp b/src/shader_recompiler/backend/spirv/emit_spirv_image.cpp index 34240b36f..8decdf399 100644 --- a/src/shader_recompiler/backend/spirv/emit_spirv_image.cpp +++ b/src/shader_recompiler/backend/spirv/emit_spirv_image.cpp @@ -204,9 +204,7 @@ Id TextureImage(EmitContext& ctx, IR::TextureInstInfo info, const IR::Value& ind if (def.count > 1) { throw NotImplementedException("Indirect texture sample"); } - const Id sampler_id{def.id}; - const Id id{ctx.OpLoad(ctx.sampled_texture_buffer_type, sampler_id)}; - return ctx.OpImage(ctx.image_buffer_type, id); + return ctx.OpLoad(ctx.image_buffer_type, def.id); } else { const TextureDefinition& def{ctx.textures.at(info.descriptor_index)}; if (def.count > 1) { diff --git a/src/shader_recompiler/backend/spirv/spirv_emit_context.cpp b/src/shader_recompiler/backend/spirv/spirv_emit_context.cpp index 238fb40e3..72f69b7aa 100644 --- a/src/shader_recompiler/backend/spirv/spirv_emit_context.cpp +++ b/src/shader_recompiler/backend/spirv/spirv_emit_context.cpp @@ -1247,9 +1247,8 @@ void EmitContext::DefineTextureBuffers(const Info& info, u32& binding) { } const spv::ImageFormat format{spv::ImageFormat::Unknown}; image_buffer_type = TypeImage(F32[1], spv::Dim::Buffer, 0U, false, false, 1, format); - sampled_texture_buffer_type = TypeSampledImage(image_buffer_type); - const Id type{TypePointer(spv::StorageClass::UniformConstant, sampled_texture_buffer_type)}; + const Id type{TypePointer(spv::StorageClass::UniformConstant, image_buffer_type)}; texture_buffers.reserve(info.texture_buffer_descriptors.size()); for (const TextureBufferDescriptor& desc : info.texture_buffer_descriptors) { if (desc.count != 1) { diff --git a/src/shader_recompiler/backend/spirv/spirv_emit_context.h b/src/shader_recompiler/backend/spirv/spirv_emit_context.h index e63330f11..7c49fd504 100644 --- a/src/shader_recompiler/backend/spirv/spirv_emit_context.h +++ b/src/shader_recompiler/backend/spirv/spirv_emit_context.h @@ -206,7 +206,6 @@ public: Id output_u32{}; Id image_buffer_type{}; - Id sampled_texture_buffer_type{}; Id image_u32{}; std::array<UniformDefinitions, Info::MAX_CBUFS> cbufs{}; diff --git a/src/video_core/texture_cache/texture_cache.h b/src/video_core/texture_cache/texture_cache.h index 4457b366f..1bdb0def5 100644 --- a/src/video_core/texture_cache/texture_cache.h +++ b/src/video_core/texture_cache/texture_cache.h @@ -719,6 +719,7 @@ typename P::ImageView* TextureCache<P>::TryFindFramebufferImageView(VAddr cpu_ad return nullptr; } const auto& image_map_ids = it->second; + boost::container::small_vector<const ImageBase*, 4> valid_images; for (const ImageMapId map_id : image_map_ids) { const ImageMapView& map = slot_map_views[map_id]; const ImageBase& image = slot_images[map.image_id]; @@ -728,8 +729,20 @@ typename P::ImageView* TextureCache<P>::TryFindFramebufferImageView(VAddr cpu_ad if (image.image_view_ids.empty()) { continue; } - return &slot_image_views[image.image_view_ids.at(0)]; + valid_images.push_back(&image); } + + if (valid_images.size() == 1) [[likely]] { + return &slot_image_views[valid_images[0]->image_view_ids.at(0)]; + } + + if (valid_images.size() > 0) [[unlikely]] { + std::ranges::sort(valid_images, [](const auto* a, const auto* b) { + return a->modification_tick > b->modification_tick; + }); + return &slot_image_views[valid_images[0]->image_view_ids.at(0)]; + } + return nullptr; } diff --git a/src/yuzu/configuration/configure_debug.cpp b/src/yuzu/configuration/configure_debug.cpp index cbeb8f168..b22fda746 100644 --- a/src/yuzu/configuration/configure_debug.cpp +++ b/src/yuzu/configuration/configure_debug.cpp @@ -59,6 +59,8 @@ void ConfigureDebug::SetConfiguration() { ui->use_debug_asserts->setChecked(Settings::values.use_debug_asserts.GetValue()); ui->use_auto_stub->setChecked(Settings::values.use_auto_stub.GetValue()); ui->enable_all_controllers->setChecked(Settings::values.enable_all_controllers.GetValue()); + ui->enable_renderdoc_hotkey->setEnabled(runtime_lock); + ui->enable_renderdoc_hotkey->setChecked(Settings::values.enable_renderdoc_hotkey.GetValue()); ui->enable_graphics_debugging->setEnabled(runtime_lock); ui->enable_graphics_debugging->setChecked(Settings::values.renderer_debug.GetValue()); ui->enable_shader_feedback->setEnabled(runtime_lock); @@ -111,6 +113,7 @@ void ConfigureDebug::ApplyConfiguration() { Settings::values.use_auto_stub = ui->use_auto_stub->isChecked(); Settings::values.enable_all_controllers = ui->enable_all_controllers->isChecked(); Settings::values.renderer_debug = ui->enable_graphics_debugging->isChecked(); + Settings::values.enable_renderdoc_hotkey = ui->enable_renderdoc_hotkey->isChecked(); Settings::values.renderer_shader_feedback = ui->enable_shader_feedback->isChecked(); Settings::values.cpu_debug_mode = ui->enable_cpu_debugging->isChecked(); Settings::values.enable_nsight_aftermath = ui->enable_nsight_aftermath->isChecked(); diff --git a/src/yuzu/configuration/configure_debug.ui b/src/yuzu/configuration/configure_debug.ui index 97c7d9022..66b8b7459 100644 --- a/src/yuzu/configuration/configure_debug.ui +++ b/src/yuzu/configuration/configure_debug.ui @@ -18,8 +18,8 @@ <rect> <x>0</x> <y>0</y> - <width>829</width> - <height>758</height> + <width>842</width> + <height>741</height> </rect> </property> <layout class="QVBoxLayout" name="verticalLayout_1"> @@ -260,7 +260,7 @@ <string>Graphics</string> </property> <layout class="QGridLayout" name="gridLayout_2"> - <item row="3" column="0"> + <item row="4" column="0"> <widget class="QCheckBox" name="disable_loop_safety_checks"> <property name="toolTip"> <string>When checked, it executes shaders without loop logic changes</string> @@ -270,33 +270,53 @@ </property> </widget> </item> - <item row="4" column="0"> - <widget class="QCheckBox" name="dump_shaders"> + <item row="8" column="0"> + <widget class="QCheckBox" name="disable_macro_hle"> <property name="enabled"> <bool>true</bool> </property> <property name="toolTip"> - <string>When checked, it will dump all the original assembler shaders from the disk shader cache or game as found</string> + <string>When checked, it disables the macro HLE functions. Enabling this makes games run slower</string> </property> <property name="text"> - <string>Dump Game Shaders</string> + <string>Disable Macro HLE</string> </property> </widget> </item> <item row="7" column="0"> - <widget class="QCheckBox" name="disable_macro_hle"> + <widget class="QCheckBox" name="dump_macros"> <property name="enabled"> <bool>true</bool> </property> <property name="toolTip"> - <string>When checked, it disables the macro HLE functions. Enabling this makes games run slower</string> + <string>When checked, it will dump all the macro programs of the GPU</string> </property> <property name="text"> - <string>Disable Macro HLE</string> + <string>Dump Maxwell Macros</string> </property> </widget> </item> - <item row="5" column="0"> + <item row="3" column="0"> + <widget class="QCheckBox" name="enable_nsight_aftermath"> + <property name="toolTip"> + <string>When checked, it enables Nsight Aftermath crash dumps</string> + </property> + <property name="text"> + <string>Enable Nsight Aftermath</string> + </property> + </widget> + </item> + <item row="2" column="0"> + <widget class="QCheckBox" name="enable_shader_feedback"> + <property name="toolTip"> + <string>When checked, yuzu will log statistics about the compiled pipeline cache</string> + </property> + <property name="text"> + <string>Enable Shader Feedback</string> + </property> + </widget> + </item> + <item row="6" column="0"> <widget class="QCheckBox" name="disable_macro_jit"> <property name="enabled"> <bool>true</bool> @@ -309,6 +329,22 @@ </property> </widget> </item> + <item row="9" column="0"> + <spacer name="verticalSpacer_5"> + <property name="orientation"> + <enum>Qt::Vertical</enum> + </property> + <property name="sizeType"> + <enum>QSizePolicy::Preferred</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>20</width> + <height>0</height> + </size> + </property> + </spacer> + </item> <item row="0" column="0"> <widget class="QCheckBox" name="enable_graphics_debugging"> <property name="enabled"> @@ -322,55 +358,26 @@ </property> </widget> </item> - <item row="6" column="0"> - <widget class="QCheckBox" name="dump_macros"> + <item row="5" column="0"> + <widget class="QCheckBox" name="dump_shaders"> <property name="enabled"> <bool>true</bool> </property> <property name="toolTip"> - <string>When checked, it will dump all the macro programs of the GPU</string> + <string>When checked, it will dump all the original assembler shaders from the disk shader cache or game as found</string> </property> <property name="text"> - <string>Dump Maxwell Macros</string> + <string>Dump Game Shaders</string> </property> </widget> </item> <item row="1" column="0"> - <widget class="QCheckBox" name="enable_shader_feedback"> - <property name="toolTip"> - <string>When checked, yuzu will log statistics about the compiled pipeline cache</string> - </property> - <property name="text"> - <string>Enable Shader Feedback</string> - </property> - </widget> - </item> - <item row="2" column="0"> - <widget class="QCheckBox" name="enable_nsight_aftermath"> - <property name="toolTip"> - <string>When checked, it enables Nsight Aftermath crash dumps</string> - </property> + <widget class="QCheckBox" name="enable_renderdoc_hotkey"> <property name="text"> - <string>Enable Nsight Aftermath</string> + <string>Enable Renderdoc Hotkey</string> </property> </widget> </item> - <item row="8" column="0"> - <spacer name="verticalSpacer_5"> - <property name="orientation"> - <enum>Qt::Vertical</enum> - </property> - <property name="sizeType"> - <enum>QSizePolicy::Preferred</enum> - </property> - <property name="sizeHint" stdset="0"> - <size> - <width>20</width> - <height>0</height> - </size> - </property> - </spacer> - </item> </layout> </widget> </item> diff --git a/src/yuzu/configuration/configure_ui.cpp b/src/yuzu/configuration/configure_ui.cpp index 34ab01617..a9fde9f4f 100644 --- a/src/yuzu/configuration/configure_ui.cpp +++ b/src/yuzu/configuration/configure_ui.cpp @@ -4,6 +4,7 @@ #include "yuzu/configuration/configure_ui.h" #include <array> +#include <cstdlib> #include <set> #include <stdexcept> #include <string> @@ -94,11 +95,7 @@ static void PopulateResolutionComboBox(QComboBox* screenshot_height, QWidget* pa } static u32 ScreenshotDimensionToInt(const QString& height) { - try { - return std::stoi(height.toStdString()); - } catch (std::invalid_argument&) { - return 0; - } + return std::strtoul(height.toUtf8(), nullptr, 0); } ConfigureUi::ConfigureUi(Core::System& system_, QWidget* parent) diff --git a/src/yuzu/configuration/shared_widget.cpp b/src/yuzu/configuration/shared_widget.cpp index d63093985..ea8d7add4 100644 --- a/src/yuzu/configuration/shared_widget.cpp +++ b/src/yuzu/configuration/shared_widget.cpp @@ -63,7 +63,7 @@ static QString DefaultSuffix(QWidget* parent, Settings::BasicSetting& setting) { return tr("%", context.c_str()); } - return QStringLiteral(""); + return default_suffix; } QPushButton* Widget::CreateRestoreGlobalButton(bool using_global, QWidget* parent) { @@ -71,7 +71,7 @@ QPushButton* Widget::CreateRestoreGlobalButton(bool using_global, QWidget* paren QStyle* style = parent->style(); QIcon* icon = new QIcon(style->standardIcon(QStyle::SP_LineEditClearButton)); - QPushButton* restore_button = new QPushButton(*icon, QStringLiteral(""), parent); + QPushButton* restore_button = new QPushButton(*icon, QStringLiteral(), parent); restore_button->setObjectName(QStringLiteral("RestoreButton%1").arg(restore_button_count)); restore_button->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); @@ -151,7 +151,7 @@ QWidget* Widget::CreateCombobox(std::function<std::string()>& serializer, return -1; }; - const u32 setting_value = std::stoi(setting.ToString()); + const u32 setting_value = std::strtoul(setting.ToString().c_str(), nullptr, 0); combobox->setCurrentIndex(find_index(setting_value)); serializer = [this, enumeration]() { @@ -160,7 +160,7 @@ QWidget* Widget::CreateCombobox(std::function<std::string()>& serializer, }; restore_func = [this, find_index]() { - const u32 global_value = std::stoi(RelevantDefault(setting)); + const u32 global_value = std::strtoul(RelevantDefault(setting).c_str(), nullptr, 0); combobox->setCurrentIndex(find_index(global_value)); }; @@ -209,7 +209,7 @@ QWidget* Widget::CreateRadioGroup(std::function<std::string()>& serializer, } }; - const u32 setting_value = std::stoi(setting.ToString()); + const u32 setting_value = std::strtoul(setting.ToString().c_str(), nullptr, 0); set_index(setting_value); serializer = [get_selected]() { @@ -218,7 +218,7 @@ QWidget* Widget::CreateRadioGroup(std::function<std::string()>& serializer, }; restore_func = [this, set_index]() { - const u32 global_value = std::stoi(RelevantDefault(setting)); + const u32 global_value = std::strtoul(RelevantDefault(setting).c_str(), nullptr, 0); set_index(global_value); }; @@ -255,6 +255,59 @@ QWidget* Widget::CreateLineEdit(std::function<std::string()>& serializer, return line_edit; } +static void CreateIntSlider(Settings::BasicSetting& setting, bool reversed, float multiplier, + QLabel* feedback, const QString& use_format, QSlider* slider, + std::function<std::string()>& serializer, + std::function<void()>& restore_func) { + const int max_val = std::strtol(setting.MaxVal().c_str(), nullptr, 0); + + const auto update_feedback = [=](int value) { + int present = (reversed ? max_val - value : value) * multiplier + 0.5f; + feedback->setText(use_format.arg(QVariant::fromValue(present).value<QString>())); + }; + + QObject::connect(slider, &QAbstractSlider::valueChanged, update_feedback); + update_feedback(std::strtol(setting.ToString().c_str(), nullptr, 0)); + + slider->setMinimum(std::strtol(setting.MinVal().c_str(), nullptr, 0)); + slider->setMaximum(max_val); + slider->setValue(std::strtol(setting.ToString().c_str(), nullptr, 0)); + + serializer = [slider]() { return std::to_string(slider->value()); }; + restore_func = [slider, &setting]() { + slider->setValue(std::strtol(RelevantDefault(setting).c_str(), nullptr, 0)); + }; +} + +static void CreateFloatSlider(Settings::BasicSetting& setting, bool reversed, float multiplier, + QLabel* feedback, const QString& use_format, QSlider* slider, + std::function<std::string()>& serializer, + std::function<void()>& restore_func) { + const float max_val = std::strtof(setting.MaxVal().c_str(), nullptr); + const float min_val = std::strtof(setting.MinVal().c_str(), nullptr); + const float use_multiplier = + multiplier == default_multiplier ? default_float_multiplier : multiplier; + + const auto update_feedback = [=](float value) { + int present = (reversed ? max_val - value : value) + 0.5f; + feedback->setText(use_format.arg(QVariant::fromValue(present).value<QString>())); + }; + + QObject::connect(slider, &QAbstractSlider::valueChanged, update_feedback); + update_feedback(std::strtof(setting.ToString().c_str(), nullptr)); + + slider->setMinimum(min_val * use_multiplier); + slider->setMaximum(max_val * use_multiplier); + slider->setValue(std::strtof(setting.ToString().c_str(), nullptr) * use_multiplier); + + serializer = [slider, use_multiplier]() { + return std::to_string(slider->value() / use_multiplier); + }; + restore_func = [slider, &setting, use_multiplier]() { + slider->setValue(std::strtof(RelevantDefault(setting).c_str(), nullptr) * use_multiplier); + }; +} + QWidget* Widget::CreateSlider(bool reversed, float multiplier, const QString& given_suffix, std::function<std::string()>& serializer, std::function<void()>& restore_func, @@ -278,27 +331,19 @@ QWidget* Widget::CreateSlider(bool reversed, float multiplier, const QString& gi layout->setContentsMargins(0, 0, 0, 0); - int max_val = std::stoi(setting.MaxVal()); - - QString suffix = - given_suffix == QStringLiteral("") ? DefaultSuffix(this, setting) : given_suffix; + QString suffix = given_suffix == default_suffix ? DefaultSuffix(this, setting) : given_suffix; const QString use_format = QStringLiteral("%1").append(suffix); - QObject::connect(slider, &QAbstractSlider::valueChanged, [=](int value) { - int present = (reversed ? max_val - value : value) * multiplier + 0.5f; - feedback->setText(use_format.arg(QVariant::fromValue(present).value<QString>())); - }); - - slider->setMinimum(std::stoi(setting.MinVal())); - slider->setMaximum(max_val); - slider->setValue(std::stoi(setting.ToString())); + if (setting.IsIntegral()) { + CreateIntSlider(setting, reversed, multiplier, feedback, use_format, slider, serializer, + restore_func); + } else { + CreateFloatSlider(setting, reversed, multiplier, feedback, use_format, slider, serializer, + restore_func); + } slider->setInvertedAppearance(reversed); - slider->setInvertedControls(reversed); - - serializer = [this]() { return std::to_string(slider->value()); }; - restore_func = [this]() { slider->setValue(std::stoi(RelevantDefault(setting))); }; if (!Settings::IsConfiguringGlobal()) { QObject::connect(slider, &QAbstractSlider::actionTriggered, [touch]() { touch(); }); @@ -311,14 +356,11 @@ QWidget* Widget::CreateSpinBox(const QString& given_suffix, std::function<std::string()>& serializer, std::function<void()>& restore_func, const std::function<void()>& touch) { - const int min_val = - setting.Ranged() ? std::stoi(setting.MinVal()) : std::numeric_limits<int>::min(); - const int max_val = - setting.Ranged() ? std::stoi(setting.MaxVal()) : std::numeric_limits<int>::max(); - const int default_val = std::stoi(setting.ToString()); + const auto min_val = std::strtol(setting.MinVal().c_str(), nullptr, 0); + const auto max_val = std::strtol(setting.MaxVal().c_str(), nullptr, 0); + const auto default_val = std::strtol(setting.ToString().c_str(), nullptr, 0); - QString suffix = - given_suffix == QStringLiteral("") ? DefaultSuffix(this, setting) : given_suffix; + QString suffix = given_suffix == default_suffix ? DefaultSuffix(this, setting) : given_suffix; spinbox = new QSpinBox(this); spinbox->setRange(min_val, max_val); @@ -329,13 +371,13 @@ QWidget* Widget::CreateSpinBox(const QString& given_suffix, serializer = [this]() { return std::to_string(spinbox->value()); }; restore_func = [this]() { - auto value{std::stol(RelevantDefault(setting))}; + auto value{std::strtol(RelevantDefault(setting).c_str(), nullptr, 0)}; spinbox->setValue(value); }; if (!Settings::IsConfiguringGlobal()) { QObject::connect(spinbox, QOverload<int>::of(&QSpinBox::valueChanged), [this, touch]() { - if (spinbox->value() != std::stoi(setting.ToStringGlobal())) { + if (spinbox->value() != std::strtol(setting.ToStringGlobal().c_str(), nullptr, 0)) { touch(); } }); @@ -344,6 +386,42 @@ QWidget* Widget::CreateSpinBox(const QString& given_suffix, return spinbox; } +QWidget* Widget::CreateDoubleSpinBox(const QString& given_suffix, + std::function<std::string()>& serializer, + std::function<void()>& restore_func, + const std::function<void()>& touch) { + const auto min_val = std::strtod(setting.MinVal().c_str(), nullptr); + const auto max_val = std::strtod(setting.MaxVal().c_str(), nullptr); + const auto default_val = std::strtod(setting.ToString().c_str(), nullptr); + + QString suffix = given_suffix == default_suffix ? DefaultSuffix(this, setting) : given_suffix; + + double_spinbox = new QDoubleSpinBox(this); + double_spinbox->setRange(min_val, max_val); + double_spinbox->setValue(default_val); + double_spinbox->setSuffix(suffix); + double_spinbox->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); + + serializer = [this]() { return fmt::format("{:f}", double_spinbox->value()); }; + + restore_func = [this]() { + auto value{std::strtod(RelevantDefault(setting).c_str(), nullptr)}; + double_spinbox->setValue(value); + }; + + if (!Settings::IsConfiguringGlobal()) { + QObject::connect(double_spinbox, QOverload<double>::of(&QDoubleSpinBox::valueChanged), + [this, touch]() { + if (double_spinbox->value() != + std::strtod(setting.ToStringGlobal().c_str(), nullptr)) { + touch(); + } + }); + } + + return double_spinbox; +} + QWidget* Widget::CreateHexEdit(std::function<std::string()>& serializer, std::function<void()>& restore_func, const std::function<void()>& touch) { @@ -353,7 +431,8 @@ QWidget* Widget::CreateHexEdit(std::function<std::string()>& serializer, } auto to_hex = [=](const std::string& input) { - return QString::fromStdString(fmt::format("{:08x}", std::stoul(input))); + return QString::fromStdString( + fmt::format("{:08x}", std::strtoul(input.c_str(), nullptr, 0))); }; QRegularExpressionValidator* regex = new QRegularExpressionValidator( @@ -366,7 +445,7 @@ QWidget* Widget::CreateHexEdit(std::function<std::string()>& serializer, line_edit->setValidator(regex); auto hex_to_dec = [this]() -> std::string { - return std::to_string(std::stoul(line_edit->text().toStdString(), nullptr, 16)); + return std::to_string(std::strtoul(line_edit->text().toStdString().c_str(), nullptr, 16)); }; serializer = [hex_to_dec]() { return hex_to_dec(); }; @@ -386,7 +465,8 @@ QWidget* Widget::CreateDateTimeEdit(bool disabled, bool restrict, std::function<void()>& restore_func, const std::function<void()>& touch) { const long long current_time = QDateTime::currentSecsSinceEpoch(); - const s64 the_time = disabled ? current_time : std::stoll(setting.ToString()); + const s64 the_time = + disabled ? current_time : std::strtoll(setting.ToString().c_str(), nullptr, 0); const auto default_val = QDateTime::fromSecsSinceEpoch(the_time); date_time_edit = new QDateTimeEdit(this); @@ -399,7 +479,7 @@ QWidget* Widget::CreateDateTimeEdit(bool disabled, bool restrict, auto get_clear_val = [this, restrict, current_time]() { return QDateTime::fromSecsSinceEpoch([this, restrict, current_time]() { if (restrict && checkbox->checkState() == Qt::Checked) { - return std::stoll(RelevantDefault(setting)); + return std::strtoll(RelevantDefault(setting).c_str(), nullptr, 0); } return current_time; }()); @@ -506,8 +586,7 @@ void Widget::SetupComponent(const QString& label, std::function<void()>& load_fu } else { data_component = CreateCombobox(serializer, restore_func, touch); } - } else if (type == typeid(u32) || type == typeid(int) || type == typeid(u16) || - type == typeid(s64) || type == typeid(u8)) { + } else if (setting.IsIntegral()) { switch (request) { case RequestType::Slider: case RequestType::ReverseSlider: @@ -534,6 +613,20 @@ void Widget::SetupComponent(const QString& label, std::function<void()>& load_fu default: UNIMPLEMENTED(); } + } else if (setting.IsFloatingPoint()) { + switch (request) { + case RequestType::Default: + case RequestType::SpinBox: + data_component = CreateDoubleSpinBox(suffix, serializer, restore_func, touch); + break; + case RequestType::Slider: + case RequestType::ReverseSlider: + data_component = CreateSlider(request == RequestType::ReverseSlider, multiplier, suffix, + serializer, restore_func, touch); + break; + default: + UNIMPLEMENTED(); + } } else if (type == typeid(std::string)) { switch (request) { case RequestType::Default: @@ -638,10 +731,10 @@ Widget::Widget(Settings::BasicSetting* setting_, const TranslationMap& translati return std::pair{translations.at(id).first, translations.at(id).second}; } LOG_WARNING(Frontend, "Translation table lacks entry for \"{}\"", setting_label); - return std::pair{QString::fromStdString(setting_label), QStringLiteral("")}; + return std::pair{QString::fromStdString(setting_label), QStringLiteral()}; }(); - if (label == QStringLiteral("")) { + if (label == QStringLiteral()) { LOG_DEBUG(Frontend, "Translation table has empty entry for \"{}\", skipping...", setting.GetLabel()); return; diff --git a/src/yuzu/configuration/shared_widget.h b/src/yuzu/configuration/shared_widget.h index 5303dd898..226284cf3 100644 --- a/src/yuzu/configuration/shared_widget.h +++ b/src/yuzu/configuration/shared_widget.h @@ -22,6 +22,7 @@ class QObject; class QPushButton; class QSlider; class QSpinBox; +class QDoubleSpinBox; class QRadioButton; namespace Settings { @@ -43,6 +44,10 @@ enum class RequestType { MaxEnum, }; +constexpr float default_multiplier{1.f}; +constexpr float default_float_multiplier{100.f}; +static const QString default_suffix = QStringLiteral(); + class Widget : public QWidget { Q_OBJECT @@ -66,8 +71,9 @@ public: const ComboboxTranslationMap& combobox_translations, QWidget* parent, bool runtime_lock, std::vector<std::function<void(bool)>>& apply_funcs_, RequestType request = RequestType::Default, bool managed = true, - float multiplier = 1.0f, Settings::BasicSetting* other_setting = nullptr, - const QString& suffix = QStringLiteral("")); + float multiplier = default_multiplier, + Settings::BasicSetting* other_setting = nullptr, + const QString& suffix = default_suffix); virtual ~Widget(); /** @@ -89,6 +95,7 @@ public: QPushButton* restore_button{}; ///< Restore button for custom configurations QLineEdit* line_edit{}; ///< QLineEdit, used for LineEdit and HexEdit QSpinBox* spinbox{}; + QDoubleSpinBox* double_spinbox{}; QCheckBox* checkbox{}; QSlider* slider{}; QComboBox* combobox{}; @@ -126,6 +133,9 @@ private: const std::function<void()>& touch); QWidget* CreateSpinBox(const QString& suffix, std::function<std::string()>& serializer, std::function<void()>& restore_func, const std::function<void()>& touch); + QWidget* CreateDoubleSpinBox(const QString& suffix, std::function<std::string()>& serializer, + std::function<void()>& restore_func, + const std::function<void()>& touch); QWidget* parent; const TranslationMap& translations; @@ -145,14 +155,15 @@ public: Widget* BuildWidget(Settings::BasicSetting* setting, std::vector<std::function<void(bool)>>& apply_funcs, RequestType request = RequestType::Default, bool managed = true, - float multiplier = 1.0f, Settings::BasicSetting* other_setting = nullptr, - const QString& suffix = QStringLiteral("")) const; + float multiplier = default_multiplier, + Settings::BasicSetting* other_setting = nullptr, + const QString& suffix = default_suffix) const; Widget* BuildWidget(Settings::BasicSetting* setting, std::vector<std::function<void(bool)>>& apply_funcs, Settings::BasicSetting* other_setting, RequestType request = RequestType::Default, - const QString& suffix = QStringLiteral("")) const; + const QString& suffix = default_suffix) const; const ComboboxTranslationMap& ComboboxTranslations() const; diff --git a/src/yuzu/hotkeys.h b/src/yuzu/hotkeys.h index 848239c35..56eee8d82 100644 --- a/src/yuzu/hotkeys.h +++ b/src/yuzu/hotkeys.h @@ -4,10 +4,12 @@ #pragma once #include <map> +#include <QKeySequence> +#include <QString> +#include <QWidget> #include "core/hid/hid_types.h" class QDialog; -class QKeySequence; class QSettings; class QShortcut; class ControllerShortcut; diff --git a/src/yuzu/main.cpp b/src/yuzu/main.cpp index 97d216638..d32aa9615 100644 --- a/src/yuzu/main.cpp +++ b/src/yuzu/main.cpp @@ -9,6 +9,7 @@ #include <memory> #include <thread> #include "core/loader/nca.h" +#include "core/tools/renderdoc.h" #ifdef __APPLE__ #include <unistd.h> // for chdir #endif @@ -1348,6 +1349,11 @@ void GMainWindow::InitializeHotkeys() { connect_shortcut(QStringLiteral("Toggle Framerate Limit"), [] { Settings::values.use_speed_limit.SetValue(!Settings::values.use_speed_limit.GetValue()); }); + connect_shortcut(QStringLiteral("Toggle Renderdoc Capture"), [this] { + if (Settings::values.enable_renderdoc_hotkey) { + system->GetRenderdocAPI().ToggleCapture(); + } + }); connect_shortcut(QStringLiteral("Toggle Mouse Panning"), [&] { if (Settings::values.mouse_enabled) { Settings::values.mouse_panning = false; diff --git a/src/yuzu_cmd/config.cpp b/src/yuzu_cmd/config.cpp index c42d98709..0d25ff400 100644 --- a/src/yuzu_cmd/config.cpp +++ b/src/yuzu_cmd/config.cpp @@ -259,7 +259,7 @@ void Config::ReadValues() { std::stringstream ss(title_list); std::string line; while (std::getline(ss, line, '|')) { - const auto title_id = std::stoul(line, nullptr, 16); + const auto title_id = std::strtoul(line.c_str(), nullptr, 16); const auto disabled_list = sdl2_config->Get("AddOns", "disabled_" + line, ""); std::stringstream inner_ss(disabled_list); diff --git a/src/yuzu_cmd/yuzu.cpp b/src/yuzu_cmd/yuzu.cpp index 55d0938f7..087cfaa26 100644 --- a/src/yuzu_cmd/yuzu.cpp +++ b/src/yuzu_cmd/yuzu.cpp @@ -264,8 +264,9 @@ int main(int argc, char** argv) { nickname = match[1]; password = match[2]; address = match[3]; - if (!match[4].str().empty()) - port = static_cast<u16>(std::stoi(match[4])); + if (!match[4].str().empty()) { + port = static_cast<u16>(std::strtoul(match[4].str().c_str(), nullptr, 0)); + } std::regex nickname_re("^[a-zA-Z0-9._\\- ]+$"); if (!std::regex_match(nickname, nickname_re)) { std::cout |