summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--src/android/app/src/main/java/org/yuzu/yuzu_emu/features/input/model/PlayerInput.kt6
-rw-r--r--src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/model/StringSetting.kt3
-rw-r--r--src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/model/view/SettingsItem.kt6
-rw-r--r--src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/model/view/StringInputSetting.kt22
-rw-r--r--src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/SettingsAdapter.kt13
-rw-r--r--src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/SettingsDialogFragment.kt23
-rw-r--r--src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/SettingsFragmentPresenter.kt16
-rw-r--r--src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/viewholder/DateTimeViewHolder.kt5
-rw-r--r--src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/viewholder/SingleChoiceViewHolder.kt5
-rw-r--r--src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/viewholder/SliderViewHolder.kt5
-rw-r--r--src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/viewholder/StringInputViewHolder.kt45
-rw-r--r--src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/viewholder/SwitchSettingViewHolder.kt5
-rw-r--r--src/android/app/src/main/java/org/yuzu/yuzu_emu/fragments/EmulationFragment.kt2
-rw-r--r--src/android/app/src/main/java/org/yuzu/yuzu_emu/overlay/InputOverlay.kt13
-rw-r--r--src/android/app/src/main/jni/native.cpp3
-rw-r--r--src/android/app/src/main/jni/native_input.cpp76
-rw-r--r--src/android/app/src/main/res/values/strings.xml1
-rw-r--r--src/common/settings.h6
-rw-r--r--src/common/settings_enums.h2
-rw-r--r--src/core/CMakeLists.txt29
-rw-r--r--src/core/device_memory_manager.inc12
-rw-r--r--src/core/file_sys/fs_filesystem.h27
-rw-r--r--src/core/file_sys/fs_memory_management.h8
-rw-r--r--src/core/file_sys/fs_path.h2
-rw-r--r--src/core/file_sys/fs_path_utility.h7
-rw-r--r--src/core/file_sys/fs_string_util.h15
-rw-r--r--src/core/file_sys/fsa/fs_i_directory.h91
-rw-r--r--src/core/file_sys/fsa/fs_i_file.h167
-rw-r--r--src/core/file_sys/fsa/fs_i_filesystem.h206
-rw-r--r--src/core/file_sys/fssrv/fssrv_sf_path.h36
-rw-r--r--src/core/file_sys/fssystem/fssystem_aes_xts_storage.h1
-rw-r--r--src/core/hle/service/btm/btm.cpp272
-rw-r--r--src/core/hle/service/btm/btm.h4
-rw-r--r--src/core/hle/service/btm/btm_debug.cpp33
-rw-r--r--src/core/hle/service/btm/btm_debug.h21
-rw-r--r--src/core/hle/service/btm/btm_system.cpp31
-rw-r--r--src/core/hle/service/btm/btm_system.h25
-rw-r--r--src/core/hle/service/btm/btm_system_core.cpp127
-rw-r--r--src/core/hle/service/btm/btm_system_core.h60
-rw-r--r--src/core/hle/service/btm/btm_user.cpp30
-rw-r--r--src/core/hle/service/btm/btm_user.h25
-rw-r--r--src/core/hle/service/btm/btm_user_core.cpp103
-rw-r--r--src/core/hle/service/btm/btm_user_core.h47
-rw-r--r--src/core/hle/service/filesystem/fsp/fs_i_directory.cpp72
-rw-r--r--src/core/hle/service/filesystem/fsp/fs_i_directory.h13
-rw-r--r--src/core/hle/service/filesystem/fsp/fs_i_file.cpp124
-rw-r--r--src/core/hle/service/filesystem/fsp/fs_i_file.h21
-rw-r--r--src/core/hle/service/filesystem/fsp/fs_i_filesystem.cpp283
-rw-r--r--src/core/hle/service/filesystem/fsp/fs_i_filesystem.h60
-rw-r--r--src/core/hle/service/ns/application_manager_interface.cpp6
-rw-r--r--src/core/hle/service/ns/application_manager_interface.h2
-rw-r--r--src/core/hle/service/ns/ns_types.h5
-rw-r--r--src/core/hle/service/ns/query_service.cpp5
-rw-r--r--src/core/hle/service/ns/query_service.h4
-rw-r--r--src/core/hle/service/nvnflinger/display.h26
-rw-r--r--src/core/hle/service/nvnflinger/hardware_composer.cpp12
-rw-r--r--src/core/hle/service/nvnflinger/surface_flinger.cpp39
-rw-r--r--src/core/hle/service/nvnflinger/surface_flinger.h6
-rw-r--r--src/core/hle/service/psc/ovln/ovln_types.h21
-rw-r--r--src/core/hle/service/psc/ovln/receiver.cpp24
-rw-r--r--src/core/hle/service/psc/ovln/receiver.h16
-rw-r--r--src/core/hle/service/psc/ovln/receiver_service.cpp28
-rw-r--r--src/core/hle/service/psc/ovln/receiver_service.h22
-rw-r--r--src/core/hle/service/psc/ovln/sender.cpp32
-rw-r--r--src/core/hle/service/psc/ovln/sender.h21
-rw-r--r--src/core/hle/service/psc/ovln/sender_service.cpp30
-rw-r--r--src/core/hle/service/psc/ovln/sender_service.h23
-rw-r--r--src/core/hle/service/psc/pm_control.cpp28
-rw-r--r--src/core/hle/service/psc/pm_control.h16
-rw-r--r--src/core/hle/service/psc/pm_module.cpp24
-rw-r--r--src/core/hle/service/psc/pm_module.h16
-rw-r--r--src/core/hle/service/psc/pm_service.cpp28
-rw-r--r--src/core/hle/service/psc/pm_service.h22
-rw-r--r--src/core/hle/service/psc/psc.cpp71
-rw-r--r--src/core/hle/service/psc/psc.h4
-rw-r--r--src/core/hle/service/vi/container.cpp52
-rw-r--r--src/core/hle/service/vi/container.h3
-rw-r--r--src/core/hle/service/vi/layer.h16
-rw-r--r--src/core/hle/service/vi/layer_list.h6
-rw-r--r--src/core/hle/service/vi/shared_buffer_manager.cpp10
-rw-r--r--src/shader_recompiler/backend/spirv/emit_spirv.cpp4
-rw-r--r--src/shader_recompiler/backend/spirv/emit_spirv_special.cpp8
-rw-r--r--src/shader_recompiler/profile.h1
-rw-r--r--src/video_core/buffer_cache/buffer_cache.h2
-rw-r--r--src/video_core/renderer_vulkan/vk_pipeline_cache.cpp1
-rw-r--r--src/video_core/surface.cpp14
-rw-r--r--src/video_core/surface.h2
-rw-r--r--src/video_core/texture_cache/texture_cache.h6
-rw-r--r--src/video_core/vulkan_common/vulkan_device.cpp14
-rw-r--r--src/video_core/vulkan_common/vulkan_device.h5
-rw-r--r--src/yuzu/configuration/shared_translation.cpp10
-rw-r--r--src/yuzu/main.cpp193
-rw-r--r--src/yuzu/main.h1
-rw-r--r--src/yuzu/main.ui8
94 files changed, 2148 insertions, 948 deletions
diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/input/model/PlayerInput.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/input/model/PlayerInput.kt
index d35de80c4..a84ac77a2 100644
--- a/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/input/model/PlayerInput.kt
+++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/input/model/PlayerInput.kt
@@ -64,17 +64,17 @@ data class PlayerInput(
64 fun hasMapping(): Boolean { 64 fun hasMapping(): Boolean {
65 var hasMapping = false 65 var hasMapping = false
66 buttons.forEach { 66 buttons.forEach {
67 if (it != "[empty]") { 67 if (it != "[empty]" && it.isNotEmpty()) {
68 hasMapping = true 68 hasMapping = true
69 } 69 }
70 } 70 }
71 analogs.forEach { 71 analogs.forEach {
72 if (it != "[empty]") { 72 if (it != "[empty]" && it.isNotEmpty()) {
73 hasMapping = true 73 hasMapping = true
74 } 74 }
75 } 75 }
76 motions.forEach { 76 motions.forEach {
77 if (it != "[empty]") { 77 if (it != "[empty]" && it.isNotEmpty()) {
78 hasMapping = true 78 hasMapping = true
79 } 79 }
80 } 80 }
diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/model/StringSetting.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/model/StringSetting.kt
index a0d8cfede..6f16cf5b1 100644
--- a/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/model/StringSetting.kt
+++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/model/StringSetting.kt
@@ -6,7 +6,8 @@ package org.yuzu.yuzu_emu.features.settings.model
6import org.yuzu.yuzu_emu.utils.NativeConfig 6import org.yuzu.yuzu_emu.utils.NativeConfig
7 7
8enum class StringSetting(override val key: String) : AbstractStringSetting { 8enum class StringSetting(override val key: String) : AbstractStringSetting {
9 DRIVER_PATH("driver_path"); 9 DRIVER_PATH("driver_path"),
10 DEVICE_NAME("device_name");
10 11
11 override fun getString(needsGlobal: Boolean): String = NativeConfig.getString(key, needsGlobal) 12 override fun getString(needsGlobal: Boolean): String = NativeConfig.getString(key, needsGlobal)
12 13
diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/model/view/SettingsItem.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/model/view/SettingsItem.kt
index 8f724835e..5fdf98318 100644
--- a/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/model/view/SettingsItem.kt
+++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/model/view/SettingsItem.kt
@@ -16,6 +16,7 @@ import org.yuzu.yuzu_emu.features.settings.model.ByteSetting
16import org.yuzu.yuzu_emu.features.settings.model.IntSetting 16import org.yuzu.yuzu_emu.features.settings.model.IntSetting
17import org.yuzu.yuzu_emu.features.settings.model.LongSetting 17import org.yuzu.yuzu_emu.features.settings.model.LongSetting
18import org.yuzu.yuzu_emu.features.settings.model.ShortSetting 18import org.yuzu.yuzu_emu.features.settings.model.ShortSetting
19import org.yuzu.yuzu_emu.features.settings.model.StringSetting
19import org.yuzu.yuzu_emu.utils.NativeConfig 20import org.yuzu.yuzu_emu.utils.NativeConfig
20 21
21/** 22/**
@@ -75,6 +76,9 @@ abstract class SettingsItem(
75 get() = NativeLibrary.isRunning() && !setting.global && 76 get() = NativeLibrary.isRunning() && !setting.global &&
76 !NativeConfig.isPerGameConfigLoaded() 77 !NativeConfig.isPerGameConfigLoaded()
77 78
79 val clearable: Boolean
80 get() = !setting.global && NativeConfig.isPerGameConfigLoaded()
81
78 companion object { 82 companion object {
79 const val TYPE_HEADER = 0 83 const val TYPE_HEADER = 0
80 const val TYPE_SWITCH = 1 84 const val TYPE_SWITCH = 1
@@ -87,6 +91,7 @@ abstract class SettingsItem(
87 const val TYPE_INPUT = 8 91 const val TYPE_INPUT = 8
88 const val TYPE_INT_SINGLE_CHOICE = 9 92 const val TYPE_INT_SINGLE_CHOICE = 9
89 const val TYPE_INPUT_PROFILE = 10 93 const val TYPE_INPUT_PROFILE = 10
94 const val TYPE_STRING_INPUT = 11
90 95
91 const val FASTMEM_COMBINED = "fastmem_combined" 96 const val FASTMEM_COMBINED = "fastmem_combined"
92 97
@@ -105,6 +110,7 @@ abstract class SettingsItem(
105 110
106 // List of all general 111 // List of all general
107 val settingsItems = HashMap<String, SettingsItem>().apply { 112 val settingsItems = HashMap<String, SettingsItem>().apply {
113 put(StringInputSetting(StringSetting.DEVICE_NAME, titleId = R.string.device_name))
108 put( 114 put(
109 SwitchSetting( 115 SwitchSetting(
110 BooleanSetting.RENDERER_USE_SPEED_LIMIT, 116 BooleanSetting.RENDERER_USE_SPEED_LIMIT,
diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/model/view/StringInputSetting.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/model/view/StringInputSetting.kt
new file mode 100644
index 000000000..1eb999416
--- /dev/null
+++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/model/view/StringInputSetting.kt
@@ -0,0 +1,22 @@
1// SPDX-FileCopyrightText: 2024 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-2.0-or-later
3
4package org.yuzu.yuzu_emu.features.settings.model.view
5
6import androidx.annotation.StringRes
7import org.yuzu.yuzu_emu.features.settings.model.AbstractStringSetting
8
9class StringInputSetting(
10 setting: AbstractStringSetting,
11 @StringRes titleId: Int = 0,
12 titleString: String = "",
13 @StringRes descriptionId: Int = 0,
14 descriptionString: String = ""
15) : SettingsItem(setting, titleId, titleString, descriptionId, descriptionString) {
16 override val type = TYPE_STRING_INPUT
17
18 fun getSelectedValue(needsGlobal: Boolean = false) = setting.getValueAsString(needsGlobal)
19
20 fun setSelectedValue(selection: String) =
21 (setting as AbstractStringSetting).setString(selection)
22}
diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/SettingsAdapter.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/SettingsAdapter.kt
index 45c8faa10..500ac6e66 100644
--- a/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/SettingsAdapter.kt
+++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/SettingsAdapter.kt
@@ -85,6 +85,10 @@ class SettingsAdapter(
85 InputProfileViewHolder(ListItemSettingBinding.inflate(inflater), this) 85 InputProfileViewHolder(ListItemSettingBinding.inflate(inflater), this)
86 } 86 }
87 87
88 SettingsItem.TYPE_STRING_INPUT -> {
89 StringInputViewHolder(ListItemSettingBinding.inflate(inflater), this)
90 }
91
88 else -> { 92 else -> {
89 HeaderViewHolder(ListItemSettingsHeaderBinding.inflate(inflater), this) 93 HeaderViewHolder(ListItemSettingsHeaderBinding.inflate(inflater), this)
90 } 94 }
@@ -392,6 +396,15 @@ class SettingsAdapter(
392 popup.show() 396 popup.show()
393 } 397 }
394 398
399 fun onStringInputClick(item: StringInputSetting, position: Int) {
400 SettingsDialogFragment.newInstance(
401 settingsViewModel,
402 item,
403 SettingsItem.TYPE_STRING_INPUT,
404 position
405 ).show(fragment.childFragmentManager, SettingsDialogFragment.TAG)
406 }
407
395 fun onLongClick(item: SettingsItem, position: Int): Boolean { 408 fun onLongClick(item: SettingsItem, position: Int): Boolean {
396 SettingsDialogFragment.newInstance( 409 SettingsDialogFragment.newInstance(
397 settingsViewModel, 410 settingsViewModel,
diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/SettingsDialogFragment.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/SettingsDialogFragment.kt
index a81ff6b1a..7f562a1f4 100644
--- a/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/SettingsDialogFragment.kt
+++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/SettingsDialogFragment.kt
@@ -14,6 +14,7 @@ import androidx.fragment.app.activityViewModels
14import com.google.android.material.dialog.MaterialAlertDialogBuilder 14import com.google.android.material.dialog.MaterialAlertDialogBuilder
15import com.google.android.material.slider.Slider 15import com.google.android.material.slider.Slider
16import org.yuzu.yuzu_emu.R 16import org.yuzu.yuzu_emu.R
17import org.yuzu.yuzu_emu.databinding.DialogEditTextBinding
17import org.yuzu.yuzu_emu.databinding.DialogSliderBinding 18import org.yuzu.yuzu_emu.databinding.DialogSliderBinding
18import org.yuzu.yuzu_emu.features.input.NativeInput 19import org.yuzu.yuzu_emu.features.input.NativeInput
19import org.yuzu.yuzu_emu.features.input.model.AnalogDirection 20import org.yuzu.yuzu_emu.features.input.model.AnalogDirection
@@ -23,6 +24,7 @@ import org.yuzu.yuzu_emu.features.settings.model.view.IntSingleChoiceSetting
23import org.yuzu.yuzu_emu.features.settings.model.view.SettingsItem 24import org.yuzu.yuzu_emu.features.settings.model.view.SettingsItem
24import org.yuzu.yuzu_emu.features.settings.model.view.SingleChoiceSetting 25import org.yuzu.yuzu_emu.features.settings.model.view.SingleChoiceSetting
25import org.yuzu.yuzu_emu.features.settings.model.view.SliderSetting 26import org.yuzu.yuzu_emu.features.settings.model.view.SliderSetting
27import org.yuzu.yuzu_emu.features.settings.model.view.StringInputSetting
26import org.yuzu.yuzu_emu.features.settings.model.view.StringSingleChoiceSetting 28import org.yuzu.yuzu_emu.features.settings.model.view.StringSingleChoiceSetting
27import org.yuzu.yuzu_emu.utils.ParamPackage 29import org.yuzu.yuzu_emu.utils.ParamPackage
28import org.yuzu.yuzu_emu.utils.collect 30import org.yuzu.yuzu_emu.utils.collect
@@ -37,6 +39,7 @@ class SettingsDialogFragment : DialogFragment(), DialogInterface.OnClickListener
37 private val settingsViewModel: SettingsViewModel by activityViewModels() 39 private val settingsViewModel: SettingsViewModel by activityViewModels()
38 40
39 private lateinit var sliderBinding: DialogSliderBinding 41 private lateinit var sliderBinding: DialogSliderBinding
42 private lateinit var stringInputBinding: DialogEditTextBinding
40 43
41 override fun onCreate(savedInstanceState: Bundle?) { 44 override fun onCreate(savedInstanceState: Bundle?) {
42 super.onCreate(savedInstanceState) 45 super.onCreate(savedInstanceState)
@@ -131,6 +134,18 @@ class SettingsDialogFragment : DialogFragment(), DialogInterface.OnClickListener
131 .create() 134 .create()
132 } 135 }
133 136
137 SettingsItem.TYPE_STRING_INPUT -> {
138 stringInputBinding = DialogEditTextBinding.inflate(layoutInflater)
139 val item = settingsViewModel.clickedItem as StringInputSetting
140 stringInputBinding.editText.setText(item.getSelectedValue())
141 MaterialAlertDialogBuilder(requireContext())
142 .setTitle(item.title)
143 .setView(stringInputBinding.root)
144 .setPositiveButton(android.R.string.ok, this)
145 .setNegativeButton(android.R.string.cancel, defaultCancelListener)
146 .create()
147 }
148
134 SettingsItem.TYPE_STRING_SINGLE_CHOICE -> { 149 SettingsItem.TYPE_STRING_SINGLE_CHOICE -> {
135 val item = settingsViewModel.clickedItem as StringSingleChoiceSetting 150 val item = settingsViewModel.clickedItem as StringSingleChoiceSetting
136 MaterialAlertDialogBuilder(requireContext()) 151 MaterialAlertDialogBuilder(requireContext())
@@ -158,6 +173,7 @@ class SettingsDialogFragment : DialogFragment(), DialogInterface.OnClickListener
158 ): View? { 173 ): View? {
159 return when (type) { 174 return when (type) {
160 SettingsItem.TYPE_SLIDER -> sliderBinding.root 175 SettingsItem.TYPE_SLIDER -> sliderBinding.root
176 SettingsItem.TYPE_STRING_INPUT -> stringInputBinding.root
161 else -> super.onCreateView(inflater, container, savedInstanceState) 177 else -> super.onCreateView(inflater, container, savedInstanceState)
162 } 178 }
163 } 179 }
@@ -200,6 +216,13 @@ class SettingsDialogFragment : DialogFragment(), DialogInterface.OnClickListener
200 val sliderSetting = settingsViewModel.clickedItem as SliderSetting 216 val sliderSetting = settingsViewModel.clickedItem as SliderSetting
201 sliderSetting.setSelectedValue(settingsViewModel.sliderProgress.value) 217 sliderSetting.setSelectedValue(settingsViewModel.sliderProgress.value)
202 } 218 }
219
220 is StringInputSetting -> {
221 val stringInputSetting = settingsViewModel.clickedItem as StringInputSetting
222 stringInputSetting.setSelectedValue(
223 (stringInputBinding.editText.text ?: "").toString()
224 )
225 }
203 } 226 }
204 closeDialog() 227 closeDialog()
205 } 228 }
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 e491c29a2..3ea5f5008 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
@@ -23,6 +23,7 @@ import org.yuzu.yuzu_emu.features.settings.model.LongSetting
23import org.yuzu.yuzu_emu.features.settings.model.Settings 23import org.yuzu.yuzu_emu.features.settings.model.Settings
24import org.yuzu.yuzu_emu.features.settings.model.Settings.MenuTag 24import org.yuzu.yuzu_emu.features.settings.model.Settings.MenuTag
25import org.yuzu.yuzu_emu.features.settings.model.ShortSetting 25import org.yuzu.yuzu_emu.features.settings.model.ShortSetting
26import org.yuzu.yuzu_emu.features.settings.model.StringSetting
26import org.yuzu.yuzu_emu.features.settings.model.view.* 27import org.yuzu.yuzu_emu.features.settings.model.view.*
27import org.yuzu.yuzu_emu.utils.InputHandler 28import org.yuzu.yuzu_emu.utils.InputHandler
28import org.yuzu.yuzu_emu.utils.NativeConfig 29import org.yuzu.yuzu_emu.utils.NativeConfig
@@ -153,6 +154,7 @@ class SettingsFragmentPresenter(
153 154
154 private fun addSystemSettings(sl: ArrayList<SettingsItem>) { 155 private fun addSystemSettings(sl: ArrayList<SettingsItem>) {
155 sl.apply { 156 sl.apply {
157 add(StringSetting.DEVICE_NAME.key)
156 add(BooleanSetting.RENDERER_USE_SPEED_LIMIT.key) 158 add(BooleanSetting.RENDERER_USE_SPEED_LIMIT.key)
157 add(ShortSetting.RENDERER_SPEED_LIMIT.key) 159 add(ShortSetting.RENDERER_SPEED_LIMIT.key)
158 add(BooleanSetting.USE_DOCKED_MODE.key) 160 add(BooleanSetting.USE_DOCKED_MODE.key)
@@ -778,7 +780,7 @@ class SettingsFragmentPresenter(
778 playerIndex: Int, 780 playerIndex: Int,
779 paramName: String, 781 paramName: String,
780 stick: NativeAnalog, 782 stick: NativeAnalog,
781 defaultValue: Int 783 defaultValue: Float
782 ): AbstractIntSetting = 784 ): AbstractIntSetting =
783 object : AbstractIntSetting { 785 object : AbstractIntSetting {
784 val params get() = NativeInput.getStickParam(playerIndex, stick) 786 val params get() = NativeInput.getStickParam(playerIndex, stick)
@@ -786,7 +788,7 @@ class SettingsFragmentPresenter(
786 override val key = "" 788 override val key = ""
787 789
788 override fun getInt(needsGlobal: Boolean): Int = 790 override fun getInt(needsGlobal: Boolean): Int =
789 (params.get(paramName, 0.15f) * 100).toInt() 791 (params.get(paramName, defaultValue) * 100).toInt()
790 792
791 override fun setInt(value: Int) { 793 override fun setInt(value: Int) {
792 val tempParams = params 794 val tempParams = params
@@ -794,12 +796,12 @@ class SettingsFragmentPresenter(
794 NativeInput.setStickParam(playerIndex, stick, tempParams) 796 NativeInput.setStickParam(playerIndex, stick, tempParams)
795 } 797 }
796 798
797 override val defaultValue = defaultValue 799 override val defaultValue = (defaultValue * 100).toInt()
798 800
799 override fun getValueAsString(needsGlobal: Boolean): String = 801 override fun getValueAsString(needsGlobal: Boolean): String =
800 getInt(needsGlobal).toString() 802 getInt(needsGlobal).toString()
801 803
802 override fun reset() = setInt(defaultValue) 804 override fun reset() = setInt(this.defaultValue)
803 } 805 }
804 806
805 private fun getExtraStickSettings( 807 private fun getExtraStickSettings(
@@ -809,11 +811,11 @@ class SettingsFragmentPresenter(
809 val stickIsController = 811 val stickIsController =
810 NativeInput.isController(NativeInput.getStickParam(playerIndex, nativeAnalog)) 812 NativeInput.isController(NativeInput.getStickParam(playerIndex, nativeAnalog))
811 val modifierRangeSetting = 813 val modifierRangeSetting =
812 getStickIntSettingFromParam(playerIndex, "modifier_scale", nativeAnalog, 50) 814 getStickIntSettingFromParam(playerIndex, "modifier_scale", nativeAnalog, 0.5f)
813 val stickRangeSetting = 815 val stickRangeSetting =
814 getStickIntSettingFromParam(playerIndex, "range", nativeAnalog, 95) 816 getStickIntSettingFromParam(playerIndex, "range", nativeAnalog, 0.95f)
815 val stickDeadzoneSetting = 817 val stickDeadzoneSetting =
816 getStickIntSettingFromParam(playerIndex, "deadzone", nativeAnalog, 15) 818 getStickIntSettingFromParam(playerIndex, "deadzone", nativeAnalog, 0.15f)
817 819
818 val out = mutableListOf<SettingsItem>().apply { 820 val out = mutableListOf<SettingsItem>().apply {
819 if (stickIsController) { 821 if (stickIsController) {
diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/viewholder/DateTimeViewHolder.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/viewholder/DateTimeViewHolder.kt
index 367db7fd2..0309fad59 100644
--- a/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/viewholder/DateTimeViewHolder.kt
+++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/viewholder/DateTimeViewHolder.kt
@@ -13,7 +13,6 @@ import org.yuzu.yuzu_emu.databinding.ListItemSettingBinding
13import org.yuzu.yuzu_emu.features.settings.model.view.DateTimeSetting 13import org.yuzu.yuzu_emu.features.settings.model.view.DateTimeSetting
14import org.yuzu.yuzu_emu.features.settings.model.view.SettingsItem 14import org.yuzu.yuzu_emu.features.settings.model.view.SettingsItem
15import org.yuzu.yuzu_emu.features.settings.ui.SettingsAdapter 15import org.yuzu.yuzu_emu.features.settings.ui.SettingsAdapter
16import org.yuzu.yuzu_emu.utils.NativeConfig
17import org.yuzu.yuzu_emu.utils.ViewUtils.setVisible 16import org.yuzu.yuzu_emu.utils.ViewUtils.setVisible
18 17
19class DateTimeViewHolder(val binding: ListItemSettingBinding, adapter: SettingsAdapter) : 18class DateTimeViewHolder(val binding: ListItemSettingBinding, adapter: SettingsAdapter) :
@@ -32,9 +31,7 @@ class DateTimeViewHolder(val binding: ListItemSettingBinding, adapter: SettingsA
32 val dateFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM) 31 val dateFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)
33 binding.textSettingValue.text = dateFormatter.format(zonedTime) 32 binding.textSettingValue.text = dateFormatter.format(zonedTime)
34 33
35 binding.buttonClear.setVisible( 34 binding.buttonClear.setVisible(setting.clearable)
36 !setting.setting.global || NativeConfig.isPerGameConfigLoaded()
37 )
38 binding.buttonClear.setOnClickListener { 35 binding.buttonClear.setOnClickListener {
39 adapter.onClearClick(setting, bindingAdapterPosition) 36 adapter.onClearClick(setting, bindingAdapterPosition)
40 } 37 }
diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/viewholder/SingleChoiceViewHolder.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/viewholder/SingleChoiceViewHolder.kt
index e2fe0b072..489f55455 100644
--- a/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/viewholder/SingleChoiceViewHolder.kt
+++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/viewholder/SingleChoiceViewHolder.kt
@@ -10,7 +10,6 @@ import org.yuzu.yuzu_emu.features.settings.model.view.SettingsItem
10import org.yuzu.yuzu_emu.features.settings.model.view.SingleChoiceSetting 10import org.yuzu.yuzu_emu.features.settings.model.view.SingleChoiceSetting
11import org.yuzu.yuzu_emu.features.settings.model.view.StringSingleChoiceSetting 11import org.yuzu.yuzu_emu.features.settings.model.view.StringSingleChoiceSetting
12import org.yuzu.yuzu_emu.features.settings.ui.SettingsAdapter 12import org.yuzu.yuzu_emu.features.settings.ui.SettingsAdapter
13import org.yuzu.yuzu_emu.utils.NativeConfig
14import org.yuzu.yuzu_emu.utils.ViewUtils.setVisible 13import org.yuzu.yuzu_emu.utils.ViewUtils.setVisible
15 14
16class SingleChoiceViewHolder(val binding: ListItemSettingBinding, adapter: SettingsAdapter) : 15class SingleChoiceViewHolder(val binding: ListItemSettingBinding, adapter: SettingsAdapter) :
@@ -48,9 +47,7 @@ class SingleChoiceViewHolder(val binding: ListItemSettingBinding, adapter: Setti
48 binding.textSettingValue.setVisible(false) 47 binding.textSettingValue.setVisible(false)
49 } 48 }
50 49
51 binding.buttonClear.setVisible( 50 binding.buttonClear.setVisible(setting.clearable)
52 !setting.setting.global || NativeConfig.isPerGameConfigLoaded()
53 )
54 binding.buttonClear.setOnClickListener { 51 binding.buttonClear.setOnClickListener {
55 adapter.onClearClick(setting, bindingAdapterPosition) 52 adapter.onClearClick(setting, bindingAdapterPosition)
56 } 53 }
diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/viewholder/SliderViewHolder.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/viewholder/SliderViewHolder.kt
index a37b59b44..90a7138cb 100644
--- a/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/viewholder/SliderViewHolder.kt
+++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/viewholder/SliderViewHolder.kt
@@ -9,7 +9,6 @@ import org.yuzu.yuzu_emu.databinding.ListItemSettingBinding
9import org.yuzu.yuzu_emu.features.settings.model.view.SettingsItem 9import org.yuzu.yuzu_emu.features.settings.model.view.SettingsItem
10import org.yuzu.yuzu_emu.features.settings.model.view.SliderSetting 10import org.yuzu.yuzu_emu.features.settings.model.view.SliderSetting
11import org.yuzu.yuzu_emu.features.settings.ui.SettingsAdapter 11import org.yuzu.yuzu_emu.features.settings.ui.SettingsAdapter
12import org.yuzu.yuzu_emu.utils.NativeConfig
13import org.yuzu.yuzu_emu.utils.ViewUtils.setVisible 12import org.yuzu.yuzu_emu.utils.ViewUtils.setVisible
14 13
15class SliderViewHolder(val binding: ListItemSettingBinding, adapter: SettingsAdapter) : 14class SliderViewHolder(val binding: ListItemSettingBinding, adapter: SettingsAdapter) :
@@ -28,9 +27,7 @@ class SliderViewHolder(val binding: ListItemSettingBinding, adapter: SettingsAda
28 setting.units 27 setting.units
29 ) 28 )
30 29
31 binding.buttonClear.setVisible( 30 binding.buttonClear.setVisible(setting.clearable)
32 !setting.setting.global || NativeConfig.isPerGameConfigLoaded()
33 )
34 binding.buttonClear.setOnClickListener { 31 binding.buttonClear.setOnClickListener {
35 adapter.onClearClick(setting, bindingAdapterPosition) 32 adapter.onClearClick(setting, bindingAdapterPosition)
36 } 33 }
diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/viewholder/StringInputViewHolder.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/viewholder/StringInputViewHolder.kt
new file mode 100644
index 000000000..a4fd36f62
--- /dev/null
+++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/viewholder/StringInputViewHolder.kt
@@ -0,0 +1,45 @@
1// SPDX-FileCopyrightText: 2024 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-2.0-or-later
3
4package org.yuzu.yuzu_emu.features.settings.ui.viewholder
5
6import android.view.View
7import org.yuzu.yuzu_emu.databinding.ListItemSettingBinding
8import org.yuzu.yuzu_emu.features.settings.model.view.SettingsItem
9import org.yuzu.yuzu_emu.features.settings.model.view.StringInputSetting
10import org.yuzu.yuzu_emu.features.settings.ui.SettingsAdapter
11import org.yuzu.yuzu_emu.utils.ViewUtils.setVisible
12
13class StringInputViewHolder(val binding: ListItemSettingBinding, adapter: SettingsAdapter) :
14 SettingViewHolder(binding.root, adapter) {
15 private lateinit var setting: StringInputSetting
16
17 override fun bind(item: SettingsItem) {
18 setting = item as StringInputSetting
19 binding.textSettingName.text = setting.title
20 binding.textSettingDescription.setVisible(setting.description.isNotEmpty())
21 binding.textSettingDescription.text = setting.description
22 binding.textSettingValue.setVisible(true)
23 binding.textSettingValue.text = setting.getSelectedValue()
24
25 binding.buttonClear.setVisible(setting.clearable)
26 binding.buttonClear.setOnClickListener {
27 adapter.onClearClick(setting, bindingAdapterPosition)
28 }
29
30 setStyle(setting.isEditable, binding)
31 }
32
33 override fun onClick(clicked: View) {
34 if (setting.isEditable) {
35 adapter.onStringInputClick(setting, bindingAdapterPosition)
36 }
37 }
38
39 override fun onLongClick(clicked: View): Boolean {
40 if (setting.isEditable) {
41 return adapter.onLongClick(setting, bindingAdapterPosition)
42 }
43 return false
44 }
45}
diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/viewholder/SwitchSettingViewHolder.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/viewholder/SwitchSettingViewHolder.kt
index 53f7b301f..e5763264a 100644
--- a/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/viewholder/SwitchSettingViewHolder.kt
+++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/viewholder/SwitchSettingViewHolder.kt
@@ -9,7 +9,6 @@ import org.yuzu.yuzu_emu.databinding.ListItemSettingSwitchBinding
9import org.yuzu.yuzu_emu.features.settings.model.view.SettingsItem 9import org.yuzu.yuzu_emu.features.settings.model.view.SettingsItem
10import org.yuzu.yuzu_emu.features.settings.model.view.SwitchSetting 10import org.yuzu.yuzu_emu.features.settings.model.view.SwitchSetting
11import org.yuzu.yuzu_emu.features.settings.ui.SettingsAdapter 11import org.yuzu.yuzu_emu.features.settings.ui.SettingsAdapter
12import org.yuzu.yuzu_emu.utils.NativeConfig
13import org.yuzu.yuzu_emu.utils.ViewUtils.setVisible 12import org.yuzu.yuzu_emu.utils.ViewUtils.setVisible
14 13
15class SwitchSettingViewHolder(val binding: ListItemSettingSwitchBinding, adapter: SettingsAdapter) : 14class SwitchSettingViewHolder(val binding: ListItemSettingSwitchBinding, adapter: SettingsAdapter) :
@@ -29,9 +28,7 @@ class SwitchSettingViewHolder(val binding: ListItemSettingSwitchBinding, adapter
29 adapter.onBooleanClick(setting, binding.switchWidget.isChecked, bindingAdapterPosition) 28 adapter.onBooleanClick(setting, binding.switchWidget.isChecked, bindingAdapterPosition)
30 } 29 }
31 30
32 binding.buttonClear.setVisible( 31 binding.buttonClear.setVisible(setting.clearable)
33 !setting.setting.global || NativeConfig.isPerGameConfigLoaded()
34 )
35 binding.buttonClear.setOnClickListener { 32 binding.buttonClear.setOnClickListener {
36 adapter.onClearClick(setting, bindingAdapterPosition) 33 adapter.onClearClick(setting, bindingAdapterPosition)
37 } 34 }
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 c3b2b11f8..bcc880e17 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
@@ -810,7 +810,7 @@ class EmulationFragment : Fragment(), SurfaceHolder.Callback {
810 } 810 }
811 } 811 }
812 } 812 }
813 binding.doneControlConfig.setVisible(false) 813 binding.doneControlConfig.setVisible(true)
814 binding.surfaceInputOverlay.setIsInEditMode(true) 814 binding.surfaceInputOverlay.setIsInEditMode(true)
815 } 815 }
816 816
diff --git a/src/android/app/src/main/java/org/yuzu/yuzu_emu/overlay/InputOverlay.kt b/src/android/app/src/main/java/org/yuzu/yuzu_emu/overlay/InputOverlay.kt
index 66907085a..737e03584 100644
--- a/src/android/app/src/main/java/org/yuzu/yuzu_emu/overlay/InputOverlay.kt
+++ b/src/android/app/src/main/java/org/yuzu/yuzu_emu/overlay/InputOverlay.kt
@@ -28,6 +28,7 @@ import org.yuzu.yuzu_emu.features.input.NativeInput
28import org.yuzu.yuzu_emu.R 28import org.yuzu.yuzu_emu.R
29import org.yuzu.yuzu_emu.features.input.model.NativeAnalog 29import org.yuzu.yuzu_emu.features.input.model.NativeAnalog
30import org.yuzu.yuzu_emu.features.input.model.NativeButton 30import org.yuzu.yuzu_emu.features.input.model.NativeButton
31import org.yuzu.yuzu_emu.features.input.model.NpadStyleIndex
31import org.yuzu.yuzu_emu.features.settings.model.BooleanSetting 32import org.yuzu.yuzu_emu.features.settings.model.BooleanSetting
32import org.yuzu.yuzu_emu.features.settings.model.IntSetting 33import org.yuzu.yuzu_emu.features.settings.model.IntSetting
33import org.yuzu.yuzu_emu.overlay.model.OverlayControl 34import org.yuzu.yuzu_emu.overlay.model.OverlayControl
@@ -99,12 +100,10 @@ class InputOverlay(context: Context, attrs: AttributeSet?) :
99 } 100 }
100 101
101 var shouldUpdateView = false 102 var shouldUpdateView = false
102 val playerIndex = 103 val playerIndex = when (NativeInput.getStyleIndex(0)) {
103 if (NativeInput.isHandheldOnly()) { 104 NpadStyleIndex.Handheld -> 8
104 NativeInput.ConsoleDevice 105 else -> 0
105 } else { 106 }
106 NativeInput.Player1Device
107 }
108 107
109 for (button in overlayButtons) { 108 for (button in overlayButtons) {
110 if (!button.updateStatus(event)) { 109 if (!button.updateStatus(event)) {
@@ -664,7 +663,7 @@ class InputOverlay(context: Context, attrs: AttributeSet?) :
664 663
665 val overlayControlData = NativeConfig.getOverlayControlData() 664 val overlayControlData = NativeConfig.getOverlayControlData()
666 overlayControlData.forEach { 665 overlayControlData.forEach {
667 it.enabled = OverlayControl.from(it.id)?.defaultVisibility == false 666 it.enabled = OverlayControl.from(it.id)?.defaultVisibility == true
668 } 667 }
669 NativeConfig.setOverlayControlData(overlayControlData) 668 NativeConfig.setOverlayControlData(overlayControlData)
670 669
diff --git a/src/android/app/src/main/jni/native.cpp b/src/android/app/src/main/jni/native.cpp
index fa2300ae6..5d484a85e 100644
--- a/src/android/app/src/main/jni/native.cpp
+++ b/src/android/app/src/main/jni/native.cpp
@@ -292,6 +292,9 @@ void EmulationSession::ShutdownEmulation() {
292 // Unload user input. 292 // Unload user input.
293 m_system.HIDCore().UnloadInputDevices(); 293 m_system.HIDCore().UnloadInputDevices();
294 294
295 // Enable all controllers
296 m_system.HIDCore().SetSupportedStyleTag({Core::HID::NpadStyleSet::All});
297
295 // Shutdown the main emulated process 298 // Shutdown the main emulated process
296 if (m_load_result == Core::SystemResultStatus::Success) { 299 if (m_load_result == Core::SystemResultStatus::Success) {
297 m_system.DetachDebugger(); 300 m_system.DetachDebugger();
diff --git a/src/android/app/src/main/jni/native_input.cpp b/src/android/app/src/main/jni/native_input.cpp
index 37a65f2b8..4935a4607 100644
--- a/src/android/app/src/main/jni/native_input.cpp
+++ b/src/android/app/src/main/jni/native_input.cpp
@@ -102,8 +102,50 @@ void ApplyControllerConfig(size_t player_index,
102 } 102 }
103} 103}
104 104
105std::vector<s32> GetSupportedStyles(int player_index) {
106 auto& hid_core = EmulationSession::GetInstance().System().HIDCore();
107 const auto npad_style_set = hid_core.GetSupportedStyleTag();
108 std::vector<s32> supported_indexes;
109 if (npad_style_set.fullkey == 1) {
110 supported_indexes.push_back(static_cast<s32>(Core::HID::NpadStyleIndex::Fullkey));
111 }
112
113 if (npad_style_set.joycon_dual == 1) {
114 supported_indexes.push_back(static_cast<s32>(Core::HID::NpadStyleIndex::JoyconDual));
115 }
116
117 if (npad_style_set.joycon_left == 1) {
118 supported_indexes.push_back(static_cast<s32>(Core::HID::NpadStyleIndex::JoyconLeft));
119 }
120
121 if (npad_style_set.joycon_right == 1) {
122 supported_indexes.push_back(static_cast<s32>(Core::HID::NpadStyleIndex::JoyconRight));
123 }
124
125 if (player_index == 0 && npad_style_set.handheld == 1) {
126 supported_indexes.push_back(static_cast<s32>(Core::HID::NpadStyleIndex::Handheld));
127 }
128
129 if (npad_style_set.gamecube == 1) {
130 supported_indexes.push_back(static_cast<s32>(Core::HID::NpadStyleIndex::GameCube));
131 }
132
133 return supported_indexes;
134}
135
105void ConnectController(size_t player_index, bool connected) { 136void ConnectController(size_t player_index, bool connected) {
106 auto& hid_core = EmulationSession::GetInstance().System().HIDCore(); 137 auto& hid_core = EmulationSession::GetInstance().System().HIDCore();
138 ApplyControllerConfig(player_index, [&](Core::HID::EmulatedController* controller) {
139 auto supported_styles = GetSupportedStyles(player_index);
140 auto controller_style = controller->GetNpadStyleIndex(true);
141 auto style = std::find(supported_styles.begin(), supported_styles.end(),
142 static_cast<int>(controller_style));
143 if (style == supported_styles.end() && !supported_styles.empty()) {
144 controller->SetNpadStyleIndex(
145 static_cast<Core::HID::NpadStyleIndex>(supported_styles[0]));
146 }
147 });
148
107 if (player_index == 0) { 149 if (player_index == 0) {
108 auto* handheld = hid_core.GetEmulatedController(Core::HID::NpadIdType::Handheld); 150 auto* handheld = hid_core.GetEmulatedController(Core::HID::NpadIdType::Handheld);
109 auto* player_one = hid_core.GetEmulatedController(Core::HID::NpadIdType::Player1); 151 auto* player_one = hid_core.GetEmulatedController(Core::HID::NpadIdType::Player1);
@@ -522,36 +564,10 @@ jint Java_org_yuzu_yuzu_1emu_features_input_NativeInput_getButtonNameImpl(JNIEnv
522 564
523jintArray Java_org_yuzu_yuzu_1emu_features_input_NativeInput_getSupportedStyleTagsImpl( 565jintArray Java_org_yuzu_yuzu_1emu_features_input_NativeInput_getSupportedStyleTagsImpl(
524 JNIEnv* env, jobject j_obj, jint j_player_index) { 566 JNIEnv* env, jobject j_obj, jint j_player_index) {
525 auto& hid_core = EmulationSession::GetInstance().System().HIDCore(); 567 auto supported_styles = GetSupportedStyles(j_player_index);
526 const auto npad_style_set = hid_core.GetSupportedStyleTag(); 568 jintArray j_supported_indexes = env->NewIntArray(supported_styles.size());
527 std::vector<s32> supported_indexes; 569 env->SetIntArrayRegion(j_supported_indexes, 0, supported_styles.size(),
528 if (npad_style_set.fullkey == 1) { 570 supported_styles.data());
529 supported_indexes.push_back(static_cast<u32>(Core::HID::NpadStyleIndex::Fullkey));
530 }
531
532 if (npad_style_set.joycon_dual == 1) {
533 supported_indexes.push_back(static_cast<u32>(Core::HID::NpadStyleIndex::JoyconDual));
534 }
535
536 if (npad_style_set.joycon_left == 1) {
537 supported_indexes.push_back(static_cast<u32>(Core::HID::NpadStyleIndex::JoyconLeft));
538 }
539
540 if (npad_style_set.joycon_right == 1) {
541 supported_indexes.push_back(static_cast<u32>(Core::HID::NpadStyleIndex::JoyconRight));
542 }
543
544 if (j_player_index == 0 && npad_style_set.handheld == 1) {
545 supported_indexes.push_back(static_cast<u32>(Core::HID::NpadStyleIndex::Handheld));
546 }
547
548 if (npad_style_set.gamecube == 1) {
549 supported_indexes.push_back(static_cast<u32>(Core::HID::NpadStyleIndex::GameCube));
550 }
551
552 jintArray j_supported_indexes = env->NewIntArray(supported_indexes.size());
553 env->SetIntArrayRegion(j_supported_indexes, 0, supported_indexes.size(),
554 supported_indexes.data());
555 return j_supported_indexes; 571 return j_supported_indexes;
556} 572}
557 573
diff --git a/src/android/app/src/main/res/values/strings.xml b/src/android/app/src/main/res/values/strings.xml
index 6a631f664..f7f19cdad 100644
--- a/src/android/app/src/main/res/values/strings.xml
+++ b/src/android/app/src/main/res/values/strings.xml
@@ -209,6 +209,7 @@
209 <string name="value_with_units">%1$s%2$s</string> 209 <string name="value_with_units">%1$s%2$s</string>
210 210
211 <!-- System settings strings --> 211 <!-- System settings strings -->
212 <string name="device_name">Device name</string>
212 <string name="use_docked_mode">Docked Mode</string> 213 <string name="use_docked_mode">Docked Mode</string>
213 <string name="use_docked_mode_description">Increases resolution, decreasing performance. Handheld Mode is used when disabled, lowering resolution and increasing performance.</string> 214 <string name="use_docked_mode_description">Increases resolution, decreasing performance. Handheld Mode is used when disabled, lowering resolution and increasing performance.</string>
214 <string name="emulated_region">Emulated region</string> 215 <string name="emulated_region">Emulated region</string>
diff --git a/src/common/settings.h b/src/common/settings.h
index aa054dc24..b2b071e7e 100644
--- a/src/common/settings.h
+++ b/src/common/settings.h
@@ -384,6 +384,12 @@ struct Values {
384 AstcRecompression::Bc3, 384 AstcRecompression::Bc3,
385 "astc_recompression", 385 "astc_recompression",
386 Category::RendererAdvanced}; 386 Category::RendererAdvanced};
387 SwitchableSetting<VramUsageMode, true> vram_usage_mode{linkage,
388 VramUsageMode::Conservative,
389 VramUsageMode::Conservative,
390 VramUsageMode::Aggressive,
391 "vram_usage_mode",
392 Category::RendererAdvanced};
387 SwitchableSetting<bool> async_presentation{linkage, 393 SwitchableSetting<bool> async_presentation{linkage,
388#ifdef ANDROID 394#ifdef ANDROID
389 true, 395 true,
diff --git a/src/common/settings_enums.h b/src/common/settings_enums.h
index f42367e67..6e247e930 100644
--- a/src/common/settings_enums.h
+++ b/src/common/settings_enums.h
@@ -122,6 +122,8 @@ ENUM(AstcRecompression, Uncompressed, Bc1, Bc3);
122 122
123ENUM(VSyncMode, Immediate, Mailbox, Fifo, FifoRelaxed); 123ENUM(VSyncMode, Immediate, Mailbox, Fifo, FifoRelaxed);
124 124
125ENUM(VramUsageMode, Conservative, Aggressive);
126
125ENUM(RendererBackend, OpenGL, Vulkan, Null); 127ENUM(RendererBackend, OpenGL, Vulkan, Null);
126 128
127ENUM(ShaderBackend, Glsl, Glasm, SpirV); 129ENUM(ShaderBackend, Glsl, Glasm, SpirV);
diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txt
index de945fa70..65bbf4818 100644
--- a/src/core/CMakeLists.txt
+++ b/src/core/CMakeLists.txt
@@ -60,8 +60,12 @@ add_library(core STATIC
60 file_sys/fs_path_utility.h 60 file_sys/fs_path_utility.h
61 file_sys/fs_save_data_types.h 61 file_sys/fs_save_data_types.h
62 file_sys/fs_string_util.h 62 file_sys/fs_string_util.h
63 file_sys/fsa/fs_i_directory.h
64 file_sys/fsa/fs_i_file.h
65 file_sys/fsa/fs_i_filesystem.h
63 file_sys/fsmitm_romfsbuild.cpp 66 file_sys/fsmitm_romfsbuild.cpp
64 file_sys/fsmitm_romfsbuild.h 67 file_sys/fsmitm_romfsbuild.h
68 file_sys/fssrv/fssrv_sf_path.h
65 file_sys/fssystem/fs_i_storage.h 69 file_sys/fssystem/fs_i_storage.h
66 file_sys/fssystem/fs_types.h 70 file_sys/fssystem/fs_types.h
67 file_sys/fssystem/fssystem_aes_ctr_counter_extended_storage.cpp 71 file_sys/fssystem/fssystem_aes_ctr_counter_extended_storage.cpp
@@ -544,6 +548,16 @@ add_library(core STATIC
544 hle/service/btdrv/btdrv.h 548 hle/service/btdrv/btdrv.h
545 hle/service/btm/btm.cpp 549 hle/service/btm/btm.cpp
546 hle/service/btm/btm.h 550 hle/service/btm/btm.h
551 hle/service/btm/btm_debug.cpp
552 hle/service/btm/btm_debug.h
553 hle/service/btm/btm_system.cpp
554 hle/service/btm/btm_system.h
555 hle/service/btm/btm_system_core.cpp
556 hle/service/btm/btm_system_core.h
557 hle/service/btm/btm_user.cpp
558 hle/service/btm/btm_user.h
559 hle/service/btm/btm_user_core.cpp
560 hle/service/btm/btm_user_core.h
547 hle/service/caps/caps.cpp 561 hle/service/caps/caps.cpp
548 hle/service/caps/caps.h 562 hle/service/caps/caps.h
549 hle/service/caps/caps_a.cpp 563 hle/service/caps/caps_a.cpp
@@ -886,6 +900,21 @@ add_library(core STATIC
886 hle/service/pm/pm.h 900 hle/service/pm/pm.h
887 hle/service/prepo/prepo.cpp 901 hle/service/prepo/prepo.cpp
888 hle/service/prepo/prepo.h 902 hle/service/prepo/prepo.h
903 hle/service/psc/ovln/ovln_types.h
904 hle/service/psc/ovln/receiver_service.cpp
905 hle/service/psc/ovln/receiver_service.h
906 hle/service/psc/ovln/receiver.cpp
907 hle/service/psc/ovln/receiver.h
908 hle/service/psc/ovln/sender_service.cpp
909 hle/service/psc/ovln/sender_service.h
910 hle/service/psc/ovln/sender.cpp
911 hle/service/psc/ovln/sender.h
912 hle/service/psc/pm_control.cpp
913 hle/service/psc/pm_control.h
914 hle/service/psc/pm_module.cpp
915 hle/service/psc/pm_module.h
916 hle/service/psc/pm_service.cpp
917 hle/service/psc/pm_service.h
889 hle/service/psc/psc.cpp 918 hle/service/psc/psc.cpp
890 hle/service/psc/psc.h 919 hle/service/psc/psc.h
891 hle/service/psc/time/alarms.cpp 920 hle/service/psc/time/alarms.cpp
diff --git a/src/core/device_memory_manager.inc b/src/core/device_memory_manager.inc
index 37c1e69c3..f104d495b 100644
--- a/src/core/device_memory_manager.inc
+++ b/src/core/device_memory_manager.inc
@@ -522,13 +522,17 @@ void DeviceMemoryManager<Traits>::UpdatePagesCachedCount(DAddr addr, size_t size
522 auto* memory_device_inter = registered_processes[asid.id]; 522 auto* memory_device_inter = registered_processes[asid.id];
523 const auto release_pending = [&] { 523 const auto release_pending = [&] {
524 if (uncache_bytes > 0) { 524 if (uncache_bytes > 0) {
525 MarkRegionCaching(memory_device_inter, uncache_begin << Memory::YUZU_PAGEBITS, 525 if (memory_device_inter != nullptr) {
526 uncache_bytes, false); 526 MarkRegionCaching(memory_device_inter, uncache_begin << Memory::YUZU_PAGEBITS,
527 uncache_bytes, false);
528 }
527 uncache_bytes = 0; 529 uncache_bytes = 0;
528 } 530 }
529 if (cache_bytes > 0) { 531 if (cache_bytes > 0) {
530 MarkRegionCaching(memory_device_inter, cache_begin << Memory::YUZU_PAGEBITS, 532 if (memory_device_inter != nullptr) {
531 cache_bytes, true); 533 MarkRegionCaching(memory_device_inter, cache_begin << Memory::YUZU_PAGEBITS,
534 cache_bytes, true);
535 }
532 cache_bytes = 0; 536 cache_bytes = 0;
533 } 537 }
534 }; 538 };
diff --git a/src/core/file_sys/fs_filesystem.h b/src/core/file_sys/fs_filesystem.h
index 7f237b7fa..329b5aca5 100644
--- a/src/core/file_sys/fs_filesystem.h
+++ b/src/core/file_sys/fs_filesystem.h
@@ -23,6 +23,8 @@ enum class OpenDirectoryMode : u64 {
23 File = (1 << 1), 23 File = (1 << 1),
24 24
25 All = (Directory | File), 25 All = (Directory | File),
26
27 NotRequireFileSize = (1ULL << 31),
26}; 28};
27DECLARE_ENUM_FLAG_OPERATORS(OpenDirectoryMode) 29DECLARE_ENUM_FLAG_OPERATORS(OpenDirectoryMode)
28 30
@@ -36,4 +38,29 @@ enum class CreateOption : u8 {
36 BigFile = (1 << 0), 38 BigFile = (1 << 0),
37}; 39};
38 40
41struct FileSystemAttribute {
42 u8 dir_entry_name_length_max_defined;
43 u8 file_entry_name_length_max_defined;
44 u8 dir_path_name_length_max_defined;
45 u8 file_path_name_length_max_defined;
46 INSERT_PADDING_BYTES_NOINIT(0x5);
47 u8 utf16_dir_entry_name_length_max_defined;
48 u8 utf16_file_entry_name_length_max_defined;
49 u8 utf16_dir_path_name_length_max_defined;
50 u8 utf16_file_path_name_length_max_defined;
51 INSERT_PADDING_BYTES_NOINIT(0x18);
52 s32 dir_entry_name_length_max;
53 s32 file_entry_name_length_max;
54 s32 dir_path_name_length_max;
55 s32 file_path_name_length_max;
56 INSERT_PADDING_WORDS_NOINIT(0x5);
57 s32 utf16_dir_entry_name_length_max;
58 s32 utf16_file_entry_name_length_max;
59 s32 utf16_dir_path_name_length_max;
60 s32 utf16_file_path_name_length_max;
61 INSERT_PADDING_WORDS_NOINIT(0x18);
62 INSERT_PADDING_WORDS_NOINIT(0x1);
63};
64static_assert(sizeof(FileSystemAttribute) == 0xC0, "FileSystemAttribute has incorrect size");
65
39} // namespace FileSys 66} // namespace FileSys
diff --git a/src/core/file_sys/fs_memory_management.h b/src/core/file_sys/fs_memory_management.h
index f03c6354b..080017c5d 100644
--- a/src/core/file_sys/fs_memory_management.h
+++ b/src/core/file_sys/fs_memory_management.h
@@ -10,7 +10,7 @@ namespace FileSys {
10 10
11constexpr size_t RequiredAlignment = alignof(u64); 11constexpr size_t RequiredAlignment = alignof(u64);
12 12
13void* AllocateUnsafe(size_t size) { 13inline void* AllocateUnsafe(size_t size) {
14 // Allocate 14 // Allocate
15 void* const ptr = ::operator new(size, std::align_val_t{RequiredAlignment}); 15 void* const ptr = ::operator new(size, std::align_val_t{RequiredAlignment});
16 16
@@ -21,16 +21,16 @@ void* AllocateUnsafe(size_t size) {
21 return ptr; 21 return ptr;
22} 22}
23 23
24void DeallocateUnsafe(void* ptr, size_t size) { 24inline void DeallocateUnsafe(void* ptr, size_t size) {
25 // Deallocate the pointer 25 // Deallocate the pointer
26 ::operator delete(ptr, std::align_val_t{RequiredAlignment}); 26 ::operator delete(ptr, std::align_val_t{RequiredAlignment});
27} 27}
28 28
29void* Allocate(size_t size) { 29inline void* Allocate(size_t size) {
30 return AllocateUnsafe(size); 30 return AllocateUnsafe(size);
31} 31}
32 32
33void Deallocate(void* ptr, size_t size) { 33inline void Deallocate(void* ptr, size_t size) {
34 // If the pointer is non-null, deallocate it 34 // If the pointer is non-null, deallocate it
35 if (ptr != nullptr) { 35 if (ptr != nullptr) {
36 DeallocateUnsafe(ptr, size); 36 DeallocateUnsafe(ptr, size);
diff --git a/src/core/file_sys/fs_path.h b/src/core/file_sys/fs_path.h
index 56ba08a6a..1566e82b9 100644
--- a/src/core/file_sys/fs_path.h
+++ b/src/core/file_sys/fs_path.h
@@ -381,7 +381,7 @@ public:
381 381
382 // Check that it's possible for us to remove a child 382 // Check that it's possible for us to remove a child
383 auto* p = m_write_buffer.Get(); 383 auto* p = m_write_buffer.Get();
384 s32 len = std::strlen(p); 384 s32 len = static_cast<s32>(std::strlen(p));
385 R_UNLESS(len != 1 || (p[0] != '/' && p[0] != '.'), ResultNotImplemented); 385 R_UNLESS(len != 1 || (p[0] != '/' && p[0] != '.'), ResultNotImplemented);
386 386
387 // Handle a trailing separator 387 // Handle a trailing separator
diff --git a/src/core/file_sys/fs_path_utility.h b/src/core/file_sys/fs_path_utility.h
index 5643141f9..cdfd8c772 100644
--- a/src/core/file_sys/fs_path_utility.h
+++ b/src/core/file_sys/fs_path_utility.h
@@ -426,9 +426,10 @@ public:
426 R_SUCCEED(); 426 R_SUCCEED();
427 } 427 }
428 428
429 static Result Normalize(char* dst, size_t* out_len, const char* path, size_t max_out_size, 429 static constexpr Result Normalize(char* dst, size_t* out_len, const char* path,
430 bool is_windows_path, bool is_drive_relative_path, 430 size_t max_out_size, bool is_windows_path,
431 bool allow_all_characters = false) { 431 bool is_drive_relative_path,
432 bool allow_all_characters = false) {
432 // Use StringTraits names for remainder of scope 433 // Use StringTraits names for remainder of scope
433 using namespace StringTraits; 434 using namespace StringTraits;
434 435
diff --git a/src/core/file_sys/fs_string_util.h b/src/core/file_sys/fs_string_util.h
index 874e09054..c751a8f1a 100644
--- a/src/core/file_sys/fs_string_util.h
+++ b/src/core/file_sys/fs_string_util.h
@@ -20,6 +20,11 @@ constexpr int Strlen(const T* str) {
20} 20}
21 21
22template <typename T> 22template <typename T>
23constexpr int Strnlen(const T* str, std::size_t count) {
24 return Strnlen(str, static_cast<int>(count));
25}
26
27template <typename T>
23constexpr int Strnlen(const T* str, int count) { 28constexpr int Strnlen(const T* str, int count) {
24 ASSERT(str != nullptr); 29 ASSERT(str != nullptr);
25 ASSERT(count >= 0); 30 ASSERT(count >= 0);
@@ -33,6 +38,11 @@ constexpr int Strnlen(const T* str, int count) {
33} 38}
34 39
35template <typename T> 40template <typename T>
41constexpr int Strncmp(const T* lhs, const T* rhs, std::size_t count) {
42 return Strncmp(lhs, rhs, static_cast<int>(count));
43}
44
45template <typename T>
36constexpr int Strncmp(const T* lhs, const T* rhs, int count) { 46constexpr int Strncmp(const T* lhs, const T* rhs, int count) {
37 ASSERT(lhs != nullptr); 47 ASSERT(lhs != nullptr);
38 ASSERT(rhs != nullptr); 48 ASSERT(rhs != nullptr);
@@ -52,6 +62,11 @@ constexpr int Strncmp(const T* lhs, const T* rhs, int count) {
52} 62}
53 63
54template <typename T> 64template <typename T>
65static constexpr int Strlcpy(T* dst, const T* src, std::size_t count) {
66 return Strlcpy<T>(dst, src, static_cast<int>(count));
67}
68
69template <typename T>
55static constexpr int Strlcpy(T* dst, const T* src, int count) { 70static constexpr int Strlcpy(T* dst, const T* src, int count) {
56 ASSERT(dst != nullptr); 71 ASSERT(dst != nullptr);
57 ASSERT(src != nullptr); 72 ASSERT(src != nullptr);
diff --git a/src/core/file_sys/fsa/fs_i_directory.h b/src/core/file_sys/fsa/fs_i_directory.h
new file mode 100644
index 000000000..c8e895eab
--- /dev/null
+++ b/src/core/file_sys/fsa/fs_i_directory.h
@@ -0,0 +1,91 @@
1// SPDX-FileCopyrightText: Copyright 2024 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-2.0-or-later
3
4#pragma once
5
6#include "common/common_types.h"
7#include "core/file_sys/errors.h"
8#include "core/file_sys/fs_directory.h"
9#include "core/file_sys/fs_file.h"
10#include "core/file_sys/fs_filesystem.h"
11#include "core/file_sys/savedata_factory.h"
12#include "core/file_sys/vfs/vfs.h"
13#include "core/hle/result.h"
14
15namespace FileSys::Fsa {
16
17class IDirectory {
18public:
19 explicit IDirectory(VirtualDir backend_, OpenDirectoryMode mode)
20 : backend(std::move(backend_)) {
21 // TODO(DarkLordZach): Verify that this is the correct behavior.
22 // Build entry index now to save time later.
23 if (True(mode & OpenDirectoryMode::Directory)) {
24 BuildEntryIndex(backend->GetSubdirectories(), DirectoryEntryType::Directory);
25 }
26 if (True(mode & OpenDirectoryMode::File)) {
27 BuildEntryIndex(backend->GetFiles(), DirectoryEntryType::File);
28 }
29 }
30 virtual ~IDirectory() {}
31
32 Result Read(s64* out_count, DirectoryEntry* out_entries, s64 max_entries) {
33 R_UNLESS(out_count != nullptr, ResultNullptrArgument);
34 if (max_entries == 0) {
35 *out_count = 0;
36 R_SUCCEED();
37 }
38 R_UNLESS(out_entries != nullptr, ResultNullptrArgument);
39 R_UNLESS(max_entries > 0, ResultInvalidArgument);
40 R_RETURN(this->DoRead(out_count, out_entries, max_entries));
41 }
42
43 Result GetEntryCount(s64* out) {
44 R_UNLESS(out != nullptr, ResultNullptrArgument);
45 R_RETURN(this->DoGetEntryCount(out));
46 }
47
48private:
49 Result DoRead(s64* out_count, DirectoryEntry* out_entries, s64 max_entries) {
50 const u64 actual_entries =
51 std::min(static_cast<u64>(max_entries), entries.size() - next_entry_index);
52 const auto* begin = reinterpret_cast<u8*>(entries.data() + next_entry_index);
53 const auto* end = reinterpret_cast<u8*>(entries.data() + next_entry_index + actual_entries);
54 const auto range_size = static_cast<std::size_t>(std::distance(begin, end));
55
56 next_entry_index += actual_entries;
57 *out_count = actual_entries;
58
59 std::memcpy(out_entries, begin, range_size);
60
61 R_SUCCEED();
62 }
63
64 Result DoGetEntryCount(s64* out) {
65 *out = entries.size() - next_entry_index;
66 R_SUCCEED();
67 }
68
69 // TODO: Remove this when VFS is gone
70 template <typename T>
71 void BuildEntryIndex(const std::vector<T>& new_data, DirectoryEntryType type) {
72 entries.reserve(entries.size() + new_data.size());
73
74 for (const auto& new_entry : new_data) {
75 auto name = new_entry->GetName();
76
77 if (type == DirectoryEntryType::File && name == GetSaveDataSizeFileName()) {
78 continue;
79 }
80
81 entries.emplace_back(name, static_cast<s8>(type),
82 type == DirectoryEntryType::Directory ? 0 : new_entry->GetSize());
83 }
84 }
85
86 VirtualDir backend;
87 std::vector<DirectoryEntry> entries;
88 u64 next_entry_index = 0;
89};
90
91} // namespace FileSys::Fsa
diff --git a/src/core/file_sys/fsa/fs_i_file.h b/src/core/file_sys/fsa/fs_i_file.h
new file mode 100644
index 000000000..1188ae8ca
--- /dev/null
+++ b/src/core/file_sys/fsa/fs_i_file.h
@@ -0,0 +1,167 @@
1// SPDX-FileCopyrightText: Copyright 2024 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-2.0-or-later
3
4#pragma once
5
6#include "common/overflow.h"
7#include "core/file_sys/errors.h"
8#include "core/file_sys/fs_file.h"
9#include "core/file_sys/fs_filesystem.h"
10#include "core/file_sys/fs_operate_range.h"
11#include "core/file_sys/vfs/vfs.h"
12#include "core/file_sys/vfs/vfs_types.h"
13#include "core/hle/result.h"
14
15namespace FileSys::Fsa {
16
17class IFile {
18public:
19 explicit IFile(VirtualFile backend_) : backend(std::move(backend_)) {}
20 virtual ~IFile() {}
21
22 Result Read(size_t* out, s64 offset, void* buffer, size_t size, const ReadOption& option) {
23 // Check that we have an output pointer
24 R_UNLESS(out != nullptr, ResultNullptrArgument);
25
26 // If we have nothing to read, just succeed
27 if (size == 0) {
28 *out = 0;
29 R_SUCCEED();
30 }
31
32 // Check that the read is valid
33 R_UNLESS(buffer != nullptr, ResultNullptrArgument);
34 R_UNLESS(offset >= 0, ResultOutOfRange);
35 R_UNLESS(Common::CanAddWithoutOverflow<s64>(offset, size), ResultOutOfRange);
36
37 // Do the read
38 R_RETURN(this->DoRead(out, offset, buffer, size, option));
39 }
40
41 Result Read(size_t* out, s64 offset, void* buffer, size_t size) {
42 R_RETURN(this->Read(out, offset, buffer, size, ReadOption::None));
43 }
44
45 Result GetSize(s64* out) {
46 R_UNLESS(out != nullptr, ResultNullptrArgument);
47 R_RETURN(this->DoGetSize(out));
48 }
49
50 Result Flush() {
51 R_RETURN(this->DoFlush());
52 }
53
54 Result Write(s64 offset, const void* buffer, size_t size, const WriteOption& option) {
55 // Handle the zero-size case
56 if (size == 0) {
57 if (option.HasFlushFlag()) {
58 R_TRY(this->Flush());
59 }
60 R_SUCCEED();
61 }
62
63 // Check the write is valid
64 R_UNLESS(buffer != nullptr, ResultNullptrArgument);
65 R_UNLESS(offset >= 0, ResultOutOfRange);
66 R_UNLESS(Common::CanAddWithoutOverflow<s64>(offset, size), ResultOutOfRange);
67
68 R_RETURN(this->DoWrite(offset, buffer, size, option));
69 }
70
71 Result SetSize(s64 size) {
72 R_UNLESS(size >= 0, ResultOutOfRange);
73 R_RETURN(this->DoSetSize(size));
74 }
75
76 Result OperateRange(void* dst, size_t dst_size, OperationId op_id, s64 offset, s64 size,
77 const void* src, size_t src_size) {
78 R_RETURN(this->DoOperateRange(dst, dst_size, op_id, offset, size, src, src_size));
79 }
80
81 Result OperateRange(OperationId op_id, s64 offset, s64 size) {
82 R_RETURN(this->DoOperateRange(nullptr, 0, op_id, offset, size, nullptr, 0));
83 }
84
85protected:
86 Result DryRead(size_t* out, s64 offset, size_t size, const ReadOption& option,
87 OpenMode open_mode) {
88 // Check that we can read
89 R_UNLESS(static_cast<u32>(open_mode & OpenMode::Read) != 0, ResultReadNotPermitted);
90
91 // Get the file size, and validate our offset
92 s64 file_size = 0;
93 R_TRY(this->DoGetSize(std::addressof(file_size)));
94 R_UNLESS(offset <= file_size, ResultOutOfRange);
95
96 *out = static_cast<size_t>(std::min(file_size - offset, static_cast<s64>(size)));
97 R_SUCCEED();
98 }
99
100 Result DrySetSize(s64 size, OpenMode open_mode) {
101 // Check that we can write
102 R_UNLESS(static_cast<u32>(open_mode & OpenMode::Write) != 0, ResultWriteNotPermitted);
103 R_SUCCEED();
104 }
105
106 Result DryWrite(bool* out_append, s64 offset, size_t size, const WriteOption& option,
107 OpenMode open_mode) {
108 // Check that we can write
109 R_UNLESS(static_cast<u32>(open_mode & OpenMode::Write) != 0, ResultWriteNotPermitted);
110
111 // Get the file size
112 s64 file_size = 0;
113 R_TRY(this->DoGetSize(&file_size));
114
115 // Determine if we need to append
116 *out_append = false;
117 if (file_size < offset + static_cast<s64>(size)) {
118 R_UNLESS(static_cast<u32>(open_mode & OpenMode::AllowAppend) != 0,
119 ResultFileExtensionWithoutOpenModeAllowAppend);
120 *out_append = true;
121 }
122
123 R_SUCCEED();
124 }
125
126private:
127 Result DoRead(size_t* out, s64 offset, void* buffer, size_t size, const ReadOption& option) {
128 const auto read_size = backend->Read(static_cast<u8*>(buffer), size, offset);
129 *out = read_size;
130
131 R_SUCCEED();
132 }
133
134 Result DoGetSize(s64* out) {
135 *out = backend->GetSize();
136 R_SUCCEED();
137 }
138
139 Result DoFlush() {
140 // Exists for SDK compatibiltity -- No need to flush file.
141 R_SUCCEED();
142 }
143
144 Result DoWrite(s64 offset, const void* buffer, size_t size, const WriteOption& option) {
145 const std::size_t written = backend->Write(static_cast<const u8*>(buffer), size, offset);
146
147 ASSERT_MSG(written == size,
148 "Could not write all bytes to file (requested={:016X}, actual={:016X}).", size,
149 written);
150
151 R_SUCCEED();
152 }
153
154 Result DoSetSize(s64 size) {
155 backend->Resize(size);
156 R_SUCCEED();
157 }
158
159 Result DoOperateRange(void* dst, size_t dst_size, OperationId op_id, s64 offset, s64 size,
160 const void* src, size_t src_size) {
161 R_THROW(ResultNotImplemented);
162 }
163
164 VirtualFile backend;
165};
166
167} // namespace FileSys::Fsa
diff --git a/src/core/file_sys/fsa/fs_i_filesystem.h b/src/core/file_sys/fsa/fs_i_filesystem.h
new file mode 100644
index 000000000..8172190f4
--- /dev/null
+++ b/src/core/file_sys/fsa/fs_i_filesystem.h
@@ -0,0 +1,206 @@
1// SPDX-FileCopyrightText: Copyright 2024 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-2.0-or-later
3
4#pragma once
5
6#include "core/file_sys/errors.h"
7#include "core/file_sys/fs_filesystem.h"
8#include "core/file_sys/fs_path.h"
9#include "core/file_sys/vfs/vfs_types.h"
10#include "core/hle/result.h"
11#include "core/hle/service/filesystem/filesystem.h"
12
13namespace FileSys::Fsa {
14
15class IFile;
16class IDirectory;
17
18enum class QueryId : u32 {
19 SetConcatenationFileAttribute = 0,
20 UpdateMac = 1,
21 IsSignedSystemPartitionOnSdCardValid = 2,
22 QueryUnpreparedFileInformation = 3,
23};
24
25class IFileSystem {
26public:
27 explicit IFileSystem(VirtualDir backend_) : backend{std::move(backend_)} {}
28 virtual ~IFileSystem() {}
29
30 Result CreateFile(const Path& path, s64 size, CreateOption option) {
31 R_UNLESS(size >= 0, ResultOutOfRange);
32 R_RETURN(this->DoCreateFile(path, size, static_cast<int>(option)));
33 }
34
35 Result CreateFile(const Path& path, s64 size) {
36 R_RETURN(this->CreateFile(path, size, CreateOption::None));
37 }
38
39 Result DeleteFile(const Path& path) {
40 R_RETURN(this->DoDeleteFile(path));
41 }
42
43 Result CreateDirectory(const Path& path) {
44 R_RETURN(this->DoCreateDirectory(path));
45 }
46
47 Result DeleteDirectory(const Path& path) {
48 R_RETURN(this->DoDeleteDirectory(path));
49 }
50
51 Result DeleteDirectoryRecursively(const Path& path) {
52 R_RETURN(this->DoDeleteDirectoryRecursively(path));
53 }
54
55 Result RenameFile(const Path& old_path, const Path& new_path) {
56 R_RETURN(this->DoRenameFile(old_path, new_path));
57 }
58
59 Result RenameDirectory(const Path& old_path, const Path& new_path) {
60 R_RETURN(this->DoRenameDirectory(old_path, new_path));
61 }
62
63 Result GetEntryType(DirectoryEntryType* out, const Path& path) {
64 R_RETURN(this->DoGetEntryType(out, path));
65 }
66
67 Result OpenFile(VirtualFile* out_file, const Path& path, OpenMode mode) {
68 R_UNLESS(out_file != nullptr, ResultNullptrArgument);
69 R_UNLESS(static_cast<u32>(mode & OpenMode::ReadWrite) != 0, ResultInvalidOpenMode);
70 R_UNLESS(static_cast<u32>(mode & ~OpenMode::All) == 0, ResultInvalidOpenMode);
71 R_RETURN(this->DoOpenFile(out_file, path, mode));
72 }
73
74 Result OpenDirectory(VirtualDir* out_dir, const Path& path, OpenDirectoryMode mode) {
75 R_UNLESS(out_dir != nullptr, ResultNullptrArgument);
76 R_UNLESS(static_cast<u64>(mode & OpenDirectoryMode::All) != 0, ResultInvalidOpenMode);
77 R_UNLESS(static_cast<u64>(
78 mode & ~(OpenDirectoryMode::All | OpenDirectoryMode::NotRequireFileSize)) == 0,
79 ResultInvalidOpenMode);
80 R_RETURN(this->DoOpenDirectory(out_dir, path, mode));
81 }
82
83 Result Commit() {
84 R_RETURN(this->DoCommit());
85 }
86
87 Result GetFreeSpaceSize(s64* out, const Path& path) {
88 R_UNLESS(out != nullptr, ResultNullptrArgument);
89 R_RETURN(this->DoGetFreeSpaceSize(out, path));
90 }
91
92 Result GetTotalSpaceSize(s64* out, const Path& path) {
93 R_UNLESS(out != nullptr, ResultNullptrArgument);
94 R_RETURN(this->DoGetTotalSpaceSize(out, path));
95 }
96
97 Result CleanDirectoryRecursively(const Path& path) {
98 R_RETURN(this->DoCleanDirectoryRecursively(path));
99 }
100
101 Result GetFileTimeStampRaw(FileTimeStampRaw* out, const Path& path) {
102 R_UNLESS(out != nullptr, ResultNullptrArgument);
103 R_RETURN(this->DoGetFileTimeStampRaw(out, path));
104 }
105
106 Result QueryEntry(char* dst, size_t dst_size, const char* src, size_t src_size, QueryId query,
107 const Path& path) {
108 R_RETURN(this->DoQueryEntry(dst, dst_size, src, src_size, query, path));
109 }
110
111 // These aren't accessible as commands
112 Result CommitProvisionally(s64 counter) {
113 R_RETURN(this->DoCommitProvisionally(counter));
114 }
115
116 Result Rollback() {
117 R_RETURN(this->DoRollback());
118 }
119
120 Result Flush() {
121 R_RETURN(this->DoFlush());
122 }
123
124private:
125 Result DoCreateFile(const Path& path, s64 size, int flags) {
126 R_RETURN(backend.CreateFile(path.GetString(), size));
127 }
128
129 Result DoDeleteFile(const Path& path) {
130 R_RETURN(backend.DeleteFile(path.GetString()));
131 }
132
133 Result DoCreateDirectory(const Path& path) {
134 R_RETURN(backend.CreateDirectory(path.GetString()));
135 }
136
137 Result DoDeleteDirectory(const Path& path) {
138 R_RETURN(backend.DeleteDirectory(path.GetString()));
139 }
140
141 Result DoDeleteDirectoryRecursively(const Path& path) {
142 R_RETURN(backend.DeleteDirectoryRecursively(path.GetString()));
143 }
144
145 Result DoRenameFile(const Path& old_path, const Path& new_path) {
146 R_RETURN(backend.RenameFile(old_path.GetString(), new_path.GetString()));
147 }
148
149 Result DoRenameDirectory(const Path& old_path, const Path& new_path) {
150 R_RETURN(backend.RenameDirectory(old_path.GetString(), new_path.GetString()));
151 }
152
153 Result DoGetEntryType(DirectoryEntryType* out, const Path& path) {
154 R_RETURN(backend.GetEntryType(out, path.GetString()));
155 }
156
157 Result DoOpenFile(VirtualFile* out_file, const Path& path, OpenMode mode) {
158 R_RETURN(backend.OpenFile(out_file, path.GetString(), mode));
159 }
160
161 Result DoOpenDirectory(VirtualDir* out_directory, const Path& path, OpenDirectoryMode mode) {
162 R_RETURN(backend.OpenDirectory(out_directory, path.GetString()));
163 }
164
165 Result DoCommit() {
166 R_THROW(ResultNotImplemented);
167 }
168
169 Result DoGetFreeSpaceSize(s64* out, const Path& path) {
170 R_THROW(ResultNotImplemented);
171 }
172
173 Result DoGetTotalSpaceSize(s64* out, const Path& path) {
174 R_THROW(ResultNotImplemented);
175 }
176
177 Result DoCleanDirectoryRecursively(const Path& path) {
178 R_RETURN(backend.CleanDirectoryRecursively(path.GetString()));
179 }
180
181 Result DoGetFileTimeStampRaw(FileTimeStampRaw* out, const Path& path) {
182 R_RETURN(backend.GetFileTimeStampRaw(out, path.GetString()));
183 }
184
185 Result DoQueryEntry(char* dst, size_t dst_size, const char* src, size_t src_size, QueryId query,
186 const Path& path) {
187 R_THROW(ResultNotImplemented);
188 }
189
190 // These aren't accessible as commands
191 Result DoCommitProvisionally(s64 counter) {
192 R_THROW(ResultNotImplemented);
193 }
194
195 Result DoRollback() {
196 R_THROW(ResultNotImplemented);
197 }
198
199 Result DoFlush() {
200 R_THROW(ResultNotImplemented);
201 }
202
203 Service::FileSystem::VfsDirectoryServiceWrapper backend;
204};
205
206} // namespace FileSys::Fsa
diff --git a/src/core/file_sys/fssrv/fssrv_sf_path.h b/src/core/file_sys/fssrv/fssrv_sf_path.h
new file mode 100644
index 000000000..a0c0b2dac
--- /dev/null
+++ b/src/core/file_sys/fssrv/fssrv_sf_path.h
@@ -0,0 +1,36 @@
1// SPDX-FileCopyrightText: Copyright 2024 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-2.0-or-later
3
4#pragma once
5
6#include "core/file_sys/fs_directory.h"
7
8namespace FileSys::Sf {
9
10struct Path {
11 char str[EntryNameLengthMax + 1];
12
13 static constexpr Path Encode(const char* p) {
14 Path path = {};
15 for (size_t i = 0; i < sizeof(path) - 1; i++) {
16 path.str[i] = p[i];
17 if (p[i] == '\x00') {
18 break;
19 }
20 }
21 return path;
22 }
23
24 static constexpr size_t GetPathLength(const Path& path) {
25 size_t len = 0;
26 for (size_t i = 0; i < sizeof(path) - 1 && path.str[i] != '\x00'; i++) {
27 len++;
28 }
29 return len;
30 }
31};
32static_assert(std::is_trivially_copyable_v<Path>, "Path must be trivially copyable.");
33
34using FspPath = Path;
35
36} // namespace FileSys::Sf
diff --git a/src/core/file_sys/fssystem/fssystem_aes_xts_storage.h b/src/core/file_sys/fssystem/fssystem_aes_xts_storage.h
index f342efb57..0e83ca1b9 100644
--- a/src/core/file_sys/fssystem/fssystem_aes_xts_storage.h
+++ b/src/core/file_sys/fssystem/fssystem_aes_xts_storage.h
@@ -3,6 +3,7 @@
3 3
4#pragma once 4#pragma once
5 5
6#include <mutex>
6#include <optional> 7#include <optional>
7 8
8#include "core/crypto/aes_util.h" 9#include "core/crypto/aes_util.h"
diff --git a/src/core/hle/service/btm/btm.cpp b/src/core/hle/service/btm/btm.cpp
index 2dc23e674..d120dade8 100644
--- a/src/core/hle/service/btm/btm.cpp
+++ b/src/core/hle/service/btm/btm.cpp
@@ -3,141 +3,18 @@
3 3
4#include <memory> 4#include <memory>
5 5
6#include "common/logging/log.h"
7#include "core/core.h"
8#include "core/hle/kernel/k_event.h"
9#include "core/hle/service/btm/btm.h" 6#include "core/hle/service/btm/btm.h"
10#include "core/hle/service/ipc_helpers.h" 7#include "core/hle/service/btm/btm_debug.h"
11#include "core/hle/service/kernel_helpers.h" 8#include "core/hle/service/btm/btm_system.h"
9#include "core/hle/service/btm/btm_user.h"
12#include "core/hle/service/server_manager.h" 10#include "core/hle/service/server_manager.h"
13#include "core/hle/service/service.h" 11#include "core/hle/service/service.h"
14 12
15namespace Service::BTM { 13namespace Service::BTM {
16 14
17class IBtmUserCore final : public ServiceFramework<IBtmUserCore> { 15class IBtm final : public ServiceFramework<IBtm> {
18public: 16public:
19 explicit IBtmUserCore(Core::System& system_) 17 explicit IBtm(Core::System& system_) : ServiceFramework{system_, "btm"} {
20 : ServiceFramework{system_, "IBtmUserCore"}, service_context{system_, "IBtmUserCore"} {
21 // clang-format off
22 static const FunctionInfo functions[] = {
23 {0, &IBtmUserCore::AcquireBleScanEvent, "AcquireBleScanEvent"},
24 {1, nullptr, "GetBleScanFilterParameter"},
25 {2, nullptr, "GetBleScanFilterParameter2"},
26 {3, nullptr, "StartBleScanForGeneral"},
27 {4, nullptr, "StopBleScanForGeneral"},
28 {5, nullptr, "GetBleScanResultsForGeneral"},
29 {6, nullptr, "StartBleScanForPaired"},
30 {7, nullptr, "StopBleScanForPaired"},
31 {8, nullptr, "StartBleScanForSmartDevice"},
32 {9, nullptr, "StopBleScanForSmartDevice"},
33 {10, nullptr, "GetBleScanResultsForSmartDevice"},
34 {17, &IBtmUserCore::AcquireBleConnectionEvent, "AcquireBleConnectionEvent"},
35 {18, nullptr, "BleConnect"},
36 {19, nullptr, "BleDisconnect"},
37 {20, nullptr, "BleGetConnectionState"},
38 {21, nullptr, "AcquireBlePairingEvent"},
39 {22, nullptr, "BlePairDevice"},
40 {23, nullptr, "BleUnPairDevice"},
41 {24, nullptr, "BleUnPairDevice2"},
42 {25, nullptr, "BleGetPairedDevices"},
43 {26, &IBtmUserCore::AcquireBleServiceDiscoveryEvent, "AcquireBleServiceDiscoveryEvent"},
44 {27, nullptr, "GetGattServices"},
45 {28, nullptr, "GetGattService"},
46 {29, nullptr, "GetGattIncludedServices"},
47 {30, nullptr, "GetBelongingGattService"},
48 {31, nullptr, "GetGattCharacteristics"},
49 {32, nullptr, "GetGattDescriptors"},
50 {33, &IBtmUserCore::AcquireBleMtuConfigEvent, "AcquireBleMtuConfigEvent"},
51 {34, nullptr, "ConfigureBleMtu"},
52 {35, nullptr, "GetBleMtu"},
53 {36, nullptr, "RegisterBleGattDataPath"},
54 {37, nullptr, "UnregisterBleGattDataPath"},
55 };
56 // clang-format on
57 RegisterHandlers(functions);
58
59 scan_event = service_context.CreateEvent("IBtmUserCore:ScanEvent");
60 connection_event = service_context.CreateEvent("IBtmUserCore:ConnectionEvent");
61 service_discovery_event = service_context.CreateEvent("IBtmUserCore:DiscoveryEvent");
62 config_event = service_context.CreateEvent("IBtmUserCore:ConfigEvent");
63 }
64
65 ~IBtmUserCore() override {
66 service_context.CloseEvent(scan_event);
67 service_context.CloseEvent(connection_event);
68 service_context.CloseEvent(service_discovery_event);
69 service_context.CloseEvent(config_event);
70 }
71
72private:
73 void AcquireBleScanEvent(HLERequestContext& ctx) {
74 LOG_WARNING(Service_BTM, "(STUBBED) called");
75
76 IPC::ResponseBuilder rb{ctx, 3, 1};
77 rb.Push(ResultSuccess);
78 rb.Push(true);
79 rb.PushCopyObjects(scan_event->GetReadableEvent());
80 }
81
82 void AcquireBleConnectionEvent(HLERequestContext& ctx) {
83 LOG_WARNING(Service_BTM, "(STUBBED) called");
84
85 IPC::ResponseBuilder rb{ctx, 3, 1};
86 rb.Push(ResultSuccess);
87 rb.Push(true);
88 rb.PushCopyObjects(connection_event->GetReadableEvent());
89 }
90
91 void AcquireBleServiceDiscoveryEvent(HLERequestContext& ctx) {
92 LOG_WARNING(Service_BTM, "(STUBBED) called");
93
94 IPC::ResponseBuilder rb{ctx, 3, 1};
95 rb.Push(ResultSuccess);
96 rb.Push(true);
97 rb.PushCopyObjects(service_discovery_event->GetReadableEvent());
98 }
99
100 void AcquireBleMtuConfigEvent(HLERequestContext& ctx) {
101 LOG_WARNING(Service_BTM, "(STUBBED) called");
102
103 IPC::ResponseBuilder rb{ctx, 3, 1};
104 rb.Push(ResultSuccess);
105 rb.Push(true);
106 rb.PushCopyObjects(config_event->GetReadableEvent());
107 }
108
109 KernelHelpers::ServiceContext service_context;
110
111 Kernel::KEvent* scan_event;
112 Kernel::KEvent* connection_event;
113 Kernel::KEvent* service_discovery_event;
114 Kernel::KEvent* config_event;
115};
116
117class BTM_USR final : public ServiceFramework<BTM_USR> {
118public:
119 explicit BTM_USR(Core::System& system_) : ServiceFramework{system_, "btm:u"} {
120 // clang-format off
121 static const FunctionInfo functions[] = {
122 {0, &BTM_USR::GetCore, "GetCore"},
123 };
124 // clang-format on
125 RegisterHandlers(functions);
126 }
127
128private:
129 void GetCore(HLERequestContext& ctx) {
130 LOG_WARNING(Service_BTM, "called");
131
132 IPC::ResponseBuilder rb{ctx, 2, 0, 1};
133 rb.Push(ResultSuccess);
134 rb.PushIpcInterface<IBtmUserCore>(system);
135 }
136};
137
138class BTM final : public ServiceFramework<BTM> {
139public:
140 explicit BTM(Core::System& system_) : ServiceFramework{system_, "btm"} {
141 // clang-format off 18 // clang-format off
142 static const FunctionInfo functions[] = { 19 static const FunctionInfo functions[] = {
143 {0, nullptr, "GetState"}, 20 {0, nullptr, "GetState"},
@@ -232,144 +109,13 @@ public:
232 } 109 }
233}; 110};
234 111
235class BTM_DBG final : public ServiceFramework<BTM_DBG> {
236public:
237 explicit BTM_DBG(Core::System& system_) : ServiceFramework{system_, "btm:dbg"} {
238 // clang-format off
239 static const FunctionInfo functions[] = {
240 {0, nullptr, "AcquireDiscoveryEvent"},
241 {1, nullptr, "StartDiscovery"},
242 {2, nullptr, "CancelDiscovery"},
243 {3, nullptr, "GetDeviceProperty"},
244 {4, nullptr, "CreateBond"},
245 {5, nullptr, "CancelBond"},
246 {6, nullptr, "SetTsiMode"},
247 {7, nullptr, "GeneralTest"},
248 {8, nullptr, "HidConnect"},
249 {9, nullptr, "GeneralGet"},
250 {10, nullptr, "GetGattClientDisconnectionReason"},
251 {11, nullptr, "GetBleConnectionParameter"},
252 {12, nullptr, "GetBleConnectionParameterRequest"},
253 {13, nullptr, "Unknown13"},
254 };
255 // clang-format on
256
257 RegisterHandlers(functions);
258 }
259};
260
261class IBtmSystemCore final : public ServiceFramework<IBtmSystemCore> {
262public:
263 explicit IBtmSystemCore(Core::System& system_) : ServiceFramework{system_, "IBtmSystemCore"} {
264 // clang-format off
265 static const FunctionInfo functions[] = {
266 {0, &IBtmSystemCore::StartGamepadPairing, "StartGamepadPairing"},
267 {1, &IBtmSystemCore::CancelGamepadPairing, "CancelGamepadPairing"},
268 {2, nullptr, "ClearGamepadPairingDatabase"},
269 {3, nullptr, "GetPairedGamepadCount"},
270 {4, nullptr, "EnableRadio"},
271 {5, nullptr, "DisableRadio"},
272 {6, &IBtmSystemCore::IsRadioEnabled, "IsRadioEnabled"},
273 {7, nullptr, "AcquireRadioEvent"},
274 {8, nullptr, "AcquireGamepadPairingEvent"},
275 {9, nullptr, "IsGamepadPairingStarted"},
276 {10, nullptr, "StartAudioDeviceDiscovery"},
277 {11, nullptr, "StopAudioDeviceDiscovery"},
278 {12, nullptr, "IsDiscoveryingAudioDevice"},
279 {13, nullptr, "GetDiscoveredAudioDevice"},
280 {14, nullptr, "AcquireAudioDeviceConnectionEvent"},
281 {15, nullptr, "ConnectAudioDevice"},
282 {16, nullptr, "IsConnectingAudioDevice"},
283 {17, &IBtmSystemCore::GetConnectedAudioDevices, "GetConnectedAudioDevices"},
284 {18, nullptr, "DisconnectAudioDevice"},
285 {19, nullptr, "AcquirePairedAudioDeviceInfoChangedEvent"},
286 {20, &IBtmSystemCore::GetPairedAudioDevices, "GetPairedAudioDevices"},
287 {21, nullptr, "RemoveAudioDevicePairing"},
288 {22, &IBtmSystemCore::RequestAudioDeviceConnectionRejection, "RequestAudioDeviceConnectionRejection"},
289 {23, &IBtmSystemCore::CancelAudioDeviceConnectionRejection, "CancelAudioDeviceConnectionRejection"}
290 };
291 // clang-format on
292
293 RegisterHandlers(functions);
294 }
295
296private:
297 void IsRadioEnabled(HLERequestContext& ctx) {
298 LOG_DEBUG(Service_BTM, "(STUBBED) called"); // Spams a lot when controller applet is running
299
300 IPC::ResponseBuilder rb{ctx, 3};
301 rb.Push(ResultSuccess);
302 rb.Push(true);
303 }
304
305 void StartGamepadPairing(HLERequestContext& ctx) {
306 LOG_WARNING(Service_BTM, "(STUBBED) called");
307 IPC::ResponseBuilder rb{ctx, 2};
308 rb.Push(ResultSuccess);
309 }
310
311 void CancelGamepadPairing(HLERequestContext& ctx) {
312 LOG_WARNING(Service_BTM, "(STUBBED) called");
313 IPC::ResponseBuilder rb{ctx, 2};
314 rb.Push(ResultSuccess);
315 }
316
317 void CancelAudioDeviceConnectionRejection(HLERequestContext& ctx) {
318 LOG_WARNING(Service_BTM, "(STUBBED) called");
319 IPC::ResponseBuilder rb{ctx, 2};
320 rb.Push(ResultSuccess);
321 }
322
323 void GetConnectedAudioDevices(HLERequestContext& ctx) {
324 LOG_WARNING(Service_BTM, "(STUBBED) called");
325 IPC::ResponseBuilder rb{ctx, 3};
326 rb.Push(ResultSuccess);
327 rb.Push<u32>(0);
328 }
329
330 void GetPairedAudioDevices(HLERequestContext& ctx) {
331 LOG_WARNING(Service_BTM, "(STUBBED) called");
332 IPC::ResponseBuilder rb{ctx, 3};
333 rb.Push(ResultSuccess);
334 rb.Push<u32>(0);
335 }
336
337 void RequestAudioDeviceConnectionRejection(HLERequestContext& ctx) {
338 LOG_WARNING(Service_BTM, "(STUBBED) called");
339 IPC::ResponseBuilder rb{ctx, 2};
340 rb.Push(ResultSuccess);
341 }
342};
343
344class BTM_SYS final : public ServiceFramework<BTM_SYS> {
345public:
346 explicit BTM_SYS(Core::System& system_) : ServiceFramework{system_, "btm:sys"} {
347 // clang-format off
348 static const FunctionInfo functions[] = {
349 {0, &BTM_SYS::GetCore, "GetCore"},
350 };
351 // clang-format on
352
353 RegisterHandlers(functions);
354 }
355
356private:
357 void GetCore(HLERequestContext& ctx) {
358 LOG_WARNING(Service_BTM, "called");
359
360 IPC::ResponseBuilder rb{ctx, 2, 0, 1};
361 rb.Push(ResultSuccess);
362 rb.PushIpcInterface<IBtmSystemCore>(system);
363 }
364};
365
366void LoopProcess(Core::System& system) { 112void LoopProcess(Core::System& system) {
367 auto server_manager = std::make_unique<ServerManager>(system); 113 auto server_manager = std::make_unique<ServerManager>(system);
368 114
369 server_manager->RegisterNamedService("btm", std::make_shared<BTM>(system)); 115 server_manager->RegisterNamedService("btm", std::make_shared<IBtm>(system));
370 server_manager->RegisterNamedService("btm:dbg", std::make_shared<BTM_DBG>(system)); 116 server_manager->RegisterNamedService("btm:dbg", std::make_shared<IBtmDebug>(system));
371 server_manager->RegisterNamedService("btm:sys", std::make_shared<BTM_SYS>(system)); 117 server_manager->RegisterNamedService("btm:sys", std::make_shared<IBtmSystem>(system));
372 server_manager->RegisterNamedService("btm:u", std::make_shared<BTM_USR>(system)); 118 server_manager->RegisterNamedService("btm:u", std::make_shared<IBtmUser>(system));
373 ServerManager::RunServer(std::move(server_manager)); 119 ServerManager::RunServer(std::move(server_manager));
374} 120}
375 121
diff --git a/src/core/hle/service/btm/btm.h b/src/core/hle/service/btm/btm.h
index a99b34364..0bf77d053 100644
--- a/src/core/hle/service/btm/btm.h
+++ b/src/core/hle/service/btm/btm.h
@@ -3,10 +3,6 @@
3 3
4#pragma once 4#pragma once
5 5
6namespace Service::SM {
7class ServiceManager;
8}
9
10namespace Core { 6namespace Core {
11class System; 7class System;
12}; 8};
diff --git a/src/core/hle/service/btm/btm_debug.cpp b/src/core/hle/service/btm/btm_debug.cpp
new file mode 100644
index 000000000..4d61d2641
--- /dev/null
+++ b/src/core/hle/service/btm/btm_debug.cpp
@@ -0,0 +1,33 @@
1// SPDX-FileCopyrightText: Copyright 2024 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-3.0-or-later
3
4#include "core/hle/service/btm/btm_debug.h"
5
6namespace Service::BTM {
7
8IBtmDebug::IBtmDebug(Core::System& system_) : ServiceFramework{system_, "btm:dbg"} {
9 // clang-format off
10 static const FunctionInfo functions[] = {
11 {0, nullptr, "AcquireDiscoveryEvent"},
12 {1, nullptr, "StartDiscovery"},
13 {2, nullptr, "CancelDiscovery"},
14 {3, nullptr, "GetDeviceProperty"},
15 {4, nullptr, "CreateBond"},
16 {5, nullptr, "CancelBond"},
17 {6, nullptr, "SetTsiMode"},
18 {7, nullptr, "GeneralTest"},
19 {8, nullptr, "HidConnect"},
20 {9, nullptr, "GeneralGet"},
21 {10, nullptr, "GetGattClientDisconnectionReason"},
22 {11, nullptr, "GetBleConnectionParameter"},
23 {12, nullptr, "GetBleConnectionParameterRequest"},
24 {13, nullptr, "Unknown13"},
25 };
26 // clang-format on
27
28 RegisterHandlers(functions);
29}
30
31IBtmDebug::~IBtmDebug() = default;
32
33} // namespace Service::BTM
diff --git a/src/core/hle/service/btm/btm_debug.h b/src/core/hle/service/btm/btm_debug.h
new file mode 100644
index 000000000..bf4f7e14f
--- /dev/null
+++ b/src/core/hle/service/btm/btm_debug.h
@@ -0,0 +1,21 @@
1// SPDX-FileCopyrightText: Copyright 2024 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-3.0-or-later
3
4#pragma once
5
6#include "core/hle/service/cmif_types.h"
7#include "core/hle/service/service.h"
8
9namespace Core {
10class System;
11}
12
13namespace Service::BTM {
14
15class IBtmDebug final : public ServiceFramework<IBtmDebug> {
16public:
17 explicit IBtmDebug(Core::System& system_);
18 ~IBtmDebug() override;
19};
20
21} // namespace Service::BTM
diff --git a/src/core/hle/service/btm/btm_system.cpp b/src/core/hle/service/btm/btm_system.cpp
new file mode 100644
index 000000000..99718a7b0
--- /dev/null
+++ b/src/core/hle/service/btm/btm_system.cpp
@@ -0,0 +1,31 @@
1// SPDX-FileCopyrightText: Copyright 2024 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-3.0-or-later
3
4#include "common/logging/log.h"
5#include "core/hle/service/btm/btm_system.h"
6#include "core/hle/service/btm/btm_system_core.h"
7#include "core/hle/service/cmif_serialization.h"
8#include "core/hle/service/service.h"
9
10namespace Service::BTM {
11
12IBtmSystem::IBtmSystem(Core::System& system_) : ServiceFramework{system_, "btm:sys"} {
13 // clang-format off
14 static const FunctionInfo functions[] = {
15 {0, C<&IBtmSystem::GetCore>, "GetCore"},
16 };
17 // clang-format on
18
19 RegisterHandlers(functions);
20}
21
22IBtmSystem::~IBtmSystem() = default;
23
24Result IBtmSystem::GetCore(OutInterface<IBtmSystemCore> out_interface) {
25 LOG_WARNING(Service_BTM, "called");
26
27 *out_interface = std::make_shared<IBtmSystemCore>(system);
28 R_SUCCEED();
29}
30
31} // namespace Service::BTM
diff --git a/src/core/hle/service/btm/btm_system.h b/src/core/hle/service/btm/btm_system.h
new file mode 100644
index 000000000..fe1c6dbd7
--- /dev/null
+++ b/src/core/hle/service/btm/btm_system.h
@@ -0,0 +1,25 @@
1// SPDX-FileCopyrightText: Copyright 2024 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-3.0-or-later
3
4#pragma once
5
6#include "core/hle/service/cmif_types.h"
7#include "core/hle/service/service.h"
8
9namespace Core {
10class System;
11}
12
13namespace Service::BTM {
14class IBtmSystemCore;
15
16class IBtmSystem final : public ServiceFramework<IBtmSystem> {
17public:
18 explicit IBtmSystem(Core::System& system_);
19 ~IBtmSystem() override;
20
21private:
22 Result GetCore(OutInterface<IBtmSystemCore> out_interface);
23};
24
25} // namespace Service::BTM
diff --git a/src/core/hle/service/btm/btm_system_core.cpp b/src/core/hle/service/btm/btm_system_core.cpp
new file mode 100644
index 000000000..4bc8a9e8b
--- /dev/null
+++ b/src/core/hle/service/btm/btm_system_core.cpp
@@ -0,0 +1,127 @@
1// SPDX-FileCopyrightText: Copyright 2024 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-3.0-or-later
3
4#include "common/logging/log.h"
5#include "core/hle/service/btm/btm_system_core.h"
6#include "core/hle/service/cmif_serialization.h"
7#include "core/hle/service/set/system_settings_server.h"
8#include "core/hle/service/sm/sm.h"
9
10namespace Service::BTM {
11
12IBtmSystemCore::IBtmSystemCore(Core::System& system_)
13 : ServiceFramework{system_, "IBtmSystemCore"}, service_context{system_, "IBtmSystemCore"} {
14 // clang-format off
15 static const FunctionInfo functions[] = {
16 {0, C<&IBtmSystemCore::StartGamepadPairing>, "StartGamepadPairing"},
17 {1, C<&IBtmSystemCore::CancelGamepadPairing>, "CancelGamepadPairing"},
18 {2, nullptr, "ClearGamepadPairingDatabase"},
19 {3, nullptr, "GetPairedGamepadCount"},
20 {4, C<&IBtmSystemCore::EnableRadio>, "EnableRadio"},
21 {5, C<&IBtmSystemCore::DisableRadio>, "DisableRadio"},
22 {6, C<&IBtmSystemCore::IsRadioEnabled>, "IsRadioEnabled"},
23 {7, C<&IBtmSystemCore::AcquireRadioEvent>, "AcquireRadioEvent"},
24 {8, nullptr, "AcquireGamepadPairingEvent"},
25 {9, nullptr, "IsGamepadPairingStarted"},
26 {10, nullptr, "StartAudioDeviceDiscovery"},
27 {11, nullptr, "StopAudioDeviceDiscovery"},
28 {12, nullptr, "IsDiscoveryingAudioDevice"},
29 {13, nullptr, "GetDiscoveredAudioDevice"},
30 {14, C<&IBtmSystemCore::AcquireAudioDeviceConnectionEvent>, "AcquireAudioDeviceConnectionEvent"},
31 {15, nullptr, "ConnectAudioDevice"},
32 {16, nullptr, "IsConnectingAudioDevice"},
33 {17, C<&IBtmSystemCore::GetConnectedAudioDevices>, "GetConnectedAudioDevices"},
34 {18, nullptr, "DisconnectAudioDevice"},
35 {19, nullptr, "AcquirePairedAudioDeviceInfoChangedEvent"},
36 {20, C<&IBtmSystemCore::GetPairedAudioDevices>, "GetPairedAudioDevices"},
37 {21, nullptr, "RemoveAudioDevicePairing"},
38 {22, C<&IBtmSystemCore::RequestAudioDeviceConnectionRejection>, "RequestAudioDeviceConnectionRejection"},
39 {23, C<&IBtmSystemCore::CancelAudioDeviceConnectionRejection>, "CancelAudioDeviceConnectionRejection"}
40 };
41 // clang-format on
42
43 RegisterHandlers(functions);
44 radio_event = service_context.CreateEvent("IBtmSystemCore::RadioEvent");
45 audio_device_connection_event =
46 service_context.CreateEvent("IBtmSystemCore::AudioDeviceConnectionEvent");
47
48 m_set_sys =
49 system.ServiceManager().GetService<Service::Set::ISystemSettingsServer>("set:sys", true);
50}
51
52IBtmSystemCore::~IBtmSystemCore() {
53 service_context.CloseEvent(radio_event);
54 service_context.CloseEvent(audio_device_connection_event);
55}
56
57Result IBtmSystemCore::StartGamepadPairing() {
58 LOG_WARNING(Service_BTM, "(STUBBED) called");
59 R_SUCCEED();
60}
61
62Result IBtmSystemCore::CancelGamepadPairing() {
63 LOG_WARNING(Service_BTM, "(STUBBED) called");
64 R_SUCCEED();
65}
66
67Result IBtmSystemCore::EnableRadio() {
68 LOG_DEBUG(Service_BTM, "called");
69
70 R_RETURN(m_set_sys->SetBluetoothEnableFlag(true));
71}
72Result IBtmSystemCore::DisableRadio() {
73 LOG_DEBUG(Service_BTM, "called");
74
75 R_RETURN(m_set_sys->SetBluetoothEnableFlag(false));
76}
77
78Result IBtmSystemCore::IsRadioEnabled(Out<bool> out_is_enabled) {
79 LOG_DEBUG(Service_BTM, "called");
80
81 R_RETURN(m_set_sys->GetBluetoothEnableFlag(out_is_enabled));
82}
83
84Result IBtmSystemCore::AcquireRadioEvent(Out<bool> out_is_valid,
85 OutCopyHandle<Kernel::KReadableEvent> out_event) {
86 LOG_WARNING(Service_BTM, "(STUBBED) called");
87
88 *out_is_valid = true;
89 *out_event = &radio_event->GetReadableEvent();
90 R_SUCCEED();
91}
92
93Result IBtmSystemCore::AcquireAudioDeviceConnectionEvent(
94 OutCopyHandle<Kernel::KReadableEvent> out_event) {
95 LOG_WARNING(Service_BTM, "(STUBBED) called");
96
97 *out_event = &audio_device_connection_event->GetReadableEvent();
98 R_SUCCEED();
99}
100
101Result IBtmSystemCore::GetConnectedAudioDevices(
102 Out<s32> out_count, OutArray<std::array<u8, 0xFF>, BufferAttr_HipcPointer> out_audio_devices) {
103 LOG_WARNING(Service_BTM, "(STUBBED) called");
104
105 *out_count = 0;
106 R_SUCCEED();
107}
108
109Result IBtmSystemCore::GetPairedAudioDevices(
110 Out<s32> out_count, OutArray<std::array<u8, 0xFF>, BufferAttr_HipcPointer> out_audio_devices) {
111 LOG_WARNING(Service_BTM, "(STUBBED) called");
112
113 *out_count = 0;
114 R_SUCCEED();
115}
116
117Result IBtmSystemCore::RequestAudioDeviceConnectionRejection(ClientAppletResourceUserId aruid) {
118 LOG_WARNING(Service_BTM, "(STUBBED) called, applet_resource_user_id={}", aruid.pid);
119 R_SUCCEED();
120}
121
122Result IBtmSystemCore::CancelAudioDeviceConnectionRejection(ClientAppletResourceUserId aruid) {
123 LOG_WARNING(Service_BTM, "(STUBBED) called, applet_resource_user_id={}", aruid.pid);
124 R_SUCCEED();
125}
126
127} // namespace Service::BTM
diff --git a/src/core/hle/service/btm/btm_system_core.h b/src/core/hle/service/btm/btm_system_core.h
new file mode 100644
index 000000000..06498b21e
--- /dev/null
+++ b/src/core/hle/service/btm/btm_system_core.h
@@ -0,0 +1,60 @@
1// SPDX-FileCopyrightText: Copyright 2024 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-3.0-or-later
3
4#pragma once
5
6#include "core/hle/service/cmif_types.h"
7#include "core/hle/service/kernel_helpers.h"
8#include "core/hle/service/service.h"
9
10namespace Kernel {
11class KEvent;
12class KReadableEvent;
13} // namespace Kernel
14
15namespace Core {
16class System;
17}
18
19namespace Service::Set {
20class ISystemSettingsServer;
21}
22
23namespace Service::BTM {
24
25class IBtmSystemCore final : public ServiceFramework<IBtmSystemCore> {
26public:
27 explicit IBtmSystemCore(Core::System& system_);
28 ~IBtmSystemCore() override;
29
30private:
31 Result StartGamepadPairing();
32 Result CancelGamepadPairing();
33 Result EnableRadio();
34 Result DisableRadio();
35 Result IsRadioEnabled(Out<bool> out_is_enabled);
36
37 Result AcquireRadioEvent(Out<bool> out_is_valid,
38 OutCopyHandle<Kernel::KReadableEvent> out_event);
39
40 Result AcquireAudioDeviceConnectionEvent(OutCopyHandle<Kernel::KReadableEvent> out_event);
41
42 Result GetConnectedAudioDevices(
43 Out<s32> out_count,
44 OutArray<std::array<u8, 0xFF>, BufferAttr_HipcPointer> out_audio_devices);
45
46 Result GetPairedAudioDevices(
47 Out<s32> out_count,
48 OutArray<std::array<u8, 0xFF>, BufferAttr_HipcPointer> out_audio_devices);
49
50 Result RequestAudioDeviceConnectionRejection(ClientAppletResourceUserId aruid);
51 Result CancelAudioDeviceConnectionRejection(ClientAppletResourceUserId aruid);
52
53 KernelHelpers::ServiceContext service_context;
54
55 Kernel::KEvent* radio_event;
56 Kernel::KEvent* audio_device_connection_event;
57 std::shared_ptr<Service::Set::ISystemSettingsServer> m_set_sys;
58};
59
60} // namespace Service::BTM
diff --git a/src/core/hle/service/btm/btm_user.cpp b/src/core/hle/service/btm/btm_user.cpp
new file mode 100644
index 000000000..d2e228f8d
--- /dev/null
+++ b/src/core/hle/service/btm/btm_user.cpp
@@ -0,0 +1,30 @@
1// SPDX-FileCopyrightText: Copyright 2024 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-3.0-or-later
3
4#include "common/logging/log.h"
5#include "core/hle/service/btm/btm_user.h"
6#include "core/hle/service/btm/btm_user_core.h"
7#include "core/hle/service/cmif_serialization.h"
8
9namespace Service::BTM {
10
11IBtmUser::IBtmUser(Core::System& system_) : ServiceFramework{system_, "btm:u"} {
12 // clang-format off
13 static const FunctionInfo functions[] = {
14 {0, C<&IBtmUser::GetCore>, "GetCore"},
15 };
16 // clang-format on
17
18 RegisterHandlers(functions);
19}
20
21IBtmUser::~IBtmUser() = default;
22
23Result IBtmUser::GetCore(OutInterface<IBtmUserCore> out_interface) {
24 LOG_WARNING(Service_BTM, "called");
25
26 *out_interface = std::make_shared<IBtmUserCore>(system);
27 R_SUCCEED();
28}
29
30} // namespace Service::BTM
diff --git a/src/core/hle/service/btm/btm_user.h b/src/core/hle/service/btm/btm_user.h
new file mode 100644
index 000000000..d9ee5db45
--- /dev/null
+++ b/src/core/hle/service/btm/btm_user.h
@@ -0,0 +1,25 @@
1// SPDX-FileCopyrightText: Copyright 2024 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-3.0-or-later
3
4#pragma once
5
6#include "core/hle/service/cmif_types.h"
7#include "core/hle/service/service.h"
8
9namespace Core {
10class System;
11}
12
13namespace Service::BTM {
14class IBtmUserCore;
15
16class IBtmUser final : public ServiceFramework<IBtmUser> {
17public:
18 explicit IBtmUser(Core::System& system_);
19 ~IBtmUser() override;
20
21private:
22 Result GetCore(OutInterface<IBtmUserCore> out_interface);
23};
24
25} // namespace Service::BTM
diff --git a/src/core/hle/service/btm/btm_user_core.cpp b/src/core/hle/service/btm/btm_user_core.cpp
new file mode 100644
index 000000000..6f9fa589b
--- /dev/null
+++ b/src/core/hle/service/btm/btm_user_core.cpp
@@ -0,0 +1,103 @@
1// SPDX-FileCopyrightText: Copyright 2024 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-3.0-or-later
3
4#include <memory>
5
6#include "common/logging/log.h"
7#include "core/core.h"
8#include "core/hle/kernel/k_event.h"
9#include "core/hle/service/btm/btm_user_core.h"
10#include "core/hle/service/cmif_serialization.h"
11
12namespace Service::BTM {
13
14IBtmUserCore::IBtmUserCore(Core::System& system_)
15 : ServiceFramework{system_, "IBtmUserCore"}, service_context{system_, "IBtmUserCore"} {
16 // clang-format off
17 static const FunctionInfo functions[] = {
18 {0, C<&IBtmUserCore::AcquireBleScanEvent>, "AcquireBleScanEvent"},
19 {1, nullptr, "GetBleScanFilterParameter"},
20 {2, nullptr, "GetBleScanFilterParameter2"},
21 {3, nullptr, "StartBleScanForGeneral"},
22 {4, nullptr, "StopBleScanForGeneral"},
23 {5, nullptr, "GetBleScanResultsForGeneral"},
24 {6, nullptr, "StartBleScanForPaired"},
25 {7, nullptr, "StopBleScanForPaired"},
26 {8, nullptr, "StartBleScanForSmartDevice"},
27 {9, nullptr, "StopBleScanForSmartDevice"},
28 {10, nullptr, "GetBleScanResultsForSmartDevice"},
29 {17, C<&IBtmUserCore::AcquireBleConnectionEvent>, "AcquireBleConnectionEvent"},
30 {18, nullptr, "BleConnect"},
31 {19, nullptr, "BleDisconnect"},
32 {20, nullptr, "BleGetConnectionState"},
33 {21, nullptr, "AcquireBlePairingEvent"},
34 {22, nullptr, "BlePairDevice"},
35 {23, nullptr, "BleUnPairDevice"},
36 {24, nullptr, "BleUnPairDevice2"},
37 {25, nullptr, "BleGetPairedDevices"},
38 {26, C<&IBtmUserCore::AcquireBleServiceDiscoveryEvent>, "AcquireBleServiceDiscoveryEvent"},
39 {27, nullptr, "GetGattServices"},
40 {28, nullptr, "GetGattService"},
41 {29, nullptr, "GetGattIncludedServices"},
42 {30, nullptr, "GetBelongingGattService"},
43 {31, nullptr, "GetGattCharacteristics"},
44 {32, nullptr, "GetGattDescriptors"},
45 {33, C<&IBtmUserCore::AcquireBleMtuConfigEvent>, "AcquireBleMtuConfigEvent"},
46 {34, nullptr, "ConfigureBleMtu"},
47 {35, nullptr, "GetBleMtu"},
48 {36, nullptr, "RegisterBleGattDataPath"},
49 {37, nullptr, "UnregisterBleGattDataPath"},
50 };
51 // clang-format on
52 RegisterHandlers(functions);
53
54 scan_event = service_context.CreateEvent("IBtmUserCore:ScanEvent");
55 connection_event = service_context.CreateEvent("IBtmUserCore:ConnectionEvent");
56 service_discovery_event = service_context.CreateEvent("IBtmUserCore:DiscoveryEvent");
57 config_event = service_context.CreateEvent("IBtmUserCore:ConfigEvent");
58}
59
60IBtmUserCore::~IBtmUserCore() {
61 service_context.CloseEvent(scan_event);
62 service_context.CloseEvent(connection_event);
63 service_context.CloseEvent(service_discovery_event);
64 service_context.CloseEvent(config_event);
65}
66
67Result IBtmUserCore::AcquireBleScanEvent(Out<bool> out_is_valid,
68 OutCopyHandle<Kernel::KReadableEvent> out_event) {
69 LOG_WARNING(Service_BTM, "(STUBBED) called");
70
71 *out_is_valid = true;
72 *out_event = &scan_event->GetReadableEvent();
73 R_SUCCEED();
74}
75
76Result IBtmUserCore::AcquireBleConnectionEvent(Out<bool> out_is_valid,
77 OutCopyHandle<Kernel::KReadableEvent> out_event) {
78 LOG_WARNING(Service_BTM, "(STUBBED) called");
79
80 *out_is_valid = true;
81 *out_event = &connection_event->GetReadableEvent();
82 R_SUCCEED();
83}
84
85Result IBtmUserCore::AcquireBleServiceDiscoveryEvent(
86 Out<bool> out_is_valid, OutCopyHandle<Kernel::KReadableEvent> out_event) {
87 LOG_WARNING(Service_BTM, "(STUBBED) called");
88
89 *out_is_valid = true;
90 *out_event = &service_discovery_event->GetReadableEvent();
91 R_SUCCEED();
92}
93
94Result IBtmUserCore::AcquireBleMtuConfigEvent(Out<bool> out_is_valid,
95 OutCopyHandle<Kernel::KReadableEvent> out_event) {
96 LOG_WARNING(Service_BTM, "(STUBBED) called");
97
98 *out_is_valid = true;
99 *out_event = &config_event->GetReadableEvent();
100 R_SUCCEED();
101}
102
103} // namespace Service::BTM
diff --git a/src/core/hle/service/btm/btm_user_core.h b/src/core/hle/service/btm/btm_user_core.h
new file mode 100644
index 000000000..dc0a22e81
--- /dev/null
+++ b/src/core/hle/service/btm/btm_user_core.h
@@ -0,0 +1,47 @@
1// SPDX-FileCopyrightText: Copyright 2024 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-3.0-or-later
3
4#pragma once
5
6#include "core/hle/service/cmif_types.h"
7#include "core/hle/service/kernel_helpers.h"
8#include "core/hle/service/service.h"
9
10namespace Kernel {
11class KEvent;
12class KReadableEvent;
13} // namespace Kernel
14
15namespace Core {
16class System;
17}
18
19namespace Service::BTM {
20
21class IBtmUserCore final : public ServiceFramework<IBtmUserCore> {
22public:
23 explicit IBtmUserCore(Core::System& system_);
24 ~IBtmUserCore() override;
25
26private:
27 Result AcquireBleScanEvent(Out<bool> out_is_valid,
28 OutCopyHandle<Kernel::KReadableEvent> out_event);
29
30 Result AcquireBleConnectionEvent(Out<bool> out_is_valid,
31 OutCopyHandle<Kernel::KReadableEvent> out_event);
32
33 Result AcquireBleServiceDiscoveryEvent(Out<bool> out_is_valid,
34 OutCopyHandle<Kernel::KReadableEvent> out_event);
35
36 Result AcquireBleMtuConfigEvent(Out<bool> out_is_valid,
37 OutCopyHandle<Kernel::KReadableEvent> out_event);
38
39 KernelHelpers::ServiceContext service_context;
40
41 Kernel::KEvent* scan_event;
42 Kernel::KEvent* connection_event;
43 Kernel::KEvent* service_discovery_event;
44 Kernel::KEvent* config_event;
45};
46
47} // namespace Service::BTM
diff --git a/src/core/hle/service/filesystem/fsp/fs_i_directory.cpp b/src/core/hle/service/filesystem/fsp/fs_i_directory.cpp
index 39690018b..8483394d0 100644
--- a/src/core/hle/service/filesystem/fsp/fs_i_directory.cpp
+++ b/src/core/hle/service/filesystem/fsp/fs_i_directory.cpp
@@ -3,82 +3,34 @@
3 3
4#include "core/file_sys/fs_filesystem.h" 4#include "core/file_sys/fs_filesystem.h"
5#include "core/file_sys/savedata_factory.h" 5#include "core/file_sys/savedata_factory.h"
6#include "core/hle/service/cmif_serialization.h"
6#include "core/hle/service/filesystem/fsp/fs_i_directory.h" 7#include "core/hle/service/filesystem/fsp/fs_i_directory.h"
7#include "core/hle/service/ipc_helpers.h"
8 8
9namespace Service::FileSystem { 9namespace Service::FileSystem {
10 10
11template <typename T> 11IDirectory::IDirectory(Core::System& system_, FileSys::VirtualDir directory_,
12static void BuildEntryIndex(std::vector<FileSys::DirectoryEntry>& entries,
13 const std::vector<T>& new_data, FileSys::DirectoryEntryType type) {
14 entries.reserve(entries.size() + new_data.size());
15
16 for (const auto& new_entry : new_data) {
17 auto name = new_entry->GetName();
18
19 if (type == FileSys::DirectoryEntryType::File &&
20 name == FileSys::GetSaveDataSizeFileName()) {
21 continue;
22 }
23
24 entries.emplace_back(name, static_cast<s8>(type),
25 type == FileSys::DirectoryEntryType::Directory ? 0
26 : new_entry->GetSize());
27 }
28}
29
30IDirectory::IDirectory(Core::System& system_, FileSys::VirtualDir backend_,
31 FileSys::OpenDirectoryMode mode) 12 FileSys::OpenDirectoryMode mode)
32 : ServiceFramework{system_, "IDirectory"}, backend(std::move(backend_)) { 13 : ServiceFramework{system_, "IDirectory"},
14 backend(std::make_unique<FileSys::Fsa::IDirectory>(directory_, mode)) {
33 static const FunctionInfo functions[] = { 15 static const FunctionInfo functions[] = {
34 {0, &IDirectory::Read, "Read"}, 16 {0, D<&IDirectory::Read>, "Read"},
35 {1, &IDirectory::GetEntryCount, "GetEntryCount"}, 17 {1, D<&IDirectory::GetEntryCount>, "GetEntryCount"},
36 }; 18 };
37 RegisterHandlers(functions); 19 RegisterHandlers(functions);
38
39 // TODO(DarkLordZach): Verify that this is the correct behavior.
40 // Build entry index now to save time later.
41 if (True(mode & FileSys::OpenDirectoryMode::Directory)) {
42 BuildEntryIndex(entries, backend->GetSubdirectories(),
43 FileSys::DirectoryEntryType::Directory);
44 }
45 if (True(mode & FileSys::OpenDirectoryMode::File)) {
46 BuildEntryIndex(entries, backend->GetFiles(), FileSys::DirectoryEntryType::File);
47 }
48} 20}
49 21
50void IDirectory::Read(HLERequestContext& ctx) { 22Result IDirectory::Read(
23 Out<s64> out_count,
24 const OutArray<FileSys::DirectoryEntry, BufferAttr_HipcMapAlias> out_entries) {
51 LOG_DEBUG(Service_FS, "called."); 25 LOG_DEBUG(Service_FS, "called.");
52 26
53 // Calculate how many entries we can fit in the output buffer 27 R_RETURN(backend->Read(out_count, out_entries.data(), out_entries.size()));
54 const u64 count_entries = ctx.GetWriteBufferNumElements<FileSys::DirectoryEntry>();
55
56 // Cap at total number of entries.
57 const u64 actual_entries = std::min(count_entries, entries.size() - next_entry_index);
58
59 // Determine data start and end
60 const auto* begin = reinterpret_cast<u8*>(entries.data() + next_entry_index);
61 const auto* end = reinterpret_cast<u8*>(entries.data() + next_entry_index + actual_entries);
62 const auto range_size = static_cast<std::size_t>(std::distance(begin, end));
63
64 next_entry_index += actual_entries;
65
66 // Write the data to memory
67 ctx.WriteBuffer(begin, range_size);
68
69 IPC::ResponseBuilder rb{ctx, 4};
70 rb.Push(ResultSuccess);
71 rb.Push(actual_entries);
72} 28}
73 29
74void IDirectory::GetEntryCount(HLERequestContext& ctx) { 30Result IDirectory::GetEntryCount(Out<s64> out_count) {
75 LOG_DEBUG(Service_FS, "called"); 31 LOG_DEBUG(Service_FS, "called");
76 32
77 u64 count = entries.size() - next_entry_index; 33 R_RETURN(backend->GetEntryCount(out_count));
78
79 IPC::ResponseBuilder rb{ctx, 4};
80 rb.Push(ResultSuccess);
81 rb.Push(count);
82} 34}
83 35
84} // namespace Service::FileSystem 36} // namespace Service::FileSystem
diff --git a/src/core/hle/service/filesystem/fsp/fs_i_directory.h b/src/core/hle/service/filesystem/fsp/fs_i_directory.h
index 793ecfcd7..b6251f7fd 100644
--- a/src/core/hle/service/filesystem/fsp/fs_i_directory.h
+++ b/src/core/hle/service/filesystem/fsp/fs_i_directory.h
@@ -3,7 +3,9 @@
3 3
4#pragma once 4#pragma once
5 5
6#include "core/file_sys/fsa/fs_i_directory.h"
6#include "core/file_sys/vfs/vfs.h" 7#include "core/file_sys/vfs/vfs.h"
8#include "core/hle/service/cmif_types.h"
7#include "core/hle/service/filesystem/filesystem.h" 9#include "core/hle/service/filesystem/filesystem.h"
8#include "core/hle/service/service.h" 10#include "core/hle/service/service.h"
9 11
@@ -15,16 +17,15 @@ namespace Service::FileSystem {
15 17
16class IDirectory final : public ServiceFramework<IDirectory> { 18class IDirectory final : public ServiceFramework<IDirectory> {
17public: 19public:
18 explicit IDirectory(Core::System& system_, FileSys::VirtualDir backend_, 20 explicit IDirectory(Core::System& system_, FileSys::VirtualDir directory_,
19 FileSys::OpenDirectoryMode mode); 21 FileSys::OpenDirectoryMode mode);
20 22
21private: 23private:
22 FileSys::VirtualDir backend; 24 std::unique_ptr<FileSys::Fsa::IDirectory> backend;
23 std::vector<FileSys::DirectoryEntry> entries;
24 u64 next_entry_index = 0;
25 25
26 void Read(HLERequestContext& ctx); 26 Result Read(Out<s64> out_count,
27 void GetEntryCount(HLERequestContext& ctx); 27 const OutArray<FileSys::DirectoryEntry, BufferAttr_HipcMapAlias> out_entries);
28 Result GetEntryCount(Out<s64> out_count);
28}; 29};
29 30
30} // namespace Service::FileSystem 31} // namespace Service::FileSystem
diff --git a/src/core/hle/service/filesystem/fsp/fs_i_file.cpp b/src/core/hle/service/filesystem/fsp/fs_i_file.cpp
index 9a18f6ec5..a355d46ae 100644
--- a/src/core/hle/service/filesystem/fsp/fs_i_file.cpp
+++ b/src/core/hle/service/filesystem/fsp/fs_i_file.cpp
@@ -2,126 +2,64 @@
2// SPDX-License-Identifier: GPL-2.0-or-later 2// SPDX-License-Identifier: GPL-2.0-or-later
3 3
4#include "core/file_sys/errors.h" 4#include "core/file_sys/errors.h"
5#include "core/hle/service/cmif_serialization.h"
5#include "core/hle/service/filesystem/fsp/fs_i_file.h" 6#include "core/hle/service/filesystem/fsp/fs_i_file.h"
6#include "core/hle/service/ipc_helpers.h"
7 7
8namespace Service::FileSystem { 8namespace Service::FileSystem {
9 9
10IFile::IFile(Core::System& system_, FileSys::VirtualFile backend_) 10IFile::IFile(Core::System& system_, FileSys::VirtualFile file_)
11 : ServiceFramework{system_, "IFile"}, backend(std::move(backend_)) { 11 : ServiceFramework{system_, "IFile"}, backend{std::make_unique<FileSys::Fsa::IFile>(file_)} {
12 // clang-format off
12 static const FunctionInfo functions[] = { 13 static const FunctionInfo functions[] = {
13 {0, &IFile::Read, "Read"}, 14 {0, D<&IFile::Read>, "Read"},
14 {1, &IFile::Write, "Write"}, 15 {1, D<&IFile::Write>, "Write"},
15 {2, &IFile::Flush, "Flush"}, 16 {2, D<&IFile::Flush>, "Flush"},
16 {3, &IFile::SetSize, "SetSize"}, 17 {3, D<&IFile::SetSize>, "SetSize"},
17 {4, &IFile::GetSize, "GetSize"}, 18 {4, D<&IFile::GetSize>, "GetSize"},
18 {5, nullptr, "OperateRange"}, 19 {5, nullptr, "OperateRange"},
19 {6, nullptr, "OperateRangeWithBuffer"}, 20 {6, nullptr, "OperateRangeWithBuffer"},
20 }; 21 };
22 // clang-format on
21 RegisterHandlers(functions); 23 RegisterHandlers(functions);
22} 24}
23 25
24void IFile::Read(HLERequestContext& ctx) { 26Result IFile::Read(
25 IPC::RequestParser rp{ctx}; 27 FileSys::ReadOption option, Out<s64> out_size, s64 offset,
26 const u64 option = rp.Pop<u64>(); 28 const OutBuffer<BufferAttr_HipcMapAlias | BufferAttr_HipcMapTransferAllowsNonSecure> out_buffer,
27 const s64 offset = rp.Pop<s64>(); 29 s64 size) {
28 const s64 length = rp.Pop<s64>(); 30 LOG_DEBUG(Service_FS, "called, option={}, offset=0x{:X}, length={}", option.value, offset,
29 31 size);
30 LOG_DEBUG(Service_FS, "called, option={}, offset=0x{:X}, length={}", option, offset, length);
31
32 // Error checking
33 if (length < 0) {
34 LOG_ERROR(Service_FS, "Length is less than 0, length={}", length);
35 IPC::ResponseBuilder rb{ctx, 2};
36 rb.Push(FileSys::ResultInvalidSize);
37 return;
38 }
39 if (offset < 0) {
40 LOG_ERROR(Service_FS, "Offset is less than 0, offset={}", offset);
41 IPC::ResponseBuilder rb{ctx, 2};
42 rb.Push(FileSys::ResultInvalidOffset);
43 return;
44 }
45 32
46 // Read the data from the Storage backend 33 // Read the data from the Storage backend
47 std::vector<u8> output = backend->ReadBytes(length, offset); 34 R_RETURN(
48 35 backend->Read(reinterpret_cast<size_t*>(out_size.Get()), offset, out_buffer.data(), size));
49 // Write the data to memory
50 ctx.WriteBuffer(output);
51
52 IPC::ResponseBuilder rb{ctx, 4};
53 rb.Push(ResultSuccess);
54 rb.Push(static_cast<u64>(output.size()));
55} 36}
56 37
57void IFile::Write(HLERequestContext& ctx) { 38Result IFile::Write(
58 IPC::RequestParser rp{ctx}; 39 const InBuffer<BufferAttr_HipcMapAlias | BufferAttr_HipcMapTransferAllowsNonSecure> buffer,
59 const u64 option = rp.Pop<u64>(); 40 FileSys::WriteOption option, s64 offset, s64 size) {
60 const s64 offset = rp.Pop<s64>(); 41 LOG_DEBUG(Service_FS, "called, option={}, offset=0x{:X}, length={}", option.value, offset,
61 const s64 length = rp.Pop<s64>(); 42 size);
62
63 LOG_DEBUG(Service_FS, "called, option={}, offset=0x{:X}, length={}", option, offset, length);
64
65 // Error checking
66 if (length < 0) {
67 LOG_ERROR(Service_FS, "Length is less than 0, length={}", length);
68 IPC::ResponseBuilder rb{ctx, 2};
69 rb.Push(FileSys::ResultInvalidSize);
70 return;
71 }
72 if (offset < 0) {
73 LOG_ERROR(Service_FS, "Offset is less than 0, offset={}", offset);
74 IPC::ResponseBuilder rb{ctx, 2};
75 rb.Push(FileSys::ResultInvalidOffset);
76 return;
77 }
78
79 const auto data = ctx.ReadBuffer();
80 43
81 ASSERT_MSG(static_cast<s64>(data.size()) <= length, 44 R_RETURN(backend->Write(offset, buffer.data(), size, option));
82 "Attempting to write more data than requested (requested={:016X}, actual={:016X}).",
83 length, data.size());
84
85 // Write the data to the Storage backend
86 const auto write_size =
87 static_cast<std::size_t>(std::distance(data.begin(), data.begin() + length));
88 const std::size_t written = backend->Write(data.data(), write_size, offset);
89
90 ASSERT_MSG(static_cast<s64>(written) == length,
91 "Could not write all bytes to file (requested={:016X}, actual={:016X}).", length,
92 written);
93
94 IPC::ResponseBuilder rb{ctx, 2};
95 rb.Push(ResultSuccess);
96} 45}
97 46
98void IFile::Flush(HLERequestContext& ctx) { 47Result IFile::Flush() {
99 LOG_DEBUG(Service_FS, "called"); 48 LOG_DEBUG(Service_FS, "called");
100 49
101 // Exists for SDK compatibiltity -- No need to flush file. 50 R_RETURN(backend->Flush());
102
103 IPC::ResponseBuilder rb{ctx, 2};
104 rb.Push(ResultSuccess);
105} 51}
106 52
107void IFile::SetSize(HLERequestContext& ctx) { 53Result IFile::SetSize(s64 size) {
108 IPC::RequestParser rp{ctx};
109 const u64 size = rp.Pop<u64>();
110 LOG_DEBUG(Service_FS, "called, size={}", size); 54 LOG_DEBUG(Service_FS, "called, size={}", size);
111 55
112 backend->Resize(size); 56 R_RETURN(backend->SetSize(size));
113
114 IPC::ResponseBuilder rb{ctx, 2};
115 rb.Push(ResultSuccess);
116} 57}
117 58
118void IFile::GetSize(HLERequestContext& ctx) { 59Result IFile::GetSize(Out<s64> out_size) {
119 const u64 size = backend->GetSize(); 60 LOG_DEBUG(Service_FS, "called");
120 LOG_DEBUG(Service_FS, "called, size={}", size);
121 61
122 IPC::ResponseBuilder rb{ctx, 4}; 62 R_RETURN(backend->GetSize(out_size));
123 rb.Push(ResultSuccess);
124 rb.Push<u64>(size);
125} 63}
126 64
127} // namespace Service::FileSystem 65} // namespace Service::FileSystem
diff --git a/src/core/hle/service/filesystem/fsp/fs_i_file.h b/src/core/hle/service/filesystem/fsp/fs_i_file.h
index 5e5430c67..e8599ee2f 100644
--- a/src/core/hle/service/filesystem/fsp/fs_i_file.h
+++ b/src/core/hle/service/filesystem/fsp/fs_i_file.h
@@ -3,6 +3,8 @@
3 3
4#pragma once 4#pragma once
5 5
6#include "core/file_sys/fsa/fs_i_file.h"
7#include "core/hle/service/cmif_types.h"
6#include "core/hle/service/filesystem/filesystem.h" 8#include "core/hle/service/filesystem/filesystem.h"
7#include "core/hle/service/service.h" 9#include "core/hle/service/service.h"
8 10
@@ -10,16 +12,21 @@ namespace Service::FileSystem {
10 12
11class IFile final : public ServiceFramework<IFile> { 13class IFile final : public ServiceFramework<IFile> {
12public: 14public:
13 explicit IFile(Core::System& system_, FileSys::VirtualFile backend_); 15 explicit IFile(Core::System& system_, FileSys::VirtualFile file_);
14 16
15private: 17private:
16 FileSys::VirtualFile backend; 18 std::unique_ptr<FileSys::Fsa::IFile> backend;
17 19
18 void Read(HLERequestContext& ctx); 20 Result Read(FileSys::ReadOption option, Out<s64> out_size, s64 offset,
19 void Write(HLERequestContext& ctx); 21 const OutBuffer<BufferAttr_HipcMapAlias | BufferAttr_HipcMapTransferAllowsNonSecure>
20 void Flush(HLERequestContext& ctx); 22 out_buffer,
21 void SetSize(HLERequestContext& ctx); 23 s64 size);
22 void GetSize(HLERequestContext& ctx); 24 Result Write(
25 const InBuffer<BufferAttr_HipcMapAlias | BufferAttr_HipcMapTransferAllowsNonSecure> buffer,
26 FileSys::WriteOption option, s64 offset, s64 size);
27 Result Flush();
28 Result SetSize(s64 size);
29 Result GetSize(Out<s64> out_size);
23}; 30};
24 31
25} // namespace Service::FileSystem 32} // namespace Service::FileSystem
diff --git a/src/core/hle/service/filesystem/fsp/fs_i_filesystem.cpp b/src/core/hle/service/filesystem/fsp/fs_i_filesystem.cpp
index efa394dd1..d881e144d 100644
--- a/src/core/hle/service/filesystem/fsp/fs_i_filesystem.cpp
+++ b/src/core/hle/service/filesystem/fsp/fs_i_filesystem.cpp
@@ -2,261 +2,172 @@
2// SPDX-License-Identifier: GPL-2.0-or-later 2// SPDX-License-Identifier: GPL-2.0-or-later
3 3
4#include "common/string_util.h" 4#include "common/string_util.h"
5#include "core/file_sys/fssrv/fssrv_sf_path.h"
6#include "core/hle/service/cmif_serialization.h"
5#include "core/hle/service/filesystem/fsp/fs_i_directory.h" 7#include "core/hle/service/filesystem/fsp/fs_i_directory.h"
6#include "core/hle/service/filesystem/fsp/fs_i_file.h" 8#include "core/hle/service/filesystem/fsp/fs_i_file.h"
7#include "core/hle/service/filesystem/fsp/fs_i_filesystem.h" 9#include "core/hle/service/filesystem/fsp/fs_i_filesystem.h"
8#include "core/hle/service/ipc_helpers.h"
9 10
10namespace Service::FileSystem { 11namespace Service::FileSystem {
11 12
12IFileSystem::IFileSystem(Core::System& system_, FileSys::VirtualDir backend_, SizeGetter size_) 13IFileSystem::IFileSystem(Core::System& system_, FileSys::VirtualDir dir_, SizeGetter size_getter_)
13 : ServiceFramework{system_, "IFileSystem"}, backend{std::move(backend_)}, size{std::move( 14 : ServiceFramework{system_, "IFileSystem"}, backend{std::make_unique<FileSys::Fsa::IFileSystem>(
14 size_)} { 15 dir_)},
16 size_getter{std::move(size_getter_)} {
15 static const FunctionInfo functions[] = { 17 static const FunctionInfo functions[] = {
16 {0, &IFileSystem::CreateFile, "CreateFile"}, 18 {0, D<&IFileSystem::CreateFile>, "CreateFile"},
17 {1, &IFileSystem::DeleteFile, "DeleteFile"}, 19 {1, D<&IFileSystem::DeleteFile>, "DeleteFile"},
18 {2, &IFileSystem::CreateDirectory, "CreateDirectory"}, 20 {2, D<&IFileSystem::CreateDirectory>, "CreateDirectory"},
19 {3, &IFileSystem::DeleteDirectory, "DeleteDirectory"}, 21 {3, D<&IFileSystem::DeleteDirectory>, "DeleteDirectory"},
20 {4, &IFileSystem::DeleteDirectoryRecursively, "DeleteDirectoryRecursively"}, 22 {4, D<&IFileSystem::DeleteDirectoryRecursively>, "DeleteDirectoryRecursively"},
21 {5, &IFileSystem::RenameFile, "RenameFile"}, 23 {5, D<&IFileSystem::RenameFile>, "RenameFile"},
22 {6, nullptr, "RenameDirectory"}, 24 {6, nullptr, "RenameDirectory"},
23 {7, &IFileSystem::GetEntryType, "GetEntryType"}, 25 {7, D<&IFileSystem::GetEntryType>, "GetEntryType"},
24 {8, &IFileSystem::OpenFile, "OpenFile"}, 26 {8, D<&IFileSystem::OpenFile>, "OpenFile"},
25 {9, &IFileSystem::OpenDirectory, "OpenDirectory"}, 27 {9, D<&IFileSystem::OpenDirectory>, "OpenDirectory"},
26 {10, &IFileSystem::Commit, "Commit"}, 28 {10, D<&IFileSystem::Commit>, "Commit"},
27 {11, &IFileSystem::GetFreeSpaceSize, "GetFreeSpaceSize"}, 29 {11, D<&IFileSystem::GetFreeSpaceSize>, "GetFreeSpaceSize"},
28 {12, &IFileSystem::GetTotalSpaceSize, "GetTotalSpaceSize"}, 30 {12, D<&IFileSystem::GetTotalSpaceSize>, "GetTotalSpaceSize"},
29 {13, &IFileSystem::CleanDirectoryRecursively, "CleanDirectoryRecursively"}, 31 {13, D<&IFileSystem::CleanDirectoryRecursively>, "CleanDirectoryRecursively"},
30 {14, &IFileSystem::GetFileTimeStampRaw, "GetFileTimeStampRaw"}, 32 {14, D<&IFileSystem::GetFileTimeStampRaw>, "GetFileTimeStampRaw"},
31 {15, nullptr, "QueryEntry"}, 33 {15, nullptr, "QueryEntry"},
32 {16, &IFileSystem::GetFileSystemAttribute, "GetFileSystemAttribute"}, 34 {16, D<&IFileSystem::GetFileSystemAttribute>, "GetFileSystemAttribute"},
33 }; 35 };
34 RegisterHandlers(functions); 36 RegisterHandlers(functions);
35} 37}
36 38
37void IFileSystem::CreateFile(HLERequestContext& ctx) { 39Result IFileSystem::CreateFile(const InLargeData<FileSys::Sf::Path, BufferAttr_HipcPointer> path,
38 IPC::RequestParser rp{ctx}; 40 s32 option, s64 size) {
41 LOG_DEBUG(Service_FS, "called. file={}, option=0x{:X}, size=0x{:08X}", path->str, option, size);
39 42
40 const auto file_buffer = ctx.ReadBuffer(); 43 R_RETURN(backend->CreateFile(FileSys::Path(path->str), size));
41 const std::string name = Common::StringFromBuffer(file_buffer);
42
43 const u64 file_mode = rp.Pop<u64>();
44 const u32 file_size = rp.Pop<u32>();
45
46 LOG_DEBUG(Service_FS, "called. file={}, mode=0x{:X}, size=0x{:08X}", name, file_mode,
47 file_size);
48
49 IPC::ResponseBuilder rb{ctx, 2};
50 rb.Push(backend.CreateFile(name, file_size));
51} 44}
52 45
53void IFileSystem::DeleteFile(HLERequestContext& ctx) { 46Result IFileSystem::DeleteFile(const InLargeData<FileSys::Sf::Path, BufferAttr_HipcPointer> path) {
54 const auto file_buffer = ctx.ReadBuffer(); 47 LOG_DEBUG(Service_FS, "called. file={}", path->str);
55 const std::string name = Common::StringFromBuffer(file_buffer);
56 48
57 LOG_DEBUG(Service_FS, "called. file={}", name); 49 R_RETURN(backend->DeleteFile(FileSys::Path(path->str)));
58
59 IPC::ResponseBuilder rb{ctx, 2};
60 rb.Push(backend.DeleteFile(name));
61} 50}
62 51
63void IFileSystem::CreateDirectory(HLERequestContext& ctx) { 52Result IFileSystem::CreateDirectory(
64 const auto file_buffer = ctx.ReadBuffer(); 53 const InLargeData<FileSys::Sf::Path, BufferAttr_HipcPointer> path) {
65 const std::string name = Common::StringFromBuffer(file_buffer); 54 LOG_DEBUG(Service_FS, "called. directory={}", path->str);
66
67 LOG_DEBUG(Service_FS, "called. directory={}", name);
68 55
69 IPC::ResponseBuilder rb{ctx, 2}; 56 R_RETURN(backend->CreateDirectory(FileSys::Path(path->str)));
70 rb.Push(backend.CreateDirectory(name));
71} 57}
72 58
73void IFileSystem::DeleteDirectory(HLERequestContext& ctx) { 59Result IFileSystem::DeleteDirectory(
74 const auto file_buffer = ctx.ReadBuffer(); 60 const InLargeData<FileSys::Sf::Path, BufferAttr_HipcPointer> path) {
75 const std::string name = Common::StringFromBuffer(file_buffer); 61 LOG_DEBUG(Service_FS, "called. directory={}", path->str);
76
77 LOG_DEBUG(Service_FS, "called. directory={}", name);
78 62
79 IPC::ResponseBuilder rb{ctx, 2}; 63 R_RETURN(backend->DeleteDirectory(FileSys::Path(path->str)));
80 rb.Push(backend.DeleteDirectory(name));
81} 64}
82 65
83void IFileSystem::DeleteDirectoryRecursively(HLERequestContext& ctx) { 66Result IFileSystem::DeleteDirectoryRecursively(
84 const auto file_buffer = ctx.ReadBuffer(); 67 const InLargeData<FileSys::Sf::Path, BufferAttr_HipcPointer> path) {
85 const std::string name = Common::StringFromBuffer(file_buffer); 68 LOG_DEBUG(Service_FS, "called. directory={}", path->str);
86 69
87 LOG_DEBUG(Service_FS, "called. directory={}", name); 70 R_RETURN(backend->DeleteDirectoryRecursively(FileSys::Path(path->str)));
88
89 IPC::ResponseBuilder rb{ctx, 2};
90 rb.Push(backend.DeleteDirectoryRecursively(name));
91} 71}
92 72
93void IFileSystem::CleanDirectoryRecursively(HLERequestContext& ctx) { 73Result IFileSystem::CleanDirectoryRecursively(
94 const auto file_buffer = ctx.ReadBuffer(); 74 const InLargeData<FileSys::Sf::Path, BufferAttr_HipcPointer> path) {
95 const std::string name = Common::StringFromBuffer(file_buffer); 75 LOG_DEBUG(Service_FS, "called. Directory: {}", path->str);
96
97 LOG_DEBUG(Service_FS, "called. Directory: {}", name);
98 76
99 IPC::ResponseBuilder rb{ctx, 2}; 77 R_RETURN(backend->CleanDirectoryRecursively(FileSys::Path(path->str)));
100 rb.Push(backend.CleanDirectoryRecursively(name));
101} 78}
102 79
103void IFileSystem::RenameFile(HLERequestContext& ctx) { 80Result IFileSystem::RenameFile(
104 const std::string src_name = Common::StringFromBuffer(ctx.ReadBuffer(0)); 81 const InLargeData<FileSys::Sf::Path, BufferAttr_HipcPointer> old_path,
105 const std::string dst_name = Common::StringFromBuffer(ctx.ReadBuffer(1)); 82 const InLargeData<FileSys::Sf::Path, BufferAttr_HipcPointer> new_path) {
106 83 LOG_DEBUG(Service_FS, "called. file '{}' to file '{}'", old_path->str, new_path->str);
107 LOG_DEBUG(Service_FS, "called. file '{}' to file '{}'", src_name, dst_name);
108 84
109 IPC::ResponseBuilder rb{ctx, 2}; 85 R_RETURN(backend->RenameFile(FileSys::Path(old_path->str), FileSys::Path(new_path->str)));
110 rb.Push(backend.RenameFile(src_name, dst_name));
111} 86}
112 87
113void IFileSystem::OpenFile(HLERequestContext& ctx) { 88Result IFileSystem::OpenFile(OutInterface<IFile> out_interface,
114 IPC::RequestParser rp{ctx}; 89 const InLargeData<FileSys::Sf::Path, BufferAttr_HipcPointer> path,
115 90 u32 mode) {
116 const auto file_buffer = ctx.ReadBuffer(); 91 LOG_DEBUG(Service_FS, "called. file={}, mode={}", path->str, mode);
117 const std::string name = Common::StringFromBuffer(file_buffer);
118
119 const auto mode = static_cast<FileSys::OpenMode>(rp.Pop<u32>());
120
121 LOG_DEBUG(Service_FS, "called. file={}, mode={}", name, mode);
122 92
123 FileSys::VirtualFile vfs_file{}; 93 FileSys::VirtualFile vfs_file{};
124 auto result = backend.OpenFile(&vfs_file, name, mode); 94 R_TRY(backend->OpenFile(&vfs_file, FileSys::Path(path->str),
125 if (result != ResultSuccess) { 95 static_cast<FileSys::OpenMode>(mode)));
126 IPC::ResponseBuilder rb{ctx, 2};
127 rb.Push(result);
128 return;
129 }
130
131 auto file = std::make_shared<IFile>(system, vfs_file);
132
133 IPC::ResponseBuilder rb{ctx, 2, 0, 1};
134 rb.Push(ResultSuccess);
135 rb.PushIpcInterface<IFile>(std::move(file));
136}
137
138void IFileSystem::OpenDirectory(HLERequestContext& ctx) {
139 IPC::RequestParser rp{ctx};
140 96
141 const auto file_buffer = ctx.ReadBuffer(); 97 *out_interface = std::make_shared<IFile>(system, vfs_file);
142 const std::string name = Common::StringFromBuffer(file_buffer); 98 R_SUCCEED();
143 const auto mode = rp.PopRaw<FileSys::OpenDirectoryMode>(); 99}
144 100
145 LOG_DEBUG(Service_FS, "called. directory={}, mode={}", name, mode); 101Result IFileSystem::OpenDirectory(OutInterface<IDirectory> out_interface,
102 const InLargeData<FileSys::Sf::Path, BufferAttr_HipcPointer> path,
103 u32 mode) {
104 LOG_DEBUG(Service_FS, "called. directory={}, mode={}", path->str, mode);
146 105
147 FileSys::VirtualDir vfs_dir{}; 106 FileSys::VirtualDir vfs_dir{};
148 auto result = backend.OpenDirectory(&vfs_dir, name); 107 R_TRY(backend->OpenDirectory(&vfs_dir, FileSys::Path(path->str),
149 if (result != ResultSuccess) { 108 static_cast<FileSys::OpenDirectoryMode>(mode)));
150 IPC::ResponseBuilder rb{ctx, 2};
151 rb.Push(result);
152 return;
153 }
154
155 auto directory = std::make_shared<IDirectory>(system, vfs_dir, mode);
156
157 IPC::ResponseBuilder rb{ctx, 2, 0, 1};
158 rb.Push(ResultSuccess);
159 rb.PushIpcInterface<IDirectory>(std::move(directory));
160}
161 109
162void IFileSystem::GetEntryType(HLERequestContext& ctx) { 110 *out_interface = std::make_shared<IDirectory>(system, vfs_dir,
163 const auto file_buffer = ctx.ReadBuffer(); 111 static_cast<FileSys::OpenDirectoryMode>(mode));
164 const std::string name = Common::StringFromBuffer(file_buffer); 112 R_SUCCEED();
113}
165 114
166 LOG_DEBUG(Service_FS, "called. file={}", name); 115Result IFileSystem::GetEntryType(
116 Out<u32> out_type, const InLargeData<FileSys::Sf::Path, BufferAttr_HipcPointer> path) {
117 LOG_DEBUG(Service_FS, "called. file={}", path->str);
167 118
168 FileSys::DirectoryEntryType vfs_entry_type{}; 119 FileSys::DirectoryEntryType vfs_entry_type{};
169 auto result = backend.GetEntryType(&vfs_entry_type, name); 120 R_TRY(backend->GetEntryType(&vfs_entry_type, FileSys::Path(path->str)));
170 if (result != ResultSuccess) { 121
171 IPC::ResponseBuilder rb{ctx, 2}; 122 *out_type = static_cast<u32>(vfs_entry_type);
172 rb.Push(result); 123 R_SUCCEED();
173 return;
174 }
175
176 IPC::ResponseBuilder rb{ctx, 3};
177 rb.Push(ResultSuccess);
178 rb.Push<u32>(static_cast<u32>(vfs_entry_type));
179} 124}
180 125
181void IFileSystem::Commit(HLERequestContext& ctx) { 126Result IFileSystem::Commit() {
182 LOG_WARNING(Service_FS, "(STUBBED) called"); 127 LOG_WARNING(Service_FS, "(STUBBED) called");
183 128
184 IPC::ResponseBuilder rb{ctx, 2}; 129 R_SUCCEED();
185 rb.Push(ResultSuccess);
186} 130}
187 131
188void IFileSystem::GetFreeSpaceSize(HLERequestContext& ctx) { 132Result IFileSystem::GetFreeSpaceSize(
133 Out<s64> out_size, const InLargeData<FileSys::Sf::Path, BufferAttr_HipcPointer> path) {
189 LOG_DEBUG(Service_FS, "called"); 134 LOG_DEBUG(Service_FS, "called");
190 135
191 IPC::ResponseBuilder rb{ctx, 4}; 136 *out_size = size_getter.get_free_size();
192 rb.Push(ResultSuccess); 137 R_SUCCEED();
193 rb.Push(size.get_free_size());
194} 138}
195 139
196void IFileSystem::GetTotalSpaceSize(HLERequestContext& ctx) { 140Result IFileSystem::GetTotalSpaceSize(
141 Out<s64> out_size, const InLargeData<FileSys::Sf::Path, BufferAttr_HipcPointer> path) {
197 LOG_DEBUG(Service_FS, "called"); 142 LOG_DEBUG(Service_FS, "called");
198 143
199 IPC::ResponseBuilder rb{ctx, 4}; 144 *out_size = size_getter.get_total_size();
200 rb.Push(ResultSuccess); 145 R_SUCCEED();
201 rb.Push(size.get_total_size());
202} 146}
203 147
204void IFileSystem::GetFileTimeStampRaw(HLERequestContext& ctx) { 148Result IFileSystem::GetFileTimeStampRaw(
205 const auto file_buffer = ctx.ReadBuffer(); 149 Out<FileSys::FileTimeStampRaw> out_timestamp,
206 const std::string name = Common::StringFromBuffer(file_buffer); 150 const InLargeData<FileSys::Sf::Path, BufferAttr_HipcPointer> path) {
207 151 LOG_WARNING(Service_FS, "(Partial Implementation) called. file={}", path->str);
208 LOG_WARNING(Service_FS, "(Partial Implementation) called. file={}", name);
209 152
210 FileSys::FileTimeStampRaw vfs_timestamp{}; 153 FileSys::FileTimeStampRaw vfs_timestamp{};
211 auto result = backend.GetFileTimeStampRaw(&vfs_timestamp, name); 154 R_TRY(backend->GetFileTimeStampRaw(&vfs_timestamp, FileSys::Path(path->str)));
212 if (result != ResultSuccess) { 155
213 IPC::ResponseBuilder rb{ctx, 2}; 156 *out_timestamp = vfs_timestamp;
214 rb.Push(result); 157 R_SUCCEED();
215 return;
216 }
217
218 IPC::ResponseBuilder rb{ctx, 10};
219 rb.Push(ResultSuccess);
220 rb.PushRaw(vfs_timestamp);
221} 158}
222 159
223void IFileSystem::GetFileSystemAttribute(HLERequestContext& ctx) { 160Result IFileSystem::GetFileSystemAttribute(Out<FileSys::FileSystemAttribute> out_attribute) {
224 LOG_WARNING(Service_FS, "(STUBBED) called"); 161 LOG_WARNING(Service_FS, "(STUBBED) called");
225 162
226 struct FileSystemAttribute { 163 FileSys::FileSystemAttribute savedata_attribute{};
227 u8 dir_entry_name_length_max_defined;
228 u8 file_entry_name_length_max_defined;
229 u8 dir_path_name_length_max_defined;
230 u8 file_path_name_length_max_defined;
231 INSERT_PADDING_BYTES_NOINIT(0x5);
232 u8 utf16_dir_entry_name_length_max_defined;
233 u8 utf16_file_entry_name_length_max_defined;
234 u8 utf16_dir_path_name_length_max_defined;
235 u8 utf16_file_path_name_length_max_defined;
236 INSERT_PADDING_BYTES_NOINIT(0x18);
237 s32 dir_entry_name_length_max;
238 s32 file_entry_name_length_max;
239 s32 dir_path_name_length_max;
240 s32 file_path_name_length_max;
241 INSERT_PADDING_WORDS_NOINIT(0x5);
242 s32 utf16_dir_entry_name_length_max;
243 s32 utf16_file_entry_name_length_max;
244 s32 utf16_dir_path_name_length_max;
245 s32 utf16_file_path_name_length_max;
246 INSERT_PADDING_WORDS_NOINIT(0x18);
247 INSERT_PADDING_WORDS_NOINIT(0x1);
248 };
249 static_assert(sizeof(FileSystemAttribute) == 0xc0, "FileSystemAttribute has incorrect size");
250
251 FileSystemAttribute savedata_attribute{};
252 savedata_attribute.dir_entry_name_length_max_defined = true; 164 savedata_attribute.dir_entry_name_length_max_defined = true;
253 savedata_attribute.file_entry_name_length_max_defined = true; 165 savedata_attribute.file_entry_name_length_max_defined = true;
254 savedata_attribute.dir_entry_name_length_max = 0x40; 166 savedata_attribute.dir_entry_name_length_max = 0x40;
255 savedata_attribute.file_entry_name_length_max = 0x40; 167 savedata_attribute.file_entry_name_length_max = 0x40;
256 168
257 IPC::ResponseBuilder rb{ctx, 50}; 169 *out_attribute = savedata_attribute;
258 rb.Push(ResultSuccess); 170 R_SUCCEED();
259 rb.PushRaw(savedata_attribute);
260} 171}
261 172
262} // namespace Service::FileSystem 173} // namespace Service::FileSystem
diff --git a/src/core/hle/service/filesystem/fsp/fs_i_filesystem.h b/src/core/hle/service/filesystem/fsp/fs_i_filesystem.h
index b1f3ab5dd..dd069f36f 100644
--- a/src/core/hle/service/filesystem/fsp/fs_i_filesystem.h
+++ b/src/core/hle/service/filesystem/fsp/fs_i_filesystem.h
@@ -3,36 +3,58 @@
3 3
4#pragma once 4#pragma once
5 5
6#include "common/common_funcs.h"
7#include "core/file_sys/fs_filesystem.h"
8#include "core/file_sys/fsa/fs_i_filesystem.h"
6#include "core/file_sys/vfs/vfs.h" 9#include "core/file_sys/vfs/vfs.h"
10#include "core/hle/service/cmif_types.h"
7#include "core/hle/service/filesystem/filesystem.h" 11#include "core/hle/service/filesystem/filesystem.h"
8#include "core/hle/service/filesystem/fsp/fsp_types.h" 12#include "core/hle/service/filesystem/fsp/fsp_types.h"
9#include "core/hle/service/service.h" 13#include "core/hle/service/service.h"
10 14
15namespace FileSys::Sf {
16struct Path;
17}
18
11namespace Service::FileSystem { 19namespace Service::FileSystem {
12 20
21class IFile;
22class IDirectory;
23
13class IFileSystem final : public ServiceFramework<IFileSystem> { 24class IFileSystem final : public ServiceFramework<IFileSystem> {
14public: 25public:
15 explicit IFileSystem(Core::System& system_, FileSys::VirtualDir backend_, SizeGetter size_); 26 explicit IFileSystem(Core::System& system_, FileSys::VirtualDir dir_, SizeGetter size_getter_);
16 27
17 void CreateFile(HLERequestContext& ctx); 28 Result CreateFile(const InLargeData<FileSys::Sf::Path, BufferAttr_HipcPointer> path, s32 option,
18 void DeleteFile(HLERequestContext& ctx); 29 s64 size);
19 void CreateDirectory(HLERequestContext& ctx); 30 Result DeleteFile(const InLargeData<FileSys::Sf::Path, BufferAttr_HipcPointer> path);
20 void DeleteDirectory(HLERequestContext& ctx); 31 Result CreateDirectory(const InLargeData<FileSys::Sf::Path, BufferAttr_HipcPointer> path);
21 void DeleteDirectoryRecursively(HLERequestContext& ctx); 32 Result DeleteDirectory(const InLargeData<FileSys::Sf::Path, BufferAttr_HipcPointer> path);
22 void CleanDirectoryRecursively(HLERequestContext& ctx); 33 Result DeleteDirectoryRecursively(
23 void RenameFile(HLERequestContext& ctx); 34 const InLargeData<FileSys::Sf::Path, BufferAttr_HipcPointer> path);
24 void OpenFile(HLERequestContext& ctx); 35 Result CleanDirectoryRecursively(
25 void OpenDirectory(HLERequestContext& ctx); 36 const InLargeData<FileSys::Sf::Path, BufferAttr_HipcPointer> path);
26 void GetEntryType(HLERequestContext& ctx); 37 Result RenameFile(const InLargeData<FileSys::Sf::Path, BufferAttr_HipcPointer> old_path,
27 void Commit(HLERequestContext& ctx); 38 const InLargeData<FileSys::Sf::Path, BufferAttr_HipcPointer> new_path);
28 void GetFreeSpaceSize(HLERequestContext& ctx); 39 Result OpenFile(OutInterface<IFile> out_interface,
29 void GetTotalSpaceSize(HLERequestContext& ctx); 40 const InLargeData<FileSys::Sf::Path, BufferAttr_HipcPointer> path, u32 mode);
30 void GetFileTimeStampRaw(HLERequestContext& ctx); 41 Result OpenDirectory(OutInterface<IDirectory> out_interface,
31 void GetFileSystemAttribute(HLERequestContext& ctx); 42 const InLargeData<FileSys::Sf::Path, BufferAttr_HipcPointer> path,
43 u32 mode);
44 Result GetEntryType(Out<u32> out_type,
45 const InLargeData<FileSys::Sf::Path, BufferAttr_HipcPointer> path);
46 Result Commit();
47 Result GetFreeSpaceSize(Out<s64> out_size,
48 const InLargeData<FileSys::Sf::Path, BufferAttr_HipcPointer> path);
49 Result GetTotalSpaceSize(Out<s64> out_size,
50 const InLargeData<FileSys::Sf::Path, BufferAttr_HipcPointer> path);
51 Result GetFileTimeStampRaw(Out<FileSys::FileTimeStampRaw> out_timestamp,
52 const InLargeData<FileSys::Sf::Path, BufferAttr_HipcPointer> path);
53 Result GetFileSystemAttribute(Out<FileSys::FileSystemAttribute> out_attribute);
32 54
33private: 55private:
34 VfsDirectoryServiceWrapper backend; 56 std::unique_ptr<FileSys::Fsa::IFileSystem> backend;
35 SizeGetter size; 57 SizeGetter size_getter;
36}; 58};
37 59
38} // namespace Service::FileSystem 60} // namespace Service::FileSystem
diff --git a/src/core/hle/service/ns/application_manager_interface.cpp b/src/core/hle/service/ns/application_manager_interface.cpp
index 2e3a44c0d..7a91727f9 100644
--- a/src/core/hle/service/ns/application_manager_interface.cpp
+++ b/src/core/hle/service/ns/application_manager_interface.cpp
@@ -436,14 +436,14 @@ Result IApplicationManagerInterface::GetApplicationViewWithPromotionInfo(
436 436
437Result IApplicationManagerInterface::GetApplicationRightsOnClient( 437Result IApplicationManagerInterface::GetApplicationRightsOnClient(
438 OutArray<ApplicationRightsOnClient, BufferAttr_HipcMapAlias> out_rights, Out<u32> out_count, 438 OutArray<ApplicationRightsOnClient, BufferAttr_HipcMapAlias> out_rights, Out<u32> out_count,
439 Common::UUID account_id, u32 flags, u64 application_id) { 439 u32 flags, u64 application_id, Uid account_id) {
440 LOG_WARNING(Service_NS, "(STUBBED) called, flags={}, application_id={:016X}, account_id={}", 440 LOG_WARNING(Service_NS, "(STUBBED) called, flags={}, application_id={:016X}, account_id={}",
441 flags, application_id, account_id.FormattedString()); 441 flags, application_id, account_id.uuid.FormattedString());
442 442
443 if (!out_rights.empty()) { 443 if (!out_rights.empty()) {
444 ApplicationRightsOnClient rights{}; 444 ApplicationRightsOnClient rights{};
445 rights.application_id = application_id; 445 rights.application_id = application_id;
446 rights.uid = account_id; 446 rights.uid = account_id.uuid;
447 rights.flags = 0; 447 rights.flags = 0;
448 rights.flags2 = 0; 448 rights.flags2 = 0;
449 449
diff --git a/src/core/hle/service/ns/application_manager_interface.h b/src/core/hle/service/ns/application_manager_interface.h
index 350ec37ce..f33d269b3 100644
--- a/src/core/hle/service/ns/application_manager_interface.h
+++ b/src/core/hle/service/ns/application_manager_interface.h
@@ -37,7 +37,7 @@ public:
37 InArray<u64, BufferAttr_HipcMapAlias> application_ids); 37 InArray<u64, BufferAttr_HipcMapAlias> application_ids);
38 Result GetApplicationRightsOnClient( 38 Result GetApplicationRightsOnClient(
39 OutArray<ApplicationRightsOnClient, BufferAttr_HipcMapAlias> out_rights, Out<u32> out_count, 39 OutArray<ApplicationRightsOnClient, BufferAttr_HipcMapAlias> out_rights, Out<u32> out_count,
40 Common::UUID account_id, u32 flags, u64 application_id); 40 u32 flags, u64 application_id, Uid account_id);
41 Result CheckSdCardMountStatus(); 41 Result CheckSdCardMountStatus();
42 Result GetSdCardMountStatusChangedEvent(OutCopyHandle<Kernel::KReadableEvent> out_event); 42 Result GetSdCardMountStatusChangedEvent(OutCopyHandle<Kernel::KReadableEvent> out_event);
43 Result GetFreeSpaceSize(Out<s64> out_free_space_size, FileSys::StorageId storage_id); 43 Result GetFreeSpaceSize(Out<s64> out_free_space_size, FileSys::StorageId storage_id);
diff --git a/src/core/hle/service/ns/ns_types.h b/src/core/hle/service/ns/ns_types.h
index 38421b0f4..2dd664c4e 100644
--- a/src/core/hle/service/ns/ns_types.h
+++ b/src/core/hle/service/ns/ns_types.h
@@ -108,4 +108,9 @@ struct ContentPath {
108}; 108};
109static_assert(sizeof(ContentPath) == 0x10, "ContentPath has incorrect size."); 109static_assert(sizeof(ContentPath) == 0x10, "ContentPath has incorrect size.");
110 110
111struct Uid {
112 alignas(8) Common::UUID uuid;
113};
114static_assert(sizeof(Uid) == 0x10, "Uid has incorrect size.");
115
111} // namespace Service::NS 116} // namespace Service::NS
diff --git a/src/core/hle/service/ns/query_service.cpp b/src/core/hle/service/ns/query_service.cpp
index 946b7fa23..138400541 100644
--- a/src/core/hle/service/ns/query_service.cpp
+++ b/src/core/hle/service/ns/query_service.cpp
@@ -41,8 +41,7 @@ IQueryService::IQueryService(Core::System& system_) : ServiceFramework{system_,
41IQueryService::~IQueryService() = default; 41IQueryService::~IQueryService() = default;
42 42
43Result IQueryService::QueryPlayStatisticsByApplicationIdAndUserAccountId( 43Result IQueryService::QueryPlayStatisticsByApplicationIdAndUserAccountId(
44 Out<PlayStatistics> out_play_statistics, bool unknown, Common::UUID account_id, 44 Out<PlayStatistics> out_play_statistics, bool unknown, u64 application_id, Uid account_id) {
45 u64 application_id) {
46 // TODO(German77): Read statistics of the game 45 // TODO(German77): Read statistics of the game
47 *out_play_statistics = { 46 *out_play_statistics = {
48 .application_id = application_id, 47 .application_id = application_id,
@@ -50,7 +49,7 @@ Result IQueryService::QueryPlayStatisticsByApplicationIdAndUserAccountId(
50 }; 49 };
51 50
52 LOG_WARNING(Service_NS, "(STUBBED) called. unknown={}. application_id={:016X}, account_id={}", 51 LOG_WARNING(Service_NS, "(STUBBED) called. unknown={}. application_id={:016X}, account_id={}",
53 unknown, application_id, account_id.FormattedString()); 52 unknown, application_id, account_id.uuid.FormattedString());
54 R_SUCCEED(); 53 R_SUCCEED();
55} 54}
56 55
diff --git a/src/core/hle/service/ns/query_service.h b/src/core/hle/service/ns/query_service.h
index 6cdbfa277..c4c82b752 100644
--- a/src/core/hle/service/ns/query_service.h
+++ b/src/core/hle/service/ns/query_service.h
@@ -5,6 +5,7 @@
5 5
6#include "common/uuid.h" 6#include "common/uuid.h"
7#include "core/hle/service/cmif_types.h" 7#include "core/hle/service/cmif_types.h"
8#include "core/hle/service/ns/ns_types.h"
8#include "core/hle/service/service.h" 9#include "core/hle/service/service.h"
9 10
10namespace Service::NS { 11namespace Service::NS {
@@ -29,8 +30,7 @@ public:
29 30
30private: 31private:
31 Result QueryPlayStatisticsByApplicationIdAndUserAccountId( 32 Result QueryPlayStatisticsByApplicationIdAndUserAccountId(
32 Out<PlayStatistics> out_play_statistics, bool unknown, Common::UUID account_id, 33 Out<PlayStatistics> out_play_statistics, bool unknown, u64 application_id, Uid account_id);
33 u64 application_id);
34}; 34};
35 35
36} // namespace Service::NS 36} // namespace Service::NS
diff --git a/src/core/hle/service/nvnflinger/display.h b/src/core/hle/service/nvnflinger/display.h
index f27cbf144..40aa59787 100644
--- a/src/core/hle/service/nvnflinger/display.h
+++ b/src/core/hle/service/nvnflinger/display.h
@@ -3,8 +3,6 @@
3 3
4#pragma once 4#pragma once
5 5
6#include <list>
7
8#include "core/hle/service/nvnflinger/buffer_item_consumer.h" 6#include "core/hle/service/nvnflinger/buffer_item_consumer.h"
9#include "core/hle/service/nvnflinger/hwc_layer.h" 7#include "core/hle/service/nvnflinger/hwc_layer.h"
10 8
@@ -26,18 +24,12 @@ struct Layer {
26}; 24};
27 25
28struct LayerStack { 26struct LayerStack {
29 std::list<Layer> layers; 27 std::vector<std::shared_ptr<Layer>> layers;
30};
31
32struct Display {
33 explicit Display(u64 id_) {
34 id = id_;
35 }
36 28
37 Layer* FindLayer(s32 consumer_id) { 29 std::shared_ptr<Layer> FindLayer(s32 consumer_id) {
38 for (auto& layer : stack.layers) { 30 for (auto& layer : layers) {
39 if (layer.consumer_id == consumer_id) { 31 if (layer->consumer_id == consumer_id) {
40 return &layer; 32 return layer;
41 } 33 }
42 } 34 }
43 35
@@ -45,7 +37,13 @@ struct Display {
45 } 37 }
46 38
47 bool HasLayers() { 39 bool HasLayers() {
48 return !stack.layers.empty(); 40 return !layers.empty();
41 }
42};
43
44struct Display {
45 explicit Display(u64 id_) {
46 id = id_;
49 } 47 }
50 48
51 u64 id; 49 u64 id;
diff --git a/src/core/hle/service/nvnflinger/hardware_composer.cpp b/src/core/hle/service/nvnflinger/hardware_composer.cpp
index 02215a786..f2dfe85a9 100644
--- a/src/core/hle/service/nvnflinger/hardware_composer.cpp
+++ b/src/core/hle/service/nvnflinger/hardware_composer.cpp
@@ -55,10 +55,10 @@ u32 HardwareComposer::ComposeLocked(f32* out_speed_scale, Display& display,
55 55
56 // Acquire all necessary framebuffers. 56 // Acquire all necessary framebuffers.
57 for (auto& layer : display.stack.layers) { 57 for (auto& layer : display.stack.layers) {
58 auto consumer_id = layer.consumer_id; 58 auto consumer_id = layer->consumer_id;
59 59
60 // Try to fetch the framebuffer (either new or stale). 60 // Try to fetch the framebuffer (either new or stale).
61 const auto result = this->CacheFramebufferLocked(layer, consumer_id); 61 const auto result = this->CacheFramebufferLocked(*layer, consumer_id);
62 62
63 // If we failed, skip this layer. 63 // If we failed, skip this layer.
64 if (result == CacheStatus::NoBufferAvailable) { 64 if (result == CacheStatus::NoBufferAvailable) {
@@ -75,7 +75,7 @@ u32 HardwareComposer::ComposeLocked(f32* out_speed_scale, Display& display,
75 const auto& igbp_buffer = *item.graphic_buffer; 75 const auto& igbp_buffer = *item.graphic_buffer;
76 76
77 // TODO: get proper Z-index from layer 77 // TODO: get proper Z-index from layer
78 if (layer.visible) { 78 if (layer->visible) {
79 composition_stack.emplace_back(HwcLayer{ 79 composition_stack.emplace_back(HwcLayer{
80 .buffer_handle = igbp_buffer.BufferId(), 80 .buffer_handle = igbp_buffer.BufferId(),
81 .offset = igbp_buffer.Offset(), 81 .offset = igbp_buffer.Offset(),
@@ -84,7 +84,7 @@ u32 HardwareComposer::ComposeLocked(f32* out_speed_scale, Display& display,
84 .height = igbp_buffer.Height(), 84 .height = igbp_buffer.Height(),
85 .stride = igbp_buffer.Stride(), 85 .stride = igbp_buffer.Stride(),
86 .z_index = 0, 86 .z_index = 0,
87 .blending = layer.blending, 87 .blending = layer->blending,
88 .transform = static_cast<android::BufferTransformFlags>(item.transform), 88 .transform = static_cast<android::BufferTransformFlags>(item.transform),
89 .crop_rect = item.crop, 89 .crop_rect = item.crop,
90 .acquire_fence = item.fence, 90 .acquire_fence = item.fence,
@@ -134,7 +134,7 @@ u32 HardwareComposer::ComposeLocked(f32* out_speed_scale, Display& display,
134 continue; 134 continue;
135 } 135 }
136 136
137 if (auto* layer = display.FindLayer(layer_id); layer != nullptr) { 137 if (const auto layer = display.stack.FindLayer(layer_id); layer != nullptr) {
138 // TODO: support release fence 138 // TODO: support release fence
139 // This is needed to prevent screen tearing 139 // This is needed to prevent screen tearing
140 layer->buffer_item_consumer->ReleaseBuffer(framebuffer.item, android::Fence::NoFence()); 140 layer->buffer_item_consumer->ReleaseBuffer(framebuffer.item, android::Fence::NoFence());
@@ -153,7 +153,7 @@ void HardwareComposer::RemoveLayerLocked(Display& display, ConsumerId consumer_i
153 } 153 }
154 154
155 // Try to release the buffer item. 155 // Try to release the buffer item.
156 auto* const layer = display.FindLayer(consumer_id); 156 const auto layer = display.stack.FindLayer(consumer_id);
157 if (layer && it->second.is_acquired) { 157 if (layer && it->second.is_acquired) {
158 layer->buffer_item_consumer->ReleaseBuffer(it->second.item, android::Fence::NoFence()); 158 layer->buffer_item_consumer->ReleaseBuffer(it->second.item, android::Fence::NoFence());
159 } 159 }
diff --git a/src/core/hle/service/nvnflinger/surface_flinger.cpp b/src/core/hle/service/nvnflinger/surface_flinger.cpp
index 41a705717..8362b65e5 100644
--- a/src/core/hle/service/nvnflinger/surface_flinger.cpp
+++ b/src/core/hle/service/nvnflinger/surface_flinger.cpp
@@ -36,7 +36,7 @@ void SurfaceFlinger::RemoveDisplay(u64 display_id) {
36bool SurfaceFlinger::ComposeDisplay(s32* out_swap_interval, f32* out_compose_speed_scale, 36bool SurfaceFlinger::ComposeDisplay(s32* out_swap_interval, f32* out_compose_speed_scale,
37 u64 display_id) { 37 u64 display_id) {
38 auto* const display = this->FindDisplay(display_id); 38 auto* const display = this->FindDisplay(display_id);
39 if (!display || !display->HasLayers()) { 39 if (!display || !display->stack.HasLayers()) {
40 return false; 40 return false;
41 } 41 }
42 42
@@ -46,19 +46,34 @@ bool SurfaceFlinger::ComposeDisplay(s32* out_swap_interval, f32* out_compose_spe
46 return true; 46 return true;
47} 47}
48 48
49void SurfaceFlinger::AddLayerToDisplayStack(u64 display_id, s32 consumer_binder_id) { 49void SurfaceFlinger::CreateLayer(s32 consumer_binder_id) {
50 auto* const display = this->FindDisplay(display_id);
51 auto binder = std::static_pointer_cast<android::BufferQueueConsumer>( 50 auto binder = std::static_pointer_cast<android::BufferQueueConsumer>(
52 m_server.TryGetBinder(consumer_binder_id)); 51 m_server.TryGetBinder(consumer_binder_id));
53 52 if (!binder) {
54 if (!display || !binder) {
55 return; 53 return;
56 } 54 }
57 55
58 auto buffer_item_consumer = std::make_shared<android::BufferItemConsumer>(std::move(binder)); 56 auto buffer_item_consumer = std::make_shared<android::BufferItemConsumer>(std::move(binder));
59 buffer_item_consumer->Connect(false); 57 buffer_item_consumer->Connect(false);
60 58
61 display->stack.layers.emplace_back(std::move(buffer_item_consumer), consumer_binder_id); 59 m_layers.layers.emplace_back(
60 std::make_shared<Layer>(std::move(buffer_item_consumer), consumer_binder_id));
61}
62
63void SurfaceFlinger::DestroyLayer(s32 consumer_binder_id) {
64 std::erase_if(m_layers.layers,
65 [&](auto& layer) { return layer->consumer_id == consumer_binder_id; });
66}
67
68void SurfaceFlinger::AddLayerToDisplayStack(u64 display_id, s32 consumer_binder_id) {
69 auto* const display = this->FindDisplay(display_id);
70 auto layer = this->FindLayer(consumer_binder_id);
71
72 if (!display || !layer) {
73 return;
74 }
75
76 display->stack.layers.emplace_back(std::move(layer));
62} 77}
63 78
64void SurfaceFlinger::RemoveLayerFromDisplayStack(u64 display_id, s32 consumer_binder_id) { 79void SurfaceFlinger::RemoveLayerFromDisplayStack(u64 display_id, s32 consumer_binder_id) {
@@ -69,18 +84,18 @@ void SurfaceFlinger::RemoveLayerFromDisplayStack(u64 display_id, s32 consumer_bi
69 84
70 m_composer.RemoveLayerLocked(*display, consumer_binder_id); 85 m_composer.RemoveLayerLocked(*display, consumer_binder_id);
71 std::erase_if(display->stack.layers, 86 std::erase_if(display->stack.layers,
72 [&](auto& layer) { return layer.consumer_id == consumer_binder_id; }); 87 [&](auto& layer) { return layer->consumer_id == consumer_binder_id; });
73} 88}
74 89
75void SurfaceFlinger::SetLayerVisibility(s32 consumer_binder_id, bool visible) { 90void SurfaceFlinger::SetLayerVisibility(s32 consumer_binder_id, bool visible) {
76 if (auto* layer = this->FindLayer(consumer_binder_id); layer != nullptr) { 91 if (const auto layer = this->FindLayer(consumer_binder_id); layer != nullptr) {
77 layer->visible = visible; 92 layer->visible = visible;
78 return; 93 return;
79 } 94 }
80} 95}
81 96
82void SurfaceFlinger::SetLayerBlending(s32 consumer_binder_id, LayerBlending blending) { 97void SurfaceFlinger::SetLayerBlending(s32 consumer_binder_id, LayerBlending blending) {
83 if (auto* layer = this->FindLayer(consumer_binder_id); layer != nullptr) { 98 if (const auto layer = this->FindLayer(consumer_binder_id); layer != nullptr) {
84 layer->blending = blending; 99 layer->blending = blending;
85 return; 100 return;
86 } 101 }
@@ -96,9 +111,9 @@ Display* SurfaceFlinger::FindDisplay(u64 display_id) {
96 return nullptr; 111 return nullptr;
97} 112}
98 113
99Layer* SurfaceFlinger::FindLayer(s32 consumer_binder_id) { 114std::shared_ptr<Layer> SurfaceFlinger::FindLayer(s32 consumer_binder_id) {
100 for (auto& display : m_displays) { 115 for (auto& layer : m_layers.layers) {
101 if (auto* layer = display.FindLayer(consumer_binder_id); layer != nullptr) { 116 if (layer->consumer_id == consumer_binder_id) {
102 return layer; 117 return layer;
103 } 118 }
104 } 119 }
diff --git a/src/core/hle/service/nvnflinger/surface_flinger.h b/src/core/hle/service/nvnflinger/surface_flinger.h
index d8c53fbda..406281c83 100644
--- a/src/core/hle/service/nvnflinger/surface_flinger.h
+++ b/src/core/hle/service/nvnflinger/surface_flinger.h
@@ -36,6 +36,9 @@ public:
36 void RemoveDisplay(u64 display_id); 36 void RemoveDisplay(u64 display_id);
37 bool ComposeDisplay(s32* out_swap_interval, f32* out_compose_speed_scale, u64 display_id); 37 bool ComposeDisplay(s32* out_swap_interval, f32* out_compose_speed_scale, u64 display_id);
38 38
39 void CreateLayer(s32 consumer_binder_id);
40 void DestroyLayer(s32 consumer_binder_id);
41
39 void AddLayerToDisplayStack(u64 display_id, s32 consumer_binder_id); 42 void AddLayerToDisplayStack(u64 display_id, s32 consumer_binder_id);
40 void RemoveLayerFromDisplayStack(u64 display_id, s32 consumer_binder_id); 43 void RemoveLayerFromDisplayStack(u64 display_id, s32 consumer_binder_id);
41 44
@@ -44,7 +47,7 @@ public:
44 47
45private: 48private:
46 Display* FindDisplay(u64 display_id); 49 Display* FindDisplay(u64 display_id);
47 Layer* FindLayer(s32 consumer_binder_id); 50 std::shared_ptr<Layer> FindLayer(s32 consumer_binder_id);
48 51
49public: 52public:
50 // TODO: these don't belong here 53 // TODO: these don't belong here
@@ -57,6 +60,7 @@ private:
57 KernelHelpers::ServiceContext m_context; 60 KernelHelpers::ServiceContext m_context;
58 61
59 std::vector<Display> m_displays; 62 std::vector<Display> m_displays;
63 LayerStack m_layers;
60 std::shared_ptr<Nvidia::Module> nvdrv; 64 std::shared_ptr<Nvidia::Module> nvdrv;
61 s32 disp_fd; 65 s32 disp_fd;
62 HardwareComposer m_composer; 66 HardwareComposer m_composer;
diff --git a/src/core/hle/service/psc/ovln/ovln_types.h b/src/core/hle/service/psc/ovln/ovln_types.h
new file mode 100644
index 000000000..343b05dcc
--- /dev/null
+++ b/src/core/hle/service/psc/ovln/ovln_types.h
@@ -0,0 +1,21 @@
1// SPDX-FileCopyrightText: Copyright 2024 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-2.0-or-later
3
4#pragma once
5
6#include "common/bit_field.h"
7#include "common/common_types.h"
8
9namespace Service::PSC {
10
11using OverlayNotification = std::array<u64, 0x10>;
12static_assert(sizeof(OverlayNotification) == 0x80, "OverlayNotification has incorrect size");
13
14union MessageFlags {
15 u64 raw;
16 BitField<0, 8, u64> message_type;
17 BitField<8, 8, u64> queue_type;
18};
19static_assert(sizeof(MessageFlags) == 0x8, "MessageFlags has incorrect size");
20
21} // namespace Service::PSC
diff --git a/src/core/hle/service/psc/ovln/receiver.cpp b/src/core/hle/service/psc/ovln/receiver.cpp
new file mode 100644
index 000000000..85f62816d
--- /dev/null
+++ b/src/core/hle/service/psc/ovln/receiver.cpp
@@ -0,0 +1,24 @@
1// SPDX-FileCopyrightText: Copyright 2024 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-2.0-or-later
3
4#include "core/hle/service/psc/ovln/receiver.h"
5
6namespace Service::PSC {
7
8IReceiver::IReceiver(Core::System& system_) : ServiceFramework{system_, "IReceiver"} {
9 // clang-format off
10 static const FunctionInfo functions[] = {
11 {0, nullptr, "AddSource"},
12 {1, nullptr, "RemoveSource"},
13 {2, nullptr, "GetReceiveEventHandle"},
14 {3, nullptr, "Receive"},
15 {4, nullptr, "ReceiveWithTick"},
16 };
17 // clang-format on
18
19 RegisterHandlers(functions);
20}
21
22IReceiver::~IReceiver() = default;
23
24} // namespace Service::PSC
diff --git a/src/core/hle/service/psc/ovln/receiver.h b/src/core/hle/service/psc/ovln/receiver.h
new file mode 100644
index 000000000..c47a4ff7e
--- /dev/null
+++ b/src/core/hle/service/psc/ovln/receiver.h
@@ -0,0 +1,16 @@
1// SPDX-FileCopyrightText: Copyright 2024 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-2.0-or-later
3
4#pragma once
5
6#include "core/hle/service/service.h"
7
8namespace Service::PSC {
9
10class IReceiver final : public ServiceFramework<IReceiver> {
11public:
12 explicit IReceiver(Core::System& system_);
13 ~IReceiver() override;
14};
15
16} // namespace Service::PSC
diff --git a/src/core/hle/service/psc/ovln/receiver_service.cpp b/src/core/hle/service/psc/ovln/receiver_service.cpp
new file mode 100644
index 000000000..bb988e905
--- /dev/null
+++ b/src/core/hle/service/psc/ovln/receiver_service.cpp
@@ -0,0 +1,28 @@
1// SPDX-FileCopyrightText: Copyright 2024 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-2.0-or-later
3
4#include "core/hle/service/cmif_serialization.h"
5#include "core/hle/service/psc/ovln/receiver.h"
6#include "core/hle/service/psc/ovln/receiver_service.h"
7
8namespace Service::PSC {
9
10IReceiverService::IReceiverService(Core::System& system_) : ServiceFramework{system_, "ovln:rcv"} {
11 // clang-format off
12 static const FunctionInfo functions[] = {
13 {0, D<&IReceiverService::OpenReceiver>, "OpenReceiver"},
14 };
15 // clang-format on
16
17 RegisterHandlers(functions);
18}
19
20IReceiverService::~IReceiverService() = default;
21
22Result IReceiverService::OpenReceiver(Out<SharedPointer<IReceiver>> out_receiver) {
23 LOG_DEBUG(Service_PSC, "called");
24 *out_receiver = std::make_shared<IReceiver>(system);
25 R_SUCCEED();
26}
27
28} // namespace Service::PSC
diff --git a/src/core/hle/service/psc/ovln/receiver_service.h b/src/core/hle/service/psc/ovln/receiver_service.h
new file mode 100644
index 000000000..b3b31ba4a
--- /dev/null
+++ b/src/core/hle/service/psc/ovln/receiver_service.h
@@ -0,0 +1,22 @@
1// SPDX-FileCopyrightText: Copyright 2024 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-2.0-or-later
3
4#pragma once
5
6#include "core/hle/service/cmif_types.h"
7#include "core/hle/service/service.h"
8
9namespace Service::PSC {
10
11class IReceiver;
12
13class IReceiverService final : public ServiceFramework<IReceiverService> {
14public:
15 explicit IReceiverService(Core::System& system_);
16 ~IReceiverService() override;
17
18private:
19 Result OpenReceiver(Out<SharedPointer<IReceiver>> out_receiver);
20};
21
22} // namespace Service::PSC
diff --git a/src/core/hle/service/psc/ovln/sender.cpp b/src/core/hle/service/psc/ovln/sender.cpp
new file mode 100644
index 000000000..3227a56f2
--- /dev/null
+++ b/src/core/hle/service/psc/ovln/sender.cpp
@@ -0,0 +1,32 @@
1// SPDX-FileCopyrightText: Copyright 2024 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-2.0-or-later
3
4#include "core/hle/service/cmif_serialization.h"
5#include "core/hle/service/psc/ovln/sender.h"
6
7namespace Service::PSC {
8
9ISender::ISender(Core::System& system_) : ServiceFramework{system_, "ISender"} {
10 // clang-format off
11 static const FunctionInfo functions[] = {
12 {0, D<&ISender::Send>, "Send"},
13 {1, nullptr, "GetUnreceivedMessageCount"},
14 };
15 // clang-format on
16
17 RegisterHandlers(functions);
18}
19
20ISender::~ISender() = default;
21
22Result ISender::Send(const OverlayNotification& notification, MessageFlags flags) {
23 std::string data;
24 for (const auto m : notification) {
25 data += fmt::format("{:016X} ", m);
26 }
27
28 LOG_WARNING(Service_PSC, "(STUBBED) called, flags={} notification={}", flags.raw, data);
29 R_SUCCEED();
30}
31
32} // namespace Service::PSC
diff --git a/src/core/hle/service/psc/ovln/sender.h b/src/core/hle/service/psc/ovln/sender.h
new file mode 100644
index 000000000..c1575428e
--- /dev/null
+++ b/src/core/hle/service/psc/ovln/sender.h
@@ -0,0 +1,21 @@
1// SPDX-FileCopyrightText: Copyright 2024 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-2.0-or-later
3
4#pragma once
5
6#include "core/hle/service/cmif_types.h"
7#include "core/hle/service/psc/ovln/ovln_types.h"
8#include "core/hle/service/service.h"
9
10namespace Service::PSC {
11
12class ISender final : public ServiceFramework<ISender> {
13public:
14 explicit ISender(Core::System& system_);
15 ~ISender() override;
16
17private:
18 Result Send(const OverlayNotification& notification, MessageFlags flags);
19};
20
21} // namespace Service::PSC
diff --git a/src/core/hle/service/psc/ovln/sender_service.cpp b/src/core/hle/service/psc/ovln/sender_service.cpp
new file mode 100644
index 000000000..18d2c83a3
--- /dev/null
+++ b/src/core/hle/service/psc/ovln/sender_service.cpp
@@ -0,0 +1,30 @@
1// SPDX-FileCopyrightText: Copyright 2024 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-2.0-or-later
3
4#include "core/hle/service/cmif_serialization.h"
5#include "core/hle/service/psc/ovln/sender.h"
6#include "core/hle/service/psc/ovln/sender_service.h"
7
8namespace Service::PSC {
9
10ISenderService::ISenderService(Core::System& system_) : ServiceFramework{system_, "ovln:snd"} {
11 // clang-format off
12 static const FunctionInfo functions[] = {
13 {0, D<&ISenderService::OpenSender>, "OpenSender"},
14 };
15 // clang-format on
16
17 RegisterHandlers(functions);
18}
19
20ISenderService::~ISenderService() = default;
21
22Result ISenderService::OpenSender(Out<SharedPointer<ISender>> out_sender, u32 sender_id,
23 std::array<u64, 2> data) {
24 LOG_WARNING(Service_PSC, "(STUBBED) called, sender_id={}, data={:016X} {:016X}", sender_id,
25 data[0], data[1]);
26 *out_sender = std::make_shared<ISender>(system);
27 R_SUCCEED();
28}
29
30} // namespace Service::PSC
diff --git a/src/core/hle/service/psc/ovln/sender_service.h b/src/core/hle/service/psc/ovln/sender_service.h
new file mode 100644
index 000000000..10027701f
--- /dev/null
+++ b/src/core/hle/service/psc/ovln/sender_service.h
@@ -0,0 +1,23 @@
1// SPDX-FileCopyrightText: Copyright 2024 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-2.0-or-later
3
4#pragma once
5
6#include "core/hle/service/cmif_types.h"
7#include "core/hle/service/service.h"
8
9namespace Service::PSC {
10
11class ISender;
12
13class ISenderService final : public ServiceFramework<ISenderService> {
14public:
15 explicit ISenderService(Core::System& system_);
16 ~ISenderService() override;
17
18private:
19 Result OpenSender(Out<SharedPointer<ISender>> out_sender, u32 sender_id,
20 std::array<u64, 2> data);
21};
22
23} // namespace Service::PSC
diff --git a/src/core/hle/service/psc/pm_control.cpp b/src/core/hle/service/psc/pm_control.cpp
new file mode 100644
index 000000000..7dedb7662
--- /dev/null
+++ b/src/core/hle/service/psc/pm_control.cpp
@@ -0,0 +1,28 @@
1// SPDX-FileCopyrightText: Copyright 2024 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-2.0-or-later
3
4#include "core/hle/service/psc/pm_control.h"
5
6namespace Service::PSC {
7
8IPmControl::IPmControl(Core::System& system_) : ServiceFramework{system_, "psc:c"} {
9 // clang-format off
10 static const FunctionInfo functions[] = {
11 {0, nullptr, "Initialize"},
12 {1, nullptr, "DispatchRequest"},
13 {2, nullptr, "GetResult"},
14 {3, nullptr, "GetState"},
15 {4, nullptr, "Cancel"},
16 {5, nullptr, "PrintModuleInformation"},
17 {6, nullptr, "GetModuleInformation"},
18 {10, nullptr, "AcquireStateLock"},
19 {11, nullptr, "HasStateLock"},
20 };
21 // clang-format on
22
23 RegisterHandlers(functions);
24}
25
26IPmControl::~IPmControl() = default;
27
28} // namespace Service::PSC
diff --git a/src/core/hle/service/psc/pm_control.h b/src/core/hle/service/psc/pm_control.h
new file mode 100644
index 000000000..e0ae2f39c
--- /dev/null
+++ b/src/core/hle/service/psc/pm_control.h
@@ -0,0 +1,16 @@
1// SPDX-FileCopyrightText: Copyright 2024 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-2.0-or-later
3
4#pragma once
5
6#include "core/hle/service/service.h"
7
8namespace Service::PSC {
9
10class IPmControl final : public ServiceFramework<IPmControl> {
11public:
12 explicit IPmControl(Core::System& system_);
13 ~IPmControl() override;
14};
15
16} // namespace Service::PSC
diff --git a/src/core/hle/service/psc/pm_module.cpp b/src/core/hle/service/psc/pm_module.cpp
new file mode 100644
index 000000000..74dc7ed4e
--- /dev/null
+++ b/src/core/hle/service/psc/pm_module.cpp
@@ -0,0 +1,24 @@
1// SPDX-FileCopyrightText: Copyright 2024 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-2.0-or-later
3
4#include "core/hle/service/psc/pm_module.h"
5
6namespace Service::PSC {
7
8IPmModule::IPmModule(Core::System& system_) : ServiceFramework{system_, "IPmModule"} {
9 // clang-format off
10 static const FunctionInfo functions[] = {
11 {0, nullptr, "Initialize"},
12 {1, nullptr, "GetRequest"},
13 {2, nullptr, "Acknowledge"},
14 {3, nullptr, "Finalize"},
15 {4, nullptr, "AcknowledgeEx"},
16 };
17 // clang-format on
18
19 RegisterHandlers(functions);
20}
21
22IPmModule::~IPmModule() = default;
23
24} // namespace Service::PSC
diff --git a/src/core/hle/service/psc/pm_module.h b/src/core/hle/service/psc/pm_module.h
new file mode 100644
index 000000000..b3a2d2584
--- /dev/null
+++ b/src/core/hle/service/psc/pm_module.h
@@ -0,0 +1,16 @@
1// SPDX-FileCopyrightText: Copyright 2024 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-2.0-or-later
3
4#pragma once
5
6#include "core/hle/service/service.h"
7
8namespace Service::PSC {
9
10class IPmModule final : public ServiceFramework<IPmModule> {
11public:
12 explicit IPmModule(Core::System& system_);
13 ~IPmModule() override;
14};
15
16} // namespace Service::PSC
diff --git a/src/core/hle/service/psc/pm_service.cpp b/src/core/hle/service/psc/pm_service.cpp
new file mode 100644
index 000000000..c4e0ad228
--- /dev/null
+++ b/src/core/hle/service/psc/pm_service.cpp
@@ -0,0 +1,28 @@
1// SPDX-FileCopyrightText: Copyright 2024 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-2.0-or-later
3
4#include "core/hle/service/cmif_serialization.h"
5#include "core/hle/service/psc/pm_module.h"
6#include "core/hle/service/psc/pm_service.h"
7
8namespace Service::PSC {
9
10IPmService::IPmService(Core::System& system_) : ServiceFramework{system_, "psc:m"} {
11 // clang-format off
12 static const FunctionInfo functions[] = {
13 {0, D<&IPmService::GetPmModule>, "GetPmModule"},
14 };
15 // clang-format on
16
17 RegisterHandlers(functions);
18}
19
20IPmService::~IPmService() = default;
21
22Result IPmService::GetPmModule(Out<SharedPointer<IPmModule>> out_module) {
23 LOG_DEBUG(Service_PSC, "called");
24 *out_module = std::make_shared<IPmModule>(system);
25 R_SUCCEED();
26}
27
28} // namespace Service::PSC
diff --git a/src/core/hle/service/psc/pm_service.h b/src/core/hle/service/psc/pm_service.h
new file mode 100644
index 000000000..08e14c6f8
--- /dev/null
+++ b/src/core/hle/service/psc/pm_service.h
@@ -0,0 +1,22 @@
1// SPDX-FileCopyrightText: Copyright 2024 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-2.0-or-later
3
4#pragma once
5
6#include "core/hle/service/cmif_types.h"
7#include "core/hle/service/service.h"
8
9namespace Service::PSC {
10
11class IPmModule;
12
13class IPmService final : public ServiceFramework<IPmService> {
14public:
15 explicit IPmService(Core::System& system_);
16 ~IPmService() override;
17
18private:
19 Result GetPmModule(Out<SharedPointer<IPmModule>> out_module);
20};
21
22} // namespace Service::PSC
diff --git a/src/core/hle/service/psc/psc.cpp b/src/core/hle/service/psc/psc.cpp
index 44310756b..e1762d694 100644
--- a/src/core/hle/service/psc/psc.cpp
+++ b/src/core/hle/service/psc/psc.cpp
@@ -1,11 +1,10 @@
1// SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project 1// SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-2.0-or-later 2// SPDX-License-Identifier: GPL-2.0-or-later
3 3
4#include <memory> 4#include "core/hle/service/psc/ovln/receiver_service.h"
5 5#include "core/hle/service/psc/ovln/sender_service.h"
6#include "common/logging/log.h" 6#include "core/hle/service/psc/pm_control.h"
7#include "core/core.h" 7#include "core/hle/service/psc/pm_service.h"
8#include "core/hle/service/ipc_helpers.h"
9#include "core/hle/service/psc/psc.h" 8#include "core/hle/service/psc/psc.h"
10#include "core/hle/service/psc/time/manager.h" 9#include "core/hle/service/psc/time/manager.h"
11#include "core/hle/service/psc/time/power_state_service.h" 10#include "core/hle/service/psc/time/power_state_service.h"
@@ -15,71 +14,13 @@
15 14
16namespace Service::PSC { 15namespace Service::PSC {
17 16
18class IPmControl final : public ServiceFramework<IPmControl> {
19public:
20 explicit IPmControl(Core::System& system_) : ServiceFramework{system_, "psc:c"} {
21 // clang-format off
22 static const FunctionInfo functions[] = {
23 {0, nullptr, "Initialize"},
24 {1, nullptr, "DispatchRequest"},
25 {2, nullptr, "GetResult"},
26 {3, nullptr, "GetState"},
27 {4, nullptr, "Cancel"},
28 {5, nullptr, "PrintModuleInformation"},
29 {6, nullptr, "GetModuleInformation"},
30 {10, nullptr, "AcquireStateLock"},
31 {11, nullptr, "HasStateLock"},
32 };
33 // clang-format on
34
35 RegisterHandlers(functions);
36 }
37};
38
39class IPmModule final : public ServiceFramework<IPmModule> {
40public:
41 explicit IPmModule(Core::System& system_) : ServiceFramework{system_, "IPmModule"} {
42 // clang-format off
43 static const FunctionInfo functions[] = {
44 {0, nullptr, "Initialize"},
45 {1, nullptr, "GetRequest"},
46 {2, nullptr, "Acknowledge"},
47 {3, nullptr, "Finalize"},
48 {4, nullptr, "AcknowledgeEx"},
49 };
50 // clang-format on
51
52 RegisterHandlers(functions);
53 }
54};
55
56class IPmService final : public ServiceFramework<IPmService> {
57public:
58 explicit IPmService(Core::System& system_) : ServiceFramework{system_, "psc:m"} {
59 // clang-format off
60 static const FunctionInfo functions[] = {
61 {0, &IPmService::GetPmModule, "GetPmModule"},
62 };
63 // clang-format on
64
65 RegisterHandlers(functions);
66 }
67
68private:
69 void GetPmModule(HLERequestContext& ctx) {
70 LOG_DEBUG(Service_PSC, "called");
71
72 IPC::ResponseBuilder rb{ctx, 2, 0, 1};
73 rb.Push(ResultSuccess);
74 rb.PushIpcInterface<IPmModule>(system);
75 }
76};
77
78void LoopProcess(Core::System& system) { 17void LoopProcess(Core::System& system) {
79 auto server_manager = std::make_unique<ServerManager>(system); 18 auto server_manager = std::make_unique<ServerManager>(system);
80 19
81 server_manager->RegisterNamedService("psc:c", std::make_shared<IPmControl>(system)); 20 server_manager->RegisterNamedService("psc:c", std::make_shared<IPmControl>(system));
82 server_manager->RegisterNamedService("psc:m", std::make_shared<IPmService>(system)); 21 server_manager->RegisterNamedService("psc:m", std::make_shared<IPmService>(system));
22 server_manager->RegisterNamedService("ovln:rcv", std::make_shared<IReceiverService>(system));
23 server_manager->RegisterNamedService("ovln:snd", std::make_shared<ISenderService>(system));
83 24
84 auto time = std::make_shared<Time::TimeManager>(system); 25 auto time = std::make_shared<Time::TimeManager>(system);
85 26
diff --git a/src/core/hle/service/psc/psc.h b/src/core/hle/service/psc/psc.h
index 459137f42..c83d07ca8 100644
--- a/src/core/hle/service/psc/psc.h
+++ b/src/core/hle/service/psc/psc.h
@@ -7,10 +7,6 @@ namespace Core {
7class System; 7class System;
8} 8}
9 9
10namespace Service::SM {
11class ServiceManager;
12}
13
14namespace Service::PSC { 10namespace Service::PSC {
15 11
16void LoopProcess(Core::System& system); 12void LoopProcess(Core::System& system);
diff --git a/src/core/hle/service/vi/container.cpp b/src/core/hle/service/vi/container.cpp
index 310a207f1..9074f4ae0 100644
--- a/src/core/hle/service/vi/container.cpp
+++ b/src/core/hle/service/vi/container.cpp
@@ -43,11 +43,7 @@ void Container::OnTerminate() {
43 43
44 m_is_shut_down = true; 44 m_is_shut_down = true;
45 45
46 m_layers.ForEachLayer([&](auto& layer) { 46 m_layers.ForEachLayer([&](auto& layer) { this->DestroyLayerLocked(layer.GetId()); });
47 if (layer.IsOpen()) {
48 this->DestroyBufferQueueLocked(&layer);
49 }
50 });
51 47
52 m_displays.ForEachDisplay( 48 m_displays.ForEachDisplay(
53 [&](auto& display) { m_surface_flinger->RemoveDisplay(display.GetId()); }); 49 [&](auto& display) { m_surface_flinger->RemoveDisplay(display.GetId()); });
@@ -161,16 +157,29 @@ Result Container::CreateLayerLocked(u64* out_layer_id, u64 display_id, u64 owner
161 auto* const display = m_displays.GetDisplayById(display_id); 157 auto* const display = m_displays.GetDisplayById(display_id);
162 R_UNLESS(display != nullptr, VI::ResultNotFound); 158 R_UNLESS(display != nullptr, VI::ResultNotFound);
163 159
164 auto* const layer = m_layers.CreateLayer(owner_aruid, display); 160 s32 consumer_binder_id, producer_binder_id;
161 m_surface_flinger->CreateBufferQueue(&consumer_binder_id, &producer_binder_id);
162
163 auto* const layer =
164 m_layers.CreateLayer(owner_aruid, display, consumer_binder_id, producer_binder_id);
165 R_UNLESS(layer != nullptr, VI::ResultNotFound); 165 R_UNLESS(layer != nullptr, VI::ResultNotFound);
166 166
167 m_surface_flinger->CreateLayer(consumer_binder_id);
168
167 *out_layer_id = layer->GetId(); 169 *out_layer_id = layer->GetId();
168 R_SUCCEED(); 170 R_SUCCEED();
169} 171}
170 172
171Result Container::DestroyLayerLocked(u64 layer_id) { 173Result Container::DestroyLayerLocked(u64 layer_id) {
172 R_SUCCEED_IF(m_layers.DestroyLayer(layer_id)); 174 auto* const layer = m_layers.GetLayerById(layer_id);
173 R_THROW(VI::ResultNotFound); 175 R_UNLESS(layer != nullptr, VI::ResultNotFound);
176
177 m_surface_flinger->DestroyLayer(layer->GetConsumerBinderId());
178 m_surface_flinger->DestroyBufferQueue(layer->GetConsumerBinderId(),
179 layer->GetProducerBinderId());
180 m_layers.DestroyLayer(layer_id);
181
182 R_SUCCEED();
174} 183}
175 184
176Result Container::OpenLayerLocked(s32* out_producer_binder_id, u64 layer_id, u64 aruid) { 185Result Container::OpenLayerLocked(s32* out_producer_binder_id, u64 layer_id, u64 aruid) {
@@ -181,7 +190,12 @@ Result Container::OpenLayerLocked(s32* out_producer_binder_id, u64 layer_id, u64
181 R_UNLESS(!layer->IsOpen(), VI::ResultOperationFailed); 190 R_UNLESS(!layer->IsOpen(), VI::ResultOperationFailed);
182 R_UNLESS(layer->GetOwnerAruid() == aruid, VI::ResultPermissionDenied); 191 R_UNLESS(layer->GetOwnerAruid() == aruid, VI::ResultPermissionDenied);
183 192
184 this->CreateBufferQueueLocked(layer); 193 layer->Open();
194
195 if (auto* display = layer->GetDisplay(); display != nullptr) {
196 m_surface_flinger->AddLayerToDisplayStack(display->GetId(), layer->GetConsumerBinderId());
197 }
198
185 *out_producer_binder_id = layer->GetProducerBinderId(); 199 *out_producer_binder_id = layer->GetProducerBinderId();
186 200
187 R_SUCCEED(); 201 R_SUCCEED();
@@ -192,30 +206,14 @@ Result Container::CloseLayerLocked(u64 layer_id) {
192 R_UNLESS(layer != nullptr, VI::ResultNotFound); 206 R_UNLESS(layer != nullptr, VI::ResultNotFound);
193 R_UNLESS(layer->IsOpen(), VI::ResultOperationFailed); 207 R_UNLESS(layer->IsOpen(), VI::ResultOperationFailed);
194 208
195 this->DestroyBufferQueueLocked(layer);
196
197 R_SUCCEED();
198}
199
200void Container::CreateBufferQueueLocked(Layer* layer) {
201 s32 consumer_binder_id, producer_binder_id;
202 m_surface_flinger->CreateBufferQueue(&consumer_binder_id, &producer_binder_id);
203 layer->Open(consumer_binder_id, producer_binder_id);
204
205 if (auto* display = layer->GetDisplay(); display != nullptr) {
206 m_surface_flinger->AddLayerToDisplayStack(display->GetId(), consumer_binder_id);
207 }
208}
209
210void Container::DestroyBufferQueueLocked(Layer* layer) {
211 if (auto* display = layer->GetDisplay(); display != nullptr) { 209 if (auto* display = layer->GetDisplay(); display != nullptr) {
212 m_surface_flinger->RemoveLayerFromDisplayStack(display->GetId(), 210 m_surface_flinger->RemoveLayerFromDisplayStack(display->GetId(),
213 layer->GetConsumerBinderId()); 211 layer->GetConsumerBinderId());
214 } 212 }
215 213
216 layer->Close(); 214 layer->Close();
217 m_surface_flinger->DestroyBufferQueue(layer->GetConsumerBinderId(), 215
218 layer->GetProducerBinderId()); 216 R_SUCCEED();
219} 217}
220 218
221bool Container::ComposeOnDisplay(s32* out_swap_interval, f32* out_compose_speed_scale, 219bool Container::ComposeOnDisplay(s32* out_swap_interval, f32* out_compose_speed_scale,
diff --git a/src/core/hle/service/vi/container.h b/src/core/hle/service/vi/container.h
index cd0d2ca86..5eac4d77d 100644
--- a/src/core/hle/service/vi/container.h
+++ b/src/core/hle/service/vi/container.h
@@ -72,9 +72,6 @@ private:
72 Result OpenLayerLocked(s32* out_producer_binder_id, u64 layer_id, u64 aruid); 72 Result OpenLayerLocked(s32* out_producer_binder_id, u64 layer_id, u64 aruid);
73 Result CloseLayerLocked(u64 layer_id); 73 Result CloseLayerLocked(u64 layer_id);
74 74
75 void CreateBufferQueueLocked(Layer* layer);
76 void DestroyBufferQueueLocked(Layer* layer);
77
78public: 75public:
79 bool ComposeOnDisplay(s32* out_swap_interval, f32* out_compose_speed_scale, u64 display_id); 76 bool ComposeOnDisplay(s32* out_swap_interval, f32* out_compose_speed_scale, u64 display_id);
80 77
diff --git a/src/core/hle/service/vi/layer.h b/src/core/hle/service/vi/layer.h
index b85c8df61..e4c9c9864 100644
--- a/src/core/hle/service/vi/layer.h
+++ b/src/core/hle/service/vi/layer.h
@@ -13,29 +13,31 @@ class Layer {
13public: 13public:
14 constexpr Layer() = default; 14 constexpr Layer() = default;
15 15
16 void Initialize(u64 id, u64 owner_aruid, Display* display) { 16 void Initialize(u64 id, u64 owner_aruid, Display* display, s32 consumer_binder_id,
17 s32 producer_binder_id) {
17 m_id = id; 18 m_id = id;
18 m_owner_aruid = owner_aruid; 19 m_owner_aruid = owner_aruid;
19 m_display = display; 20 m_display = display;
21 m_consumer_binder_id = consumer_binder_id;
22 m_producer_binder_id = producer_binder_id;
20 m_is_initialized = true; 23 m_is_initialized = true;
21 } 24 }
22 25
23 void Finalize() { 26 void Finalize() {
24 m_id = {}; 27 m_id = {};
28 m_owner_aruid = {};
25 m_display = {}; 29 m_display = {};
30 m_consumer_binder_id = {};
31 m_producer_binder_id = {};
26 m_is_initialized = {}; 32 m_is_initialized = {};
27 } 33 }
28 34
29 void Open(s32 consumer_binder_id, s32 producer_binder_id) { 35 void Open() {
30 m_consumer_binder_id = consumer_binder_id;
31 m_producer_binder_id = producer_binder_id;
32 m_is_open = true; 36 m_is_open = true;
33 } 37 }
34 38
35 void Close() { 39 void Close() {
36 m_producer_binder_id = {}; 40 m_is_open = false;
37 m_consumer_binder_id = {};
38 m_is_open = {};
39 } 41 }
40 42
41 u64 GetId() const { 43 u64 GetId() const {
diff --git a/src/core/hle/service/vi/layer_list.h b/src/core/hle/service/vi/layer_list.h
index 1738ede9a..4afca6f40 100644
--- a/src/core/hle/service/vi/layer_list.h
+++ b/src/core/hle/service/vi/layer_list.h
@@ -11,13 +11,15 @@ class LayerList {
11public: 11public:
12 constexpr LayerList() = default; 12 constexpr LayerList() = default;
13 13
14 Layer* CreateLayer(u64 owner_aruid, Display* display) { 14 Layer* CreateLayer(u64 owner_aruid, Display* display, s32 consumer_binder_id,
15 s32 producer_binder_id) {
15 Layer* const layer = GetFreeLayer(); 16 Layer* const layer = GetFreeLayer();
16 if (!layer) { 17 if (!layer) {
17 return nullptr; 18 return nullptr;
18 } 19 }
19 20
20 layer->Initialize(++m_next_id, owner_aruid, display); 21 layer->Initialize(++m_next_id, owner_aruid, display, consumer_binder_id,
22 producer_binder_id);
21 return layer; 23 return layer;
22 } 24 }
23 25
diff --git a/src/core/hle/service/vi/shared_buffer_manager.cpp b/src/core/hle/service/vi/shared_buffer_manager.cpp
index 869b18961..12cba16fa 100644
--- a/src/core/hle/service/vi/shared_buffer_manager.cpp
+++ b/src/core/hle/service/vi/shared_buffer_manager.cpp
@@ -285,7 +285,7 @@ void SharedBufferManager::DestroySession(Kernel::KProcess* owner_process) {
285 auto& session = it->second; 285 auto& session = it->second;
286 286
287 // Destroy the layer. 287 // Destroy the layer.
288 R_ASSERT(m_container.DestroyStrayLayer(session.layer_id)); 288 m_container.DestroyStrayLayer(session.layer_id);
289 289
290 // Close nvmap handle. 290 // Close nvmap handle.
291 FreeHandle(session.buffer_nvmap_handle, *m_nvdrv, session.nvmap_fd); 291 FreeHandle(session.buffer_nvmap_handle, *m_nvdrv, session.nvmap_fd);
@@ -322,8 +322,6 @@ Result SharedBufferManager::GetSharedBufferMemoryHandleId(u64* out_buffer_size,
322Result SharedBufferManager::AcquireSharedFrameBuffer(android::Fence* out_fence, 322Result SharedBufferManager::AcquireSharedFrameBuffer(android::Fence* out_fence,
323 std::array<s32, 4>& out_slot_indexes, 323 std::array<s32, 4>& out_slot_indexes,
324 s64* out_target_slot, u64 layer_id) { 324 s64* out_target_slot, u64 layer_id) {
325 std::scoped_lock lk{m_guard};
326
327 // Get the producer. 325 // Get the producer.
328 std::shared_ptr<android::BufferQueueProducer> producer; 326 std::shared_ptr<android::BufferQueueProducer> producer;
329 R_TRY(m_container.GetLayerProducerHandle(std::addressof(producer), layer_id)); 327 R_TRY(m_container.GetLayerProducerHandle(std::addressof(producer), layer_id));
@@ -347,8 +345,6 @@ Result SharedBufferManager::PresentSharedFrameBuffer(android::Fence fence,
347 Common::Rectangle<s32> crop_region, 345 Common::Rectangle<s32> crop_region,
348 u32 transform, s32 swap_interval, u64 layer_id, 346 u32 transform, s32 swap_interval, u64 layer_id,
349 s64 slot) { 347 s64 slot) {
350 std::scoped_lock lk{m_guard};
351
352 // Get the producer. 348 // Get the producer.
353 std::shared_ptr<android::BufferQueueProducer> producer; 349 std::shared_ptr<android::BufferQueueProducer> producer;
354 R_TRY(m_container.GetLayerProducerHandle(std::addressof(producer), layer_id)); 350 R_TRY(m_container.GetLayerProducerHandle(std::addressof(producer), layer_id));
@@ -379,8 +375,6 @@ Result SharedBufferManager::PresentSharedFrameBuffer(android::Fence fence,
379} 375}
380 376
381Result SharedBufferManager::CancelSharedFrameBuffer(u64 layer_id, s64 slot) { 377Result SharedBufferManager::CancelSharedFrameBuffer(u64 layer_id, s64 slot) {
382 std::scoped_lock lk{m_guard};
383
384 // Get the producer. 378 // Get the producer.
385 std::shared_ptr<android::BufferQueueProducer> producer; 379 std::shared_ptr<android::BufferQueueProducer> producer;
386 R_TRY(m_container.GetLayerProducerHandle(std::addressof(producer), layer_id)); 380 R_TRY(m_container.GetLayerProducerHandle(std::addressof(producer), layer_id));
@@ -394,8 +388,6 @@ Result SharedBufferManager::CancelSharedFrameBuffer(u64 layer_id, s64 slot) {
394 388
395Result SharedBufferManager::GetSharedFrameBufferAcquirableEvent(Kernel::KReadableEvent** out_event, 389Result SharedBufferManager::GetSharedFrameBufferAcquirableEvent(Kernel::KReadableEvent** out_event,
396 u64 layer_id) { 390 u64 layer_id) {
397 std::scoped_lock lk{m_guard};
398
399 // Get the producer. 391 // Get the producer.
400 std::shared_ptr<android::BufferQueueProducer> producer; 392 std::shared_ptr<android::BufferQueueProducer> producer;
401 R_TRY(m_container.GetLayerProducerHandle(std::addressof(producer), layer_id)); 393 R_TRY(m_container.GetLayerProducerHandle(std::addressof(producer), layer_id));
diff --git a/src/shader_recompiler/backend/spirv/emit_spirv.cpp b/src/shader_recompiler/backend/spirv/emit_spirv.cpp
index 0031fa5fb..3f9698d6b 100644
--- a/src/shader_recompiler/backend/spirv/emit_spirv.cpp
+++ b/src/shader_recompiler/backend/spirv/emit_spirv.cpp
@@ -261,7 +261,9 @@ void DefineEntryPoint(const IR::Program& program, EmitContext& ctx, Id main) {
261 case Stage::Geometry: 261 case Stage::Geometry:
262 execution_model = spv::ExecutionModel::Geometry; 262 execution_model = spv::ExecutionModel::Geometry;
263 ctx.AddCapability(spv::Capability::Geometry); 263 ctx.AddCapability(spv::Capability::Geometry);
264 ctx.AddCapability(spv::Capability::GeometryStreams); 264 if (ctx.profile.support_geometry_streams) {
265 ctx.AddCapability(spv::Capability::GeometryStreams);
266 }
265 switch (ctx.runtime_info.input_topology) { 267 switch (ctx.runtime_info.input_topology) {
266 case InputTopology::Points: 268 case InputTopology::Points:
267 ctx.AddExecutionMode(main, spv::ExecutionMode::InputPoints); 269 ctx.AddExecutionMode(main, spv::ExecutionMode::InputPoints);
diff --git a/src/shader_recompiler/backend/spirv/emit_spirv_special.cpp b/src/shader_recompiler/backend/spirv/emit_spirv_special.cpp
index 9f7b6bb4b..f60da758e 100644
--- a/src/shader_recompiler/backend/spirv/emit_spirv_special.cpp
+++ b/src/shader_recompiler/backend/spirv/emit_spirv_special.cpp
@@ -129,7 +129,9 @@ void EmitEmitVertex(EmitContext& ctx, const IR::Value& stream) {
129 if (ctx.runtime_info.convert_depth_mode && !ctx.profile.support_native_ndc) { 129 if (ctx.runtime_info.convert_depth_mode && !ctx.profile.support_native_ndc) {
130 ConvertDepthMode(ctx); 130 ConvertDepthMode(ctx);
131 } 131 }
132 if (stream.IsImmediate()) { 132 if (!ctx.profile.support_geometry_streams) {
133 throw NotImplementedException("Geometry streams");
134 } else if (stream.IsImmediate()) {
133 ctx.OpEmitStreamVertex(ctx.Def(stream)); 135 ctx.OpEmitStreamVertex(ctx.Def(stream));
134 } else { 136 } else {
135 LOG_WARNING(Shader_SPIRV, "Stream is not immediate"); 137 LOG_WARNING(Shader_SPIRV, "Stream is not immediate");
@@ -140,7 +142,9 @@ void EmitEmitVertex(EmitContext& ctx, const IR::Value& stream) {
140} 142}
141 143
142void EmitEndPrimitive(EmitContext& ctx, const IR::Value& stream) { 144void EmitEndPrimitive(EmitContext& ctx, const IR::Value& stream) {
143 if (stream.IsImmediate()) { 145 if (!ctx.profile.support_geometry_streams) {
146 throw NotImplementedException("Geometry streams");
147 } else if (stream.IsImmediate()) {
144 ctx.OpEndStreamPrimitive(ctx.Def(stream)); 148 ctx.OpEndStreamPrimitive(ctx.Def(stream));
145 } else { 149 } else {
146 LOG_WARNING(Shader_SPIRV, "Stream is not immediate"); 150 LOG_WARNING(Shader_SPIRV, "Stream is not immediate");
diff --git a/src/shader_recompiler/profile.h b/src/shader_recompiler/profile.h
index 7578d41cc..90e46bb1b 100644
--- a/src/shader_recompiler/profile.h
+++ b/src/shader_recompiler/profile.h
@@ -44,6 +44,7 @@ struct Profile {
44 bool support_gl_derivative_control{}; 44 bool support_gl_derivative_control{};
45 bool support_scaled_attributes{}; 45 bool support_scaled_attributes{};
46 bool support_multi_viewport{}; 46 bool support_multi_viewport{};
47 bool support_geometry_streams{};
47 48
48 bool warp_size_potentially_larger_than_guest{}; 49 bool warp_size_potentially_larger_than_guest{};
49 50
diff --git a/src/video_core/buffer_cache/buffer_cache.h b/src/video_core/buffer_cache/buffer_cache.h
index 296c90e85..ed7a5b27e 100644
--- a/src/video_core/buffer_cache/buffer_cache.h
+++ b/src/video_core/buffer_cache/buffer_cache.h
@@ -35,7 +35,7 @@ BufferCache<P>::BufferCache(Tegra::MaxwellDeviceMemoryManager& device_memory_, R
35 const s64 min_spacing_critical = device_local_memory - 512_MiB; 35 const s64 min_spacing_critical = device_local_memory - 512_MiB;
36 const s64 mem_threshold = std::min(device_local_memory, TARGET_THRESHOLD); 36 const s64 mem_threshold = std::min(device_local_memory, TARGET_THRESHOLD);
37 const s64 min_vacancy_expected = (6 * mem_threshold) / 10; 37 const s64 min_vacancy_expected = (6 * mem_threshold) / 10;
38 const s64 min_vacancy_critical = (3 * mem_threshold) / 10; 38 const s64 min_vacancy_critical = (2 * mem_threshold) / 10;
39 minimum_memory = static_cast<u64>( 39 minimum_memory = static_cast<u64>(
40 std::max(std::min(device_local_memory - min_vacancy_expected, min_spacing_expected), 40 std::max(std::min(device_local_memory - min_vacancy_expected, min_spacing_expected),
41 DEFAULT_EXPECTED_MEMORY)); 41 DEFAULT_EXPECTED_MEMORY));
diff --git a/src/video_core/renderer_vulkan/vk_pipeline_cache.cpp b/src/video_core/renderer_vulkan/vk_pipeline_cache.cpp
index 20f7a9702..d34b585d6 100644
--- a/src/video_core/renderer_vulkan/vk_pipeline_cache.cpp
+++ b/src/video_core/renderer_vulkan/vk_pipeline_cache.cpp
@@ -352,6 +352,7 @@ PipelineCache::PipelineCache(Tegra::MaxwellDeviceMemoryManager& device_memory_,
352 .support_native_ndc = device.IsExtDepthClipControlSupported(), 352 .support_native_ndc = device.IsExtDepthClipControlSupported(),
353 .support_scaled_attributes = !device.MustEmulateScaledFormats(), 353 .support_scaled_attributes = !device.MustEmulateScaledFormats(),
354 .support_multi_viewport = device.SupportsMultiViewport(), 354 .support_multi_viewport = device.SupportsMultiViewport(),
355 .support_geometry_streams = device.AreTransformFeedbackGeometryStreamsSupported(),
355 356
356 .warp_size_potentially_larger_than_guest = device.IsWarpSizePotentiallyBiggerThanGuest(), 357 .warp_size_potentially_larger_than_guest = device.IsWarpSizePotentiallyBiggerThanGuest(),
357 358
diff --git a/src/video_core/surface.cpp b/src/video_core/surface.cpp
index 5b3c7aa5a..9055b1b92 100644
--- a/src/video_core/surface.cpp
+++ b/src/video_core/surface.cpp
@@ -3,6 +3,7 @@
3 3
4#include "common/common_types.h" 4#include "common/common_types.h"
5#include "common/math_util.h" 5#include "common/math_util.h"
6#include "common/settings.h"
6#include "video_core/surface.h" 7#include "video_core/surface.h"
7 8
8namespace VideoCore::Surface { 9namespace VideoCore::Surface {
@@ -400,11 +401,20 @@ std::pair<u32, u32> GetASTCBlockSize(PixelFormat format) {
400 return {DefaultBlockWidth(format), DefaultBlockHeight(format)}; 401 return {DefaultBlockWidth(format), DefaultBlockHeight(format)};
401} 402}
402 403
403u64 EstimatedDecompressedSize(u64 base_size, PixelFormat format) { 404u64 TranscodedAstcSize(u64 base_size, PixelFormat format) {
404 constexpr u64 RGBA8_PIXEL_SIZE = 4; 405 constexpr u64 RGBA8_PIXEL_SIZE = 4;
405 const u64 base_block_size = static_cast<u64>(DefaultBlockWidth(format)) * 406 const u64 base_block_size = static_cast<u64>(DefaultBlockWidth(format)) *
406 static_cast<u64>(DefaultBlockHeight(format)) * RGBA8_PIXEL_SIZE; 407 static_cast<u64>(DefaultBlockHeight(format)) * RGBA8_PIXEL_SIZE;
407 return (base_size * base_block_size) / BytesPerBlock(format); 408 const u64 uncompressed_size = (base_size * base_block_size) / BytesPerBlock(format);
409
410 switch (Settings::values.astc_recompression.GetValue()) {
411 case Settings::AstcRecompression::Bc1:
412 return uncompressed_size / 8;
413 case Settings::AstcRecompression::Bc3:
414 return uncompressed_size / 4;
415 default:
416 return uncompressed_size;
417 }
408} 418}
409 419
410} // namespace VideoCore::Surface 420} // namespace VideoCore::Surface
diff --git a/src/video_core/surface.h b/src/video_core/surface.h
index a5e8e2f62..ec9cd2fbf 100644
--- a/src/video_core/surface.h
+++ b/src/video_core/surface.h
@@ -517,6 +517,6 @@ size_t PixelComponentSizeBitsInteger(PixelFormat format);
517 517
518std::pair<u32, u32> GetASTCBlockSize(PixelFormat format); 518std::pair<u32, u32> GetASTCBlockSize(PixelFormat format);
519 519
520u64 EstimatedDecompressedSize(u64 base_size, PixelFormat format); 520u64 TranscodedAstcSize(u64 base_size, PixelFormat format);
521 521
522} // namespace VideoCore::Surface 522} // namespace VideoCore::Surface
diff --git a/src/video_core/texture_cache/texture_cache.h b/src/video_core/texture_cache/texture_cache.h
index 01c3561c9..53b4876f2 100644
--- a/src/video_core/texture_cache/texture_cache.h
+++ b/src/video_core/texture_cache/texture_cache.h
@@ -55,7 +55,7 @@ TextureCache<P>::TextureCache(Runtime& runtime_, Tegra::MaxwellDeviceMemoryManag
55 const s64 min_spacing_critical = device_local_memory - 512_MiB; 55 const s64 min_spacing_critical = device_local_memory - 512_MiB;
56 const s64 mem_threshold = std::min(device_local_memory, TARGET_THRESHOLD); 56 const s64 mem_threshold = std::min(device_local_memory, TARGET_THRESHOLD);
57 const s64 min_vacancy_expected = (6 * mem_threshold) / 10; 57 const s64 min_vacancy_expected = (6 * mem_threshold) / 10;
58 const s64 min_vacancy_critical = (3 * mem_threshold) / 10; 58 const s64 min_vacancy_critical = (2 * mem_threshold) / 10;
59 expected_memory = static_cast<u64>( 59 expected_memory = static_cast<u64>(
60 std::max(std::min(device_local_memory - min_vacancy_expected, min_spacing_expected), 60 std::max(std::min(device_local_memory - min_vacancy_expected, min_spacing_expected),
61 DEFAULT_EXPECTED_MEMORY)); 61 DEFAULT_EXPECTED_MEMORY));
@@ -1979,7 +1979,7 @@ void TextureCache<P>::RegisterImage(ImageId image_id) {
1979 if ((IsPixelFormatASTC(image.info.format) && 1979 if ((IsPixelFormatASTC(image.info.format) &&
1980 True(image.flags & ImageFlagBits::AcceleratedUpload)) || 1980 True(image.flags & ImageFlagBits::AcceleratedUpload)) ||
1981 True(image.flags & ImageFlagBits::Converted)) { 1981 True(image.flags & ImageFlagBits::Converted)) {
1982 tentative_size = EstimatedDecompressedSize(tentative_size, image.info.format); 1982 tentative_size = TranscodedAstcSize(tentative_size, image.info.format);
1983 } 1983 }
1984 total_used_memory += Common::AlignUp(tentative_size, 1024); 1984 total_used_memory += Common::AlignUp(tentative_size, 1024);
1985 image.lru_index = lru_cache.Insert(image_id, frame_tick); 1985 image.lru_index = lru_cache.Insert(image_id, frame_tick);
@@ -2149,7 +2149,7 @@ void TextureCache<P>::DeleteImage(ImageId image_id, bool immediate_delete) {
2149 if ((IsPixelFormatASTC(image.info.format) && 2149 if ((IsPixelFormatASTC(image.info.format) &&
2150 True(image.flags & ImageFlagBits::AcceleratedUpload)) || 2150 True(image.flags & ImageFlagBits::AcceleratedUpload)) ||
2151 True(image.flags & ImageFlagBits::Converted)) { 2151 True(image.flags & ImageFlagBits::Converted)) {
2152 tentative_size = EstimatedDecompressedSize(tentative_size, image.info.format); 2152 tentative_size = TranscodedAstcSize(tentative_size, image.info.format);
2153 } 2153 }
2154 total_used_memory -= Common::AlignUp(tentative_size, 1024); 2154 total_used_memory -= Common::AlignUp(tentative_size, 1024);
2155 const GPUVAddr gpu_addr = image.gpu_addr; 2155 const GPUVAddr gpu_addr = image.gpu_addr;
diff --git a/src/video_core/vulkan_common/vulkan_device.cpp b/src/video_core/vulkan_common/vulkan_device.cpp
index d7216d349..b94924a58 100644
--- a/src/video_core/vulkan_common/vulkan_device.cpp
+++ b/src/video_core/vulkan_common/vulkan_device.cpp
@@ -1297,10 +1297,6 @@ u64 Device::GetDeviceMemoryUsage() const {
1297} 1297}
1298 1298
1299void Device::CollectPhysicalMemoryInfo() { 1299void Device::CollectPhysicalMemoryInfo() {
1300 // Account for resolution scaling in memory limits
1301 const size_t normal_memory = 6_GiB;
1302 const size_t scaler_memory = 1_GiB * Settings::values.resolution_info.ScaleUp(1);
1303
1304 // Calculate limits using memory budget 1300 // Calculate limits using memory budget
1305 VkPhysicalDeviceMemoryBudgetPropertiesEXT budget{}; 1301 VkPhysicalDeviceMemoryBudgetPropertiesEXT budget{};
1306 budget.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_BUDGET_PROPERTIES_EXT; 1302 budget.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_BUDGET_PROPERTIES_EXT;
@@ -1331,7 +1327,15 @@ void Device::CollectPhysicalMemoryInfo() {
1331 if (!is_integrated) { 1327 if (!is_integrated) {
1332 const u64 reserve_memory = std::min<u64>(device_access_memory / 8, 1_GiB); 1328 const u64 reserve_memory = std::min<u64>(device_access_memory / 8, 1_GiB);
1333 device_access_memory -= reserve_memory; 1329 device_access_memory -= reserve_memory;
1334 device_access_memory = std::min<u64>(device_access_memory, normal_memory + scaler_memory); 1330
1331 if (Settings::values.vram_usage_mode.GetValue() != Settings::VramUsageMode::Aggressive) {
1332 // Account for resolution scaling in memory limits
1333 const size_t normal_memory = 6_GiB;
1334 const size_t scaler_memory = 1_GiB * Settings::values.resolution_info.ScaleUp(1);
1335 device_access_memory =
1336 std::min<u64>(device_access_memory, normal_memory + scaler_memory);
1337 }
1338
1335 return; 1339 return;
1336 } 1340 }
1337 const s64 available_memory = static_cast<s64>(device_access_memory - device_initial_usage); 1341 const s64 available_memory = static_cast<s64>(device_access_memory - device_initial_usage);
diff --git a/src/video_core/vulkan_common/vulkan_device.h b/src/video_core/vulkan_common/vulkan_device.h
index a2ec26697..e3abe8ddf 100644
--- a/src/video_core/vulkan_common/vulkan_device.h
+++ b/src/video_core/vulkan_common/vulkan_device.h
@@ -499,6 +499,11 @@ public:
499 return extensions.transform_feedback; 499 return extensions.transform_feedback;
500 } 500 }
501 501
502 /// Returns true if the device supports VK_EXT_transform_feedback properly.
503 bool AreTransformFeedbackGeometryStreamsSupported() const {
504 return features.transform_feedback.geometryStreams;
505 }
506
502 /// Returns true if the device supports VK_EXT_custom_border_color. 507 /// Returns true if the device supports VK_EXT_custom_border_color.
503 bool IsExtCustomBorderColorSupported() const { 508 bool IsExtCustomBorderColorSupported() const {
504 return extensions.custom_border_color; 509 return extensions.custom_border_color;
diff --git a/src/yuzu/configuration/shared_translation.cpp b/src/yuzu/configuration/shared_translation.cpp
index d138b53c8..0549e8ae4 100644
--- a/src/yuzu/configuration/shared_translation.cpp
+++ b/src/yuzu/configuration/shared_translation.cpp
@@ -164,6 +164,11 @@ std::unique_ptr<TranslationMap> InitializeTranslations(QWidget* parent) {
164 "the emulator to decompress to an intermediate format any card supports, RGBA8.\n" 164 "the emulator to decompress to an intermediate format any card supports, RGBA8.\n"
165 "This option recompresses RGBA8 to either the BC1 or BC3 format, saving VRAM but " 165 "This option recompresses RGBA8 to either the BC1 or BC3 format, saving VRAM but "
166 "negatively affecting image quality.")); 166 "negatively affecting image quality."));
167 INSERT(Settings, vram_usage_mode, tr("VRAM Usage Mode:"),
168 tr("Selects whether the emulator should prefer to conserve memory or make maximum usage "
169 "of available video memory for performance. Has no effect on integrated graphics. "
170 "Aggressive mode may severely impact the performance of other applications such as "
171 "recording software."));
167 INSERT( 172 INSERT(
168 Settings, vsync_mode, tr("VSync Mode:"), 173 Settings, vsync_mode, tr("VSync Mode:"),
169 tr("FIFO (VSync) does not drop frames or exhibit tearing but is limited by the screen " 174 tr("FIFO (VSync) does not drop frames or exhibit tearing but is limited by the screen "
@@ -315,6 +320,11 @@ std::unique_ptr<ComboboxTranslationMap> ComboboxEnumeration(QWidget* parent) {
315 PAIR(AstcRecompression, Bc1, tr("BC1 (Low quality)")), 320 PAIR(AstcRecompression, Bc1, tr("BC1 (Low quality)")),
316 PAIR(AstcRecompression, Bc3, tr("BC3 (Medium quality)")), 321 PAIR(AstcRecompression, Bc3, tr("BC3 (Medium quality)")),
317 }}); 322 }});
323 translations->insert({Settings::EnumMetadata<Settings::VramUsageMode>::Index(),
324 {
325 PAIR(VramUsageMode, Conservative, tr("Conservative")),
326 PAIR(VramUsageMode, Aggressive, tr("Aggressive")),
327 }});
318 translations->insert({Settings::EnumMetadata<Settings::RendererBackend>::Index(), 328 translations->insert({Settings::EnumMetadata<Settings::RendererBackend>::Index(),
319 { 329 {
320#ifdef HAS_OPENGL 330#ifdef HAS_OPENGL
diff --git a/src/yuzu/main.cpp b/src/yuzu/main.cpp
index 9d63b5935..c0c0a19b8 100644
--- a/src/yuzu/main.cpp
+++ b/src/yuzu/main.cpp
@@ -1604,6 +1604,7 @@ void GMainWindow::ConnectMenuEvents() {
1604 connect_menu(ui->action_Open_yuzu_Folder, &GMainWindow::OnOpenYuzuFolder); 1604 connect_menu(ui->action_Open_yuzu_Folder, &GMainWindow::OnOpenYuzuFolder);
1605 connect_menu(ui->action_Verify_installed_contents, &GMainWindow::OnVerifyInstalledContents); 1605 connect_menu(ui->action_Verify_installed_contents, &GMainWindow::OnVerifyInstalledContents);
1606 connect_menu(ui->action_Install_Firmware, &GMainWindow::OnInstallFirmware); 1606 connect_menu(ui->action_Install_Firmware, &GMainWindow::OnInstallFirmware);
1607 connect_menu(ui->action_Install_Keys, &GMainWindow::OnInstallDecryptionKeys);
1607 connect_menu(ui->action_About, &GMainWindow::OnAbout); 1608 connect_menu(ui->action_About, &GMainWindow::OnAbout);
1608} 1609}
1609 1610
@@ -1633,6 +1634,7 @@ void GMainWindow::UpdateMenuState() {
1633 } 1634 }
1634 1635
1635 ui->action_Install_Firmware->setEnabled(!emulation_running); 1636 ui->action_Install_Firmware->setEnabled(!emulation_running);
1637 ui->action_Install_Keys->setEnabled(!emulation_running);
1636 1638
1637 for (QAction* action : applet_actions) { 1639 for (QAction* action : applet_actions) {
1638 action->setEnabled(is_firmware_available && !emulation_running); 1640 action->setEnabled(is_firmware_available && !emulation_running);
@@ -3008,9 +3010,6 @@ bool GMainWindow::MakeShortcutIcoPath(const u64 program_id, const std::string_vi
3008 3010
3009void GMainWindow::OnGameListCreateShortcut(u64 program_id, const std::string& game_path, 3011void GMainWindow::OnGameListCreateShortcut(u64 program_id, const std::string& game_path,
3010 GameListShortcutTarget target) { 3012 GameListShortcutTarget target) {
3011 std::string game_title;
3012 QString qt_game_title;
3013 std::filesystem::path out_icon_path;
3014 // Get path to yuzu executable 3013 // Get path to yuzu executable
3015 const QStringList args = QApplication::arguments(); 3014 const QStringList args = QApplication::arguments();
3016 std::filesystem::path yuzu_command = args[0].toStdString(); 3015 std::filesystem::path yuzu_command = args[0].toStdString();
@@ -3027,48 +3026,51 @@ void GMainWindow::OnGameListCreateShortcut(u64 program_id, const std::string& ga
3027 shortcut_path = 3026 shortcut_path =
3028 QStandardPaths::writableLocation(QStandardPaths::ApplicationsLocation).toStdString(); 3027 QStandardPaths::writableLocation(QStandardPaths::ApplicationsLocation).toStdString();
3029 } 3028 }
3030 // Icon path and title 3029
3031 if (std::filesystem::exists(shortcut_path)) { 3030 if (!std::filesystem::exists(shortcut_path)) {
3032 // Get title from game file 3031 GMainWindow::CreateShortcutMessagesGUI(
3033 const FileSys::PatchManager pm{program_id, system->GetFileSystemController(), 3032 this, GMainWindow::CREATE_SHORTCUT_MSGBOX_ERROR,
3034 system->GetContentProvider()}; 3033 QString::fromStdString(shortcut_path.generic_string()));
3035 const auto control = pm.GetControlMetadata(); 3034 LOG_ERROR(Frontend, "Invalid shortcut target {}", shortcut_path.generic_string());
3036 const auto loader = 3035 return;
3037 Loader::GetLoader(*system, vfs->OpenFile(game_path, FileSys::OpenMode::Read)); 3036 }
3038 game_title = fmt::format("{:016X}", program_id); 3037
3039 if (control.first != nullptr) { 3038 // Get title from game file
3040 game_title = control.first->GetApplicationName(); 3039 const FileSys::PatchManager pm{program_id, system->GetFileSystemController(),
3041 } else { 3040 system->GetContentProvider()};
3042 loader->ReadTitle(game_title); 3041 const auto control = pm.GetControlMetadata();
3043 } 3042 const auto loader =
3044 // Delete illegal characters from title 3043 Loader::GetLoader(*system, vfs->OpenFile(game_path, FileSys::OpenMode::Read));
3045 const std::string illegal_chars = "<>:\"/\\|?*."; 3044 std::string game_title = fmt::format("{:016X}", program_id);
3046 for (auto it = game_title.rbegin(); it != game_title.rend(); ++it) { 3045 if (control.first != nullptr) {
3047 if (illegal_chars.find(*it) != std::string::npos) { 3046 game_title = control.first->GetApplicationName();
3048 game_title.erase(it.base() - 1); 3047 } else {
3049 } 3048 loader->ReadTitle(game_title);
3050 } 3049 }
3051 qt_game_title = QString::fromStdString(game_title); 3050 // Delete illegal characters from title
3052 // Get icon from game file 3051 const std::string illegal_chars = "<>:\"/\\|?*.";
3053 std::vector<u8> icon_image_file{}; 3052 for (auto it = game_title.rbegin(); it != game_title.rend(); ++it) {
3054 if (control.second != nullptr) { 3053 if (illegal_chars.find(*it) != std::string::npos) {
3055 icon_image_file = control.second->ReadAllBytes(); 3054 game_title.erase(it.base() - 1);
3056 } else if (loader->ReadIcon(icon_image_file) != Loader::ResultStatus::Success) {
3057 LOG_WARNING(Frontend, "Could not read icon from {:s}", game_path);
3058 } 3055 }
3059 QImage icon_data = 3056 }
3060 QImage::fromData(icon_image_file.data(), static_cast<int>(icon_image_file.size())); 3057 const QString qt_game_title = QString::fromStdString(game_title);
3061 if (GMainWindow::MakeShortcutIcoPath(program_id, game_title, out_icon_path)) { 3058 // Get icon from game file
3062 if (!SaveIconToFile(out_icon_path, icon_data)) { 3059 std::vector<u8> icon_image_file{};
3063 LOG_ERROR(Frontend, "Could not write icon to file"); 3060 if (control.second != nullptr) {
3064 } 3061 icon_image_file = control.second->ReadAllBytes();
3062 } else if (loader->ReadIcon(icon_image_file) != Loader::ResultStatus::Success) {
3063 LOG_WARNING(Frontend, "Could not read icon from {:s}", game_path);
3064 }
3065 QImage icon_data =
3066 QImage::fromData(icon_image_file.data(), static_cast<int>(icon_image_file.size()));
3067 std::filesystem::path out_icon_path;
3068 if (GMainWindow::MakeShortcutIcoPath(program_id, game_title, out_icon_path)) {
3069 if (!SaveIconToFile(out_icon_path, icon_data)) {
3070 LOG_ERROR(Frontend, "Could not write icon to file");
3065 } 3071 }
3066 } else {
3067 GMainWindow::CreateShortcutMessagesGUI(this, GMainWindow::CREATE_SHORTCUT_MSGBOX_ERROR,
3068 qt_game_title);
3069 LOG_ERROR(Frontend, "Invalid shortcut target");
3070 return;
3071 } 3072 }
3073
3072#if defined(__linux__) 3074#if defined(__linux__)
3073 // Special case for AppImages 3075 // Special case for AppImages
3074 // Warn once if we are making a shortcut to a volatile AppImage 3076 // Warn once if we are making a shortcut to a volatile AppImage
@@ -4169,9 +4171,8 @@ void GMainWindow::OnInstallFirmware() {
4169 return; 4171 return;
4170 } 4172 }
4171 4173
4172 QString firmware_source_location = 4174 const QString firmware_source_location = QFileDialog::getExistingDirectory(
4173 QFileDialog::getExistingDirectory(this, tr("Select Dumped Firmware Source Location"), 4175 this, tr("Select Dumped Firmware Source Location"), {}, QFileDialog::ShowDirsOnly);
4174 QString::fromStdString(""), QFileDialog::ShowDirsOnly);
4175 if (firmware_source_location.isEmpty()) { 4176 if (firmware_source_location.isEmpty()) {
4176 return; 4177 return;
4177 } 4178 }
@@ -4202,8 +4203,9 @@ void GMainWindow::OnInstallFirmware() {
4202 std::vector<std::filesystem::path> out; 4203 std::vector<std::filesystem::path> out;
4203 const Common::FS::DirEntryCallable callback = 4204 const Common::FS::DirEntryCallable callback =
4204 [&out](const std::filesystem::directory_entry& entry) { 4205 [&out](const std::filesystem::directory_entry& entry) {
4205 if (entry.path().has_extension() && entry.path().extension() == ".nca") 4206 if (entry.path().has_extension() && entry.path().extension() == ".nca") {
4206 out.emplace_back(entry.path()); 4207 out.emplace_back(entry.path());
4208 }
4207 4209
4208 return true; 4210 return true;
4209 }; 4211 };
@@ -4235,7 +4237,6 @@ void GMainWindow::OnInstallFirmware() {
4235 auto firmware_vdir = sysnand_content_vdir->GetDirectoryRelative("registered"); 4237 auto firmware_vdir = sysnand_content_vdir->GetDirectoryRelative("registered");
4236 4238
4237 bool success = true; 4239 bool success = true;
4238 bool cancelled = false;
4239 int i = 0; 4240 int i = 0;
4240 for (const auto& firmware_src_path : out) { 4241 for (const auto& firmware_src_path : out) {
4241 i++; 4242 i++;
@@ -4250,24 +4251,22 @@ void GMainWindow::OnInstallFirmware() {
4250 success = false; 4251 success = false;
4251 } 4252 }
4252 4253
4253 if (QtProgressCallback(100, 20 + (int)(((float)(i) / (float)out.size()) * 70.0))) { 4254 if (QtProgressCallback(
4254 success = false; 4255 100, 20 + static_cast<int>(((i) / static_cast<float>(out.size())) * 70.0))) {
4255 cancelled = true; 4256 progress.close();
4256 break; 4257 QMessageBox::warning(
4258 this, tr("Firmware install failed"),
4259 tr("Firmware installation cancelled, firmware may be in bad state, "
4260 "restart yuzu or re-install firmware."));
4261 return;
4257 } 4262 }
4258 } 4263 }
4259 4264
4260 if (!success && !cancelled) { 4265 if (!success) {
4261 progress.close(); 4266 progress.close();
4262 QMessageBox::critical(this, tr("Firmware install failed"), 4267 QMessageBox::critical(this, tr("Firmware install failed"),
4263 tr("One or more firmware files failed to copy into NAND.")); 4268 tr("One or more firmware files failed to copy into NAND."));
4264 return; 4269 return;
4265 } else if (cancelled) {
4266 progress.close();
4267 QMessageBox::warning(this, tr("Firmware install failed"),
4268 tr("Firmware installation cancelled, firmware may be in bad state, "
4269 "restart yuzu or re-install firmware."));
4270 return;
4271 } 4270 }
4272 4271
4273 // Re-scan VFS for the newly placed firmware files. 4272 // Re-scan VFS for the newly placed firmware files.
@@ -4295,6 +4294,84 @@ void GMainWindow::OnInstallFirmware() {
4295 OnCheckFirmwareDecryption(); 4294 OnCheckFirmwareDecryption();
4296} 4295}
4297 4296
4297void GMainWindow::OnInstallDecryptionKeys() {
4298 // Don't do this while emulation is running.
4299 if (emu_thread != nullptr && emu_thread->IsRunning()) {
4300 return;
4301 }
4302
4303 const QString key_source_location = QFileDialog::getOpenFileName(
4304 this, tr("Select Dumped Keys Location"), {}, QStringLiteral("prod.keys (prod.keys)"), {},
4305 QFileDialog::ReadOnly);
4306 if (key_source_location.isEmpty()) {
4307 return;
4308 }
4309
4310 // Verify that it contains prod.keys, title.keys and optionally, key_retail.bin
4311 LOG_INFO(Frontend, "Installing key files from {}", key_source_location.toStdString());
4312
4313 const std::filesystem::path prod_key_path = key_source_location.toStdString();
4314 const std::filesystem::path key_source_path = prod_key_path.parent_path();
4315 if (!Common::FS::IsDir(key_source_path)) {
4316 return;
4317 }
4318
4319 bool prod_keys_found = false;
4320 std::vector<std::filesystem::path> source_key_files;
4321
4322 if (Common::FS::Exists(prod_key_path)) {
4323 prod_keys_found = true;
4324 source_key_files.emplace_back(prod_key_path);
4325 }
4326
4327 if (Common::FS::Exists(key_source_path / "title.keys")) {
4328 source_key_files.emplace_back(key_source_path / "title.keys");
4329 }
4330
4331 if (Common::FS::Exists(key_source_path / "key_retail.bin")) {
4332 source_key_files.emplace_back(key_source_path / "key_retail.bin");
4333 }
4334
4335 // There should be at least prod.keys.
4336 if (source_key_files.empty() || !prod_keys_found) {
4337 QMessageBox::warning(this, tr("Decryption Keys install failed"),
4338 tr("prod.keys is a required decryption key file."));
4339 return;
4340 }
4341
4342 const auto yuzu_keys_dir = Common::FS::GetYuzuPath(Common::FS::YuzuPath::KeysDir);
4343 for (auto key_file : source_key_files) {
4344 std::filesystem::path destination_key_file = yuzu_keys_dir / key_file.filename();
4345 if (!std::filesystem::copy_file(key_file, destination_key_file,
4346 std::filesystem::copy_options::overwrite_existing)) {
4347 LOG_ERROR(Frontend, "Failed to copy file {} to {}", key_file.string(),
4348 destination_key_file.string());
4349 QMessageBox::critical(this, tr("Decryption Keys install failed"),
4350 tr("One or more keys failed to copy."));
4351 return;
4352 }
4353 }
4354
4355 // Reinitialize the key manager, re-read the vfs (for update/dlc files),
4356 // and re-populate the game list in the UI if the user has already added
4357 // game folders.
4358 Core::Crypto::KeyManager::Instance().ReloadKeys();
4359 system->GetFileSystemController().CreateFactories(*vfs);
4360 game_list->PopulateAsync(UISettings::values.game_dirs);
4361
4362 if (ContentManager::AreKeysPresent()) {
4363 QMessageBox::information(this, tr("Decryption Keys install succeeded"),
4364 tr("Decryption Keys were successfully installed"));
4365 } else {
4366 QMessageBox::critical(
4367 this, tr("Decryption Keys install failed"),
4368 tr("Decryption Keys failed to initialize. Check that your dumping tools are "
4369 "up to date and re-dump keys."));
4370 }
4371
4372 OnCheckFirmwareDecryption();
4373}
4374
4298void GMainWindow::OnAbout() { 4375void GMainWindow::OnAbout() {
4299 AboutDialog aboutDialog(this); 4376 AboutDialog aboutDialog(this);
4300 aboutDialog.exec(); 4377 aboutDialog.exec();
diff --git a/src/yuzu/main.h b/src/yuzu/main.h
index 1f0e35c67..fce643f3f 100644
--- a/src/yuzu/main.h
+++ b/src/yuzu/main.h
@@ -381,6 +381,7 @@ private slots:
381 void OnOpenYuzuFolder(); 381 void OnOpenYuzuFolder();
382 void OnVerifyInstalledContents(); 382 void OnVerifyInstalledContents();
383 void OnInstallFirmware(); 383 void OnInstallFirmware();
384 void OnInstallDecryptionKeys();
384 void OnAbout(); 385 void OnAbout();
385 void OnToggleFilterBar(); 386 void OnToggleFilterBar();
386 void OnToggleStatusBar(); 387 void OnToggleStatusBar();
diff --git a/src/yuzu/main.ui b/src/yuzu/main.ui
index 6ff444a22..85dc1f2f6 100644
--- a/src/yuzu/main.ui
+++ b/src/yuzu/main.ui
@@ -165,8 +165,9 @@
165 <addaction name="separator"/> 165 <addaction name="separator"/>
166 <addaction name="action_Configure_Tas"/> 166 <addaction name="action_Configure_Tas"/>
167 </widget> 167 </widget>
168 <addaction name="action_Verify_installed_contents"/> 168 <addaction name="action_Install_Keys"/>
169 <addaction name="action_Install_Firmware"/> 169 <addaction name="action_Install_Firmware"/>
170 <addaction name="action_Verify_installed_contents"/>
170 <addaction name="separator"/> 171 <addaction name="separator"/>
171 <addaction name="menu_cabinet_applet"/> 172 <addaction name="menu_cabinet_applet"/>
172 <addaction name="action_Load_Album"/> 173 <addaction name="action_Load_Album"/>
@@ -469,6 +470,11 @@
469 <string>Install Firmware</string> 470 <string>Install Firmware</string>
470 </property> 471 </property>
471 </action> 472 </action>
473 <action name="action_Install_Keys">
474 <property name="text">
475 <string>Install Decryption Keys</string>
476 </property>
477 </action>
472 </widget> 478 </widget>
473 <resources> 479 <resources>
474 <include location="yuzu.qrc"/> 480 <include location="yuzu.qrc"/>