diff --git a/CMakeModules/CopySudachiFFmpegDeps.cmake b/CMakeModules/CopySudachiFFmpegDeps.cmake new file mode 100644 index 0000000..fddca9b --- /dev/null +++ b/CMakeModules/CopySudachiFFmpegDeps.cmake @@ -0,0 +1,10 @@ +# SPDX-FileCopyrightText: 2020 sudachi Emulator Project +# SPDX-License-Identifier: GPL-2.0-or-later + +function(copy_sudachi_FFmpeg_deps target_dir) + include(WindowsCopyFiles) + set(DLL_DEST "$/") + file(READ "${FFmpeg_PATH}/requirements.txt" FFmpeg_REQUIRED_DLLS) + string(STRIP "${FFmpeg_REQUIRED_DLLS}" FFmpeg_REQUIRED_DLLS) + windows_copy_files(${target_dir} ${FFmpeg_LIBRARY_DIR} ${DLL_DEST} ${FFmpeg_REQUIRED_DLLS}) +endfunction(copy_sudachi_FFmpeg_deps) diff --git a/CMakeModules/CopySudachiQt5Deps.cmake b/CMakeModules/CopySudachiQt5Deps.cmake new file mode 100644 index 0000000..992864c --- /dev/null +++ b/CMakeModules/CopySudachiQt5Deps.cmake @@ -0,0 +1,125 @@ +# SPDX-FileCopyrightText: 2016 Citra Emulator Project +# SPDX-License-Identifier: GPL-2.0-or-later + +function(copy_sudachi_Qt5_deps target_dir) + include(WindowsCopyFiles) + if (MSVC) + set(DLL_DEST "$/") + set(Qt5_DLL_DIR "${Qt5_DIR}/../../../bin") + else() + set(DLL_DEST "${CMAKE_BINARY_DIR}/bin/") + set(Qt5_DLL_DIR "${Qt5_DIR}/../../../lib/") + endif() + set(Qt5_PLATFORMS_DIR "${Qt5_DIR}/../../../plugins/platforms/") + set(Qt5_PLATFORMTHEMES_DIR "${Qt5_DIR}/../../../plugins/platformthemes/") + set(Qt5_PLATFORMINPUTCONTEXTS_DIR "${Qt5_DIR}/../../../plugins/platforminputcontexts/") + set(Qt5_MEDIASERVICE_DIR "${Qt5_DIR}/../../../plugins/mediaservice/") + set(Qt5_XCBGLINTEGRATIONS_DIR "${Qt5_DIR}/../../../plugins/xcbglintegrations/") + set(Qt5_STYLES_DIR "${Qt5_DIR}/../../../plugins/styles/") + set(Qt5_IMAGEFORMATS_DIR "${Qt5_DIR}/../../../plugins/imageformats/") + set(Qt5_RESOURCES_DIR "${Qt5_DIR}/../../../resources/") + set(PLATFORMS ${DLL_DEST}plugins/platforms/) + set(MEDIASERVICE ${DLL_DEST}mediaservice/) + set(STYLES ${DLL_DEST}plugins/styles/) + set(IMAGEFORMATS ${DLL_DEST}plugins/imageformats/) + if (MSVC) + windows_copy_files(${target_dir} ${Qt5_DLL_DIR} ${DLL_DEST} + Qt5Core$<$:d>.* + Qt5Gui$<$:d>.* + Qt5Widgets$<$:d>.* + Qt5Network$<$:d>.* + ) + if (SUDACHI_USE_QT_MULTIMEDIA) + windows_copy_files(${target_dir} ${Qt5_DLL_DIR} ${DLL_DEST} + Qt5Multimedia$<$:d>.* + ) + endif() + if (SUDACHI_USE_QT_WEB_ENGINE) + windows_copy_files(${target_dir} ${Qt5_DLL_DIR} ${DLL_DEST} + Qt5Network$<$:d>.* + Qt5Positioning$<$:d>.* + Qt5PrintSupport$<$:d>.* + Qt5Qml$<$:d>.* + Qt5QmlModels$<$:d>.* + Qt5Quick$<$:d>.* + Qt5QuickWidgets$<$:d>.* + Qt5WebChannel$<$:d>.* + Qt5WebEngineCore$<$:d>.* + Qt5WebEngineWidgets$<$:d>.* + QtWebEngineProcess$<$:d>.* + ) + + windows_copy_files(${target_dir} ${Qt5_RESOURCES_DIR} ${DLL_DEST} + icudtl.dat + qtwebengine_devtools_resources.pak + qtwebengine_resources.pak + qtwebengine_resources_100p.pak + qtwebengine_resources_200p.pak + ) + endif () + windows_copy_files(sudachi ${Qt5_PLATFORMS_DIR} ${PLATFORMS} qwindows$<$:d>.*) + windows_copy_files(sudachi ${Qt5_STYLES_DIR} ${STYLES} qwindowsvistastyle$<$:d>.*) + windows_copy_files(sudachi ${Qt5_IMAGEFORMATS_DIR} ${IMAGEFORMATS} + qjpeg$<$:d>.* + qgif$<$:d>.* + ) + windows_copy_files(sudachi ${Qt5_MEDIASERVICE_DIR} ${MEDIASERVICE} + dsengine$<$:d>.* + wmfengine$<$:d>.* + ) + else() + set(Qt5_DLLS + "${Qt5_DLL_DIR}libQt5Core.so.5" + "${Qt5_DLL_DIR}libQt5DBus.so.5" + "${Qt5_DLL_DIR}libQt5Gui.so.5" + "${Qt5_DLL_DIR}libQt5Widgets.so.5" + "${Qt5_DLL_DIR}libQt5XcbQpa.so.5" + "${Qt5_DLL_DIR}libicudata.so.60" + "${Qt5_DLL_DIR}libicui18n.so.60" + "${Qt5_DLL_DIR}libicuuc.so.60" + ) + set(Qt5_IMAGEFORMAT_DLLS + "${Qt5_IMAGEFORMATS_DIR}libqjpeg.so" + "${Qt5_IMAGEFORMATS_DIR}libqgif.so" + "${Qt5_IMAGEFORMATS_DIR}libqico.so" + ) + set(Qt5_PLATFORMTHEME_DLLS + "${Qt5_PLATFORMTHEMES_DIR}libqgtk3.so" + "${Qt5_PLATFORMTHEMES_DIR}libqxdgdesktopportal.so" + ) + set(Qt5_PLATFORM_DLLS + "${Qt5_PLATFORMS_DIR}libqxcb.so" + ) + set(Qt5_PLATFORMINPUTCONTEXT_DLLS + "${Qt5_PLATFORMINPUTCONTEXTS_DIR}libcomposeplatforminputcontextplugin.so" + "${Qt5_PLATFORMINPUTCONTEXTS_DIR}libibusplatforminputcontextplugin.so" + ) + set(Qt5_XCBGLINTEGRATION_DLLS + "${Qt5_XCBGLINTEGRATIONS_DIR}libqxcb-glx-integration.so" + ) + foreach(LIB ${Qt5_DLLS}) + file(COPY ${LIB} DESTINATION "${DLL_DEST}/lib" FOLLOW_SYMLINK_CHAIN) + endforeach() + foreach(LIB ${Qt5_IMAGEFORMAT_DLLS}) + file(COPY ${LIB} DESTINATION "${DLL_DEST}plugins/imageformats/" FOLLOW_SYMLINK_CHAIN) + endforeach() + foreach(LIB ${Qt5_PLATFORMTHEME_DLLS}) + file(COPY ${LIB} DESTINATION "${DLL_DEST}plugins/platformthemes/" FOLLOW_SYMLINK_CHAIN) + endforeach() + foreach(LIB ${Qt5_PLATFORM_DLLS}) + file(COPY ${LIB} DESTINATION "${DLL_DEST}plugins/platforms/" FOLLOW_SYMLINK_CHAIN) + endforeach() + foreach(LIB ${Qt5_PLATFORMINPUTCONTEXT_DLLS}) + file(COPY ${LIB} DESTINATION "${DLL_DEST}plugins/platforminputcontexts/" FOLLOW_SYMLINK_CHAIN) + endforeach() + foreach(LIB ${Qt5_XCBGLINTEGRATION_DLLS}) + file(COPY ${LIB} DESTINATION "${DLL_DEST}plugins/xcbglintegrations/" FOLLOW_SYMLINK_CHAIN) + endforeach() + + endif() + # Create an empty qt.conf file. Qt will detect that this file exists, and use the folder that its in as the root folder. + # This way it'll look for plugins in the root/plugins/ folder + add_custom_command(TARGET sudachi POST_BUILD + COMMAND ${CMAKE_COMMAND} -E touch ${DLL_DEST}qt.conf + ) +endfunction(copy_sudachi_Qt5_deps) diff --git a/CMakeModules/CopySudachiSDLDeps.cmake b/CMakeModules/CopySudachiSDLDeps.cmake new file mode 100644 index 0000000..71d4952 --- /dev/null +++ b/CMakeModules/CopySudachiSDLDeps.cmake @@ -0,0 +1,8 @@ +# SPDX-FileCopyrightText: 2016 Citra Emulator Project +# SPDX-License-Identifier: GPL-2.0-or-later + +function(copy_sudachi_SDL_deps target_dir) + include(WindowsCopyFiles) + set(DLL_DEST "$/") + windows_copy_files(${target_dir} ${SDL2_DLL_DIR} ${DLL_DEST} SDL2.dll) +endfunction(copy_sudachi_SDL_deps) diff --git a/dist/72-sudachi-input.rules b/dist/72-sudachi-input.rules new file mode 100644 index 0000000..57c8d59 --- /dev/null +++ b/dist/72-sudachi-input.rules @@ -0,0 +1,19 @@ +# SPDX-FileCopyrightText: 2023 sudachi Emulator Project +# SPDX-License-Identifier: GPL-2.0-or-later + +# Allow systemd-logind to manage user access to hidraw with this file +# On most systems, this file should be installed to /etc/udev/rules.d/72-sudachi-input.rules +# Consult your distro if this is not the case + +# Switch Pro Controller (USB/Bluetooth) +KERNEL=="hidraw*", ATTRS{idVendor}=="057e", ATTRS{idProduct}=="2009", MODE="0660", TAG+="uaccess" +KERNEL=="hidraw*", KERNELS=="*057e:2009*", MODE="0660", TAG+="uaccess" + +# Joy-Con L (Bluetooth) +KERNEL=="hidraw*", KERNELS=="*057e:2006*", MODE="0660", TAG+="uaccess" + +# Joy-Con R (Bluetooth) +KERNEL=="hidraw*", KERNELS=="*057e:2007*", MODE="0660", TAG+="uaccess" + +# Joy-Con Charging Grip (USB) +KERNEL=="hidraw*", ATTRS{idVendor}=="057e", ATTRS{idProduct}=="200e", MODE="0660", TAG+="uaccess" diff --git a/dist/org.sudachi_emu.sudachi.desktop b/dist/org.sudachi_emu.sudachi.desktop new file mode 100644 index 0000000..278ebd2 --- /dev/null +++ b/dist/org.sudachi_emu.sudachi.desktop @@ -0,0 +1,16 @@ +# SPDX-FileCopyrightText: 2018 sudachi Emulator Project +# SPDX-License-Identifier: GPL-2.0-or-later + +[Desktop Entry] +Version=1.0 +Type=Application +Name=sudachi +GenericName=Switch Emulator +Comment=Nintendo Switch video game console emulator +Icon=org.sudachi_emu.sudachi +TryExec=sudachi +Exec=sudachi %f +Categories=Game;Emulator;Qt; +MimeType=application/x-nx-nro;application/x-nx-nso;application/x-nx-nsp;application/x-nx-xci; +Keywords=Nintendo;Switch; +StartupWMClass=sudachi diff --git a/dist/org.sudachi_emu.sudachi.metainfo.xml b/dist/org.sudachi_emu.sudachi.metainfo.xml new file mode 100644 index 0000000..888da98 --- /dev/null +++ b/dist/org.sudachi_emu.sudachi.metainfo.xml @@ -0,0 +1,62 @@ + + + + + + org.sudachi_emu.sudachi + CC0-1.0 + sudachi + Nintendo Switch emulator + +

sudachi is the world's most popular, open-source, Nintendo Switch emulator — started by the creators of Citra.

+

The emulator is capable of running most commercial games at full speed, provided you meet the necessary hardware requirements.

+

For a full list of games sudachi support, please visit our Compatibility page.

+

Check out our website for the latest news on exciting features, monthly progress reports, and more!

+
+ + Game + Emulator + + + switch + emulator + + https://sudachi-emu.org/ + https://github.com/sudachi-emu/sudachi/issues + https://sudachi-emu.org/wiki/faq/ + https://sudachi-emu.org/wiki/home/ + https://sudachi-emu.org/donate/ + https://www.transifex.com/projects/p/sudachi + https://community.citra-emu.org/ + https://github.com/sudachi-emu/sudachi + https://sudachi-emu.org/wiki/contributing/ + org.sudachi_emu.sudachi.desktop + + sudachi + sudachi-cmd + + + pointing + keyboard + gamepad + + + 8192 + + + 16384 + + GPL-3.0-or-later + sudachi Emulator Team + + + https://raw.githubusercontent.com/sudachi-emu/sudachi-emu.github.io/master/images/screenshots/001-Super%20Mario%20Odyssey%20.png + https://raw.githubusercontent.com/sudachi-emu/sudachi-emu.github.io/master/images/screenshots/004-The%20Legend%20of%20Zelda%20Skyward%20Sword%20HD.png + https://raw.githubusercontent.com/sudachi-emu/sudachi-emu.github.io/master/images/screenshots/007-Pokemon%20Sword.png + https://raw.githubusercontent.com/sudachi-emu/sudachi-emu.github.io/master/images/screenshots/010-Hyrule%20Warriors%20Age%20of%20Calamity.png + https://raw.githubusercontent.com/sudachi-emu/sudachi-emu.github.io/master/images/screenshots/039-Pok%C3%A9mon%20Mystery%20Dungeon%20Rescue%20Team%20DX.png.png.png + +
diff --git a/dist/org.sudachi_emu.sudachi.xml b/dist/org.sudachi_emu.sudachi.xml new file mode 100644 index 0000000..a1839d7 --- /dev/null +++ b/dist/org.sudachi_emu.sudachi.xml @@ -0,0 +1,39 @@ + + + + + + + Nintendo Switch homebrew executable + NRO + + + + + + + Nintendo Switch homebrew executable + NSO + + + + + + + Nintendo Switch Package + NSP + + + + + + + Nintendo Switch Card Image + XCI + + + + diff --git a/dist/qt_themes/default/icons/256x256/sudachi.png b/dist/qt_themes/default/icons/256x256/sudachi.png new file mode 100644 index 0000000..a8702db Binary files /dev/null and b/dist/qt_themes/default/icons/256x256/sudachi.png differ diff --git a/dist/sudachi.bmp b/dist/sudachi.bmp new file mode 100644 index 0000000..a8702db Binary files /dev/null and b/dist/sudachi.bmp differ diff --git a/dist/sudachi.desktop b/dist/sudachi.desktop new file mode 100644 index 0000000..a0fcd48 --- /dev/null +++ b/dist/sudachi.desktop @@ -0,0 +1,12 @@ +[Desktop Entry] +Version=1.0 +Type=Application +Name=sudachi +GenericName=Switch Emulator +Comment=Nintendo Switch video game console emulator +Icon=sudachi +TryExec=sudachi +Exec=sudachi %f +Categories=Game;Emulator;Qt; +MimeType=application/x-nx-nro;application/x-nx-nso;application/x-nx-nsp;application/x-nx-xci; +Keywords=Switch;Nintendo; \ No newline at end of file diff --git a/dist/sudachi.icns b/dist/sudachi.icns new file mode 100644 index 0000000..8cb83f9 Binary files /dev/null and b/dist/sudachi.icns differ diff --git a/dist/sudachi.ico b/dist/sudachi.ico new file mode 100644 index 0000000..223be21 Binary files /dev/null and b/dist/sudachi.ico differ diff --git a/dist/sudachi.manifest b/dist/sudachi.manifest new file mode 100644 index 0000000..0236ad1 --- /dev/null +++ b/dist/sudachi.manifest @@ -0,0 +1,58 @@ + + + + + + + + + + true/pm + + + + PerMonitorV2 + + + + true + + + true + + + + + + + + + + + + + + + + + + diff --git a/externals/SDL b/externals/SDL index ee87132..d79f865 160000 --- a/externals/SDL +++ b/externals/SDL @@ -1 +1 @@ -Subproject commit ee87132385014449c4cd33236c661d57539071c1 +Subproject commit d79f8652510b8bd1f89c90be2ab65fc8940056eb diff --git a/externals/ffmpeg/ffmpeg b/externals/ffmpeg/ffmpeg index 53a952a..d65908c 160000 --- a/externals/ffmpeg/ffmpeg +++ b/externals/ffmpeg/ffmpeg @@ -1 +1 @@ -Subproject commit 53a952a7313f2c78d93a4f6805abe570fe35f96b +Subproject commit d65908c3d416e331e075c3a5ffe7bc670112a018 diff --git a/hooks/pre-commit b/hooks/pre-commit index 484eef1..13f9a6e 100644 --- a/hooks/pre-commit +++ b/hooks/pre-commit @@ -3,7 +3,7 @@ # SPDX-FileCopyrightText: 2015 Citra Emulator Project # SPDX-License-Identifier: GPL-2.0-or-later -# Enforce yuzu's whitespace policy +# Enforce sudachi's whitespace policy git config --local core.whitespace tab-in-indent,trailing-space paths_to_check="src/ CMakeLists.txt" diff --git a/src/android/app/src/ea/res/drawable/ic_sudachi.xml b/src/android/app/src/ea/res/drawable/ic_sudachi.xml new file mode 100644 index 0000000..deb8ba5 --- /dev/null +++ b/src/android/app/src/ea/res/drawable/ic_sudachi.xml @@ -0,0 +1,22 @@ + + + + diff --git a/src/android/app/src/ea/res/drawable/ic_sudachi_full.xml b/src/android/app/src/ea/res/drawable/ic_sudachi_full.xml new file mode 100644 index 0000000..4ef4728 --- /dev/null +++ b/src/android/app/src/ea/res/drawable/ic_sudachi_full.xml @@ -0,0 +1,12 @@ + + + + diff --git a/src/android/app/src/ea/res/drawable/ic_sudachi_title.xml b/src/android/app/src/ea/res/drawable/ic_sudachi_title.xml new file mode 100644 index 0000000..29d0cfc --- /dev/null +++ b/src/android/app/src/ea/res/drawable/ic_sudachi_title.xml @@ -0,0 +1,24 @@ + + + + + + + + diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/NativeLibrary.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/NativeLibrary.kt new file mode 100644 index 0000000..f321e35 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/NativeLibrary.kt @@ -0,0 +1,462 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu + +import android.content.DialogInterface +import android.net.Uri +import android.text.Html +import android.text.method.LinkMovementMethod +import android.view.Surface +import android.view.View +import android.widget.TextView +import androidx.annotation.Keep +import com.google.android.material.dialog.MaterialAlertDialogBuilder +import java.lang.ref.WeakReference +import org.sudachi.sudachi_emu.activities.EmulationActivity +import org.sudachi.sudachi_emu.fragments.CoreErrorDialogFragment +import org.sudachi.sudachi_emu.utils.DocumentsTree +import org.sudachi.sudachi_emu.utils.FileUtil +import org.sudachi.sudachi_emu.utils.Log +import org.sudachi.sudachi_emu.model.InstallResult +import org.sudachi.sudachi_emu.model.Patch +import org.sudachi.sudachi_emu.model.GameVerificationResult + +/** + * Class which contains methods that interact + * with the native side of the Sudachi code. + */ +object NativeLibrary { + @JvmField + var sEmulationActivity = WeakReference(null) + + init { + try { + System.loadLibrary("sudachi-android") + } catch (ex: UnsatisfiedLinkError) { + error("[NativeLibrary] $ex") + } + } + + @Keep + @JvmStatic + fun openContentUri(path: String?, openmode: String?): Int { + return if (DocumentsTree.isNativePath(path!!)) { + SudachiApplication.documentsTree!!.openContentUri(path, openmode) + } else { + FileUtil.openContentUri(path, openmode) + } + } + + @Keep + @JvmStatic + fun getSize(path: String?): Long { + return if (DocumentsTree.isNativePath(path!!)) { + SudachiApplication.documentsTree!!.getFileSize(path) + } else { + FileUtil.getFileSize(path) + } + } + + @Keep + @JvmStatic + fun exists(path: String?): Boolean { + return if (DocumentsTree.isNativePath(path!!)) { + SudachiApplication.documentsTree!!.exists(path) + } else { + FileUtil.exists(path, suppressLog = true) + } + } + + @Keep + @JvmStatic + fun isDirectory(path: String?): Boolean { + return if (DocumentsTree.isNativePath(path!!)) { + SudachiApplication.documentsTree!!.isDirectory(path) + } else { + FileUtil.isDirectory(path) + } + } + + @Keep + @JvmStatic + fun getParentDirectory(path: String): String = + if (DocumentsTree.isNativePath(path)) { + SudachiApplication.documentsTree!!.getParentDirectory(path) + } else { + path + } + + @Keep + @JvmStatic + fun getFilename(path: String): String = + if (DocumentsTree.isNativePath(path)) { + SudachiApplication.documentsTree!!.getFilename(path) + } else { + FileUtil.getFilename(Uri.parse(path)) + } + + external fun setAppDirectory(directory: String) + + /** + * Installs a nsp or xci file to nand + * @param filename String representation of file uri + * @return int representation of [InstallResult] + */ + external fun installFileToNand( + filename: String, + callback: (max: Long, progress: Long) -> Boolean + ): Int + + external fun doesUpdateMatchProgram(programId: String, updatePath: String): Boolean + + external fun initializeGpuDriver( + hookLibDir: String?, + customDriverDir: String?, + customDriverName: String?, + fileRedirectDir: String? + ) + + external fun reloadKeys(): Boolean + + external fun initializeSystem(reload: Boolean) + + /** + * Begins emulation. + */ + external fun run(path: String?, programIndex: Int, frontendInitiated: Boolean) + + // Surface Handling + external fun surfaceChanged(surf: Surface?) + + external fun surfaceDestroyed() + + /** + * Unpauses emulation from a paused state. + */ + external fun unpauseEmulation() + + /** + * Pauses emulation. + */ + external fun pauseEmulation() + + /** + * Stops emulation. + */ + external fun stopEmulation() + + /** + * Returns true if emulation is running (or is paused). + */ + external fun isRunning(): Boolean + + /** + * Returns true if emulation is paused. + */ + external fun isPaused(): Boolean + + /** + * Returns the performance stats for the current game + */ + external fun getPerfStats(): DoubleArray + + /** + * Returns the current CPU backend. + */ + external fun getCpuBackend(): String + + /** + * Returns the current GPU Driver. + */ + external fun getGpuDriver(): String + + external fun applySettings() + + external fun logSettings() + + enum class CoreError { + ErrorSystemFiles, + ErrorSavestate, + ErrorUnknown + } + + var coreErrorAlertResult = false + val coreErrorAlertLock = Object() + + private fun onCoreErrorImpl(title: String, message: String) { + val emulationActivity = sEmulationActivity.get() + if (emulationActivity == null) { + Log.error("[NativeLibrary] EmulationActivity not present") + return + } + + val fragment = CoreErrorDialogFragment.newInstance(title, message) + fragment.show(emulationActivity.supportFragmentManager, "coreError") + } + + /** + * Handles a core error. + * + * @return true: continue; false: abort + */ + fun onCoreError(error: CoreError?, details: String): Boolean { + val emulationActivity = sEmulationActivity.get() + if (emulationActivity == null) { + Log.error("[NativeLibrary] EmulationActivity not present") + return false + } + + val title: String + val message: String + when (error) { + CoreError.ErrorSystemFiles -> { + title = emulationActivity.getString(R.string.system_archive_not_found) + message = emulationActivity.getString( + R.string.system_archive_not_found_message, + details.ifEmpty { emulationActivity.getString(R.string.system_archive_general) } + ) + } + + CoreError.ErrorSavestate -> { + title = emulationActivity.getString(R.string.save_load_error) + message = details + } + + CoreError.ErrorUnknown -> { + title = emulationActivity.getString(R.string.fatal_error) + message = emulationActivity.getString(R.string.fatal_error_message) + } + + else -> { + return true + } + } + + // Show the AlertDialog on the main thread. + emulationActivity.runOnUiThread { onCoreErrorImpl(title, message) } + + // Wait for the lock to notify that it is complete. + synchronized(coreErrorAlertLock) { coreErrorAlertLock.wait() } + + return coreErrorAlertResult + } + + @Keep + @JvmStatic + fun exitEmulationActivity(resultCode: Int) { + val Success = 0 + val ErrorNotInitialized = 1 + val ErrorGetLoader = 2 + val ErrorSystemFiles = 3 + val ErrorSharedFont = 4 + val ErrorVideoCore = 5 + val ErrorUnknown = 6 + val ErrorLoader = 7 + + val captionId: Int + var descriptionId: Int + when (resultCode) { + ErrorVideoCore -> { + captionId = R.string.loader_error_video_core + descriptionId = R.string.loader_error_video_core_description + } + + else -> { + captionId = R.string.loader_error_encrypted + descriptionId = R.string.loader_error_encrypted_roms_description + if (!reloadKeys()) { + descriptionId = R.string.loader_error_encrypted_keys_description + } + } + } + + val emulationActivity = sEmulationActivity.get() + if (emulationActivity == null) { + Log.warning("[NativeLibrary] EmulationActivity is null, can't exit.") + return + } + + val builder = MaterialAlertDialogBuilder(emulationActivity) + .setTitle(captionId) + .setMessage( + Html.fromHtml( + emulationActivity.getString(descriptionId), + Html.FROM_HTML_MODE_LEGACY + ) + ) + .setPositiveButton(android.R.string.ok) { _: DialogInterface?, _: Int -> + emulationActivity.finish() + } + .setOnDismissListener { emulationActivity.finish() } + emulationActivity.runOnUiThread { + val alert = builder.create() + alert.show() + (alert.findViewById(android.R.id.message) as TextView).movementMethod = + LinkMovementMethod.getInstance() + } + } + + fun setEmulationActivity(emulationActivity: EmulationActivity?) { + Log.debug("[NativeLibrary] Registering EmulationActivity.") + sEmulationActivity = WeakReference(emulationActivity) + } + + fun clearEmulationActivity() { + Log.debug("[NativeLibrary] Unregistering EmulationActivity.") + sEmulationActivity.clear() + } + + @Keep + @JvmStatic + fun onEmulationStarted() { + sEmulationActivity.get()!!.onEmulationStarted() + } + + @Keep + @JvmStatic + fun onEmulationStopped(status: Int) { + sEmulationActivity.get()!!.onEmulationStopped(status) + } + + @Keep + @JvmStatic + fun onProgramChanged(programIndex: Int) { + sEmulationActivity.get()!!.onProgramChanged(programIndex) + } + + /** + * Logs the Sudachi version, Android version and, CPU. + */ + external fun logDeviceInfo() + + /** + * Submits inline keyboard text. Called on input for buttons that result text. + * @param text Text to submit to the inline software keyboard implementation. + */ + external fun submitInlineKeyboardText(text: String?) + + /** + * Submits inline keyboard input. Used to indicate keys pressed that are not text. + * @param key_code Android Key Code associated with the keyboard input. + */ + external fun submitInlineKeyboardInput(key_code: Int) + + /** + * Creates a generic user directory if it doesn't exist already + */ + external fun initializeEmptyUserDirectory() + + /** + * Gets the launch path for a given applet. It is the caller's responsibility to also + * set the system's current applet ID before trying to launch the nca given by this function. + * + * @param id The applet entry ID + * @return The applet's launch path + */ + external fun getAppletLaunchPath(id: Long): String + + /** + * Sets the system's current applet ID before launching. + * + * @param appletId One of the ids in the Service::AM::Applets::AppletId enum + */ + external fun setCurrentAppletId(appletId: Int) + + /** + * Sets the cabinet mode for launching the cabinet applet. + * + * @param cabinetMode One of the modes that corresponds to the enum in Service::NFP::CabinetMode + */ + external fun setCabinetMode(cabinetMode: Int) + + /** + * Checks whether NAND contents are available and valid. + * + * @return 'true' if firmware is available + */ + external fun isFirmwareAvailable(): Boolean + + /** + * Checks the PatchManager for any addons that are available + * + * @param path Path to game file. Can be a [Uri]. + * @param programId String representation of a game's program ID + * @return Array of available patches + */ + external fun getPatchesForFile(path: String, programId: String): Array? + + /** + * Removes an update for a given [programId] + * @param programId String representation of a game's program ID + */ + external fun removeUpdate(programId: String) + + /** + * Removes all DLC for a [programId] + * @param programId String representation of a game's program ID + */ + external fun removeDLC(programId: String) + + /** + * Removes a mod installed for a given [programId] + * @param programId String representation of a game's program ID + * @param name The name of a mod as given by [getPatchesForFile]. This corresponds with the name + * of the mod's directory in a game's load folder. + */ + external fun removeMod(programId: String, name: String) + + /** + * Verifies all installed content + * @param callback UI callback for verification progress. Return true in the callback to cancel. + * @return Array of content that failed verification. Successful if empty. + */ + external fun verifyInstalledContents( + callback: (max: Long, progress: Long) -> Boolean + ): Array + + /** + * Verifies the contents of a game + * @param path String path to a game + * @param callback UI callback for verification progress. Return true in the callback to cancel. + * @return Int that is meant to be converted to a [GameVerificationResult] + */ + external fun verifyGameContents( + path: String, + callback: (max: Long, progress: Long) -> Boolean + ): Int + + /** + * Gets the save location for a specific game + * + * @param programId String representation of a game's program ID + * @return Save data path that may not exist yet + */ + external fun getSavePath(programId: String): String + + /** + * Gets the root save directory for the default profile as either + * /user/save/account/ or /user/save/000...000/ + * + * @param future If true, returns the /user/save/account/... directory + * @return Save data path that may not exist yet + */ + external fun getDefaultProfileSaveDataRoot(future: Boolean): String + + /** + * Adds a file to the manual filesystem provider in our EmulationSession instance + * @param path Path to the file we're adding. Can be a string representation of a [Uri] or + * a normal path + */ + external fun addFileToFilesystemProvider(path: String) + + /** + * Clears all files added to the manual filesystem provider in our EmulationSession instance + */ + external fun clearFilesystemProvider() + + /** + * Checks if all necessary keys are present for decryption + */ + external fun areKeysPresent(): Boolean +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/SudachiApplication.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/SudachiApplication.kt new file mode 100644 index 0000000..858b6ef --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/SudachiApplication.kt @@ -0,0 +1,55 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu + +import android.app.Application +import android.app.NotificationChannel +import android.app.NotificationManager +import android.content.Context +import org.sudachi.sudachi_emu.features.input.NativeInput +import java.io.File +import org.sudachi.sudachi_emu.utils.DirectoryInitialization +import org.sudachi.sudachi_emu.utils.DocumentsTree +import org.sudachi.sudachi_emu.utils.GpuDriverHelper +import org.sudachi.sudachi_emu.utils.Log + +fun Context.getPublicFilesDir(): File = getExternalFilesDir(null) ?: filesDir + +class SudachiApplication : Application() { + private fun createNotificationChannels() { + val noticeChannel = NotificationChannel( + getString(R.string.notice_notification_channel_id), + getString(R.string.notice_notification_channel_name), + NotificationManager.IMPORTANCE_HIGH + ) + noticeChannel.description = getString(R.string.notice_notification_channel_description) + noticeChannel.setSound(null, null) + + // Register the channel with the system; you can't change the importance + // or other notification behaviors after this + val notificationManager = getSystemService(NotificationManager::class.java) + notificationManager.createNotificationChannel(noticeChannel) + } + + override fun onCreate() { + super.onCreate() + application = this + documentsTree = DocumentsTree() + DirectoryInitialization.start() + GpuDriverHelper.initializeDriverParameters() + NativeInput.reloadInputDevices() + NativeLibrary.logDeviceInfo() + Log.logDeviceInfo() + + createNotificationChannels() + } + + companion object { + var documentsTree: DocumentsTree? = null + lateinit var application: SudachiApplication + + val appContext: Context + get() = application.applicationContext + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/activities/EmulationActivity.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/activities/EmulationActivity.kt new file mode 100644 index 0000000..59a14ea --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/activities/EmulationActivity.kt @@ -0,0 +1,509 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.activities + +import android.annotation.SuppressLint +import android.app.PendingIntent +import android.app.PictureInPictureParams +import android.app.RemoteAction +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.content.IntentFilter +import android.content.res.Configuration +import android.graphics.Rect +import android.graphics.drawable.Icon +import android.hardware.Sensor +import android.hardware.SensorEvent +import android.hardware.SensorEventListener +import android.hardware.SensorManager +import android.os.Build +import android.os.Bundle +import android.util.Rational +import android.view.InputDevice +import android.view.KeyEvent +import android.view.MotionEvent +import android.view.Surface +import android.view.View +import android.view.inputmethod.InputMethodManager +import android.widget.Toast +import androidx.activity.viewModels +import androidx.appcompat.app.AppCompatActivity +import androidx.core.view.WindowCompat +import androidx.core.view.WindowInsetsCompat +import androidx.core.view.WindowInsetsControllerCompat +import androidx.navigation.fragment.NavHostFragment +import androidx.preference.PreferenceManager +import org.sudachi.sudachi_emu.NativeLibrary +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.SudachiApplication +import org.sudachi.sudachi_emu.databinding.ActivityEmulationBinding +import org.sudachi.sudachi_emu.features.input.NativeInput +import org.sudachi.sudachi_emu.features.settings.model.BooleanSetting +import org.sudachi.sudachi_emu.features.settings.model.IntSetting +import org.sudachi.sudachi_emu.features.settings.model.Settings +import org.sudachi.sudachi_emu.model.EmulationViewModel +import org.sudachi.sudachi_emu.model.Game +import org.sudachi.sudachi_emu.utils.InputHandler +import org.sudachi.sudachi_emu.utils.Log +import org.sudachi.sudachi_emu.utils.MemoryUtil +import org.sudachi.sudachi_emu.utils.NativeConfig +import org.sudachi.sudachi_emu.utils.NfcReader +import org.sudachi.sudachi_emu.utils.ParamPackage +import org.sudachi.sudachi_emu.utils.ThemeHelper +import java.text.NumberFormat +import kotlin.math.roundToInt + +class EmulationActivity : AppCompatActivity(), SensorEventListener { + private lateinit var binding: ActivityEmulationBinding + + var isActivityRecreated = false + private lateinit var nfcReader: NfcReader + + private val gyro = FloatArray(3) + private val accel = FloatArray(3) + private var motionTimestamp: Long = 0 + private var flipMotionOrientation: Boolean = false + + private val actionPause = "ACTION_EMULATOR_PAUSE" + private val actionPlay = "ACTION_EMULATOR_PLAY" + private val actionMute = "ACTION_EMULATOR_MUTE" + private val actionUnmute = "ACTION_EMULATOR_UNMUTE" + + private val emulationViewModel: EmulationViewModel by viewModels() + + override fun onCreate(savedInstanceState: Bundle?) { + Log.gameLaunched = true + ThemeHelper.setTheme(this) + + super.onCreate(savedInstanceState) + + InputHandler.updateControllerData() + val players = NativeConfig.getInputSettings(true) + var hasConfiguredControllers = false + players.forEach { + if (it.hasMapping()) { + hasConfiguredControllers = true + } + } + if (!hasConfiguredControllers && InputHandler.androidControllers.isNotEmpty()) { + var params: ParamPackage? = null + for (controller in InputHandler.registeredControllers) { + if (controller.get("port", -1) == 0) { + params = controller + break + } + } + + if (params != null) { + NativeInput.updateMappingsWithDefault( + 0, + params, + params.get("display", getString(R.string.unknown)) + ) + NativeConfig.saveGlobalConfig() + } + } + + binding = ActivityEmulationBinding.inflate(layoutInflater) + setContentView(binding.root) + + val navHostFragment = + supportFragmentManager.findFragmentById(R.id.fragment_container) as NavHostFragment + navHostFragment.navController.setGraph(R.navigation.emulation_navigation, intent.extras) + + isActivityRecreated = savedInstanceState != null + + // Set these options now so that the SurfaceView the game renders into is the right size. + enableFullscreenImmersive() + + window.decorView.setBackgroundColor(getColor(android.R.color.black)) + + nfcReader = NfcReader(this) + nfcReader.initialize() + + val preferences = PreferenceManager.getDefaultSharedPreferences(SudachiApplication.appContext) + if (!preferences.getBoolean(Settings.PREF_MEMORY_WARNING_SHOWN, false)) { + if (MemoryUtil.isLessThan(MemoryUtil.REQUIRED_MEMORY, MemoryUtil.totalMemory)) { + Toast.makeText( + this, + getString( + R.string.device_memory_inadequate, + MemoryUtil.getDeviceRAM(), + getString( + R.string.memory_formatted, + NumberFormat.getInstance().format(MemoryUtil.REQUIRED_MEMORY), + getString(R.string.memory_gigabyte) + ) + ), + Toast.LENGTH_LONG + ).show() + preferences.edit() + .putBoolean(Settings.PREF_MEMORY_WARNING_SHOWN, true) + .apply() + } + } + } + + override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean { + if (event.action == KeyEvent.ACTION_DOWN) { + if (keyCode == KeyEvent.KEYCODE_ENTER) { + // Special case, we do not support multiline input, dismiss the keyboard. + val overlayView: View = + this.findViewById(R.id.surface_input_overlay) + val im = + overlayView.context.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager + im.hideSoftInputFromWindow(overlayView.windowToken, 0) + } else { + val textChar = event.unicodeChar + if (textChar == 0) { + // No text, button input. + NativeLibrary.submitInlineKeyboardInput(keyCode) + } else { + // Text submitted. + NativeLibrary.submitInlineKeyboardText(textChar.toChar().toString()) + } + } + } + return super.onKeyDown(keyCode, event) + } + + override fun onResume() { + super.onResume() + nfcReader.startScanning() + startMotionSensorListener() + InputHandler.updateControllerData() + + buildPictureInPictureParams() + } + + override fun onPause() { + super.onPause() + nfcReader.stopScanning() + stopMotionSensorListener() + } + + override fun onUserLeaveHint() { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) { + if (BooleanSetting.PICTURE_IN_PICTURE.getBoolean() && !isInPictureInPictureMode) { + val pictureInPictureParamsBuilder = PictureInPictureParams.Builder() + .getPictureInPictureActionsBuilder().getPictureInPictureAspectBuilder() + enterPictureInPictureMode(pictureInPictureParamsBuilder.build()) + } + } + } + + override fun onNewIntent(intent: Intent) { + super.onNewIntent(intent) + setIntent(intent) + nfcReader.onNewIntent(intent) + InputHandler.updateControllerData() + } + + override fun dispatchKeyEvent(event: KeyEvent): Boolean { + if (event.source and InputDevice.SOURCE_JOYSTICK != InputDevice.SOURCE_JOYSTICK && + event.source and InputDevice.SOURCE_GAMEPAD != InputDevice.SOURCE_GAMEPAD + ) { + return super.dispatchKeyEvent(event) + } + + if (emulationViewModel.drawerOpen.value) { + return super.dispatchKeyEvent(event) + } + + return InputHandler.dispatchKeyEvent(event) + } + + override fun dispatchGenericMotionEvent(event: MotionEvent): Boolean { + if (event.source and InputDevice.SOURCE_JOYSTICK != InputDevice.SOURCE_JOYSTICK && + event.source and InputDevice.SOURCE_GAMEPAD != InputDevice.SOURCE_GAMEPAD + ) { + return super.dispatchGenericMotionEvent(event) + } + + if (emulationViewModel.drawerOpen.value) { + return super.dispatchGenericMotionEvent(event) + } + + // Don't attempt to do anything if we are disconnecting a device. + if (event.actionMasked == MotionEvent.ACTION_CANCEL) { + return true + } + + return InputHandler.dispatchGenericMotionEvent(event) + } + + override fun onSensorChanged(event: SensorEvent) { + val rotation = this.display?.rotation + if (rotation == Surface.ROTATION_90) { + flipMotionOrientation = true + } + if (rotation == Surface.ROTATION_270) { + flipMotionOrientation = false + } + + if (event.sensor.type == Sensor.TYPE_ACCELEROMETER) { + if (flipMotionOrientation) { + accel[0] = event.values[1] / SensorManager.GRAVITY_EARTH + accel[1] = -event.values[0] / SensorManager.GRAVITY_EARTH + } else { + accel[0] = -event.values[1] / SensorManager.GRAVITY_EARTH + accel[1] = event.values[0] / SensorManager.GRAVITY_EARTH + } + accel[2] = -event.values[2] / SensorManager.GRAVITY_EARTH + } + if (event.sensor.type == Sensor.TYPE_GYROSCOPE) { + // Investigate why sensor value is off by 6x + if (flipMotionOrientation) { + gyro[0] = -event.values[1] / 6.0f + gyro[1] = event.values[0] / 6.0f + } else { + gyro[0] = event.values[1] / 6.0f + gyro[1] = -event.values[0] / 6.0f + } + gyro[2] = event.values[2] / 6.0f + } + + // Only update state on accelerometer data + if (event.sensor.type != Sensor.TYPE_ACCELEROMETER) { + return + } + val deltaTimestamp = (event.timestamp - motionTimestamp) / 1000 + motionTimestamp = event.timestamp + NativeInput.onDeviceMotionEvent( + NativeInput.Player1Device, + deltaTimestamp, + gyro[0], + gyro[1], + gyro[2], + accel[0], + accel[1], + accel[2] + ) + NativeInput.onDeviceMotionEvent( + NativeInput.ConsoleDevice, + deltaTimestamp, + gyro[0], + gyro[1], + gyro[2], + accel[0], + accel[1], + accel[2] + ) + } + + override fun onAccuracyChanged(sensor: Sensor, i: Int) {} + + private fun enableFullscreenImmersive() { + WindowCompat.setDecorFitsSystemWindows(window, false) + + WindowInsetsControllerCompat(window, window.decorView).let { controller -> + controller.hide(WindowInsetsCompat.Type.systemBars()) + controller.systemBarsBehavior = + WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE + } + } + + private fun PictureInPictureParams.Builder.getPictureInPictureAspectBuilder(): + PictureInPictureParams.Builder { + val aspectRatio = when (IntSetting.RENDERER_ASPECT_RATIO.getInt()) { + 0 -> Rational(16, 9) + 1 -> Rational(4, 3) + 2 -> Rational(21, 9) + 3 -> Rational(16, 10) + else -> null // Best fit + } + return this.apply { aspectRatio?.let { setAspectRatio(it) } } + } + + private fun PictureInPictureParams.Builder.getPictureInPictureActionsBuilder(): + PictureInPictureParams.Builder { + val pictureInPictureActions: MutableList = mutableListOf() + val pendingFlags = PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE + + if (NativeLibrary.isPaused()) { + val playIcon = Icon.createWithResource(this@EmulationActivity, R.drawable.ic_pip_play) + val playPendingIntent = PendingIntent.getBroadcast( + this@EmulationActivity, + R.drawable.ic_pip_play, + Intent(actionPlay), + pendingFlags + ) + val playRemoteAction = RemoteAction( + playIcon, + getString(R.string.play), + getString(R.string.play), + playPendingIntent + ) + pictureInPictureActions.add(playRemoteAction) + } else { + val pauseIcon = Icon.createWithResource(this@EmulationActivity, R.drawable.ic_pip_pause) + val pausePendingIntent = PendingIntent.getBroadcast( + this@EmulationActivity, + R.drawable.ic_pip_pause, + Intent(actionPause), + pendingFlags + ) + val pauseRemoteAction = RemoteAction( + pauseIcon, + getString(R.string.pause), + getString(R.string.pause), + pausePendingIntent + ) + pictureInPictureActions.add(pauseRemoteAction) + } + + if (BooleanSetting.AUDIO_MUTED.getBoolean()) { + val unmuteIcon = Icon.createWithResource( + this@EmulationActivity, + R.drawable.ic_pip_unmute + ) + val unmutePendingIntent = PendingIntent.getBroadcast( + this@EmulationActivity, + R.drawable.ic_pip_unmute, + Intent(actionUnmute), + pendingFlags + ) + val unmuteRemoteAction = RemoteAction( + unmuteIcon, + getString(R.string.unmute), + getString(R.string.unmute), + unmutePendingIntent + ) + pictureInPictureActions.add(unmuteRemoteAction) + } else { + val muteIcon = Icon.createWithResource(this@EmulationActivity, R.drawable.ic_pip_mute) + val mutePendingIntent = PendingIntent.getBroadcast( + this@EmulationActivity, + R.drawable.ic_pip_mute, + Intent(actionMute), + pendingFlags + ) + val muteRemoteAction = RemoteAction( + muteIcon, + getString(R.string.mute), + getString(R.string.mute), + mutePendingIntent + ) + pictureInPictureActions.add(muteRemoteAction) + } + + return this.apply { setActions(pictureInPictureActions) } + } + + fun buildPictureInPictureParams() { + val pictureInPictureParamsBuilder = PictureInPictureParams.Builder() + .getPictureInPictureActionsBuilder().getPictureInPictureAspectBuilder() + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + val isEmulationActive = emulationViewModel.emulationStarted.value && + !emulationViewModel.isEmulationStopping.value + pictureInPictureParamsBuilder.setAutoEnterEnabled( + BooleanSetting.PICTURE_IN_PICTURE.getBoolean() && isEmulationActive + ) + } + setPictureInPictureParams(pictureInPictureParamsBuilder.build()) + } + + private var pictureInPictureReceiver = object : BroadcastReceiver() { + override fun onReceive(context: Context?, intent: Intent) { + if (intent.action == actionPlay) { + if (NativeLibrary.isPaused()) NativeLibrary.unpauseEmulation() + } else if (intent.action == actionPause) { + if (!NativeLibrary.isPaused()) NativeLibrary.pauseEmulation() + } + if (intent.action == actionUnmute) { + if (BooleanSetting.AUDIO_MUTED.getBoolean()) { + BooleanSetting.AUDIO_MUTED.setBoolean(false) + } + } else if (intent.action == actionMute) { + if (!BooleanSetting.AUDIO_MUTED.getBoolean()) { + BooleanSetting.AUDIO_MUTED.setBoolean(true) + } + } + buildPictureInPictureParams() + } + } + + @SuppressLint("UnspecifiedRegisterReceiverFlag") + override fun onPictureInPictureModeChanged( + isInPictureInPictureMode: Boolean, + newConfig: Configuration + ) { + super.onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig) + if (isInPictureInPictureMode) { + IntentFilter().apply { + addAction(actionPause) + addAction(actionPlay) + addAction(actionMute) + addAction(actionUnmute) + }.also { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + registerReceiver(pictureInPictureReceiver, it, RECEIVER_EXPORTED) + } else { + registerReceiver(pictureInPictureReceiver, it) + } + } + } else { + try { + unregisterReceiver(pictureInPictureReceiver) + } catch (ignored: Exception) { + } + // Always resume audio, since there is no UI button + if (BooleanSetting.AUDIO_MUTED.getBoolean()) { + BooleanSetting.AUDIO_MUTED.setBoolean(false) + } + } + } + + fun onEmulationStarted() { + emulationViewModel.setEmulationStarted(true) + } + + fun onEmulationStopped(status: Int) { + if (status == 0 && emulationViewModel.programChanged.value == -1) { + finish() + } + emulationViewModel.setEmulationStopped(true) + } + + fun onProgramChanged(programIndex: Int) { + emulationViewModel.setProgramChanged(programIndex) + } + + private fun startMotionSensorListener() { + val sensorManager = this.getSystemService(Context.SENSOR_SERVICE) as SensorManager + val gyroSensor = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE) + val accelSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) + sensorManager.registerListener(this, gyroSensor, SensorManager.SENSOR_DELAY_GAME) + sensorManager.registerListener(this, accelSensor, SensorManager.SENSOR_DELAY_GAME) + } + + private fun stopMotionSensorListener() { + val sensorManager = this.getSystemService(Context.SENSOR_SERVICE) as SensorManager + val gyroSensor = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE) + val accelSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) + + sensorManager.unregisterListener(this, gyroSensor) + sensorManager.unregisterListener(this, accelSensor) + } + + companion object { + const val EXTRA_SELECTED_GAME = "SelectedGame" + + fun launch(activity: AppCompatActivity, game: Game) { + val launcher = Intent(activity, EmulationActivity::class.java) + launcher.putExtra(EXTRA_SELECTED_GAME, game) + activity.startActivity(launcher) + } + + private fun areCoordinatesOutside(view: View?, x: Float, y: Float): Boolean { + if (view == null) { + return true + } + val viewBounds = Rect() + view.getGlobalVisibleRect(viewBounds) + return !viewBounds.contains(x.roundToInt(), y.roundToInt()) + } + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/adapters/AbstractDiffAdapter.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/adapters/AbstractDiffAdapter.kt new file mode 100644 index 0000000..b145080 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/adapters/AbstractDiffAdapter.kt @@ -0,0 +1,38 @@ +// SPDX-FileCopyrightText: 2024 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.adapters + +import android.annotation.SuppressLint +import androidx.recyclerview.widget.AsyncDifferConfig +import androidx.recyclerview.widget.DiffUtil +import androidx.recyclerview.widget.ListAdapter +import org.sudachi.sudachi_emu.viewholder.AbstractViewHolder +import androidx.recyclerview.widget.RecyclerView + +/** + * Generic adapter that implements an [AsyncDifferConfig] and covers some of the basic boilerplate + * code used in every [RecyclerView]. + * Type assigned to [Model] must inherit from [Object] in order to be compared properly. + * @param exact Decides whether each item will be compared by reference or by their contents + */ +abstract class AbstractDiffAdapter>( + exact: Boolean = true +) : ListAdapter(AsyncDifferConfig.Builder(DiffCallback(exact)).build()) { + override fun onBindViewHolder(holder: Holder, position: Int) = + holder.bind(currentList[position]) + + private class DiffCallback(val exact: Boolean) : DiffUtil.ItemCallback() { + override fun areItemsTheSame(oldItem: Model & Any, newItem: Model & Any): Boolean { + if (exact) { + return oldItem === newItem + } + return oldItem == newItem + } + + @SuppressLint("DiffUtilEquals") + override fun areContentsTheSame(oldItem: Model & Any, newItem: Model & Any): Boolean { + return oldItem == newItem + } + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/adapters/AbstractListAdapter.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/adapters/AbstractListAdapter.kt new file mode 100644 index 0000000..2a99788 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/adapters/AbstractListAdapter.kt @@ -0,0 +1,98 @@ +// SPDX-FileCopyrightText: 2024 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.adapters + +import android.annotation.SuppressLint +import androidx.recyclerview.widget.RecyclerView +import org.sudachi.sudachi_emu.viewholder.AbstractViewHolder + +/** + * Generic list class meant to take care of basic lists + * @param currentList The list to show initially + */ +abstract class AbstractListAdapter>( + open var currentList: List +) : RecyclerView.Adapter() { + override fun onBindViewHolder(holder: Holder, position: Int) = + holder.bind(currentList[position]) + + override fun getItemCount(): Int = currentList.size + + /** + * Adds an item to [currentList] and notifies the underlying adapter of the change. If no parameter + * is passed in for position, [item] is added to the end of the list. Invokes [callback] last. + * @param item The item to add to the list + * @param position Index where [item] will be added + * @param callback Lambda that's called at the end of the list changes and has the added list + * position passed in as a parameter + */ + open fun addItem(item: Model, position: Int = -1, callback: ((position: Int) -> Unit)? = null) { + val newList = currentList.toMutableList() + val positionToUpdate: Int + if (position == -1) { + newList.add(item) + currentList = newList + positionToUpdate = currentList.size - 1 + } else { + newList.add(position, item) + currentList = newList + positionToUpdate = position + } + onItemAdded(positionToUpdate, callback) + } + + protected fun onItemAdded(position: Int, callback: ((Int) -> Unit)? = null) { + notifyItemInserted(position) + callback?.invoke(position) + } + + /** + * Replaces the [item] at [position] in the [currentList] and notifies the underlying adapter + * of the change. Invokes [callback] last. + * @param item New list item + * @param position Index where [item] will replace the existing list item + * @param callback Lambda that's called at the end of the list changes and has the changed list + * position passed in as a parameter + */ + fun changeItem(item: Model, position: Int, callback: ((position: Int) -> Unit)? = null) { + val newList = currentList.toMutableList() + newList[position] = item + currentList = newList + onItemChanged(position, callback) + } + + protected fun onItemChanged(position: Int, callback: ((Int) -> Unit)? = null) { + notifyItemChanged(position) + callback?.invoke(position) + } + + /** + * Removes the list item at [position] in [currentList] and notifies the underlying adapter + * of the change. Invokes [callback] last. + * @param position Index where the list item will be removed + * @param callback Lambda that's called at the end of the list changes and has the removed list + * position passed in as a parameter + */ + fun removeItem(position: Int, callback: ((position: Int) -> Unit)? = null) { + val newList = currentList.toMutableList() + newList.removeAt(position) + currentList = newList + onItemRemoved(position, callback) + } + + protected fun onItemRemoved(position: Int, callback: ((Int) -> Unit)? = null) { + notifyItemRemoved(position) + callback?.invoke(position) + } + + /** + * Replaces [currentList] with [newList] and notifies the underlying adapter of the change. + * @param newList The new list to replace [currentList] + */ + @SuppressLint("NotifyDataSetChanged") + open fun replaceList(newList: List) { + currentList = newList + notifyDataSetChanged() + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/adapters/AbstractSingleSelectionList.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/adapters/AbstractSingleSelectionList.kt new file mode 100644 index 0000000..5122fa4 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/adapters/AbstractSingleSelectionList.kt @@ -0,0 +1,105 @@ +// SPDX-FileCopyrightText: 2024 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.adapters + +import org.sudachi.sudachi_emu.model.SelectableItem +import org.sudachi.sudachi_emu.viewholder.AbstractViewHolder + +/** + * Generic list class meant to take care of single selection UI updates + * @param currentList The list to show initially + * @param defaultSelection The default selection to use if no list items are selected by + * [SelectableItem.selected] or if the currently selected item is removed from the list + */ +abstract class AbstractSingleSelectionList< + Model : SelectableItem, + Holder : AbstractViewHolder + >( + final override var currentList: List, + private val defaultSelection: DefaultSelection = DefaultSelection.Start +) : AbstractListAdapter(currentList) { + var selectedItem = getDefaultSelection() + + init { + findSelectedItem() + } + + /** + * Changes the selection state of the [SelectableItem] that was selected and the previously selected + * item and notifies the underlying adapter of the change for those items. Invokes [callback] last. + * Does nothing if [position] is the same as the currently selected item. + * @param position Index of the item that was selected + * @param callback Lambda that's called at the end of the list changes and has the selected list + * position passed in as a parameter + */ + fun selectItem(position: Int, callback: ((position: Int) -> Unit)? = null) { + if (position == selectedItem) { + return + } + + val previouslySelectedItem = selectedItem + selectedItem = position + if (currentList.indices.contains(selectedItem)) { + currentList[selectedItem].onSelectionStateChanged(true) + } + if (currentList.indices.contains(previouslySelectedItem)) { + currentList[previouslySelectedItem].onSelectionStateChanged(false) + } + onItemChanged(previouslySelectedItem) + onItemChanged(selectedItem) + callback?.invoke(position) + } + + /** + * Removes a given item from the list and notifies the underlying adapter of the change. If the + * currently selected item was the item that was removed, the item at the position provided + * by [defaultSelection] will be made the new selection. Invokes [callback] last. + * @param position Index of the item that was removed + * @param callback Lambda that's called at the end of the list changes and has the removed and + * selected list positions passed in as parameters + */ + fun removeSelectableItem( + position: Int, + callback: ((removedPosition: Int, selectedPosition: Int) -> Unit)? + ) { + removeItem(position) + if (position == selectedItem) { + selectedItem = getDefaultSelection() + currentList[selectedItem].onSelectionStateChanged(true) + onItemChanged(selectedItem) + } else if (position < selectedItem) { + selectedItem-- + } + callback?.invoke(position, selectedItem) + } + + override fun addItem(item: Model, position: Int, callback: ((Int) -> Unit)?) { + super.addItem(item, position, callback) + if (position <= selectedItem && position != -1) { + selectedItem++ + } + } + + override fun replaceList(newList: List) { + super.replaceList(newList) + findSelectedItem() + } + + private fun findSelectedItem() { + for (i in currentList.indices) { + if (currentList[i].selected) { + selectedItem = i + break + } + } + } + + private fun getDefaultSelection(): Int = + when (defaultSelection) { + DefaultSelection.Start -> currentList.indices.first + DefaultSelection.End -> currentList.indices.last + } + + enum class DefaultSelection { Start, End } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/adapters/AddonAdapter.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/adapters/AddonAdapter.kt new file mode 100644 index 0000000..92824b2 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/adapters/AddonAdapter.kt @@ -0,0 +1,37 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.adapters + +import android.view.LayoutInflater +import android.view.ViewGroup +import org.sudachi.sudachi_emu.databinding.ListItemAddonBinding +import org.sudachi.sudachi_emu.model.Patch +import org.sudachi.sudachi_emu.model.AddonViewModel +import org.sudachi.sudachi_emu.viewholder.AbstractViewHolder + +class AddonAdapter(val addonViewModel: AddonViewModel) : + AbstractDiffAdapter() { + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AddonViewHolder { + ListItemAddonBinding.inflate(LayoutInflater.from(parent.context), parent, false) + .also { return AddonViewHolder(it) } + } + + inner class AddonViewHolder(val binding: ListItemAddonBinding) : + AbstractViewHolder(binding) { + override fun bind(model: Patch) { + binding.root.setOnClickListener { + binding.addonCheckbox.isChecked = !binding.addonCheckbox.isChecked + } + binding.title.text = model.name + binding.version.text = model.version + binding.addonCheckbox.setOnCheckedChangeListener { _, checked -> + model.enabled = checked + } + binding.addonCheckbox.isChecked = model.enabled + binding.buttonDelete.setOnClickListener { + addonViewModel.setAddonToDelete(model) + } + } + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/adapters/AppletAdapter.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/adapters/AppletAdapter.kt new file mode 100644 index 0000000..10db1f7 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/adapters/AppletAdapter.kt @@ -0,0 +1,74 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.adapters + +import android.view.LayoutInflater +import android.view.ViewGroup +import android.widget.Toast +import androidx.core.content.res.ResourcesCompat +import androidx.fragment.app.FragmentActivity +import androidx.navigation.findNavController +import org.sudachi.sudachi_emu.HomeNavigationDirections +import org.sudachi.sudachi_emu.NativeLibrary +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.SudachiApplication +import org.sudachi.sudachi_emu.databinding.CardSimpleOutlinedBinding +import org.sudachi.sudachi_emu.model.Applet +import org.sudachi.sudachi_emu.model.AppletInfo +import org.sudachi.sudachi_emu.model.Game +import org.sudachi.sudachi_emu.viewholder.AbstractViewHolder + +class AppletAdapter(val activity: FragmentActivity, applets: List) : + AbstractListAdapter(applets) { + override fun onCreateViewHolder( + parent: ViewGroup, + viewType: Int + ): AppletAdapter.AppletViewHolder { + CardSimpleOutlinedBinding.inflate(LayoutInflater.from(parent.context), parent, false) + .also { return AppletViewHolder(it) } + } + + inner class AppletViewHolder(val binding: CardSimpleOutlinedBinding) : + AbstractViewHolder(binding) { + override fun bind(model: Applet) { + binding.title.setText(model.titleId) + binding.description.setText(model.descriptionId) + binding.icon.setImageDrawable( + ResourcesCompat.getDrawable( + binding.icon.context.resources, + model.iconId, + binding.icon.context.theme + ) + ) + + binding.root.setOnClickListener { onClick(model) } + } + + fun onClick(applet: Applet) { + val appletPath = NativeLibrary.getAppletLaunchPath(applet.appletInfo.entryId) + if (appletPath.isEmpty()) { + Toast.makeText( + binding.root.context, + R.string.applets_error_applet, + Toast.LENGTH_SHORT + ).show() + return + } + + if (applet.appletInfo == AppletInfo.Cabinet) { + binding.root.findNavController() + .navigate(R.id.action_appletLauncherFragment_to_cabinetLauncherDialogFragment) + return + } + + NativeLibrary.setCurrentAppletId(applet.appletInfo.appletId) + val appletGame = Game( + title = SudachiApplication.appContext.getString(applet.titleId), + path = appletPath + ) + val action = HomeNavigationDirections.actionGlobalEmulationActivity(appletGame) + binding.root.findNavController().navigate(action) + } + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/adapters/CabinetLauncherDialogAdapter.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/adapters/CabinetLauncherDialogAdapter.kt new file mode 100644 index 0000000..c3d1298 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/adapters/CabinetLauncherDialogAdapter.kt @@ -0,0 +1,59 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.adapters + +import android.view.LayoutInflater +import android.view.ViewGroup +import androidx.core.content.res.ResourcesCompat +import androidx.fragment.app.Fragment +import androidx.navigation.fragment.findNavController +import org.sudachi.sudachi_emu.HomeNavigationDirections +import org.sudachi.sudachi_emu.NativeLibrary +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.SudachiApplication +import org.sudachi.sudachi_emu.databinding.DialogListItemBinding +import org.sudachi.sudachi_emu.model.CabinetMode +import org.sudachi.sudachi_emu.adapters.CabinetLauncherDialogAdapter.CabinetModeViewHolder +import org.sudachi.sudachi_emu.model.AppletInfo +import org.sudachi.sudachi_emu.model.Game +import org.sudachi.sudachi_emu.viewholder.AbstractViewHolder + +class CabinetLauncherDialogAdapter(val fragment: Fragment) : + AbstractListAdapter( + CabinetMode.values().copyOfRange(1, CabinetMode.entries.size).toList() + ) { + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CabinetModeViewHolder { + DialogListItemBinding.inflate(LayoutInflater.from(parent.context), parent, false) + .also { return CabinetModeViewHolder(it) } + } + + inner class CabinetModeViewHolder(val binding: DialogListItemBinding) : + AbstractViewHolder(binding) { + override fun bind(model: CabinetMode) { + binding.icon.setImageDrawable( + ResourcesCompat.getDrawable( + binding.icon.context.resources, + model.iconId, + binding.icon.context.theme + ) + ) + binding.title.setText(model.titleId) + + binding.root.setOnClickListener { onClick(model) } + } + + private fun onClick(mode: CabinetMode) { + val appletPath = NativeLibrary.getAppletLaunchPath(AppletInfo.Cabinet.entryId) + NativeLibrary.setCurrentAppletId(AppletInfo.Cabinet.appletId) + NativeLibrary.setCabinetMode(mode.id) + val appletGame = Game( + title = SudachiApplication.appContext.getString(R.string.cabinet_applet), + path = appletPath + ) + val action = HomeNavigationDirections.actionGlobalEmulationActivity(appletGame) + fragment.findNavController().navigate(action) + } + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/adapters/DriverAdapter.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/adapters/DriverAdapter.kt new file mode 100644 index 0000000..65ff222 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/adapters/DriverAdapter.kt @@ -0,0 +1,59 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.adapters + +import android.view.LayoutInflater +import android.view.ViewGroup +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.databinding.CardDriverOptionBinding +import org.sudachi.sudachi_emu.features.settings.model.StringSetting +import org.sudachi.sudachi_emu.model.Driver +import org.sudachi.sudachi_emu.model.DriverViewModel +import org.sudachi.sudachi_emu.utils.ViewUtils.marquee +import org.sudachi.sudachi_emu.utils.ViewUtils.setVisible +import org.sudachi.sudachi_emu.viewholder.AbstractViewHolder + +class DriverAdapter(private val driverViewModel: DriverViewModel) : + AbstractSingleSelectionList( + driverViewModel.driverList.value + ) { + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DriverViewHolder { + CardDriverOptionBinding.inflate(LayoutInflater.from(parent.context), parent, false) + .also { return DriverViewHolder(it) } + } + + inner class DriverViewHolder(val binding: CardDriverOptionBinding) : + AbstractViewHolder(binding) { + override fun bind(model: Driver) { + binding.apply { + radioButton.isChecked = model.selected + root.setOnClickListener { + selectItem(bindingAdapterPosition) { + driverViewModel.onDriverSelected(it) + driverViewModel.showClearButton(!StringSetting.DRIVER_PATH.global) + } + } + buttonDelete.setOnClickListener { + removeSelectableItem( + bindingAdapterPosition + ) { removedPosition: Int, selectedPosition: Int -> + driverViewModel.onDriverRemoved(removedPosition, selectedPosition) + driverViewModel.showClearButton(!StringSetting.DRIVER_PATH.global) + } + } + + // Delay marquee by 3s + title.marquee() + version.marquee() + description.marquee() + title.text = model.title + version.text = model.version + description.text = model.description + buttonDelete.setVisible( + model.title != binding.root.context.getString(R.string.system_gpu_driver) + ) + } + } + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/adapters/FolderAdapter.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/adapters/FolderAdapter.kt new file mode 100644 index 0000000..703280d --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/adapters/FolderAdapter.kt @@ -0,0 +1,48 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.adapters + +import android.net.Uri +import android.view.LayoutInflater +import android.view.ViewGroup +import androidx.fragment.app.FragmentActivity +import org.sudachi.sudachi_emu.databinding.CardFolderBinding +import org.sudachi.sudachi_emu.fragments.GameFolderPropertiesDialogFragment +import org.sudachi.sudachi_emu.model.GameDir +import org.sudachi.sudachi_emu.model.GamesViewModel +import org.sudachi.sudachi_emu.utils.ViewUtils.marquee +import org.sudachi.sudachi_emu.viewholder.AbstractViewHolder + +class FolderAdapter(val activity: FragmentActivity, val gamesViewModel: GamesViewModel) : + AbstractDiffAdapter() { + override fun onCreateViewHolder( + parent: ViewGroup, + viewType: Int + ): FolderAdapter.FolderViewHolder { + CardFolderBinding.inflate(LayoutInflater.from(parent.context), parent, false) + .also { return FolderViewHolder(it) } + } + + inner class FolderViewHolder(val binding: CardFolderBinding) : + AbstractViewHolder(binding) { + override fun bind(model: GameDir) { + binding.apply { + path.text = Uri.parse(model.uriString).path + path.marquee() + + buttonEdit.setOnClickListener { + GameFolderPropertiesDialogFragment.newInstance(model) + .show( + activity.supportFragmentManager, + GameFolderPropertiesDialogFragment.TAG + ) + } + + buttonDelete.setOnClickListener { + gamesViewModel.removeFolder(model) + } + } + } + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/adapters/GameAdapter.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/adapters/GameAdapter.kt new file mode 100644 index 0000000..b396326 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/adapters/GameAdapter.kt @@ -0,0 +1,99 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.adapters + +import android.net.Uri +import android.view.LayoutInflater +import android.view.ViewGroup +import android.widget.ImageView +import android.widget.Toast +import androidx.appcompat.app.AppCompatActivity +import androidx.core.content.pm.ShortcutInfoCompat +import androidx.core.content.pm.ShortcutManagerCompat +import androidx.documentfile.provider.DocumentFile +import androidx.lifecycle.ViewModelProvider +import androidx.lifecycle.lifecycleScope +import androidx.navigation.findNavController +import androidx.preference.PreferenceManager +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import org.sudachi.sudachi_emu.HomeNavigationDirections +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.SudachiApplication +import org.sudachi.sudachi_emu.databinding.CardGameBinding +import org.sudachi.sudachi_emu.model.Game +import org.sudachi.sudachi_emu.model.GamesViewModel +import org.sudachi.sudachi_emu.utils.GameIconUtils +import org.sudachi.sudachi_emu.utils.ViewUtils.marquee +import org.sudachi.sudachi_emu.viewholder.AbstractViewHolder + +class GameAdapter(private val activity: AppCompatActivity) : + AbstractDiffAdapter(exact = false) { + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): GameViewHolder { + CardGameBinding.inflate(LayoutInflater.from(parent.context), parent, false) + .also { return GameViewHolder(it) } + } + + inner class GameViewHolder(val binding: CardGameBinding) : + AbstractViewHolder(binding) { + override fun bind(model: Game) { + binding.imageGameScreen.scaleType = ImageView.ScaleType.CENTER_CROP + GameIconUtils.loadGameIcon(model, binding.imageGameScreen) + + binding.textGameTitle.text = model.title.replace("[\\t\\n\\r]+".toRegex(), " ") + + binding.textGameTitle.marquee() + binding.cardGame.setOnClickListener { onClick(model) } + binding.cardGame.setOnLongClickListener { onLongClick(model) } + } + + fun onClick(game: Game) { + val gameExists = DocumentFile.fromSingleUri( + SudachiApplication.appContext, + Uri.parse(game.path) + )?.exists() == true + if (!gameExists) { + Toast.makeText( + SudachiApplication.appContext, + R.string.loader_error_file_not_found, + Toast.LENGTH_LONG + ).show() + + ViewModelProvider(activity)[GamesViewModel::class.java].reloadGames(true) + return + } + + val preferences = + PreferenceManager.getDefaultSharedPreferences(SudachiApplication.appContext) + preferences.edit() + .putLong( + game.keyLastPlayedTime, + System.currentTimeMillis() + ) + .apply() + + activity.lifecycleScope.launch { + withContext(Dispatchers.IO) { + val shortcut = + ShortcutInfoCompat.Builder(SudachiApplication.appContext, game.path) + .setShortLabel(game.title) + .setIcon(GameIconUtils.getShortcutIcon(activity, game)) + .setIntent(game.launchIntent) + .build() + ShortcutManagerCompat.pushDynamicShortcut(SudachiApplication.appContext, shortcut) + } + } + + val action = HomeNavigationDirections.actionGlobalEmulationActivity(game, true) + binding.root.findNavController().navigate(action) + } + + fun onLongClick(game: Game): Boolean { + val action = HomeNavigationDirections.actionGlobalPerGamePropertiesFragment(game) + binding.root.findNavController().navigate(action) + return true + } + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/adapters/GamePropertiesAdapter.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/adapters/GamePropertiesAdapter.kt new file mode 100644 index 0000000..79424bb --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/adapters/GamePropertiesAdapter.kt @@ -0,0 +1,115 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.adapters + +import android.view.LayoutInflater +import android.view.ViewGroup +import androidx.core.content.res.ResourcesCompat +import androidx.lifecycle.LifecycleOwner +import org.sudachi.sudachi_emu.databinding.CardInstallableIconBinding +import org.sudachi.sudachi_emu.databinding.CardSimpleOutlinedBinding +import org.sudachi.sudachi_emu.model.GameProperty +import org.sudachi.sudachi_emu.model.InstallableProperty +import org.sudachi.sudachi_emu.model.SubmenuProperty +import org.sudachi.sudachi_emu.utils.ViewUtils.marquee +import org.sudachi.sudachi_emu.utils.ViewUtils.setVisible +import org.sudachi.sudachi_emu.utils.collect +import org.sudachi.sudachi_emu.viewholder.AbstractViewHolder + +class GamePropertiesAdapter( + private val viewLifecycle: LifecycleOwner, + private var properties: List +) : AbstractListAdapter>(properties) { + override fun onCreateViewHolder( + parent: ViewGroup, + viewType: Int + ): AbstractViewHolder { + val inflater = LayoutInflater.from(parent.context) + return when (viewType) { + PropertyType.Submenu.ordinal -> { + SubmenuPropertyViewHolder( + CardSimpleOutlinedBinding.inflate( + inflater, + parent, + false + ) + ) + } + + else -> InstallablePropertyViewHolder( + CardInstallableIconBinding.inflate( + inflater, + parent, + false + ) + ) + } + } + + override fun getItemViewType(position: Int): Int { + return when (properties[position]) { + is SubmenuProperty -> PropertyType.Submenu.ordinal + else -> PropertyType.Installable.ordinal + } + } + + inner class SubmenuPropertyViewHolder(val binding: CardSimpleOutlinedBinding) : + AbstractViewHolder(binding) { + override fun bind(model: GameProperty) { + val submenuProperty = model as SubmenuProperty + + binding.root.setOnClickListener { + submenuProperty.action.invoke() + } + + binding.title.setText(submenuProperty.titleId) + binding.description.setText(submenuProperty.descriptionId) + binding.icon.setImageDrawable( + ResourcesCompat.getDrawable( + binding.icon.context.resources, + submenuProperty.iconId, + binding.icon.context.theme + ) + ) + + binding.details.marquee() + if (submenuProperty.details != null) { + binding.details.setVisible(true) + binding.details.text = submenuProperty.details.invoke() + } else if (submenuProperty.detailsFlow != null) { + binding.details.setVisible(true) + submenuProperty.detailsFlow.collect(viewLifecycle) { binding.details.text = it } + } else { + binding.details.setVisible(false) + } + } + } + + inner class InstallablePropertyViewHolder(val binding: CardInstallableIconBinding) : + AbstractViewHolder(binding) { + override fun bind(model: GameProperty) { + val installableProperty = model as InstallableProperty + + binding.title.setText(installableProperty.titleId) + binding.description.setText(installableProperty.descriptionId) + binding.icon.setImageDrawable( + ResourcesCompat.getDrawable( + binding.icon.context.resources, + installableProperty.iconId, + binding.icon.context.theme + ) + ) + + binding.buttonInstall.setVisible(installableProperty.install != null) + binding.buttonInstall.setOnClickListener { installableProperty.install?.invoke() } + binding.buttonExport.setVisible(installableProperty.export != null) + binding.buttonExport.setOnClickListener { installableProperty.export?.invoke() } + } + } + + enum class PropertyType { + Submenu, + Installable + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/adapters/HomeSettingAdapter.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/adapters/HomeSettingAdapter.kt new file mode 100644 index 0000000..6cdf533 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/adapters/HomeSettingAdapter.kt @@ -0,0 +1,84 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.adapters + +import android.view.LayoutInflater +import android.view.ViewGroup +import androidx.appcompat.app.AppCompatActivity +import androidx.core.content.ContextCompat +import androidx.core.content.res.ResourcesCompat +import androidx.lifecycle.LifecycleOwner +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.databinding.CardHomeOptionBinding +import org.sudachi.sudachi_emu.fragments.MessageDialogFragment +import org.sudachi.sudachi_emu.model.HomeSetting +import org.sudachi.sudachi_emu.utils.ViewUtils.marquee +import org.sudachi.sudachi_emu.utils.ViewUtils.setVisible +import org.sudachi.sudachi_emu.utils.collect +import org.sudachi.sudachi_emu.viewholder.AbstractViewHolder + +class HomeSettingAdapter( + private val activity: AppCompatActivity, + private val viewLifecycle: LifecycleOwner, + options: List +) : AbstractListAdapter(options) { + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HomeOptionViewHolder { + CardHomeOptionBinding.inflate(LayoutInflater.from(parent.context), parent, false) + .also { return HomeOptionViewHolder(it) } + } + + inner class HomeOptionViewHolder(val binding: CardHomeOptionBinding) : + AbstractViewHolder(binding) { + override fun bind(model: HomeSetting) { + binding.optionTitle.text = activity.resources.getString(model.titleId) + binding.optionDescription.text = activity.resources.getString(model.descriptionId) + binding.optionIcon.setImageDrawable( + ResourcesCompat.getDrawable( + activity.resources, + model.iconId, + activity.theme + ) + ) + + when (model.titleId) { + R.string.get_early_access -> + binding.optionLayout.background = + ContextCompat.getDrawable( + binding.optionCard.context, + R.drawable.premium_background + ) + } + + if (!model.isEnabled.invoke()) { + binding.optionTitle.alpha = 0.5f + binding.optionDescription.alpha = 0.5f + binding.optionIcon.alpha = 0.5f + } + + model.details.collect(viewLifecycle) { updateOptionDetails(it) } + binding.optionDetail.marquee() + + binding.root.setOnClickListener { onClick(model) } + } + + private fun onClick(model: HomeSetting) { + if (model.isEnabled.invoke()) { + model.onClick.invoke() + } else { + MessageDialogFragment.newInstance( + activity, + titleId = model.disabledTitleId, + descriptionId = model.disabledMessageId + ).show(activity.supportFragmentManager, MessageDialogFragment.TAG) + } + } + + private fun updateOptionDetails(detailString: String) { + if (detailString.isNotEmpty()) { + binding.optionDetail.text = detailString + binding.optionDetail.setVisible(true) + } + } + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/adapters/InstallableAdapter.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/adapters/InstallableAdapter.kt new file mode 100644 index 0000000..38fa196 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/adapters/InstallableAdapter.kt @@ -0,0 +1,35 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.adapters + +import android.view.LayoutInflater +import android.view.ViewGroup +import org.sudachi.sudachi_emu.databinding.CardInstallableBinding +import org.sudachi.sudachi_emu.model.Installable +import org.sudachi.sudachi_emu.utils.ViewUtils.setVisible +import org.sudachi.sudachi_emu.viewholder.AbstractViewHolder + +class InstallableAdapter(installables: List) : + AbstractListAdapter(installables) { + override fun onCreateViewHolder( + parent: ViewGroup, + viewType: Int + ): InstallableAdapter.InstallableViewHolder { + CardInstallableBinding.inflate(LayoutInflater.from(parent.context), parent, false) + .also { return InstallableViewHolder(it) } + } + + inner class InstallableViewHolder(val binding: CardInstallableBinding) : + AbstractViewHolder(binding) { + override fun bind(model: Installable) { + binding.title.setText(model.titleId) + binding.description.setText(model.descriptionId) + + binding.buttonInstall.setVisible(model.install != null) + binding.buttonInstall.setOnClickListener { model.install?.invoke() } + binding.buttonExport.setVisible(model.export != null) + binding.buttonExport.setOnClickListener { model.export?.invoke() } + } + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/adapters/LicenseAdapter.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/adapters/LicenseAdapter.kt new file mode 100644 index 0000000..dd06d2e --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/adapters/LicenseAdapter.kt @@ -0,0 +1,39 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.adapters + +import android.view.LayoutInflater +import android.view.ViewGroup +import androidx.appcompat.app.AppCompatActivity +import org.sudachi.sudachi_emu.databinding.ListItemSettingBinding +import org.sudachi.sudachi_emu.fragments.LicenseBottomSheetDialogFragment +import org.sudachi.sudachi_emu.model.License +import org.sudachi.sudachi_emu.utils.ViewUtils.setVisible +import org.sudachi.sudachi_emu.viewholder.AbstractViewHolder + +class LicenseAdapter(private val activity: AppCompatActivity, licenses: List) : + AbstractListAdapter(licenses) { + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): LicenseViewHolder { + ListItemSettingBinding.inflate(LayoutInflater.from(parent.context), parent, false) + .also { return LicenseViewHolder(it) } + } + + inner class LicenseViewHolder(val binding: ListItemSettingBinding) : + AbstractViewHolder(binding) { + override fun bind(model: License) { + binding.apply { + textSettingName.text = root.context.getString(model.titleId) + textSettingDescription.text = root.context.getString(model.descriptionId) + textSettingValue.setVisible(false) + + root.setOnClickListener { onClick(model) } + } + } + + private fun onClick(license: License) { + LicenseBottomSheetDialogFragment.newInstance(license) + .show(activity.supportFragmentManager, LicenseBottomSheetDialogFragment.TAG) + } + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/adapters/SetupAdapter.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/adapters/SetupAdapter.kt new file mode 100644 index 0000000..313ae21 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/adapters/SetupAdapter.kt @@ -0,0 +1,75 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.adapters + +import android.text.Html +import android.view.LayoutInflater +import android.view.ViewGroup +import androidx.appcompat.app.AppCompatActivity +import androidx.core.content.res.ResourcesCompat +import androidx.lifecycle.ViewModelProvider +import com.google.android.material.button.MaterialButton +import org.sudachi.sudachi_emu.databinding.PageSetupBinding +import org.sudachi.sudachi_emu.model.HomeViewModel +import org.sudachi.sudachi_emu.model.SetupCallback +import org.sudachi.sudachi_emu.model.SetupPage +import org.sudachi.sudachi_emu.model.StepState +import org.sudachi.sudachi_emu.utils.ViewUtils +import org.sudachi.sudachi_emu.utils.ViewUtils.setVisible +import org.sudachi.sudachi_emu.viewholder.AbstractViewHolder + +class SetupAdapter(val activity: AppCompatActivity, pages: List) : + AbstractListAdapter(pages) { + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SetupPageViewHolder { + PageSetupBinding.inflate(LayoutInflater.from(parent.context), parent, false) + .also { return SetupPageViewHolder(it) } + } + + inner class SetupPageViewHolder(val binding: PageSetupBinding) : + AbstractViewHolder(binding), SetupCallback { + override fun bind(model: SetupPage) { + if (model.stepCompleted.invoke() == StepState.COMPLETE) { + binding.buttonAction.setVisible(visible = false, gone = false) + binding.textConfirmation.setVisible(true) + } + + binding.icon.setImageDrawable( + ResourcesCompat.getDrawable( + activity.resources, + model.iconId, + activity.theme + ) + ) + binding.textTitle.text = activity.resources.getString(model.titleId) + binding.textDescription.text = + Html.fromHtml(activity.resources.getString(model.descriptionId), 0) + + binding.buttonAction.apply { + text = activity.resources.getString(model.buttonTextId) + if (model.buttonIconId != 0) { + icon = ResourcesCompat.getDrawable( + activity.resources, + model.buttonIconId, + activity.theme + ) + } + iconGravity = + if (model.leftAlignedIcon) { + MaterialButton.ICON_GRAVITY_START + } else { + MaterialButton.ICON_GRAVITY_END + } + setOnClickListener { + model.buttonAction.invoke(this@SetupPageViewHolder) + } + } + } + + override fun onStepCompleted() { + ViewUtils.hideView(binding.buttonAction, 200) + ViewUtils.showView(binding.textConfirmation, 200) + ViewModelProvider(activity)[HomeViewModel::class.java].setShouldPageForward(true) + } + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/applets/keyboard/SoftwareKeyboard.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/applets/keyboard/SoftwareKeyboard.kt new file mode 100644 index 0000000..390eca6 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/applets/keyboard/SoftwareKeyboard.kt @@ -0,0 +1,124 @@ +// SPDX-FileCopyrightText: Copyright 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.applets.keyboard + +import android.content.Context +import android.os.Handler +import android.os.Looper +import android.view.KeyEvent +import android.view.View +import android.view.WindowInsets +import android.view.inputmethod.InputMethodManager +import androidx.annotation.Keep +import androidx.core.view.ViewCompat +import java.io.Serializable +import org.sudachi.sudachi_emu.NativeLibrary +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.applets.keyboard.ui.KeyboardDialogFragment + +@Keep +object SoftwareKeyboard { + lateinit var data: KeyboardData + val dataLock = Object() + + private fun executeNormalImpl(config: KeyboardConfig) { + val emulationActivity = NativeLibrary.sEmulationActivity.get() + data = KeyboardData(SwkbdResult.Cancel.ordinal, "") + val fragment = KeyboardDialogFragment.newInstance(config) + fragment.show(emulationActivity!!.supportFragmentManager, KeyboardDialogFragment.TAG) + } + + private fun executeInlineImpl(config: KeyboardConfig) { + val emulationActivity = NativeLibrary.sEmulationActivity.get() + + val overlayView = emulationActivity!!.findViewById(R.id.surface_input_overlay) + val im = + overlayView.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager + im.showSoftInput(overlayView, InputMethodManager.SHOW_FORCED) + + // There isn't a good way to know that the IMM is dismissed, so poll every 500ms to submit inline keyboard result. + val handler = Handler(Looper.myLooper()!!) + val delayMs = 500 + handler.postDelayed( + object : Runnable { + override fun run() { + val insets = ViewCompat.getRootWindowInsets(overlayView) + val isKeyboardVisible = insets!!.isVisible(WindowInsets.Type.ime()) + if (isKeyboardVisible) { + handler.postDelayed(this, delayMs.toLong()) + return + } + + // No longer visible, submit the result. + NativeLibrary.submitInlineKeyboardInput(KeyEvent.KEYCODE_ENTER) + } + }, + delayMs.toLong() + ) + } + + @JvmStatic + fun executeNormal(config: KeyboardConfig): KeyboardData { + NativeLibrary.sEmulationActivity.get()!!.runOnUiThread { executeNormalImpl(config) } + synchronized(dataLock) { + dataLock.wait() + } + return data + } + + @JvmStatic + fun executeInline(config: KeyboardConfig) { + NativeLibrary.sEmulationActivity.get()!!.runOnUiThread { executeInlineImpl(config) } + } + + // Corresponds to Service::AM::Applets::SwkbdType + enum class SwkbdType { + Normal, + NumberPad, + Qwerty, + Unknown3, + Latin, + SimplifiedChinese, + TraditionalChinese, + Korean + } + + // Corresponds to Service::AM::Applets::SwkbdPasswordMode + enum class SwkbdPasswordMode { + Disabled, + Enabled + } + + // Corresponds to Service::AM::Applets::SwkbdResult + enum class SwkbdResult { + Ok, + Cancel + } + + @Keep + data class KeyboardConfig( + var ok_text: String? = null, + var header_text: String? = null, + var sub_text: String? = null, + var guide_text: String? = null, + var initial_text: String? = null, + var left_optional_symbol_key: Short = 0, + var right_optional_symbol_key: Short = 0, + var max_text_length: Int = 0, + var min_text_length: Int = 0, + var initial_cursor_position: Int = 0, + var type: Int = 0, + var password_mode: Int = 0, + var text_draw_type: Int = 0, + var key_disable_flags: Int = 0, + var use_blur_background: Boolean = false, + var enable_backspace_button: Boolean = false, + var enable_return_button: Boolean = false, + var disable_cancel_button: Boolean = false + ) : Serializable + + // Corresponds to Frontend::KeyboardData + @Keep + data class KeyboardData(var result: Int, var text: String) +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/applets/keyboard/ui/KeyboardDialogFragment.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/applets/keyboard/ui/KeyboardDialogFragment.kt new file mode 100644 index 0000000..16fbc48 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/applets/keyboard/ui/KeyboardDialogFragment.kt @@ -0,0 +1,100 @@ +// SPDX-FileCopyrightText: Copyright 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.applets.keyboard.ui + +import android.app.Dialog +import android.content.DialogInterface +import android.os.Bundle +import android.text.InputFilter +import android.text.InputType +import androidx.fragment.app.DialogFragment +import com.google.android.material.dialog.MaterialAlertDialogBuilder +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.applets.keyboard.SoftwareKeyboard +import org.sudachi.sudachi_emu.applets.keyboard.SoftwareKeyboard.KeyboardConfig +import org.sudachi.sudachi_emu.databinding.DialogEditTextBinding +import org.sudachi.sudachi_emu.utils.SerializableHelper.serializable + +class KeyboardDialogFragment : DialogFragment() { + private lateinit var binding: DialogEditTextBinding + private lateinit var config: KeyboardConfig + + override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { + binding = DialogEditTextBinding.inflate(layoutInflater) + config = requireArguments().serializable(CONFIG)!! + + // Set up the input + binding.editText.hint = config.initial_text + binding.editText.isSingleLine = !config.enable_return_button + binding.editText.filters = + arrayOf(InputFilter.LengthFilter(config.max_text_length)) + + // Handle input type + var inputType: Int + when (config.type) { + SoftwareKeyboard.SwkbdType.Normal.ordinal, + SoftwareKeyboard.SwkbdType.Qwerty.ordinal, + SoftwareKeyboard.SwkbdType.Unknown3.ordinal, + SoftwareKeyboard.SwkbdType.Latin.ordinal, + SoftwareKeyboard.SwkbdType.SimplifiedChinese.ordinal, + SoftwareKeyboard.SwkbdType.TraditionalChinese.ordinal, + SoftwareKeyboard.SwkbdType.Korean.ordinal -> { + inputType = InputType.TYPE_CLASS_TEXT + if (config.password_mode == SoftwareKeyboard.SwkbdPasswordMode.Enabled.ordinal) { + inputType = inputType or InputType.TYPE_TEXT_VARIATION_PASSWORD + } + } + SoftwareKeyboard.SwkbdType.NumberPad.ordinal -> { + inputType = InputType.TYPE_CLASS_NUMBER + if (config.password_mode == SoftwareKeyboard.SwkbdPasswordMode.Enabled.ordinal) { + inputType = inputType or InputType.TYPE_NUMBER_VARIATION_PASSWORD + } + } + else -> { + inputType = InputType.TYPE_CLASS_TEXT + if (config.password_mode == SoftwareKeyboard.SwkbdPasswordMode.Enabled.ordinal) { + inputType = inputType or InputType.TYPE_TEXT_VARIATION_PASSWORD + } + } + } + binding.editText.inputType = inputType + + val headerText = + config.header_text!!.ifEmpty { resources.getString(R.string.software_keyboard) } + val okText = + config.ok_text!!.ifEmpty { resources.getString(R.string.submit) } + + return MaterialAlertDialogBuilder(requireContext()) + .setTitle(headerText) + .setView(binding.root) + .setPositiveButton(okText) { _, _ -> + SoftwareKeyboard.data.result = SoftwareKeyboard.SwkbdResult.Ok.ordinal + SoftwareKeyboard.data.text = binding.editText.text.toString() + } + .setNegativeButton(resources.getString(android.R.string.cancel)) { _, _ -> + SoftwareKeyboard.data.result = SoftwareKeyboard.SwkbdResult.Cancel.ordinal + } + .create() + } + + override fun onDismiss(dialog: DialogInterface) { + super.onDismiss(dialog) + synchronized(SoftwareKeyboard.dataLock) { + SoftwareKeyboard.dataLock.notifyAll() + } + } + + companion object { + const val TAG = "KeyboardDialogFragment" + const val CONFIG = "keyboard_config" + + fun newInstance(config: KeyboardConfig?): KeyboardDialogFragment { + val frag = KeyboardDialogFragment() + val args = Bundle() + args.putSerializable(CONFIG, config) + frag.arguments = args + return frag + } + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/disk_shader_cache/DiskShaderCacheProgress.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/disk_shader_cache/DiskShaderCacheProgress.kt new file mode 100644 index 0000000..eacb965 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/disk_shader_cache/DiskShaderCacheProgress.kt @@ -0,0 +1,51 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.disk_shader_cache + +import androidx.annotation.Keep +import androidx.lifecycle.ViewModelProvider +import org.sudachi.sudachi_emu.NativeLibrary +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.activities.EmulationActivity +import org.sudachi.sudachi_emu.model.EmulationViewModel +import org.sudachi.sudachi_emu.utils.Log + +@Keep +object DiskShaderCacheProgress { + private lateinit var emulationViewModel: EmulationViewModel + + private fun prepareViewModel() { + emulationViewModel = + ViewModelProvider( + NativeLibrary.sEmulationActivity.get() as EmulationActivity + )[EmulationViewModel::class.java] + } + + @JvmStatic + fun loadProgress(stage: Int, progress: Int, max: Int) { + val emulationActivity = NativeLibrary.sEmulationActivity.get() + if (emulationActivity == null) { + Log.error("[DiskShaderCacheProgress] EmulationActivity not present") + return + } + + emulationActivity.runOnUiThread { + when (LoadCallbackStage.entries[stage]) { + LoadCallbackStage.Prepare -> prepareViewModel() + LoadCallbackStage.Build -> emulationViewModel.updateProgress( + emulationActivity.getString(R.string.building_shaders), + progress, + max + ) + + LoadCallbackStage.Complete -> {} + } + } + } + + // Equivalent to VideoCore::LoadCallbackStage + enum class LoadCallbackStage { + Prepare, Build, Complete + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/DocumentProvider.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/DocumentProvider.kt new file mode 100644 index 0000000..883c19f --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/DocumentProvider.kt @@ -0,0 +1,341 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +// SPDX-License-Identifier: MPL-2.0 +// Copyright © 2023 Skyline Team and Contributors (https://github.com/skyline-emu/) + +package org.sudachi.sudachi_emu.features + +import android.database.Cursor +import android.database.MatrixCursor +import android.os.CancellationSignal +import android.os.ParcelFileDescriptor +import android.provider.DocumentsContract +import android.provider.DocumentsProvider +import android.webkit.MimeTypeMap +import java.io.* +import org.sudachi.sudachi_emu.BuildConfig +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.SudachiApplication +import org.sudachi.sudachi_emu.getPublicFilesDir + +class DocumentProvider : DocumentsProvider() { + private val baseDirectory: File + get() = File(SudachiApplication.application.getPublicFilesDir().canonicalPath) + + companion object { + private val DEFAULT_ROOT_PROJECTION: Array = arrayOf( + DocumentsContract.Root.COLUMN_ROOT_ID, + DocumentsContract.Root.COLUMN_MIME_TYPES, + DocumentsContract.Root.COLUMN_FLAGS, + DocumentsContract.Root.COLUMN_ICON, + DocumentsContract.Root.COLUMN_TITLE, + DocumentsContract.Root.COLUMN_SUMMARY, + DocumentsContract.Root.COLUMN_DOCUMENT_ID, + DocumentsContract.Root.COLUMN_AVAILABLE_BYTES + ) + + private val DEFAULT_DOCUMENT_PROJECTION: Array = arrayOf( + DocumentsContract.Document.COLUMN_DOCUMENT_ID, + DocumentsContract.Document.COLUMN_MIME_TYPE, + DocumentsContract.Document.COLUMN_DISPLAY_NAME, + DocumentsContract.Document.COLUMN_LAST_MODIFIED, + DocumentsContract.Document.COLUMN_FLAGS, + DocumentsContract.Document.COLUMN_SIZE + ) + + const val AUTHORITY: String = BuildConfig.APPLICATION_ID + ".user" + const val ROOT_ID: String = "root" + } + + override fun onCreate(): Boolean { + return true + } + + /** + * @return The [File] that corresponds to the document ID supplied by [getDocumentId] + */ + private fun getFile(documentId: String): File { + if (documentId.startsWith(ROOT_ID)) { + val file = baseDirectory.resolve(documentId.drop(ROOT_ID.length + 1)) + if (!file.exists()) { + throw FileNotFoundException( + "${file.absolutePath} ($documentId) not found" + ) + } + return file + } else { + throw FileNotFoundException("'$documentId' is not in any known root") + } + } + + /** + * @return A unique ID for the provided [File] + */ + private fun getDocumentId(file: File): String { + return "$ROOT_ID/${file.toRelativeString(baseDirectory)}" + } + + override fun queryRoots(projection: Array?): Cursor { + val cursor = MatrixCursor(projection ?: DEFAULT_ROOT_PROJECTION) + + cursor.newRow().apply { + add(DocumentsContract.Root.COLUMN_ROOT_ID, ROOT_ID) + add(DocumentsContract.Root.COLUMN_SUMMARY, null) + add( + DocumentsContract.Root.COLUMN_FLAGS, + DocumentsContract.Root.FLAG_SUPPORTS_CREATE or + DocumentsContract.Root.FLAG_SUPPORTS_IS_CHILD + ) + add(DocumentsContract.Root.COLUMN_TITLE, context!!.getString(R.string.app_name)) + add(DocumentsContract.Root.COLUMN_DOCUMENT_ID, getDocumentId(baseDirectory)) + add(DocumentsContract.Root.COLUMN_MIME_TYPES, "*/*") + add(DocumentsContract.Root.COLUMN_AVAILABLE_BYTES, baseDirectory.freeSpace) + add(DocumentsContract.Root.COLUMN_ICON, R.drawable.ic_sudachi) + } + + return cursor + } + + override fun queryDocument(documentId: String?, projection: Array?): Cursor { + val cursor = MatrixCursor(projection ?: DEFAULT_DOCUMENT_PROJECTION) + return includeFile(cursor, documentId, null) + } + + override fun isChildDocument(parentDocumentId: String?, documentId: String?): Boolean { + return documentId?.startsWith(parentDocumentId!!) ?: false + } + + /** + * @return A new [File] with a unique name based off the supplied [name], not conflicting with any existing file + */ + private fun File.resolveWithoutConflict(name: String): File { + var file = resolve(name) + if (file.exists()) { + var noConflictId = + 1 // Makes sure two files don't have the same name by adding a number to the end + val extension = name.substringAfterLast('.') + val baseName = name.substringBeforeLast('.') + while (file.exists()) + file = resolve("$baseName (${noConflictId++}).$extension") + } + return file + } + + override fun createDocument( + parentDocumentId: String?, + mimeType: String?, + displayName: String + ): String { + val parentFile = getFile(parentDocumentId!!) + val newFile = parentFile.resolveWithoutConflict(displayName) + + try { + if (DocumentsContract.Document.MIME_TYPE_DIR == mimeType) { + if (!newFile.mkdir()) { + throw IOException("Failed to create directory") + } + } else { + if (!newFile.createNewFile()) { + throw IOException("Failed to create file") + } + } + } catch (e: IOException) { + throw FileNotFoundException("Couldn't create document '${newFile.path}': ${e.message}") + } + + return getDocumentId(newFile) + } + + override fun deleteDocument(documentId: String?) { + val file = getFile(documentId!!) + if (!file.delete()) { + throw FileNotFoundException("Couldn't delete document with ID '$documentId'") + } + } + + override fun removeDocument(documentId: String, parentDocumentId: String?) { + val parent = getFile(parentDocumentId!!) + val file = getFile(documentId) + + if (parent == file || file.parentFile == null || file.parentFile!! == parent) { + if (!file.delete()) { + throw FileNotFoundException("Couldn't delete document with ID '$documentId'") + } + } else { + throw FileNotFoundException("Couldn't delete document with ID '$documentId'") + } + } + + override fun renameDocument(documentId: String?, displayName: String?): String { + if (displayName == null) { + throw FileNotFoundException( + "Couldn't rename document '$documentId' as the new name is null" + ) + } + + val sourceFile = getFile(documentId!!) + val sourceParentFile = sourceFile.parentFile + ?: throw FileNotFoundException( + "Couldn't rename document '$documentId' as it has no parent" + ) + val destFile = sourceParentFile.resolve(displayName) + + try { + if (!sourceFile.renameTo(destFile)) { + throw FileNotFoundException( + "Couldn't rename document from '${sourceFile.name}' to '${destFile.name}'" + ) + } + } catch (e: Exception) { + throw FileNotFoundException( + "Couldn't rename document from '${sourceFile.name}' to '${destFile.name}': " + + "${e.message}" + ) + } + + return getDocumentId(destFile) + } + + private fun copyDocument( + sourceDocumentId: String, + sourceParentDocumentId: String, + targetParentDocumentId: String? + ): String { + if (!isChildDocument(sourceParentDocumentId, sourceDocumentId)) { + throw FileNotFoundException( + "Couldn't copy document '$sourceDocumentId' as its parent is not " + + "'$sourceParentDocumentId'" + ) + } + + return copyDocument(sourceDocumentId, targetParentDocumentId) + } + + override fun copyDocument(sourceDocumentId: String, targetParentDocumentId: String?): String { + val parent = getFile(targetParentDocumentId!!) + val oldFile = getFile(sourceDocumentId) + val newFile = parent.resolveWithoutConflict(oldFile.name) + + try { + if (!( + newFile.createNewFile() && newFile.setWritable(true) && + newFile.setReadable(true) + ) + ) { + throw IOException("Couldn't create new file") + } + + FileInputStream(oldFile).use { inStream -> + FileOutputStream(newFile).use { outStream -> + inStream.copyTo(outStream) + } + } + } catch (e: IOException) { + throw FileNotFoundException("Couldn't copy document '$sourceDocumentId': ${e.message}") + } + + return getDocumentId(newFile) + } + + override fun moveDocument( + sourceDocumentId: String, + sourceParentDocumentId: String?, + targetParentDocumentId: String? + ): String { + try { + val newDocumentId = copyDocument( + sourceDocumentId, + sourceParentDocumentId!!, + targetParentDocumentId + ) + removeDocument(sourceDocumentId, sourceParentDocumentId) + return newDocumentId + } catch (e: FileNotFoundException) { + throw FileNotFoundException("Couldn't move document '$sourceDocumentId'") + } + } + + private fun includeFile(cursor: MatrixCursor, documentId: String?, file: File?): MatrixCursor { + val localDocumentId = documentId ?: file?.let { getDocumentId(it) } + val localFile = file ?: getFile(documentId!!) + + var flags = 0 + if (localFile.isDirectory && localFile.canWrite()) { + flags = DocumentsContract.Document.FLAG_DIR_SUPPORTS_CREATE + } else if (localFile.canWrite()) { + flags = DocumentsContract.Document.FLAG_SUPPORTS_WRITE + flags = flags or DocumentsContract.Document.FLAG_SUPPORTS_DELETE + + flags = flags or DocumentsContract.Document.FLAG_SUPPORTS_REMOVE + flags = flags or DocumentsContract.Document.FLAG_SUPPORTS_MOVE + flags = flags or DocumentsContract.Document.FLAG_SUPPORTS_COPY + flags = flags or DocumentsContract.Document.FLAG_SUPPORTS_RENAME + } + + cursor.newRow().apply { + add(DocumentsContract.Document.COLUMN_DOCUMENT_ID, localDocumentId) + add( + DocumentsContract.Document.COLUMN_DISPLAY_NAME, + if (localFile == baseDirectory) { + context!!.getString(R.string.app_name) + } else { + localFile.name + } + ) + add(DocumentsContract.Document.COLUMN_SIZE, localFile.length()) + add(DocumentsContract.Document.COLUMN_MIME_TYPE, getTypeForFile(localFile)) + add(DocumentsContract.Document.COLUMN_LAST_MODIFIED, localFile.lastModified()) + add(DocumentsContract.Document.COLUMN_FLAGS, flags) + if (localFile == baseDirectory) { + add(DocumentsContract.Root.COLUMN_ICON, R.drawable.ic_sudachi) + } + } + + return cursor + } + + private fun getTypeForFile(file: File): Any { + return if (file.isDirectory) { + DocumentsContract.Document.MIME_TYPE_DIR + } else { + getTypeForName(file.name) + } + } + + private fun getTypeForName(name: String): Any { + val lastDot = name.lastIndexOf('.') + if (lastDot >= 0) { + val extension = name.substring(lastDot + 1) + val mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension) + if (mime != null) { + return mime + } + } + return "application/octect-stream" + } + + override fun queryChildDocuments( + parentDocumentId: String?, + projection: Array?, + sortOrder: String? + ): Cursor { + var cursor = MatrixCursor(projection ?: DEFAULT_DOCUMENT_PROJECTION) + + val parent = getFile(parentDocumentId!!) + for (file in parent.listFiles()!!) + cursor = includeFile(cursor, null, file) + + return cursor + } + + override fun openDocument( + documentId: String?, + mode: String?, + signal: CancellationSignal? + ): ParcelFileDescriptor { + val file = documentId?.let { getFile(it) } + val accessMode = ParcelFileDescriptor.parseMode(mode) + return ParcelFileDescriptor.open(file, accessMode) + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/input/NativeInput.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/input/NativeInput.kt new file mode 100644 index 0000000..52288d9 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/input/NativeInput.kt @@ -0,0 +1,416 @@ +// SPDX-FileCopyrightText: 2024 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.input + +import org.sudachi.sudachi_emu.features.input.model.NativeButton +import org.sudachi.sudachi_emu.features.input.model.NativeAnalog +import org.sudachi.sudachi_emu.features.input.model.InputType +import org.sudachi.sudachi_emu.features.input.model.ButtonName +import org.sudachi.sudachi_emu.features.input.model.NpadStyleIndex +import org.sudachi.sudachi_emu.utils.NativeConfig +import org.sudachi.sudachi_emu.utils.ParamPackage +import android.view.InputDevice + +object NativeInput { + /** + * Default controller id for each device + */ + const val Player1Device = 0 + const val Player2Device = 1 + const val Player3Device = 2 + const val Player4Device = 3 + const val Player5Device = 4 + const val Player6Device = 5 + const val Player7Device = 6 + const val Player8Device = 7 + const val ConsoleDevice = 8 + + /** + * Button states + */ + object ButtonState { + const val RELEASED = 0 + const val PRESSED = 1 + } + + /** + * Returns true if pro controller isn't available and handheld is. + * Intended to check where the input overlay should direct its inputs. + */ + external fun isHandheldOnly(): Boolean + + /** + * Handles button press events for a gamepad. + * @param guid 32 character hexadecimal string consisting of the controller's PID+VID. + * @param port Port determined by controller connection order. + * @param buttonId The Android Keycode corresponding to this event. + * @param action Mask identifying which action is happening (button pressed down, or button released). + */ + external fun onGamePadButtonEvent( + guid: String, + port: Int, + buttonId: Int, + action: Int + ) + + /** + * Handles axis movement events. + * @param guid 32 character hexadecimal string consisting of the controller's PID+VID. + * @param port Port determined by controller connection order. + * @param axis The axis ID. + * @param value Value along the given axis. + */ + external fun onGamePadAxisEvent(guid: String, port: Int, axis: Int, value: Float) + + /** + * Handles motion events. + * @param guid 32 character hexadecimal string consisting of the controller's PID+VID. + * @param port Port determined by controller connection order. + * @param deltaTimestamp The finger id corresponding to this event. + * @param xGyro The value of the x-axis for the gyroscope. + * @param yGyro The value of the y-axis for the gyroscope. + * @param zGyro The value of the z-axis for the gyroscope. + * @param xAccel The value of the x-axis for the accelerometer. + * @param yAccel The value of the y-axis for the accelerometer. + * @param zAccel The value of the z-axis for the accelerometer. + */ + external fun onGamePadMotionEvent( + guid: String, + port: Int, + deltaTimestamp: Long, + xGyro: Float, + yGyro: Float, + zGyro: Float, + xAccel: Float, + yAccel: Float, + zAccel: Float + ) + + /** + * Signals and load a nfc tag + * @param data Byte array containing all the data from a nfc tag. + */ + external fun onReadNfcTag(data: ByteArray?) + + /** + * Removes current loaded nfc tag. + */ + external fun onRemoveNfcTag() + + /** + * Handles touch press events. + * @param fingerId The finger id corresponding to this event. + * @param xAxis The value of the x-axis on the touchscreen. + * @param yAxis The value of the y-axis on the touchscreen. + */ + external fun onTouchPressed(fingerId: Int, xAxis: Float, yAxis: Float) + + /** + * Handles touch movement. + * @param fingerId The finger id corresponding to this event. + * @param xAxis The value of the x-axis on the touchscreen. + * @param yAxis The value of the y-axis on the touchscreen. + */ + external fun onTouchMoved(fingerId: Int, xAxis: Float, yAxis: Float) + + /** + * Handles touch release events. + * @param fingerId The finger id corresponding to this event + */ + external fun onTouchReleased(fingerId: Int) + + /** + * Sends a button input to the global virtual controllers. + * @param port Port determined by controller connection order. + * @param button The [NativeButton] corresponding to this event. + * @param action Mask identifying which action is happening (button pressed down, or button released). + */ + fun onOverlayButtonEvent(port: Int, button: NativeButton, action: Int) = + onOverlayButtonEventImpl(port, button.int, action) + + private external fun onOverlayButtonEventImpl(port: Int, buttonId: Int, action: Int) + + /** + * Sends a joystick input to the global virtual controllers. + * @param port Port determined by controller connection order. + * @param stick The [NativeAnalog] corresponding to this event. + * @param xAxis Value along the X axis. + * @param yAxis Value along the Y axis. + */ + fun onOverlayJoystickEvent(port: Int, stick: NativeAnalog, xAxis: Float, yAxis: Float) = + onOverlayJoystickEventImpl(port, stick.int, xAxis, yAxis) + + private external fun onOverlayJoystickEventImpl( + port: Int, + stickId: Int, + xAxis: Float, + yAxis: Float + ) + + /** + * Handles motion events for the global virtual controllers. + * @param port Port determined by controller connection order + * @param deltaTimestamp The finger id corresponding to this event. + * @param xGyro The value of the x-axis for the gyroscope. + * @param yGyro The value of the y-axis for the gyroscope. + * @param zGyro The value of the z-axis for the gyroscope. + * @param xAccel The value of the x-axis for the accelerometer. + * @param yAccel The value of the y-axis for the accelerometer. + * @param zAccel The value of the z-axis for the accelerometer. + */ + external fun onDeviceMotionEvent( + port: Int, + deltaTimestamp: Long, + xGyro: Float, + yGyro: Float, + zGyro: Float, + xAccel: Float, + yAccel: Float, + zAccel: Float + ) + + /** + * Reloads all input devices from the currently loaded Settings::values.players into HID Core + */ + external fun reloadInputDevices() + + /** + * Registers a controller to be used with mapping + * @param device An [InputDevice] or the input overlay wrapped with [SudachiInputDevice] + */ + external fun registerController(device: SudachiInputDevice) + + /** + * Gets the names of input devices that have been registered with the input subsystem via [registerController] + */ + external fun getInputDevices(): Array + + /** + * Reads all input profiles from disk. Must be called before creating a profile picker. + */ + external fun loadInputProfiles() + + /** + * Gets the names of each available input profile. + */ + external fun getInputProfileNames(): Array + + /** + * Checks if the user-provided name for an input profile is valid. + * @param name User-provided name for an input profile. + * @return Whether [name] is valid or not. + */ + external fun isProfileNameValid(name: String): Boolean + + /** + * Creates a new input profile. + * @param name The new profile's name. + * @param playerIndex Index of the player that's currently being edited. Used to write the profile + * name to this player's config. + * @return Whether creating the profile was successful or not. + */ + external fun createProfile(name: String, playerIndex: Int): Boolean + + /** + * Deletes an input profile. + * @param name Name of the profile to delete. + * @param playerIndex Index of the player that's currently being edited. Used to remove the profile + * name from this player's config if they have it loaded. + * @return Whether deleting this profile was successful or not. + */ + external fun deleteProfile(name: String, playerIndex: Int): Boolean + + /** + * Loads an input profile. + * @param name Name of the input profile to load. + * @param playerIndex Index of the player that will have this profile loaded. + * @return Whether loading this profile was successful or not. + */ + external fun loadProfile(name: String, playerIndex: Int): Boolean + + /** + * Saves an input profile. + * @param name Name of the profile to save. + * @param playerIndex Index of the player that's currently being edited. Used to write the profile + * name to this player's config. + * @return Whether saving the profile was successful or not. + */ + external fun saveProfile(name: String, playerIndex: Int): Boolean + + /** + * Intended to be used immediately before a call to [NativeConfig.saveControlPlayerValues] + * Must be used while per-game config is loaded. + */ + external fun loadPerGameConfiguration( + playerIndex: Int, + selectedIndex: Int, + selectedProfileName: String + ) + + /** + * Tells the input subsystem to start listening for inputs to map. + * @param type Type of input to map as shown by the int property in each [InputType]. + */ + external fun beginMapping(type: Int) + + /** + * Gets an input's [ParamPackage] as a serialized string. Used for input verification before mapping. + * Must be run after [beginMapping] and before [stopMapping]. + */ + external fun getNextInput(): String + + /** + * Tells the input subsystem to stop listening for inputs to map. + */ + external fun stopMapping() + + /** + * Updates a controller's mappings with auto-mapping params. + * @param playerIndex Index of the player to auto-map. + * @param deviceParams [ParamPackage] representing the device to auto-map as received + * from [getInputDevices]. + * @param displayName Name of the device to auto-map as received from the "display" param in [deviceParams]. + * Intended to be a way to provide a default name for a controller if the "display" param is empty. + */ + fun updateMappingsWithDefault( + playerIndex: Int, + deviceParams: ParamPackage, + displayName: String + ) = updateMappingsWithDefaultImpl(playerIndex, deviceParams.serialize(), displayName) + + private external fun updateMappingsWithDefaultImpl( + playerIndex: Int, + deviceParams: String, + displayName: String + ) + + /** + * Gets the params for a specific button. + * @param playerIndex Index of the player to get params from. + * @param button The [NativeButton] to get params for. + * @return A [ParamPackage] representing a player's specific button. + */ + fun getButtonParam(playerIndex: Int, button: NativeButton): ParamPackage = + ParamPackage(getButtonParamImpl(playerIndex, button.int)) + + private external fun getButtonParamImpl(playerIndex: Int, buttonId: Int): String + + /** + * Sets the params for a specific button. + * @param playerIndex Index of the player to set params for. + * @param button The [NativeButton] to set params for. + * @param param A [ParamPackage] to set. + */ + fun setButtonParam(playerIndex: Int, button: NativeButton, param: ParamPackage) = + setButtonParamImpl(playerIndex, button.int, param.serialize()) + + private external fun setButtonParamImpl(playerIndex: Int, buttonId: Int, param: String) + + /** + * Gets the params for a specific stick. + * @param playerIndex Index of the player to get params from. + * @param stick The [NativeAnalog] to get params for. + * @return A [ParamPackage] representing a player's specific stick. + */ + fun getStickParam(playerIndex: Int, stick: NativeAnalog): ParamPackage = + ParamPackage(getStickParamImpl(playerIndex, stick.int)) + + private external fun getStickParamImpl(playerIndex: Int, stickId: Int): String + + /** + * Sets the params for a specific stick. + * @param playerIndex Index of the player to set params for. + * @param stick The [NativeAnalog] to set params for. + * @param param A [ParamPackage] to set. + */ + fun setStickParam(playerIndex: Int, stick: NativeAnalog, param: ParamPackage) = + setStickParamImpl(playerIndex, stick.int, param.serialize()) + + private external fun setStickParamImpl(playerIndex: Int, stickId: Int, param: String) + + /** + * Gets the int representation of a [ButtonName]. Tells you what to show as the mapped input for + * a button/analog/other. + * @param param A [ParamPackage] that represents a specific button's params. + * @return The [ButtonName] for [param]. + */ + fun getButtonName(param: ParamPackage): ButtonName = + ButtonName.from(getButtonNameImpl(param.serialize())) + + private external fun getButtonNameImpl(param: String): Int + + /** + * Gets each supported [NpadStyleIndex] for a given player. + * @param playerIndex Index of the player to get supported indexes for. + * @return List of each supported [NpadStyleIndex]. + */ + fun getSupportedStyleTags(playerIndex: Int): List = + getSupportedStyleTagsImpl(playerIndex).map { NpadStyleIndex.from(it) } + + private external fun getSupportedStyleTagsImpl(playerIndex: Int): IntArray + + /** + * Gets the [NpadStyleIndex] for a given player. + * @param playerIndex Index of the player to get an [NpadStyleIndex] from. + * @return The [NpadStyleIndex] for a given player. + */ + fun getStyleIndex(playerIndex: Int): NpadStyleIndex = + NpadStyleIndex.from(getStyleIndexImpl(playerIndex)) + + private external fun getStyleIndexImpl(playerIndex: Int): Int + + /** + * Sets the [NpadStyleIndex] for a given player. + * @param playerIndex Index of the player to change. + * @param style The new style to set. + */ + fun setStyleIndex(playerIndex: Int, style: NpadStyleIndex) = + setStyleIndexImpl(playerIndex, style.int) + + private external fun setStyleIndexImpl(playerIndex: Int, styleIndex: Int) + + /** + * Checks if a device is a controller. + * @param params [ParamPackage] for an input device retrieved from [getInputDevices] + * @return Whether the device is a controller or not. + */ + fun isController(params: ParamPackage): Boolean = isControllerImpl(params.serialize()) + + private external fun isControllerImpl(params: String): Boolean + + /** + * Checks if a controller is connected + * @param playerIndex Index of the player to check. + * @return Whether the player is connected or not. + */ + external fun getIsConnected(playerIndex: Int): Boolean + + /** + * Connects/disconnects a controller and ensures that connection order stays in-tact. + * @param playerIndex Index of the player to connect/disconnect. + * @param connected Whether to connect or disconnect this controller. + */ + fun connectControllers(playerIndex: Int, connected: Boolean = true) { + val connectedControllers = mutableListOf().apply { + if (connected) { + for (i in 0 until 8) { + add(i <= playerIndex) + } + } else { + for (i in 0 until 8) { + add(i < playerIndex) + } + } + } + connectControllersImpl(connectedControllers.toBooleanArray()) + } + + private external fun connectControllersImpl(connected: BooleanArray) + + /** + * Resets all of the button and analog mappings for a player. + * @param playerIndex Index of the player that will have its mappings reset. + */ + external fun resetControllerMappings(playerIndex: Int) +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/input/SudachiInputDevice.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/input/SudachiInputDevice.kt new file mode 100644 index 0000000..d985eaf --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/input/SudachiInputDevice.kt @@ -0,0 +1,93 @@ +// SPDX-FileCopyrightText: 2024 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.input + +import android.view.InputDevice +import androidx.annotation.Keep +import org.sudachi.sudachi_emu.SudachiApplication +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.utils.InputHandler.getGUID + +@Keep +interface SudachiInputDevice { + fun getName(): String + + fun getGUID(): String + + fun getPort(): Int + + fun getSupportsVibration(): Boolean + + fun vibrate(intensity: Float) + + fun getAxes(): Array = arrayOf() + fun hasKeys(keys: IntArray): BooleanArray = BooleanArray(0) +} + +class SudachiPhysicalDevice( + private val device: InputDevice, + private val port: Int, + useSystemVibrator: Boolean +) : SudachiInputDevice { + private val vibrator = if (useSystemVibrator) { + SudachiVibrator.getSystemVibrator() + } else { + SudachiVibrator.getControllerVibrator(device) + } + + override fun getName(): String { + return device.name + } + + override fun getGUID(): String { + return device.getGUID() + } + + override fun getPort(): Int { + return port + } + + override fun getSupportsVibration(): Boolean { + return vibrator.supportsVibration() + } + + override fun vibrate(intensity: Float) { + vibrator.vibrate(intensity) + } + + override fun getAxes(): Array = device.motionRanges.map { it.axis }.toTypedArray() + override fun hasKeys(keys: IntArray): BooleanArray = device.hasKeys(*keys) +} + +class SudachiInputOverlayDevice( + private val vibration: Boolean, + private val port: Int +) : SudachiInputDevice { + private val vibrator = SudachiVibrator.getSystemVibrator() + + override fun getName(): String { + return SudachiApplication.appContext.getString(R.string.input_overlay) + } + + override fun getGUID(): String { + return "00000000000000000000000000000000" + } + + override fun getPort(): Int { + return port + } + + override fun getSupportsVibration(): Boolean { + if (vibration) { + return vibrator.supportsVibration() + } + return false + } + + override fun vibrate(intensity: Float) { + if (vibration) { + vibrator.vibrate(intensity) + } + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/input/SudachiVibrator.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/input/SudachiVibrator.kt new file mode 100644 index 0000000..4f50bb0 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/input/SudachiVibrator.kt @@ -0,0 +1,76 @@ +// SPDX-FileCopyrightText: 2024 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.input + +import android.content.Context +import android.os.Build +import android.os.CombinedVibration +import android.os.VibrationEffect +import android.os.Vibrator +import android.os.VibratorManager +import android.view.InputDevice +import androidx.annotation.Keep +import androidx.annotation.RequiresApi +import org.sudachi.sudachi_emu.SudachiApplication + +@Keep +@Suppress("DEPRECATION") +interface SudachiVibrator { + fun supportsVibration(): Boolean + + fun vibrate(intensity: Float) + + companion object { + fun getControllerVibrator(device: InputDevice): SudachiVibrator = + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + SudachiVibratorManager(device.vibratorManager) + } else { + SudachiVibratorManagerCompat(device.vibrator) + } + + fun getSystemVibrator(): SudachiVibrator = + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + val vibratorManager = SudachiApplication.appContext + .getSystemService(Context.VIBRATOR_MANAGER_SERVICE) as VibratorManager + SudachiVibratorManager(vibratorManager) + } else { + val vibrator = SudachiApplication.appContext + .getSystemService(Context.VIBRATOR_SERVICE) as Vibrator + SudachiVibratorManagerCompat(vibrator) + } + + fun getVibrationEffect(intensity: Float): VibrationEffect? { + if (intensity > 0f) { + return VibrationEffect.createOneShot( + 50, + (255.0 * intensity).toInt().coerceIn(1, 255) + ) + } + return null + } + } +} + +@RequiresApi(Build.VERSION_CODES.S) +class SudachiVibratorManager(private val vibratorManager: VibratorManager) : SudachiVibrator { + override fun supportsVibration(): Boolean { + return vibratorManager.vibratorIds.isNotEmpty() + } + + override fun vibrate(intensity: Float) { + val vibration = SudachiVibrator.getVibrationEffect(intensity) ?: return + vibratorManager.vibrate(CombinedVibration.createParallel(vibration)) + } +} + +class SudachiVibratorManagerCompat(private val vibrator: Vibrator) : SudachiVibrator { + override fun supportsVibration(): Boolean { + return vibrator.hasVibrator() + } + + override fun vibrate(intensity: Float) { + val vibration = SudachiVibrator.getVibrationEffect(intensity) ?: return + vibrator.vibrate(vibration) + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/input/model/AnalogDirection.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/input/model/AnalogDirection.kt new file mode 100644 index 0000000..45d92d1 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/input/model/AnalogDirection.kt @@ -0,0 +1,11 @@ +// SPDX-FileCopyrightText: 2024 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.input.model + +enum class AnalogDirection(val int: Int, val param: String) { + Up(0, "up"), + Down(1, "down"), + Left(2, "left"), + Right(3, "right") +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/input/model/ButtonName.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/input/model/ButtonName.kt new file mode 100644 index 0000000..2d8ff80 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/input/model/ButtonName.kt @@ -0,0 +1,19 @@ +// SPDX-FileCopyrightText: 2024 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.input.model + +// Loosely matches the enum in common/input.h +enum class ButtonName(val int: Int) { + Invalid(1), + + // This will display the engine name instead of the button name + Engine(2), + + // This will display the button by value instead of the button name + Value(3); + + companion object { + fun from(int: Int): ButtonName = entries.firstOrNull { it.int == int } ?: Invalid + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/input/model/InputType.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/input/model/InputType.kt new file mode 100644 index 0000000..11f263a --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/input/model/InputType.kt @@ -0,0 +1,13 @@ +// SPDX-FileCopyrightText: 2024 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.input.model + +// Must match the corresponding enum in input_common/main.h +enum class InputType(val int: Int) { + None(0), + Button(1), + Stick(2), + Motion(3), + Touch(4) +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/input/model/NativeAnalog.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/input/model/NativeAnalog.kt new file mode 100644 index 0000000..88ef792 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/input/model/NativeAnalog.kt @@ -0,0 +1,14 @@ +// SPDX-FileCopyrightText: 2024 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.input.model + +// Must match enum in src/common/settings_input.h +enum class NativeAnalog(val int: Int) { + LStick(0), + RStick(1); + + companion object { + fun from(int: Int): NativeAnalog = entries.firstOrNull { it.int == int } ?: LStick + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/input/model/NativeButton.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/input/model/NativeButton.kt new file mode 100644 index 0000000..d26e008 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/input/model/NativeButton.kt @@ -0,0 +1,38 @@ +// SPDX-FileCopyrightText: 2024 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.input.model + +// Must match enum in src/common/settings_input.h +enum class NativeButton(val int: Int) { + A(0), + B(1), + X(2), + Y(3), + LStick(4), + RStick(5), + L(6), + R(7), + ZL(8), + ZR(9), + Plus(10), + Minus(11), + + DLeft(12), + DUp(13), + DRight(14), + DDown(15), + + SLLeft(16), + SRLeft(17), + + Home(18), + Capture(19), + + SLRight(20), + SRRight(21); + + companion object { + fun from(int: Int): NativeButton = entries.firstOrNull { it.int == int } ?: A + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/input/model/NativeTrigger.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/input/model/NativeTrigger.kt new file mode 100644 index 0000000..de97a45 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/input/model/NativeTrigger.kt @@ -0,0 +1,10 @@ +// SPDX-FileCopyrightText: 2024 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.input.model + +// Must match enum in src/common/settings_input.h +enum class NativeTrigger(val int: Int) { + LTrigger(0), + RTrigger(1) +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/input/model/NpadStyleIndex.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/input/model/NpadStyleIndex.kt new file mode 100644 index 0000000..4d938fa --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/input/model/NpadStyleIndex.kt @@ -0,0 +1,30 @@ +// SPDX-FileCopyrightText: 2024 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.input.model + +import androidx.annotation.StringRes +import org.sudachi.sudachi_emu.R + +// Must match enum in src/core/hid/hid_types.h +enum class NpadStyleIndex(val int: Int, @StringRes val nameId: Int = 0) { + None(0), + Fullkey(3, R.string.pro_controller), + Handheld(4, R.string.handheld), + HandheldNES(4), + JoyconDual(5, R.string.dual_joycons), + JoyconLeft(6, R.string.left_joycon), + JoyconRight(7, R.string.right_joycon), + GameCube(8, R.string.gamecube_controller), + Pokeball(9), + NES(10), + SNES(12), + N64(13), + SegaGenesis(14), + SystemExt(32), + System(33); + + companion object { + fun from(int: Int): NpadStyleIndex = entries.firstOrNull { it.int == int } ?: None + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/input/model/PlayerInput.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/input/model/PlayerInput.kt new file mode 100644 index 0000000..bd1328c --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/input/model/PlayerInput.kt @@ -0,0 +1,83 @@ +// SPDX-FileCopyrightText: 2024 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.input.model + +import androidx.annotation.Keep + +@Keep +data class PlayerInput( + var connected: Boolean, + var buttons: Array, + var analogs: Array, + var motions: Array, + + var vibrationEnabled: Boolean, + var vibrationStrength: Int, + + var bodyColorLeft: Long, + var bodyColorRight: Long, + var buttonColorLeft: Long, + var buttonColorRight: Long, + var profileName: String, + + var useSystemVibrator: Boolean +) { + // It's recommended to use the generated equals() and hashCode() methods + // when using arrays in a data class + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (javaClass != other?.javaClass) return false + + other as PlayerInput + + if (connected != other.connected) return false + if (!buttons.contentEquals(other.buttons)) return false + if (!analogs.contentEquals(other.analogs)) return false + if (!motions.contentEquals(other.motions)) return false + if (vibrationEnabled != other.vibrationEnabled) return false + if (vibrationStrength != other.vibrationStrength) return false + if (bodyColorLeft != other.bodyColorLeft) return false + if (bodyColorRight != other.bodyColorRight) return false + if (buttonColorLeft != other.buttonColorLeft) return false + if (buttonColorRight != other.buttonColorRight) return false + if (profileName != other.profileName) return false + return useSystemVibrator == other.useSystemVibrator + } + + override fun hashCode(): Int { + var result = connected.hashCode() + result = 31 * result + buttons.contentHashCode() + result = 31 * result + analogs.contentHashCode() + result = 31 * result + motions.contentHashCode() + result = 31 * result + vibrationEnabled.hashCode() + result = 31 * result + vibrationStrength + result = 31 * result + bodyColorLeft.hashCode() + result = 31 * result + bodyColorRight.hashCode() + result = 31 * result + buttonColorLeft.hashCode() + result = 31 * result + buttonColorRight.hashCode() + result = 31 * result + profileName.hashCode() + result = 31 * result + useSystemVibrator.hashCode() + return result + } + + fun hasMapping(): Boolean { + var hasMapping = false + buttons.forEach { + if (it != "[empty]" && it.isNotEmpty()) { + hasMapping = true + } + } + analogs.forEach { + if (it != "[empty]" && it.isNotEmpty()) { + hasMapping = true + } + } + motions.forEach { + if (it != "[empty]" && it.isNotEmpty()) { + hasMapping = true + } + } + return hasMapping + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/AbstractBooleanSetting.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/AbstractBooleanSetting.kt new file mode 100644 index 0000000..df4673b --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/AbstractBooleanSetting.kt @@ -0,0 +1,9 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.settings.model + +interface AbstractBooleanSetting : AbstractSetting { + fun getBoolean(needsGlobal: Boolean = false): Boolean + fun setBoolean(value: Boolean) +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/AbstractByteSetting.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/AbstractByteSetting.kt new file mode 100644 index 0000000..dd7a678 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/AbstractByteSetting.kt @@ -0,0 +1,9 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.settings.model + +interface AbstractByteSetting : AbstractSetting { + fun getByte(needsGlobal: Boolean = false): Byte + fun setByte(value: Byte) +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/AbstractFloatSetting.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/AbstractFloatSetting.kt new file mode 100644 index 0000000..7dd7c0f --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/AbstractFloatSetting.kt @@ -0,0 +1,9 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.settings.model + +interface AbstractFloatSetting : AbstractSetting { + fun getFloat(needsGlobal: Boolean = false): Float + fun setFloat(value: Float) +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/AbstractIntSetting.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/AbstractIntSetting.kt new file mode 100644 index 0000000..bc01b75 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/AbstractIntSetting.kt @@ -0,0 +1,9 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.settings.model + +interface AbstractIntSetting : AbstractSetting { + fun getInt(needsGlobal: Boolean = false): Int + fun setInt(value: Int) +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/AbstractLongSetting.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/AbstractLongSetting.kt new file mode 100644 index 0000000..a6da258 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/AbstractLongSetting.kt @@ -0,0 +1,9 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.settings.model + +interface AbstractLongSetting : AbstractSetting { + fun getLong(needsGlobal: Boolean = false): Long + fun setLong(value: Long) +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/AbstractSetting.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/AbstractSetting.kt new file mode 100644 index 0000000..62c86fb --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/AbstractSetting.kt @@ -0,0 +1,31 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.settings.model + +import org.sudachi.sudachi_emu.utils.NativeConfig + +interface AbstractSetting { + val key: String + val defaultValue: Any + + val isRuntimeModifiable: Boolean + get() = NativeConfig.getIsRuntimeModifiable(key) + + val pairedSettingKey: String + get() = NativeConfig.getPairedSettingKey(key) + + val isSwitchable: Boolean + get() = NativeConfig.getIsSwitchable(key) + + var global: Boolean + get() = NativeConfig.usingGlobal(key) + set(value) = NativeConfig.setGlobal(key, value) + + val isSaveable: Boolean + get() = NativeConfig.getIsSaveable(key) + + fun getValueAsString(needsGlobal: Boolean = false): String + + fun reset() +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/AbstractShortSetting.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/AbstractShortSetting.kt new file mode 100644 index 0000000..c568fdf --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/AbstractShortSetting.kt @@ -0,0 +1,9 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.settings.model + +interface AbstractShortSetting : AbstractSetting { + fun getShort(needsGlobal: Boolean = false): Short + fun setShort(value: Short) +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/AbstractStringSetting.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/AbstractStringSetting.kt new file mode 100644 index 0000000..88213f7 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/AbstractStringSetting.kt @@ -0,0 +1,9 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.settings.model + +interface AbstractStringSetting : AbstractSetting { + fun getString(needsGlobal: Boolean = false): String + fun setString(value: String) +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/BooleanSetting.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/BooleanSetting.kt new file mode 100644 index 0000000..5af0d38 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/BooleanSetting.kt @@ -0,0 +1,46 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.settings.model + +import org.sudachi.sudachi_emu.utils.NativeConfig + +enum class BooleanSetting(override val key: String) : AbstractBooleanSetting { + AUDIO_MUTED("audio_muted"), + CPU_DEBUG_MODE("cpu_debug_mode"), + FASTMEM("cpuopt_fastmem"), + FASTMEM_EXCLUSIVES("cpuopt_fastmem_exclusives"), + RENDERER_USE_SPEED_LIMIT("use_speed_limit"), + USE_DOCKED_MODE("use_docked_mode"), + RENDERER_USE_DISK_SHADER_CACHE("use_disk_shader_cache"), + RENDERER_FORCE_MAX_CLOCK("force_max_clock"), + RENDERER_ASYNCHRONOUS_SHADERS("use_asynchronous_shaders"), + RENDERER_REACTIVE_FLUSHING("use_reactive_flushing"), + RENDERER_DEBUG("debug"), + PICTURE_IN_PICTURE("picture_in_picture"), + USE_CUSTOM_RTC("custom_rtc_enabled"), + BLACK_BACKGROUNDS("black_backgrounds"), + JOYSTICK_REL_CENTER("joystick_rel_center"), + DPAD_SLIDE("dpad_slide"), + HAPTIC_FEEDBACK("haptic_feedback"), + SHOW_PERFORMANCE_OVERLAY("show_performance_overlay"), + SHOW_INPUT_OVERLAY("show_input_overlay"), + TOUCHSCREEN("touchscreen"), + SHOW_THERMAL_OVERLAY("show_thermal_overlay"); + + override fun getBoolean(needsGlobal: Boolean): Boolean = + NativeConfig.getBoolean(key, needsGlobal) + + override fun setBoolean(value: Boolean) { + if (NativeConfig.isPerGameConfigLoaded()) { + global = false + } + NativeConfig.setBoolean(key, value) + } + + override val defaultValue: Boolean by lazy { NativeConfig.getDefaultToString(key).toBoolean() } + + override fun getValueAsString(needsGlobal: Boolean): String = getBoolean(needsGlobal).toString() + + override fun reset() = NativeConfig.setBoolean(key, defaultValue) +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/ByteSetting.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/ByteSetting.kt new file mode 100644 index 0000000..49b9459 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/ByteSetting.kt @@ -0,0 +1,25 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.settings.model + +import org.sudachi.sudachi_emu.utils.NativeConfig + +enum class ByteSetting(override val key: String) : AbstractByteSetting { + AUDIO_VOLUME("volume"); + + override fun getByte(needsGlobal: Boolean): Byte = NativeConfig.getByte(key, needsGlobal) + + override fun setByte(value: Byte) { + if (NativeConfig.isPerGameConfigLoaded()) { + global = false + } + NativeConfig.setByte(key, value) + } + + override val defaultValue: Byte by lazy { NativeConfig.getDefaultToString(key).toByte() } + + override fun getValueAsString(needsGlobal: Boolean): String = getByte(needsGlobal).toString() + + override fun reset() = NativeConfig.setByte(key, defaultValue) +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/FloatSetting.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/FloatSetting.kt new file mode 100644 index 0000000..e7e1c29 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/FloatSetting.kt @@ -0,0 +1,26 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.settings.model + +import org.sudachi.sudachi_emu.utils.NativeConfig + +enum class FloatSetting(override val key: String) : AbstractFloatSetting { + // No float settings currently exist + EMPTY_SETTING(""); + + override fun getFloat(needsGlobal: Boolean): Float = NativeConfig.getFloat(key, false) + + override fun setFloat(value: Float) { + if (NativeConfig.isPerGameConfigLoaded()) { + global = false + } + NativeConfig.setFloat(key, value) + } + + override val defaultValue: Float by lazy { NativeConfig.getDefaultToString(key).toFloat() } + + override fun getValueAsString(needsGlobal: Boolean): String = getFloat(needsGlobal).toString() + + override fun reset() = NativeConfig.setFloat(key, defaultValue) +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/IntSetting.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/IntSetting.kt new file mode 100644 index 0000000..5aad3d4 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/IntSetting.kt @@ -0,0 +1,45 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.settings.model + +import org.sudachi.sudachi_emu.utils.NativeConfig + +enum class IntSetting(override val key: String) : AbstractIntSetting { + CPU_BACKEND("cpu_backend"), + CPU_ACCURACY("cpu_accuracy"), + REGION_INDEX("region_index"), + LANGUAGE_INDEX("language_index"), + RENDERER_BACKEND("backend"), + RENDERER_ACCURACY("gpu_accuracy"), + RENDERER_RESOLUTION("resolution_setup"), + RENDERER_VSYNC("use_vsync"), + RENDERER_SCALING_FILTER("scaling_filter"), + RENDERER_ANTI_ALIASING("anti_aliasing"), + RENDERER_SCREEN_LAYOUT("screen_layout"), + RENDERER_ASPECT_RATIO("aspect_ratio"), + AUDIO_OUTPUT_ENGINE("output_engine"), + MAX_ANISOTROPY("max_anisotropy"), + THEME("theme"), + THEME_MODE("theme_mode"), + OVERLAY_SCALE("control_scale"), + OVERLAY_OPACITY("control_opacity"), + LOCK_DRAWER("lock_drawer"), + VERTICAL_ALIGNMENT("vertical_alignment"), + FSR_SHARPENING_SLIDER("fsr_sharpening_slider"); + + override fun getInt(needsGlobal: Boolean): Int = NativeConfig.getInt(key, needsGlobal) + + override fun setInt(value: Int) { + if (NativeConfig.isPerGameConfigLoaded()) { + global = false + } + NativeConfig.setInt(key, value) + } + + override val defaultValue: Int by lazy { NativeConfig.getDefaultToString(key).toInt() } + + override fun getValueAsString(needsGlobal: Boolean): String = getInt(needsGlobal).toString() + + override fun reset() = NativeConfig.setInt(key, defaultValue) +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/LongSetting.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/LongSetting.kt new file mode 100644 index 0000000..677d0e9 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/LongSetting.kt @@ -0,0 +1,25 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.settings.model + +import org.sudachi.sudachi_emu.utils.NativeConfig + +enum class LongSetting(override val key: String) : AbstractLongSetting { + CUSTOM_RTC("custom_rtc"); + + override fun getLong(needsGlobal: Boolean): Long = NativeConfig.getLong(key, needsGlobal) + + override fun setLong(value: Long) { + if (NativeConfig.isPerGameConfigLoaded()) { + global = false + } + NativeConfig.setLong(key, value) + } + + override val defaultValue: Long by lazy { NativeConfig.getDefaultToString(key).toLong() } + + override fun getValueAsString(needsGlobal: Boolean): String = getLong(needsGlobal).toString() + + override fun reset() = NativeConfig.setLong(key, defaultValue) +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/Settings.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/Settings.kt new file mode 100644 index 0000000..4965f73 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/Settings.kt @@ -0,0 +1,120 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.settings.model + +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.SudachiApplication + +object Settings { + enum class MenuTag(val titleId: Int = 0) { + SECTION_ROOT(R.string.advanced_settings), + SECTION_SYSTEM(R.string.preferences_system), + SECTION_RENDERER(R.string.preferences_graphics), + SECTION_AUDIO(R.string.preferences_audio), + SECTION_INPUT(R.string.preferences_controls), + SECTION_INPUT_PLAYER_ONE, + SECTION_INPUT_PLAYER_TWO, + SECTION_INPUT_PLAYER_THREE, + SECTION_INPUT_PLAYER_FOUR, + SECTION_INPUT_PLAYER_FIVE, + SECTION_INPUT_PLAYER_SIX, + SECTION_INPUT_PLAYER_SEVEN, + SECTION_INPUT_PLAYER_EIGHT, + SECTION_THEME(R.string.preferences_theme), + SECTION_DEBUG(R.string.preferences_debug); + } + + fun getPlayerString(player: Int): String = + SudachiApplication.appContext.getString(R.string.preferences_player, player) + + const val PREF_FIRST_APP_LAUNCH = "FirstApplicationLaunch" + const val PREF_MEMORY_WARNING_SHOWN = "MemoryWarningShown" + + // Deprecated input overlay preference keys + const val PREF_CONTROL_SCALE = "controlScale" + const val PREF_CONTROL_OPACITY = "controlOpacity" + const val PREF_TOUCH_ENABLED = "isTouchEnabled" + const val PREF_BUTTON_A = "buttonToggle0" + const val PREF_BUTTON_B = "buttonToggle1" + const val PREF_BUTTON_X = "buttonToggle2" + const val PREF_BUTTON_Y = "buttonToggle3" + const val PREF_BUTTON_L = "buttonToggle4" + const val PREF_BUTTON_R = "buttonToggle5" + const val PREF_BUTTON_ZL = "buttonToggle6" + const val PREF_BUTTON_ZR = "buttonToggle7" + const val PREF_BUTTON_PLUS = "buttonToggle8" + const val PREF_BUTTON_MINUS = "buttonToggle9" + const val PREF_BUTTON_DPAD = "buttonToggle10" + const val PREF_STICK_L = "buttonToggle11" + const val PREF_STICK_R = "buttonToggle12" + const val PREF_BUTTON_STICK_L = "buttonToggle13" + const val PREF_BUTTON_STICK_R = "buttonToggle14" + const val PREF_BUTTON_HOME = "buttonToggle15" + const val PREF_BUTTON_SCREENSHOT = "buttonToggle16" + const val PREF_MENU_SETTINGS_JOYSTICK_REL_CENTER = "EmulationMenuSettings_JoystickRelCenter" + const val PREF_MENU_SETTINGS_DPAD_SLIDE = "EmulationMenuSettings_DpadSlideEnable" + const val PREF_MENU_SETTINGS_HAPTICS = "EmulationMenuSettings_Haptics" + const val PREF_MENU_SETTINGS_SHOW_FPS = "EmulationMenuSettings_ShowFps" + const val PREF_MENU_SETTINGS_SHOW_OVERLAY = "EmulationMenuSettings_ShowOverlay" + val overlayPreferences = listOf( + PREF_BUTTON_A, + PREF_BUTTON_B, + PREF_BUTTON_X, + PREF_BUTTON_Y, + PREF_BUTTON_L, + PREF_BUTTON_R, + PREF_BUTTON_ZL, + PREF_BUTTON_ZR, + PREF_BUTTON_PLUS, + PREF_BUTTON_MINUS, + PREF_BUTTON_DPAD, + PREF_STICK_L, + PREF_STICK_R, + PREF_BUTTON_HOME, + PREF_BUTTON_SCREENSHOT, + PREF_BUTTON_STICK_L, + PREF_BUTTON_STICK_R + ) + + // Deprecated layout preference keys + const val PREF_LANDSCAPE_SUFFIX = "_Landscape" + const val PREF_PORTRAIT_SUFFIX = "_Portrait" + const val PREF_FOLDABLE_SUFFIX = "_Foldable" + val overlayLayoutSuffixes = listOf( + PREF_LANDSCAPE_SUFFIX, + PREF_PORTRAIT_SUFFIX, + PREF_FOLDABLE_SUFFIX + ) + + // Deprecated theme preference keys + const val PREF_THEME = "Theme" + const val PREF_THEME_MODE = "ThemeMode" + const val PREF_BLACK_BACKGROUNDS = "BlackBackgrounds" + + enum class EmulationOrientation(val int: Int) { + Unspecified(0), + SensorLandscape(5), + Landscape(1), + ReverseLandscape(2), + SensorPortrait(6), + Portrait(4), + ReversePortrait(3); + + companion object { + fun from(int: Int): EmulationOrientation = + entries.firstOrNull { it.int == int } ?: Unspecified + } + } + + enum class EmulationVerticalAlignment(val int: Int) { + Top(1), + Center(0), + Bottom(2); + + companion object { + fun from(int: Int): EmulationVerticalAlignment = + entries.firstOrNull { it.int == int } ?: Center + } + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/ShortSetting.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/ShortSetting.kt new file mode 100644 index 0000000..6526c6d --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/ShortSetting.kt @@ -0,0 +1,25 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.settings.model + +import org.sudachi.sudachi_emu.utils.NativeConfig + +enum class ShortSetting(override val key: String) : AbstractShortSetting { + RENDERER_SPEED_LIMIT("speed_limit"); + + override fun getShort(needsGlobal: Boolean): Short = NativeConfig.getShort(key, needsGlobal) + + override fun setShort(value: Short) { + if (NativeConfig.isPerGameConfigLoaded()) { + global = false + } + NativeConfig.setShort(key, value) + } + + override val defaultValue: Short by lazy { NativeConfig.getDefaultToString(key).toShort() } + + override fun getValueAsString(needsGlobal: Boolean): String = getShort(needsGlobal).toString() + + override fun reset() = NativeConfig.setShort(key, defaultValue) +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/StringSetting.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/StringSetting.kt new file mode 100644 index 0000000..29aea99 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/StringSetting.kt @@ -0,0 +1,26 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.settings.model + +import org.sudachi.sudachi_emu.utils.NativeConfig + +enum class StringSetting(override val key: String) : AbstractStringSetting { + DRIVER_PATH("driver_path"), + DEVICE_NAME("device_name"); + + override fun getString(needsGlobal: Boolean): String = NativeConfig.getString(key, needsGlobal) + + override fun setString(value: String) { + if (NativeConfig.isPerGameConfigLoaded()) { + global = false + } + NativeConfig.setString(key, value) + } + + override val defaultValue: String by lazy { NativeConfig.getDefaultToString(key) } + + override fun getValueAsString(needsGlobal: Boolean): String = getString(needsGlobal) + + override fun reset() = NativeConfig.setString(key, defaultValue) +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/view/AnalogInputSetting.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/view/AnalogInputSetting.kt new file mode 100644 index 0000000..1e5b91d --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/view/AnalogInputSetting.kt @@ -0,0 +1,31 @@ +// SPDX-FileCopyrightText: 2024 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.settings.model.view + +import androidx.annotation.StringRes +import org.sudachi.sudachi_emu.features.input.NativeInput +import org.sudachi.sudachi_emu.features.input.model.AnalogDirection +import org.sudachi.sudachi_emu.features.input.model.InputType +import org.sudachi.sudachi_emu.features.input.model.NativeAnalog +import org.sudachi.sudachi_emu.utils.ParamPackage + +class AnalogInputSetting( + override val playerIndex: Int, + val nativeAnalog: NativeAnalog, + val analogDirection: AnalogDirection, + @StringRes titleId: Int = 0, + titleString: String = "" +) : InputSetting(titleId, titleString) { + override val type = TYPE_INPUT + override val inputType = InputType.Stick + + override fun getSelectedValue(): String { + val params = NativeInput.getStickParam(playerIndex, nativeAnalog) + val analog = analogToText(params, analogDirection.param) + return getDisplayString(params, analog) + } + + override fun setSelectedValue(param: ParamPackage) = + NativeInput.setStickParam(playerIndex, nativeAnalog, param) +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/view/ButtonInputSetting.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/view/ButtonInputSetting.kt new file mode 100644 index 0000000..edd563e --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/view/ButtonInputSetting.kt @@ -0,0 +1,29 @@ +// SPDX-FileCopyrightText: 2024 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.settings.model.view + +import androidx.annotation.StringRes +import org.sudachi.sudachi_emu.utils.ParamPackage +import org.sudachi.sudachi_emu.features.input.NativeInput +import org.sudachi.sudachi_emu.features.input.model.InputType +import org.sudachi.sudachi_emu.features.input.model.NativeButton + +class ButtonInputSetting( + override val playerIndex: Int, + val nativeButton: NativeButton, + @StringRes titleId: Int = 0, + titleString: String = "" +) : InputSetting(titleId, titleString) { + override val type = TYPE_INPUT + override val inputType = InputType.Button + + override fun getSelectedValue(): String { + val params = NativeInput.getButtonParam(playerIndex, nativeButton) + val button = buttonToText(params) + return getDisplayString(params, button) + } + + override fun setSelectedValue(param: ParamPackage) = + NativeInput.setButtonParam(playerIndex, nativeButton, param) +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/view/DateTimeSetting.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/view/DateTimeSetting.kt new file mode 100644 index 0000000..5a53371 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/view/DateTimeSetting.kt @@ -0,0 +1,20 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.settings.model.view + +import androidx.annotation.StringRes +import org.sudachi.sudachi_emu.features.settings.model.AbstractLongSetting + +class DateTimeSetting( + private val longSetting: AbstractLongSetting, + @StringRes titleId: Int = 0, + titleString: String = "", + @StringRes descriptionId: Int = 0, + descriptionString: String = "" +) : SettingsItem(longSetting, titleId, titleString, descriptionId, descriptionString) { + override val type = TYPE_DATETIME_SETTING + + fun getValue(needsGlobal: Boolean = false): Long = longSetting.getLong(needsGlobal) + fun setValue(value: Long) = (setting as AbstractLongSetting).setLong(value) +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/view/HeaderSetting.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/view/HeaderSetting.kt new file mode 100644 index 0000000..8a68451 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/view/HeaderSetting.kt @@ -0,0 +1,13 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.settings.model.view + +import androidx.annotation.StringRes + +class HeaderSetting( + @StringRes titleId: Int = 0, + titleString: String = "" +) : SettingsItem(emptySetting, titleId, titleString, 0, "") { + override val type = TYPE_HEADER +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/view/InputProfileSetting.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/view/InputProfileSetting.kt new file mode 100644 index 0000000..f80c173 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/view/InputProfileSetting.kt @@ -0,0 +1,32 @@ +// SPDX-FileCopyrightText: 2024 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.settings.model.view + +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.features.input.NativeInput +import org.sudachi.sudachi_emu.utils.NativeConfig + +class InputProfileSetting(private val playerIndex: Int) : + SettingsItem(emptySetting, R.string.profile, "", 0, "") { + override val type = TYPE_INPUT_PROFILE + + fun getCurrentProfile(): String = + NativeConfig.getInputSettings(true)[playerIndex].profileName + + fun getProfileNames(): Array = NativeInput.getInputProfileNames() + + fun isProfileNameValid(name: String): Boolean = NativeInput.isProfileNameValid(name) + + fun createProfile(name: String): Boolean = NativeInput.createProfile(name, playerIndex) + + fun deleteProfile(name: String): Boolean = NativeInput.deleteProfile(name, playerIndex) + + fun loadProfile(name: String): Boolean { + val result = NativeInput.loadProfile(name, playerIndex) + NativeInput.reloadInputDevices() + return result + } + + fun saveProfile(name: String): Boolean = NativeInput.saveProfile(name, playerIndex) +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/view/InputSetting.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/view/InputSetting.kt new file mode 100644 index 0000000..094a00d --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/view/InputSetting.kt @@ -0,0 +1,134 @@ +// SPDX-FileCopyrightText: 2024 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.settings.model.view + +import androidx.annotation.StringRes +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.SudachiApplication +import org.sudachi.sudachi_emu.features.input.NativeInput +import org.sudachi.sudachi_emu.features.input.model.ButtonName +import org.sudachi.sudachi_emu.features.input.model.InputType +import org.sudachi.sudachi_emu.utils.ParamPackage + +sealed class InputSetting( + @StringRes titleId: Int, + titleString: String +) : SettingsItem(emptySetting, titleId, titleString, 0, "") { + override val type = TYPE_INPUT + abstract val inputType: InputType + abstract val playerIndex: Int + + protected val context get() = SudachiApplication.appContext + + abstract fun getSelectedValue(): String + + abstract fun setSelectedValue(param: ParamPackage) + + protected fun getDisplayString(params: ParamPackage, control: String): String { + val deviceName = params.get("display", "") + deviceName.ifEmpty { + return context.getString(R.string.not_set) + } + return "$deviceName: $control" + } + + private fun getDirectionName(direction: String): String = + when (direction) { + "up" -> context.getString(R.string.up) + "down" -> context.getString(R.string.down) + "left" -> context.getString(R.string.left) + "right" -> context.getString(R.string.right) + else -> direction + } + + protected fun buttonToText(param: ParamPackage): String { + if (!param.has("engine")) { + return context.getString(R.string.not_set) + } + + val toggle = if (param.get("toggle", false)) "~" else "" + val inverted = if (param.get("inverted", false)) "!" else "" + val invert = if (param.get("invert", "+") == "-") "-" else "" + val turbo = if (param.get("turbo", false)) "$" else "" + val commonButtonName = NativeInput.getButtonName(param) + + if (commonButtonName == ButtonName.Invalid) { + return context.getString(R.string.invalid) + } + + if (commonButtonName == ButtonName.Engine) { + return param.get("engine", "") + } + + if (commonButtonName == ButtonName.Value) { + if (param.has("hat")) { + val hat = getDirectionName(param.get("direction", "")) + return context.getString(R.string.qualified_hat, turbo, toggle, inverted, hat) + } + if (param.has("axis")) { + val axis = param.get("axis", "") + return context.getString( + R.string.qualified_button_stick_axis, + toggle, + inverted, + invert, + axis + ) + } + if (param.has("button")) { + val button = param.get("button", "") + return context.getString(R.string.qualified_button, turbo, toggle, inverted, button) + } + } + + return context.getString(R.string.unknown) + } + + protected fun analogToText(param: ParamPackage, direction: String): String { + if (!param.has("engine")) { + return context.getString(R.string.not_set) + } + + if (param.get("engine", "") == "analog_from_button") { + return buttonToText(ParamPackage(param.get(direction, ""))) + } + + if (!param.has("axis_x") || !param.has("axis_y")) { + return context.getString(R.string.unknown) + } + + val xAxis = param.get("axis_x", "") + val yAxis = param.get("axis_y", "") + val xInvert = param.get("invert_x", "+") == "-" + val yInvert = param.get("invert_y", "+") == "-" + + if (direction == "modifier") { + return context.getString(R.string.unused) + } + + when (direction) { + "up" -> { + val yInvertString = if (yInvert) "+" else "-" + return context.getString(R.string.qualified_axis, yAxis, yInvertString) + } + + "down" -> { + val yInvertString = if (yInvert) "-" else "+" + return context.getString(R.string.qualified_axis, yAxis, yInvertString) + } + + "left" -> { + val xInvertString = if (xInvert) "+" else "-" + return context.getString(R.string.qualified_axis, xAxis, xInvertString) + } + + "right" -> { + val xInvertString = if (xInvert) "-" else "+" + return context.getString(R.string.qualified_axis, xAxis, xInvertString) + } + } + + return context.getString(R.string.unknown) + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/view/IntSingleChoiceSetting.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/view/IntSingleChoiceSetting.kt new file mode 100644 index 0000000..13b4917 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/view/IntSingleChoiceSetting.kt @@ -0,0 +1,38 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.settings.model.view + +import androidx.annotation.StringRes +import org.sudachi.sudachi_emu.features.settings.model.AbstractIntSetting + +class IntSingleChoiceSetting( + private val intSetting: AbstractIntSetting, + @StringRes titleId: Int = 0, + titleString: String = "", + @StringRes descriptionId: Int = 0, + descriptionString: String = "", + val choices: Array, + val values: Array +) : SettingsItem(intSetting, titleId, titleString, descriptionId, descriptionString) { + override val type = TYPE_INT_SINGLE_CHOICE + + fun getValueAt(index: Int): Int = + if (values.indices.contains(index)) values[index] else -1 + + fun getChoiceAt(index: Int): String = + if (choices.indices.contains(index)) choices[index] else "" + + fun getSelectedValue(needsGlobal: Boolean = false) = intSetting.getInt(needsGlobal) + fun setSelectedValue(value: Int) = intSetting.setInt(value) + + val selectedValueIndex: Int + get() { + for (i in values.indices) { + if (values[i] == getSelectedValue()) { + return i + } + } + return -1 + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/view/ModifierInputSetting.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/view/ModifierInputSetting.kt new file mode 100644 index 0000000..3b77c6a --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/view/ModifierInputSetting.kt @@ -0,0 +1,31 @@ +// SPDX-FileCopyrightText: 2024 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.settings.model.view + +import androidx.annotation.StringRes +import org.sudachi.sudachi_emu.features.input.NativeInput +import org.sudachi.sudachi_emu.features.input.model.InputType +import org.sudachi.sudachi_emu.features.input.model.NativeAnalog +import org.sudachi.sudachi_emu.utils.ParamPackage + +class ModifierInputSetting( + override val playerIndex: Int, + val nativeAnalog: NativeAnalog, + @StringRes titleId: Int = 0, + titleString: String = "" +) : InputSetting(titleId, titleString) { + override val inputType = InputType.Button + + override fun getSelectedValue(): String { + val analogParam = NativeInput.getStickParam(playerIndex, nativeAnalog) + val modifierParam = ParamPackage(analogParam.get("modifier", "")) + return buttonToText(modifierParam) + } + + override fun setSelectedValue(param: ParamPackage) { + val newParam = NativeInput.getStickParam(playerIndex, nativeAnalog) + newParam.set("modifier", param.serialize()) + NativeInput.setStickParam(playerIndex, nativeAnalog, newParam) + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/view/RunnableSetting.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/view/RunnableSetting.kt new file mode 100644 index 0000000..242bebf --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/view/RunnableSetting.kt @@ -0,0 +1,19 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.settings.model.view + +import androidx.annotation.DrawableRes +import androidx.annotation.StringRes + +class RunnableSetting( + @StringRes titleId: Int = 0, + titleString: String = "", + @StringRes descriptionId: Int = 0, + descriptionString: String = "", + val isRunnable: Boolean, + @DrawableRes val iconId: Int = 0, + val runnable: () -> Unit +) : SettingsItem(emptySetting, titleId, titleString, descriptionId, descriptionString) { + override val type = TYPE_RUNNABLE +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/view/SettingsItem.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/view/SettingsItem.kt new file mode 100644 index 0000000..4a17199 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/view/SettingsItem.kt @@ -0,0 +1,391 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.settings.model.view + +import androidx.annotation.StringRes +import org.sudachi.sudachi_emu.NativeLibrary +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.SudachiApplication +import org.sudachi.sudachi_emu.features.input.NativeInput +import org.sudachi.sudachi_emu.features.input.model.NpadStyleIndex +import org.sudachi.sudachi_emu.features.settings.model.AbstractBooleanSetting +import org.sudachi.sudachi_emu.features.settings.model.AbstractSetting +import org.sudachi.sudachi_emu.features.settings.model.BooleanSetting +import org.sudachi.sudachi_emu.features.settings.model.ByteSetting +import org.sudachi.sudachi_emu.features.settings.model.IntSetting +import org.sudachi.sudachi_emu.features.settings.model.LongSetting +import org.sudachi.sudachi_emu.features.settings.model.ShortSetting +import org.sudachi.sudachi_emu.features.settings.model.StringSetting +import org.sudachi.sudachi_emu.utils.NativeConfig + +/** + * ViewModel abstraction for an Item in the RecyclerView powering SettingsFragments. + * Each one corresponds to a [AbstractSetting] object, so this class's subclasses + * should vaguely correspond to those subclasses. There are a few with multiple analogues + * and a few with none (Headers, for example, do not correspond to anything in the ini + * file.) + */ +abstract class SettingsItem( + val setting: AbstractSetting, + @StringRes val titleId: Int, + val titleString: String, + @StringRes val descriptionId: Int, + val descriptionString: String +) { + abstract val type: Int + + val title: String by lazy { + if (titleId != 0) { + return@lazy SudachiApplication.appContext.getString(titleId) + } + return@lazy titleString + } + + val description: String by lazy { + if (descriptionId != 0) { + return@lazy SudachiApplication.appContext.getString(descriptionId) + } + return@lazy descriptionString + } + + val isEditable: Boolean + get() { + // Can't change docked mode toggle when using handheld mode + if (setting.key == BooleanSetting.USE_DOCKED_MODE.key) { + return NativeInput.getStyleIndex(0) != NpadStyleIndex.Handheld + } + + // Can't edit settings that aren't saveable in per-game config even if they are switchable + if (NativeConfig.isPerGameConfigLoaded() && !setting.isSaveable) { + return false + } + + if (!NativeLibrary.isRunning()) return true + + // Prevent editing settings that were modified in per-game config while editing global + // config + if (!NativeConfig.isPerGameConfigLoaded() && !setting.global) { + return false + } + + return setting.isRuntimeModifiable + } + + val needsRuntimeGlobal: Boolean + get() = NativeLibrary.isRunning() && !setting.global && + !NativeConfig.isPerGameConfigLoaded() + + val clearable: Boolean + get() = !setting.global && NativeConfig.isPerGameConfigLoaded() + + companion object { + const val TYPE_HEADER = 0 + const val TYPE_SWITCH = 1 + const val TYPE_SINGLE_CHOICE = 2 + const val TYPE_SLIDER = 3 + const val TYPE_SUBMENU = 4 + const val TYPE_STRING_SINGLE_CHOICE = 5 + const val TYPE_DATETIME_SETTING = 6 + const val TYPE_RUNNABLE = 7 + const val TYPE_INPUT = 8 + const val TYPE_INT_SINGLE_CHOICE = 9 + const val TYPE_INPUT_PROFILE = 10 + const val TYPE_STRING_INPUT = 11 + + const val FASTMEM_COMBINED = "fastmem_combined" + + val emptySetting = object : AbstractSetting { + override val key: String = "" + override val defaultValue: Any = false + override val isSaveable = true + override fun getValueAsString(needsGlobal: Boolean): String = "" + override fun reset() {} + } + + // Extension for putting SettingsItems into a hashmap without repeating yourself + fun HashMap.put(item: SettingsItem) { + put(item.setting.key, item) + } + + // List of all general + val settingsItems = HashMap().apply { + put(StringInputSetting(StringSetting.DEVICE_NAME, titleId = R.string.device_name)) + put( + SwitchSetting( + BooleanSetting.RENDERER_USE_SPEED_LIMIT, + titleId = R.string.frame_limit_enable, + descriptionId = R.string.frame_limit_enable_description + ) + ) + put( + SliderSetting( + ShortSetting.RENDERER_SPEED_LIMIT, + titleId = R.string.frame_limit_slider, + descriptionId = R.string.frame_limit_slider_description, + min = 1, + max = 400, + units = "%" + ) + ) + put( + SingleChoiceSetting( + IntSetting.CPU_BACKEND, + titleId = R.string.cpu_backend, + choicesId = R.array.cpuBackendArm64Names, + valuesId = R.array.cpuBackendArm64Values + ) + ) + put( + SingleChoiceSetting( + IntSetting.CPU_ACCURACY, + titleId = R.string.cpu_accuracy, + choicesId = R.array.cpuAccuracyNames, + valuesId = R.array.cpuAccuracyValues + ) + ) + put( + SwitchSetting( + BooleanSetting.PICTURE_IN_PICTURE, + titleId = R.string.picture_in_picture, + descriptionId = R.string.picture_in_picture_description + ) + ) + + val dockedModeSetting = object : AbstractBooleanSetting { + override val key = BooleanSetting.USE_DOCKED_MODE.key + + override fun getBoolean(needsGlobal: Boolean): Boolean { + if (NativeInput.getStyleIndex(0) == NpadStyleIndex.Handheld) { + return false + } + return BooleanSetting.USE_DOCKED_MODE.getBoolean(needsGlobal) + } + + override fun setBoolean(value: Boolean) = + BooleanSetting.USE_DOCKED_MODE.setBoolean(value) + + override val defaultValue = BooleanSetting.USE_DOCKED_MODE.defaultValue + + override fun getValueAsString(needsGlobal: Boolean): String = + BooleanSetting.USE_DOCKED_MODE.getValueAsString(needsGlobal) + + override fun reset() = BooleanSetting.USE_DOCKED_MODE.reset() + } + put( + SwitchSetting( + dockedModeSetting, + titleId = R.string.use_docked_mode, + descriptionId = R.string.use_docked_mode_description + ) + ) + + put( + SingleChoiceSetting( + IntSetting.REGION_INDEX, + titleId = R.string.emulated_region, + choicesId = R.array.regionNames, + valuesId = R.array.regionValues + ) + ) + put( + SingleChoiceSetting( + IntSetting.LANGUAGE_INDEX, + titleId = R.string.emulated_language, + choicesId = R.array.languageNames, + valuesId = R.array.languageValues + ) + ) + put( + SwitchSetting( + BooleanSetting.USE_CUSTOM_RTC, + titleId = R.string.use_custom_rtc, + descriptionId = R.string.use_custom_rtc_description + ) + ) + put(DateTimeSetting(LongSetting.CUSTOM_RTC, titleId = R.string.set_custom_rtc)) + put( + SingleChoiceSetting( + IntSetting.RENDERER_ACCURACY, + titleId = R.string.renderer_accuracy, + choicesId = R.array.rendererAccuracyNames, + valuesId = R.array.rendererAccuracyValues + ) + ) + put( + SingleChoiceSetting( + IntSetting.RENDERER_RESOLUTION, + titleId = R.string.renderer_resolution, + choicesId = R.array.rendererResolutionNames, + valuesId = R.array.rendererResolutionValues + ) + ) + put( + SingleChoiceSetting( + IntSetting.RENDERER_VSYNC, + titleId = R.string.renderer_vsync, + choicesId = R.array.rendererVSyncNames, + valuesId = R.array.rendererVSyncValues + ) + ) + put( + SingleChoiceSetting( + IntSetting.RENDERER_SCALING_FILTER, + titleId = R.string.renderer_scaling_filter, + choicesId = R.array.rendererScalingFilterNames, + valuesId = R.array.rendererScalingFilterValues + ) + ) + put( + SliderSetting( + IntSetting.FSR_SHARPENING_SLIDER, + titleId = R.string.fsr_sharpness, + descriptionId = R.string.fsr_sharpness_description, + units = "%" + ) + ) + put( + SingleChoiceSetting( + IntSetting.RENDERER_ANTI_ALIASING, + titleId = R.string.renderer_anti_aliasing, + choicesId = R.array.rendererAntiAliasingNames, + valuesId = R.array.rendererAntiAliasingValues + ) + ) + put( + SingleChoiceSetting( + IntSetting.RENDERER_SCREEN_LAYOUT, + titleId = R.string.renderer_screen_layout, + choicesId = R.array.rendererScreenLayoutNames, + valuesId = R.array.rendererScreenLayoutValues + ) + ) + put( + SingleChoiceSetting( + IntSetting.RENDERER_ASPECT_RATIO, + titleId = R.string.renderer_aspect_ratio, + choicesId = R.array.rendererAspectRatioNames, + valuesId = R.array.rendererAspectRatioValues + ) + ) + put( + SingleChoiceSetting( + IntSetting.VERTICAL_ALIGNMENT, + titleId = R.string.vertical_alignment, + descriptionId = 0, + choicesId = R.array.verticalAlignmentEntries, + valuesId = R.array.verticalAlignmentValues + ) + ) + put( + SwitchSetting( + BooleanSetting.RENDERER_USE_DISK_SHADER_CACHE, + titleId = R.string.use_disk_shader_cache, + descriptionId = R.string.use_disk_shader_cache_description + ) + ) + put( + SwitchSetting( + BooleanSetting.RENDERER_FORCE_MAX_CLOCK, + titleId = R.string.renderer_force_max_clock, + descriptionId = R.string.renderer_force_max_clock_description + ) + ) + put( + SwitchSetting( + BooleanSetting.RENDERER_ASYNCHRONOUS_SHADERS, + titleId = R.string.renderer_asynchronous_shaders, + descriptionId = R.string.renderer_asynchronous_shaders_description + ) + ) + put( + SwitchSetting( + BooleanSetting.RENDERER_REACTIVE_FLUSHING, + titleId = R.string.renderer_reactive_flushing, + descriptionId = R.string.renderer_reactive_flushing_description + ) + ) + put( + SingleChoiceSetting( + IntSetting.MAX_ANISOTROPY, + titleId = R.string.anisotropic_filtering, + descriptionId = R.string.anisotropic_filtering_description, + choicesId = R.array.anisoEntries, + valuesId = R.array.anisoValues + ) + ) + put( + SingleChoiceSetting( + IntSetting.AUDIO_OUTPUT_ENGINE, + titleId = R.string.audio_output_engine, + choicesId = R.array.outputEngineEntries, + valuesId = R.array.outputEngineValues + ) + ) + put( + SliderSetting( + ByteSetting.AUDIO_VOLUME, + titleId = R.string.audio_volume, + descriptionId = R.string.audio_volume_description, + units = "%" + ) + ) + put( + SingleChoiceSetting( + IntSetting.RENDERER_BACKEND, + titleId = R.string.renderer_api, + choicesId = R.array.rendererApiNames, + valuesId = R.array.rendererApiValues + ) + ) + put( + SwitchSetting( + BooleanSetting.RENDERER_DEBUG, + titleId = R.string.renderer_debug, + descriptionId = R.string.renderer_debug_description + ) + ) + put( + SwitchSetting( + BooleanSetting.CPU_DEBUG_MODE, + titleId = R.string.cpu_debug_mode, + descriptionId = R.string.cpu_debug_mode_description + ) + ) + + val fastmem = object : AbstractBooleanSetting { + override fun getBoolean(needsGlobal: Boolean): Boolean = + BooleanSetting.FASTMEM.getBoolean() && + BooleanSetting.FASTMEM_EXCLUSIVES.getBoolean() + + override fun setBoolean(value: Boolean) { + BooleanSetting.FASTMEM.setBoolean(value) + BooleanSetting.FASTMEM_EXCLUSIVES.setBoolean(value) + } + + override val key: String = FASTMEM_COMBINED + override val isRuntimeModifiable: Boolean = false + override val pairedSettingKey = BooleanSetting.CPU_DEBUG_MODE.key + override val defaultValue: Boolean = true + override val isSwitchable: Boolean = true + override var global: Boolean + get() { + return BooleanSetting.FASTMEM.global && + BooleanSetting.FASTMEM_EXCLUSIVES.global + } + set(value) { + BooleanSetting.FASTMEM.global = value + BooleanSetting.FASTMEM_EXCLUSIVES.global = value + } + + override val isSaveable = true + + override fun getValueAsString(needsGlobal: Boolean): String = + getBoolean().toString() + + override fun reset() = setBoolean(defaultValue) + } + put(SwitchSetting(fastmem, R.string.fastmem)) + } + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/view/SingleChoiceSetting.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/view/SingleChoiceSetting.kt new file mode 100644 index 0000000..946f683 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/view/SingleChoiceSetting.kt @@ -0,0 +1,29 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.settings.model.view + +import androidx.annotation.ArrayRes +import androidx.annotation.StringRes +import org.sudachi.sudachi_emu.features.settings.model.AbstractIntSetting +import org.sudachi.sudachi_emu.features.settings.model.AbstractSetting + +class SingleChoiceSetting( + setting: AbstractSetting, + @StringRes titleId: Int = 0, + titleString: String = "", + @StringRes descriptionId: Int = 0, + descriptionString: String = "", + @ArrayRes val choicesId: Int, + @ArrayRes val valuesId: Int +) : SettingsItem(setting, titleId, titleString, descriptionId, descriptionString) { + override val type = TYPE_SINGLE_CHOICE + + fun getSelectedValue(needsGlobal: Boolean = false) = + when (setting) { + is AbstractIntSetting -> setting.getInt(needsGlobal) + else -> -1 + } + + fun setSelectedValue(value: Int) = (setting as AbstractIntSetting).setInt(value) +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/view/SliderSetting.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/view/SliderSetting.kt new file mode 100644 index 0000000..012441e --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/view/SliderSetting.kt @@ -0,0 +1,42 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.settings.model.view + +import androidx.annotation.StringRes +import org.sudachi.sudachi_emu.features.settings.model.AbstractByteSetting +import org.sudachi.sudachi_emu.features.settings.model.AbstractFloatSetting +import org.sudachi.sudachi_emu.features.settings.model.AbstractIntSetting +import org.sudachi.sudachi_emu.features.settings.model.AbstractSetting +import org.sudachi.sudachi_emu.features.settings.model.AbstractShortSetting +import kotlin.math.roundToInt + +class SliderSetting( + setting: AbstractSetting, + @StringRes titleId: Int = 0, + titleString: String = "", + @StringRes descriptionId: Int = 0, + descriptionString: String = "", + val min: Int = 0, + val max: Int = 100, + val units: String = "" +) : SettingsItem(setting, titleId, titleString, descriptionId, descriptionString) { + override val type = TYPE_SLIDER + + fun getSelectedValue(needsGlobal: Boolean = false) = + when (setting) { + is AbstractByteSetting -> setting.getByte(needsGlobal).toInt() + is AbstractShortSetting -> setting.getShort(needsGlobal).toInt() + is AbstractIntSetting -> setting.getInt(needsGlobal) + is AbstractFloatSetting -> setting.getFloat(needsGlobal).roundToInt() + else -> -1 + } + + fun setSelectedValue(value: Int) = + when (setting) { + is AbstractByteSetting -> setting.setByte(value.toByte()) + is AbstractShortSetting -> setting.setShort(value.toShort()) + is AbstractFloatSetting -> setting.setFloat(value.toFloat()) + else -> (setting as AbstractIntSetting).setInt(value) + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/view/StringInputSetting.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/view/StringInputSetting.kt new file mode 100644 index 0000000..f488290 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/view/StringInputSetting.kt @@ -0,0 +1,22 @@ +// SPDX-FileCopyrightText: 2024 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.settings.model.view + +import androidx.annotation.StringRes +import org.sudachi.sudachi_emu.features.settings.model.AbstractStringSetting + +class StringInputSetting( + setting: AbstractStringSetting, + @StringRes titleId: Int = 0, + titleString: String = "", + @StringRes descriptionId: Int = 0, + descriptionString: String = "" +) : SettingsItem(setting, titleId, titleString, descriptionId, descriptionString) { + override val type = TYPE_STRING_INPUT + + fun getSelectedValue(needsGlobal: Boolean = false) = setting.getValueAsString(needsGlobal) + + fun setSelectedValue(selection: String) = + (setting as AbstractStringSetting).setString(selection) +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/view/StringSingleChoiceSetting.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/view/StringSingleChoiceSetting.kt new file mode 100644 index 0000000..e035562 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/view/StringSingleChoiceSetting.kt @@ -0,0 +1,35 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.settings.model.view + +import androidx.annotation.StringRes +import org.sudachi.sudachi_emu.features.settings.model.AbstractStringSetting + +class StringSingleChoiceSetting( + private val stringSetting: AbstractStringSetting, + @StringRes titleId: Int = 0, + titleString: String = "", + @StringRes descriptionId: Int = 0, + descriptionString: String = "", + val choices: Array, + val values: Array +) : SettingsItem(stringSetting, titleId, titleString, descriptionId, descriptionString) { + override val type = TYPE_STRING_SINGLE_CHOICE + + fun getValueAt(index: Int): String = + if (index >= 0 && index < values.size) values[index] else "" + + fun getSelectedValue(needsGlobal: Boolean = false) = stringSetting.getString(needsGlobal) + fun setSelectedValue(value: String) = stringSetting.setString(value) + + val selectedValueIndex: Int + get() { + for (i in values.indices) { + if (values[i] == getSelectedValue()) { + return i + } + } + return -1 + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/view/SubmenuSetting.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/view/SubmenuSetting.kt new file mode 100644 index 0000000..dcbd04b --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/view/SubmenuSetting.kt @@ -0,0 +1,19 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.settings.model.view + +import androidx.annotation.DrawableRes +import androidx.annotation.StringRes +import org.sudachi.sudachi_emu.features.settings.model.Settings + +class SubmenuSetting( + @StringRes titleId: Int = 0, + titleString: String = "", + @StringRes descriptionId: Int = 0, + descriptionString: String = "", + @DrawableRes val iconId: Int = 0, + val menuKey: Settings.MenuTag +) : SettingsItem(emptySetting, titleId, titleString, descriptionId, descriptionString) { + override val type = TYPE_SUBMENU +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/view/SwitchSetting.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/view/SwitchSetting.kt new file mode 100644 index 0000000..897935e --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/model/view/SwitchSetting.kt @@ -0,0 +1,34 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.settings.model.view + +import androidx.annotation.StringRes +import org.sudachi.sudachi_emu.features.settings.model.AbstractBooleanSetting +import org.sudachi.sudachi_emu.features.settings.model.AbstractIntSetting +import org.sudachi.sudachi_emu.features.settings.model.AbstractSetting + +class SwitchSetting( + setting: AbstractSetting, + @StringRes titleId: Int = 0, + titleString: String = "", + @StringRes descriptionId: Int = 0, + descriptionString: String = "" +) : SettingsItem(setting, titleId, titleString, descriptionId, descriptionString) { + override val type = TYPE_SWITCH + + fun getIsChecked(needsGlobal: Boolean = false): Boolean { + return when (setting) { + is AbstractIntSetting -> setting.getInt(needsGlobal) == 1 + is AbstractBooleanSetting -> setting.getBoolean(needsGlobal) + else -> false + } + } + + fun setChecked(value: Boolean) { + when (setting) { + is AbstractIntSetting -> setting.setInt(if (value) 1 else 0) + is AbstractBooleanSetting -> setting.setBoolean(value) + } + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/InputDialogFragment.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/InputDialogFragment.kt new file mode 100644 index 0000000..91fc566 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/InputDialogFragment.kt @@ -0,0 +1,300 @@ +// SPDX-FileCopyrightText: 2024 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.settings.ui + +import android.app.Dialog +import android.graphics.drawable.Animatable2 +import android.graphics.drawable.AnimatedVectorDrawable +import android.graphics.drawable.Drawable +import android.os.Bundle +import android.view.InputDevice +import android.view.KeyEvent +import android.view.LayoutInflater +import android.view.MotionEvent +import android.view.View +import android.view.ViewGroup +import androidx.fragment.app.DialogFragment +import androidx.fragment.app.activityViewModels +import com.google.android.material.dialog.MaterialAlertDialogBuilder +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.databinding.DialogMappingBinding +import org.sudachi.sudachi_emu.features.input.NativeInput +import org.sudachi.sudachi_emu.features.input.model.NativeAnalog +import org.sudachi.sudachi_emu.features.input.model.NativeButton +import org.sudachi.sudachi_emu.features.settings.model.view.AnalogInputSetting +import org.sudachi.sudachi_emu.features.settings.model.view.ButtonInputSetting +import org.sudachi.sudachi_emu.features.settings.model.view.InputSetting +import org.sudachi.sudachi_emu.features.settings.model.view.ModifierInputSetting +import org.sudachi.sudachi_emu.utils.InputHandler +import org.sudachi.sudachi_emu.utils.ParamPackage + +class InputDialogFragment : DialogFragment() { + private var inputAccepted = false + + private var position: Int = 0 + + private lateinit var inputSetting: InputSetting + + private lateinit var binding: DialogMappingBinding + + private val settingsViewModel: SettingsViewModel by activityViewModels() + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + if (settingsViewModel.clickedItem == null) dismiss() + + position = requireArguments().getInt(POSITION) + + InputHandler.updateControllerData() + } + + override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { + inputSetting = settingsViewModel.clickedItem as InputSetting + binding = DialogMappingBinding.inflate(layoutInflater) + + val builder = MaterialAlertDialogBuilder(requireContext()) + .setPositiveButton(android.R.string.cancel) { _, _ -> + NativeInput.stopMapping() + dismiss() + } + .setView(binding.root) + + val playButtonMapAnimation = { twoDirections: Boolean -> + val stickAnimation: AnimatedVectorDrawable + val buttonAnimation: AnimatedVectorDrawable + binding.imageStickAnimation.apply { + val anim = if (twoDirections) { + R.drawable.stick_two_direction_anim + } else { + R.drawable.stick_one_direction_anim + } + setBackgroundResource(anim) + stickAnimation = background as AnimatedVectorDrawable + } + binding.imageButtonAnimation.apply { + setBackgroundResource(R.drawable.button_anim) + buttonAnimation = background as AnimatedVectorDrawable + } + stickAnimation.registerAnimationCallback(object : Animatable2.AnimationCallback() { + override fun onAnimationEnd(drawable: Drawable?) { + buttonAnimation.start() + } + }) + buttonAnimation.registerAnimationCallback(object : Animatable2.AnimationCallback() { + override fun onAnimationEnd(drawable: Drawable?) { + stickAnimation.start() + } + }) + stickAnimation.start() + } + + when (val setting = inputSetting) { + is AnalogInputSetting -> { + when (setting.nativeAnalog) { + NativeAnalog.LStick -> builder.setTitle( + getString(R.string.map_control, getString(R.string.left_stick)) + ) + + NativeAnalog.RStick -> builder.setTitle( + getString(R.string.map_control, getString(R.string.right_stick)) + ) + } + + builder.setMessage(R.string.stick_map_description) + + playButtonMapAnimation.invoke(true) + } + + is ModifierInputSetting -> { + builder.setTitle(getString(R.string.map_control, setting.title)) + .setMessage(R.string.button_map_description) + playButtonMapAnimation.invoke(false) + } + + is ButtonInputSetting -> { + if (setting.nativeButton == NativeButton.DUp || + setting.nativeButton == NativeButton.DDown || + setting.nativeButton == NativeButton.DLeft || + setting.nativeButton == NativeButton.DRight + ) { + builder.setTitle(getString(R.string.map_dpad_direction, setting.title)) + } else { + builder.setTitle(getString(R.string.map_control, setting.title)) + } + builder.setMessage(R.string.button_map_description) + playButtonMapAnimation.invoke(false) + } + } + + return builder.create() + } + + override fun onCreateView( + inflater: LayoutInflater, + container: ViewGroup?, + savedInstanceState: Bundle? + ): View { + return binding.root + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + view.requestFocus() + view.setOnFocusChangeListener { v, hasFocus -> if (!hasFocus) v.requestFocus() } + dialog?.setOnKeyListener { _, _, keyEvent -> onKeyEvent(keyEvent) } + binding.root.setOnGenericMotionListener { _, motionEvent -> onMotionEvent(motionEvent) } + NativeInput.beginMapping(inputSetting.inputType.int) + } + + private fun onKeyEvent(event: KeyEvent): Boolean { + if (event.source and InputDevice.SOURCE_JOYSTICK != InputDevice.SOURCE_JOYSTICK && + event.source and InputDevice.SOURCE_GAMEPAD != InputDevice.SOURCE_GAMEPAD + ) { + return false + } + + val action = when (event.action) { + KeyEvent.ACTION_DOWN -> NativeInput.ButtonState.PRESSED + KeyEvent.ACTION_UP -> NativeInput.ButtonState.RELEASED + else -> return false + } + val controllerData = + InputHandler.androidControllers[event.device.controllerNumber] ?: return false + NativeInput.onGamePadButtonEvent( + controllerData.getGUID(), + controllerData.getPort(), + event.keyCode, + action + ) + onInputReceived(event.device) + return true + } + + private fun onMotionEvent(event: MotionEvent): Boolean { + if (event.source and InputDevice.SOURCE_JOYSTICK != InputDevice.SOURCE_JOYSTICK && + event.source and InputDevice.SOURCE_GAMEPAD != InputDevice.SOURCE_GAMEPAD + ) { + return false + } + + // Temp workaround for DPads that give both axis and button input. The input system can't + // take in a specific axis direction for a binding so you lose half of the directions for a DPad. + + val controllerData = + InputHandler.androidControllers[event.device.controllerNumber] ?: return false + event.device.motionRanges.forEach { + NativeInput.onGamePadAxisEvent( + controllerData.getGUID(), + controllerData.getPort(), + it.axis, + event.getAxisValue(it.axis) + ) + onInputReceived(event.device) + } + return true + } + + private fun onInputReceived(device: InputDevice) { + val params = ParamPackage(NativeInput.getNextInput()) + if (params.has("engine") && isInputAcceptable(params) && !inputAccepted) { + inputAccepted = true + setResult(params, device) + } + } + + private fun setResult(params: ParamPackage, device: InputDevice) { + NativeInput.stopMapping() + params.set("display", "${device.name} ${params.get("port", 0)}") + when (val item = settingsViewModel.clickedItem as InputSetting) { + is ModifierInputSetting, + is ButtonInputSetting -> { + // Invert DPad up and left bindings by default + val tempSetting = inputSetting as? ButtonInputSetting + if (tempSetting != null) { + if (tempSetting.nativeButton == NativeButton.DUp || + tempSetting.nativeButton == NativeButton.DLeft && + params.has("axis") + ) { + params.set("invert", "-") + } + } + + item.setSelectedValue(params) + settingsViewModel.setAdapterItemChanged(position) + } + + is AnalogInputSetting -> { + var analogParam = NativeInput.getStickParam(item.playerIndex, item.nativeAnalog) + analogParam = adjustAnalogParam(params, analogParam, item.analogDirection.param) + + // Invert Y-Axis by default + analogParam.set("invert_y", "-") + + item.setSelectedValue(analogParam) + settingsViewModel.setReloadListAndNotifyDataset(true) + } + } + dismiss() + } + + private fun adjustAnalogParam( + inputParam: ParamPackage, + analogParam: ParamPackage, + buttonName: String + ): ParamPackage { + // The poller returned a complete axis, so set all the buttons + if (inputParam.has("axis_x") && inputParam.has("axis_y")) { + return inputParam + } + + // Check if the current configuration has either no engine or an axis binding. + // Clears out the old binding and adds one with analog_from_button. + if (!analogParam.has("engine") || analogParam.has("axis_x") || analogParam.has("axis_y")) { + analogParam.clear() + analogParam.set("engine", "analog_from_button") + } + analogParam.set(buttonName, inputParam.serialize()) + return analogParam + } + + private fun isInputAcceptable(params: ParamPackage): Boolean { + if (InputHandler.registeredControllers.size == 1) { + return true + } + + if (params.has("motion")) { + return true + } + + val currentDevice = settingsViewModel.getCurrentDeviceParams(params) + if (currentDevice.get("engine", "any") == "any") { + return true + } + + val guidMatch = params.get("guid", "") == currentDevice.get("guid", "") || + params.get("guid", "") == currentDevice.get("guid2", "") + return params.get("engine", "") == currentDevice.get("engine", "") && + guidMatch && + params.get("port", 0) == currentDevice.get("port", 0) + } + + companion object { + const val TAG = "InputDialogFragment" + + const val POSITION = "Position" + + fun newInstance( + inputMappingViewModel: SettingsViewModel, + setting: InputSetting, + position: Int + ): InputDialogFragment { + inputMappingViewModel.clickedItem = setting + val args = Bundle() + args.putInt(POSITION, position) + val fragment = InputDialogFragment() + fragment.arguments = args + return fragment + } + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/InputProfileAdapter.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/InputProfileAdapter.kt new file mode 100644 index 0000000..1275408 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/InputProfileAdapter.kt @@ -0,0 +1,68 @@ +// SPDX-FileCopyrightText: 2024 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.settings.ui + +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import org.sudachi.sudachi_emu.SudachiApplication +import org.sudachi.sudachi_emu.adapters.AbstractListAdapter +import org.sudachi.sudachi_emu.databinding.ListItemInputProfileBinding +import org.sudachi.sudachi_emu.viewholder.AbstractViewHolder +import org.sudachi.sudachi_emu.R + +class InputProfileAdapter(options: List) : + AbstractListAdapter>(options) { + override fun onCreateViewHolder( + parent: ViewGroup, + viewType: Int + ): AbstractViewHolder { + ListItemInputProfileBinding.inflate(LayoutInflater.from(parent.context), parent, false) + .also { return InputProfileViewHolder(it) } + } + + inner class InputProfileViewHolder(val binding: ListItemInputProfileBinding) : + AbstractViewHolder(binding) { + override fun bind(model: ProfileItem) { + when (model) { + is ExistingProfileItem -> { + binding.title.text = model.name + binding.buttonNew.visibility = View.GONE + binding.buttonDelete.visibility = View.VISIBLE + binding.buttonDelete.setOnClickListener { model.deleteProfile.invoke() } + binding.buttonSave.visibility = View.VISIBLE + binding.buttonSave.setOnClickListener { model.saveProfile.invoke() } + binding.buttonLoad.visibility = View.VISIBLE + binding.buttonLoad.setOnClickListener { model.loadProfile.invoke() } + } + + is NewProfileItem -> { + binding.title.text = model.name + binding.buttonNew.visibility = View.VISIBLE + binding.buttonNew.setOnClickListener { model.createNewProfile.invoke() } + binding.buttonSave.visibility = View.GONE + binding.buttonDelete.visibility = View.GONE + binding.buttonLoad.visibility = View.GONE + } + } + } + } +} + +sealed interface ProfileItem { + val name: String +} + +data class NewProfileItem( + val createNewProfile: () -> Unit +) : ProfileItem { + override val name: String = SudachiApplication.appContext.getString(R.string.create_new_profile) +} + +data class ExistingProfileItem( + override val name: String, + val deleteProfile: () -> Unit, + val saveProfile: () -> Unit, + val loadProfile: () -> Unit +) : ProfileItem diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/InputProfileDialogFragment.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/InputProfileDialogFragment.kt new file mode 100644 index 0000000..4257ccf --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/InputProfileDialogFragment.kt @@ -0,0 +1,148 @@ +// SPDX-FileCopyrightText: 2024 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.settings.ui + +import android.app.Dialog +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.Toast +import androidx.fragment.app.DialogFragment +import androidx.fragment.app.activityViewModels +import androidx.recyclerview.widget.LinearLayoutManager +import com.google.android.material.dialog.MaterialAlertDialogBuilder +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.databinding.DialogInputProfilesBinding +import org.sudachi.sudachi_emu.features.settings.model.view.InputProfileSetting +import org.sudachi.sudachi_emu.fragments.MessageDialogFragment +import org.sudachi.sudachi_emu.utils.collect + +class InputProfileDialogFragment : DialogFragment() { + private var position = 0 + + private val settingsViewModel: SettingsViewModel by activityViewModels() + + private lateinit var binding: DialogInputProfilesBinding + + private lateinit var setting: InputProfileSetting + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + position = requireArguments().getInt(POSITION) + } + + override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { + binding = DialogInputProfilesBinding.inflate(layoutInflater) + + setting = settingsViewModel.clickedItem as InputProfileSetting + val options = mutableListOf().apply { + add( + NewProfileItem( + createNewProfile = { + NewInputProfileDialogFragment.newInstance( + settingsViewModel, + setting, + position + ).show(parentFragmentManager, NewInputProfileDialogFragment.TAG) + dismiss() + } + ) + ) + + val onActionDismiss = { + settingsViewModel.setReloadListAndNotifyDataset(true) + dismiss() + } + setting.getProfileNames().forEach { + add( + ExistingProfileItem( + it, + deleteProfile = { + settingsViewModel.setShouldShowDeleteProfileDialog(it) + }, + saveProfile = { + if (!setting.saveProfile(it)) { + Toast.makeText( + requireContext(), + R.string.failed_to_save_profile, + Toast.LENGTH_SHORT + ).show() + } + onActionDismiss.invoke() + }, + loadProfile = { + if (!setting.loadProfile(it)) { + Toast.makeText( + requireContext(), + R.string.failed_to_load_profile, + Toast.LENGTH_SHORT + ).show() + } + onActionDismiss.invoke() + } + ) + ) + } + } + binding.listProfiles.apply { + layoutManager = LinearLayoutManager(requireContext()) + adapter = InputProfileAdapter(options) + } + + return MaterialAlertDialogBuilder(requireContext()) + .setView(binding.root) + .create() + } + + override fun onCreateView( + inflater: LayoutInflater, + container: ViewGroup?, + savedInstanceState: Bundle? + ): View { + return binding.root + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + + settingsViewModel.shouldShowDeleteProfileDialog.collect(viewLifecycleOwner) { + if (it.isNotEmpty()) { + MessageDialogFragment.newInstance( + activity = requireActivity(), + titleId = R.string.delete_input_profile, + descriptionId = R.string.delete_input_profile_description, + positiveAction = { + setting.deleteProfile(it) + settingsViewModel.setReloadListAndNotifyDataset(true) + }, + negativeAction = {}, + negativeButtonTitleId = android.R.string.cancel + ).show(parentFragmentManager, MessageDialogFragment.TAG) + settingsViewModel.setShouldShowDeleteProfileDialog("") + dismiss() + } + } + } + + companion object { + const val TAG = "InputProfileDialogFragment" + + const val POSITION = "Position" + + fun newInstance( + settingsViewModel: SettingsViewModel, + profileSetting: InputProfileSetting, + position: Int + ): InputProfileDialogFragment { + settingsViewModel.clickedItem = profileSetting + + val args = Bundle() + args.putInt(POSITION, position) + val fragment = InputProfileDialogFragment() + fragment.arguments = args + return fragment + } + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/NewInputProfileDialogFragment.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/NewInputProfileDialogFragment.kt new file mode 100644 index 0000000..dcf269a --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/NewInputProfileDialogFragment.kt @@ -0,0 +1,79 @@ +// SPDX-FileCopyrightText: 2024 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.settings.ui + +import android.app.Dialog +import android.os.Bundle +import android.widget.Toast +import androidx.fragment.app.DialogFragment +import androidx.fragment.app.activityViewModels +import com.google.android.material.dialog.MaterialAlertDialogBuilder +import org.sudachi.sudachi_emu.databinding.DialogEditTextBinding +import org.sudachi.sudachi_emu.features.settings.model.view.InputProfileSetting +import org.sudachi.sudachi_emu.R + +class NewInputProfileDialogFragment : DialogFragment() { + private var position = 0 + + private val settingsViewModel: SettingsViewModel by activityViewModels() + + private lateinit var binding: DialogEditTextBinding + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + position = requireArguments().getInt(POSITION) + } + + override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { + binding = DialogEditTextBinding.inflate(layoutInflater) + + val setting = settingsViewModel.clickedItem as InputProfileSetting + return MaterialAlertDialogBuilder(requireContext()) + .setTitle(R.string.enter_profile_name) + .setPositiveButton(android.R.string.ok) { _, _ -> + val profileName = binding.editText.text.toString() + if (!setting.isProfileNameValid(profileName)) { + Toast.makeText( + requireContext(), + R.string.invalid_profile_name, + Toast.LENGTH_SHORT + ).show() + return@setPositiveButton + } + + if (!setting.createProfile(profileName)) { + Toast.makeText( + requireContext(), + R.string.profile_name_already_exists, + Toast.LENGTH_SHORT + ).show() + } else { + settingsViewModel.setAdapterItemChanged(position) + } + } + .setNegativeButton(android.R.string.cancel, null) + .setView(binding.root) + .show() + } + + companion object { + const val TAG = "NewInputProfileDialogFragment" + + const val POSITION = "Position" + + fun newInstance( + settingsViewModel: SettingsViewModel, + profileSetting: InputProfileSetting, + position: Int + ): NewInputProfileDialogFragment { + settingsViewModel.clickedItem = profileSetting + + val args = Bundle() + args.putInt(POSITION, position) + val fragment = NewInputProfileDialogFragment() + fragment.arguments = args + return fragment + } + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/SettingsActivity.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/SettingsActivity.kt new file mode 100644 index 0000000..84f6bd0 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/SettingsActivity.kt @@ -0,0 +1,171 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.settings.ui + +import android.os.Bundle +import android.view.View +import android.view.ViewGroup.MarginLayoutParams +import android.widget.Toast +import androidx.activity.OnBackPressedCallback +import androidx.activity.viewModels +import androidx.appcompat.app.AppCompatActivity +import androidx.core.view.ViewCompat +import androidx.core.view.WindowCompat +import androidx.core.view.WindowInsetsCompat +import androidx.navigation.fragment.NavHostFragment +import androidx.navigation.navArgs +import com.google.android.material.color.MaterialColors +import org.sudachi.sudachi_emu.NativeLibrary +import java.io.IOException +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.databinding.ActivitySettingsBinding +import org.sudachi.sudachi_emu.features.input.NativeInput +import org.sudachi.sudachi_emu.features.settings.utils.SettingsFile +import org.sudachi.sudachi_emu.fragments.ResetSettingsDialogFragment +import org.sudachi.sudachi_emu.utils.* + +class SettingsActivity : AppCompatActivity() { + private lateinit var binding: ActivitySettingsBinding + + private val args by navArgs() + + private val settingsViewModel: SettingsViewModel by viewModels() + + override fun onCreate(savedInstanceState: Bundle?) { + ThemeHelper.setTheme(this) + + super.onCreate(savedInstanceState) + + binding = ActivitySettingsBinding.inflate(layoutInflater) + setContentView(binding.root) + + if (!NativeConfig.isPerGameConfigLoaded() && args.game != null) { + SettingsFile.loadCustomConfig(args.game!!) + } + settingsViewModel.game = args.game + + val navHostFragment = + supportFragmentManager.findFragmentById(R.id.fragment_container) as NavHostFragment + navHostFragment.navController.setGraph(R.navigation.settings_navigation, intent.extras) + + WindowCompat.setDecorFitsSystemWindows(window, false) + + if (InsetsHelper.getSystemGestureType(applicationContext) != + InsetsHelper.GESTURE_NAVIGATION + ) { + binding.navigationBarShade.setBackgroundColor( + ThemeHelper.getColorWithOpacity( + MaterialColors.getColor( + binding.navigationBarShade, + com.google.android.material.R.attr.colorSurface + ), + ThemeHelper.SYSTEM_BAR_ALPHA + ) + ) + } + + settingsViewModel.shouldRecreate.collect( + this, + resetState = { settingsViewModel.setShouldRecreate(false) } + ) { if (it) recreate() } + settingsViewModel.shouldNavigateBack.collect( + this, + resetState = { settingsViewModel.setShouldNavigateBack(false) } + ) { if (it) navigateBack() } + settingsViewModel.shouldShowResetSettingsDialog.collect( + this, + resetState = { settingsViewModel.setShouldShowResetSettingsDialog(false) } + ) { + if (it) { + ResetSettingsDialogFragment().show( + supportFragmentManager, + ResetSettingsDialogFragment.TAG + ) + } + } + + onBackPressedDispatcher.addCallback( + this, + object : OnBackPressedCallback(true) { + override fun handleOnBackPressed() = navigateBack() + } + ) + + setInsets() + } + + fun navigateBack() { + val navHostFragment = + supportFragmentManager.findFragmentById(R.id.fragment_container) as NavHostFragment + if (navHostFragment.childFragmentManager.backStackEntryCount > 0) { + navHostFragment.navController.popBackStack() + } else { + finish() + } + } + + override fun onStart() { + super.onStart() + if (!DirectoryInitialization.areDirectoriesReady) { + DirectoryInitialization.start() + } + } + + override fun onStop() { + super.onStop() + Log.info("[SettingsActivity] Settings activity stopping. Saving settings to INI...") + if (isFinishing) { + NativeInput.reloadInputDevices() + NativeLibrary.applySettings() + if (args.game == null) { + NativeConfig.saveGlobalConfig() + } else if (NativeConfig.isPerGameConfigLoaded()) { + NativeLibrary.logSettings() + NativeConfig.savePerGameConfig() + NativeConfig.unloadPerGameConfig() + } + } + } + + fun onSettingsReset() { + // Delete settings file because the user may have changed values that do not exist in the UI + if (args.game == null) { + NativeConfig.unloadGlobalConfig() + val settingsFile = SettingsFile.getSettingsFile(SettingsFile.FILE_NAME_CONFIG) + if (!settingsFile.delete()) { + throw IOException("Failed to delete $settingsFile") + } + NativeConfig.initializeGlobalConfig() + } else { + NativeConfig.unloadPerGameConfig() + val settingsFile = SettingsFile.getCustomSettingsFile(args.game!!) + if (!settingsFile.delete()) { + throw IOException("Failed to delete $settingsFile") + } + } + + Toast.makeText( + applicationContext, + getString(R.string.settings_reset), + Toast.LENGTH_LONG + ).show() + finish() + } + + private fun setInsets() { + ViewCompat.setOnApplyWindowInsetsListener( + binding.navigationBarShade + ) { _: View, windowInsets: WindowInsetsCompat -> + val barInsets = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars()) + + // The only situation where we care to have a nav bar shade is when it's at the bottom + // of the screen where scrolling list elements can go behind it. + val mlpNavShade = binding.navigationBarShade.layoutParams as MarginLayoutParams + mlpNavShade.height = barInsets.bottom + binding.navigationBarShade.layoutParams = mlpNavShade + + windowInsets + } + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/SettingsAdapter.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/SettingsAdapter.kt new file mode 100644 index 0000000..e1b172e --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/SettingsAdapter.kt @@ -0,0 +1,434 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.settings.ui + +import android.content.Context +import android.icu.util.Calendar +import android.icu.util.TimeZone +import android.text.format.DateFormat +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.PopupMenu +import androidx.fragment.app.Fragment +import androidx.lifecycle.ViewModelProvider +import androidx.navigation.findNavController +import androidx.recyclerview.widget.AsyncDifferConfig +import androidx.recyclerview.widget.DiffUtil +import androidx.recyclerview.widget.ListAdapter +import com.google.android.material.datepicker.MaterialDatePicker +import com.google.android.material.timepicker.MaterialTimePicker +import com.google.android.material.timepicker.TimeFormat +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.SettingsNavigationDirections +import org.sudachi.sudachi_emu.databinding.ListItemSettingBinding +import org.sudachi.sudachi_emu.databinding.ListItemSettingInputBinding +import org.sudachi.sudachi_emu.databinding.ListItemSettingSwitchBinding +import org.sudachi.sudachi_emu.databinding.ListItemSettingsHeaderBinding +import org.sudachi.sudachi_emu.features.input.NativeInput +import org.sudachi.sudachi_emu.features.input.model.AnalogDirection +import org.sudachi.sudachi_emu.features.settings.model.AbstractIntSetting +import org.sudachi.sudachi_emu.features.settings.model.view.* +import org.sudachi.sudachi_emu.features.settings.ui.viewholder.* +import org.sudachi.sudachi_emu.utils.ParamPackage + +class SettingsAdapter( + private val fragment: Fragment, + private val context: Context +) : ListAdapter( + AsyncDifferConfig.Builder(DiffCallback()).build() +) { + private val settingsViewModel: SettingsViewModel + get() = ViewModelProvider(fragment.requireActivity())[SettingsViewModel::class.java] + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SettingViewHolder { + val inflater = LayoutInflater.from(parent.context) + return when (viewType) { + SettingsItem.TYPE_HEADER -> { + HeaderViewHolder(ListItemSettingsHeaderBinding.inflate(inflater), this) + } + + SettingsItem.TYPE_SWITCH -> { + SwitchSettingViewHolder(ListItemSettingSwitchBinding.inflate(inflater), this) + } + + SettingsItem.TYPE_SINGLE_CHOICE, SettingsItem.TYPE_STRING_SINGLE_CHOICE -> { + SingleChoiceViewHolder(ListItemSettingBinding.inflate(inflater), this) + } + + SettingsItem.TYPE_SLIDER -> { + SliderViewHolder(ListItemSettingBinding.inflate(inflater), this) + } + + SettingsItem.TYPE_SUBMENU -> { + SubmenuViewHolder(ListItemSettingBinding.inflate(inflater), this) + } + + SettingsItem.TYPE_DATETIME_SETTING -> { + DateTimeViewHolder(ListItemSettingBinding.inflate(inflater), this) + } + + SettingsItem.TYPE_RUNNABLE -> { + RunnableViewHolder(ListItemSettingBinding.inflate(inflater), this) + } + + SettingsItem.TYPE_INPUT -> { + InputViewHolder(ListItemSettingInputBinding.inflate(inflater), this) + } + + SettingsItem.TYPE_INT_SINGLE_CHOICE -> { + SingleChoiceViewHolder(ListItemSettingBinding.inflate(inflater), this) + } + + SettingsItem.TYPE_INPUT_PROFILE -> { + InputProfileViewHolder(ListItemSettingBinding.inflate(inflater), this) + } + + SettingsItem.TYPE_STRING_INPUT -> { + StringInputViewHolder(ListItemSettingBinding.inflate(inflater), this) + } + + else -> { + HeaderViewHolder(ListItemSettingsHeaderBinding.inflate(inflater), this) + } + } + } + + override fun onBindViewHolder(holder: SettingViewHolder, position: Int) { + holder.bind(currentList[position]) + } + + override fun getItemCount(): Int = currentList.size + + override fun getItemViewType(position: Int): Int { + return currentList[position].type + } + + fun onBooleanClick(item: SwitchSetting, checked: Boolean, position: Int) { + item.setChecked(checked) + notifyItemChanged(position) + settingsViewModel.setShouldReloadSettingsList(true) + } + + fun onSingleChoiceClick(item: SingleChoiceSetting, position: Int) { + SettingsDialogFragment.newInstance( + settingsViewModel, + item, + SettingsItem.TYPE_SINGLE_CHOICE, + position + ).show(fragment.childFragmentManager, SettingsDialogFragment.TAG) + } + + fun onStringSingleChoiceClick(item: StringSingleChoiceSetting, position: Int) { + SettingsDialogFragment.newInstance( + settingsViewModel, + item, + SettingsItem.TYPE_STRING_SINGLE_CHOICE, + position + ).show(fragment.childFragmentManager, SettingsDialogFragment.TAG) + } + + fun onIntSingleChoiceClick(item: IntSingleChoiceSetting, position: Int) { + SettingsDialogFragment.newInstance( + settingsViewModel, + item, + SettingsItem.TYPE_INT_SINGLE_CHOICE, + position + ).show(fragment.childFragmentManager, SettingsDialogFragment.TAG) + } + + fun onDateTimeClick(item: DateTimeSetting, position: Int) { + val storedTime = item.getValue() * 1000 + + // Helper to extract hour and minute from epoch time + val calendar: Calendar = Calendar.getInstance() + calendar.timeInMillis = storedTime + calendar.timeZone = TimeZone.getTimeZone("UTC") + + var timeFormat: Int = TimeFormat.CLOCK_12H + if (DateFormat.is24HourFormat(context)) { + timeFormat = TimeFormat.CLOCK_24H + } + + val datePicker: MaterialDatePicker = MaterialDatePicker.Builder.datePicker() + .setSelection(storedTime) + .setTitleText(R.string.select_rtc_date) + .build() + val timePicker: MaterialTimePicker = MaterialTimePicker.Builder() + .setTimeFormat(timeFormat) + .setHour(calendar.get(Calendar.HOUR_OF_DAY)) + .setMinute(calendar.get(Calendar.MINUTE)) + .setTitleText(R.string.select_rtc_time) + .build() + + datePicker.addOnPositiveButtonClickListener { + timePicker.show( + fragment.childFragmentManager, + "TimePicker" + ) + } + timePicker.addOnPositiveButtonClickListener { + var epochTime: Long = datePicker.selection!! / 1000 + epochTime += timePicker.hour.toLong() * 60 * 60 + epochTime += timePicker.minute.toLong() * 60 + if (item.getValue() != epochTime) { + notifyItemChanged(position) + item.setValue(epochTime) + } + } + datePicker.show( + fragment.childFragmentManager, + "DatePicker" + ) + } + + fun onSliderClick(item: SliderSetting, position: Int) { + SettingsDialogFragment.newInstance( + settingsViewModel, + item, + SettingsItem.TYPE_SLIDER, + position + ).show(fragment.childFragmentManager, SettingsDialogFragment.TAG) + } + + fun onSubmenuClick(item: SubmenuSetting) { + val action = SettingsNavigationDirections.actionGlobalSettingsFragment(item.menuKey, null) + fragment.view?.findNavController()?.navigate(action) + } + + fun onInputProfileClick(item: InputProfileSetting, position: Int) { + InputProfileDialogFragment.newInstance( + settingsViewModel, + item, + position + ).show(fragment.childFragmentManager, InputProfileDialogFragment.TAG) + } + + fun onInputClick(item: InputSetting, position: Int) { + InputDialogFragment.newInstance( + settingsViewModel, + item, + position + ).show(fragment.childFragmentManager, InputDialogFragment.TAG) + } + + fun onInputOptionsClick(anchor: View, item: InputSetting, position: Int) { + val popup = PopupMenu(context, anchor) + popup.menuInflater.inflate(R.menu.menu_input_options, popup.menu) + + popup.menu.apply { + val invertAxis = findItem(R.id.invert_axis) + val invertButton = findItem(R.id.invert_button) + val toggleButton = findItem(R.id.toggle_button) + val turboButton = findItem(R.id.turbo_button) + val setThreshold = findItem(R.id.set_threshold) + val toggleAxis = findItem(R.id.toggle_axis) + when (item) { + is AnalogInputSetting -> { + val params = NativeInput.getStickParam(item.playerIndex, item.nativeAnalog) + + invertAxis.isVisible = true + invertAxis.isCheckable = true + invertAxis.isChecked = when (item.analogDirection) { + AnalogDirection.Left, AnalogDirection.Right -> { + params.get("invert_x", "+") == "-" + } + + AnalogDirection.Up, AnalogDirection.Down -> { + params.get("invert_y", "+") == "-" + } + } + invertAxis.setOnMenuItemClickListener { + if (item.analogDirection == AnalogDirection.Left || + item.analogDirection == AnalogDirection.Right + ) { + val invertValue = params.get("invert_x", "+") == "-" + val invertString = if (invertValue) "+" else "-" + params.set("invert_x", invertString) + } else if ( + item.analogDirection == AnalogDirection.Up || + item.analogDirection == AnalogDirection.Down + ) { + val invertValue = params.get("invert_y", "+") == "-" + val invertString = if (invertValue) "+" else "-" + params.set("invert_y", invertString) + } + true + } + + popup.setOnDismissListener { + NativeInput.setStickParam(item.playerIndex, item.nativeAnalog, params) + settingsViewModel.setDatasetChanged(true) + } + } + + is ButtonInputSetting -> { + val params = NativeInput.getButtonParam(item.playerIndex, item.nativeButton) + if (params.has("code") || params.has("button") || params.has("hat")) { + val buttonInvert = params.get("inverted", false) + invertButton.isVisible = true + invertButton.isCheckable = true + invertButton.isChecked = buttonInvert + invertButton.setOnMenuItemClickListener { + params.set("inverted", !buttonInvert) + true + } + + val toggle = params.get("toggle", false) + toggleButton.isVisible = true + toggleButton.isCheckable = true + toggleButton.isChecked = toggle + toggleButton.setOnMenuItemClickListener { + params.set("toggle", !toggle) + true + } + + val turbo = params.get("turbo", false) + turboButton.isVisible = true + turboButton.isCheckable = true + turboButton.isChecked = turbo + turboButton.setOnMenuItemClickListener { + params.set("turbo", !turbo) + true + } + } else if (params.has("axis")) { + val axisInvert = params.get("invert", "+") == "-" + invertAxis.isVisible = true + invertAxis.isCheckable = true + invertAxis.isChecked = axisInvert + invertAxis.setOnMenuItemClickListener { + params.set("invert", if (!axisInvert) "-" else "+") + true + } + + val buttonInvert = params.get("inverted", false) + invertButton.isVisible = true + invertButton.isCheckable = true + invertButton.isChecked = buttonInvert + invertButton.setOnMenuItemClickListener { + params.set("inverted", !buttonInvert) + true + } + + setThreshold.isVisible = true + val thresholdSetting = object : AbstractIntSetting { + override val key = "" + + override fun getInt(needsGlobal: Boolean): Int = + (params.get("threshold", 0.5f) * 100).toInt() + + override fun setInt(value: Int) { + params.set("threshold", value.toFloat() / 100) + NativeInput.setButtonParam( + item.playerIndex, + item.nativeButton, + params + ) + } + + override val defaultValue = 50 + + override fun getValueAsString(needsGlobal: Boolean): String = + getInt(needsGlobal).toString() + + override fun reset() = setInt(defaultValue) + } + setThreshold.setOnMenuItemClickListener { + onSliderClick( + SliderSetting(thresholdSetting, R.string.set_threshold), + position + ) + true + } + + val axisToggle = params.get("toggle", false) + toggleAxis.isVisible = true + toggleAxis.isCheckable = true + toggleAxis.isChecked = axisToggle + toggleAxis.setOnMenuItemClickListener { + params.set("toggle", !axisToggle) + true + } + } + + popup.setOnDismissListener { + NativeInput.setButtonParam(item.playerIndex, item.nativeButton, params) + settingsViewModel.setAdapterItemChanged(position) + } + } + + is ModifierInputSetting -> { + val stickParams = NativeInput.getStickParam(item.playerIndex, item.nativeAnalog) + val modifierParams = ParamPackage(stickParams.get("modifier", "")) + + val invert = modifierParams.get("inverted", false) + invertButton.isVisible = true + invertButton.isCheckable = true + invertButton.isChecked = invert + invertButton.setOnMenuItemClickListener { + modifierParams.set("inverted", !invert) + stickParams.set("modifier", modifierParams.serialize()) + true + } + + val toggle = modifierParams.get("toggle", false) + toggleButton.isVisible = true + toggleButton.isCheckable = true + toggleButton.isChecked = toggle + toggleButton.setOnMenuItemClickListener { + modifierParams.set("toggle", !toggle) + stickParams.set("modifier", modifierParams.serialize()) + true + } + + popup.setOnDismissListener { + NativeInput.setStickParam( + item.playerIndex, + item.nativeAnalog, + stickParams + ) + settingsViewModel.setAdapterItemChanged(position) + } + } + } + } + popup.show() + } + + fun onStringInputClick(item: StringInputSetting, position: Int) { + SettingsDialogFragment.newInstance( + settingsViewModel, + item, + SettingsItem.TYPE_STRING_INPUT, + position + ).show(fragment.childFragmentManager, SettingsDialogFragment.TAG) + } + + fun onLongClick(item: SettingsItem, position: Int): Boolean { + SettingsDialogFragment.newInstance( + settingsViewModel, + item, + SettingsDialogFragment.TYPE_RESET_SETTING, + position + ).show(fragment.childFragmentManager, SettingsDialogFragment.TAG) + + return true + } + + fun onClearClick(item: SettingsItem, position: Int) { + item.setting.global = true + notifyItemChanged(position) + settingsViewModel.setShouldReloadSettingsList(true) + } + + private class DiffCallback : DiffUtil.ItemCallback() { + override fun areItemsTheSame(oldItem: SettingsItem, newItem: SettingsItem): Boolean { + return oldItem.setting.key == newItem.setting.key + } + + override fun areContentsTheSame(oldItem: SettingsItem, newItem: SettingsItem): Boolean { + return oldItem.setting.key == newItem.setting.key + } + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/SettingsDialogFragment.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/SettingsDialogFragment.kt new file mode 100644 index 0000000..5cc66d2 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/SettingsDialogFragment.kt @@ -0,0 +1,301 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.settings.ui + +import android.app.Dialog +import android.content.DialogInterface +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.fragment.app.DialogFragment +import androidx.fragment.app.activityViewModels +import com.google.android.material.dialog.MaterialAlertDialogBuilder +import com.google.android.material.slider.Slider +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.databinding.DialogEditTextBinding +import org.sudachi.sudachi_emu.databinding.DialogSliderBinding +import org.sudachi.sudachi_emu.features.input.NativeInput +import org.sudachi.sudachi_emu.features.input.model.AnalogDirection +import org.sudachi.sudachi_emu.features.settings.model.view.AnalogInputSetting +import org.sudachi.sudachi_emu.features.settings.model.view.ButtonInputSetting +import org.sudachi.sudachi_emu.features.settings.model.view.IntSingleChoiceSetting +import org.sudachi.sudachi_emu.features.settings.model.view.SettingsItem +import org.sudachi.sudachi_emu.features.settings.model.view.SingleChoiceSetting +import org.sudachi.sudachi_emu.features.settings.model.view.SliderSetting +import org.sudachi.sudachi_emu.features.settings.model.view.StringInputSetting +import org.sudachi.sudachi_emu.features.settings.model.view.StringSingleChoiceSetting +import org.sudachi.sudachi_emu.utils.ParamPackage +import org.sudachi.sudachi_emu.utils.collect + +class SettingsDialogFragment : DialogFragment(), DialogInterface.OnClickListener { + private var type = 0 + private var position = 0 + + private var defaultCancelListener = + DialogInterface.OnClickListener { _: DialogInterface?, _: Int -> closeDialog() } + + private val settingsViewModel: SettingsViewModel by activityViewModels() + + private lateinit var sliderBinding: DialogSliderBinding + private lateinit var stringInputBinding: DialogEditTextBinding + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + type = requireArguments().getInt(TYPE) + position = requireArguments().getInt(POSITION) + + if (settingsViewModel.clickedItem == null) dismiss() + } + + override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { + return when (type) { + TYPE_RESET_SETTING -> { + MaterialAlertDialogBuilder(requireContext()) + .setMessage(R.string.reset_setting_confirmation) + .setPositiveButton(android.R.string.ok) { _: DialogInterface, _: Int -> + when (val item = settingsViewModel.clickedItem) { + is AnalogInputSetting -> { + val stickParam = NativeInput.getStickParam( + item.playerIndex, + item.nativeAnalog + ) + if (stickParam.get("engine", "") == "analog_from_button") { + when (item.analogDirection) { + AnalogDirection.Up -> stickParam.erase("up") + AnalogDirection.Down -> stickParam.erase("down") + AnalogDirection.Left -> stickParam.erase("left") + AnalogDirection.Right -> stickParam.erase("right") + } + NativeInput.setStickParam( + item.playerIndex, + item.nativeAnalog, + stickParam + ) + settingsViewModel.setAdapterItemChanged(position) + } else { + NativeInput.setStickParam( + item.playerIndex, + item.nativeAnalog, + ParamPackage() + ) + settingsViewModel.setDatasetChanged(true) + } + } + + is ButtonInputSetting -> { + NativeInput.setButtonParam( + item.playerIndex, + item.nativeButton, + ParamPackage() + ) + settingsViewModel.setAdapterItemChanged(position) + } + + else -> { + settingsViewModel.clickedItem!!.setting.reset() + settingsViewModel.setAdapterItemChanged(position) + } + } + } + .setNegativeButton(android.R.string.cancel, null) + .create() + } + + SettingsItem.TYPE_SINGLE_CHOICE -> { + val item = settingsViewModel.clickedItem as SingleChoiceSetting + val value = getSelectionForSingleChoiceValue(item) + MaterialAlertDialogBuilder(requireContext()) + .setTitle(item.title) + .setSingleChoiceItems(item.choicesId, value, this) + .create() + } + + SettingsItem.TYPE_SLIDER -> { + sliderBinding = DialogSliderBinding.inflate(layoutInflater) + val item = settingsViewModel.clickedItem as SliderSetting + + settingsViewModel.setSliderTextValue(item.getSelectedValue().toFloat(), item.units) + sliderBinding.slider.apply { + valueFrom = item.min.toFloat() + valueTo = item.max.toFloat() + value = settingsViewModel.sliderProgress.value.toFloat() + addOnChangeListener { _: Slider, value: Float, _: Boolean -> + settingsViewModel.setSliderTextValue(value, item.units) + } + } + + MaterialAlertDialogBuilder(requireContext()) + .setTitle(item.title) + .setView(sliderBinding.root) + .setPositiveButton(android.R.string.ok, this) + .setNegativeButton(android.R.string.cancel, defaultCancelListener) + .create() + } + + SettingsItem.TYPE_STRING_INPUT -> { + stringInputBinding = DialogEditTextBinding.inflate(layoutInflater) + val item = settingsViewModel.clickedItem as StringInputSetting + stringInputBinding.editText.setText(item.getSelectedValue()) + MaterialAlertDialogBuilder(requireContext()) + .setTitle(item.title) + .setView(stringInputBinding.root) + .setPositiveButton(android.R.string.ok, this) + .setNegativeButton(android.R.string.cancel, defaultCancelListener) + .create() + } + + SettingsItem.TYPE_STRING_SINGLE_CHOICE -> { + val item = settingsViewModel.clickedItem as StringSingleChoiceSetting + MaterialAlertDialogBuilder(requireContext()) + .setTitle(item.title) + .setSingleChoiceItems(item.choices, item.selectedValueIndex, this) + .create() + } + + SettingsItem.TYPE_INT_SINGLE_CHOICE -> { + val item = settingsViewModel.clickedItem as IntSingleChoiceSetting + MaterialAlertDialogBuilder(requireContext()) + .setTitle(item.title) + .setSingleChoiceItems(item.choices, item.selectedValueIndex, this) + .create() + } + + else -> super.onCreateDialog(savedInstanceState) + } + } + + override fun onCreateView( + inflater: LayoutInflater, + container: ViewGroup?, + savedInstanceState: Bundle? + ): View? { + return when (type) { + SettingsItem.TYPE_SLIDER -> sliderBinding.root + SettingsItem.TYPE_STRING_INPUT -> stringInputBinding.root + else -> super.onCreateView(inflater, container, savedInstanceState) + } + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + when (type) { + SettingsItem.TYPE_SLIDER -> { + settingsViewModel.sliderTextValue.collect(viewLifecycleOwner) { + sliderBinding.textValue.text = it + } + settingsViewModel.sliderProgress.collect(viewLifecycleOwner) { + sliderBinding.slider.value = it.toFloat() + } + } + } + } + + override fun onClick(dialog: DialogInterface, which: Int) { + when (settingsViewModel.clickedItem) { + is SingleChoiceSetting -> { + val scSetting = settingsViewModel.clickedItem as SingleChoiceSetting + val value = getValueForSingleChoiceSelection(scSetting, which) + scSetting.setSelectedValue(value) + } + + is StringSingleChoiceSetting -> { + val scSetting = settingsViewModel.clickedItem as StringSingleChoiceSetting + val value = scSetting.getValueAt(which) + scSetting.setSelectedValue(value) + } + + is IntSingleChoiceSetting -> { + val scSetting = settingsViewModel.clickedItem as IntSingleChoiceSetting + val value = scSetting.getValueAt(which) + scSetting.setSelectedValue(value) + } + + is SliderSetting -> { + val sliderSetting = settingsViewModel.clickedItem as SliderSetting + sliderSetting.setSelectedValue(settingsViewModel.sliderProgress.value) + } + + is StringInputSetting -> { + val stringInputSetting = settingsViewModel.clickedItem as StringInputSetting + stringInputSetting.setSelectedValue( + (stringInputBinding.editText.text ?: "").toString() + ) + } + } + closeDialog() + } + + private fun closeDialog() { + settingsViewModel.setAdapterItemChanged(position) + settingsViewModel.clickedItem = null + settingsViewModel.setSliderProgress(-1f) + dismiss() + } + + private fun getValueForSingleChoiceSelection(item: SingleChoiceSetting, which: Int): Int { + val valuesId = item.valuesId + return if (valuesId > 0) { + val valuesArray = requireContext().resources.getIntArray(valuesId) + valuesArray[which] + } else { + which + } + } + + private fun getSelectionForSingleChoiceValue(item: SingleChoiceSetting): Int { + val value = item.getSelectedValue() + val valuesId = item.valuesId + if (valuesId > 0) { + val valuesArray = requireContext().resources.getIntArray(valuesId) + for (index in valuesArray.indices) { + val current = valuesArray[index] + if (current == value) { + return index + } + } + } else { + return value + } + return -1 + } + + companion object { + const val TAG = "SettingsDialogFragment" + + const val TYPE_RESET_SETTING = -1 + + const val TITLE = "Title" + const val TYPE = "Type" + const val POSITION = "Position" + + fun newInstance( + settingsViewModel: SettingsViewModel, + clickedItem: SettingsItem, + type: Int, + position: Int + ): SettingsDialogFragment { + when (type) { + SettingsItem.TYPE_HEADER, + SettingsItem.TYPE_SWITCH, + SettingsItem.TYPE_SUBMENU, + SettingsItem.TYPE_DATETIME_SETTING, + SettingsItem.TYPE_RUNNABLE -> + throw IllegalArgumentException("[SettingsDialogFragment] Incompatible type!") + + SettingsItem.TYPE_SLIDER -> settingsViewModel.setSliderProgress( + (clickedItem as SliderSetting).getSelectedValue().toFloat() + ) + } + settingsViewModel.clickedItem = clickedItem + + val args = Bundle() + args.putInt(TYPE, type) + args.putInt(POSITION, position) + val fragment = SettingsDialogFragment() + fragment.arguments = args + return fragment + } + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/SettingsFragment.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/SettingsFragment.kt new file mode 100644 index 0000000..b1dde26 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/SettingsFragment.kt @@ -0,0 +1,182 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.settings.ui + +import android.annotation.SuppressLint +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.core.view.ViewCompat +import androidx.core.view.WindowInsetsCompat +import androidx.core.view.updatePadding +import androidx.fragment.app.Fragment +import androidx.fragment.app.activityViewModels +import androidx.navigation.findNavController +import androidx.navigation.fragment.navArgs +import androidx.recyclerview.widget.LinearLayoutManager +import com.google.android.material.transition.MaterialSharedAxis +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.databinding.FragmentSettingsBinding +import org.sudachi.sudachi_emu.features.input.NativeInput +import org.sudachi.sudachi_emu.features.settings.model.Settings +import org.sudachi.sudachi_emu.fragments.MessageDialogFragment +import org.sudachi.sudachi_emu.utils.ViewUtils.updateMargins +import org.sudachi.sudachi_emu.utils.collect + +class SettingsFragment : Fragment() { + private lateinit var presenter: SettingsFragmentPresenter + private var settingsAdapter: SettingsAdapter? = null + + private var _binding: FragmentSettingsBinding? = null + private val binding get() = _binding!! + + private val args by navArgs() + + private val settingsViewModel: SettingsViewModel by activityViewModels() + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + enterTransition = MaterialSharedAxis(MaterialSharedAxis.X, true) + returnTransition = MaterialSharedAxis(MaterialSharedAxis.X, false) + reenterTransition = MaterialSharedAxis(MaterialSharedAxis.X, false) + exitTransition = MaterialSharedAxis(MaterialSharedAxis.X, true) + + val playerIndex = getPlayerIndex() + if (playerIndex != -1) { + NativeInput.loadInputProfiles() + NativeInput.reloadInputDevices() + } + } + + override fun onCreateView( + inflater: LayoutInflater, + container: ViewGroup?, + savedInstanceState: Bundle? + ): View { + _binding = FragmentSettingsBinding.inflate(layoutInflater) + return binding.root + } + + @SuppressLint("NotifyDataSetChanged") + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + settingsAdapter = SettingsAdapter(this, requireContext()) + presenter = SettingsFragmentPresenter( + settingsViewModel, + settingsAdapter!!, + args.menuTag + ) + + binding.toolbarSettingsLayout.title = if (args.menuTag == Settings.MenuTag.SECTION_ROOT && + args.game != null + ) { + args.game!!.title + } else { + when (args.menuTag) { + Settings.MenuTag.SECTION_INPUT_PLAYER_ONE -> Settings.getPlayerString(1) + Settings.MenuTag.SECTION_INPUT_PLAYER_TWO -> Settings.getPlayerString(2) + Settings.MenuTag.SECTION_INPUT_PLAYER_THREE -> Settings.getPlayerString(3) + Settings.MenuTag.SECTION_INPUT_PLAYER_FOUR -> Settings.getPlayerString(4) + Settings.MenuTag.SECTION_INPUT_PLAYER_FIVE -> Settings.getPlayerString(5) + Settings.MenuTag.SECTION_INPUT_PLAYER_SIX -> Settings.getPlayerString(6) + Settings.MenuTag.SECTION_INPUT_PLAYER_SEVEN -> Settings.getPlayerString(7) + Settings.MenuTag.SECTION_INPUT_PLAYER_EIGHT -> Settings.getPlayerString(8) + else -> getString(args.menuTag.titleId) + } + } + binding.listSettings.apply { + adapter = settingsAdapter + layoutManager = LinearLayoutManager(requireContext()) + } + + binding.toolbarSettings.setNavigationOnClickListener { + settingsViewModel.setShouldNavigateBack(true) + } + + settingsViewModel.shouldReloadSettingsList.collect( + viewLifecycleOwner, + resetState = { settingsViewModel.setShouldReloadSettingsList(false) } + ) { if (it) presenter.loadSettingsList() } + settingsViewModel.adapterItemChanged.collect( + viewLifecycleOwner, + resetState = { settingsViewModel.setAdapterItemChanged(-1) } + ) { if (it != -1) settingsAdapter?.notifyItemChanged(it) } + settingsViewModel.datasetChanged.collect( + viewLifecycleOwner, + resetState = { settingsViewModel.setDatasetChanged(false) } + ) { if (it) settingsAdapter?.notifyDataSetChanged() } + settingsViewModel.reloadListAndNotifyDataset.collect( + viewLifecycleOwner, + resetState = { settingsViewModel.setReloadListAndNotifyDataset(false) } + ) { if (it) presenter.loadSettingsList(true) } + settingsViewModel.shouldShowResetInputDialog.collect( + viewLifecycleOwner, + resetState = { settingsViewModel.setShouldShowResetInputDialog(false) } + ) { + if (it) { + MessageDialogFragment.newInstance( + activity = requireActivity(), + titleId = R.string.reset_mapping, + descriptionId = R.string.reset_mapping_description, + positiveAction = { + NativeInput.resetControllerMappings(getPlayerIndex()) + settingsViewModel.setReloadListAndNotifyDataset(true) + }, + negativeAction = {} + ).show(parentFragmentManager, MessageDialogFragment.TAG) + } + } + + if (args.menuTag == Settings.MenuTag.SECTION_ROOT) { + binding.toolbarSettings.inflateMenu(R.menu.menu_settings) + binding.toolbarSettings.setOnMenuItemClickListener { + when (it.itemId) { + R.id.action_search -> { + view.findNavController() + .navigate(R.id.action_settingsFragment_to_settingsSearchFragment) + true + } + + else -> false + } + } + } + + presenter.onViewCreated() + + setInsets() + } + + private fun getPlayerIndex(): Int = + when (args.menuTag) { + Settings.MenuTag.SECTION_INPUT_PLAYER_ONE -> 0 + Settings.MenuTag.SECTION_INPUT_PLAYER_TWO -> 1 + Settings.MenuTag.SECTION_INPUT_PLAYER_THREE -> 2 + Settings.MenuTag.SECTION_INPUT_PLAYER_FOUR -> 3 + Settings.MenuTag.SECTION_INPUT_PLAYER_FIVE -> 4 + Settings.MenuTag.SECTION_INPUT_PLAYER_SIX -> 5 + Settings.MenuTag.SECTION_INPUT_PLAYER_SEVEN -> 6 + Settings.MenuTag.SECTION_INPUT_PLAYER_EIGHT -> 7 + else -> -1 + } + + private fun setInsets() { + ViewCompat.setOnApplyWindowInsetsListener( + binding.root + ) { _: View, windowInsets: WindowInsetsCompat -> + val barInsets = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars()) + val cutoutInsets = windowInsets.getInsets(WindowInsetsCompat.Type.displayCutout()) + + val leftInsets = barInsets.left + cutoutInsets.left + val rightInsets = barInsets.right + cutoutInsets.right + + binding.listSettings.updateMargins(left = leftInsets, right = rightInsets) + binding.listSettings.updatePadding(bottom = barInsets.bottom) + + binding.appbarSettings.updateMargins(left = leftInsets, right = rightInsets) + windowInsets + } + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/SettingsFragmentPresenter.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/SettingsFragmentPresenter.kt new file mode 100644 index 0000000..725fe74 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/SettingsFragmentPresenter.kt @@ -0,0 +1,975 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.settings.ui + +import android.annotation.SuppressLint +import android.os.Build +import android.widget.Toast +import org.sudachi.sudachi_emu.NativeLibrary +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.SudachiApplication +import org.sudachi.sudachi_emu.features.input.NativeInput +import org.sudachi.sudachi_emu.features.input.model.AnalogDirection +import org.sudachi.sudachi_emu.features.input.model.NativeAnalog +import org.sudachi.sudachi_emu.features.input.model.NativeButton +import org.sudachi.sudachi_emu.features.input.model.NpadStyleIndex +import org.sudachi.sudachi_emu.features.settings.model.AbstractBooleanSetting +import org.sudachi.sudachi_emu.features.settings.model.AbstractIntSetting +import org.sudachi.sudachi_emu.features.settings.model.BooleanSetting +import org.sudachi.sudachi_emu.features.settings.model.ByteSetting +import org.sudachi.sudachi_emu.features.settings.model.IntSetting +import org.sudachi.sudachi_emu.features.settings.model.LongSetting +import org.sudachi.sudachi_emu.features.settings.model.Settings +import org.sudachi.sudachi_emu.features.settings.model.Settings.MenuTag +import org.sudachi.sudachi_emu.features.settings.model.ShortSetting +import org.sudachi.sudachi_emu.features.settings.model.StringSetting +import org.sudachi.sudachi_emu.features.settings.model.view.* +import org.sudachi.sudachi_emu.utils.InputHandler +import org.sudachi.sudachi_emu.utils.NativeConfig + +class SettingsFragmentPresenter( + private val settingsViewModel: SettingsViewModel, + private val adapter: SettingsAdapter, + private var menuTag: MenuTag +) { + private var settingsList = ArrayList() + + private val context get() = SudachiApplication.appContext + + // Extension for altering settings list based on each setting's properties + fun ArrayList.add(key: String) { + val item = SettingsItem.settingsItems[key]!! + if (settingsViewModel.game != null && !item.setting.isSwitchable) { + return + } + + if (!NativeConfig.isPerGameConfigLoaded() && !NativeLibrary.isRunning()) { + item.setting.global = true + } + + val pairedSettingKey = item.setting.pairedSettingKey + if (pairedSettingKey.isNotEmpty()) { + val pairedSettingValue = NativeConfig.getBoolean( + pairedSettingKey, + if (NativeLibrary.isRunning() && !NativeConfig.isPerGameConfigLoaded()) { + !NativeConfig.usingGlobal(pairedSettingKey) + } else { + NativeConfig.usingGlobal(pairedSettingKey) + } + ) + if (!pairedSettingValue) return + } + add(item) + } + + // Allows you to show/hide abstract settings based on the paired setting key + fun ArrayList.addAbstract(item: SettingsItem) { + val pairedSettingKey = item.setting.pairedSettingKey + if (pairedSettingKey.isNotEmpty()) { + val pairedSettingsItem = + this.firstOrNull { it.setting.key == pairedSettingKey } ?: return + val pairedSetting = pairedSettingsItem.setting as AbstractBooleanSetting + if (!pairedSetting.getBoolean(!NativeConfig.isPerGameConfigLoaded())) return + } + add(item) + } + + fun onViewCreated() { + loadSettingsList() + } + + @SuppressLint("NotifyDataSetChanged") + fun loadSettingsList(notifyDataSetChanged: Boolean = false) { + val sl = ArrayList() + when (menuTag) { + MenuTag.SECTION_ROOT -> addConfigSettings(sl) + MenuTag.SECTION_SYSTEM -> addSystemSettings(sl) + MenuTag.SECTION_RENDERER -> addGraphicsSettings(sl) + MenuTag.SECTION_AUDIO -> addAudioSettings(sl) + MenuTag.SECTION_INPUT -> addInputSettings(sl) + MenuTag.SECTION_INPUT_PLAYER_ONE -> addInputPlayer(sl, 0) + MenuTag.SECTION_INPUT_PLAYER_TWO -> addInputPlayer(sl, 1) + MenuTag.SECTION_INPUT_PLAYER_THREE -> addInputPlayer(sl, 2) + MenuTag.SECTION_INPUT_PLAYER_FOUR -> addInputPlayer(sl, 3) + MenuTag.SECTION_INPUT_PLAYER_FIVE -> addInputPlayer(sl, 4) + MenuTag.SECTION_INPUT_PLAYER_SIX -> addInputPlayer(sl, 5) + MenuTag.SECTION_INPUT_PLAYER_SEVEN -> addInputPlayer(sl, 6) + MenuTag.SECTION_INPUT_PLAYER_EIGHT -> addInputPlayer(sl, 7) + MenuTag.SECTION_THEME -> addThemeSettings(sl) + MenuTag.SECTION_DEBUG -> addDebugSettings(sl) + } + settingsList = sl + adapter.submitList(settingsList) { + if (notifyDataSetChanged) { + adapter.notifyDataSetChanged() + } + } + } + + private fun addConfigSettings(sl: ArrayList) { + sl.apply { + add( + SubmenuSetting( + titleId = R.string.preferences_system, + descriptionId = R.string.preferences_system_description, + iconId = R.drawable.ic_system_settings, + menuKey = MenuTag.SECTION_SYSTEM + ) + ) + add( + SubmenuSetting( + titleId = R.string.preferences_graphics, + descriptionId = R.string.preferences_graphics_description, + iconId = R.drawable.ic_graphics, + menuKey = MenuTag.SECTION_RENDERER + ) + ) + add( + SubmenuSetting( + titleId = R.string.preferences_audio, + descriptionId = R.string.preferences_audio_description, + iconId = R.drawable.ic_audio, + menuKey = MenuTag.SECTION_AUDIO + ) + ) + add( + SubmenuSetting( + titleId = R.string.preferences_debug, + descriptionId = R.string.preferences_debug_description, + iconId = R.drawable.ic_code, + menuKey = MenuTag.SECTION_DEBUG + ) + ) + add( + RunnableSetting( + titleId = R.string.reset_to_default, + descriptionId = R.string.reset_to_default_description, + isRunnable = !NativeLibrary.isRunning(), + iconId = R.drawable.ic_restore + ) { settingsViewModel.setShouldShowResetSettingsDialog(true) } + ) + } + } + + private fun addSystemSettings(sl: ArrayList) { + sl.apply { + add(StringSetting.DEVICE_NAME.key) + add(BooleanSetting.RENDERER_USE_SPEED_LIMIT.key) + add(ShortSetting.RENDERER_SPEED_LIMIT.key) + add(BooleanSetting.USE_DOCKED_MODE.key) + add(IntSetting.REGION_INDEX.key) + add(IntSetting.LANGUAGE_INDEX.key) + add(BooleanSetting.USE_CUSTOM_RTC.key) + add(LongSetting.CUSTOM_RTC.key) + } + } + + private fun addGraphicsSettings(sl: ArrayList) { + sl.apply { + add(IntSetting.RENDERER_ACCURACY.key) + add(IntSetting.RENDERER_RESOLUTION.key) + add(IntSetting.RENDERER_VSYNC.key) + add(IntSetting.RENDERER_SCALING_FILTER.key) + add(IntSetting.FSR_SHARPENING_SLIDER.key) + add(IntSetting.RENDERER_ANTI_ALIASING.key) + add(IntSetting.MAX_ANISOTROPY.key) + add(IntSetting.RENDERER_SCREEN_LAYOUT.key) + add(IntSetting.RENDERER_ASPECT_RATIO.key) + add(IntSetting.VERTICAL_ALIGNMENT.key) + add(BooleanSetting.PICTURE_IN_PICTURE.key) + add(BooleanSetting.RENDERER_USE_DISK_SHADER_CACHE.key) + add(BooleanSetting.RENDERER_FORCE_MAX_CLOCK.key) + add(BooleanSetting.RENDERER_ASYNCHRONOUS_SHADERS.key) + add(BooleanSetting.RENDERER_REACTIVE_FLUSHING.key) + } + } + + private fun addAudioSettings(sl: ArrayList) { + sl.apply { + add(IntSetting.AUDIO_OUTPUT_ENGINE.key) + add(ByteSetting.AUDIO_VOLUME.key) + } + } + + private fun addInputSettings(sl: ArrayList) { + settingsViewModel.currentDevice = 0 + + if (NativeConfig.isPerGameConfigLoaded()) { + NativeInput.loadInputProfiles() + val profiles = NativeInput.getInputProfileNames().toMutableList() + profiles.add(0, "") + val prettyProfiles = profiles.toTypedArray() + prettyProfiles[0] = + context.getString(R.string.use_global_input_configuration) + sl.apply { + for (i in 0 until 8) { + add( + IntSingleChoiceSetting( + getPerGameProfileSetting(profiles, i), + titleString = getPlayerProfileString(i + 1), + choices = prettyProfiles, + values = IntArray(profiles.size) { it }.toTypedArray() + ) + ) + } + } + return + } + + val getConnectedIcon: (Int) -> Int = { playerIndex: Int -> + if (NativeInput.getIsConnected(playerIndex)) { + R.drawable.ic_controller + } else { + R.drawable.ic_controller_disconnected + } + } + + val inputSettings = NativeConfig.getInputSettings(true) + sl.apply { + add( + SubmenuSetting( + titleString = Settings.getPlayerString(1), + descriptionString = inputSettings[0].profileName, + menuKey = MenuTag.SECTION_INPUT_PLAYER_ONE, + iconId = getConnectedIcon(0) + ) + ) + add( + SubmenuSetting( + titleString = Settings.getPlayerString(2), + descriptionString = inputSettings[1].profileName, + menuKey = MenuTag.SECTION_INPUT_PLAYER_TWO, + iconId = getConnectedIcon(1) + ) + ) + add( + SubmenuSetting( + titleString = Settings.getPlayerString(3), + descriptionString = inputSettings[2].profileName, + menuKey = MenuTag.SECTION_INPUT_PLAYER_THREE, + iconId = getConnectedIcon(2) + ) + ) + add( + SubmenuSetting( + titleString = Settings.getPlayerString(4), + descriptionString = inputSettings[3].profileName, + menuKey = MenuTag.SECTION_INPUT_PLAYER_FOUR, + iconId = getConnectedIcon(3) + ) + ) + add( + SubmenuSetting( + titleString = Settings.getPlayerString(5), + descriptionString = inputSettings[4].profileName, + menuKey = MenuTag.SECTION_INPUT_PLAYER_FIVE, + iconId = getConnectedIcon(4) + ) + ) + add( + SubmenuSetting( + titleString = Settings.getPlayerString(6), + descriptionString = inputSettings[5].profileName, + menuKey = MenuTag.SECTION_INPUT_PLAYER_SIX, + iconId = getConnectedIcon(5) + ) + ) + add( + SubmenuSetting( + titleString = Settings.getPlayerString(7), + descriptionString = inputSettings[6].profileName, + menuKey = MenuTag.SECTION_INPUT_PLAYER_SEVEN, + iconId = getConnectedIcon(6) + ) + ) + add( + SubmenuSetting( + titleString = Settings.getPlayerString(8), + descriptionString = inputSettings[7].profileName, + menuKey = MenuTag.SECTION_INPUT_PLAYER_EIGHT, + iconId = getConnectedIcon(7) + ) + ) + } + } + + private fun getPlayerProfileString(player: Int): String = + context.getString(R.string.player_num_profile, player) + + private fun getPerGameProfileSetting( + profiles: List, + playerIndex: Int + ): AbstractIntSetting { + return object : AbstractIntSetting { + private val players + get() = NativeConfig.getInputSettings(false) + + override val key = "" + + override fun getInt(needsGlobal: Boolean): Int { + val currentProfile = players[playerIndex].profileName + profiles.forEachIndexed { i, profile -> + if (profile == currentProfile) { + return i + } + } + return 0 + } + + override fun setInt(value: Int) { + NativeInput.loadPerGameConfiguration(playerIndex, value, profiles[value]) + NativeInput.connectControllers(playerIndex) + NativeConfig.saveControlPlayerValues() + } + + override val defaultValue = 0 + + override fun getValueAsString(needsGlobal: Boolean): String = getInt().toString() + + override fun reset() = setInt(defaultValue) + + override var global = true + + override val isRuntimeModifiable = true + + override val isSaveable = true + } + } + + private fun addInputPlayer(sl: ArrayList, playerIndex: Int) { + sl.apply { + val connectedSetting = object : AbstractBooleanSetting { + override val key = "connected" + + override fun getBoolean(needsGlobal: Boolean): Boolean = + NativeInput.getIsConnected(playerIndex) + + override fun setBoolean(value: Boolean) = + NativeInput.connectControllers(playerIndex, value) + + override val defaultValue = playerIndex == 0 + + override fun getValueAsString(needsGlobal: Boolean): String = + getBoolean(needsGlobal).toString() + + override fun reset() = setBoolean(defaultValue) + } + add(SwitchSetting(connectedSetting, R.string.connected)) + + val styleTags = NativeInput.getSupportedStyleTags(playerIndex) + val npadType = object : AbstractIntSetting { + override val key = "npad_type" + override fun getInt(needsGlobal: Boolean): Int { + val styleIndex = NativeInput.getStyleIndex(playerIndex) + return styleTags.indexOfFirst { it == styleIndex } + } + + override fun setInt(value: Int) { + NativeInput.setStyleIndex(playerIndex, styleTags[value]) + settingsViewModel.setReloadListAndNotifyDataset(true) + } + + override val defaultValue = NpadStyleIndex.Fullkey.int + override fun getValueAsString(needsGlobal: Boolean): String = getInt().toString() + override fun reset() = setInt(defaultValue) + override val pairedSettingKey: String = "connected" + } + addAbstract( + IntSingleChoiceSetting( + npadType, + titleId = R.string.controller_type, + choices = styleTags.map { context.getString(it.nameId) } + .toTypedArray(), + values = IntArray(styleTags.size) { it }.toTypedArray() + ) + ) + + InputHandler.updateControllerData() + + val autoMappingSetting = object : AbstractIntSetting { + override val key = "auto_mapping_device" + + override fun getInt(needsGlobal: Boolean): Int = -1 + + override fun setInt(value: Int) { + val registeredController = InputHandler.registeredControllers[value + 1] + val displayName = registeredController.get( + "display", + context.getString(R.string.unknown) + ) + NativeInput.updateMappingsWithDefault( + playerIndex, + registeredController, + displayName + ) + Toast.makeText( + context, + context.getString(R.string.attempted_auto_map, displayName), + Toast.LENGTH_SHORT + ).show() + settingsViewModel.setReloadListAndNotifyDataset(true) + } + + override val defaultValue = -1 + + override fun getValueAsString(needsGlobal: Boolean) = getInt().toString() + + override fun reset() = setInt(defaultValue) + + override val isRuntimeModifiable: Boolean = true + } + + val unknownString = context.getString(R.string.unknown) + val prettyAutoMappingControllerList = InputHandler.registeredControllers.mapNotNull { + val port = it.get("port", -1) + return@mapNotNull if (port == 100 || port == -1) { + null + } else { + it.get("display", unknownString) + } + }.toTypedArray() + add( + IntSingleChoiceSetting( + autoMappingSetting, + titleId = R.string.auto_map, + descriptionId = R.string.auto_map_description, + choices = prettyAutoMappingControllerList, + values = IntArray(prettyAutoMappingControllerList.size) { it }.toTypedArray() + ) + ) + + val mappingFilterSetting = object : AbstractIntSetting { + override val key = "mapping_filter" + + override fun getInt(needsGlobal: Boolean): Int = settingsViewModel.currentDevice + + override fun setInt(value: Int) { + settingsViewModel.currentDevice = value + } + + override val defaultValue = 0 + + override fun getValueAsString(needsGlobal: Boolean) = getInt().toString() + + override fun reset() = setInt(defaultValue) + + override val isRuntimeModifiable: Boolean = true + } + + val prettyControllerList = InputHandler.registeredControllers.mapNotNull { + return@mapNotNull if (it.get("port", 0) == 100) { + null + } else { + it.get("display", unknownString) + } + }.toTypedArray() + add( + IntSingleChoiceSetting( + mappingFilterSetting, + titleId = R.string.input_mapping_filter, + descriptionId = R.string.input_mapping_filter_description, + choices = prettyControllerList, + values = IntArray(prettyControllerList.size) { it }.toTypedArray() + ) + ) + + add(InputProfileSetting(playerIndex)) + add( + RunnableSetting(titleId = R.string.reset_to_default, isRunnable = true) { + settingsViewModel.setShouldShowResetInputDialog(true) + } + ) + + val styleIndex = NativeInput.getStyleIndex(playerIndex) + + // Buttons + when (styleIndex) { + NpadStyleIndex.Fullkey, + NpadStyleIndex.Handheld, + NpadStyleIndex.JoyconDual -> { + add(HeaderSetting(R.string.buttons)) + add(ButtonInputSetting(playerIndex, NativeButton.A, R.string.button_a)) + add(ButtonInputSetting(playerIndex, NativeButton.B, R.string.button_b)) + add(ButtonInputSetting(playerIndex, NativeButton.X, R.string.button_x)) + add(ButtonInputSetting(playerIndex, NativeButton.Y, R.string.button_y)) + add(ButtonInputSetting(playerIndex, NativeButton.Plus, R.string.button_plus)) + add(ButtonInputSetting(playerIndex, NativeButton.Minus, R.string.button_minus)) + add(ButtonInputSetting(playerIndex, NativeButton.Home, R.string.button_home)) + add( + ButtonInputSetting( + playerIndex, + NativeButton.Capture, + R.string.button_capture + ) + ) + } + + NpadStyleIndex.JoyconLeft -> { + add(HeaderSetting(R.string.buttons)) + add(ButtonInputSetting(playerIndex, NativeButton.Minus, R.string.button_minus)) + add( + ButtonInputSetting( + playerIndex, + NativeButton.Capture, + R.string.button_capture + ) + ) + } + + NpadStyleIndex.JoyconRight -> { + add(HeaderSetting(R.string.buttons)) + add(ButtonInputSetting(playerIndex, NativeButton.A, R.string.button_a)) + add(ButtonInputSetting(playerIndex, NativeButton.B, R.string.button_b)) + add(ButtonInputSetting(playerIndex, NativeButton.X, R.string.button_x)) + add(ButtonInputSetting(playerIndex, NativeButton.Y, R.string.button_y)) + add(ButtonInputSetting(playerIndex, NativeButton.Plus, R.string.button_plus)) + add(ButtonInputSetting(playerIndex, NativeButton.Home, R.string.button_home)) + } + + NpadStyleIndex.GameCube -> { + add(HeaderSetting(R.string.buttons)) + add(ButtonInputSetting(playerIndex, NativeButton.A, R.string.button_a)) + add(ButtonInputSetting(playerIndex, NativeButton.B, R.string.button_b)) + add(ButtonInputSetting(playerIndex, NativeButton.X, R.string.button_x)) + add(ButtonInputSetting(playerIndex, NativeButton.Y, R.string.button_y)) + add(ButtonInputSetting(playerIndex, NativeButton.Plus, R.string.start_pause)) + } + + else -> { + // No-op + } + } + + when (styleIndex) { + NpadStyleIndex.Fullkey, + NpadStyleIndex.Handheld, + NpadStyleIndex.JoyconDual, + NpadStyleIndex.JoyconLeft -> { + add(HeaderSetting(R.string.dpad)) + add(ButtonInputSetting(playerIndex, NativeButton.DUp, R.string.up)) + add(ButtonInputSetting(playerIndex, NativeButton.DDown, R.string.down)) + add(ButtonInputSetting(playerIndex, NativeButton.DLeft, R.string.left)) + add(ButtonInputSetting(playerIndex, NativeButton.DRight, R.string.right)) + } + + else -> { + // No-op + } + } + + // Left stick + when (styleIndex) { + NpadStyleIndex.Fullkey, + NpadStyleIndex.Handheld, + NpadStyleIndex.JoyconDual, + NpadStyleIndex.JoyconLeft -> { + add(HeaderSetting(R.string.left_stick)) + addAll(getStickDirections(playerIndex, NativeAnalog.LStick)) + add(ButtonInputSetting(playerIndex, NativeButton.LStick, R.string.pressed)) + addAll(getExtraStickSettings(playerIndex, NativeAnalog.LStick)) + } + + NpadStyleIndex.GameCube -> { + add(HeaderSetting(R.string.control_stick)) + addAll(getStickDirections(playerIndex, NativeAnalog.LStick)) + addAll(getExtraStickSettings(playerIndex, NativeAnalog.LStick)) + } + + else -> { + // No-op + } + } + + // Right stick + when (styleIndex) { + NpadStyleIndex.Fullkey, + NpadStyleIndex.Handheld, + NpadStyleIndex.JoyconDual, + NpadStyleIndex.JoyconRight -> { + add(HeaderSetting(R.string.right_stick)) + addAll(getStickDirections(playerIndex, NativeAnalog.RStick)) + add(ButtonInputSetting(playerIndex, NativeButton.RStick, R.string.pressed)) + addAll(getExtraStickSettings(playerIndex, NativeAnalog.RStick)) + } + + NpadStyleIndex.GameCube -> { + add(HeaderSetting(R.string.c_stick)) + addAll(getStickDirections(playerIndex, NativeAnalog.RStick)) + addAll(getExtraStickSettings(playerIndex, NativeAnalog.RStick)) + } + + else -> { + // No-op + } + } + + // L/R, ZL/ZR, and SL/SR + when (styleIndex) { + NpadStyleIndex.Fullkey, + NpadStyleIndex.Handheld -> { + add(HeaderSetting(R.string.triggers)) + add(ButtonInputSetting(playerIndex, NativeButton.L, R.string.button_l)) + add(ButtonInputSetting(playerIndex, NativeButton.R, R.string.button_r)) + add(ButtonInputSetting(playerIndex, NativeButton.ZL, R.string.button_zl)) + add(ButtonInputSetting(playerIndex, NativeButton.ZR, R.string.button_zr)) + } + + NpadStyleIndex.JoyconDual -> { + add(HeaderSetting(R.string.triggers)) + add(ButtonInputSetting(playerIndex, NativeButton.L, R.string.button_l)) + add(ButtonInputSetting(playerIndex, NativeButton.R, R.string.button_r)) + add(ButtonInputSetting(playerIndex, NativeButton.ZL, R.string.button_zl)) + add(ButtonInputSetting(playerIndex, NativeButton.ZR, R.string.button_zr)) + add( + ButtonInputSetting( + playerIndex, + NativeButton.SLLeft, + R.string.button_sl_left + ) + ) + add( + ButtonInputSetting( + playerIndex, + NativeButton.SRLeft, + R.string.button_sr_left + ) + ) + add( + ButtonInputSetting( + playerIndex, + NativeButton.SLRight, + R.string.button_sl_right + ) + ) + add( + ButtonInputSetting( + playerIndex, + NativeButton.SRRight, + R.string.button_sr_right + ) + ) + } + + NpadStyleIndex.JoyconLeft -> { + add(HeaderSetting(R.string.triggers)) + add(ButtonInputSetting(playerIndex, NativeButton.L, R.string.button_l)) + add(ButtonInputSetting(playerIndex, NativeButton.ZL, R.string.button_zl)) + add( + ButtonInputSetting( + playerIndex, + NativeButton.SLLeft, + R.string.button_sl_left + ) + ) + add( + ButtonInputSetting( + playerIndex, + NativeButton.SRLeft, + R.string.button_sr_left + ) + ) + } + + NpadStyleIndex.JoyconRight -> { + add(HeaderSetting(R.string.triggers)) + add(ButtonInputSetting(playerIndex, NativeButton.R, R.string.button_r)) + add(ButtonInputSetting(playerIndex, NativeButton.ZR, R.string.button_zr)) + add( + ButtonInputSetting( + playerIndex, + NativeButton.SLRight, + R.string.button_sl_right + ) + ) + add( + ButtonInputSetting( + playerIndex, + NativeButton.SRRight, + R.string.button_sr_right + ) + ) + } + + NpadStyleIndex.GameCube -> { + add(HeaderSetting(R.string.triggers)) + add(ButtonInputSetting(playerIndex, NativeButton.R, R.string.button_z)) + add(ButtonInputSetting(playerIndex, NativeButton.ZL, R.string.button_l)) + add(ButtonInputSetting(playerIndex, NativeButton.ZR, R.string.button_r)) + } + + else -> { + // No-op + } + } + + add(HeaderSetting(R.string.vibration)) + val vibrationEnabledSetting = object : AbstractBooleanSetting { + override val key = "vibration" + + override fun getBoolean(needsGlobal: Boolean): Boolean = + NativeConfig.getInputSettings(true)[playerIndex].vibrationEnabled + + override fun setBoolean(value: Boolean) { + val settings = NativeConfig.getInputSettings(true) + settings[playerIndex].vibrationEnabled = value + NativeConfig.setInputSettings(settings, true) + } + + override val defaultValue = true + + override fun getValueAsString(needsGlobal: Boolean): String = + getBoolean(needsGlobal).toString() + + override fun reset() = setBoolean(defaultValue) + } + add(SwitchSetting(vibrationEnabledSetting, R.string.vibration)) + + val useSystemVibratorSetting = object : AbstractBooleanSetting { + override val key = "" + + override fun getBoolean(needsGlobal: Boolean): Boolean = + NativeConfig.getInputSettings(true)[playerIndex].useSystemVibrator + + override fun setBoolean(value: Boolean) { + val settings = NativeConfig.getInputSettings(true) + settings[playerIndex].useSystemVibrator = value + NativeConfig.setInputSettings(settings, true) + } + + override val defaultValue = playerIndex == 0 + + override fun getValueAsString(needsGlobal: Boolean): String = + getBoolean(needsGlobal).toString() + + override fun reset() = setBoolean(defaultValue) + + override val pairedSettingKey: String = "vibration" + } + addAbstract(SwitchSetting(useSystemVibratorSetting, R.string.use_system_vibrator)) + + val vibrationStrengthSetting = object : AbstractIntSetting { + override val key = "" + + override fun getInt(needsGlobal: Boolean): Int = + NativeConfig.getInputSettings(true)[playerIndex].vibrationStrength + + override fun setInt(value: Int) { + val settings = NativeConfig.getInputSettings(true) + settings[playerIndex].vibrationStrength = value + NativeConfig.setInputSettings(settings, true) + } + + override val defaultValue = 100 + + override fun getValueAsString(needsGlobal: Boolean): String = + getInt(needsGlobal).toString() + + override fun reset() = setInt(defaultValue) + + override val pairedSettingKey: String = "vibration" + } + addAbstract( + SliderSetting(vibrationStrengthSetting, R.string.vibration_strength, units = "%") + ) + } + } + + // Convenience function for creating AbstractIntSettings for modifier range/stick range/stick deadzones + private fun getStickIntSettingFromParam( + playerIndex: Int, + paramName: String, + stick: NativeAnalog, + defaultValue: Float + ): AbstractIntSetting = + object : AbstractIntSetting { + val params get() = NativeInput.getStickParam(playerIndex, stick) + + override val key = "" + + override fun getInt(needsGlobal: Boolean): Int = + (params.get(paramName, defaultValue) * 100).toInt() + + override fun setInt(value: Int) { + val tempParams = params + tempParams.set(paramName, value.toFloat() / 100) + NativeInput.setStickParam(playerIndex, stick, tempParams) + } + + override val defaultValue = (defaultValue * 100).toInt() + + override fun getValueAsString(needsGlobal: Boolean): String = + getInt(needsGlobal).toString() + + override fun reset() = setInt(this.defaultValue) + } + + private fun getExtraStickSettings( + playerIndex: Int, + nativeAnalog: NativeAnalog + ): List { + val stickIsController = + NativeInput.isController(NativeInput.getStickParam(playerIndex, nativeAnalog)) + val modifierRangeSetting = + getStickIntSettingFromParam(playerIndex, "modifier_scale", nativeAnalog, 0.5f) + val stickRangeSetting = + getStickIntSettingFromParam(playerIndex, "range", nativeAnalog, 0.95f) + val stickDeadzoneSetting = + getStickIntSettingFromParam(playerIndex, "deadzone", nativeAnalog, 0.15f) + + val out = mutableListOf().apply { + if (stickIsController) { + add(SliderSetting(stickRangeSetting, titleId = R.string.range, min = 25, max = 150)) + add(SliderSetting(stickDeadzoneSetting, R.string.deadzone)) + } else { + add(ModifierInputSetting(playerIndex, NativeAnalog.LStick, R.string.modifier)) + add(SliderSetting(modifierRangeSetting, R.string.modifier_range)) + } + } + return out + } + + private fun getStickDirections(player: Int, stick: NativeAnalog): List = + listOf( + AnalogInputSetting( + player, + stick, + AnalogDirection.Up, + R.string.up + ), + AnalogInputSetting( + player, + stick, + AnalogDirection.Down, + R.string.down + ), + AnalogInputSetting( + player, + stick, + AnalogDirection.Left, + R.string.left + ), + AnalogInputSetting( + player, + stick, + AnalogDirection.Right, + R.string.right + ) + ) + + private fun addThemeSettings(sl: ArrayList) { + sl.apply { + val theme: AbstractIntSetting = object : AbstractIntSetting { + override fun getInt(needsGlobal: Boolean): Int = IntSetting.THEME.getInt() + override fun setInt(value: Int) { + IntSetting.THEME.setInt(value) + settingsViewModel.setShouldRecreate(true) + } + + override val key: String = IntSetting.THEME.key + override val isRuntimeModifiable: Boolean = IntSetting.THEME.isRuntimeModifiable + override fun getValueAsString(needsGlobal: Boolean): String = + IntSetting.THEME.getValueAsString() + + override val defaultValue: Int = IntSetting.THEME.defaultValue + override fun reset() = IntSetting.THEME.setInt(defaultValue) + } + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + add( + SingleChoiceSetting( + theme, + titleId = R.string.change_app_theme, + choicesId = R.array.themeEntriesA12, + valuesId = R.array.themeValuesA12 + ) + ) + } else { + add( + SingleChoiceSetting( + theme, + titleId = R.string.change_app_theme, + choicesId = R.array.themeEntries, + valuesId = R.array.themeValues + ) + ) + } + + val themeMode: AbstractIntSetting = object : AbstractIntSetting { + override fun getInt(needsGlobal: Boolean): Int = IntSetting.THEME_MODE.getInt() + override fun setInt(value: Int) { + IntSetting.THEME_MODE.setInt(value) + settingsViewModel.setShouldRecreate(true) + } + + override val key: String = IntSetting.THEME_MODE.key + override val isRuntimeModifiable: Boolean = + IntSetting.THEME_MODE.isRuntimeModifiable + + override fun getValueAsString(needsGlobal: Boolean): String = + IntSetting.THEME_MODE.getValueAsString() + + override val defaultValue: Int = IntSetting.THEME_MODE.defaultValue + override fun reset() { + IntSetting.THEME_MODE.setInt(defaultValue) + settingsViewModel.setShouldRecreate(true) + } + } + + add( + SingleChoiceSetting( + themeMode, + titleId = R.string.change_theme_mode, + choicesId = R.array.themeModeEntries, + valuesId = R.array.themeModeValues + ) + ) + + val blackBackgrounds: AbstractBooleanSetting = object : AbstractBooleanSetting { + override fun getBoolean(needsGlobal: Boolean): Boolean = + BooleanSetting.BLACK_BACKGROUNDS.getBoolean() + + override fun setBoolean(value: Boolean) { + BooleanSetting.BLACK_BACKGROUNDS.setBoolean(value) + settingsViewModel.setShouldRecreate(true) + } + + override val key: String = BooleanSetting.BLACK_BACKGROUNDS.key + override val isRuntimeModifiable: Boolean = + BooleanSetting.BLACK_BACKGROUNDS.isRuntimeModifiable + + override fun getValueAsString(needsGlobal: Boolean): String = + BooleanSetting.BLACK_BACKGROUNDS.getValueAsString() + + override val defaultValue: Boolean = BooleanSetting.BLACK_BACKGROUNDS.defaultValue + override fun reset() { + BooleanSetting.BLACK_BACKGROUNDS + .setBoolean(BooleanSetting.BLACK_BACKGROUNDS.defaultValue) + settingsViewModel.setShouldRecreate(true) + } + } + + add( + SwitchSetting( + blackBackgrounds, + titleId = R.string.use_black_backgrounds, + descriptionId = R.string.use_black_backgrounds_description + ) + ) + } + } + + private fun addDebugSettings(sl: ArrayList) { + sl.apply { + add(HeaderSetting(R.string.gpu)) + add(IntSetting.RENDERER_BACKEND.key) + add(BooleanSetting.RENDERER_DEBUG.key) + + add(HeaderSetting(R.string.cpu)) + add(IntSetting.CPU_BACKEND.key) + add(IntSetting.CPU_ACCURACY.key) + add(BooleanSetting.CPU_DEBUG_MODE.key) + add(SettingsItem.FASTMEM_COMBINED) + } + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/SettingsSearchFragment.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/SettingsSearchFragment.kt new file mode 100644 index 0000000..529cd4f --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/SettingsSearchFragment.kt @@ -0,0 +1,183 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.settings.ui + +import android.content.Context +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.view.inputmethod.InputMethodManager +import androidx.core.view.ViewCompat +import androidx.core.view.WindowInsetsCompat +import androidx.core.view.updatePadding +import androidx.core.widget.doOnTextChanged +import androidx.fragment.app.Fragment +import androidx.fragment.app.activityViewModels +import androidx.recyclerview.widget.LinearLayoutManager +import com.google.android.material.divider.MaterialDividerItemDecoration +import com.google.android.material.transition.MaterialSharedAxis +import info.debatty.java.stringsimilarity.Cosine +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.databinding.FragmentSettingsSearchBinding +import org.sudachi.sudachi_emu.features.settings.model.view.SettingsItem +import org.sudachi.sudachi_emu.utils.NativeConfig +import org.sudachi.sudachi_emu.utils.ViewUtils.setVisible +import org.sudachi.sudachi_emu.utils.ViewUtils.updateMargins +import org.sudachi.sudachi_emu.utils.collect + +class SettingsSearchFragment : Fragment() { + private var _binding: FragmentSettingsSearchBinding? = null + private val binding get() = _binding!! + + private var settingsAdapter: SettingsAdapter? = null + + private val settingsViewModel: SettingsViewModel by activityViewModels() + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + enterTransition = MaterialSharedAxis(MaterialSharedAxis.X, true) + returnTransition = MaterialSharedAxis(MaterialSharedAxis.X, false) + reenterTransition = MaterialSharedAxis(MaterialSharedAxis.X, false) + exitTransition = MaterialSharedAxis(MaterialSharedAxis.X, true) + } + + override fun onCreateView( + inflater: LayoutInflater, + container: ViewGroup?, + savedInstanceState: Bundle? + ): View { + _binding = FragmentSettingsSearchBinding.inflate(layoutInflater) + return binding.root + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + + if (savedInstanceState != null) { + binding.searchText.setText(savedInstanceState.getString(SEARCH_TEXT)) + } + + settingsAdapter = SettingsAdapter(this, requireContext()) + + val dividerDecoration = MaterialDividerItemDecoration( + requireContext(), + LinearLayoutManager.VERTICAL + ) + dividerDecoration.isLastItemDecorated = false + binding.settingsList.apply { + adapter = settingsAdapter + layoutManager = LinearLayoutManager(requireContext()) + addItemDecoration(dividerDecoration) + } + + focusSearch() + + binding.backButton.setOnClickListener { settingsViewModel.setShouldNavigateBack(true) } + binding.searchBackground.setOnClickListener { focusSearch() } + binding.clearButton.setOnClickListener { binding.searchText.setText("") } + binding.searchText.doOnTextChanged { _, _, _, _ -> + search() + binding.settingsList.smoothScrollToPosition(0) + } + settingsViewModel.shouldReloadSettingsList.collect(viewLifecycleOwner) { + if (it) { + settingsViewModel.setShouldReloadSettingsList(false) + search() + } + } + + search() + + setInsets() + } + + override fun onSaveInstanceState(outState: Bundle) { + super.onSaveInstanceState(outState) + outState.putString(SEARCH_TEXT, binding.searchText.text.toString()) + } + + private fun search() { + val searchTerm = binding.searchText.text.toString().lowercase() + binding.clearButton.setVisible(visible = searchTerm.isNotEmpty(), gone = false) + if (searchTerm.isEmpty()) { + binding.noResultsView.setVisible(visible = false, gone = false) + settingsAdapter?.submitList(emptyList()) + return + } + + val baseList = SettingsItem.settingsItems + val similarityAlgorithm = if (searchTerm.length > 2) Cosine() else Cosine(1) + val sortedList: List = baseList.mapNotNull { item -> + val title = item.value.title.lowercase() + val similarity = similarityAlgorithm.similarity(searchTerm, title) + if (similarity > 0.08) { + Pair(similarity, item) + } else { + null + } + }.sortedByDescending { it.first }.mapNotNull { + val item = it.second.value + val pairedSettingKey = item.setting.pairedSettingKey + val optionalSetting: SettingsItem? = if (pairedSettingKey.isNotEmpty()) { + val pairedSettingValue = NativeConfig.getBoolean(pairedSettingKey, false) + if (pairedSettingValue) it.second.value else null + } else { + it.second.value + } + optionalSetting + } + settingsAdapter?.submitList(sortedList) + binding.noResultsView.setVisible(visible = sortedList.isEmpty(), gone = false) + } + + private fun focusSearch() { + binding.searchText.requestFocus() + val imm = requireActivity() + .getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager? + imm?.showSoftInput(binding.searchText, InputMethodManager.SHOW_IMPLICIT) + } + + private fun setInsets() = + ViewCompat.setOnApplyWindowInsetsListener( + binding.root + ) { _: View, windowInsets: WindowInsetsCompat -> + val extraListSpacing = resources.getDimensionPixelSize(R.dimen.spacing_med) + val sideMargin = resources.getDimensionPixelSize(R.dimen.spacing_medlarge) + val topMargin = resources.getDimensionPixelSize(R.dimen.spacing_chip) + + val barInsets = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars()) + val cutoutInsets = windowInsets.getInsets(WindowInsetsCompat.Type.displayCutout()) + + val leftInsets = barInsets.left + cutoutInsets.left + val rightInsets = barInsets.right + cutoutInsets.right + + binding.settingsList.updatePadding(bottom = barInsets.bottom + extraListSpacing) + binding.frameSearch.updatePadding( + left = leftInsets + sideMargin, + top = barInsets.top + topMargin, + right = rightInsets + sideMargin + ) + binding.noResultsView.updatePadding( + left = leftInsets, + right = rightInsets, + bottom = barInsets.bottom + ) + + binding.settingsList.updateMargins( + left = leftInsets + sideMargin, + right = rightInsets + sideMargin + ) + binding.divider.updateMargins( + left = leftInsets + sideMargin, + right = rightInsets + sideMargin + ) + + windowInsets + } + + companion object { + const val SEARCH_TEXT = "SearchText" + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/SettingsViewModel.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/SettingsViewModel.kt new file mode 100644 index 0000000..9f03729 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/SettingsViewModel.kt @@ -0,0 +1,112 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.settings.ui + +import androidx.lifecycle.ViewModel +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.SudachiApplication +import org.sudachi.sudachi_emu.features.settings.model.view.SettingsItem +import org.sudachi.sudachi_emu.model.Game +import org.sudachi.sudachi_emu.utils.InputHandler +import org.sudachi.sudachi_emu.utils.ParamPackage + +class SettingsViewModel : ViewModel() { + var game: Game? = null + + var clickedItem: SettingsItem? = null + + var currentDevice = 0 + + val shouldRecreate: StateFlow get() = _shouldRecreate + private val _shouldRecreate = MutableStateFlow(false) + + val shouldNavigateBack: StateFlow get() = _shouldNavigateBack + private val _shouldNavigateBack = MutableStateFlow(false) + + val shouldShowResetSettingsDialog: StateFlow get() = _shouldShowResetSettingsDialog + private val _shouldShowResetSettingsDialog = MutableStateFlow(false) + + val shouldReloadSettingsList: StateFlow get() = _shouldReloadSettingsList + private val _shouldReloadSettingsList = MutableStateFlow(false) + + val sliderProgress: StateFlow get() = _sliderProgress + private val _sliderProgress = MutableStateFlow(-1) + + val sliderTextValue: StateFlow get() = _sliderTextValue + private val _sliderTextValue = MutableStateFlow("") + + val adapterItemChanged: StateFlow get() = _adapterItemChanged + private val _adapterItemChanged = MutableStateFlow(-1) + + private val _datasetChanged = MutableStateFlow(false) + val datasetChanged = _datasetChanged.asStateFlow() + + private val _reloadListAndNotifyDataset = MutableStateFlow(false) + val reloadListAndNotifyDataset = _reloadListAndNotifyDataset.asStateFlow() + + private val _shouldShowDeleteProfileDialog = MutableStateFlow("") + val shouldShowDeleteProfileDialog = _shouldShowDeleteProfileDialog.asStateFlow() + + private val _shouldShowResetInputDialog = MutableStateFlow(false) + val shouldShowResetInputDialog = _shouldShowResetInputDialog.asStateFlow() + + fun setShouldRecreate(value: Boolean) { + _shouldRecreate.value = value + } + + fun setShouldNavigateBack(value: Boolean) { + _shouldNavigateBack.value = value + } + + fun setShouldShowResetSettingsDialog(value: Boolean) { + _shouldShowResetSettingsDialog.value = value + } + + fun setShouldReloadSettingsList(value: Boolean) { + _shouldReloadSettingsList.value = value + } + + fun setSliderTextValue(value: Float, units: String) { + _sliderProgress.value = value.toInt() + _sliderTextValue.value = String.format( + SudachiApplication.appContext.getString(R.string.value_with_units), + value.toInt().toString(), + units + ) + } + + fun setSliderProgress(value: Float) { + _sliderProgress.value = value.toInt() + } + + fun setAdapterItemChanged(value: Int) { + _adapterItemChanged.value = value + } + + fun setDatasetChanged(value: Boolean) { + _datasetChanged.value = value + } + + fun setReloadListAndNotifyDataset(value: Boolean) { + _reloadListAndNotifyDataset.value = value + } + + fun setShouldShowDeleteProfileDialog(profile: String) { + _shouldShowDeleteProfileDialog.value = profile + } + + fun setShouldShowResetInputDialog(value: Boolean) { + _shouldShowResetInputDialog.value = value + } + + fun getCurrentDeviceParams(defaultParams: ParamPackage): ParamPackage = + try { + InputHandler.registeredControllers[currentDevice] + } catch (e: IndexOutOfBoundsException) { + defaultParams + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/viewholder/DateTimeViewHolder.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/viewholder/DateTimeViewHolder.kt new file mode 100644 index 0000000..6305e70 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/viewholder/DateTimeViewHolder.kt @@ -0,0 +1,54 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.settings.ui.viewholder + +import android.view.View +import java.time.Instant +import java.time.ZoneId +import java.time.ZonedDateTime +import java.time.format.DateTimeFormatter +import java.time.format.FormatStyle +import org.sudachi.sudachi_emu.databinding.ListItemSettingBinding +import org.sudachi.sudachi_emu.features.settings.model.view.DateTimeSetting +import org.sudachi.sudachi_emu.features.settings.model.view.SettingsItem +import org.sudachi.sudachi_emu.features.settings.ui.SettingsAdapter +import org.sudachi.sudachi_emu.utils.ViewUtils.setVisible + +class DateTimeViewHolder(val binding: ListItemSettingBinding, adapter: SettingsAdapter) : + SettingViewHolder(binding.root, adapter) { + private lateinit var setting: DateTimeSetting + + override fun bind(item: SettingsItem) { + setting = item as DateTimeSetting + binding.textSettingName.text = item.title + binding.textSettingDescription.setVisible(item.description.isNotEmpty()) + binding.textSettingDescription.text = item.description + binding.textSettingValue.setVisible(true) + val epochTime = setting.getValue() + val instant = Instant.ofEpochMilli(epochTime * 1000) + val zonedTime = ZonedDateTime.ofInstant(instant, ZoneId.of("UTC")) + val dateFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM) + binding.textSettingValue.text = dateFormatter.format(zonedTime) + + binding.buttonClear.setVisible(setting.clearable) + binding.buttonClear.setOnClickListener { + adapter.onClearClick(setting, bindingAdapterPosition) + } + + setStyle(setting.isEditable, binding) + } + + override fun onClick(clicked: View) { + if (setting.isEditable) { + adapter.onDateTimeClick(setting, bindingAdapterPosition) + } + } + + override fun onLongClick(clicked: View): Boolean { + if (setting.isEditable) { + return adapter.onLongClick(setting, bindingAdapterPosition) + } + return false + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/viewholder/HeaderViewHolder.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/viewholder/HeaderViewHolder.kt new file mode 100644 index 0000000..b8a4629 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/viewholder/HeaderViewHolder.kt @@ -0,0 +1,30 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.settings.ui.viewholder + +import android.view.View +import org.sudachi.sudachi_emu.databinding.ListItemSettingsHeaderBinding +import org.sudachi.sudachi_emu.features.settings.model.view.SettingsItem +import org.sudachi.sudachi_emu.features.settings.ui.SettingsAdapter + +class HeaderViewHolder(val binding: ListItemSettingsHeaderBinding, adapter: SettingsAdapter) : + SettingViewHolder(binding.root, adapter) { + + init { + itemView.setOnClickListener(null) + } + + override fun bind(item: SettingsItem) { + binding.textHeaderName.text = item.title + } + + override fun onClick(clicked: View) { + // no-op + } + + override fun onLongClick(clicked: View): Boolean { + // no-op + return true + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/viewholder/InputProfileViewHolder.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/viewholder/InputProfileViewHolder.kt new file mode 100644 index 0000000..693b8d5 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/viewholder/InputProfileViewHolder.kt @@ -0,0 +1,34 @@ +// SPDX-FileCopyrightText: 2024 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.settings.ui.viewholder + +import android.view.View +import org.sudachi.sudachi_emu.databinding.ListItemSettingBinding +import org.sudachi.sudachi_emu.features.settings.model.view.InputProfileSetting +import org.sudachi.sudachi_emu.features.settings.model.view.SettingsItem +import org.sudachi.sudachi_emu.features.settings.ui.SettingsAdapter +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.utils.ViewUtils.setVisible + +class InputProfileViewHolder(val binding: ListItemSettingBinding, adapter: SettingsAdapter) : + SettingViewHolder(binding.root, adapter) { + private lateinit var setting: InputProfileSetting + + override fun bind(item: SettingsItem) { + setting = item as InputProfileSetting + binding.textSettingName.text = setting.title + binding.textSettingValue.text = + setting.getCurrentProfile().ifEmpty { binding.root.context.getString(R.string.not_set) } + + binding.textSettingDescription.setVisible(false) + binding.buttonClear.setVisible(false) + binding.icon.setVisible(false) + binding.buttonClear.setVisible(false) + } + + override fun onClick(clicked: View) = + adapter.onInputProfileClick(setting, bindingAdapterPosition) + + override fun onLongClick(clicked: View): Boolean = false +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/viewholder/InputViewHolder.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/viewholder/InputViewHolder.kt new file mode 100644 index 0000000..5163473 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/viewholder/InputViewHolder.kt @@ -0,0 +1,60 @@ +// SPDX-FileCopyrightText: 2024 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.settings.ui.viewholder + +import android.view.View +import org.sudachi.sudachi_emu.databinding.ListItemSettingInputBinding +import org.sudachi.sudachi_emu.features.input.NativeInput +import org.sudachi.sudachi_emu.features.settings.model.view.AnalogInputSetting +import org.sudachi.sudachi_emu.features.settings.model.view.ButtonInputSetting +import org.sudachi.sudachi_emu.features.settings.model.view.InputSetting +import org.sudachi.sudachi_emu.features.settings.model.view.ModifierInputSetting +import org.sudachi.sudachi_emu.features.settings.model.view.SettingsItem +import org.sudachi.sudachi_emu.features.settings.ui.SettingsAdapter +import org.sudachi.sudachi_emu.utils.ViewUtils.setVisible + +class InputViewHolder(val binding: ListItemSettingInputBinding, adapter: SettingsAdapter) : + SettingViewHolder(binding.root, adapter) { + private lateinit var setting: InputSetting + + override fun bind(item: SettingsItem) { + setting = item as InputSetting + binding.textSettingName.text = setting.title + binding.textSettingValue.text = setting.getSelectedValue() + + when (item) { + is AnalogInputSetting -> { + val param = NativeInput.getStickParam(item.playerIndex, item.nativeAnalog) + binding.buttonOptions.setVisible( + param.get("engine", "") == "analog_from_button" || + param.has("axis_x") || param.has("axis_y") + ) + } + + is ButtonInputSetting -> { + val param = NativeInput.getButtonParam(item.playerIndex, item.nativeButton) + binding.buttonOptions.setVisible( + param.has("code") || param.has("button") || param.has("hat") || + param.has("axis") + ) + } + + is ModifierInputSetting -> { + val params = NativeInput.getStickParam(item.playerIndex, item.nativeAnalog) + binding.buttonOptions.setVisible(params.has("modifier")) + } + } + + binding.buttonOptions.setOnClickListener(null) + binding.buttonOptions.setOnClickListener { + adapter.onInputOptionsClick(binding.buttonOptions, setting, bindingAdapterPosition) + } + } + + override fun onClick(clicked: View) = + adapter.onInputClick(setting, bindingAdapterPosition) + + override fun onLongClick(clicked: View): Boolean = + adapter.onLongClick(setting, bindingAdapterPosition) +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/viewholder/RunnableViewHolder.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/viewholder/RunnableViewHolder.kt new file mode 100644 index 0000000..18677d1 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/viewholder/RunnableViewHolder.kt @@ -0,0 +1,50 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.settings.ui.viewholder + +import android.view.View +import androidx.core.content.res.ResourcesCompat +import org.sudachi.sudachi_emu.databinding.ListItemSettingBinding +import org.sudachi.sudachi_emu.features.settings.model.view.RunnableSetting +import org.sudachi.sudachi_emu.features.settings.model.view.SettingsItem +import org.sudachi.sudachi_emu.features.settings.ui.SettingsAdapter +import org.sudachi.sudachi_emu.utils.ViewUtils.setVisible + +class RunnableViewHolder(val binding: ListItemSettingBinding, adapter: SettingsAdapter) : + SettingViewHolder(binding.root, adapter) { + private lateinit var setting: RunnableSetting + + override fun bind(item: SettingsItem) { + setting = item as RunnableSetting + binding.icon.setVisible(setting.iconId != 0) + if (setting.iconId != 0) { + binding.icon.setImageDrawable( + ResourcesCompat.getDrawable( + binding.icon.resources, + setting.iconId, + binding.icon.context.theme + ) + ) + } + + binding.textSettingName.text = setting.title + binding.textSettingDescription.setVisible(setting.description.isNotEmpty()) + binding.textSettingDescription.text = item.description + binding.textSettingValue.setVisible(false) + binding.buttonClear.setVisible(false) + + setStyle(setting.isEditable, binding) + } + + override fun onClick(clicked: View) { + if (setting.isRunnable) { + setting.runnable.invoke() + } + } + + override fun onLongClick(clicked: View): Boolean { + // no-op + return true + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/viewholder/SettingViewHolder.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/viewholder/SettingViewHolder.kt new file mode 100644 index 0000000..3aff869 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/viewholder/SettingViewHolder.kt @@ -0,0 +1,54 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.settings.ui.viewholder + +import android.view.View +import androidx.recyclerview.widget.RecyclerView +import org.sudachi.sudachi_emu.databinding.ListItemSettingBinding +import org.sudachi.sudachi_emu.databinding.ListItemSettingSwitchBinding +import org.sudachi.sudachi_emu.features.settings.model.view.SettingsItem +import org.sudachi.sudachi_emu.features.settings.ui.SettingsAdapter + +abstract class SettingViewHolder(itemView: View, protected val adapter: SettingsAdapter) : + RecyclerView.ViewHolder(itemView), View.OnClickListener, View.OnLongClickListener { + + init { + itemView.setOnClickListener(this) + itemView.setOnLongClickListener(this) + } + + /** + * Called by the adapter to set this ViewHolder's child views to display the list item + * it must now represent. + * + * @param item The list item that should be represented by this ViewHolder. + */ + abstract fun bind(item: SettingsItem) + + /** + * Called when this ViewHolder's view is clicked on. Implementations should usually pass + * this event up to the adapter. + * + * @param clicked The view that was clicked on. + */ + abstract override fun onClick(clicked: View) + + abstract override fun onLongClick(clicked: View): Boolean + + fun setStyle(isEditable: Boolean, binding: ListItemSettingBinding) { + val opacity = if (isEditable) 1.0f else 0.5f + binding.textSettingName.alpha = opacity + binding.textSettingDescription.alpha = opacity + binding.textSettingValue.alpha = opacity + binding.buttonClear.isEnabled = isEditable + } + + fun setStyle(isEditable: Boolean, binding: ListItemSettingSwitchBinding) { + binding.switchWidget.isEnabled = isEditable + val opacity = if (isEditable) 1.0f else 0.5f + binding.textSettingName.alpha = opacity + binding.textSettingDescription.alpha = opacity + binding.buttonClear.isEnabled = isEditable + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/viewholder/SingleChoiceViewHolder.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/viewholder/SingleChoiceViewHolder.kt new file mode 100644 index 0000000..85a938d --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/viewholder/SingleChoiceViewHolder.kt @@ -0,0 +1,91 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.settings.ui.viewholder + +import android.view.View +import org.sudachi.sudachi_emu.databinding.ListItemSettingBinding +import org.sudachi.sudachi_emu.features.settings.model.view.IntSingleChoiceSetting +import org.sudachi.sudachi_emu.features.settings.model.view.SettingsItem +import org.sudachi.sudachi_emu.features.settings.model.view.SingleChoiceSetting +import org.sudachi.sudachi_emu.features.settings.model.view.StringSingleChoiceSetting +import org.sudachi.sudachi_emu.features.settings.ui.SettingsAdapter +import org.sudachi.sudachi_emu.utils.ViewUtils.setVisible + +class SingleChoiceViewHolder(val binding: ListItemSettingBinding, adapter: SettingsAdapter) : + SettingViewHolder(binding.root, adapter) { + private lateinit var setting: SettingsItem + + override fun bind(item: SettingsItem) { + setting = item + binding.textSettingName.text = setting.title + binding.textSettingDescription.setVisible(item.description.isNotEmpty()) + binding.textSettingDescription.text = item.description + + binding.textSettingValue.setVisible(true) + when (item) { + is SingleChoiceSetting -> { + val resMgr = binding.textSettingValue.context.resources + val values = resMgr.getIntArray(item.valuesId) + for (i in values.indices) { + if (values[i] == item.getSelectedValue()) { + binding.textSettingValue.text = resMgr.getStringArray(item.choicesId)[i] + break + } + } + } + + is StringSingleChoiceSetting -> { + binding.textSettingValue.text = item.getSelectedValue() + } + + is IntSingleChoiceSetting -> { + binding.textSettingValue.text = item.getChoiceAt(item.getSelectedValue()) + } + } + if (binding.textSettingValue.text.isEmpty()) { + binding.textSettingValue.setVisible(false) + } + + binding.buttonClear.setVisible(setting.clearable) + binding.buttonClear.setOnClickListener { + adapter.onClearClick(setting, bindingAdapterPosition) + } + + setStyle(setting.isEditable, binding) + } + + override fun onClick(clicked: View) { + if (!setting.isEditable) { + return + } + + when (setting) { + is SingleChoiceSetting -> adapter.onSingleChoiceClick( + setting as SingleChoiceSetting, + bindingAdapterPosition + ) + + is StringSingleChoiceSetting -> { + adapter.onStringSingleChoiceClick( + setting as StringSingleChoiceSetting, + bindingAdapterPosition + ) + } + + is IntSingleChoiceSetting -> { + adapter.onIntSingleChoiceClick( + setting as IntSingleChoiceSetting, + bindingAdapterPosition + ) + } + } + } + + override fun onLongClick(clicked: View): Boolean { + if (setting.isEditable) { + return adapter.onLongClick(setting, bindingAdapterPosition) + } + return false + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/viewholder/SliderViewHolder.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/viewholder/SliderViewHolder.kt new file mode 100644 index 0000000..c971bf2 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/viewholder/SliderViewHolder.kt @@ -0,0 +1,50 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.settings.ui.viewholder + +import android.view.View +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.databinding.ListItemSettingBinding +import org.sudachi.sudachi_emu.features.settings.model.view.SettingsItem +import org.sudachi.sudachi_emu.features.settings.model.view.SliderSetting +import org.sudachi.sudachi_emu.features.settings.ui.SettingsAdapter +import org.sudachi.sudachi_emu.utils.ViewUtils.setVisible + +class SliderViewHolder(val binding: ListItemSettingBinding, adapter: SettingsAdapter) : + SettingViewHolder(binding.root, adapter) { + private lateinit var setting: SliderSetting + + override fun bind(item: SettingsItem) { + setting = item as SliderSetting + binding.textSettingName.text = setting.title + binding.textSettingDescription.setVisible(item.description.isNotEmpty()) + binding.textSettingDescription.text = setting.description + binding.textSettingValue.setVisible(true) + binding.textSettingValue.text = String.format( + binding.textSettingValue.context.getString(R.string.value_with_units), + setting.getSelectedValue(), + setting.units + ) + + binding.buttonClear.setVisible(setting.clearable) + binding.buttonClear.setOnClickListener { + adapter.onClearClick(setting, bindingAdapterPosition) + } + + setStyle(setting.isEditable, binding) + } + + override fun onClick(clicked: View) { + if (setting.isEditable) { + adapter.onSliderClick(setting, bindingAdapterPosition) + } + } + + override fun onLongClick(clicked: View): Boolean { + if (setting.isEditable) { + return adapter.onLongClick(setting, bindingAdapterPosition) + } + return false + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/viewholder/StringInputViewHolder.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/viewholder/StringInputViewHolder.kt new file mode 100644 index 0000000..48e132d --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/viewholder/StringInputViewHolder.kt @@ -0,0 +1,45 @@ +// SPDX-FileCopyrightText: 2024 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.settings.ui.viewholder + +import android.view.View +import org.sudachi.sudachi_emu.databinding.ListItemSettingBinding +import org.sudachi.sudachi_emu.features.settings.model.view.SettingsItem +import org.sudachi.sudachi_emu.features.settings.model.view.StringInputSetting +import org.sudachi.sudachi_emu.features.settings.ui.SettingsAdapter +import org.sudachi.sudachi_emu.utils.ViewUtils.setVisible + +class StringInputViewHolder(val binding: ListItemSettingBinding, adapter: SettingsAdapter) : + SettingViewHolder(binding.root, adapter) { + private lateinit var setting: StringInputSetting + + override fun bind(item: SettingsItem) { + setting = item as StringInputSetting + binding.textSettingName.text = setting.title + binding.textSettingDescription.setVisible(setting.description.isNotEmpty()) + binding.textSettingDescription.text = setting.description + binding.textSettingValue.setVisible(true) + binding.textSettingValue.text = setting.getSelectedValue() + + binding.buttonClear.setVisible(setting.clearable) + binding.buttonClear.setOnClickListener { + adapter.onClearClick(setting, bindingAdapterPosition) + } + + setStyle(setting.isEditable, binding) + } + + override fun onClick(clicked: View) { + if (setting.isEditable) { + adapter.onStringInputClick(setting, bindingAdapterPosition) + } + } + + override fun onLongClick(clicked: View): Boolean { + if (setting.isEditable) { + return adapter.onLongClick(setting, bindingAdapterPosition) + } + return false + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/viewholder/SubmenuViewHolder.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/viewholder/SubmenuViewHolder.kt new file mode 100644 index 0000000..4e60b9e --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/viewholder/SubmenuViewHolder.kt @@ -0,0 +1,46 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.settings.ui.viewholder + +import android.view.View +import androidx.core.content.res.ResourcesCompat +import org.sudachi.sudachi_emu.databinding.ListItemSettingBinding +import org.sudachi.sudachi_emu.features.settings.model.view.SettingsItem +import org.sudachi.sudachi_emu.features.settings.model.view.SubmenuSetting +import org.sudachi.sudachi_emu.features.settings.ui.SettingsAdapter +import org.sudachi.sudachi_emu.utils.ViewUtils.setVisible + +class SubmenuViewHolder(val binding: ListItemSettingBinding, adapter: SettingsAdapter) : + SettingViewHolder(binding.root, adapter) { + private lateinit var setting: SubmenuSetting + + override fun bind(item: SettingsItem) { + setting = item as SubmenuSetting + binding.icon.setVisible(setting.iconId != 0) + if (setting.iconId != 0) { + binding.icon.setImageDrawable( + ResourcesCompat.getDrawable( + binding.icon.resources, + setting.iconId, + binding.icon.context.theme + ) + ) + } + + binding.textSettingName.text = setting.title + binding.textSettingDescription.setVisible(setting.description.isNotEmpty()) + binding.textSettingDescription.text = setting.description + binding.textSettingValue.setVisible(false) + binding.buttonClear.setVisible(false) + } + + override fun onClick(clicked: View) { + adapter.onSubmenuClick(setting) + } + + override fun onLongClick(clicked: View): Boolean { + // no-op + return true + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/viewholder/SwitchSettingViewHolder.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/viewholder/SwitchSettingViewHolder.kt new file mode 100644 index 0000000..f2002ce --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/ui/viewholder/SwitchSettingViewHolder.kt @@ -0,0 +1,51 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.settings.ui.viewholder + +import android.view.View +import android.widget.CompoundButton +import org.sudachi.sudachi_emu.databinding.ListItemSettingSwitchBinding +import org.sudachi.sudachi_emu.features.settings.model.view.SettingsItem +import org.sudachi.sudachi_emu.features.settings.model.view.SwitchSetting +import org.sudachi.sudachi_emu.features.settings.ui.SettingsAdapter +import org.sudachi.sudachi_emu.utils.ViewUtils.setVisible + +class SwitchSettingViewHolder(val binding: ListItemSettingSwitchBinding, adapter: SettingsAdapter) : + SettingViewHolder(binding.root, adapter) { + + private lateinit var setting: SwitchSetting + + override fun bind(item: SettingsItem) { + setting = item as SwitchSetting + binding.textSettingName.text = setting.title + binding.textSettingDescription.setVisible(setting.description.isNotEmpty()) + binding.textSettingDescription.text = setting.description + + binding.switchWidget.setOnCheckedChangeListener(null) + binding.switchWidget.isChecked = setting.getIsChecked(setting.needsRuntimeGlobal) + binding.switchWidget.setOnCheckedChangeListener { _: CompoundButton, _: Boolean -> + adapter.onBooleanClick(setting, binding.switchWidget.isChecked, bindingAdapterPosition) + } + + binding.buttonClear.setVisible(setting.clearable) + binding.buttonClear.setOnClickListener { + adapter.onClearClick(setting, bindingAdapterPosition) + } + + setStyle(setting.isEditable, binding) + } + + override fun onClick(clicked: View) { + if (setting.isEditable) { + binding.switchWidget.toggle() + } + } + + override fun onLongClick(clicked: View): Boolean { + if (setting.isEditable) { + return adapter.onLongClick(setting, bindingAdapterPosition) + } + return false + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/utils/SettingsFile.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/utils/SettingsFile.kt new file mode 100644 index 0000000..a9b9d84 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/features/settings/utils/SettingsFile.kt @@ -0,0 +1,29 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.features.settings.utils + +import android.net.Uri +import org.sudachi.sudachi_emu.model.Game +import java.io.* +import org.sudachi.sudachi_emu.utils.DirectoryInitialization +import org.sudachi.sudachi_emu.utils.FileUtil +import org.sudachi.sudachi_emu.utils.NativeConfig + +/** + * Contains static methods for interacting with .ini files in which settings are stored. + */ +object SettingsFile { + const val FILE_NAME_CONFIG = "config.ini" + + fun getSettingsFile(fileName: String): File = + File(DirectoryInitialization.userDirectory + "/config/" + fileName) + + fun getCustomSettingsFile(game: Game): File = + File(DirectoryInitialization.userDirectory + "/config/custom/" + game.settingsName + ".ini") + + fun loadCustomConfig(game: Game) { + val fileName = FileUtil.getFilename(Uri.parse(game.path)) + NativeConfig.initializePerGameConfig(game.programId, fileName) + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/AboutFragment.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/AboutFragment.kt new file mode 100644 index 0000000..428a011 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/AboutFragment.kt @@ -0,0 +1,124 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.fragments + +import android.content.ClipData +import android.content.ClipboardManager +import android.content.Context +import android.content.Intent +import android.net.Uri +import android.os.Build +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.Toast +import androidx.core.view.ViewCompat +import androidx.core.view.WindowInsetsCompat +import androidx.core.view.updatePadding +import androidx.fragment.app.Fragment +import androidx.fragment.app.activityViewModels +import androidx.navigation.findNavController +import com.google.android.material.transition.MaterialSharedAxis +import org.sudachi.sudachi_emu.BuildConfig +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.databinding.FragmentAboutBinding +import org.sudachi.sudachi_emu.model.HomeViewModel +import org.sudachi.sudachi_emu.utils.ViewUtils.updateMargins + +class AboutFragment : Fragment() { + private var _binding: FragmentAboutBinding? = null + private val binding get() = _binding!! + + private val homeViewModel: HomeViewModel by activityViewModels() + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + enterTransition = MaterialSharedAxis(MaterialSharedAxis.X, true) + returnTransition = MaterialSharedAxis(MaterialSharedAxis.X, false) + reenterTransition = MaterialSharedAxis(MaterialSharedAxis.X, false) + } + + override fun onCreateView( + inflater: LayoutInflater, + container: ViewGroup?, + savedInstanceState: Bundle? + ): View { + _binding = FragmentAboutBinding.inflate(layoutInflater) + return binding.root + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + homeViewModel.setNavigationVisibility(visible = false, animated = true) + homeViewModel.setStatusBarShadeVisibility(visible = false) + + binding.toolbarAbout.setNavigationOnClickListener { + binding.root.findNavController().popBackStack() + } + + binding.imageLogo.setOnLongClickListener { + Toast.makeText( + requireContext(), + R.string.gaia_is_not_real, + Toast.LENGTH_SHORT + ).show() + true + } + + binding.buttonContributors.setOnClickListener { + openLink( + getString(R.string.contributors_link) + ) + } + binding.buttonLicenses.setOnClickListener { + exitTransition = MaterialSharedAxis(MaterialSharedAxis.X, true) + binding.root.findNavController().navigate(R.id.action_aboutFragment_to_licensesFragment) + } + + binding.textVersionName.text = BuildConfig.VERSION_NAME + binding.buttonVersionName.setOnClickListener { + val clipBoard = + requireContext().getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager + val clip = ClipData.newPlainText(getString(R.string.build), BuildConfig.GIT_HASH) + clipBoard.setPrimaryClip(clip) + + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) { + Toast.makeText( + requireContext(), + R.string.copied_to_clipboard, + Toast.LENGTH_SHORT + ).show() + } + } + + binding.buttonDiscord.setOnClickListener { openLink(getString(R.string.support_link)) } + binding.buttonWebsite.setOnClickListener { openLink(getString(R.string.website_link)) } + binding.buttonGithub.setOnClickListener { openLink(getString(R.string.github_link)) } + + setInsets() + } + + private fun openLink(link: String) { + val intent = Intent(Intent.ACTION_VIEW, Uri.parse(link)) + startActivity(intent) + } + + private fun setInsets() = + ViewCompat.setOnApplyWindowInsetsListener( + binding.root + ) { _: View, windowInsets: WindowInsetsCompat -> + val barInsets = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars()) + val cutoutInsets = windowInsets.getInsets(WindowInsetsCompat.Type.displayCutout()) + + val leftInsets = barInsets.left + cutoutInsets.left + val rightInsets = barInsets.right + cutoutInsets.right + + binding.toolbarAbout.updateMargins(left = leftInsets, right = rightInsets) + binding.scrollAbout.updateMargins(left = leftInsets, right = rightInsets) + + binding.contentAbout.updatePadding(bottom = barInsets.bottom) + + windowInsets + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/AddGameFolderDialogFragment.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/AddGameFolderDialogFragment.kt new file mode 100644 index 0000000..e39bdd5 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/AddGameFolderDialogFragment.kt @@ -0,0 +1,56 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.fragments + +import android.app.Dialog +import android.content.DialogInterface +import android.net.Uri +import android.os.Bundle +import androidx.fragment.app.DialogFragment +import androidx.fragment.app.activityViewModels +import com.google.android.material.dialog.MaterialAlertDialogBuilder +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.databinding.DialogAddFolderBinding +import org.sudachi.sudachi_emu.model.GameDir +import org.sudachi.sudachi_emu.model.GamesViewModel +import org.sudachi.sudachi_emu.model.HomeViewModel + +class AddGameFolderDialogFragment : DialogFragment() { + private val homeViewModel: HomeViewModel by activityViewModels() + private val gamesViewModel: GamesViewModel by activityViewModels() + + override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { + val binding = DialogAddFolderBinding.inflate(layoutInflater) + val folderUriString = requireArguments().getString(FOLDER_URI_STRING) + if (folderUriString == null) { + dismiss() + } + binding.path.text = Uri.parse(folderUriString).path + + return MaterialAlertDialogBuilder(requireContext()) + .setTitle(R.string.add_game_folder) + .setPositiveButton(android.R.string.ok) { _: DialogInterface, _: Int -> + val newGameDir = GameDir(folderUriString!!, binding.deepScanSwitch.isChecked) + homeViewModel.setGamesDirSelected(true) + gamesViewModel.addFolder(newGameDir) + } + .setNegativeButton(android.R.string.cancel, null) + .setView(binding.root) + .show() + } + + companion object { + const val TAG = "AddGameFolderDialogFragment" + + private const val FOLDER_URI_STRING = "FolderUriString" + + fun newInstance(folderUriString: String): AddGameFolderDialogFragment { + val args = Bundle() + args.putString(FOLDER_URI_STRING, folderUriString) + val fragment = AddGameFolderDialogFragment() + fragment.arguments = args + return fragment + } + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/AddonsFragment.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/AddonsFragment.kt new file mode 100644 index 0000000..07d5882 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/AddonsFragment.kt @@ -0,0 +1,205 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.fragments + +import android.content.Intent +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.activity.result.contract.ActivityResultContracts +import androidx.core.view.ViewCompat +import androidx.core.view.WindowInsetsCompat +import androidx.core.view.updatePadding +import androidx.documentfile.provider.DocumentFile +import androidx.fragment.app.Fragment +import androidx.fragment.app.activityViewModels +import androidx.navigation.findNavController +import androidx.navigation.fragment.navArgs +import androidx.recyclerview.widget.LinearLayoutManager +import com.google.android.material.transition.MaterialSharedAxis +import kotlinx.coroutines.launch +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.adapters.AddonAdapter +import org.sudachi.sudachi_emu.databinding.FragmentAddonsBinding +import org.sudachi.sudachi_emu.model.AddonViewModel +import org.sudachi.sudachi_emu.model.HomeViewModel +import org.sudachi.sudachi_emu.utils.AddonUtil +import org.sudachi.sudachi_emu.utils.FileUtil.copyFilesTo +import org.sudachi.sudachi_emu.utils.ViewUtils.updateMargins +import org.sudachi.sudachi_emu.utils.collect +import java.io.File + +class AddonsFragment : Fragment() { + private var _binding: FragmentAddonsBinding? = null + private val binding get() = _binding!! + + private val homeViewModel: HomeViewModel by activityViewModels() + private val addonViewModel: AddonViewModel by activityViewModels() + + private val args by navArgs() + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + addonViewModel.onOpenAddons(args.game) + enterTransition = MaterialSharedAxis(MaterialSharedAxis.X, true) + returnTransition = MaterialSharedAxis(MaterialSharedAxis.X, false) + reenterTransition = MaterialSharedAxis(MaterialSharedAxis.X, false) + } + + override fun onCreateView( + inflater: LayoutInflater, + container: ViewGroup?, + savedInstanceState: Bundle? + ): View { + _binding = FragmentAddonsBinding.inflate(inflater) + return binding.root + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + homeViewModel.setNavigationVisibility(visible = false, animated = false) + homeViewModel.setStatusBarShadeVisibility(false) + + binding.toolbarAddons.setNavigationOnClickListener { + binding.root.findNavController().popBackStack() + } + + binding.toolbarAddons.title = getString(R.string.addons_game, args.game.title) + + binding.listAddons.apply { + layoutManager = LinearLayoutManager(requireContext()) + adapter = AddonAdapter(addonViewModel) + } + + addonViewModel.addonList.collect(viewLifecycleOwner) { + (binding.listAddons.adapter as AddonAdapter).submitList(it) + } + addonViewModel.showModInstallPicker.collect( + viewLifecycleOwner, + resetState = { addonViewModel.showModInstallPicker(false) } + ) { if (it) installAddon.launch(Intent(Intent.ACTION_OPEN_DOCUMENT_TREE).data) } + addonViewModel.showModNoticeDialog.collect( + viewLifecycleOwner, + resetState = { addonViewModel.showModNoticeDialog(false) } + ) { + if (it) { + MessageDialogFragment.newInstance( + requireActivity(), + titleId = R.string.addon_notice, + descriptionId = R.string.addon_notice_description, + dismissible = false, + positiveAction = { addonViewModel.showModInstallPicker(true) }, + negativeAction = {}, + negativeButtonTitleId = R.string.close + ).show(parentFragmentManager, MessageDialogFragment.TAG) + } + } + addonViewModel.addonToDelete.collect( + viewLifecycleOwner, + resetState = { addonViewModel.setAddonToDelete(null) } + ) { + if (it != null) { + MessageDialogFragment.newInstance( + requireActivity(), + titleId = R.string.confirm_uninstall, + descriptionId = R.string.confirm_uninstall_description, + positiveAction = { addonViewModel.onDeleteAddon(it) }, + negativeAction = {} + ).show(parentFragmentManager, MessageDialogFragment.TAG) + } + } + + binding.buttonInstall.setOnClickListener { + ContentTypeSelectionDialogFragment().show( + parentFragmentManager, + ContentTypeSelectionDialogFragment.TAG + ) + } + + setInsets() + } + + override fun onResume() { + super.onResume() + addonViewModel.refreshAddons() + } + + override fun onDestroy() { + super.onDestroy() + addonViewModel.onCloseAddons() + } + + val installAddon = + registerForActivityResult(ActivityResultContracts.OpenDocumentTree()) { result -> + if (result == null) { + return@registerForActivityResult + } + + val externalAddonDirectory = DocumentFile.fromTreeUri(requireContext(), result) + if (externalAddonDirectory == null) { + MessageDialogFragment.newInstance( + requireActivity(), + titleId = R.string.invalid_directory, + descriptionId = R.string.invalid_directory_description + ).show(parentFragmentManager, MessageDialogFragment.TAG) + return@registerForActivityResult + } + + val isValid = externalAddonDirectory.listFiles() + .any { AddonUtil.validAddonDirectories.contains(it.name?.lowercase()) } + val errorMessage = MessageDialogFragment.newInstance( + requireActivity(), + titleId = R.string.invalid_directory, + descriptionId = R.string.invalid_directory_description + ) + if (isValid) { + ProgressDialogFragment.newInstance( + requireActivity(), + R.string.installing_game_content, + false + ) { progressCallback, _ -> + val parentDirectoryName = externalAddonDirectory.name + val internalAddonDirectory = + File(args.game.addonDir + parentDirectoryName) + try { + externalAddonDirectory.copyFilesTo(internalAddonDirectory, progressCallback) + } catch (_: Exception) { + return@newInstance errorMessage + } + addonViewModel.refreshAddons() + return@newInstance getString(R.string.addon_installed_successfully) + }.show(parentFragmentManager, ProgressDialogFragment.TAG) + } else { + errorMessage.show(parentFragmentManager, MessageDialogFragment.TAG) + } + } + + private fun setInsets() = + ViewCompat.setOnApplyWindowInsetsListener( + binding.root + ) { _: View, windowInsets: WindowInsetsCompat -> + val barInsets = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars()) + val cutoutInsets = windowInsets.getInsets(WindowInsetsCompat.Type.displayCutout()) + + val leftInsets = barInsets.left + cutoutInsets.left + val rightInsets = barInsets.right + cutoutInsets.right + + binding.toolbarAddons.updateMargins(left = leftInsets, right = rightInsets) + binding.listAddons.updateMargins(left = leftInsets, right = rightInsets) + binding.listAddons.updatePadding( + bottom = barInsets.bottom + + resources.getDimensionPixelSize(R.dimen.spacing_bottom_list_fab) + ) + + val fabSpacing = resources.getDimensionPixelSize(R.dimen.spacing_fab) + binding.buttonInstall.updateMargins( + left = leftInsets + fabSpacing, + right = rightInsets + fabSpacing, + bottom = barInsets.bottom + fabSpacing + ) + + windowInsets + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/AppletLauncherFragment.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/AppletLauncherFragment.kt new file mode 100644 index 0000000..19c4500 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/AppletLauncherFragment.kt @@ -0,0 +1,106 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.fragments + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.core.view.ViewCompat +import androidx.core.view.WindowInsetsCompat +import androidx.core.view.updatePadding +import androidx.fragment.app.Fragment +import androidx.fragment.app.activityViewModels +import androidx.navigation.findNavController +import androidx.recyclerview.widget.GridLayoutManager +import com.google.android.material.transition.MaterialSharedAxis +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.adapters.AppletAdapter +import org.sudachi.sudachi_emu.databinding.FragmentAppletLauncherBinding +import org.sudachi.sudachi_emu.model.Applet +import org.sudachi.sudachi_emu.model.AppletInfo +import org.sudachi.sudachi_emu.model.HomeViewModel +import org.sudachi.sudachi_emu.utils.ViewUtils.updateMargins + +class AppletLauncherFragment : Fragment() { + private var _binding: FragmentAppletLauncherBinding? = null + private val binding get() = _binding!! + + private val homeViewModel: HomeViewModel by activityViewModels() + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + enterTransition = MaterialSharedAxis(MaterialSharedAxis.X, true) + returnTransition = MaterialSharedAxis(MaterialSharedAxis.X, false) + reenterTransition = MaterialSharedAxis(MaterialSharedAxis.X, false) + } + + override fun onCreateView( + inflater: LayoutInflater, + container: ViewGroup?, + savedInstanceState: Bundle? + ): View { + _binding = FragmentAppletLauncherBinding.inflate(inflater) + return binding.root + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + homeViewModel.setNavigationVisibility(visible = false, animated = true) + homeViewModel.setStatusBarShadeVisibility(visible = false) + + binding.toolbarApplets.setNavigationOnClickListener { + binding.root.findNavController().popBackStack() + } + + val applets = listOf( + Applet( + R.string.album_applet, + R.string.album_applet_description, + R.drawable.ic_album, + AppletInfo.PhotoViewer + ), + Applet( + R.string.cabinet_applet, + R.string.cabinet_applet_description, + R.drawable.ic_nfc, + AppletInfo.Cabinet + ), + Applet( + R.string.mii_edit_applet, + R.string.mii_edit_applet_description, + R.drawable.ic_mii, + AppletInfo.MiiEdit + ) + ) + + binding.listApplets.apply { + layoutManager = GridLayoutManager( + requireContext(), + resources.getInteger(R.integer.grid_columns) + ) + adapter = AppletAdapter(requireActivity(), applets) + } + + setInsets() + } + + private fun setInsets() = + ViewCompat.setOnApplyWindowInsetsListener( + binding.root + ) { _: View, windowInsets: WindowInsetsCompat -> + val barInsets = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars()) + val cutoutInsets = windowInsets.getInsets(WindowInsetsCompat.Type.displayCutout()) + + val leftInsets = barInsets.left + cutoutInsets.left + val rightInsets = barInsets.right + cutoutInsets.right + + binding.toolbarApplets.updateMargins(left = leftInsets, right = rightInsets) + binding.listApplets.updateMargins(left = leftInsets, right = rightInsets) + + binding.listApplets.updatePadding(bottom = barInsets.bottom) + + windowInsets + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/CabinetLauncherDialogFragment.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/CabinetLauncherDialogFragment.kt new file mode 100644 index 0000000..056f31a --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/CabinetLauncherDialogFragment.kt @@ -0,0 +1,41 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.fragments + +import android.app.Dialog +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.fragment.app.DialogFragment +import androidx.recyclerview.widget.LinearLayoutManager +import com.google.android.material.dialog.MaterialAlertDialogBuilder +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.adapters.CabinetLauncherDialogAdapter +import org.sudachi.sudachi_emu.databinding.DialogListBinding + +class CabinetLauncherDialogFragment : DialogFragment() { + private lateinit var binding: DialogListBinding + + override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { + binding = DialogListBinding.inflate(layoutInflater) + binding.dialogList.apply { + layoutManager = LinearLayoutManager(requireContext()) + adapter = CabinetLauncherDialogAdapter(this@CabinetLauncherDialogFragment) + } + + return MaterialAlertDialogBuilder(requireContext()) + .setTitle(R.string.cabinet_launcher) + .setView(binding.root) + .create() + } + + override fun onCreateView( + inflater: LayoutInflater, + container: ViewGroup?, + savedInstanceState: Bundle? + ): View { + return binding.root + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/ContentTypeSelectionDialogFragment.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/ContentTypeSelectionDialogFragment.kt new file mode 100644 index 0000000..384daf0 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/ContentTypeSelectionDialogFragment.kt @@ -0,0 +1,68 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.fragments + +import android.app.Dialog +import android.content.DialogInterface +import android.os.Bundle +import androidx.fragment.app.DialogFragment +import androidx.fragment.app.activityViewModels +import androidx.preference.PreferenceManager +import com.google.android.material.dialog.MaterialAlertDialogBuilder +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.SudachiApplication +import org.sudachi.sudachi_emu.model.AddonViewModel +import org.sudachi.sudachi_emu.ui.main.MainActivity + +class ContentTypeSelectionDialogFragment : DialogFragment() { + private val addonViewModel: AddonViewModel by activityViewModels() + + private val preferences get() = + PreferenceManager.getDefaultSharedPreferences(SudachiApplication.appContext) + + private var selectedItem = 0 + + override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { + val launchOptions = + arrayOf(getString(R.string.updates_and_dlc), getString(R.string.mods_and_cheats)) + + if (savedInstanceState != null) { + selectedItem = savedInstanceState.getInt(SELECTED_ITEM) + } + + val mainActivity = requireActivity() as MainActivity + return MaterialAlertDialogBuilder(requireContext()) + .setTitle(R.string.select_content_type) + .setPositiveButton(android.R.string.ok) { _: DialogInterface, _: Int -> + when (selectedItem) { + 0 -> mainActivity.installGameUpdate.launch(arrayOf("*/*")) + else -> { + if (!preferences.getBoolean(MOD_NOTICE_SEEN, false)) { + preferences.edit().putBoolean(MOD_NOTICE_SEEN, true).apply() + addonViewModel.showModNoticeDialog(true) + return@setPositiveButton + } + addonViewModel.showModInstallPicker(true) + } + } + } + .setSingleChoiceItems(launchOptions, 0) { _: DialogInterface, i: Int -> + selectedItem = i + } + .setNegativeButton(android.R.string.cancel, null) + .show() + } + + override fun onSaveInstanceState(outState: Bundle) { + super.onSaveInstanceState(outState) + outState.putInt(SELECTED_ITEM, selectedItem) + } + + companion object { + const val TAG = "ContentTypeSelectionDialogFragment" + + private const val SELECTED_ITEM = "SelectedItem" + private const val MOD_NOTICE_SEEN = "ModNoticeSeen" + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/CoreErrorDialogFragment.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/CoreErrorDialogFragment.kt new file mode 100644 index 0000000..c750e9e --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/CoreErrorDialogFragment.kt @@ -0,0 +1,47 @@ +// SPDX-FileCopyrightText: 2024 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.fragments + +import android.app.Dialog +import android.content.DialogInterface +import android.os.Bundle +import androidx.fragment.app.DialogFragment +import com.google.android.material.dialog.MaterialAlertDialogBuilder +import org.sudachi.sudachi_emu.NativeLibrary +import org.sudachi.sudachi_emu.R + +class CoreErrorDialogFragment : DialogFragment() { + override fun onCreateDialog(savedInstanceState: Bundle?): Dialog = + MaterialAlertDialogBuilder(requireActivity()) + .setTitle(requireArguments().getString(TITLE)) + .setMessage(requireArguments().getString(MESSAGE)) + .setPositiveButton(R.string.continue_button, null) + .setNegativeButton(R.string.abort_button) { _: DialogInterface?, _: Int -> + NativeLibrary.coreErrorAlertResult = false + synchronized(NativeLibrary.coreErrorAlertLock) { + NativeLibrary.coreErrorAlertLock.notify() + } + } + .create() + + override fun onDismiss(dialog: DialogInterface) { + super.onDismiss(dialog) + NativeLibrary.coreErrorAlertResult = true + synchronized(NativeLibrary.coreErrorAlertLock) { NativeLibrary.coreErrorAlertLock.notify() } + } + + companion object { + const val TITLE = "Title" + const val MESSAGE = "Message" + + fun newInstance(title: String, message: String): CoreErrorDialogFragment { + val frag = CoreErrorDialogFragment() + val args = Bundle() + args.putString(TITLE, title) + args.putString(MESSAGE, message) + frag.arguments = args + return frag + } + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/DriverManagerFragment.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/DriverManagerFragment.kt new file mode 100644 index 0000000..1ff81bc --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/DriverManagerFragment.kt @@ -0,0 +1,199 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.fragments + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.activity.result.contract.ActivityResultContracts +import androidx.core.view.ViewCompat +import androidx.core.view.WindowInsetsCompat +import androidx.core.view.updatePadding +import androidx.fragment.app.Fragment +import androidx.fragment.app.activityViewModels +import androidx.navigation.findNavController +import androidx.navigation.fragment.navArgs +import androidx.recyclerview.widget.GridLayoutManager +import com.google.android.material.transition.MaterialSharedAxis +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.adapters.DriverAdapter +import org.sudachi.sudachi_emu.databinding.FragmentDriverManagerBinding +import org.sudachi.sudachi_emu.features.settings.model.StringSetting +import org.sudachi.sudachi_emu.model.Driver.Companion.toDriver +import org.sudachi.sudachi_emu.model.DriverViewModel +import org.sudachi.sudachi_emu.model.HomeViewModel +import org.sudachi.sudachi_emu.utils.FileUtil +import org.sudachi.sudachi_emu.utils.GpuDriverHelper +import org.sudachi.sudachi_emu.utils.NativeConfig +import org.sudachi.sudachi_emu.utils.ViewUtils.updateMargins +import org.sudachi.sudachi_emu.utils.collect +import java.io.File +import java.io.IOException + +class DriverManagerFragment : Fragment() { + private var _binding: FragmentDriverManagerBinding? = null + private val binding get() = _binding!! + + private val homeViewModel: HomeViewModel by activityViewModels() + private val driverViewModel: DriverViewModel by activityViewModels() + + private val args by navArgs() + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + enterTransition = MaterialSharedAxis(MaterialSharedAxis.X, true) + returnTransition = MaterialSharedAxis(MaterialSharedAxis.X, false) + reenterTransition = MaterialSharedAxis(MaterialSharedAxis.X, false) + } + + override fun onCreateView( + inflater: LayoutInflater, + container: ViewGroup?, + savedInstanceState: Bundle? + ): View { + _binding = FragmentDriverManagerBinding.inflate(inflater) + return binding.root + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + homeViewModel.setNavigationVisibility(visible = false, animated = true) + homeViewModel.setStatusBarShadeVisibility(visible = false) + + driverViewModel.onOpenDriverManager(args.game) + if (NativeConfig.isPerGameConfigLoaded()) { + binding.toolbarDrivers.inflateMenu(R.menu.menu_driver_manager) + driverViewModel.showClearButton(!StringSetting.DRIVER_PATH.global) + binding.toolbarDrivers.setOnMenuItemClickListener { + when (it.itemId) { + R.id.menu_driver_use_global -> { + StringSetting.DRIVER_PATH.global = true + driverViewModel.updateDriverList() + (binding.listDrivers.adapter as DriverAdapter) + .replaceList(driverViewModel.driverList.value) + driverViewModel.showClearButton(false) + true + } + + else -> false + } + } + + driverViewModel.showClearButton.collect(viewLifecycleOwner) { + binding.toolbarDrivers.menu.findItem(R.id.menu_driver_use_global).isVisible = it + } + } + + if (!driverViewModel.isInteractionAllowed.value) { + DriversLoadingDialogFragment().show( + childFragmentManager, + DriversLoadingDialogFragment.TAG + ) + } + + binding.toolbarDrivers.setNavigationOnClickListener { + binding.root.findNavController().popBackStack() + } + + binding.buttonInstall.setOnClickListener { + getDriver.launch(arrayOf("application/zip")) + } + + binding.listDrivers.apply { + layoutManager = GridLayoutManager( + requireContext(), + resources.getInteger(R.integer.grid_columns) + ) + adapter = DriverAdapter(driverViewModel) + } + + setInsets() + } + + override fun onDestroy() { + super.onDestroy() + driverViewModel.onCloseDriverManager(args.game) + } + + private fun setInsets() = + ViewCompat.setOnApplyWindowInsetsListener( + binding.root + ) { _: View, windowInsets: WindowInsetsCompat -> + val barInsets = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars()) + val cutoutInsets = windowInsets.getInsets(WindowInsetsCompat.Type.displayCutout()) + + val leftInsets = barInsets.left + cutoutInsets.left + val rightInsets = barInsets.right + cutoutInsets.right + + binding.toolbarDrivers.updateMargins(left = leftInsets, right = rightInsets) + binding.listDrivers.updateMargins(left = leftInsets, right = rightInsets) + + val fabSpacing = resources.getDimensionPixelSize(R.dimen.spacing_fab) + binding.buttonInstall.updateMargins( + left = leftInsets + fabSpacing, + right = rightInsets + fabSpacing, + bottom = barInsets.bottom + fabSpacing + ) + + binding.listDrivers.updatePadding( + bottom = barInsets.bottom + + resources.getDimensionPixelSize(R.dimen.spacing_bottom_list_fab) + ) + + windowInsets + } + + private val getDriver = + registerForActivityResult(ActivityResultContracts.OpenDocument()) { result -> + if (result == null) { + return@registerForActivityResult + } + + ProgressDialogFragment.newInstance( + requireActivity(), + R.string.installing_driver, + false + ) { _, _ -> + val driverPath = + "${GpuDriverHelper.driverStoragePath}${FileUtil.getFilename(result)}" + val driverFile = File(driverPath) + + // Ignore file exceptions when a user selects an invalid zip + try { + if (!GpuDriverHelper.copyDriverToInternalStorage(result)) { + throw IOException("Driver failed validation!") + } + } catch (_: IOException) { + if (driverFile.exists()) { + driverFile.delete() + } + return@newInstance getString(R.string.select_gpu_driver_error) + } + + val driverData = GpuDriverHelper.getMetadataFromZip(driverFile) + val driverInList = + driverViewModel.driverData.firstOrNull { it.second == driverData } + if (driverInList != null) { + return@newInstance getString(R.string.driver_already_installed) + } else { + driverViewModel.onDriverAdded(Pair(driverPath, driverData)) + withContext(Dispatchers.Main) { + if (_binding != null) { + val adapter = binding.listDrivers.adapter as DriverAdapter + adapter.addItem(driverData.toDriver()) + adapter.selectItem(adapter.currentList.indices.last) + driverViewModel.showClearButton(!StringSetting.DRIVER_PATH.global) + binding.listDrivers + .smoothScrollToPosition(adapter.currentList.indices.last) + } + } + } + return@newInstance Any() + }.show(childFragmentManager, ProgressDialogFragment.TAG) + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/DriversLoadingDialogFragment.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/DriversLoadingDialogFragment.kt new file mode 100644 index 0000000..bb34bd3 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/DriversLoadingDialogFragment.kt @@ -0,0 +1,50 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.fragments + +import android.app.Dialog +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.fragment.app.DialogFragment +import androidx.fragment.app.activityViewModels +import com.google.android.material.dialog.MaterialAlertDialogBuilder +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.databinding.DialogProgressBarBinding +import org.sudachi.sudachi_emu.model.DriverViewModel +import org.sudachi.sudachi_emu.utils.collect + +class DriversLoadingDialogFragment : DialogFragment() { + private val driverViewModel: DriverViewModel by activityViewModels() + + private lateinit var binding: DialogProgressBarBinding + + override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { + binding = DialogProgressBarBinding.inflate(layoutInflater) + binding.progressBar.isIndeterminate = true + + isCancelable = false + + return MaterialAlertDialogBuilder(requireContext()) + .setTitle(R.string.loading) + .setView(binding.root) + .create() + } + + override fun onCreateView( + inflater: LayoutInflater, + container: ViewGroup?, + savedInstanceState: Bundle? + ): View = binding.root + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + driverViewModel.isInteractionAllowed.collect(viewLifecycleOwner) { if (it) dismiss() } + } + + companion object { + const val TAG = "DriversLoadingDialogFragment" + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/EarlyAccessFragment.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/EarlyAccessFragment.kt new file mode 100644 index 0000000..0712521 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/EarlyAccessFragment.kt @@ -0,0 +1,87 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.fragments + +import android.content.Intent +import android.net.Uri +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.core.view.ViewCompat +import androidx.core.view.WindowInsetsCompat +import androidx.core.view.updatePadding +import androidx.fragment.app.Fragment +import androidx.fragment.app.activityViewModels +import androidx.navigation.fragment.findNavController +import com.google.android.material.transition.MaterialSharedAxis +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.databinding.FragmentEarlyAccessBinding +import org.sudachi.sudachi_emu.model.HomeViewModel +import org.sudachi.sudachi_emu.utils.ViewUtils.updateMargins + +class EarlyAccessFragment : Fragment() { + private var _binding: FragmentEarlyAccessBinding? = null + private val binding get() = _binding!! + + private val homeViewModel: HomeViewModel by activityViewModels() + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + enterTransition = MaterialSharedAxis(MaterialSharedAxis.X, true) + returnTransition = MaterialSharedAxis(MaterialSharedAxis.X, false) + } + + override fun onCreateView( + inflater: LayoutInflater, + container: ViewGroup?, + savedInstanceState: Bundle? + ): View { + _binding = FragmentEarlyAccessBinding.inflate(layoutInflater) + return binding.root + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + homeViewModel.setNavigationVisibility(visible = false, animated = true) + homeViewModel.setStatusBarShadeVisibility(visible = false) + + binding.toolbarAbout.setNavigationOnClickListener { + parentFragmentManager.primaryNavigationFragment?.findNavController()?.popBackStack() + } + + binding.getEarlyAccessButton.setOnClickListener { + openLink( + getString(R.string.play_store_link) + ) + } + + setInsets() + } + + private fun openLink(link: String) { + val intent = Intent(Intent.ACTION_VIEW, Uri.parse(link)) + startActivity(intent) + } + + private fun setInsets() = + ViewCompat.setOnApplyWindowInsetsListener( + binding.root + ) { _: View, windowInsets: WindowInsetsCompat -> + val barInsets = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars()) + val cutoutInsets = windowInsets.getInsets(WindowInsetsCompat.Type.displayCutout()) + + val leftInsets = barInsets.left + cutoutInsets.left + val rightInsets = barInsets.right + cutoutInsets.right + + binding.appbarEa.updateMargins(left = leftInsets, right = rightInsets) + + binding.scrollEa.updatePadding( + left = leftInsets, + right = rightInsets, + bottom = barInsets.bottom + ) + + windowInsets + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/EmulationFragment.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/EmulationFragment.kt new file mode 100644 index 0000000..d5ca95d --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/EmulationFragment.kt @@ -0,0 +1,1048 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.fragments + +import android.annotation.SuppressLint +import android.app.AlertDialog +import android.content.Context +import android.content.DialogInterface +import android.content.pm.ActivityInfo +import android.content.res.Configuration +import android.net.Uri +import android.os.Bundle +import android.os.Handler +import android.os.Looper +import android.os.PowerManager +import android.os.SystemClock +import android.util.Rational +import android.view.* +import android.widget.FrameLayout +import android.widget.TextView +import android.widget.Toast +import androidx.activity.OnBackPressedCallback +import androidx.appcompat.widget.PopupMenu +import androidx.core.content.res.ResourcesCompat +import androidx.core.graphics.Insets +import androidx.core.view.ViewCompat +import androidx.core.view.WindowInsetsCompat +import androidx.core.view.updateLayoutParams +import androidx.core.view.updatePadding +import androidx.drawerlayout.widget.DrawerLayout +import androidx.drawerlayout.widget.DrawerLayout.DrawerListener +import androidx.fragment.app.Fragment +import androidx.fragment.app.activityViewModels +import androidx.navigation.findNavController +import androidx.navigation.fragment.navArgs +import androidx.window.layout.FoldingFeature +import androidx.window.layout.WindowInfoTracker +import androidx.window.layout.WindowLayoutInfo +import com.google.android.material.dialog.MaterialAlertDialogBuilder +import com.google.android.material.slider.Slider +import org.sudachi.sudachi_emu.HomeNavigationDirections +import org.sudachi.sudachi_emu.NativeLibrary +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.activities.EmulationActivity +import org.sudachi.sudachi_emu.databinding.DialogOverlayAdjustBinding +import org.sudachi.sudachi_emu.databinding.FragmentEmulationBinding +import org.sudachi.sudachi_emu.features.settings.model.BooleanSetting +import org.sudachi.sudachi_emu.features.settings.model.IntSetting +import org.sudachi.sudachi_emu.features.settings.model.Settings +import org.sudachi.sudachi_emu.features.settings.model.Settings.EmulationOrientation +import org.sudachi.sudachi_emu.features.settings.model.Settings.EmulationVerticalAlignment +import org.sudachi.sudachi_emu.features.settings.utils.SettingsFile +import org.sudachi.sudachi_emu.model.DriverViewModel +import org.sudachi.sudachi_emu.model.Game +import org.sudachi.sudachi_emu.model.EmulationViewModel +import org.sudachi.sudachi_emu.overlay.model.OverlayControl +import org.sudachi.sudachi_emu.overlay.model.OverlayLayout +import org.sudachi.sudachi_emu.utils.* +import org.sudachi.sudachi_emu.utils.ViewUtils.setVisible +import java.lang.NullPointerException + +class EmulationFragment : Fragment(), SurfaceHolder.Callback { + private lateinit var emulationState: EmulationState + private var emulationActivity: EmulationActivity? = null + private var perfStatsUpdater: (() -> Unit)? = null + private var thermalStatsUpdater: (() -> Unit)? = null + + private var _binding: FragmentEmulationBinding? = null + private val binding get() = _binding!! + + private val args by navArgs() + + private lateinit var game: Game + + private val emulationViewModel: EmulationViewModel by activityViewModels() + private val driverViewModel: DriverViewModel by activityViewModels() + + private var isInFoldableLayout = false + + private lateinit var powerManager: PowerManager + + override fun onAttach(context: Context) { + super.onAttach(context) + if (context is EmulationActivity) { + emulationActivity = context + NativeLibrary.setEmulationActivity(context) + } else { + throw IllegalStateException("EmulationFragment must have EmulationActivity parent") + } + } + + /** + * Initialize anything that doesn't depend on the layout / views in here. + */ + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + updateOrientation() + + powerManager = requireContext().getSystemService(Context.POWER_SERVICE) as PowerManager + + val intentUri: Uri? = requireActivity().intent.data + var intentGame: Game? = null + if (intentUri != null) { + intentGame = if (Game.extensions.contains(FileUtil.getExtension(intentUri))) { + GameHelper.getGame(requireActivity().intent.data!!, false) + } else { + null + } + } + + try { + game = if (args.game != null) { + args.game!! + } else { + intentGame!! + } + } catch (e: NullPointerException) { + Toast.makeText( + requireContext(), + R.string.no_game_present, + Toast.LENGTH_SHORT + ).show() + requireActivity().finish() + return + } + + // Always load custom settings when launching a game from an intent + if (args.custom || intentGame != null) { + SettingsFile.loadCustomConfig(game) + NativeConfig.unloadPerGameConfig() + } else { + NativeConfig.reloadGlobalConfig() + } + + // Install the selected driver asynchronously as the game starts + driverViewModel.onLaunchGame() + + // So this fragment doesn't restart on configuration changes; i.e. rotation. + retainInstance = true + emulationState = EmulationState(game.path) { + return@EmulationState driverViewModel.isInteractionAllowed.value + } + } + + /** + * Initialize the UI and start emulation in here. + */ + override fun onCreateView( + inflater: LayoutInflater, + container: ViewGroup?, + savedInstanceState: Bundle? + ): View { + _binding = FragmentEmulationBinding.inflate(layoutInflater) + return binding.root + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + if (requireActivity().isFinishing) { + return + } + + binding.surfaceEmulation.holder.addCallback(this) + binding.doneControlConfig.setOnClickListener { stopConfiguringControls() } + + binding.drawerLayout.addDrawerListener(object : DrawerListener { + override fun onDrawerSlide(drawerView: View, slideOffset: Float) { + binding.surfaceInputOverlay.dispatchTouchEvent( + MotionEvent.obtain( + SystemClock.uptimeMillis(), + SystemClock.uptimeMillis() + 100, + MotionEvent.ACTION_UP, + 0f, + 0f, + 0 + ) + ) + } + + override fun onDrawerOpened(drawerView: View) { + binding.drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED) + binding.inGameMenu.requestFocus() + emulationViewModel.setDrawerOpen(true) + } + + override fun onDrawerClosed(drawerView: View) { + binding.drawerLayout.setDrawerLockMode(IntSetting.LOCK_DRAWER.getInt()) + emulationViewModel.setDrawerOpen(false) + } + + override fun onDrawerStateChanged(newState: Int) { + // No op + } + }) + binding.drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED) + binding.inGameMenu.getHeaderView(0).findViewById(R.id.text_game_title).text = + game.title + + binding.inGameMenu.menu.findItem(R.id.menu_lock_drawer).apply { + val lockMode = IntSetting.LOCK_DRAWER.getInt() + val titleId = if (lockMode == DrawerLayout.LOCK_MODE_LOCKED_CLOSED) { + R.string.unlock_drawer + } else { + R.string.lock_drawer + } + val iconId = if (lockMode == DrawerLayout.LOCK_MODE_UNLOCKED) { + R.drawable.ic_unlock + } else { + R.drawable.ic_lock + } + + title = getString(titleId) + icon = ResourcesCompat.getDrawable( + resources, + iconId, + requireContext().theme + ) + } + + binding.inGameMenu.setNavigationItemSelectedListener { + when (it.itemId) { + R.id.menu_pause_emulation -> { + if (emulationState.isPaused) { + emulationState.run(false) + it.title = resources.getString(R.string.emulation_pause) + it.icon = ResourcesCompat.getDrawable( + resources, + R.drawable.ic_pause, + requireContext().theme + ) + } else { + emulationState.pause() + it.title = resources.getString(R.string.emulation_unpause) + it.icon = ResourcesCompat.getDrawable( + resources, + R.drawable.ic_play, + requireContext().theme + ) + } + binding.inGameMenu.requestFocus() + true + } + + R.id.menu_settings -> { + val action = HomeNavigationDirections.actionGlobalSettingsActivity( + null, + Settings.MenuTag.SECTION_ROOT + ) + binding.inGameMenu.requestFocus() + binding.root.findNavController().navigate(action) + true + } + + R.id.menu_settings_per_game -> { + val action = HomeNavigationDirections.actionGlobalSettingsActivity( + args.game, + Settings.MenuTag.SECTION_ROOT + ) + binding.inGameMenu.requestFocus() + binding.root.findNavController().navigate(action) + true + } + + R.id.menu_controls -> { + val action = HomeNavigationDirections.actionGlobalSettingsActivity( + null, + Settings.MenuTag.SECTION_INPUT + ) + binding.root.findNavController().navigate(action) + true + } + + R.id.menu_overlay_controls -> { + showOverlayOptions() + true + } + + R.id.menu_lock_drawer -> { + when (IntSetting.LOCK_DRAWER.getInt()) { + DrawerLayout.LOCK_MODE_UNLOCKED -> { + IntSetting.LOCK_DRAWER.setInt(DrawerLayout.LOCK_MODE_LOCKED_CLOSED) + it.title = resources.getString(R.string.unlock_drawer) + it.icon = ResourcesCompat.getDrawable( + resources, + R.drawable.ic_lock, + requireContext().theme + ) + } + + DrawerLayout.LOCK_MODE_LOCKED_CLOSED -> { + IntSetting.LOCK_DRAWER.setInt(DrawerLayout.LOCK_MODE_UNLOCKED) + it.title = resources.getString(R.string.lock_drawer) + it.icon = ResourcesCompat.getDrawable( + resources, + R.drawable.ic_unlock, + requireContext().theme + ) + } + } + binding.inGameMenu.requestFocus() + NativeConfig.saveGlobalConfig() + true + } + + R.id.menu_exit -> { + emulationState.stop() + NativeConfig.reloadGlobalConfig() + emulationViewModel.setIsEmulationStopping(true) + binding.drawerLayout.close() + binding.inGameMenu.requestFocus() + true + } + + else -> true + } + } + + setInsets() + + requireActivity().onBackPressedDispatcher.addCallback( + requireActivity(), + object : OnBackPressedCallback(true) { + override fun handleOnBackPressed() { + if (!NativeLibrary.isRunning()) { + return + } + emulationViewModel.setDrawerOpen(!binding.drawerLayout.isOpen) + } + } + ) + + GameIconUtils.loadGameIcon(game, binding.loadingImage) + binding.loadingTitle.text = game.title + binding.loadingTitle.isSelected = true + binding.loadingText.isSelected = true + + WindowInfoTracker.getOrCreate(requireContext()) + .windowLayoutInfo(requireActivity()).collect(viewLifecycleOwner) { + updateFoldableLayout(requireActivity() as EmulationActivity, it) + } + emulationViewModel.shaderProgress.collect(viewLifecycleOwner) { + if (it > 0 && it != emulationViewModel.totalShaders.value) { + binding.loadingProgressIndicator.isIndeterminate = false + + if (it < binding.loadingProgressIndicator.max) { + binding.loadingProgressIndicator.progress = it + } + } + + if (it == emulationViewModel.totalShaders.value) { + binding.loadingText.setText(R.string.loading) + binding.loadingProgressIndicator.isIndeterminate = true + } + } + emulationViewModel.totalShaders.collect(viewLifecycleOwner) { + binding.loadingProgressIndicator.max = it + } + emulationViewModel.shaderMessage.collect(viewLifecycleOwner) { + if (it.isNotEmpty()) { + binding.loadingText.text = it + } + } + + emulationViewModel.emulationStarted.collect(viewLifecycleOwner) { + if (it) { + binding.drawerLayout.setDrawerLockMode(IntSetting.LOCK_DRAWER.getInt()) + ViewUtils.showView(binding.surfaceInputOverlay) + ViewUtils.hideView(binding.loadingIndicator) + + emulationState.updateSurface() + + // Setup overlays + updateShowFpsOverlay() + updateThermalOverlay() + } + } + emulationViewModel.isEmulationStopping.collect(viewLifecycleOwner) { + if (it) { + binding.loadingText.setText(R.string.shutting_down) + ViewUtils.showView(binding.loadingIndicator) + ViewUtils.hideView(binding.inputContainer) + ViewUtils.hideView(binding.showFpsText) + } + } + emulationViewModel.drawerOpen.collect(viewLifecycleOwner) { + if (it) { + binding.drawerLayout.open() + binding.inGameMenu.requestFocus() + } else { + binding.drawerLayout.close() + } + } + emulationViewModel.programChanged.collect(viewLifecycleOwner) { + if (it != 0) { + emulationViewModel.setEmulationStarted(false) + binding.drawerLayout.close() + binding.drawerLayout + .setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED) + ViewUtils.hideView(binding.surfaceInputOverlay) + ViewUtils.showView(binding.loadingIndicator) + } + } + emulationViewModel.emulationStopped.collect(viewLifecycleOwner) { + if (it && emulationViewModel.programChanged.value != -1) { + if (perfStatsUpdater != null) { + perfStatsUpdateHandler.removeCallbacks(perfStatsUpdater!!) + } + emulationState.changeProgram(emulationViewModel.programChanged.value) + emulationViewModel.setProgramChanged(-1) + emulationViewModel.setEmulationStopped(false) + } + } + + driverViewModel.isInteractionAllowed.collect(viewLifecycleOwner) { + if (it) startEmulation() + } + } + + private fun startEmulation(programIndex: Int = 0) { + if (!NativeLibrary.isRunning() && !NativeLibrary.isPaused()) { + if (!DirectoryInitialization.areDirectoriesReady) { + DirectoryInitialization.start() + } + + updateScreenLayout() + + emulationState.run(emulationActivity!!.isActivityRecreated, programIndex) + } + } + + override fun onConfigurationChanged(newConfig: Configuration) { + super.onConfigurationChanged(newConfig) + if (_binding == null) { + return + } + + updateScreenLayout() + val showInputOverlay = BooleanSetting.SHOW_INPUT_OVERLAY.getBoolean() + if (emulationActivity?.isInPictureInPictureMode == true) { + if (binding.drawerLayout.isOpen) { + binding.drawerLayout.close() + } + if (showInputOverlay) { + binding.surfaceInputOverlay.setVisible(visible = false, gone = false) + } + } else { + binding.surfaceInputOverlay.setVisible( + showInputOverlay && emulationViewModel.emulationStarted.value + ) + if (!isInFoldableLayout) { + if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) { + binding.surfaceInputOverlay.layout = OverlayLayout.Portrait + } else { + binding.surfaceInputOverlay.layout = OverlayLayout.Landscape + } + } + } + } + + override fun onPause() { + if (emulationState.isRunning && emulationActivity?.isInPictureInPictureMode != true) { + emulationState.pause() + } + super.onPause() + } + + override fun onDestroyView() { + super.onDestroyView() + _binding = null + } + + override fun onDetach() { + NativeLibrary.clearEmulationActivity() + super.onDetach() + } + + private fun resetInputOverlay() { + IntSetting.OVERLAY_SCALE.reset() + IntSetting.OVERLAY_OPACITY.reset() + binding.surfaceInputOverlay.post { + binding.surfaceInputOverlay.resetLayoutVisibilityAndPlacement() + } + } + + private fun updateShowFpsOverlay() { + val showOverlay = BooleanSetting.SHOW_PERFORMANCE_OVERLAY.getBoolean() + binding.showFpsText.setVisible(showOverlay) + if (showOverlay) { + val SYSTEM_FPS = 0 + val FPS = 1 + val FRAMETIME = 2 + val SPEED = 3 + perfStatsUpdater = { + if (emulationViewModel.emulationStarted.value && + !emulationViewModel.isEmulationStopping.value + ) { + val perfStats = NativeLibrary.getPerfStats() + val cpuBackend = NativeLibrary.getCpuBackend() + val gpuDriver = NativeLibrary.getGpuDriver() + if (_binding != null) { + binding.showFpsText.text = + String.format("FPS: %.1f\n%s/%s", perfStats[FPS], cpuBackend, gpuDriver) + } + perfStatsUpdateHandler.postDelayed(perfStatsUpdater!!, 800) + } + } + perfStatsUpdateHandler.post(perfStatsUpdater!!) + } else { + if (perfStatsUpdater != null) { + perfStatsUpdateHandler.removeCallbacks(perfStatsUpdater!!) + } + } + } + + private fun updateThermalOverlay() { + val showOverlay = BooleanSetting.SHOW_THERMAL_OVERLAY.getBoolean() + binding.showThermalsText.setVisible(showOverlay) + if (showOverlay) { + thermalStatsUpdater = { + if (emulationViewModel.emulationStarted.value && + !emulationViewModel.isEmulationStopping.value + ) { + val thermalStatus = when (powerManager.currentThermalStatus) { + PowerManager.THERMAL_STATUS_LIGHT -> "😥" + PowerManager.THERMAL_STATUS_MODERATE -> "🥵" + PowerManager.THERMAL_STATUS_SEVERE -> "🔥" + PowerManager.THERMAL_STATUS_CRITICAL, + PowerManager.THERMAL_STATUS_EMERGENCY, + PowerManager.THERMAL_STATUS_SHUTDOWN -> "☢️" + + else -> "🙂" + } + if (_binding != null) { + binding.showThermalsText.text = thermalStatus + } + thermalStatsUpdateHandler.postDelayed(thermalStatsUpdater!!, 1000) + } + } + thermalStatsUpdateHandler.post(thermalStatsUpdater!!) + } else { + if (thermalStatsUpdater != null) { + thermalStatsUpdateHandler.removeCallbacks(thermalStatsUpdater!!) + } + } + } + + @SuppressLint("SourceLockedOrientationActivity") + private fun updateOrientation() { + emulationActivity?.let { + val orientationSetting = + EmulationOrientation.from(IntSetting.RENDERER_SCREEN_LAYOUT.getInt()) + it.requestedOrientation = when (orientationSetting) { + EmulationOrientation.Unspecified -> ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED + EmulationOrientation.SensorLandscape -> + ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE + + EmulationOrientation.Landscape -> ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE + EmulationOrientation.ReverseLandscape -> + ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE + + EmulationOrientation.SensorPortrait -> + ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT + + EmulationOrientation.Portrait -> ActivityInfo.SCREEN_ORIENTATION_PORTRAIT + EmulationOrientation.ReversePortrait -> + ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT + } + } + } + + private fun updateScreenLayout() { + val verticalAlignment = + EmulationVerticalAlignment.from(IntSetting.VERTICAL_ALIGNMENT.getInt()) + val aspectRatio = when (IntSetting.RENDERER_ASPECT_RATIO.getInt()) { + 0 -> Rational(16, 9) + 1 -> Rational(4, 3) + 2 -> Rational(21, 9) + 3 -> Rational(16, 10) + else -> null // Best fit + } + when (verticalAlignment) { + EmulationVerticalAlignment.Top -> { + binding.surfaceEmulation.setAspectRatio(aspectRatio) + val params = FrameLayout.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, + ViewGroup.LayoutParams.WRAP_CONTENT + ) + params.gravity = Gravity.TOP or Gravity.CENTER_HORIZONTAL + binding.surfaceEmulation.layoutParams = params + } + + EmulationVerticalAlignment.Center -> { + binding.surfaceEmulation.setAspectRatio(null) + binding.surfaceEmulation.updateLayoutParams { + width = ViewGroup.LayoutParams.MATCH_PARENT + height = ViewGroup.LayoutParams.MATCH_PARENT + } + } + + EmulationVerticalAlignment.Bottom -> { + binding.surfaceEmulation.setAspectRatio(aspectRatio) + val params = + FrameLayout.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, + ViewGroup.LayoutParams.WRAP_CONTENT + ) + params.gravity = Gravity.BOTTOM or Gravity.CENTER_HORIZONTAL + binding.surfaceEmulation.layoutParams = params + } + } + emulationState.updateSurface() + emulationActivity?.buildPictureInPictureParams() + updateOrientation() + } + + private fun updateFoldableLayout( + emulationActivity: EmulationActivity, + newLayoutInfo: WindowLayoutInfo + ) { + val isFolding = + (newLayoutInfo.displayFeatures.find { it is FoldingFeature } as? FoldingFeature)?.let { + if (it.isSeparating) { + emulationActivity.requestedOrientation = + ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED + if (it.orientation == FoldingFeature.Orientation.HORIZONTAL) { + // Restrict emulation and overlays to the top of the screen + binding.emulationContainer.layoutParams.height = it.bounds.top + // Restrict input and menu drawer to the bottom of the screen + binding.inputContainer.layoutParams.height = it.bounds.bottom + binding.inGameMenu.layoutParams.height = it.bounds.bottom + + isInFoldableLayout = true + binding.surfaceInputOverlay.layout = OverlayLayout.Foldable + } + } + it.isSeparating + } ?: false + if (!isFolding) { + binding.emulationContainer.layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT + binding.inputContainer.layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT + binding.inGameMenu.layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT + isInFoldableLayout = false + updateOrientation() + onConfigurationChanged(resources.configuration) + } + binding.emulationContainer.requestLayout() + binding.inputContainer.requestLayout() + binding.inGameMenu.requestLayout() + } + + override fun surfaceCreated(holder: SurfaceHolder) { + // We purposely don't do anything here. + // All work is done in surfaceChanged, which we are guaranteed to get even for surface creation. + } + + override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) { + Log.debug("[EmulationFragment] Surface changed. Resolution: " + width + "x" + height) + emulationState.newSurface(holder.surface) + } + + override fun surfaceDestroyed(holder: SurfaceHolder) { + emulationState.clearSurface() + } + + private fun showOverlayOptions() { + val anchor = binding.inGameMenu.findViewById(R.id.menu_overlay_controls) + val popup = PopupMenu(requireContext(), anchor) + + popup.menuInflater.inflate(R.menu.menu_overlay_options, popup.menu) + + popup.menu.apply { + findItem(R.id.menu_toggle_fps).isChecked = + BooleanSetting.SHOW_PERFORMANCE_OVERLAY.getBoolean() + findItem(R.id.thermal_indicator).isChecked = + BooleanSetting.SHOW_THERMAL_OVERLAY.getBoolean() + findItem(R.id.menu_rel_stick_center).isChecked = + BooleanSetting.JOYSTICK_REL_CENTER.getBoolean() + findItem(R.id.menu_dpad_slide).isChecked = BooleanSetting.DPAD_SLIDE.getBoolean() + findItem(R.id.menu_show_overlay).isChecked = + BooleanSetting.SHOW_INPUT_OVERLAY.getBoolean() + findItem(R.id.menu_haptics).isChecked = BooleanSetting.HAPTIC_FEEDBACK.getBoolean() + findItem(R.id.menu_touchscreen).isChecked = BooleanSetting.TOUCHSCREEN.getBoolean() + } + + popup.setOnDismissListener { NativeConfig.saveGlobalConfig() } + popup.setOnMenuItemClickListener { + when (it.itemId) { + R.id.menu_toggle_fps -> { + it.isChecked = !it.isChecked + BooleanSetting.SHOW_PERFORMANCE_OVERLAY.setBoolean(it.isChecked) + updateShowFpsOverlay() + true + } + + R.id.thermal_indicator -> { + it.isChecked = !it.isChecked + BooleanSetting.SHOW_THERMAL_OVERLAY.setBoolean(it.isChecked) + updateThermalOverlay() + true + } + + R.id.menu_edit_overlay -> { + binding.drawerLayout.close() + binding.surfaceInputOverlay.requestFocus() + startConfiguringControls() + true + } + + R.id.menu_adjust_overlay -> { + adjustOverlay() + true + } + + R.id.menu_toggle_controls -> { + val overlayControlData = NativeConfig.getOverlayControlData() + val optionsArray = BooleanArray(overlayControlData.size) + overlayControlData.forEachIndexed { i, _ -> + optionsArray[i] = overlayControlData.firstOrNull { data -> + OverlayControl.entries[i].id == data.id + }?.enabled == true + } + + val dialog = MaterialAlertDialogBuilder(requireContext()) + .setTitle(R.string.emulation_toggle_controls) + .setMultiChoiceItems( + R.array.gamepadButtons, + optionsArray + ) { _, indexSelected, isChecked -> + overlayControlData.firstOrNull { data -> + OverlayControl.entries[indexSelected].id == data.id + }?.enabled = isChecked + } + .setPositiveButton(android.R.string.ok) { _, _ -> + NativeConfig.setOverlayControlData(overlayControlData) + NativeConfig.saveGlobalConfig() + binding.surfaceInputOverlay.refreshControls() + } + .setNegativeButton(android.R.string.cancel, null) + .setNeutralButton(R.string.emulation_toggle_all) { _, _ -> } + .show() + + // Override normal behaviour so the dialog doesn't close + dialog.getButton(AlertDialog.BUTTON_NEUTRAL) + .setOnClickListener { + val isChecked = !optionsArray[0] + overlayControlData.forEachIndexed { i, _ -> + optionsArray[i] = isChecked + dialog.listView.setItemChecked(i, isChecked) + overlayControlData[i].enabled = isChecked + } + } + true + } + + R.id.menu_show_overlay -> { + it.isChecked = !it.isChecked + BooleanSetting.SHOW_INPUT_OVERLAY.setBoolean(it.isChecked) + binding.surfaceInputOverlay.refreshControls() + true + } + + R.id.menu_rel_stick_center -> { + it.isChecked = !it.isChecked + BooleanSetting.JOYSTICK_REL_CENTER.setBoolean(it.isChecked) + true + } + + R.id.menu_dpad_slide -> { + it.isChecked = !it.isChecked + BooleanSetting.DPAD_SLIDE.setBoolean(it.isChecked) + true + } + + R.id.menu_haptics -> { + it.isChecked = !it.isChecked + BooleanSetting.HAPTIC_FEEDBACK.setBoolean(it.isChecked) + true + } + + R.id.menu_touchscreen -> { + it.isChecked = !it.isChecked + BooleanSetting.TOUCHSCREEN.setBoolean(it.isChecked) + true + } + + R.id.menu_reset_overlay -> { + binding.drawerLayout.close() + resetInputOverlay() + true + } + + else -> true + } + } + + popup.show() + } + + @SuppressLint("SourceLockedOrientationActivity") + private fun startConfiguringControls() { + // Lock the current orientation to prevent editing inconsistencies + if (IntSetting.RENDERER_SCREEN_LAYOUT.getInt() == EmulationOrientation.Unspecified.int) { + emulationActivity?.let { + it.requestedOrientation = + if (resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT) { + ActivityInfo.SCREEN_ORIENTATION_USER_PORTRAIT + } else { + ActivityInfo.SCREEN_ORIENTATION_USER_LANDSCAPE + } + } + } + binding.doneControlConfig.setVisible(true) + binding.surfaceInputOverlay.setIsInEditMode(true) + } + + private fun stopConfiguringControls() { + binding.doneControlConfig.setVisible(false) + binding.surfaceInputOverlay.setIsInEditMode(false) + // Unlock the orientation if it was locked for editing + if (IntSetting.RENDERER_SCREEN_LAYOUT.getInt() == EmulationOrientation.Unspecified.int) { + emulationActivity?.let { + it.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED + } + } + NativeConfig.saveGlobalConfig() + } + + @SuppressLint("SetTextI18n") + private fun adjustOverlay() { + val adjustBinding = DialogOverlayAdjustBinding.inflate(layoutInflater) + adjustBinding.apply { + inputScaleSlider.apply { + valueTo = 150F + value = IntSetting.OVERLAY_SCALE.getInt().toFloat() + addOnChangeListener( + Slider.OnChangeListener { _, value, _ -> + inputScaleValue.text = "${value.toInt()}%" + setControlScale(value.toInt()) + } + ) + } + inputOpacitySlider.apply { + valueTo = 100F + value = IntSetting.OVERLAY_OPACITY.getInt().toFloat() + addOnChangeListener( + Slider.OnChangeListener { _, value, _ -> + inputOpacityValue.text = "${value.toInt()}%" + setControlOpacity(value.toInt()) + } + ) + } + inputScaleValue.text = "${inputScaleSlider.value.toInt()}%" + inputOpacityValue.text = "${inputOpacitySlider.value.toInt()}%" + } + + MaterialAlertDialogBuilder(requireContext()) + .setTitle(R.string.emulation_control_adjust) + .setView(adjustBinding.root) + .setPositiveButton(android.R.string.ok) { _: DialogInterface?, _: Int -> + NativeConfig.saveGlobalConfig() + } + .setNeutralButton(R.string.slider_default) { _: DialogInterface?, _: Int -> + setControlScale(50) + setControlOpacity(100) + } + .show() + } + + private fun setControlScale(scale: Int) { + IntSetting.OVERLAY_SCALE.setInt(scale) + binding.surfaceInputOverlay.refreshControls() + } + + private fun setControlOpacity(opacity: Int) { + IntSetting.OVERLAY_OPACITY.setInt(opacity) + binding.surfaceInputOverlay.refreshControls() + } + + private fun setInsets() { + ViewCompat.setOnApplyWindowInsetsListener( + binding.inGameMenu + ) { v: View, windowInsets: WindowInsetsCompat -> + val cutInsets: Insets = windowInsets.getInsets(WindowInsetsCompat.Type.displayCutout()) + var left = 0 + var right = 0 + if (ViewCompat.getLayoutDirection(v) == ViewCompat.LAYOUT_DIRECTION_LTR) { + left = cutInsets.left + } else { + right = cutInsets.right + } + + v.updatePadding(left = left, top = cutInsets.top, right = right) + windowInsets + } + } + + private class EmulationState( + private val gamePath: String, + private val emulationCanStart: () -> Boolean + ) { + private var state: State + private var surface: Surface? = null + lateinit var emulationThread: Thread + + init { + // Starting state is stopped. + state = State.STOPPED + } + + @get:Synchronized + val isStopped: Boolean + get() = state == State.STOPPED + + // Getters for the current state + @get:Synchronized + val isPaused: Boolean + get() = state == State.PAUSED + + @get:Synchronized + val isRunning: Boolean + get() = state == State.RUNNING + + @Synchronized + fun stop() { + if (state != State.STOPPED) { + Log.debug("[EmulationFragment] Stopping emulation.") + NativeLibrary.stopEmulation() + state = State.STOPPED + } else { + Log.warning("[EmulationFragment] Stop called while already stopped.") + } + } + + // State changing methods + @Synchronized + fun pause() { + if (state != State.PAUSED) { + Log.debug("[EmulationFragment] Pausing emulation.") + + NativeLibrary.pauseEmulation() + + state = State.PAUSED + } else { + Log.warning("[EmulationFragment] Pause called while already paused.") + } + } + + @Synchronized + fun run(isActivityRecreated: Boolean, programIndex: Int = 0) { + if (isActivityRecreated) { + if (NativeLibrary.isRunning()) { + state = State.PAUSED + } + } else { + Log.debug("[EmulationFragment] activity resumed or fresh start") + } + + // If the surface is set, run now. Otherwise, wait for it to get set. + if (surface != null) { + runWithValidSurface(programIndex) + } + } + + @Synchronized + fun changeProgram(programIndex: Int) { + emulationThread.join() + emulationThread = Thread({ + Log.debug("[EmulationFragment] Starting emulation thread.") + NativeLibrary.run(gamePath, programIndex, false) + }, "NativeEmulation") + emulationThread.start() + } + + // Surface callbacks + @Synchronized + fun newSurface(surface: Surface?) { + this.surface = surface + if (this.surface != null) { + runWithValidSurface() + } + } + + @Synchronized + fun updateSurface() { + if (surface != null) { + NativeLibrary.surfaceChanged(surface) + } + } + + @Synchronized + fun clearSurface() { + if (surface == null) { + Log.warning("[EmulationFragment] clearSurface called, but surface already null.") + } else { + surface = null + Log.debug("[EmulationFragment] Surface destroyed.") + when (state) { + State.RUNNING -> { + state = State.PAUSED + } + + State.PAUSED -> Log.warning( + "[EmulationFragment] Surface cleared while emulation paused." + ) + + else -> Log.warning( + "[EmulationFragment] Surface cleared while emulation stopped." + ) + } + } + } + + private fun runWithValidSurface(programIndex: Int = 0) { + NativeLibrary.surfaceChanged(surface) + if (!emulationCanStart.invoke()) { + return + } + + when (state) { + State.STOPPED -> { + emulationThread = Thread({ + Log.debug("[EmulationFragment] Starting emulation thread.") + NativeLibrary.run(gamePath, programIndex, true) + }, "NativeEmulation") + emulationThread.start() + } + + State.PAUSED -> { + Log.debug("[EmulationFragment] Resuming emulation.") + NativeLibrary.unpauseEmulation() + } + + else -> Log.debug("[EmulationFragment] Bug, run called while already running.") + } + state = State.RUNNING + } + + private enum class State { + STOPPED, RUNNING, PAUSED + } + } + + companion object { + private val perfStatsUpdateHandler = Handler(Looper.myLooper()!!) + private val thermalStatsUpdateHandler = Handler(Looper.myLooper()!!) + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/GameFolderPropertiesDialogFragment.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/GameFolderPropertiesDialogFragment.kt new file mode 100644 index 0000000..b75bd53 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/GameFolderPropertiesDialogFragment.kt @@ -0,0 +1,78 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.fragments + +import android.app.Dialog +import android.content.DialogInterface +import android.os.Bundle +import androidx.fragment.app.DialogFragment +import androidx.fragment.app.activityViewModels +import com.google.android.material.dialog.MaterialAlertDialogBuilder +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.databinding.DialogFolderPropertiesBinding +import org.sudachi.sudachi_emu.model.GameDir +import org.sudachi.sudachi_emu.model.GamesViewModel +import org.sudachi.sudachi_emu.utils.NativeConfig +import org.sudachi.sudachi_emu.utils.SerializableHelper.parcelable + +class GameFolderPropertiesDialogFragment : DialogFragment() { + private val gamesViewModel: GamesViewModel by activityViewModels() + + private var deepScan = false + + override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { + val binding = DialogFolderPropertiesBinding.inflate(layoutInflater) + val gameDir = requireArguments().parcelable(GAME_DIR)!! + + // Restore checkbox state + binding.deepScanSwitch.isChecked = + savedInstanceState?.getBoolean(DEEP_SCAN) ?: gameDir.deepScan + + // Ensure that we can get the checkbox state even if the view is destroyed + deepScan = binding.deepScanSwitch.isChecked + binding.deepScanSwitch.setOnClickListener { + deepScan = binding.deepScanSwitch.isChecked + } + + return MaterialAlertDialogBuilder(requireContext()) + .setView(binding.root) + .setTitle(R.string.game_folder_properties) + .setPositiveButton(android.R.string.ok) { _: DialogInterface, _: Int -> + val folderIndex = gamesViewModel.folders.value.indexOf(gameDir) + if (folderIndex != -1) { + gamesViewModel.folders.value[folderIndex].deepScan = + binding.deepScanSwitch.isChecked + gamesViewModel.updateGameDirs() + } + } + .setNegativeButton(android.R.string.cancel, null) + .show() + } + + override fun onStop() { + super.onStop() + NativeConfig.saveGlobalConfig() + } + + override fun onSaveInstanceState(outState: Bundle) { + super.onSaveInstanceState(outState) + outState.putBoolean(DEEP_SCAN, deepScan) + } + + companion object { + const val TAG = "GameFolderPropertiesDialogFragment" + + private const val GAME_DIR = "GameDir" + + private const val DEEP_SCAN = "DeepScan" + + fun newInstance(gameDir: GameDir): GameFolderPropertiesDialogFragment { + val args = Bundle() + args.putParcelable(GAME_DIR, gameDir) + val fragment = GameFolderPropertiesDialogFragment() + fragment.arguments = args + return fragment + } + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/GameFoldersFragment.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/GameFoldersFragment.kt new file mode 100644 index 0000000..ee290c1 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/GameFoldersFragment.kt @@ -0,0 +1,116 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.fragments + +import android.content.Intent +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.core.view.ViewCompat +import androidx.core.view.WindowInsetsCompat +import androidx.core.view.updatePadding +import androidx.fragment.app.Fragment +import androidx.fragment.app.activityViewModels +import androidx.navigation.findNavController +import androidx.recyclerview.widget.GridLayoutManager +import com.google.android.material.transition.MaterialSharedAxis +import kotlinx.coroutines.launch +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.adapters.FolderAdapter +import org.sudachi.sudachi_emu.databinding.FragmentFoldersBinding +import org.sudachi.sudachi_emu.model.GamesViewModel +import org.sudachi.sudachi_emu.model.HomeViewModel +import org.sudachi.sudachi_emu.ui.main.MainActivity +import org.sudachi.sudachi_emu.utils.ViewUtils.updateMargins +import org.sudachi.sudachi_emu.utils.collect + +class GameFoldersFragment : Fragment() { + private var _binding: FragmentFoldersBinding? = null + private val binding get() = _binding!! + + private val homeViewModel: HomeViewModel by activityViewModels() + private val gamesViewModel: GamesViewModel by activityViewModels() + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + enterTransition = MaterialSharedAxis(MaterialSharedAxis.X, true) + returnTransition = MaterialSharedAxis(MaterialSharedAxis.X, false) + reenterTransition = MaterialSharedAxis(MaterialSharedAxis.X, false) + + gamesViewModel.onOpenGameFoldersFragment() + } + + override fun onCreateView( + inflater: LayoutInflater, + container: ViewGroup?, + savedInstanceState: Bundle? + ): View { + _binding = FragmentFoldersBinding.inflate(inflater) + return binding.root + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + homeViewModel.setNavigationVisibility(visible = false, animated = true) + homeViewModel.setStatusBarShadeVisibility(visible = false) + + binding.toolbarFolders.setNavigationOnClickListener { + binding.root.findNavController().popBackStack() + } + + binding.listFolders.apply { + layoutManager = GridLayoutManager( + requireContext(), + resources.getInteger(R.integer.grid_columns) + ) + adapter = FolderAdapter(requireActivity(), gamesViewModel) + } + + gamesViewModel.folders.collect(viewLifecycleOwner) { + (binding.listFolders.adapter as FolderAdapter).submitList(it) + } + + val mainActivity = requireActivity() as MainActivity + binding.buttonAdd.setOnClickListener { + mainActivity.getGamesDirectory.launch(Intent(Intent.ACTION_OPEN_DOCUMENT_TREE).data) + } + + setInsets() + } + + override fun onStop() { + super.onStop() + gamesViewModel.onCloseGameFoldersFragment() + } + + private fun setInsets() = + ViewCompat.setOnApplyWindowInsetsListener( + binding.root + ) { _: View, windowInsets: WindowInsetsCompat -> + val barInsets = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars()) + val cutoutInsets = windowInsets.getInsets(WindowInsetsCompat.Type.displayCutout()) + + val leftInsets = barInsets.left + cutoutInsets.left + val rightInsets = barInsets.right + cutoutInsets.right + + binding.toolbarFolders.updateMargins(left = leftInsets, right = rightInsets) + + val fabSpacing = resources.getDimensionPixelSize(R.dimen.spacing_fab) + binding.buttonAdd.updateMargins( + left = leftInsets + fabSpacing, + right = rightInsets + fabSpacing, + bottom = barInsets.bottom + fabSpacing + ) + + binding.listFolders.updateMargins(left = leftInsets, right = rightInsets) + + binding.listFolders.updatePadding( + bottom = barInsets.bottom + + resources.getDimensionPixelSize(R.dimen.spacing_bottom_list_fab) + ) + + windowInsets + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/GameInfoFragment.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/GameInfoFragment.kt new file mode 100644 index 0000000..9c13afe --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/GameInfoFragment.kt @@ -0,0 +1,179 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.fragments + +import android.content.ClipData +import android.content.ClipboardManager +import android.content.Context +import android.net.Uri +import android.os.Build +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.Toast +import androidx.core.view.ViewCompat +import androidx.core.view.WindowInsetsCompat +import androidx.core.view.updatePadding +import androidx.fragment.app.Fragment +import androidx.fragment.app.activityViewModels +import androidx.navigation.findNavController +import androidx.navigation.fragment.navArgs +import com.google.android.material.transition.MaterialSharedAxis +import org.sudachi.sudachi_emu.NativeLibrary +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.databinding.FragmentGameInfoBinding +import org.sudachi.sudachi_emu.model.GameVerificationResult +import org.sudachi.sudachi_emu.model.HomeViewModel +import org.sudachi.sudachi_emu.utils.GameMetadata +import org.sudachi.sudachi_emu.utils.ViewUtils.setVisible +import org.sudachi.sudachi_emu.utils.ViewUtils.updateMargins + +class GameInfoFragment : Fragment() { + private var _binding: FragmentGameInfoBinding? = null + private val binding get() = _binding!! + + private val homeViewModel: HomeViewModel by activityViewModels() + + private val args by navArgs() + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + enterTransition = MaterialSharedAxis(MaterialSharedAxis.X, true) + returnTransition = MaterialSharedAxis(MaterialSharedAxis.X, false) + reenterTransition = MaterialSharedAxis(MaterialSharedAxis.X, false) + + // Check for an up-to-date version string + args.game.version = GameMetadata.getVersion(args.game.path, true) + } + + override fun onCreateView( + inflater: LayoutInflater, + container: ViewGroup?, + savedInstanceState: Bundle? + ): View { + _binding = FragmentGameInfoBinding.inflate(inflater) + return binding.root + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + homeViewModel.setNavigationVisibility(visible = false, animated = false) + homeViewModel.setStatusBarShadeVisibility(false) + + binding.apply { + toolbarInfo.title = args.game.title + toolbarInfo.setNavigationOnClickListener { + view.findNavController().popBackStack() + } + + val pathString = Uri.parse(args.game.path).path ?: "" + path.setHint(R.string.path) + pathField.setText(pathString) + pathField.setOnClickListener { copyToClipboard(getString(R.string.path), pathString) } + + programId.setHint(R.string.program_id) + programIdField.setText(args.game.programIdHex) + programIdField.setOnClickListener { + copyToClipboard(getString(R.string.program_id), args.game.programIdHex) + } + + if (args.game.developer.isNotEmpty()) { + developer.setHint(R.string.developer) + developerField.setText(args.game.developer) + developerField.setOnClickListener { + copyToClipboard(getString(R.string.developer), args.game.developer) + } + } else { + developer.setVisible(false) + } + + version.setHint(R.string.version) + versionField.setText(args.game.version) + versionField.setOnClickListener { + copyToClipboard(getString(R.string.version), args.game.version) + } + + buttonCopy.setOnClickListener { + val details = """ + ${args.game.title} + ${getString(R.string.path)} - $pathString + ${getString(R.string.program_id)} - ${args.game.programIdHex} + ${getString(R.string.developer)} - ${args.game.developer} + ${getString(R.string.version)} - ${args.game.version} + """.trimIndent() + copyToClipboard(args.game.title, details) + } + + buttonVerifyIntegrity.setOnClickListener { + ProgressDialogFragment.newInstance( + requireActivity(), + R.string.verifying, + true + ) { progressCallback, _ -> + val result = GameVerificationResult.from( + NativeLibrary.verifyGameContents( + args.game.path, + progressCallback + ) + ) + return@newInstance when (result) { + GameVerificationResult.Success -> + MessageDialogFragment.newInstance( + titleId = R.string.verify_success, + descriptionId = R.string.operation_completed_successfully + ) + + GameVerificationResult.Failed -> + MessageDialogFragment.newInstance( + titleId = R.string.verify_failure, + descriptionId = R.string.verify_failure_description + ) + + GameVerificationResult.NotImplemented -> + MessageDialogFragment.newInstance( + titleId = R.string.verify_no_result, + descriptionId = R.string.verify_no_result_description + ) + } + }.show(parentFragmentManager, ProgressDialogFragment.TAG) + } + } + + setInsets() + } + + private fun copyToClipboard(label: String, body: String) { + val clipBoard = + requireContext().getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager + val clip = ClipData.newPlainText(label, body) + clipBoard.setPrimaryClip(clip) + + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) { + Toast.makeText( + requireContext(), + R.string.copied_to_clipboard, + Toast.LENGTH_SHORT + ).show() + } + } + + private fun setInsets() = + ViewCompat.setOnApplyWindowInsetsListener( + binding.root + ) { _: View, windowInsets: WindowInsetsCompat -> + val barInsets = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars()) + val cutoutInsets = windowInsets.getInsets(WindowInsetsCompat.Type.displayCutout()) + + val leftInsets = barInsets.left + cutoutInsets.left + val rightInsets = barInsets.right + cutoutInsets.right + + binding.toolbarInfo.updateMargins(left = leftInsets, right = rightInsets) + binding.scrollInfo.updateMargins(left = leftInsets, right = rightInsets) + + binding.contentInfo.updatePadding(bottom = barInsets.bottom) + + windowInsets + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/GamePropertiesFragment.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/GamePropertiesFragment.kt new file mode 100644 index 0000000..f6b0dd2 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/GamePropertiesFragment.kt @@ -0,0 +1,424 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.fragments + +import android.content.pm.ShortcutInfo +import android.content.pm.ShortcutManager +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.Toast +import androidx.activity.result.contract.ActivityResultContracts +import androidx.core.view.ViewCompat +import androidx.core.view.WindowInsetsCompat +import androidx.core.view.updatePadding +import androidx.fragment.app.Fragment +import androidx.fragment.app.activityViewModels +import androidx.lifecycle.lifecycleScope +import androidx.navigation.findNavController +import androidx.navigation.fragment.navArgs +import androidx.recyclerview.widget.GridLayoutManager +import com.google.android.material.transition.MaterialSharedAxis +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import org.sudachi.sudachi_emu.HomeNavigationDirections +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.SudachiApplication +import org.sudachi.sudachi_emu.adapters.GamePropertiesAdapter +import org.sudachi.sudachi_emu.databinding.FragmentGamePropertiesBinding +import org.sudachi.sudachi_emu.features.settings.model.Settings +import org.sudachi.sudachi_emu.model.DriverViewModel +import org.sudachi.sudachi_emu.model.GameProperty +import org.sudachi.sudachi_emu.model.GamesViewModel +import org.sudachi.sudachi_emu.model.HomeViewModel +import org.sudachi.sudachi_emu.model.InstallableProperty +import org.sudachi.sudachi_emu.model.SubmenuProperty +import org.sudachi.sudachi_emu.model.TaskState +import org.sudachi.sudachi_emu.utils.DirectoryInitialization +import org.sudachi.sudachi_emu.utils.FileUtil +import org.sudachi.sudachi_emu.utils.GameIconUtils +import org.sudachi.sudachi_emu.utils.GpuDriverHelper +import org.sudachi.sudachi_emu.utils.MemoryUtil +import org.sudachi.sudachi_emu.utils.ViewUtils.marquee +import org.sudachi.sudachi_emu.utils.ViewUtils.updateMargins +import org.sudachi.sudachi_emu.utils.collect +import java.io.BufferedOutputStream +import java.io.File + +class GamePropertiesFragment : Fragment() { + private var _binding: FragmentGamePropertiesBinding? = null + private val binding get() = _binding!! + + private val homeViewModel: HomeViewModel by activityViewModels() + private val gamesViewModel: GamesViewModel by activityViewModels() + private val driverViewModel: DriverViewModel by activityViewModels() + + private val args by navArgs() + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + enterTransition = MaterialSharedAxis(MaterialSharedAxis.Y, true) + returnTransition = MaterialSharedAxis(MaterialSharedAxis.Y, false) + reenterTransition = MaterialSharedAxis(MaterialSharedAxis.X, false) + } + + override fun onCreateView( + inflater: LayoutInflater, + container: ViewGroup?, + savedInstanceState: Bundle? + ): View { + _binding = FragmentGamePropertiesBinding.inflate(layoutInflater) + return binding.root + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + homeViewModel.setNavigationVisibility(visible = false, animated = true) + homeViewModel.setStatusBarShadeVisibility(true) + + binding.buttonBack.setOnClickListener { + view.findNavController().popBackStack() + } + + val shortcutManager = requireActivity().getSystemService(ShortcutManager::class.java) + binding.buttonShortcut.isEnabled = shortcutManager.isRequestPinShortcutSupported + binding.buttonShortcut.setOnClickListener { + viewLifecycleOwner.lifecycleScope.launch { + withContext(Dispatchers.IO) { + val shortcut = ShortcutInfo.Builder(requireContext(), args.game.title) + .setShortLabel(args.game.title) + .setIcon( + GameIconUtils.getShortcutIcon(requireActivity(), args.game) + .toIcon(requireContext()) + ) + .setIntent(args.game.launchIntent) + .build() + shortcutManager.requestPinShortcut(shortcut, null) + } + } + } + + GameIconUtils.loadGameIcon(args.game, binding.imageGameScreen) + binding.title.text = args.game.title + binding.title.marquee() + + binding.buttonStart.setOnClickListener { + LaunchGameDialogFragment.newInstance(args.game) + .show(childFragmentManager, LaunchGameDialogFragment.TAG) + } + + reloadList() + + homeViewModel.openImportSaves.collect( + viewLifecycleOwner, + resetState = { homeViewModel.setOpenImportSaves(false) } + ) { if (it) importSaves.launch(arrayOf("application/zip")) } + homeViewModel.reloadPropertiesList.collect( + viewLifecycleOwner, + resetState = { homeViewModel.reloadPropertiesList(false) } + ) { if (it) reloadList() } + + setInsets() + } + + override fun onDestroy() { + super.onDestroy() + gamesViewModel.reloadGames(true) + } + + private fun reloadList() { + _binding ?: return + + driverViewModel.updateDriverNameForGame(args.game) + val properties = mutableListOf().apply { + add( + SubmenuProperty( + R.string.info, + R.string.info_description, + R.drawable.ic_info_outline + ) { + val action = GamePropertiesFragmentDirections + .actionPerGamePropertiesFragmentToGameInfoFragment(args.game) + binding.root.findNavController().navigate(action) + } + ) + add( + SubmenuProperty( + R.string.preferences_settings, + R.string.per_game_settings_description, + R.drawable.ic_settings + ) { + val action = HomeNavigationDirections.actionGlobalSettingsActivity( + args.game, + Settings.MenuTag.SECTION_ROOT + ) + binding.root.findNavController().navigate(action) + } + ) + + if (GpuDriverHelper.supportsCustomDriverLoading()) { + add( + SubmenuProperty( + R.string.gpu_driver_manager, + R.string.install_gpu_driver_description, + R.drawable.ic_build, + detailsFlow = driverViewModel.selectedDriverTitle + ) { + val action = GamePropertiesFragmentDirections + .actionPerGamePropertiesFragmentToDriverManagerFragment(args.game) + binding.root.findNavController().navigate(action) + } + ) + } + + if (!args.game.isHomebrew) { + add( + SubmenuProperty( + R.string.add_ons, + R.string.add_ons_description, + R.drawable.ic_edit + ) { + val action = GamePropertiesFragmentDirections + .actionPerGamePropertiesFragmentToAddonsFragment(args.game) + binding.root.findNavController().navigate(action) + } + ) + add( + InstallableProperty( + R.string.save_data, + R.string.save_data_description, + R.drawable.ic_save, + { + MessageDialogFragment.newInstance( + requireActivity(), + titleId = R.string.import_save_warning, + descriptionId = R.string.import_save_warning_description, + positiveAction = { homeViewModel.setOpenImportSaves(true) } + ).show(parentFragmentManager, MessageDialogFragment.TAG) + }, + if (File(args.game.saveDir).exists()) { + { exportSaves.launch(args.game.saveZipName) } + } else { + null + } + ) + ) + + val saveDirFile = File(args.game.saveDir) + if (saveDirFile.exists()) { + add( + SubmenuProperty( + R.string.delete_save_data, + R.string.delete_save_data_description, + R.drawable.ic_delete, + action = { + MessageDialogFragment.newInstance( + requireActivity(), + titleId = R.string.delete_save_data, + descriptionId = R.string.delete_save_data_warning_description, + positiveButtonTitleId = android.R.string.cancel, + negativeButtonTitleId = android.R.string.ok, + negativeAction = { + File(args.game.saveDir).deleteRecursively() + Toast.makeText( + SudachiApplication.appContext, + R.string.save_data_deleted_successfully, + Toast.LENGTH_SHORT + ).show() + homeViewModel.reloadPropertiesList(true) + } + ).show(parentFragmentManager, MessageDialogFragment.TAG) + } + ) + ) + } + + val shaderCacheDir = File( + DirectoryInitialization.userDirectory + + "/shader/" + args.game.settingsName.lowercase() + ) + if (shaderCacheDir.exists()) { + add( + SubmenuProperty( + R.string.clear_shader_cache, + R.string.clear_shader_cache_description, + R.drawable.ic_delete, + { + if (shaderCacheDir.exists()) { + val bytes = shaderCacheDir.walkTopDown().filter { it.isFile } + .map { it.length() }.sum() + MemoryUtil.bytesToSizeUnit(bytes.toFloat()) + } else { + MemoryUtil.bytesToSizeUnit(0f) + } + } + ) { + MessageDialogFragment.newInstance( + requireActivity(), + titleId = R.string.clear_shader_cache, + descriptionId = R.string.clear_shader_cache_warning_description, + positiveAction = { + shaderCacheDir.deleteRecursively() + Toast.makeText( + SudachiApplication.appContext, + R.string.cleared_shaders_successfully, + Toast.LENGTH_SHORT + ).show() + homeViewModel.reloadPropertiesList(true) + } + ).show(parentFragmentManager, MessageDialogFragment.TAG) + } + ) + } + } + } + binding.listProperties.apply { + layoutManager = + GridLayoutManager(requireContext(), resources.getInteger(R.integer.grid_columns)) + adapter = GamePropertiesAdapter(viewLifecycleOwner, properties) + } + } + + override fun onResume() { + super.onResume() + driverViewModel.updateDriverNameForGame(args.game) + } + + private fun setInsets() = + ViewCompat.setOnApplyWindowInsetsListener( + binding.root + ) { _: View, windowInsets: WindowInsetsCompat -> + val barInsets = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars()) + val cutoutInsets = windowInsets.getInsets(WindowInsetsCompat.Type.displayCutout()) + + val leftInsets = barInsets.left + cutoutInsets.left + val rightInsets = barInsets.right + cutoutInsets.right + + val smallLayout = resources.getBoolean(R.bool.small_layout) + if (smallLayout) { + binding.listAll.updateMargins(left = leftInsets, right = rightInsets) + } else { + if (ViewCompat.getLayoutDirection(binding.root) == + ViewCompat.LAYOUT_DIRECTION_LTR + ) { + binding.listAll.updateMargins(right = rightInsets) + binding.iconLayout!!.updateMargins(top = barInsets.top, left = leftInsets) + } else { + binding.listAll.updateMargins(left = leftInsets) + binding.iconLayout!!.updateMargins(top = barInsets.top, right = rightInsets) + } + } + + val fabSpacing = resources.getDimensionPixelSize(R.dimen.spacing_fab) + binding.buttonStart.updateMargins( + left = leftInsets + fabSpacing, + right = rightInsets + fabSpacing, + bottom = barInsets.bottom + fabSpacing + ) + + binding.layoutAll.updatePadding( + top = barInsets.top, + bottom = barInsets.bottom + + resources.getDimensionPixelSize(R.dimen.spacing_bottom_list_fab) + ) + + windowInsets + } + + private val importSaves = + registerForActivityResult(ActivityResultContracts.OpenDocument()) { result -> + if (result == null) { + return@registerForActivityResult + } + + val savesFolder = File(args.game.saveDir) + val cacheSaveDir = File("${requireContext().cacheDir.path}/saves/") + cacheSaveDir.mkdir() + + ProgressDialogFragment.newInstance( + requireActivity(), + R.string.save_files_importing, + false + ) { _, _ -> + try { + FileUtil.unzipToInternalStorage(result.toString(), cacheSaveDir) + val files = cacheSaveDir.listFiles() + var savesFolderFile: File? = null + if (files != null) { + val savesFolderName = args.game.programIdHex + for (file in files) { + if (file.isDirectory && file.name == savesFolderName) { + savesFolderFile = file + break + } + } + } + + if (savesFolderFile != null) { + savesFolder.deleteRecursively() + savesFolder.mkdir() + savesFolderFile.copyRecursively(savesFolder) + savesFolderFile.deleteRecursively() + } + + withContext(Dispatchers.Main) { + if (savesFolderFile == null) { + MessageDialogFragment.newInstance( + requireActivity(), + titleId = R.string.save_file_invalid_zip_structure, + descriptionId = R.string.save_file_invalid_zip_structure_description + ).show(parentFragmentManager, MessageDialogFragment.TAG) + return@withContext + } + Toast.makeText( + SudachiApplication.appContext, + getString(R.string.save_file_imported_success), + Toast.LENGTH_LONG + ).show() + homeViewModel.reloadPropertiesList(true) + } + + cacheSaveDir.deleteRecursively() + } catch (e: Exception) { + Toast.makeText( + SudachiApplication.appContext, + getString(R.string.fatal_error), + Toast.LENGTH_LONG + ).show() + } + }.show(parentFragmentManager, ProgressDialogFragment.TAG) + } + + /** + * Exports the save file located in the given folder path by creating a zip file and opening a + * file picker to save. + */ + private val exportSaves = registerForActivityResult( + ActivityResultContracts.CreateDocument("application/zip") + ) { result -> + if (result == null) { + return@registerForActivityResult + } + + ProgressDialogFragment.newInstance( + requireActivity(), + R.string.save_files_exporting, + false + ) { _, _ -> + val saveLocation = args.game.saveDir + val zipResult = FileUtil.zipFromInternalStorage( + File(saveLocation), + saveLocation.replaceAfterLast("/", ""), + BufferedOutputStream(requireContext().contentResolver.openOutputStream(result)), + compression = false + ) + return@newInstance when (zipResult) { + TaskState.Completed -> getString(R.string.export_success) + TaskState.Cancelled, TaskState.Failed -> getString(R.string.export_failed) + } + }.show(parentFragmentManager, ProgressDialogFragment.TAG) + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/HomeSettingsFragment.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/HomeSettingsFragment.kt new file mode 100644 index 0000000..a6acd08 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/HomeSettingsFragment.kt @@ -0,0 +1,437 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.fragments + +import android.Manifest +import android.content.ActivityNotFoundException +import android.content.Intent +import android.content.pm.PackageManager +import android.os.Bundle +import android.provider.DocumentsContract +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.Toast +import androidx.appcompat.app.AppCompatActivity +import androidx.core.app.ActivityCompat +import androidx.core.app.NotificationCompat +import androidx.core.app.NotificationManagerCompat +import androidx.core.view.ViewCompat +import androidx.core.view.WindowInsetsCompat +import androidx.core.view.updatePadding +import androidx.documentfile.provider.DocumentFile +import androidx.fragment.app.Fragment +import androidx.fragment.app.activityViewModels +import androidx.navigation.findNavController +import androidx.navigation.fragment.findNavController +import androidx.recyclerview.widget.GridLayoutManager +import com.google.android.material.transition.MaterialSharedAxis +import org.sudachi.sudachi_emu.BuildConfig +import org.sudachi.sudachi_emu.HomeNavigationDirections +import org.sudachi.sudachi_emu.NativeLibrary +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.SudachiApplication +import org.sudachi.sudachi_emu.adapters.HomeSettingAdapter +import org.sudachi.sudachi_emu.databinding.FragmentHomeSettingsBinding +import org.sudachi.sudachi_emu.features.DocumentProvider +import org.sudachi.sudachi_emu.features.settings.model.Settings +import org.sudachi.sudachi_emu.model.DriverViewModel +import org.sudachi.sudachi_emu.model.HomeSetting +import org.sudachi.sudachi_emu.model.HomeViewModel +import org.sudachi.sudachi_emu.ui.main.MainActivity +import org.sudachi.sudachi_emu.utils.FileUtil +import org.sudachi.sudachi_emu.utils.GpuDriverHelper +import org.sudachi.sudachi_emu.utils.Log +import org.sudachi.sudachi_emu.utils.ViewUtils.updateMargins + +class HomeSettingsFragment : Fragment() { + private var _binding: FragmentHomeSettingsBinding? = null + private val binding get() = _binding!! + + private lateinit var mainActivity: MainActivity + + private val homeViewModel: HomeViewModel by activityViewModels() + private val driverViewModel: DriverViewModel by activityViewModels() + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + reenterTransition = MaterialSharedAxis(MaterialSharedAxis.X, false) + } + + override fun onCreateView( + inflater: LayoutInflater, + container: ViewGroup?, + savedInstanceState: Bundle? + ): View { + _binding = FragmentHomeSettingsBinding.inflate(layoutInflater) + return binding.root + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + homeViewModel.setNavigationVisibility(visible = true, animated = true) + homeViewModel.setStatusBarShadeVisibility(visible = true) + mainActivity = requireActivity() as MainActivity + + val optionsList: MutableList = mutableListOf().apply { + add( + HomeSetting( + R.string.advanced_settings, + R.string.settings_description, + R.drawable.ic_settings, + { + val action = HomeNavigationDirections.actionGlobalSettingsActivity( + null, + Settings.MenuTag.SECTION_ROOT + ) + binding.root.findNavController().navigate(action) + } + ) + ) + add( + HomeSetting( + R.string.preferences_controls, + R.string.preferences_controls_description, + R.drawable.ic_controller, + { + val action = HomeNavigationDirections.actionGlobalSettingsActivity( + null, + Settings.MenuTag.SECTION_INPUT + ) + binding.root.findNavController().navigate(action) + } + ) + ) + add( + HomeSetting( + R.string.gpu_driver_manager, + R.string.install_gpu_driver_description, + R.drawable.ic_build, + { + val action = HomeSettingsFragmentDirections + .actionHomeSettingsFragmentToDriverManagerFragment(null) + binding.root.findNavController().navigate(action) + }, + { GpuDriverHelper.supportsCustomDriverLoading() }, + R.string.custom_driver_not_supported, + R.string.custom_driver_not_supported_description, + driverViewModel.selectedDriverTitle + ) + ) + add( + HomeSetting( + R.string.applets, + R.string.applets_description, + R.drawable.ic_applet, + { + binding.root.findNavController() + .navigate(R.id.action_homeSettingsFragment_to_appletLauncherFragment) + }, + { NativeLibrary.isFirmwareAvailable() }, + R.string.applets_error_firmware, + R.string.applets_error_description + ) + ) + add( + HomeSetting( + R.string.manage_sudachi_data, + R.string.manage_sudachi_data_description, + R.drawable.ic_install, + { + binding.root.findNavController() + .navigate(R.id.action_homeSettingsFragment_to_installableFragment) + } + ) + ) + add( + HomeSetting( + R.string.manage_game_folders, + R.string.select_games_folder_description, + R.drawable.ic_add, + { + binding.root.findNavController() + .navigate(R.id.action_homeSettingsFragment_to_gameFoldersFragment) + } + ) + ) + add( + HomeSetting( + R.string.verify_installed_content, + R.string.verify_installed_content_description, + R.drawable.ic_check_circle, + { + ProgressDialogFragment.newInstance( + requireActivity(), + titleId = R.string.verifying, + cancellable = true + ) { progressCallback, _ -> + val result = NativeLibrary.verifyInstalledContents(progressCallback) + return@newInstance if (progressCallback.invoke(100, 100)) { + // Invoke the progress callback to check if the process was cancelled + MessageDialogFragment.newInstance( + titleId = R.string.verify_no_result, + descriptionId = R.string.verify_no_result_description + ) + } else if (result.isEmpty()) { + MessageDialogFragment.newInstance( + titleId = R.string.verify_success, + descriptionId = R.string.operation_completed_successfully + ) + } else { + val failedNames = result.joinToString("\n") + val errorMessage = SudachiApplication.appContext.getString( + R.string.verification_failed_for, + failedNames + ) + MessageDialogFragment.newInstance( + titleId = R.string.verify_failure, + descriptionString = errorMessage + ) + } + }.show(parentFragmentManager, ProgressDialogFragment.TAG) + } + ) + ) + add( + HomeSetting( + R.string.share_log, + R.string.share_log_description, + R.drawable.ic_log, + { shareLog() } + ) + ) + add( + HomeSetting( + R.string.open_user_folder, + R.string.open_user_folder_description, + R.drawable.ic_folder_open, + { openFileManager() } + ) + ) + add( + HomeSetting( + R.string.preferences_theme, + R.string.theme_and_color_description, + R.drawable.ic_palette, + { + val action = HomeNavigationDirections.actionGlobalSettingsActivity( + null, + Settings.MenuTag.SECTION_THEME + ) + binding.root.findNavController().navigate(action) + } + ) + ) + add( + HomeSetting( + R.string.about, + R.string.about_description, + R.drawable.ic_info_outline, + { + exitTransition = MaterialSharedAxis(MaterialSharedAxis.X, true) + parentFragmentManager.primaryNavigationFragment?.findNavController() + ?.navigate(R.id.action_homeSettingsFragment_to_aboutFragment) + } + ) + ) + } + + if (!BuildConfig.PREMIUM) { + optionsList.add( + 0, + HomeSetting( + R.string.get_early_access, + R.string.get_early_access_description, + R.drawable.ic_diamond, + { + exitTransition = MaterialSharedAxis(MaterialSharedAxis.X, true) + parentFragmentManager.primaryNavigationFragment?.findNavController() + ?.navigate(R.id.action_homeSettingsFragment_to_earlyAccessFragment) + } + ) + ) + } + + binding.homeSettingsList.apply { + layoutManager = + GridLayoutManager(requireContext(), resources.getInteger(R.integer.grid_columns)) + adapter = HomeSettingAdapter( + requireActivity() as AppCompatActivity, + viewLifecycleOwner, + optionsList + ) + } + + setInsets() + } + + override fun onStart() { + super.onStart() + exitTransition = null + } + + override fun onResume() { + super.onResume() + driverViewModel.updateDriverNameForGame(null) + } + + override fun onDestroyView() { + super.onDestroyView() + _binding = null + } + + private fun openFileManager() { + // First, try to open the user data folder directly + try { + startActivity(getFileManagerIntentOnDocumentProvider(Intent.ACTION_VIEW)) + return + } catch (_: ActivityNotFoundException) { + } + + try { + startActivity(getFileManagerIntentOnDocumentProvider("android.provider.action.BROWSE")) + return + } catch (_: ActivityNotFoundException) { + } + + // Just try to open the file manager, try the package name used on "normal" phones + try { + startActivity(getFileManagerIntent("com.google.android.documentsui")) + showNoLinkNotification() + return + } catch (_: ActivityNotFoundException) { + } + + try { + // Next, try the AOSP package name + startActivity(getFileManagerIntent("com.android.documentsui")) + showNoLinkNotification() + return + } catch (_: ActivityNotFoundException) { + } + + Toast.makeText( + requireContext(), + resources.getString(R.string.no_file_manager), + Toast.LENGTH_LONG + ).show() + } + + private fun getFileManagerIntent(packageName: String): Intent { + // Fragile, but some phones don't expose the system file manager in any better way + val intent = Intent(Intent.ACTION_MAIN) + intent.setClassName(packageName, "com.android.documentsui.files.FilesActivity") + intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK + return intent + } + + private fun getFileManagerIntentOnDocumentProvider(action: String): Intent { + val authority = "${requireContext().packageName}.user" + val intent = Intent(action) + intent.addCategory(Intent.CATEGORY_DEFAULT) + intent.data = DocumentsContract.buildRootUri(authority, DocumentProvider.ROOT_ID) + intent.addFlags( + Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION or + Intent.FLAG_GRANT_PREFIX_URI_PERMISSION or + Intent.FLAG_GRANT_WRITE_URI_PERMISSION + ) + return intent + } + + private fun showNoLinkNotification() { + val builder = NotificationCompat.Builder( + requireContext(), + getString(R.string.notice_notification_channel_id) + ) + .setSmallIcon(R.drawable.ic_stat_notification_logo) + .setContentTitle(getString(R.string.notification_no_directory_link)) + .setContentText(getString(R.string.notification_no_directory_link_description)) + .setPriority(NotificationCompat.PRIORITY_HIGH) + .setAutoCancel(true) + // TODO: Make the click action for this notification lead to a help article + + with(NotificationManagerCompat.from(requireContext())) { + if (ActivityCompat.checkSelfPermission( + requireContext(), + Manifest.permission.POST_NOTIFICATIONS + ) != PackageManager.PERMISSION_GRANTED + ) { + Toast.makeText( + requireContext(), + resources.getString(R.string.notification_permission_not_granted), + Toast.LENGTH_LONG + ).show() + return + } + notify(0, builder.build()) + } + } + + // Share the current log if we just returned from a game but share the old log + // if we just started the app and the old log exists. + private fun shareLog() { + val currentLog = DocumentFile.fromSingleUri( + mainActivity, + DocumentsContract.buildDocumentUri( + DocumentProvider.AUTHORITY, + "${DocumentProvider.ROOT_ID}/log/sudachi_log.txt" + ) + )!! + val oldLog = DocumentFile.fromSingleUri( + mainActivity, + DocumentsContract.buildDocumentUri( + DocumentProvider.AUTHORITY, + "${DocumentProvider.ROOT_ID}/log/sudachi_log.txt.old.txt" + ) + )!! + + val intent = Intent(Intent.ACTION_SEND) + .setDataAndType(currentLog.uri, FileUtil.TEXT_PLAIN) + .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) + if (!Log.gameLaunched && oldLog.exists()) { + intent.putExtra(Intent.EXTRA_STREAM, oldLog.uri) + startActivity(Intent.createChooser(intent, getText(R.string.share_log))) + } else if (currentLog.exists()) { + intent.putExtra(Intent.EXTRA_STREAM, currentLog.uri) + startActivity(Intent.createChooser(intent, getText(R.string.share_log))) + } else { + Toast.makeText( + requireContext(), + getText(R.string.share_log_missing), + Toast.LENGTH_SHORT + ).show() + } + } + + private fun setInsets() = + ViewCompat.setOnApplyWindowInsetsListener( + binding.root + ) { view: View, windowInsets: WindowInsetsCompat -> + val barInsets = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars()) + val cutoutInsets = windowInsets.getInsets(WindowInsetsCompat.Type.displayCutout()) + val spacingNavigation = resources.getDimensionPixelSize(R.dimen.spacing_navigation) + val spacingNavigationRail = + resources.getDimensionPixelSize(R.dimen.spacing_navigation_rail) + + val leftInsets = barInsets.left + cutoutInsets.left + val rightInsets = barInsets.right + cutoutInsets.right + + binding.scrollViewSettings.updatePadding( + top = barInsets.top, + bottom = barInsets.bottom + ) + + binding.scrollViewSettings.updateMargins(left = leftInsets, right = rightInsets) + + binding.linearLayoutSettings.updatePadding(bottom = spacingNavigation) + + if (ViewCompat.getLayoutDirection(view) == ViewCompat.LAYOUT_DIRECTION_LTR) { + binding.linearLayoutSettings.updatePadding(left = spacingNavigationRail) + } else { + binding.linearLayoutSettings.updatePadding(right = spacingNavigationRail) + } + + windowInsets + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/InstallableFragment.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/InstallableFragment.kt new file mode 100644 index 0000000..18f116e --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/InstallableFragment.kt @@ -0,0 +1,323 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.fragments + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.Toast +import androidx.activity.result.contract.ActivityResultContracts +import androidx.core.view.ViewCompat +import androidx.core.view.WindowInsetsCompat +import androidx.core.view.updatePadding +import androidx.fragment.app.Fragment +import androidx.fragment.app.activityViewModels +import androidx.navigation.findNavController +import androidx.recyclerview.widget.GridLayoutManager +import com.google.android.material.transition.MaterialSharedAxis +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import org.sudachi.sudachi_emu.NativeLibrary +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.SudachiApplication +import org.sudachi.sudachi_emu.adapters.InstallableAdapter +import org.sudachi.sudachi_emu.databinding.FragmentInstallablesBinding +import org.sudachi.sudachi_emu.model.HomeViewModel +import org.sudachi.sudachi_emu.model.Installable +import org.sudachi.sudachi_emu.model.TaskState +import org.sudachi.sudachi_emu.ui.main.MainActivity +import org.sudachi.sudachi_emu.utils.DirectoryInitialization +import org.sudachi.sudachi_emu.utils.FileUtil +import org.sudachi.sudachi_emu.utils.ViewUtils.updateMargins +import org.sudachi.sudachi_emu.utils.collect +import java.io.BufferedOutputStream +import java.io.File +import java.math.BigInteger +import java.time.LocalDateTime +import java.time.format.DateTimeFormatter + +class InstallableFragment : Fragment() { + private var _binding: FragmentInstallablesBinding? = null + private val binding get() = _binding!! + + private val homeViewModel: HomeViewModel by activityViewModels() + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + enterTransition = MaterialSharedAxis(MaterialSharedAxis.X, true) + returnTransition = MaterialSharedAxis(MaterialSharedAxis.X, false) + reenterTransition = MaterialSharedAxis(MaterialSharedAxis.X, false) + } + + override fun onCreateView( + inflater: LayoutInflater, + container: ViewGroup?, + savedInstanceState: Bundle? + ): View { + _binding = FragmentInstallablesBinding.inflate(layoutInflater) + return binding.root + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + + val mainActivity = requireActivity() as MainActivity + + homeViewModel.setNavigationVisibility(visible = false, animated = true) + homeViewModel.setStatusBarShadeVisibility(visible = false) + + binding.toolbarInstallables.setNavigationOnClickListener { + binding.root.findNavController().popBackStack() + } + + homeViewModel.openImportSaves.collect(viewLifecycleOwner) { + if (it) { + importSaves.launch(arrayOf("application/zip")) + homeViewModel.setOpenImportSaves(false) + } + } + + val installables = listOf( + Installable( + R.string.user_data, + R.string.user_data_description, + install = { mainActivity.importUserData.launch(arrayOf("application/zip")) }, + export = { mainActivity.exportUserData.launch("export.zip") } + ), + Installable( + R.string.manage_save_data, + R.string.manage_save_data_description, + install = { + MessageDialogFragment.newInstance( + requireActivity(), + titleId = R.string.import_save_warning, + descriptionId = R.string.import_save_warning_description, + positiveAction = { homeViewModel.setOpenImportSaves(true) } + ).show(parentFragmentManager, MessageDialogFragment.TAG) + }, + export = { + val oldSaveDataFolder = File( + "${DirectoryInitialization.userDirectory}/nand" + + NativeLibrary.getDefaultProfileSaveDataRoot(false) + ) + val futureSaveDataFolder = File( + "${DirectoryInitialization.userDirectory}/nand" + + NativeLibrary.getDefaultProfileSaveDataRoot(true) + ) + if (!oldSaveDataFolder.exists() && !futureSaveDataFolder.exists()) { + Toast.makeText( + SudachiApplication.appContext, + R.string.no_save_data_found, + Toast.LENGTH_SHORT + ).show() + return@Installable + } else { + exportSaves.launch( + "${getString(R.string.save_data)} " + + LocalDateTime.now().format( + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm") + ) + ) + } + } + ), + Installable( + R.string.install_game_content, + R.string.install_game_content_description, + install = { mainActivity.installGameUpdate.launch(arrayOf("*/*")) } + ), + Installable( + R.string.install_firmware, + R.string.install_firmware_description, + install = { mainActivity.getFirmware.launch(arrayOf("application/zip")) } + ), + Installable( + R.string.install_prod_keys, + R.string.install_prod_keys_description, + install = { mainActivity.getProdKey.launch(arrayOf("*/*")) } + ), + Installable( + R.string.install_amiibo_keys, + R.string.install_amiibo_keys_description, + install = { mainActivity.getAmiiboKey.launch(arrayOf("*/*")) } + ) + ) + + binding.listInstallables.apply { + layoutManager = GridLayoutManager( + requireContext(), + resources.getInteger(R.integer.grid_columns) + ) + adapter = InstallableAdapter(installables) + } + + setInsets() + } + + private fun setInsets() = + ViewCompat.setOnApplyWindowInsetsListener( + binding.root + ) { _: View, windowInsets: WindowInsetsCompat -> + val barInsets = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars()) + val cutoutInsets = windowInsets.getInsets(WindowInsetsCompat.Type.displayCutout()) + + val leftInsets = barInsets.left + cutoutInsets.left + val rightInsets = barInsets.right + cutoutInsets.right + + binding.toolbarInstallables.updateMargins(left = leftInsets, right = rightInsets) + binding.listInstallables.updateMargins(left = leftInsets, right = rightInsets) + + binding.listInstallables.updatePadding(bottom = barInsets.bottom) + + windowInsets + } + + private val importSaves = + registerForActivityResult(ActivityResultContracts.OpenDocument()) { result -> + if (result == null) { + return@registerForActivityResult + } + + val cacheSaveDir = File("${requireContext().cacheDir.path}/saves/") + cacheSaveDir.mkdir() + + ProgressDialogFragment.newInstance( + requireActivity(), + R.string.save_files_importing, + false + ) { progressCallback, _ -> + try { + FileUtil.unzipToInternalStorage( + result.toString(), + cacheSaveDir, + progressCallback + ) + val files = cacheSaveDir.listFiles() + var successfulImports = 0 + var failedImports = 0 + if (files != null) { + for (file in files) { + if (file.isDirectory) { + val baseSaveDir = + NativeLibrary.getSavePath(BigInteger(file.name, 16).toString()) + if (baseSaveDir.isEmpty()) { + failedImports++ + continue + } + + val internalSaveFolder = File( + "${DirectoryInitialization.userDirectory}/nand$baseSaveDir" + ) + internalSaveFolder.deleteRecursively() + internalSaveFolder.mkdir() + file.copyRecursively(target = internalSaveFolder, overwrite = true) + successfulImports++ + } + } + } + + withContext(Dispatchers.Main) { + if (successfulImports == 0) { + MessageDialogFragment.newInstance( + requireActivity(), + titleId = R.string.save_file_invalid_zip_structure, + descriptionId = R.string.save_file_invalid_zip_structure_description + ).show(parentFragmentManager, MessageDialogFragment.TAG) + return@withContext + } + val successString = if (failedImports > 0) { + """ + ${ + requireContext().resources.getQuantityString( + R.plurals.saves_import_success, + successfulImports, + successfulImports + ) + } + ${ + requireContext().resources.getQuantityString( + R.plurals.saves_import_failed, + failedImports, + failedImports + ) + } + """ + } else { + requireContext().resources.getQuantityString( + R.plurals.saves_import_success, + successfulImports, + successfulImports + ) + } + MessageDialogFragment.newInstance( + requireActivity(), + titleId = R.string.import_complete, + descriptionString = successString + ).show(parentFragmentManager, MessageDialogFragment.TAG) + } + + cacheSaveDir.deleteRecursively() + } catch (e: Exception) { + Toast.makeText( + SudachiApplication.appContext, + getString(R.string.fatal_error), + Toast.LENGTH_LONG + ).show() + } + }.show(parentFragmentManager, ProgressDialogFragment.TAG) + } + + private val exportSaves = registerForActivityResult( + ActivityResultContracts.CreateDocument("application/zip") + ) { result -> + if (result == null) { + return@registerForActivityResult + } + + ProgressDialogFragment.newInstance( + requireActivity(), + R.string.save_files_exporting, + false + ) { _, _ -> + val cacheSaveDir = File("${requireContext().cacheDir.path}/saves/") + cacheSaveDir.mkdir() + + val oldSaveDataFolder = File( + "${DirectoryInitialization.userDirectory}/nand" + + NativeLibrary.getDefaultProfileSaveDataRoot(false) + ) + if (oldSaveDataFolder.exists()) { + oldSaveDataFolder.copyRecursively(cacheSaveDir) + } + + val futureSaveDataFolder = File( + "${DirectoryInitialization.userDirectory}/nand" + + NativeLibrary.getDefaultProfileSaveDataRoot(true) + ) + if (futureSaveDataFolder.exists()) { + futureSaveDataFolder.copyRecursively(cacheSaveDir) + } + + val saveFilesTotal = cacheSaveDir.listFiles()?.size ?: 0 + if (saveFilesTotal == 0) { + cacheSaveDir.deleteRecursively() + return@newInstance getString(R.string.no_save_data_found) + } + + val zipResult = FileUtil.zipFromInternalStorage( + cacheSaveDir, + cacheSaveDir.path, + BufferedOutputStream(requireContext().contentResolver.openOutputStream(result)) + ) + cacheSaveDir.deleteRecursively() + + return@newInstance when (zipResult) { + TaskState.Completed -> getString(R.string.export_success) + TaskState.Cancelled, TaskState.Failed -> getString(R.string.export_failed) + } + }.show(parentFragmentManager, ProgressDialogFragment.TAG) + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/LaunchGameDialogFragment.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/LaunchGameDialogFragment.kt new file mode 100644 index 0000000..a807bb0 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/LaunchGameDialogFragment.kt @@ -0,0 +1,61 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.fragments + +import android.app.Dialog +import android.content.DialogInterface +import android.os.Bundle +import androidx.fragment.app.DialogFragment +import androidx.navigation.fragment.findNavController +import com.google.android.material.dialog.MaterialAlertDialogBuilder +import org.sudachi.sudachi_emu.HomeNavigationDirections +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.model.Game +import org.sudachi.sudachi_emu.utils.SerializableHelper.parcelable + +class LaunchGameDialogFragment : DialogFragment() { + private var selectedItem = 1 + + override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { + val game = requireArguments().parcelable(GAME) + val launchOptions = arrayOf(getString(R.string.global), getString(R.string.custom)) + + if (savedInstanceState != null) { + selectedItem = savedInstanceState.getInt(SELECTED_ITEM) + } + + return MaterialAlertDialogBuilder(requireContext()) + .setTitle(R.string.launch_options) + .setPositiveButton(android.R.string.ok) { _: DialogInterface, _: Int -> + val action = HomeNavigationDirections + .actionGlobalEmulationActivity(game, selectedItem != 0) + requireParentFragment().findNavController().navigate(action) + } + .setSingleChoiceItems(launchOptions, 1) { _: DialogInterface, i: Int -> + selectedItem = i + } + .setNegativeButton(android.R.string.cancel, null) + .show() + } + + override fun onSaveInstanceState(outState: Bundle) { + super.onSaveInstanceState(outState) + outState.putInt(SELECTED_ITEM, selectedItem) + } + + companion object { + const val TAG = "LaunchGameDialogFragment" + + const val GAME = "Game" + const val SELECTED_ITEM = "SelectedItem" + + fun newInstance(game: Game): LaunchGameDialogFragment { + val args = Bundle() + args.putParcelable(GAME, game) + val fragment = LaunchGameDialogFragment() + fragment.arguments = args + return fragment + } + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/LicenseBottomSheetDialogFragment.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/LicenseBottomSheetDialogFragment.kt new file mode 100644 index 0000000..a525bd3 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/LicenseBottomSheetDialogFragment.kt @@ -0,0 +1,59 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.fragments + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import com.google.android.material.bottomsheet.BottomSheetBehavior +import com.google.android.material.bottomsheet.BottomSheetDialogFragment +import org.sudachi.sudachi_emu.databinding.DialogLicenseBinding +import org.sudachi.sudachi_emu.model.License +import org.sudachi.sudachi_emu.utils.SerializableHelper.parcelable + +class LicenseBottomSheetDialogFragment : BottomSheetDialogFragment() { + private var _binding: DialogLicenseBinding? = null + private val binding get() = _binding!! + + override fun onCreateView( + inflater: LayoutInflater, + container: ViewGroup?, + savedInstanceState: Bundle? + ): View { + _binding = DialogLicenseBinding.inflate(layoutInflater) + return binding.root + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + BottomSheetBehavior.from(view.parent as View).state = + BottomSheetBehavior.STATE_HALF_EXPANDED + + val license = requireArguments().parcelable(LICENSE)!! + + binding.apply { + textTitle.setText(license.titleId) + textLink.setText(license.linkId) + textCopyright.setText(license.copyrightId) + textLicense.setText(license.licenseId) + } + } + + companion object { + const val TAG = "LicenseBottomSheetDialogFragment" + + const val LICENSE = "License" + + fun newInstance( + license: License + ): LicenseBottomSheetDialogFragment { + val dialog = LicenseBottomSheetDialogFragment() + val bundle = Bundle() + bundle.putParcelable(LICENSE, license) + dialog.arguments = bundle + return dialog + } + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/LicensesFragment.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/LicensesFragment.kt new file mode 100644 index 0000000..76dec47 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/LicensesFragment.kt @@ -0,0 +1,132 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.fragments + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.appcompat.app.AppCompatActivity +import androidx.core.view.ViewCompat +import androidx.core.view.WindowInsetsCompat +import androidx.core.view.updatePadding +import androidx.fragment.app.Fragment +import androidx.fragment.app.activityViewModels +import androidx.navigation.findNavController +import androidx.recyclerview.widget.LinearLayoutManager +import com.google.android.material.transition.MaterialSharedAxis +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.adapters.LicenseAdapter +import org.sudachi.sudachi_emu.databinding.FragmentLicensesBinding +import org.sudachi.sudachi_emu.model.HomeViewModel +import org.sudachi.sudachi_emu.model.License +import org.sudachi.sudachi_emu.utils.ViewUtils.updateMargins + +class LicensesFragment : Fragment() { + private var _binding: FragmentLicensesBinding? = null + private val binding get() = _binding!! + + private val homeViewModel: HomeViewModel by activityViewModels() + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + enterTransition = MaterialSharedAxis(MaterialSharedAxis.X, true) + returnTransition = MaterialSharedAxis(MaterialSharedAxis.X, false) + } + + override fun onCreateView( + inflater: LayoutInflater, + container: ViewGroup?, + savedInstanceState: Bundle? + ): View { + _binding = FragmentLicensesBinding.inflate(layoutInflater) + return binding.root + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + homeViewModel.setNavigationVisibility(visible = false, animated = true) + homeViewModel.setStatusBarShadeVisibility(visible = false) + + binding.toolbarLicenses.setNavigationOnClickListener { + binding.root.findNavController().popBackStack() + } + + val licenses = listOf( + License( + R.string.license_fidelityfx_fsr, + R.string.license_fidelityfx_fsr_description, + R.string.license_fidelityfx_fsr_link, + R.string.license_fidelityfx_fsr_copyright, + R.string.license_fidelityfx_fsr_text + ), + License( + R.string.license_cubeb, + R.string.license_cubeb_description, + R.string.license_cubeb_link, + R.string.license_cubeb_copyright, + R.string.license_cubeb_text + ), + License( + R.string.license_dynarmic, + R.string.license_dynarmic_description, + R.string.license_dynarmic_link, + R.string.license_dynarmic_copyright, + R.string.license_dynarmic_text + ), + License( + R.string.license_ffmpeg, + R.string.license_ffmpeg_description, + R.string.license_ffmpeg_link, + R.string.license_ffmpeg_copyright, + R.string.license_ffmpeg_text + ), + License( + R.string.license_opus, + R.string.license_opus_description, + R.string.license_opus_link, + R.string.license_opus_copyright, + R.string.license_opus_text + ), + License( + R.string.license_sirit, + R.string.license_sirit_description, + R.string.license_sirit_link, + R.string.license_sirit_copyright, + R.string.license_sirit_text + ), + License( + R.string.license_adreno_tools, + R.string.license_adreno_tools_description, + R.string.license_adreno_tools_link, + R.string.license_adreno_tools_copyright, + R.string.license_adreno_tools_text + ) + ) + + binding.listLicenses.apply { + layoutManager = LinearLayoutManager(requireContext()) + adapter = LicenseAdapter(requireActivity() as AppCompatActivity, licenses) + } + + setInsets() + } + + private fun setInsets() = + ViewCompat.setOnApplyWindowInsetsListener( + binding.root + ) { _: View, windowInsets: WindowInsetsCompat -> + val barInsets = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars()) + val cutoutInsets = windowInsets.getInsets(WindowInsetsCompat.Type.displayCutout()) + + val leftInsets = barInsets.left + cutoutInsets.left + val rightInsets = barInsets.right + cutoutInsets.right + + binding.appbarLicenses.updateMargins(left = leftInsets, right = rightInsets) + binding.listLicenses.updateMargins(left = leftInsets, right = rightInsets) + + binding.listLicenses.updatePadding(bottom = barInsets.bottom) + + windowInsets + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/MessageDialogFragment.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/MessageDialogFragment.kt new file mode 100644 index 0000000..37f272b --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/MessageDialogFragment.kt @@ -0,0 +1,195 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.fragments + +import android.app.Dialog +import android.content.Intent +import android.net.Uri +import android.os.Bundle +import android.text.Html +import androidx.fragment.app.DialogFragment +import androidx.fragment.app.FragmentActivity +import androidx.fragment.app.activityViewModels +import androidx.lifecycle.ViewModelProvider +import com.google.android.material.dialog.MaterialAlertDialogBuilder +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.model.MessageDialogViewModel +import org.sudachi.sudachi_emu.utils.Log + +class MessageDialogFragment : DialogFragment() { + private val messageDialogViewModel: MessageDialogViewModel by activityViewModels() + + override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { + val titleId = requireArguments().getInt(TITLE_ID) + val title = if (titleId != 0) { + getString(titleId) + } else { + requireArguments().getString(TITLE_STRING)!! + } + + val descriptionId = requireArguments().getInt(DESCRIPTION_ID) + val description = if (descriptionId != 0) { + getString(descriptionId) + } else { + requireArguments().getString(DESCRIPTION_STRING)!! + } + + val positiveButtonId = requireArguments().getInt(POSITIVE_BUTTON_TITLE_ID) + val positiveButtonString = requireArguments().getString(POSITIVE_BUTTON_TITLE_STRING)!! + val positiveButton = if (positiveButtonId != 0) { + getString(positiveButtonId) + } else if (positiveButtonString.isNotEmpty()) { + positiveButtonString + } else if (messageDialogViewModel.positiveAction != null) { + getString(android.R.string.ok) + } else { + getString(R.string.close) + } + + val negativeButtonId = requireArguments().getInt(NEGATIVE_BUTTON_TITLE_ID) + val negativeButtonString = requireArguments().getString(NEGATIVE_BUTTON_TITLE_STRING)!! + val negativeButton = if (negativeButtonId != 0) { + getString(negativeButtonId) + } else if (negativeButtonString.isNotEmpty()) { + negativeButtonString + } else { + getString(android.R.string.cancel) + } + + val helpLinkId = requireArguments().getInt(HELP_LINK) + val dismissible = requireArguments().getBoolean(DISMISSIBLE) + val clearPositiveAction = requireArguments().getBoolean(CLEAR_ACTIONS) + val showNegativeButton = requireArguments().getBoolean(SHOW_NEGATIVE_BUTTON) + + val builder = MaterialAlertDialogBuilder(requireContext()) + + if (clearPositiveAction) { + messageDialogViewModel.positiveAction = null + } + + builder.setPositiveButton(positiveButton) { _, _ -> + messageDialogViewModel.positiveAction?.invoke() + } + if (messageDialogViewModel.negativeAction != null || showNegativeButton) { + builder.setNegativeButton(negativeButton) { _, _ -> + messageDialogViewModel.negativeAction?.invoke() + } + } + + if (title.isNotEmpty()) builder.setTitle(title) + if (description.isNotEmpty()) { + builder.setMessage(Html.fromHtml(description, Html.FROM_HTML_MODE_LEGACY)) + } + + if (helpLinkId != 0) { + builder.setNeutralButton(R.string.learn_more) { _, _ -> + openLink(getString(helpLinkId)) + } + } + + isCancelable = dismissible + + return builder.show() + } + + private fun openLink(link: String) { + val intent = Intent(Intent.ACTION_VIEW, Uri.parse(link)) + startActivity(intent) + } + + companion object { + const val TAG = "MessageDialogFragment" + + private const val TITLE_ID = "Title" + private const val TITLE_STRING = "TitleString" + private const val DESCRIPTION_ID = "DescriptionId" + private const val DESCRIPTION_STRING = "DescriptionString" + private const val HELP_LINK = "Link" + private const val DISMISSIBLE = "Dismissible" + private const val CLEAR_ACTIONS = "ClearActions" + private const val POSITIVE_BUTTON_TITLE_ID = "PositiveButtonTitleId" + private const val POSITIVE_BUTTON_TITLE_STRING = "PositiveButtonTitleString" + private const val SHOW_NEGATIVE_BUTTON = "ShowNegativeButton" + private const val NEGATIVE_BUTTON_TITLE_ID = "NegativeButtonTitleId" + private const val NEGATIVE_BUTTON_TITLE_STRING = "NegativeButtonTitleString" + + /** + * Creates a new [MessageDialogFragment] instance. + * @param activity Activity that will hold a [MessageDialogViewModel] instance if using + * [positiveAction] or [negativeAction]. + * @param titleId String resource ID that will be used for the title. [titleString] used if 0. + * @param titleString String that will be used for the title. No title is set if empty. + * @param descriptionId String resource ID that will be used for the description. + * [descriptionString] used if 0. + * @param descriptionString String that will be used for the description. + * No description is set if empty. + * @param helpLinkId String resource ID that contains a help link. Will be added as a neutral + * button with the title R.string.help. + * @param dismissible Whether the dialog is dismissible or not. Typically used to ensure that + * the user clicks on one of the dialog buttons before closing. + * @param positiveButtonTitleId String resource ID that will be used for the positive button. + * [positiveButtonTitleString] used if 0. + * @param positiveButtonTitleString String that will be used for the positive button. + * android.R.string.close used if empty. android.R.string.ok will be used if [positiveAction] + * is not null. + * @param positiveAction Lambda to run when the positive button is clicked. + * @param showNegativeButton Normally the negative button isn't shown if there is no + * [negativeAction] set. This can override that behavior to always show a button. + * @param negativeButtonTitleId String resource ID that will be used for the negative button. + * [negativeButtonTitleString] used if 0. + * @param negativeButtonTitleString String that will be used for the negative button. + * android.R.string.cancel used if empty. + * @param negativeAction Lambda to run when the negative button is clicked + */ + fun newInstance( + activity: FragmentActivity? = null, + titleId: Int = 0, + titleString: String = "", + descriptionId: Int = 0, + descriptionString: String = "", + helpLinkId: Int = 0, + dismissible: Boolean = true, + positiveButtonTitleId: Int = 0, + positiveButtonTitleString: String = "", + positiveAction: (() -> Unit)? = null, + showNegativeButton: Boolean = false, + negativeButtonTitleId: Int = 0, + negativeButtonTitleString: String = "", + negativeAction: (() -> Unit)? = null + ): MessageDialogFragment { + var clearActions = false + if (activity != null) { + ViewModelProvider(activity)[MessageDialogViewModel::class.java].apply { + clear() + this.positiveAction = positiveAction + this.negativeAction = negativeAction + } + } else { + clearActions = true + } + + if (activity == null && (positiveAction == null || negativeAction == null)) { + Log.warning("[$TAG] Tried to set action with no activity!") + } + + val dialog = MessageDialogFragment() + val bundle = Bundle().apply { + putInt(TITLE_ID, titleId) + putString(TITLE_STRING, titleString) + putInt(DESCRIPTION_ID, descriptionId) + putString(DESCRIPTION_STRING, descriptionString) + putInt(HELP_LINK, helpLinkId) + putBoolean(DISMISSIBLE, dismissible) + putBoolean(CLEAR_ACTIONS, clearActions) + putInt(POSITIVE_BUTTON_TITLE_ID, positiveButtonTitleId) + putString(POSITIVE_BUTTON_TITLE_STRING, positiveButtonTitleString) + putBoolean(SHOW_NEGATIVE_BUTTON, showNegativeButton) + putInt(NEGATIVE_BUTTON_TITLE_ID, negativeButtonTitleId) + putString(NEGATIVE_BUTTON_TITLE_STRING, negativeButtonTitleString) + } + dialog.arguments = bundle + return dialog + } + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/PermissionDeniedDialogFragment.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/PermissionDeniedDialogFragment.kt new file mode 100644 index 0000000..33ccdfb --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/PermissionDeniedDialogFragment.kt @@ -0,0 +1,38 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.fragments + +import android.app.Dialog +import android.content.DialogInterface +import android.content.Intent +import android.net.Uri +import android.os.Bundle +import android.provider.Settings +import androidx.fragment.app.DialogFragment +import com.google.android.material.dialog.MaterialAlertDialogBuilder +import org.sudachi.sudachi_emu.R + +class PermissionDeniedDialogFragment : DialogFragment() { + override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { + return MaterialAlertDialogBuilder(requireContext()) + .setPositiveButton(R.string.home_settings) { _: DialogInterface?, _: Int -> + openSettings() + } + .setNegativeButton(android.R.string.cancel, null) + .setTitle(R.string.permission_denied) + .setMessage(R.string.permission_denied_description) + .show() + } + + private fun openSettings() { + val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS) + val uri = Uri.fromParts("package", requireActivity().packageName, null) + intent.data = uri + startActivity(intent) + } + + companion object { + const val TAG = "PermissionDeniedDialogFragment" + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/ProgressDialogFragment.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/ProgressDialogFragment.kt new file mode 100644 index 0000000..03eaa8d --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/ProgressDialogFragment.kt @@ -0,0 +1,148 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.fragments + +import android.app.Dialog +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.Toast +import androidx.appcompat.app.AlertDialog +import androidx.fragment.app.DialogFragment +import androidx.fragment.app.FragmentActivity +import androidx.fragment.app.activityViewModels +import androidx.lifecycle.ViewModelProvider +import com.google.android.material.dialog.MaterialAlertDialogBuilder +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.databinding.DialogProgressBarBinding +import org.sudachi.sudachi_emu.model.TaskViewModel +import org.sudachi.sudachi_emu.utils.ViewUtils.setVisible +import org.sudachi.sudachi_emu.utils.collect + +class ProgressDialogFragment : DialogFragment() { + private val taskViewModel: TaskViewModel by activityViewModels() + + private lateinit var binding: DialogProgressBarBinding + + private val PROGRESS_BAR_RESOLUTION = 1000 + + override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { + val titleId = requireArguments().getInt(TITLE) + val cancellable = requireArguments().getBoolean(CANCELLABLE) + + binding = DialogProgressBarBinding.inflate(layoutInflater) + binding.progressBar.isIndeterminate = true + val dialog = MaterialAlertDialogBuilder(requireContext()) + .setTitle(titleId) + .setView(binding.root) + + if (cancellable) { + dialog.setNegativeButton(android.R.string.cancel, null) + } + + val alertDialog = dialog.create() + alertDialog.setCanceledOnTouchOutside(false) + + if (!taskViewModel.isRunning.value) { + taskViewModel.runTask() + } + return alertDialog + } + + override fun onCreateView( + inflater: LayoutInflater, + container: ViewGroup?, + savedInstanceState: Bundle? + ): View { + return binding.root + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + binding.message.isSelected = true + taskViewModel.isComplete.collect(viewLifecycleOwner) { + if (it) { + dismiss() + when (val result = taskViewModel.result.value) { + is String -> Toast.makeText( + requireContext(), + result, + Toast.LENGTH_LONG + ).show() + + is MessageDialogFragment -> result.show( + requireActivity().supportFragmentManager, + MessageDialogFragment.TAG + ) + + else -> { + // Do nothing + } + } + taskViewModel.clear() + } + } + taskViewModel.cancelled.collect(viewLifecycleOwner) { + if (it) { + dialog?.setTitle(R.string.cancelling) + } + } + taskViewModel.progress.collect(viewLifecycleOwner) { + if (it != 0.0) { + binding.progressBar.apply { + isIndeterminate = false + progress = ( + (it / taskViewModel.maxProgress.value) * + PROGRESS_BAR_RESOLUTION + ).toInt() + min = 0 + max = PROGRESS_BAR_RESOLUTION + } + } + } + taskViewModel.message.collect(viewLifecycleOwner) { + binding.message.setVisible(it.isNotEmpty()) + binding.message.text = it + } + } + + // By default, the ProgressDialog will immediately dismiss itself upon a button being pressed. + // Setting the OnClickListener again after the dialog is shown overrides this behavior. + override fun onResume() { + super.onResume() + val alertDialog = dialog as AlertDialog + val negativeButton = alertDialog.getButton(Dialog.BUTTON_NEGATIVE) + negativeButton.setOnClickListener { + alertDialog.setTitle(getString(R.string.cancelling)) + binding.progressBar.isIndeterminate = true + taskViewModel.setCancelled(true) + } + } + + companion object { + const val TAG = "IndeterminateProgressDialogFragment" + + private const val TITLE = "Title" + private const val CANCELLABLE = "Cancellable" + + fun newInstance( + activity: FragmentActivity, + titleId: Int, + cancellable: Boolean = false, + task: suspend ( + progressCallback: (max: Long, progress: Long) -> Boolean, + messageCallback: (message: String) -> Unit + ) -> Any + ): ProgressDialogFragment { + val dialog = ProgressDialogFragment() + val args = Bundle() + ViewModelProvider(activity)[TaskViewModel::class.java].task = task + args.putInt(TITLE, titleId) + args.putBoolean(CANCELLABLE, cancellable) + dialog.arguments = args + return dialog + } + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/ResetSettingsDialogFragment.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/ResetSettingsDialogFragment.kt new file mode 100644 index 0000000..8a82475 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/ResetSettingsDialogFragment.kt @@ -0,0 +1,30 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.fragments + +import android.app.Dialog +import android.os.Bundle +import androidx.fragment.app.DialogFragment +import com.google.android.material.dialog.MaterialAlertDialogBuilder +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.features.settings.ui.SettingsActivity + +class ResetSettingsDialogFragment : DialogFragment() { + override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { + val settingsActivity = requireActivity() as SettingsActivity + + return MaterialAlertDialogBuilder(requireContext()) + .setTitle(R.string.reset_all_settings) + .setMessage(R.string.reset_all_settings_description) + .setPositiveButton(android.R.string.ok) { _, _ -> + settingsActivity.onSettingsReset() + } + .setNegativeButton(android.R.string.cancel, null) + .show() + } + + companion object { + const val TAG = "ResetSettingsDialogFragment" + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/SearchFragment.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/SearchFragment.kt new file mode 100644 index 0000000..803e00c --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/SearchFragment.kt @@ -0,0 +1,218 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.fragments + +import android.content.Context +import android.content.SharedPreferences +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.view.inputmethod.InputMethodManager +import androidx.appcompat.app.AppCompatActivity +import androidx.core.view.ViewCompat +import androidx.core.view.WindowInsetsCompat +import androidx.core.view.updatePadding +import androidx.core.widget.doOnTextChanged +import androidx.fragment.app.Fragment +import androidx.fragment.app.activityViewModels +import androidx.preference.PreferenceManager +import info.debatty.java.stringsimilarity.Jaccard +import info.debatty.java.stringsimilarity.JaroWinkler +import java.util.Locale +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.SudachiApplication +import org.sudachi.sudachi_emu.adapters.GameAdapter +import org.sudachi.sudachi_emu.databinding.FragmentSearchBinding +import org.sudachi.sudachi_emu.layout.AutofitGridLayoutManager +import org.sudachi.sudachi_emu.model.Game +import org.sudachi.sudachi_emu.model.GamesViewModel +import org.sudachi.sudachi_emu.model.HomeViewModel +import org.sudachi.sudachi_emu.utils.ViewUtils.setVisible +import org.sudachi.sudachi_emu.utils.collect + +class SearchFragment : Fragment() { + private var _binding: FragmentSearchBinding? = null + private val binding get() = _binding!! + + private val gamesViewModel: GamesViewModel by activityViewModels() + private val homeViewModel: HomeViewModel by activityViewModels() + + private lateinit var preferences: SharedPreferences + + companion object { + private const val SEARCH_TEXT = "SearchText" + } + + override fun onCreateView( + inflater: LayoutInflater, + container: ViewGroup?, + savedInstanceState: Bundle? + ): View { + _binding = FragmentSearchBinding.inflate(layoutInflater) + return binding.root + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + homeViewModel.setNavigationVisibility(visible = true, animated = true) + homeViewModel.setStatusBarShadeVisibility(true) + preferences = PreferenceManager.getDefaultSharedPreferences(SudachiApplication.appContext) + + if (savedInstanceState != null) { + binding.searchText.setText(savedInstanceState.getString(SEARCH_TEXT)) + } + + binding.gridGamesSearch.apply { + layoutManager = AutofitGridLayoutManager( + requireContext(), + requireContext().resources.getDimensionPixelSize(R.dimen.card_width) + ) + adapter = GameAdapter(requireActivity() as AppCompatActivity) + } + + binding.chipGroup.setOnCheckedStateChangeListener { _, _ -> filterAndSearch() } + + binding.searchText.doOnTextChanged { text: CharSequence?, _: Int, _: Int, _: Int -> + binding.clearButton.setVisible(text.toString().isNotEmpty()) + filterAndSearch() + } + + gamesViewModel.searchFocused.collect( + viewLifecycleOwner, + resetState = { gamesViewModel.setSearchFocused(false) } + ) { if (it) focusSearch() } + gamesViewModel.games.collect(viewLifecycleOwner) { filterAndSearch() } + gamesViewModel.searchedGames.collect(viewLifecycleOwner) { + (binding.gridGamesSearch.adapter as GameAdapter).submitList(it) + binding.noResultsView.setVisible(it.isNotEmpty()) + } + + binding.clearButton.setOnClickListener { binding.searchText.setText("") } + + binding.searchBackground.setOnClickListener { focusSearch() } + + setInsets() + filterAndSearch() + } + + private inner class ScoredGame(val score: Double, val item: Game) + + private fun filterAndSearch() { + val baseList = gamesViewModel.games.value + val filteredList: List = when (binding.chipGroup.checkedChipId) { + R.id.chip_recently_played -> { + baseList.filter { + val lastPlayedTime = preferences.getLong(it.keyLastPlayedTime, 0L) + lastPlayedTime > (System.currentTimeMillis() - 24 * 60 * 60 * 1000) + }.sortedByDescending { preferences.getLong(it.keyLastPlayedTime, 0L) } + } + + R.id.chip_recently_added -> { + baseList.filter { + val addedTime = preferences.getLong(it.keyAddedToLibraryTime, 0L) + addedTime > (System.currentTimeMillis() - 24 * 60 * 60 * 1000) + }.sortedByDescending { preferences.getLong(it.keyAddedToLibraryTime, 0L) } + } + + R.id.chip_homebrew -> baseList.filter { it.isHomebrew } + + R.id.chip_retail -> baseList.filter { !it.isHomebrew } + + else -> baseList + } + + if (binding.searchText.text.toString().isEmpty() && + binding.chipGroup.checkedChipId != View.NO_ID + ) { + gamesViewModel.setSearchedGames(filteredList) + return + } + + val searchTerm = binding.searchText.text.toString().lowercase(Locale.getDefault()) + val searchAlgorithm = if (searchTerm.length > 1) Jaccard(2) else JaroWinkler() + val sortedList: List = filteredList.mapNotNull { game -> + val title = game.title.lowercase(Locale.getDefault()) + val score = searchAlgorithm.similarity(searchTerm, title) + if (score > 0.03) { + ScoredGame(score, game) + } else { + null + } + }.sortedByDescending { it.score }.map { it.item } + gamesViewModel.setSearchedGames(sortedList) + } + + override fun onDestroyView() { + super.onDestroyView() + _binding = null + } + + override fun onSaveInstanceState(outState: Bundle) { + super.onSaveInstanceState(outState) + if (_binding != null) { + outState.putString(SEARCH_TEXT, binding.searchText.text.toString()) + } + } + + private fun focusSearch() { + if (_binding != null) { + binding.searchText.requestFocus() + val imm = requireActivity() + .getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager? + imm?.showSoftInput(binding.searchText, InputMethodManager.SHOW_IMPLICIT) + } + } + + private fun setInsets() = + ViewCompat.setOnApplyWindowInsetsListener( + binding.root + ) { view: View, windowInsets: WindowInsetsCompat -> + val barInsets = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars()) + val cutoutInsets = windowInsets.getInsets(WindowInsetsCompat.Type.displayCutout()) + val extraListSpacing = resources.getDimensionPixelSize(R.dimen.spacing_med) + val spacingNavigation = resources.getDimensionPixelSize(R.dimen.spacing_navigation) + val spacingNavigationRail = + resources.getDimensionPixelSize(R.dimen.spacing_navigation_rail) + val chipSpacing = resources.getDimensionPixelSize(R.dimen.spacing_chip) + + binding.constraintSearch.updatePadding( + left = barInsets.left + cutoutInsets.left, + top = barInsets.top, + right = barInsets.right + cutoutInsets.right + ) + + binding.gridGamesSearch.updatePadding( + top = extraListSpacing, + bottom = barInsets.bottom + spacingNavigation + extraListSpacing + ) + binding.noResultsView.updatePadding(bottom = spacingNavigation + barInsets.bottom) + + val mlpDivider = binding.divider.layoutParams as ViewGroup.MarginLayoutParams + if (ViewCompat.getLayoutDirection(view) == ViewCompat.LAYOUT_DIRECTION_LTR) { + binding.frameSearch.updatePadding(left = spacingNavigationRail) + binding.gridGamesSearch.updatePadding(left = spacingNavigationRail) + binding.noResultsView.updatePadding(left = spacingNavigationRail) + binding.chipGroup.updatePadding( + left = chipSpacing + spacingNavigationRail, + right = chipSpacing + ) + mlpDivider.leftMargin = chipSpacing + spacingNavigationRail + mlpDivider.rightMargin = chipSpacing + } else { + binding.frameSearch.updatePadding(right = spacingNavigationRail) + binding.gridGamesSearch.updatePadding(right = spacingNavigationRail) + binding.noResultsView.updatePadding(right = spacingNavigationRail) + binding.chipGroup.updatePadding( + left = chipSpacing, + right = chipSpacing + spacingNavigationRail + ) + mlpDivider.leftMargin = chipSpacing + mlpDivider.rightMargin = chipSpacing + spacingNavigationRail + } + binding.divider.layoutParams = mlpDivider + + windowInsets + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/SetupFragment.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/SetupFragment.kt new file mode 100644 index 0000000..a5d504b --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/SetupFragment.kt @@ -0,0 +1,396 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.fragments + +import android.Manifest +import android.content.Intent +import android.os.Build +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.activity.OnBackPressedCallback +import androidx.activity.result.contract.ActivityResultContracts +import androidx.annotation.RequiresApi +import androidx.appcompat.app.AppCompatActivity +import androidx.core.app.NotificationManagerCompat +import androidx.core.content.ContextCompat +import androidx.core.view.ViewCompat +import androidx.core.view.WindowInsetsCompat +import androidx.core.view.isVisible +import androidx.core.view.updatePadding +import androidx.fragment.app.Fragment +import androidx.fragment.app.activityViewModels +import androidx.navigation.findNavController +import androidx.preference.PreferenceManager +import androidx.viewpager2.widget.ViewPager2.OnPageChangeCallback +import com.google.android.material.transition.MaterialFadeThrough +import kotlinx.coroutines.launch +import org.sudachi.sudachi_emu.NativeLibrary +import java.io.File +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.SudachiApplication +import org.sudachi.sudachi_emu.adapters.SetupAdapter +import org.sudachi.sudachi_emu.databinding.FragmentSetupBinding +import org.sudachi.sudachi_emu.features.settings.model.Settings +import org.sudachi.sudachi_emu.model.HomeViewModel +import org.sudachi.sudachi_emu.model.SetupCallback +import org.sudachi.sudachi_emu.model.SetupPage +import org.sudachi.sudachi_emu.model.StepState +import org.sudachi.sudachi_emu.ui.main.MainActivity +import org.sudachi.sudachi_emu.utils.DirectoryInitialization +import org.sudachi.sudachi_emu.utils.NativeConfig +import org.sudachi.sudachi_emu.utils.ViewUtils +import org.sudachi.sudachi_emu.utils.ViewUtils.setVisible +import org.sudachi.sudachi_emu.utils.collect + +class SetupFragment : Fragment() { + private var _binding: FragmentSetupBinding? = null + private val binding get() = _binding!! + + private val homeViewModel: HomeViewModel by activityViewModels() + + private lateinit var mainActivity: MainActivity + + private lateinit var hasBeenWarned: BooleanArray + + companion object { + const val KEY_NEXT_VISIBILITY = "NextButtonVisibility" + const val KEY_BACK_VISIBILITY = "BackButtonVisibility" + const val KEY_HAS_BEEN_WARNED = "HasBeenWarned" + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + exitTransition = MaterialFadeThrough() + } + + override fun onCreateView( + inflater: LayoutInflater, + container: ViewGroup?, + savedInstanceState: Bundle? + ): View { + _binding = FragmentSetupBinding.inflate(layoutInflater) + return binding.root + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + mainActivity = requireActivity() as MainActivity + + homeViewModel.setNavigationVisibility(visible = false, animated = false) + + requireActivity().onBackPressedDispatcher.addCallback( + viewLifecycleOwner, + object : OnBackPressedCallback(true) { + override fun handleOnBackPressed() { + if (binding.viewPager2.currentItem > 0) { + pageBackward() + } else { + requireActivity().finish() + } + } + } + ) + + requireActivity().window.navigationBarColor = + ContextCompat.getColor(requireContext(), android.R.color.transparent) + + val pages = mutableListOf() + pages.apply { + add( + SetupPage( + R.drawable.ic_sudachi_title, + R.string.welcome, + R.string.welcome_description, + 0, + true, + R.string.get_started, + { pageForward() }, + false + ) + ) + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + add( + SetupPage( + R.drawable.ic_notification, + R.string.notifications, + R.string.notifications_description, + 0, + false, + R.string.give_permission, + { + notificationCallback = it + permissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS) + }, + true, + R.string.notification_warning, + R.string.notification_warning_description, + 0, + { + if (NotificationManagerCompat.from(requireContext()) + .areNotificationsEnabled() + ) { + StepState.COMPLETE + } else { + StepState.INCOMPLETE + } + } + ) + ) + } + + add( + SetupPage( + R.drawable.ic_key, + R.string.keys, + R.string.keys_description, + R.drawable.ic_add, + true, + R.string.select_keys, + { + keyCallback = it + getProdKey.launch(arrayOf("*/*")) + }, + true, + R.string.install_prod_keys_warning, + R.string.install_prod_keys_warning_description, + R.string.install_prod_keys_warning_help, + { + val file = File(DirectoryInitialization.userDirectory + "/keys/prod.keys") + if (file.exists() && NativeLibrary.areKeysPresent()) { + StepState.COMPLETE + } else { + StepState.INCOMPLETE + } + } + ) + ) + add( + SetupPage( + R.drawable.ic_controller, + R.string.games, + R.string.games_description, + R.drawable.ic_add, + true, + R.string.add_games, + { + gamesDirCallback = it + getGamesDirectory.launch(Intent(Intent.ACTION_OPEN_DOCUMENT_TREE).data) + }, + true, + R.string.add_games_warning, + R.string.add_games_warning_description, + R.string.add_games_warning_help, + { + if (NativeConfig.getGameDirs().isNotEmpty()) { + StepState.COMPLETE + } else { + StepState.INCOMPLETE + } + } + ) + ) + add( + SetupPage( + R.drawable.ic_check, + R.string.done, + R.string.done_description, + R.drawable.ic_arrow_forward, + false, + R.string.text_continue, + { finishSetup() }, + false + ) + ) + } + + homeViewModel.shouldPageForward.collect( + viewLifecycleOwner, + resetState = { homeViewModel.setShouldPageForward(false) } + ) { if (it) pageForward() } + homeViewModel.gamesDirSelected.collect( + viewLifecycleOwner, + resetState = { homeViewModel.setGamesDirSelected(false) } + ) { if (it) gamesDirCallback.onStepCompleted() } + + binding.viewPager2.apply { + adapter = SetupAdapter(requireActivity() as AppCompatActivity, pages) + offscreenPageLimit = 2 + isUserInputEnabled = false + } + + binding.viewPager2.registerOnPageChangeCallback(object : OnPageChangeCallback() { + var previousPosition: Int = 0 + + override fun onPageSelected(position: Int) { + super.onPageSelected(position) + + if (position == 1 && previousPosition == 0) { + ViewUtils.showView(binding.buttonNext) + ViewUtils.showView(binding.buttonBack) + } else if (position == 0 && previousPosition == 1) { + ViewUtils.hideView(binding.buttonBack) + ViewUtils.hideView(binding.buttonNext) + } else if (position == pages.size - 1 && previousPosition == pages.size - 2) { + ViewUtils.hideView(binding.buttonNext) + } else if (position == pages.size - 2 && previousPosition == pages.size - 1) { + ViewUtils.showView(binding.buttonNext) + } + + previousPosition = position + } + }) + + binding.buttonNext.setOnClickListener { + val index = binding.viewPager2.currentItem + val currentPage = pages[index] + + // Checks if the user has completed the task on the current page + if (currentPage.hasWarning) { + val stepState = currentPage.stepCompleted.invoke() + if (stepState != StepState.INCOMPLETE) { + pageForward() + return@setOnClickListener + } + + if (!hasBeenWarned[index]) { + SetupWarningDialogFragment.newInstance( + currentPage.warningTitleId, + currentPage.warningDescriptionId, + currentPage.warningHelpLinkId, + index + ).show(childFragmentManager, SetupWarningDialogFragment.TAG) + return@setOnClickListener + } + } + pageForward() + } + binding.buttonBack.setOnClickListener { pageBackward() } + + if (savedInstanceState != null) { + val nextIsVisible = savedInstanceState.getBoolean(KEY_NEXT_VISIBILITY) + val backIsVisible = savedInstanceState.getBoolean(KEY_BACK_VISIBILITY) + hasBeenWarned = savedInstanceState.getBooleanArray(KEY_HAS_BEEN_WARNED)!! + + binding.buttonNext.setVisible(nextIsVisible) + binding.buttonBack.setVisible(backIsVisible) + } else { + hasBeenWarned = BooleanArray(pages.size) + } + + setInsets() + } + + override fun onStop() { + super.onStop() + NativeConfig.saveGlobalConfig() + } + + override fun onSaveInstanceState(outState: Bundle) { + super.onSaveInstanceState(outState) + if (_binding != null) { + outState.putBoolean(KEY_NEXT_VISIBILITY, binding.buttonNext.isVisible) + outState.putBoolean(KEY_BACK_VISIBILITY, binding.buttonBack.isVisible) + } + outState.putBooleanArray(KEY_HAS_BEEN_WARNED, hasBeenWarned) + } + + override fun onDestroyView() { + super.onDestroyView() + _binding = null + } + + private lateinit var notificationCallback: SetupCallback + + @RequiresApi(Build.VERSION_CODES.TIRAMISU) + private val permissionLauncher = + registerForActivityResult(ActivityResultContracts.RequestPermission()) { + if (it) { + notificationCallback.onStepCompleted() + } + + if (!it && + !shouldShowRequestPermissionRationale(Manifest.permission.POST_NOTIFICATIONS) + ) { + PermissionDeniedDialogFragment().show( + childFragmentManager, + PermissionDeniedDialogFragment.TAG + ) + } + } + + private lateinit var keyCallback: SetupCallback + + val getProdKey = + registerForActivityResult(ActivityResultContracts.OpenDocument()) { result -> + if (result != null) { + mainActivity.processKey(result) + if (NativeLibrary.areKeysPresent()) { + keyCallback.onStepCompleted() + } + } + } + + private lateinit var gamesDirCallback: SetupCallback + + val getGamesDirectory = + registerForActivityResult(ActivityResultContracts.OpenDocumentTree()) { result -> + if (result != null) { + mainActivity.processGamesDir(result) + } + } + + private fun finishSetup() { + PreferenceManager.getDefaultSharedPreferences(SudachiApplication.appContext).edit() + .putBoolean(Settings.PREF_FIRST_APP_LAUNCH, false) + .apply() + mainActivity.finishSetup(binding.root.findNavController()) + } + + fun pageForward() { + if (_binding != null) { + binding.viewPager2.currentItem += 1 + } + } + + fun pageBackward() { + if (_binding != null) { + binding.viewPager2.currentItem -= 1 + } + } + + fun setPageWarned(page: Int) { + hasBeenWarned[page] = true + } + + private fun setInsets() = + ViewCompat.setOnApplyWindowInsetsListener( + binding.root + ) { _: View, windowInsets: WindowInsetsCompat -> + val barInsets = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars()) + val cutoutInsets = windowInsets.getInsets(WindowInsetsCompat.Type.displayCutout()) + + val leftPadding = barInsets.left + cutoutInsets.left + val topPadding = barInsets.top + cutoutInsets.top + val rightPadding = barInsets.right + cutoutInsets.right + val bottomPadding = barInsets.bottom + cutoutInsets.bottom + + if (resources.getBoolean(R.bool.small_layout)) { + binding.viewPager2 + .updatePadding(left = leftPadding, top = topPadding, right = rightPadding) + binding.constraintButtons + .updatePadding(left = leftPadding, right = rightPadding, bottom = bottomPadding) + } else { + binding.viewPager2.updatePadding(top = topPadding, bottom = bottomPadding) + binding.constraintButtons + .updatePadding( + left = leftPadding, + right = rightPadding, + bottom = bottomPadding + ) + } + windowInsets + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/SetupWarningDialogFragment.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/SetupWarningDialogFragment.kt new file mode 100644 index 0000000..f964594 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/fragments/SetupWarningDialogFragment.kt @@ -0,0 +1,86 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.fragments + +import android.app.Dialog +import android.content.DialogInterface +import android.content.Intent +import android.net.Uri +import android.os.Bundle +import androidx.fragment.app.DialogFragment +import com.google.android.material.dialog.MaterialAlertDialogBuilder +import org.sudachi.sudachi_emu.R + +class SetupWarningDialogFragment : DialogFragment() { + private var titleId: Int = 0 + private var descriptionId: Int = 0 + private var helpLinkId: Int = 0 + private var page: Int = 0 + + private lateinit var setupFragment: SetupFragment + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + titleId = requireArguments().getInt(TITLE) + descriptionId = requireArguments().getInt(DESCRIPTION) + helpLinkId = requireArguments().getInt(HELP_LINK) + page = requireArguments().getInt(PAGE) + + setupFragment = requireParentFragment() as SetupFragment + } + + override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { + val builder = MaterialAlertDialogBuilder(requireContext()) + .setPositiveButton(R.string.warning_skip) { _: DialogInterface?, _: Int -> + setupFragment.pageForward() + setupFragment.setPageWarned(page) + } + .setNegativeButton(R.string.warning_cancel, null) + + if (titleId != 0) { + builder.setTitle(titleId) + } else { + builder.setTitle("") + } + if (descriptionId != 0) { + builder.setMessage(descriptionId) + } + if (helpLinkId != 0) { + builder.setNeutralButton(R.string.warning_help) { _: DialogInterface?, _: Int -> + val helpLink = resources.getString(R.string.install_prod_keys_warning_help) + val intent = Intent(Intent.ACTION_VIEW, Uri.parse(helpLink)) + startActivity(intent) + } + } + + return builder.show() + } + + companion object { + const val TAG = "SetupWarningDialogFragment" + + private const val TITLE = "Title" + private const val DESCRIPTION = "Description" + private const val HELP_LINK = "HelpLink" + private const val PAGE = "Page" + + fun newInstance( + titleId: Int, + descriptionId: Int, + helpLinkId: Int, + page: Int + ): SetupWarningDialogFragment { + val dialog = SetupWarningDialogFragment() + val bundle = Bundle() + bundle.apply { + putInt(TITLE, titleId) + putInt(DESCRIPTION, descriptionId) + putInt(HELP_LINK, helpLinkId) + putInt(PAGE, page) + } + dialog.arguments = bundle + return dialog + } + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/layout/AutofitGridLayoutManager.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/layout/AutofitGridLayoutManager.kt new file mode 100644 index 0000000..aedda0e --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/layout/AutofitGridLayoutManager.kt @@ -0,0 +1,63 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.layout + +import android.content.Context +import androidx.recyclerview.widget.GridLayoutManager +import androidx.recyclerview.widget.RecyclerView +import androidx.recyclerview.widget.RecyclerView.Recycler +import org.sudachi.sudachi_emu.R + +/** + * Cut down version of the solution provided here + * https://stackoverflow.com/questions/26666143/recyclerview-gridlayoutmanager-how-to-auto-detect-span-count + */ +class AutofitGridLayoutManager( + context: Context, + columnWidth: Int +) : GridLayoutManager(context, 1) { + private var columnWidth = 0 + private var isColumnWidthChanged = true + private var lastWidth = 0 + private var lastHeight = 0 + + init { + setColumnWidth(checkedColumnWidth(context, columnWidth)) + } + + private fun checkedColumnWidth(context: Context, columnWidth: Int): Int { + var newColumnWidth = columnWidth + if (newColumnWidth <= 0) { + newColumnWidth = context.resources.getDimensionPixelSize(R.dimen.spacing_xtralarge) + } + return newColumnWidth + } + + private fun setColumnWidth(newColumnWidth: Int) { + if (newColumnWidth > 0 && newColumnWidth != columnWidth) { + columnWidth = newColumnWidth + isColumnWidthChanged = true + } + } + + override fun onLayoutChildren(recycler: Recycler, state: RecyclerView.State) { + val width = width + val height = height + if (columnWidth > 0 && width > 0 && height > 0 && + (isColumnWidthChanged || lastWidth != width || lastHeight != height) + ) { + val totalSpace: Int = if (orientation == VERTICAL) { + width - paddingRight - paddingLeft + } else { + height - paddingTop - paddingBottom + } + val spanCount = 1.coerceAtLeast(totalSpace / columnWidth) + setSpanCount(spanCount) + isColumnWidthChanged = false + } + lastWidth = width + lastHeight = height + super.onLayoutChildren(recycler, state) + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/Addon.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/Addon.kt new file mode 100644 index 0000000..bedbc37 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/Addon.kt @@ -0,0 +1,10 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.model + +data class Addon( + var enabled: Boolean, + val title: String, + val version: String +) diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/AddonViewModel.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/AddonViewModel.kt new file mode 100644 index 0000000..b83ad2f --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/AddonViewModel.kt @@ -0,0 +1,97 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.model + +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import org.sudachi.sudachi_emu.NativeLibrary +import org.sudachi.sudachi_emu.utils.NativeConfig +import java.util.concurrent.atomic.AtomicBoolean + +class AddonViewModel : ViewModel() { + private val _patchList = MutableStateFlow(mutableListOf()) + val addonList get() = _patchList.asStateFlow() + + private val _showModInstallPicker = MutableStateFlow(false) + val showModInstallPicker get() = _showModInstallPicker.asStateFlow() + + private val _showModNoticeDialog = MutableStateFlow(false) + val showModNoticeDialog get() = _showModNoticeDialog.asStateFlow() + + private val _addonToDelete = MutableStateFlow(null) + val addonToDelete = _addonToDelete.asStateFlow() + + var game: Game? = null + + private val isRefreshing = AtomicBoolean(false) + + fun onOpenAddons(game: Game) { + this.game = game + refreshAddons() + } + + fun refreshAddons() { + if (isRefreshing.get() || game == null) { + return + } + isRefreshing.set(true) + viewModelScope.launch { + withContext(Dispatchers.IO) { + val patchList = ( + NativeLibrary.getPatchesForFile(game!!.path, game!!.programId) + ?: emptyArray() + ).toMutableList() + patchList.sortBy { it.name } + _patchList.value = patchList + isRefreshing.set(false) + } + } + } + + fun setAddonToDelete(patch: Patch?) { + _addonToDelete.value = patch + } + + fun onDeleteAddon(patch: Patch) { + when (PatchType.from(patch.type)) { + PatchType.Update -> NativeLibrary.removeUpdate(patch.programId) + PatchType.DLC -> NativeLibrary.removeDLC(patch.programId) + PatchType.Mod -> NativeLibrary.removeMod(patch.programId, patch.name) + } + refreshAddons() + } + + fun onCloseAddons() { + if (_patchList.value.isEmpty()) { + return + } + + NativeConfig.setDisabledAddons( + game!!.programId, + _patchList.value.mapNotNull { + if (it.enabled) { + null + } else { + it.name + } + }.toTypedArray() + ) + NativeConfig.saveGlobalConfig() + _patchList.value.clear() + game = null + } + + fun showModInstallPicker(install: Boolean) { + _showModInstallPicker.value = install + } + + fun showModNoticeDialog(show: Boolean) { + _showModNoticeDialog.value = show + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/Applet.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/Applet.kt new file mode 100644 index 0000000..a7c9aef --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/Applet.kt @@ -0,0 +1,55 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.model + +import androidx.annotation.DrawableRes +import androidx.annotation.StringRes +import org.sudachi.sudachi_emu.R + +data class Applet( + @StringRes val titleId: Int, + @StringRes val descriptionId: Int, + @DrawableRes val iconId: Int, + val appletInfo: AppletInfo, + val cabinetMode: CabinetMode = CabinetMode.None +) + +// Combination of Common::AM::Applets::AppletId enum and the entry id +enum class AppletInfo(val appletId: Int, val entryId: Long = 0) { + None(0x00), + Application(0x01), + OverlayDisplay(0x02), + QLaunch(0x03), + Starter(0x04), + Auth(0x0A), + Cabinet(0x0B, 0x0100000000001002), + Controller(0x0C), + DataErase(0x0D), + Error(0x0E), + NetConnect(0x0F), + ProfileSelect(0x10), + SoftwareKeyboard(0x11), + MiiEdit(0x12, 0x0100000000001009), + Web(0x13), + Shop(0x14), + PhotoViewer(0x015, 0x010000000000100D), + Settings(0x16), + OfflineWeb(0x17), + LoginShare(0x18), + WebAuth(0x19), + MyPage(0x1A) +} + +// Matches enum in Service::NFP::CabinetMode with extra metadata +enum class CabinetMode( + val id: Int, + @StringRes val titleId: Int = 0, + @DrawableRes val iconId: Int = 0 +) { + None(-1), + StartNicknameAndOwnerSettings(0, R.string.cabinet_nickname_and_owner, R.drawable.ic_edit), + StartGameDataEraser(1, R.string.cabinet_game_data_eraser, R.drawable.ic_refresh), + StartRestorer(2, R.string.cabinet_restorer, R.drawable.ic_restore), + StartFormatter(3, R.string.cabinet_formatter, R.drawable.ic_clear) +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/Driver.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/Driver.kt new file mode 100644 index 0000000..756fa25 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/Driver.kt @@ -0,0 +1,27 @@ +// SPDX-FileCopyrightText: 2024 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.model + +import org.sudachi.sudachi_emu.utils.GpuDriverMetadata + +data class Driver( + override var selected: Boolean, + val title: String, + val version: String = "", + val description: String = "" +) : SelectableItem { + override fun onSelectionStateChanged(selected: Boolean) { + this.selected = selected + } + + companion object { + fun GpuDriverMetadata.toDriver(selected: Boolean = false): Driver = + Driver( + selected, + this.name ?: "", + this.version ?: "", + this.description ?: "" + ) + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/DriverViewModel.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/DriverViewModel.kt new file mode 100644 index 0000000..de2604a --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/DriverViewModel.kt @@ -0,0 +1,196 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.model + +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.SharingStarted +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.stateIn +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.SudachiApplication +import org.sudachi.sudachi_emu.features.settings.model.StringSetting +import org.sudachi.sudachi_emu.features.settings.utils.SettingsFile +import org.sudachi.sudachi_emu.model.Driver.Companion.toDriver +import org.sudachi.sudachi_emu.utils.GpuDriverHelper +import org.sudachi.sudachi_emu.utils.GpuDriverMetadata +import org.sudachi.sudachi_emu.utils.NativeConfig +import java.io.File + +class DriverViewModel : ViewModel() { + private val _areDriversLoading = MutableStateFlow(false) + private val _isDriverReady = MutableStateFlow(true) + private val _isDeletingDrivers = MutableStateFlow(false) + + val isInteractionAllowed: StateFlow = + combine( + _areDriversLoading, + _isDriverReady, + _isDeletingDrivers + ) { loading, ready, deleting -> + !loading && ready && !deleting + }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(), initialValue = false) + + var driverData = GpuDriverHelper.getDrivers() + + private val _driverList = MutableStateFlow(emptyList()) + val driverList: StateFlow> get() = _driverList + + // Used for showing which driver is currently installed within the driver manager card + private val _selectedDriverTitle = MutableStateFlow("") + val selectedDriverTitle: StateFlow get() = _selectedDriverTitle + + private val _showClearButton = MutableStateFlow(false) + val showClearButton = _showClearButton.asStateFlow() + + private val driversToDelete = mutableListOf() + + init { + updateDriverList() + updateDriverNameForGame(null) + } + + fun reloadDriverData() { + _areDriversLoading.value = true + driverData = GpuDriverHelper.getDrivers() + updateDriverList() + _areDriversLoading.value = false + } + + fun updateDriverList() { + val selectedDriver = GpuDriverHelper.customDriverSettingData + val systemDriverData = GpuDriverHelper.getSystemDriverInfo() + val newDriverList = mutableListOf( + Driver( + selectedDriver == GpuDriverMetadata(), + SudachiApplication.appContext.getString(R.string.system_gpu_driver), + systemDriverData?.get(0) ?: "", + systemDriverData?.get(1) ?: "" + ) + ) + driverData.forEach { + newDriverList.add(it.second.toDriver(it.second == selectedDriver)) + } + _driverList.value = newDriverList + } + + fun onOpenDriverManager(game: Game?) { + if (game != null) { + SettingsFile.loadCustomConfig(game) + } + updateDriverList() + } + + fun showClearButton(value: Boolean) { + _showClearButton.value = value + } + + fun onDriverSelected(position: Int) { + if (position == 0) { + StringSetting.DRIVER_PATH.setString("") + } else { + StringSetting.DRIVER_PATH.setString(driverData[position - 1].first) + } + } + + fun onDriverRemoved(removedPosition: Int, selectedPosition: Int) { + driversToDelete.add(driverData[removedPosition - 1].first) + driverData.removeAt(removedPosition - 1) + onDriverSelected(selectedPosition) + } + + fun onDriverAdded(driver: Pair) { + if (driversToDelete.contains(driver.first)) { + driversToDelete.remove(driver.first) + } + driverData.add(driver) + onDriverSelected(driverData.size) + } + + fun onCloseDriverManager(game: Game?) { + _isDeletingDrivers.value = true + updateDriverNameForGame(game) + if (game == null) { + NativeConfig.saveGlobalConfig() + } else { + NativeConfig.savePerGameConfig() + NativeConfig.unloadPerGameConfig() + NativeConfig.reloadGlobalConfig() + } + + viewModelScope.launch { + withContext(Dispatchers.IO) { + driversToDelete.forEach { + val driver = File(it) + if (driver.exists()) { + driver.delete() + } + } + driversToDelete.clear() + _isDeletingDrivers.value = false + } + } + } + + // It is the Emulation Fragment's responsibility to load per-game settings so that this function + // knows what driver to load. + fun onLaunchGame() { + _isDriverReady.value = false + + val selectedDriverFile = File(StringSetting.DRIVER_PATH.getString()) + val selectedDriverMetadata = GpuDriverHelper.customDriverSettingData + if (GpuDriverHelper.installedCustomDriverData == selectedDriverMetadata) { + setDriverReady() + return + } + + viewModelScope.launch { + withContext(Dispatchers.IO) { + if (selectedDriverMetadata.name == null) { + GpuDriverHelper.installDefaultDriver() + setDriverReady() + return@withContext + } + + if (selectedDriverFile.exists()) { + GpuDriverHelper.installCustomDriver(selectedDriverFile) + } else { + GpuDriverHelper.installDefaultDriver() + } + setDriverReady() + } + } + } + + fun updateDriverNameForGame(game: Game?) { + if (!GpuDriverHelper.supportsCustomDriverLoading()) { + return + } + + if (game == null || NativeConfig.isPerGameConfigLoaded()) { + updateName() + } else { + SettingsFile.loadCustomConfig(game) + updateName() + NativeConfig.unloadPerGameConfig() + NativeConfig.reloadGlobalConfig() + } + } + + private fun updateName() { + _selectedDriverTitle.value = GpuDriverHelper.customDriverSettingData.name + ?: SudachiApplication.appContext.getString(R.string.system_gpu_driver) + } + + private fun setDriverReady() { + _isDriverReady.value = true + updateName() + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/EmulationViewModel.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/EmulationViewModel.kt new file mode 100644 index 0000000..5595c32 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/EmulationViewModel.kt @@ -0,0 +1,76 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-3.0-or-later + +package org.sudachi.sudachi_emu.model + +import androidx.lifecycle.ViewModel +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow + +class EmulationViewModel : ViewModel() { + val emulationStarted: StateFlow get() = _emulationStarted + private val _emulationStarted = MutableStateFlow(false) + + val isEmulationStopping: StateFlow get() = _isEmulationStopping + private val _isEmulationStopping = MutableStateFlow(false) + + private val _emulationStopped = MutableStateFlow(false) + val emulationStopped = _emulationStopped.asStateFlow() + + private val _programChanged = MutableStateFlow(-1) + val programChanged = _programChanged.asStateFlow() + + val shaderProgress: StateFlow get() = _shaderProgress + private val _shaderProgress = MutableStateFlow(0) + + val totalShaders: StateFlow get() = _totalShaders + private val _totalShaders = MutableStateFlow(0) + + val shaderMessage: StateFlow get() = _shaderMessage + private val _shaderMessage = MutableStateFlow("") + + private val _drawerOpen = MutableStateFlow(false) + val drawerOpen = _drawerOpen.asStateFlow() + + fun setEmulationStarted(started: Boolean) { + _emulationStarted.value = started + } + + fun setIsEmulationStopping(value: Boolean) { + _isEmulationStopping.value = value + } + + fun setEmulationStopped(value: Boolean) { + if (value) { + _emulationStarted.value = false + } + _emulationStopped.value = value + } + + fun setProgramChanged(programIndex: Int) { + _programChanged.value = programIndex + } + + fun setShaderProgress(progress: Int) { + _shaderProgress.value = progress + } + + fun setTotalShaders(max: Int) { + _totalShaders.value = max + } + + fun setShaderMessage(msg: String) { + _shaderMessage.value = msg + } + + fun updateProgress(msg: String, progress: Int, max: Int) { + setShaderMessage(msg) + setShaderProgress(progress) + setTotalShaders(max) + } + + fun setDrawerOpen(value: Boolean) { + _drawerOpen.value = value + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/Game.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/Game.kt new file mode 100644 index 0000000..3d7fd2f --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/Game.kt @@ -0,0 +1,103 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.model + +import android.content.Intent +import android.net.Uri +import android.os.Parcelable +import java.util.HashSet +import kotlinx.parcelize.Parcelize +import kotlinx.serialization.Serializable +import org.sudachi.sudachi_emu.NativeLibrary +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.SudachiApplication +import org.sudachi.sudachi_emu.activities.EmulationActivity +import org.sudachi.sudachi_emu.utils.DirectoryInitialization +import org.sudachi.sudachi_emu.utils.FileUtil +import java.time.LocalDateTime +import java.time.format.DateTimeFormatter + +@Parcelize +@Serializable +class Game( + val title: String = "", + val path: String, + val programId: String = "", + val developer: String = "", + var version: String = "", + val isHomebrew: Boolean = false +) : Parcelable { + val keyAddedToLibraryTime get() = "${path}_AddedToLibraryTime" + val keyLastPlayedTime get() = "${path}_LastPlayed" + + val settingsName: String + get() { + val programIdLong = programId.toLong() + return if (programIdLong == 0L) { + FileUtil.getFilename(Uri.parse(path)) + } else { + "0" + programIdLong.toString(16).uppercase() + } + } + + val programIdHex: String + get() { + val programIdLong = programId.toLong() + return if (programIdLong == 0L) { + "0" + } else { + "0" + programIdLong.toString(16).uppercase() + } + } + + val saveZipName: String + get() = "$title ${SudachiApplication.appContext.getString(R.string.save_data).lowercase()} - ${ + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")) + }.zip" + + val saveDir: String + get() = DirectoryInitialization.userDirectory + "/nand" + + NativeLibrary.getSavePath(programId) + + val addonDir: String + get() = DirectoryInitialization.userDirectory + "/load/" + programIdHex + "/" + + val launchIntent: Intent + get() = Intent(SudachiApplication.appContext, EmulationActivity::class.java).apply { + action = Intent.ACTION_VIEW + data = Uri.parse(path) + } + + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (javaClass != other?.javaClass) return false + + other as Game + + if (title != other.title) return false + if (path != other.path) return false + if (programId != other.programId) return false + if (developer != other.developer) return false + if (version != other.version) return false + if (isHomebrew != other.isHomebrew) return false + + return true + } + + override fun hashCode(): Int { + var result = title.hashCode() + result = 31 * result + path.hashCode() + result = 31 * result + programId.hashCode() + result = 31 * result + developer.hashCode() + result = 31 * result + version.hashCode() + result = 31 * result + isHomebrew.hashCode() + return result + } + + companion object { + val extensions: Set = HashSet( + listOf("xci", "nsp", "nca", "nro") + ) + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/GameDir.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/GameDir.kt new file mode 100644 index 0000000..6095848 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/GameDir.kt @@ -0,0 +1,13 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.model + +import android.os.Parcelable +import kotlinx.parcelize.Parcelize + +@Parcelize +data class GameDir( + val uriString: String, + var deepScan: Boolean +) : Parcelable diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/GameProperties.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/GameProperties.kt new file mode 100644 index 0000000..a218631 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/GameProperties.kt @@ -0,0 +1,36 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.model + +import androidx.annotation.DrawableRes +import androidx.annotation.StringRes +import kotlinx.coroutines.flow.StateFlow + +interface GameProperty { + @get:StringRes + val titleId: Int + + @get:StringRes + val descriptionId: Int + + @get:DrawableRes + val iconId: Int +} + +data class SubmenuProperty( + override val titleId: Int, + override val descriptionId: Int, + override val iconId: Int, + val details: (() -> String)? = null, + val detailsFlow: StateFlow? = null, + val action: () -> Unit +) : GameProperty + +data class InstallableProperty( + override val titleId: Int, + override val descriptionId: Int, + override val iconId: Int, + val install: (() -> Unit)? = null, + val export: (() -> Unit)? = null +) : GameProperty diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/GameVerificationResult.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/GameVerificationResult.kt new file mode 100644 index 0000000..aff32ff --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/GameVerificationResult.kt @@ -0,0 +1,15 @@ +// SPDX-FileCopyrightText: 2024 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.model + +enum class GameVerificationResult(val int: Int) { + Success(0), + Failed(1), + NotImplemented(2); + + companion object { + fun from(int: Int): GameVerificationResult = + entries.firstOrNull { it.int == int } ?: Success + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/GamesViewModel.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/GamesViewModel.kt new file mode 100644 index 0000000..eb3c532 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/GamesViewModel.kt @@ -0,0 +1,186 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.model + +import android.net.Uri +import androidx.documentfile.provider.DocumentFile +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import androidx.preference.PreferenceManager +import java.util.Locale +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import kotlinx.serialization.decodeFromString +import kotlinx.serialization.json.Json +import org.sudachi.sudachi_emu.NativeLibrary +import org.sudachi.sudachi_emu.SudachiApplication +import org.sudachi.sudachi_emu.utils.GameHelper +import org.sudachi.sudachi_emu.utils.NativeConfig +import java.util.concurrent.atomic.AtomicBoolean + +class GamesViewModel : ViewModel() { + val games: StateFlow> get() = _games + private val _games = MutableStateFlow(emptyList()) + + val searchedGames: StateFlow> get() = _searchedGames + private val _searchedGames = MutableStateFlow(emptyList()) + + val isReloading: StateFlow get() = _isReloading + private val _isReloading = MutableStateFlow(false) + + private val reloading = AtomicBoolean(false) + + val shouldSwapData: StateFlow get() = _shouldSwapData + private val _shouldSwapData = MutableStateFlow(false) + + val shouldScrollToTop: StateFlow get() = _shouldScrollToTop + private val _shouldScrollToTop = MutableStateFlow(false) + + val searchFocused: StateFlow get() = _searchFocused + private val _searchFocused = MutableStateFlow(false) + + private val _folders = MutableStateFlow(mutableListOf()) + val folders = _folders.asStateFlow() + + init { + // Ensure keys are loaded so that ROM metadata can be decrypted. + NativeLibrary.reloadKeys() + + getGameDirs() + reloadGames(directoriesChanged = false, firstStartup = true) + } + + fun setGames(games: List) { + val sortedList = games.sortedWith( + compareBy( + { it.title.lowercase(Locale.getDefault()) }, + { it.path } + ) + ) + + _games.value = sortedList + } + + fun setSearchedGames(games: List) { + _searchedGames.value = games + } + + fun setShouldSwapData(shouldSwap: Boolean) { + _shouldSwapData.value = shouldSwap + } + + fun setShouldScrollToTop(shouldScroll: Boolean) { + _shouldScrollToTop.value = shouldScroll + } + + fun setSearchFocused(searchFocused: Boolean) { + _searchFocused.value = searchFocused + } + + fun reloadGames(directoriesChanged: Boolean, firstStartup: Boolean = false) { + if (reloading.get()) { + return + } + reloading.set(true) + _isReloading.value = true + + viewModelScope.launch { + withContext(Dispatchers.IO) { + if (firstStartup) { + // Retrieve list of cached games + val storedGames = + PreferenceManager.getDefaultSharedPreferences(SudachiApplication.appContext) + .getStringSet(GameHelper.KEY_GAMES, emptySet()) + if (storedGames!!.isNotEmpty()) { + val deserializedGames = mutableSetOf() + storedGames.forEach { + val game: Game + try { + game = Json.decodeFromString(it) + } catch (e: Exception) { + // We don't care about any errors related to parsing the game cache + return@forEach + } + + val gameExists = + DocumentFile.fromSingleUri( + SudachiApplication.appContext, + Uri.parse(game.path) + )?.exists() + if (gameExists == true) { + deserializedGames.add(game) + } + } + setGames(deserializedGames.toList()) + } + } + + setGames(GameHelper.getGames()) + reloading.set(false) + _isReloading.value = false + + if (directoriesChanged) { + setShouldSwapData(true) + } + } + } + } + + fun addFolder(gameDir: GameDir) = + viewModelScope.launch { + withContext(Dispatchers.IO) { + NativeConfig.addGameDir(gameDir) + getGameDirs(true) + } + } + + fun removeFolder(gameDir: GameDir) = + viewModelScope.launch { + withContext(Dispatchers.IO) { + val gameDirs = _folders.value.toMutableList() + val removedDirIndex = gameDirs.indexOf(gameDir) + if (removedDirIndex != -1) { + gameDirs.removeAt(removedDirIndex) + NativeConfig.setGameDirs(gameDirs.toTypedArray()) + getGameDirs() + } + } + } + + fun updateGameDirs() = + viewModelScope.launch { + withContext(Dispatchers.IO) { + NativeConfig.setGameDirs(_folders.value.toTypedArray()) + getGameDirs() + } + } + + fun onOpenGameFoldersFragment() = + viewModelScope.launch { + withContext(Dispatchers.IO) { + getGameDirs() + } + } + + fun onCloseGameFoldersFragment() { + NativeConfig.saveGlobalConfig() + viewModelScope.launch { + withContext(Dispatchers.IO) { + getGameDirs(true) + } + } + } + + private fun getGameDirs(reloadList: Boolean = false) { + val gameDirs = NativeConfig.getGameDirs() + _folders.value = gameDirs.toMutableList() + if (reloadList) { + reloadGames(true) + } + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/HomeSetting.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/HomeSetting.kt new file mode 100644 index 0000000..dc9aa5e --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/HomeSetting.kt @@ -0,0 +1,18 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.model + +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow + +data class HomeSetting( + val titleId: Int, + val descriptionId: Int, + val iconId: Int, + val onClick: () -> Unit, + val isEnabled: () -> Boolean = { true }, + val disabledTitleId: Int = 0, + val disabledMessageId: Int = 0, + val details: StateFlow = MutableStateFlow("") +) diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/HomeViewModel.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/HomeViewModel.kt new file mode 100644 index 0000000..d003e36 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/HomeViewModel.kt @@ -0,0 +1,76 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-3.0-or-later + +package org.sudachi.sudachi_emu.model + +import android.net.Uri +import androidx.lifecycle.ViewModel +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow + +class HomeViewModel : ViewModel() { + val navigationVisible: StateFlow> get() = _navigationVisible + private val _navigationVisible = MutableStateFlow(Pair(false, false)) + + val statusBarShadeVisible: StateFlow get() = _statusBarShadeVisible + private val _statusBarShadeVisible = MutableStateFlow(true) + + val shouldPageForward: StateFlow get() = _shouldPageForward + private val _shouldPageForward = MutableStateFlow(false) + + private val _gamesDirSelected = MutableStateFlow(false) + val gamesDirSelected get() = _gamesDirSelected.asStateFlow() + + private val _openImportSaves = MutableStateFlow(false) + val openImportSaves get() = _openImportSaves.asStateFlow() + + private val _contentToInstall = MutableStateFlow?>(null) + val contentToInstall get() = _contentToInstall.asStateFlow() + + private val _reloadPropertiesList = MutableStateFlow(false) + val reloadPropertiesList get() = _reloadPropertiesList.asStateFlow() + + private val _checkKeys = MutableStateFlow(false) + val checkKeys = _checkKeys.asStateFlow() + + var navigatedToSetup = false + + fun setNavigationVisibility(visible: Boolean, animated: Boolean) { + if (navigationVisible.value.first == visible) { + return + } + _navigationVisible.value = Pair(visible, animated) + } + + fun setStatusBarShadeVisibility(visible: Boolean) { + if (statusBarShadeVisible.value == visible) { + return + } + _statusBarShadeVisible.value = visible + } + + fun setShouldPageForward(pageForward: Boolean) { + _shouldPageForward.value = pageForward + } + + fun setGamesDirSelected(selected: Boolean) { + _gamesDirSelected.value = selected + } + + fun setOpenImportSaves(import: Boolean) { + _openImportSaves.value = import + } + + fun setContentToInstall(documents: List?) { + _contentToInstall.value = documents + } + + fun reloadPropertiesList(reload: Boolean) { + _reloadPropertiesList.value = reload + } + + fun setCheckKeys(value: Boolean) { + _checkKeys.value = value + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/InstallResult.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/InstallResult.kt new file mode 100644 index 0000000..c736305 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/InstallResult.kt @@ -0,0 +1,15 @@ +// SPDX-FileCopyrightText: 2024 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.model + +enum class InstallResult(val int: Int) { + Success(0), + Overwrite(1), + Failure(2), + BaseInstallAttempted(3); + + companion object { + fun from(int: Int): InstallResult = entries.firstOrNull { it.int == int } ?: Success + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/Installable.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/Installable.kt new file mode 100644 index 0000000..669f4c8 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/Installable.kt @@ -0,0 +1,13 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.model + +import androidx.annotation.StringRes + +data class Installable( + @StringRes val titleId: Int, + @StringRes val descriptionId: Int, + val install: (() -> Unit)? = null, + val export: (() -> Unit)? = null +) diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/License.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/License.kt new file mode 100644 index 0000000..24f2800 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/License.kt @@ -0,0 +1,16 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.model + +import android.os.Parcelable +import kotlinx.parcelize.Parcelize + +@Parcelize +data class License( + val titleId: Int, + val descriptionId: Int, + val linkId: Int, + val copyrightId: Int, + val licenseId: Int +) : Parcelable diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/MessageDialogViewModel.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/MessageDialogViewModel.kt new file mode 100644 index 0000000..2452d1f --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/MessageDialogViewModel.kt @@ -0,0 +1,16 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.model + +import androidx.lifecycle.ViewModel + +class MessageDialogViewModel : ViewModel() { + var positiveAction: (() -> Unit)? = null + var negativeAction: (() -> Unit)? = null + + fun clear() { + positiveAction = null + negativeAction = null + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/MinimalDocumentFile.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/MinimalDocumentFile.kt new file mode 100644 index 0000000..521f99e --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/MinimalDocumentFile.kt @@ -0,0 +1,11 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.model + +import android.net.Uri +import android.provider.DocumentsContract + +class MinimalDocumentFile(val filename: String, mimeType: String, val uri: Uri) { + val isDirectory: Boolean = mimeType == DocumentsContract.Document.MIME_TYPE_DIR +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/Patch.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/Patch.kt new file mode 100644 index 0000000..b556efb --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/Patch.kt @@ -0,0 +1,16 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.model + +import androidx.annotation.Keep + +@Keep +data class Patch( + var enabled: Boolean, + val name: String, + val version: String, + val type: Int, + val programId: String, + val titleId: String +) diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/PatchType.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/PatchType.kt new file mode 100644 index 0000000..305d75d --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/PatchType.kt @@ -0,0 +1,14 @@ +// SPDX-FileCopyrightText: 2024 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.model + +enum class PatchType(val int: Int) { + Update(0), + DLC(1), + Mod(2); + + companion object { + fun from(int: Int): PatchType = entries.firstOrNull { it.int == int } ?: Update + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/SelectableItem.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/SelectableItem.kt new file mode 100644 index 0000000..c24819a --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/SelectableItem.kt @@ -0,0 +1,9 @@ +// SPDX-FileCopyrightText: 2024 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.model + +interface SelectableItem { + var selected: Boolean + fun onSelectionStateChanged(selected: Boolean) +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/SettingsViewModel.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/SettingsViewModel.kt new file mode 100644 index 0000000..b4ee78e --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/SettingsViewModel.kt @@ -0,0 +1,71 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.model + +import androidx.lifecycle.ViewModel +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.SudachiApplication +import org.sudachi.sudachi_emu.features.settings.model.view.SettingsItem + +class SettingsViewModel : ViewModel() { + var game: Game? = null + + var clickedItem: SettingsItem? = null + + val shouldRecreate: StateFlow get() = _shouldRecreate + private val _shouldRecreate = MutableStateFlow(false) + + val shouldNavigateBack: StateFlow get() = _shouldNavigateBack + private val _shouldNavigateBack = MutableStateFlow(false) + + val shouldShowResetSettingsDialog: StateFlow get() = _shouldShowResetSettingsDialog + private val _shouldShowResetSettingsDialog = MutableStateFlow(false) + + val shouldReloadSettingsList: StateFlow get() = _shouldReloadSettingsList + private val _shouldReloadSettingsList = MutableStateFlow(false) + + val sliderProgress: StateFlow get() = _sliderProgress + private val _sliderProgress = MutableStateFlow(-1) + + val sliderTextValue: StateFlow get() = _sliderTextValue + private val _sliderTextValue = MutableStateFlow("") + + val adapterItemChanged: StateFlow get() = _adapterItemChanged + private val _adapterItemChanged = MutableStateFlow(-1) + + fun setShouldRecreate(value: Boolean) { + _shouldRecreate.value = value + } + + fun setShouldNavigateBack(value: Boolean) { + _shouldNavigateBack.value = value + } + + fun setShouldShowResetSettingsDialog(value: Boolean) { + _shouldShowResetSettingsDialog.value = value + } + + fun setShouldReloadSettingsList(value: Boolean) { + _shouldReloadSettingsList.value = value + } + + fun setSliderTextValue(value: Float, units: String) { + _sliderProgress.value = value.toInt() + _sliderTextValue.value = String.format( + SudachiApplication.appContext.getString(R.string.value_with_units), + value.toInt().toString(), + units + ) + } + + fun setSliderProgress(value: Float) { + _sliderProgress.value = value.toInt() + } + + fun setAdapterItemChanged(value: Int) { + _adapterItemChanged.value = value + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/SetupPage.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/SetupPage.kt new file mode 100644 index 0000000..3f6ad5c --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/SetupPage.kt @@ -0,0 +1,29 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.model + +data class SetupPage( + val iconId: Int, + val titleId: Int, + val descriptionId: Int, + val buttonIconId: Int, + val leftAlignedIcon: Boolean, + val buttonTextId: Int, + val buttonAction: (callback: SetupCallback) -> Unit, + val hasWarning: Boolean, + val warningTitleId: Int = 0, + val warningDescriptionId: Int = 0, + val warningHelpLinkId: Int = 0, + val stepCompleted: () -> StepState = { StepState.UNDEFINED } +) + +interface SetupCallback { + fun onStepCompleted() +} + +enum class StepState { + COMPLETE, + INCOMPLETE, + UNDEFINED +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/TaskViewModel.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/TaskViewModel.kt new file mode 100644 index 0000000..f90e678 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/model/TaskViewModel.kt @@ -0,0 +1,83 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.model + +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.launch + +class TaskViewModel : ViewModel() { + val result: StateFlow get() = _result + private val _result = MutableStateFlow(Any()) + + val isComplete: StateFlow get() = _isComplete + private val _isComplete = MutableStateFlow(false) + + val isRunning: StateFlow get() = _isRunning + private val _isRunning = MutableStateFlow(false) + + val cancelled: StateFlow get() = _cancelled + private val _cancelled = MutableStateFlow(false) + + private val _progress = MutableStateFlow(0.0) + val progress = _progress.asStateFlow() + + private val _maxProgress = MutableStateFlow(0.0) + val maxProgress = _maxProgress.asStateFlow() + + private val _message = MutableStateFlow("") + val message = _message.asStateFlow() + + lateinit var task: suspend ( + progressCallback: (max: Long, progress: Long) -> Boolean, + messageCallback: (message: String) -> Unit + ) -> Any + + fun clear() { + _result.value = Any() + _isComplete.value = false + _isRunning.value = false + _cancelled.value = false + _progress.value = 0.0 + _maxProgress.value = 0.0 + _message.value = "" + } + + fun setCancelled(value: Boolean) { + _cancelled.value = value + } + + fun runTask() { + if (isRunning.value) { + return + } + _isRunning.value = true + + viewModelScope.launch(Dispatchers.IO) { + val res = task( + { max, progress -> + _maxProgress.value = max.toDouble() + _progress.value = progress.toDouble() + return@task cancelled.value + }, + { message -> + _message.value = message + } + ) + _result.value = res + _isComplete.value = true + _isRunning.value = false + } + } +} + +enum class TaskState { + Completed, + Failed, + Cancelled +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/overlay/InputOverlay.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/overlay/InputOverlay.kt new file mode 100644 index 0000000..850cbf9 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/overlay/InputOverlay.kt @@ -0,0 +1,1049 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.overlay + +import android.app.Activity +import android.content.Context +import android.content.SharedPreferences +import android.graphics.Bitmap +import android.graphics.Canvas +import android.graphics.Point +import android.graphics.Rect +import android.graphics.drawable.Drawable +import android.graphics.drawable.VectorDrawable +import android.os.Build +import android.util.AttributeSet +import android.view.HapticFeedbackConstants +import android.view.MotionEvent +import android.view.SurfaceView +import android.view.View +import android.view.View.OnTouchListener +import android.view.WindowInsets +import androidx.core.content.ContextCompat +import androidx.window.layout.WindowMetricsCalculator +import kotlin.math.max +import kotlin.math.min +import org.sudachi.sudachi_emu.features.input.NativeInput +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.features.input.model.NativeAnalog +import org.sudachi.sudachi_emu.features.input.model.NativeButton +import org.sudachi.sudachi_emu.features.input.model.NpadStyleIndex +import org.sudachi.sudachi_emu.features.settings.model.BooleanSetting +import org.sudachi.sudachi_emu.features.settings.model.IntSetting +import org.sudachi.sudachi_emu.overlay.model.OverlayControl +import org.sudachi.sudachi_emu.overlay.model.OverlayControlData +import org.sudachi.sudachi_emu.overlay.model.OverlayLayout +import org.sudachi.sudachi_emu.utils.NativeConfig + +/** + * Draws the interactive input overlay on top of the + * [SurfaceView] that is rendering emulation. + */ +class InputOverlay(context: Context, attrs: AttributeSet?) : + SurfaceView(context, attrs), + OnTouchListener { + private val overlayButtons: MutableSet = HashSet() + private val overlayDpads: MutableSet = HashSet() + private val overlayJoysticks: MutableSet = HashSet() + + private var inEditMode = false + private var buttonBeingConfigured: InputOverlayDrawableButton? = null + private var dpadBeingConfigured: InputOverlayDrawableDpad? = null + private var joystickBeingConfigured: InputOverlayDrawableJoystick? = null + + private lateinit var windowInsets: WindowInsets + + var layout = OverlayLayout.Landscape + + override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) { + super.onLayout(changed, left, top, right, bottom) + + windowInsets = rootWindowInsets + + val overlayControlData = NativeConfig.getOverlayControlData() + if (overlayControlData.isEmpty()) { + populateDefaultConfig() + } else { + checkForNewControls(overlayControlData) + } + + // Load the controls. + refreshControls() + + // Set the on touch listener. + setOnTouchListener(this) + + // Force draw + setWillNotDraw(false) + + // Request focus for the overlay so it has priority on presses. + requestFocus() + } + + override fun draw(canvas: Canvas) { + super.draw(canvas) + for (button in overlayButtons) { + button.draw(canvas) + } + for (dpad in overlayDpads) { + dpad.draw(canvas) + } + for (joystick in overlayJoysticks) { + joystick.draw(canvas) + } + } + + override fun onTouch(v: View, event: MotionEvent): Boolean { + if (inEditMode) { + return onTouchWhileEditing(event) + } + + var shouldUpdateView = false + val playerIndex = when (NativeInput.getStyleIndex(0)) { + NpadStyleIndex.Handheld -> 8 + else -> 0 + } + + for (button in overlayButtons) { + if (!button.updateStatus(event)) { + continue + } + NativeInput.onOverlayButtonEvent( + playerIndex, + button.button, + button.status + ) + playHaptics(event) + shouldUpdateView = true + } + + for (dpad in overlayDpads) { + if (!dpad.updateStatus(event, BooleanSetting.DPAD_SLIDE.getBoolean())) { + continue + } + NativeInput.onOverlayButtonEvent( + playerIndex, + dpad.up, + dpad.upStatus + ) + NativeInput.onOverlayButtonEvent( + playerIndex, + dpad.down, + dpad.downStatus + ) + NativeInput.onOverlayButtonEvent( + playerIndex, + dpad.left, + dpad.leftStatus + ) + NativeInput.onOverlayButtonEvent( + playerIndex, + dpad.right, + dpad.rightStatus + ) + playHaptics(event) + shouldUpdateView = true + } + + for (joystick in overlayJoysticks) { + if (!joystick.updateStatus(event)) { + continue + } + NativeInput.onOverlayJoystickEvent( + playerIndex, + joystick.joystick, + joystick.xAxis, + joystick.realYAxis + ) + NativeInput.onOverlayButtonEvent( + playerIndex, + joystick.button, + joystick.buttonStatus + ) + playHaptics(event) + shouldUpdateView = true + } + + if (shouldUpdateView) { + invalidate() + } + + if (!BooleanSetting.TOUCHSCREEN.getBoolean()) { + return true + } + + val pointerIndex = event.actionIndex + val xPosition = event.getX(pointerIndex).toInt() + val yPosition = event.getY(pointerIndex).toInt() + val pointerId = event.getPointerId(pointerIndex) + val motionEvent = event.action and MotionEvent.ACTION_MASK + val isActionDown = + motionEvent == MotionEvent.ACTION_DOWN || motionEvent == MotionEvent.ACTION_POINTER_DOWN + val isActionMove = motionEvent == MotionEvent.ACTION_MOVE + val isActionUp = + motionEvent == MotionEvent.ACTION_UP || motionEvent == MotionEvent.ACTION_POINTER_UP + + if (isActionDown && !isTouchInputConsumed(pointerId)) { + NativeInput.onTouchPressed(pointerId, xPosition.toFloat(), yPosition.toFloat()) + } + + if (isActionMove) { + for (i in 0 until event.pointerCount) { + val fingerId = event.getPointerId(i) + if (isTouchInputConsumed(fingerId)) { + continue + } + NativeInput.onTouchMoved(fingerId, event.getX(i), event.getY(i)) + } + } + + if (isActionUp && !isTouchInputConsumed(pointerId)) { + NativeInput.onTouchReleased(pointerId) + } + + return true + } + + private fun playHaptics(event: MotionEvent) { + if (BooleanSetting.HAPTIC_FEEDBACK.getBoolean()) { + when (event.actionMasked) { + MotionEvent.ACTION_DOWN, + MotionEvent.ACTION_POINTER_DOWN -> + performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY) + + MotionEvent.ACTION_UP, + MotionEvent.ACTION_POINTER_UP -> + performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY_RELEASE) + } + } + } + + private fun isTouchInputConsumed(track_id: Int): Boolean { + for (button in overlayButtons) { + if (button.trackId == track_id) { + return true + } + } + for (dpad in overlayDpads) { + if (dpad.trackId == track_id) { + return true + } + } + for (joystick in overlayJoysticks) { + if (joystick.trackId == track_id) { + return true + } + } + return false + } + + private fun onTouchWhileEditing(event: MotionEvent): Boolean { + val pointerIndex = event.actionIndex + val fingerPositionX = event.getX(pointerIndex).toInt() + val fingerPositionY = event.getY(pointerIndex).toInt() + + for (button in overlayButtons) { + // Determine the button state to apply based on the MotionEvent action flag. + when (event.action and MotionEvent.ACTION_MASK) { + MotionEvent.ACTION_DOWN, + MotionEvent.ACTION_POINTER_DOWN -> + // If no button is being moved now, remember the currently touched button to move. + if (buttonBeingConfigured == null && + button.bounds.contains(fingerPositionX, fingerPositionY) + ) { + buttonBeingConfigured = button + buttonBeingConfigured!!.onConfigureTouch(event) + } + + MotionEvent.ACTION_MOVE -> if (buttonBeingConfigured != null) { + buttonBeingConfigured!!.onConfigureTouch(event) + invalidate() + return true + } + + MotionEvent.ACTION_UP, + MotionEvent.ACTION_POINTER_UP -> if (buttonBeingConfigured === button) { + // Persist button position by saving new place. + saveControlPosition( + buttonBeingConfigured!!.overlayControlData.id, + buttonBeingConfigured!!.bounds.centerX(), + buttonBeingConfigured!!.bounds.centerY(), + layout + ) + buttonBeingConfigured = null + } + } + } + + for (dpad in overlayDpads) { + // Determine the button state to apply based on the MotionEvent action flag. + when (event.action and MotionEvent.ACTION_MASK) { + MotionEvent.ACTION_DOWN, + MotionEvent.ACTION_POINTER_DOWN -> + // If no button is being moved now, remember the currently touched button to move. + if (buttonBeingConfigured == null && + dpad.bounds.contains(fingerPositionX, fingerPositionY) + ) { + dpadBeingConfigured = dpad + dpadBeingConfigured!!.onConfigureTouch(event) + } + + MotionEvent.ACTION_MOVE -> if (dpadBeingConfigured != null) { + dpadBeingConfigured!!.onConfigureTouch(event) + invalidate() + return true + } + + MotionEvent.ACTION_UP, + MotionEvent.ACTION_POINTER_UP -> if (dpadBeingConfigured === dpad) { + // Persist button position by saving new place. + saveControlPosition( + OverlayControl.COMBINED_DPAD.id, + dpadBeingConfigured!!.bounds.centerX(), + dpadBeingConfigured!!.bounds.centerY(), + layout + ) + dpadBeingConfigured = null + } + } + } + + for (joystick in overlayJoysticks) { + when (event.action) { + MotionEvent.ACTION_DOWN, + MotionEvent.ACTION_POINTER_DOWN -> if (joystickBeingConfigured == null && + joystick.bounds.contains(fingerPositionX, fingerPositionY) + ) { + joystickBeingConfigured = joystick + joystickBeingConfigured!!.onConfigureTouch(event) + } + + MotionEvent.ACTION_MOVE -> if (joystickBeingConfigured != null) { + joystickBeingConfigured!!.onConfigureTouch(event) + invalidate() + } + + MotionEvent.ACTION_UP, + MotionEvent.ACTION_POINTER_UP -> if (joystickBeingConfigured != null) { + saveControlPosition( + joystickBeingConfigured!!.prefId, + joystickBeingConfigured!!.bounds.centerX(), + joystickBeingConfigured!!.bounds.centerY(), + layout + ) + joystickBeingConfigured = null + } + } + } + + return true + } + + private fun addOverlayControls(layout: OverlayLayout) { + val windowSize = getSafeScreenSize(context, Pair(measuredWidth, measuredHeight)) + val overlayControlData = NativeConfig.getOverlayControlData() + for (data in overlayControlData) { + if (!data.enabled) { + continue + } + + val position = data.positionFromLayout(layout) + when (data.id) { + OverlayControl.BUTTON_A.id -> { + overlayButtons.add( + initializeOverlayButton( + context, + windowSize, + R.drawable.facebutton_a, + R.drawable.facebutton_a_depressed, + NativeButton.A, + data, + position + ) + ) + } + + OverlayControl.BUTTON_B.id -> { + overlayButtons.add( + initializeOverlayButton( + context, + windowSize, + R.drawable.facebutton_b, + R.drawable.facebutton_b_depressed, + NativeButton.B, + data, + position + ) + ) + } + + OverlayControl.BUTTON_X.id -> { + overlayButtons.add( + initializeOverlayButton( + context, + windowSize, + R.drawable.facebutton_x, + R.drawable.facebutton_x_depressed, + NativeButton.X, + data, + position + ) + ) + } + + OverlayControl.BUTTON_Y.id -> { + overlayButtons.add( + initializeOverlayButton( + context, + windowSize, + R.drawable.facebutton_y, + R.drawable.facebutton_y_depressed, + NativeButton.Y, + data, + position + ) + ) + } + + OverlayControl.BUTTON_PLUS.id -> { + overlayButtons.add( + initializeOverlayButton( + context, + windowSize, + R.drawable.facebutton_plus, + R.drawable.facebutton_plus_depressed, + NativeButton.Plus, + data, + position + ) + ) + } + + OverlayControl.BUTTON_MINUS.id -> { + overlayButtons.add( + initializeOverlayButton( + context, + windowSize, + R.drawable.facebutton_minus, + R.drawable.facebutton_minus_depressed, + NativeButton.Minus, + data, + position + ) + ) + } + + OverlayControl.BUTTON_HOME.id -> { + overlayButtons.add( + initializeOverlayButton( + context, + windowSize, + R.drawable.facebutton_home, + R.drawable.facebutton_home_depressed, + NativeButton.Home, + data, + position + ) + ) + } + + OverlayControl.BUTTON_CAPTURE.id -> { + overlayButtons.add( + initializeOverlayButton( + context, + windowSize, + R.drawable.facebutton_screenshot, + R.drawable.facebutton_screenshot_depressed, + NativeButton.Capture, + data, + position + ) + ) + } + + OverlayControl.BUTTON_L.id -> { + overlayButtons.add( + initializeOverlayButton( + context, + windowSize, + R.drawable.l_shoulder, + R.drawable.l_shoulder_depressed, + NativeButton.L, + data, + position + ) + ) + } + + OverlayControl.BUTTON_R.id -> { + overlayButtons.add( + initializeOverlayButton( + context, + windowSize, + R.drawable.r_shoulder, + R.drawable.r_shoulder_depressed, + NativeButton.R, + data, + position + ) + ) + } + + OverlayControl.BUTTON_ZL.id -> { + overlayButtons.add( + initializeOverlayButton( + context, + windowSize, + R.drawable.zl_trigger, + R.drawable.zl_trigger_depressed, + NativeButton.ZL, + data, + position + ) + ) + } + + OverlayControl.BUTTON_ZR.id -> { + overlayButtons.add( + initializeOverlayButton( + context, + windowSize, + R.drawable.zr_trigger, + R.drawable.zr_trigger_depressed, + NativeButton.ZR, + data, + position + ) + ) + } + + OverlayControl.BUTTON_STICK_L.id -> { + overlayButtons.add( + initializeOverlayButton( + context, + windowSize, + R.drawable.button_l3, + R.drawable.button_l3_depressed, + NativeButton.LStick, + data, + position + ) + ) + } + + OverlayControl.BUTTON_STICK_R.id -> { + overlayButtons.add( + initializeOverlayButton( + context, + windowSize, + R.drawable.button_r3, + R.drawable.button_r3_depressed, + NativeButton.RStick, + data, + position + ) + ) + } + + OverlayControl.STICK_L.id -> { + overlayJoysticks.add( + initializeOverlayJoystick( + context, + windowSize, + R.drawable.joystick_range, + R.drawable.joystick, + R.drawable.joystick_depressed, + NativeAnalog.LStick, + NativeButton.LStick, + data, + position + ) + ) + } + + OverlayControl.STICK_R.id -> { + overlayJoysticks.add( + initializeOverlayJoystick( + context, + windowSize, + R.drawable.joystick_range, + R.drawable.joystick, + R.drawable.joystick_depressed, + NativeAnalog.RStick, + NativeButton.RStick, + data, + position + ) + ) + } + + OverlayControl.COMBINED_DPAD.id -> { + overlayDpads.add( + initializeOverlayDpad( + context, + windowSize, + R.drawable.dpad_standard, + R.drawable.dpad_standard_cardinal_depressed, + R.drawable.dpad_standard_diagonal_depressed, + position + ) + ) + } + } + } + } + + fun refreshControls() { + // Remove all the overlay buttons from the HashSet. + overlayButtons.clear() + overlayDpads.clear() + overlayJoysticks.clear() + + // Add all the enabled overlay items back to the HashSet. + if (BooleanSetting.SHOW_INPUT_OVERLAY.getBoolean()) { + addOverlayControls(layout) + } + invalidate() + } + + private fun saveControlPosition(id: String, x: Int, y: Int, layout: OverlayLayout) { + val windowSize = getSafeScreenSize(context, Pair(measuredWidth, measuredHeight)) + val min = windowSize.first + val max = windowSize.second + val overlayControlData = NativeConfig.getOverlayControlData() + val data = overlayControlData.firstOrNull { it.id == id } + val newPosition = Pair((x - min.x).toDouble() / max.x, (y - min.y).toDouble() / max.y) + when (layout) { + OverlayLayout.Landscape -> data?.landscapePosition = newPosition + OverlayLayout.Portrait -> data?.portraitPosition = newPosition + OverlayLayout.Foldable -> data?.foldablePosition = newPosition + } + NativeConfig.setOverlayControlData(overlayControlData) + } + + fun setIsInEditMode(editMode: Boolean) { + inEditMode = editMode + } + + /** + * Applies and saves all default values for the overlay + */ + private fun populateDefaultConfig() { + val newConfig = OverlayControl.entries.map { it.toOverlayControlData() } + NativeConfig.setOverlayControlData(newConfig.toTypedArray()) + NativeConfig.saveGlobalConfig() + } + + /** + * Checks if any new controls were added to OverlayControl that do not exist within deserialized + * config and adds / saves them if necessary + * + * @param overlayControlData Overlay control data from [NativeConfig.getOverlayControlData] + */ + private fun checkForNewControls(overlayControlData: Array) { + val missingControls = mutableListOf() + OverlayControl.entries.forEach { defaultControl -> + val controlData = overlayControlData.firstOrNull { it.id == defaultControl.id } + if (controlData == null) { + missingControls.add(defaultControl.toOverlayControlData()) + } + } + + if (missingControls.isNotEmpty()) { + NativeConfig.setOverlayControlData( + arrayOf(*overlayControlData, *(missingControls.toTypedArray())) + ) + NativeConfig.saveGlobalConfig() + } + } + + fun resetLayoutVisibilityAndPlacement() { + defaultOverlayPositionByLayout(layout) + + val overlayControlData = NativeConfig.getOverlayControlData() + overlayControlData.forEach { + it.enabled = OverlayControl.from(it.id)?.defaultVisibility == true + } + NativeConfig.setOverlayControlData(overlayControlData) + + refreshControls() + } + + private fun defaultOverlayPositionByLayout(layout: OverlayLayout) { + val overlayControlData = NativeConfig.getOverlayControlData() + for (data in overlayControlData) { + val defaultControlData = OverlayControl.from(data.id) ?: continue + val position = defaultControlData.getDefaultPositionForLayout(layout) + when (layout) { + OverlayLayout.Landscape -> data.landscapePosition = position + OverlayLayout.Portrait -> data.portraitPosition = position + OverlayLayout.Foldable -> data.foldablePosition = position + } + } + NativeConfig.setOverlayControlData(overlayControlData) + } + + override fun isInEditMode(): Boolean { + return inEditMode + } + + companion object { + // Increase this number every time there is a breaking change to every overlay layout + const val OVERLAY_VERSION = 1 + + // Increase the corresponding layout version number whenever that layout has a breaking change + private const val LANDSCAPE_OVERLAY_VERSION = 1 + private const val PORTRAIT_OVERLAY_VERSION = 1 + private const val FOLDABLE_OVERLAY_VERSION = 1 + val overlayLayoutVersions = listOf( + LANDSCAPE_OVERLAY_VERSION, + PORTRAIT_OVERLAY_VERSION, + FOLDABLE_OVERLAY_VERSION + ) + + /** + * Resizes a [Bitmap] by a given scale factor + * + * @param context Context for getting the vector drawable + * @param drawableId The ID of the drawable to scale. + * @param scale The scale factor for the bitmap. + * @return The scaled [Bitmap] + */ + private fun getBitmap(context: Context, drawableId: Int, scale: Float): Bitmap { + val vectorDrawable = ContextCompat.getDrawable(context, drawableId) as VectorDrawable + + val bitmap = Bitmap.createBitmap( + (vectorDrawable.intrinsicWidth * scale).toInt(), + (vectorDrawable.intrinsicHeight * scale).toInt(), + Bitmap.Config.ARGB_8888 + ) + + val dm = context.resources.displayMetrics + val minScreenDimension = min(dm.widthPixels, dm.heightPixels) + + val maxBitmapDimension = max(bitmap.width, bitmap.height) + val bitmapScale = scale * minScreenDimension / maxBitmapDimension + + val scaledBitmap = Bitmap.createScaledBitmap( + bitmap, + (bitmap.width * bitmapScale).toInt(), + (bitmap.height * bitmapScale).toInt(), + true + ) + + val canvas = Canvas(scaledBitmap) + vectorDrawable.setBounds(0, 0, canvas.width, canvas.height) + vectorDrawable.draw(canvas) + return scaledBitmap + } + + /** + * Gets the safe screen size for drawing the overlay + * + * @param context Context for getting the window metrics + * @return A pair of points, the first being the top left corner of the safe area, + * the second being the bottom right corner of the safe area + */ + private fun getSafeScreenSize( + context: Context, + screenSize: Pair + ): Pair { + // Get screen size + val windowMetrics = WindowMetricsCalculator.getOrCreate() + .computeCurrentWindowMetrics(context as Activity) + var maxX = screenSize.first.toFloat() + var maxY = screenSize.second.toFloat() + var minX = 0 + var minY = 0 + + // If we have API access, calculate the safe area to draw the overlay + var cutoutLeft = 0 + var cutoutBottom = 0 + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + val insets = context.windowManager.currentWindowMetrics.windowInsets.displayCutout + if (insets != null) { + if (insets.boundingRectTop.bottom != 0 && + insets.boundingRectTop.bottom > maxY / 2 + ) { + maxY = insets.boundingRectTop.bottom.toFloat() + } + if (insets.boundingRectRight.left != 0 && + insets.boundingRectRight.left > maxX / 2 + ) { + maxX = insets.boundingRectRight.left.toFloat() + } + + minX = insets.boundingRectLeft.right - insets.boundingRectLeft.left + minY = insets.boundingRectBottom.top - insets.boundingRectBottom.bottom + + cutoutLeft = insets.boundingRectRight.right - insets.boundingRectRight.left + cutoutBottom = insets.boundingRectTop.top - insets.boundingRectTop.bottom + } + } + + // This makes sure that if we have an inset on one side of the screen, we mirror it on + // the other side. Since removing space from one of the max values messes with the scale, + // we also have to account for it using our min values. + if (maxX.toInt() != windowMetrics.bounds.width()) minX += cutoutLeft + if (maxY.toInt() != windowMetrics.bounds.height()) minY += cutoutBottom + if (minX > 0 && maxX.toInt() == windowMetrics.bounds.width()) { + maxX -= (minX * 2) + } else if (minX > 0) { + maxX -= minX + } + if (minY > 0 && maxY.toInt() == windowMetrics.bounds.height()) { + maxY -= (minY * 2) + } else if (minY > 0) { + maxY -= minY + } + + return Pair(Point(minX, minY), Point(maxX.toInt(), maxY.toInt())) + } + + /** + * Initializes an InputOverlayDrawableButton, given by resId, with all of the + * parameters set for it to be properly shown on the InputOverlay. + * + * + * This works due to the way the X and Y coordinates are stored within + * the [SharedPreferences]. + * + * + * In the input overlay configuration menu, + * once a touch event begins and then ends (ie. Organizing the buttons to one's own liking for the overlay). + * the X and Y coordinates of the button at the END of its touch event + * (when you remove your finger/stylus from the touchscreen) are then stored in a native . + * + * Technically no modifications should need to be performed on the returned + * InputOverlayDrawableButton. Simply add it to the HashSet of overlay items and wait + * for Android to call the onDraw method. + * + * @param context The current [Context]. + * @param windowSize The size of the window to draw the overlay on. + * @param defaultResId The resource ID of the [Drawable] to get the [Bitmap] of (Default State). + * @param pressedResId The resource ID of the [Drawable] to get the [Bitmap] of (Pressed State). + * @param buttonId Identifier for determining what type of button the initialized InputOverlayDrawableButton represents. + * @param overlayControlData Identifier for determining where a button appears on screen. + * @param position The position on screen as represented by an x and y value between 0 and 1. + * @return An [InputOverlayDrawableButton] with the correct drawing bounds set. + */ + private fun initializeOverlayButton( + context: Context, + windowSize: Pair, + defaultResId: Int, + pressedResId: Int, + button: NativeButton, + overlayControlData: OverlayControlData, + position: Pair + ): InputOverlayDrawableButton { + // Resources handle for fetching the initial Drawable resource. + val res = context.resources + + // Decide scale based on button preference ID and user preference + var scale: Float = when (overlayControlData.id) { + OverlayControl.BUTTON_HOME.id, + OverlayControl.BUTTON_CAPTURE.id, + OverlayControl.BUTTON_PLUS.id, + OverlayControl.BUTTON_MINUS.id -> 0.07f + + OverlayControl.BUTTON_L.id, + OverlayControl.BUTTON_R.id, + OverlayControl.BUTTON_ZL.id, + OverlayControl.BUTTON_ZR.id -> 0.26f + + OverlayControl.BUTTON_STICK_L.id, + OverlayControl.BUTTON_STICK_R.id -> 0.155f + + else -> 0.11f + } + scale *= (IntSetting.OVERLAY_SCALE.getInt() + 50).toFloat() + scale /= 100f + + // Initialize the InputOverlayDrawableButton. + val defaultStateBitmap = getBitmap(context, defaultResId, scale) + val pressedStateBitmap = getBitmap(context, pressedResId, scale) + val overlayDrawable = InputOverlayDrawableButton( + res, + defaultStateBitmap, + pressedStateBitmap, + button, + overlayControlData + ) + + // Get the minimum and maximum coordinates of the screen where the button can be placed. + val min = windowSize.first + val max = windowSize.second + + // The X and Y coordinates of the InputOverlayDrawableButton on the InputOverlay. + // These were set in the input overlay configuration menu. + val drawableX = (position.first * max.x + min.x).toInt() + val drawableY = (position.second * max.y + min.y).toInt() + val width = overlayDrawable.width + val height = overlayDrawable.height + + // Now set the bounds for the InputOverlayDrawableButton. + // This will dictate where on the screen (and the what the size) the InputOverlayDrawableButton will be. + overlayDrawable.setBounds( + drawableX - (width / 2), + drawableY - (height / 2), + drawableX + (width / 2), + drawableY + (height / 2) + ) + + // Need to set the image's position + overlayDrawable.setPosition( + drawableX - (width / 2), + drawableY - (height / 2) + ) + overlayDrawable.setOpacity(IntSetting.OVERLAY_OPACITY.getInt() * 255 / 100) + return overlayDrawable + } + + /** + * Initializes an [InputOverlayDrawableDpad] + * + * @param context The current [Context]. + * @param windowSize The size of the window to draw the overlay on. + * @param defaultResId The [Bitmap] resource ID of the default state. + * @param pressedOneDirectionResId The [Bitmap] resource ID of the pressed state in one direction. + * @param pressedTwoDirectionsResId The [Bitmap] resource ID of the pressed state in two directions. + * @param position The position on screen as represented by an x and y value between 0 and 1. + * @return The initialized [InputOverlayDrawableDpad] + */ + private fun initializeOverlayDpad( + context: Context, + windowSize: Pair, + defaultResId: Int, + pressedOneDirectionResId: Int, + pressedTwoDirectionsResId: Int, + position: Pair + ): InputOverlayDrawableDpad { + // Resources handle for fetching the initial Drawable resource. + val res = context.resources + + // Decide scale based on button ID and user preference + var scale = 0.25f + scale *= (IntSetting.OVERLAY_SCALE.getInt() + 50).toFloat() + scale /= 100f + + // Initialize the InputOverlayDrawableDpad. + val defaultStateBitmap = + getBitmap(context, defaultResId, scale) + val pressedOneDirectionStateBitmap = getBitmap(context, pressedOneDirectionResId, scale) + val pressedTwoDirectionsStateBitmap = + getBitmap(context, pressedTwoDirectionsResId, scale) + + val overlayDrawable = InputOverlayDrawableDpad( + res, + defaultStateBitmap, + pressedOneDirectionStateBitmap, + pressedTwoDirectionsStateBitmap + ) + + // Get the minimum and maximum coordinates of the screen where the button can be placed. + val min = windowSize.first + val max = windowSize.second + + // The X and Y coordinates of the InputOverlayDrawableDpad on the InputOverlay. + // These were set in the input overlay configuration menu. + val drawableX = (position.first * max.x + min.x).toInt() + val drawableY = (position.second * max.y + min.y).toInt() + val width = overlayDrawable.width + val height = overlayDrawable.height + + // Now set the bounds for the InputOverlayDrawableDpad. + // This will dictate where on the screen (and the what the size) the InputOverlayDrawableDpad will be. + overlayDrawable.setBounds( + drawableX - (width / 2), + drawableY - (height / 2), + drawableX + (width / 2), + drawableY + (height / 2) + ) + + // Need to set the image's position + overlayDrawable.setPosition(drawableX - (width / 2), drawableY - (height / 2)) + overlayDrawable.setOpacity(IntSetting.OVERLAY_OPACITY.getInt() * 255 / 100) + return overlayDrawable + } + + /** + * Initializes an [InputOverlayDrawableJoystick] + * + * @param context The current [Context] + * @param windowSize The size of the window to draw the overlay on. + * @param resOuter Resource ID for the outer image of the joystick (the static image that shows the circular bounds). + * @param defaultResInner Resource ID for the default inner image of the joystick (the one you actually move around). + * @param pressedResInner Resource ID for the pressed inner image of the joystick. + * @param joystick Identifier for which joystick this is. + * @param buttonId Identifier for which joystick button this is. + * @param overlayControlData Identifier for determining where a button appears on screen. + * @param position The position on screen as represented by an x and y value between 0 and 1. + * @return The initialized [InputOverlayDrawableJoystick]. + */ + private fun initializeOverlayJoystick( + context: Context, + windowSize: Pair, + resOuter: Int, + defaultResInner: Int, + pressedResInner: Int, + joystick: NativeAnalog, + button: NativeButton, + overlayControlData: OverlayControlData, + position: Pair + ): InputOverlayDrawableJoystick { + // Resources handle for fetching the initial Drawable resource. + val res = context.resources + + // Decide scale based on user preference + var scale = 0.3f + scale *= (IntSetting.OVERLAY_SCALE.getInt() + 50).toFloat() + scale /= 100f + + // Initialize the InputOverlayDrawableJoystick. + val bitmapOuter = getBitmap(context, resOuter, scale) + val bitmapInnerDefault = getBitmap(context, defaultResInner, 1.0f) + val bitmapInnerPressed = getBitmap(context, pressedResInner, 1.0f) + + // Get the minimum and maximum coordinates of the screen where the button can be placed. + val min = windowSize.first + val max = windowSize.second + + // The X and Y coordinates of the InputOverlayDrawableButton on the InputOverlay. + // These were set in the input overlay configuration menu. + val drawableX = (position.first * max.x + min.x).toInt() + val drawableY = (position.second * max.y + min.y).toInt() + val outerScale = 1.66f + + // Now set the bounds for the InputOverlayDrawableJoystick. + // This will dictate where on the screen (and the what the size) the InputOverlayDrawableJoystick will be. + val outerSize = bitmapOuter.width + val outerRect = Rect( + drawableX - (outerSize / 2), + drawableY - (outerSize / 2), + drawableX + (outerSize / 2), + drawableY + (outerSize / 2) + ) + val innerRect = + Rect(0, 0, (outerSize / outerScale).toInt(), (outerSize / outerScale).toInt()) + + // Send the drawableId to the joystick so it can be referenced when saving control position. + val overlayDrawable = InputOverlayDrawableJoystick( + res, + bitmapOuter, + bitmapInnerDefault, + bitmapInnerPressed, + outerRect, + innerRect, + joystick, + button, + overlayControlData.id + ) + + // Need to set the image's position + overlayDrawable.setPosition(drawableX, drawableY) + overlayDrawable.setOpacity(IntSetting.OVERLAY_OPACITY.getInt() * 255 / 100) + return overlayDrawable + } + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/overlay/InputOverlayDrawableButton.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/overlay/InputOverlayDrawableButton.kt new file mode 100644 index 0000000..4c5bc1a --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/overlay/InputOverlayDrawableButton.kt @@ -0,0 +1,151 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.overlay + +import android.content.res.Resources +import android.graphics.Bitmap +import android.graphics.Canvas +import android.graphics.Rect +import android.graphics.drawable.BitmapDrawable +import android.view.MotionEvent +import org.sudachi.sudachi_emu.features.input.NativeInput.ButtonState +import org.sudachi.sudachi_emu.features.input.model.NativeButton +import org.sudachi.sudachi_emu.overlay.model.OverlayControlData + +/** + * Custom [BitmapDrawable] that is capable + * of storing it's own ID. + * + * @param res [Resources] instance. + * @param defaultStateBitmap [Bitmap] to use with the default state Drawable. + * @param pressedStateBitmap [Bitmap] to use with the pressed state Drawable. + * @param button [NativeButton] for this type of button. + */ +class InputOverlayDrawableButton( + res: Resources, + defaultStateBitmap: Bitmap, + pressedStateBitmap: Bitmap, + val button: NativeButton, + val overlayControlData: OverlayControlData +) { + // The ID value what motion event is tracking + var trackId: Int + + // The drawable position on the screen + private var buttonPositionX = 0 + private var buttonPositionY = 0 + + val width: Int + val height: Int + + private val defaultStateBitmap: BitmapDrawable + private val pressedStateBitmap: BitmapDrawable + private var pressedState = false + + private var previousTouchX = 0 + private var previousTouchY = 0 + var controlPositionX = 0 + var controlPositionY = 0 + + init { + this.defaultStateBitmap = BitmapDrawable(res, defaultStateBitmap) + this.pressedStateBitmap = BitmapDrawable(res, pressedStateBitmap) + trackId = -1 + width = this.defaultStateBitmap.intrinsicWidth + height = this.defaultStateBitmap.intrinsicHeight + } + + /** + * Updates button status based on the motion event. + * + * @return true if value was changed + */ + fun updateStatus(event: MotionEvent): Boolean { + val pointerIndex = event.actionIndex + val xPosition = event.getX(pointerIndex).toInt() + val yPosition = event.getY(pointerIndex).toInt() + val pointerId = event.getPointerId(pointerIndex) + val motionEvent = event.action and MotionEvent.ACTION_MASK + val isActionDown = + motionEvent == MotionEvent.ACTION_DOWN || motionEvent == MotionEvent.ACTION_POINTER_DOWN + val isActionUp = + motionEvent == MotionEvent.ACTION_UP || motionEvent == MotionEvent.ACTION_POINTER_UP + + if (isActionDown) { + if (!bounds.contains(xPosition, yPosition)) { + return false + } + pressedState = true + trackId = pointerId + return true + } + + if (isActionUp) { + if (trackId != pointerId) { + return false + } + pressedState = false + trackId = -1 + return true + } + + return false + } + + fun setPosition(x: Int, y: Int) { + buttonPositionX = x + buttonPositionY = y + } + + fun draw(canvas: Canvas?) { + currentStateBitmapDrawable.draw(canvas!!) + } + + private val currentStateBitmapDrawable: BitmapDrawable + get() = if (pressedState) pressedStateBitmap else defaultStateBitmap + + fun onConfigureTouch(event: MotionEvent): Boolean { + val pointerIndex = event.actionIndex + val fingerPositionX = event.getX(pointerIndex).toInt() + val fingerPositionY = event.getY(pointerIndex).toInt() + + when (event.action) { + MotionEvent.ACTION_DOWN -> { + previousTouchX = fingerPositionX + previousTouchY = fingerPositionY + controlPositionX = fingerPositionX - (width / 2) + controlPositionY = fingerPositionY - (height / 2) + } + + MotionEvent.ACTION_MOVE -> { + controlPositionX += fingerPositionX - previousTouchX + controlPositionY += fingerPositionY - previousTouchY + setBounds( + controlPositionX, + controlPositionY, + width + controlPositionX, + height + controlPositionY + ) + previousTouchX = fingerPositionX + previousTouchY = fingerPositionY + } + } + return true + } + + fun setBounds(left: Int, top: Int, right: Int, bottom: Int) { + defaultStateBitmap.setBounds(left, top, right, bottom) + pressedStateBitmap.setBounds(left, top, right, bottom) + } + + fun setOpacity(value: Int) { + defaultStateBitmap.alpha = value + pressedStateBitmap.alpha = value + } + + val status: Int + get() = if (pressedState) ButtonState.PRESSED else ButtonState.RELEASED + val bounds: Rect + get() = defaultStateBitmap.bounds +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/overlay/InputOverlayDrawableDpad.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/overlay/InputOverlayDrawableDpad.kt new file mode 100644 index 0000000..82ba281 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/overlay/InputOverlayDrawableDpad.kt @@ -0,0 +1,266 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.overlay + +import android.content.res.Resources +import android.graphics.Bitmap +import android.graphics.Canvas +import android.graphics.Rect +import android.graphics.drawable.BitmapDrawable +import android.view.MotionEvent +import org.sudachi.sudachi_emu.features.input.NativeInput.ButtonState +import org.sudachi.sudachi_emu.features.input.model.NativeButton + +/** + * Custom [BitmapDrawable] that is capable + * of storing it's own ID. + * + * @param res [Resources] instance. + * @param defaultStateBitmap [Bitmap] of the default state. + * @param pressedOneDirectionStateBitmap [Bitmap] of the pressed state in one direction. + * @param pressedTwoDirectionsStateBitmap [Bitmap] of the pressed state in two direction. + */ +class InputOverlayDrawableDpad( + res: Resources, + defaultStateBitmap: Bitmap, + pressedOneDirectionStateBitmap: Bitmap, + pressedTwoDirectionsStateBitmap: Bitmap +) { + /** + * Gets one of the InputOverlayDrawableDpad's button IDs. + * + * @return the requested InputOverlayDrawableDpad's button ID. + */ + // The ID identifying what type of button this Drawable represents. + val up = NativeButton.DUp + val down = NativeButton.DDown + val left = NativeButton.DLeft + val right = NativeButton.DRight + var trackId: Int + + val width: Int + val height: Int + + private val defaultStateBitmap: BitmapDrawable + private val pressedOneDirectionStateBitmap: BitmapDrawable + private val pressedTwoDirectionsStateBitmap: BitmapDrawable + + private var previousTouchX = 0 + private var previousTouchY = 0 + private var controlPositionX = 0 + private var controlPositionY = 0 + + private var upButtonState = false + private var downButtonState = false + private var leftButtonState = false + private var rightButtonState = false + + init { + this.defaultStateBitmap = BitmapDrawable(res, defaultStateBitmap) + this.pressedOneDirectionStateBitmap = BitmapDrawable(res, pressedOneDirectionStateBitmap) + this.pressedTwoDirectionsStateBitmap = BitmapDrawable(res, pressedTwoDirectionsStateBitmap) + width = this.defaultStateBitmap.intrinsicWidth + height = this.defaultStateBitmap.intrinsicHeight + trackId = -1 + } + + fun updateStatus(event: MotionEvent, dpad_slide: Boolean): Boolean { + val pointerIndex = event.actionIndex + val xPosition = event.getX(pointerIndex).toInt() + val yPosition = event.getY(pointerIndex).toInt() + val pointerId = event.getPointerId(pointerIndex) + val motionEvent = event.action and MotionEvent.ACTION_MASK + val isActionDown = + motionEvent == MotionEvent.ACTION_DOWN || motionEvent == MotionEvent.ACTION_POINTER_DOWN + val isActionUp = + motionEvent == MotionEvent.ACTION_UP || motionEvent == MotionEvent.ACTION_POINTER_UP + if (isActionDown) { + if (!bounds.contains(xPosition, yPosition)) { + return false + } + trackId = pointerId + } + if (isActionUp) { + if (trackId != pointerId) { + return false + } + trackId = -1 + upButtonState = false + downButtonState = false + leftButtonState = false + rightButtonState = false + return true + } + if (trackId == -1) { + return false + } + if (!dpad_slide && !isActionDown) { + return false + } + for (i in 0 until event.pointerCount) { + if (trackId != event.getPointerId(i)) { + continue + } + + var touchX = event.getX(i) + var touchY = event.getY(i) + var maxY = bounds.bottom.toFloat() + var maxX = bounds.right.toFloat() + touchX -= bounds.centerX().toFloat() + maxX -= bounds.centerX().toFloat() + touchY -= bounds.centerY().toFloat() + maxY -= bounds.centerY().toFloat() + val axisX = touchX / maxX + val axisY = touchY / maxY + val oldUpState = upButtonState + val oldDownState = downButtonState + val oldLeftState = leftButtonState + val oldRightState = rightButtonState + + upButtonState = axisY < -VIRT_AXIS_DEADZONE + downButtonState = axisY > VIRT_AXIS_DEADZONE + leftButtonState = axisX < -VIRT_AXIS_DEADZONE + rightButtonState = axisX > VIRT_AXIS_DEADZONE + return oldUpState != upButtonState || + oldDownState != downButtonState || + oldLeftState != leftButtonState || + oldRightState != rightButtonState + } + return false + } + + fun draw(canvas: Canvas) { + val px = controlPositionX + width / 2 + val py = controlPositionY + height / 2 + + // Pressed up + if (upButtonState && !leftButtonState && !rightButtonState) { + pressedOneDirectionStateBitmap.draw(canvas) + return + } + + // Pressed down + if (downButtonState && !leftButtonState && !rightButtonState) { + canvas.save() + canvas.rotate(180f, px.toFloat(), py.toFloat()) + pressedOneDirectionStateBitmap.draw(canvas) + canvas.restore() + return + } + + // Pressed left + if (leftButtonState && !upButtonState && !downButtonState) { + canvas.save() + canvas.rotate(270f, px.toFloat(), py.toFloat()) + pressedOneDirectionStateBitmap.draw(canvas) + canvas.restore() + return + } + + // Pressed right + if (rightButtonState && !upButtonState && !downButtonState) { + canvas.save() + canvas.rotate(90f, px.toFloat(), py.toFloat()) + pressedOneDirectionStateBitmap.draw(canvas) + canvas.restore() + return + } + + // Pressed up left + if (upButtonState && leftButtonState && !rightButtonState) { + pressedTwoDirectionsStateBitmap.draw(canvas) + return + } + + // Pressed up right + if (upButtonState && !leftButtonState && rightButtonState) { + canvas.save() + canvas.rotate(90f, px.toFloat(), py.toFloat()) + pressedTwoDirectionsStateBitmap.draw(canvas) + canvas.restore() + return + } + + // Pressed down right + if (downButtonState && !leftButtonState && rightButtonState) { + canvas.save() + canvas.rotate(180f, px.toFloat(), py.toFloat()) + pressedTwoDirectionsStateBitmap.draw(canvas) + canvas.restore() + return + } + + // Pressed down left + if (downButtonState && leftButtonState && !rightButtonState) { + canvas.save() + canvas.rotate(270f, px.toFloat(), py.toFloat()) + pressedTwoDirectionsStateBitmap.draw(canvas) + canvas.restore() + return + } + + // Not pressed + defaultStateBitmap.draw(canvas) + } + + val upStatus: Int + get() = if (upButtonState) ButtonState.PRESSED else ButtonState.RELEASED + val downStatus: Int + get() = if (downButtonState) ButtonState.PRESSED else ButtonState.RELEASED + val leftStatus: Int + get() = if (leftButtonState) ButtonState.PRESSED else ButtonState.RELEASED + val rightStatus: Int + get() = if (rightButtonState) ButtonState.PRESSED else ButtonState.RELEASED + + fun onConfigureTouch(event: MotionEvent): Boolean { + val pointerIndex = event.actionIndex + val fingerPositionX = event.getX(pointerIndex).toInt() + val fingerPositionY = event.getY(pointerIndex).toInt() + + when (event.action) { + MotionEvent.ACTION_DOWN -> { + previousTouchX = fingerPositionX + previousTouchY = fingerPositionY + } + + MotionEvent.ACTION_MOVE -> { + controlPositionX += fingerPositionX - previousTouchX + controlPositionY += fingerPositionY - previousTouchY + setBounds( + controlPositionX, + controlPositionY, + width + controlPositionX, + height + controlPositionY + ) + previousTouchX = fingerPositionX + previousTouchY = fingerPositionY + } + } + return true + } + + fun setPosition(x: Int, y: Int) { + controlPositionX = x + controlPositionY = y + } + + fun setBounds(left: Int, top: Int, right: Int, bottom: Int) { + defaultStateBitmap.setBounds(left, top, right, bottom) + pressedOneDirectionStateBitmap.setBounds(left, top, right, bottom) + pressedTwoDirectionsStateBitmap.setBounds(left, top, right, bottom) + } + + fun setOpacity(value: Int) { + defaultStateBitmap.alpha = value + pressedOneDirectionStateBitmap.alpha = value + pressedTwoDirectionsStateBitmap.alpha = value + } + + val bounds: Rect + get() = defaultStateBitmap.bounds + + companion object { + const val VIRT_AXIS_DEADZONE = 0.5f + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/overlay/InputOverlayDrawableJoystick.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/overlay/InputOverlayDrawableJoystick.kt new file mode 100644 index 0000000..1b7ba40 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/overlay/InputOverlayDrawableJoystick.kt @@ -0,0 +1,292 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.overlay + +import android.content.res.Resources +import android.graphics.Bitmap +import android.graphics.Canvas +import android.graphics.Rect +import android.graphics.drawable.BitmapDrawable +import android.view.MotionEvent +import kotlin.math.atan2 +import kotlin.math.cos +import kotlin.math.sin +import kotlin.math.sqrt +import org.sudachi.sudachi_emu.features.input.NativeInput.ButtonState +import org.sudachi.sudachi_emu.features.input.model.NativeAnalog +import org.sudachi.sudachi_emu.features.input.model.NativeButton +import org.sudachi.sudachi_emu.features.settings.model.BooleanSetting + +/** + * Custom [BitmapDrawable] that is capable + * of storing it's own ID. + * + * @param res [Resources] instance. + * @param bitmapOuter [Bitmap] which represents the outer non-movable part of the joystick. + * @param bitmapInnerDefault [Bitmap] which represents the default inner movable part of the joystick. + * @param bitmapInnerPressed [Bitmap] which represents the pressed inner movable part of the joystick. + * @param rectOuter [Rect] which represents the outer joystick bounds. + * @param rectInner [Rect] which represents the inner joystick bounds. + * @param joystick The [NativeAnalog] this Drawable represents. + * @param button The [NativeButton] this Drawable represents. + */ +class InputOverlayDrawableJoystick( + res: Resources, + bitmapOuter: Bitmap, + bitmapInnerDefault: Bitmap, + bitmapInnerPressed: Bitmap, + rectOuter: Rect, + rectInner: Rect, + val joystick: NativeAnalog, + val button: NativeButton, + val prefId: String +) { + // The ID value what motion event is tracking + var trackId = -1 + + var xAxis = 0f + private var yAxis = 0f + + val width: Int + val height: Int + + private var opacity: Int = 0 + + private var virtBounds: Rect + private var origBounds: Rect + + private val outerBitmap: BitmapDrawable + private val defaultStateInnerBitmap: BitmapDrawable + private val pressedStateInnerBitmap: BitmapDrawable + + private var previousTouchX = 0 + private var previousTouchY = 0 + var controlPositionX = 0 + var controlPositionY = 0 + + private val boundsBoxBitmap: BitmapDrawable + + private var pressedState = false + + // TODO: Add button support + val buttonStatus: Int + get() = ButtonState.RELEASED + var bounds: Rect + get() = outerBitmap.bounds + set(bounds) { + outerBitmap.bounds = bounds + } + + // Nintendo joysticks have y axis inverted + val realYAxis: Float + get() = -yAxis + + private val currentStateBitmapDrawable: BitmapDrawable + get() = if (pressedState) pressedStateInnerBitmap else defaultStateInnerBitmap + + init { + outerBitmap = BitmapDrawable(res, bitmapOuter) + defaultStateInnerBitmap = BitmapDrawable(res, bitmapInnerDefault) + pressedStateInnerBitmap = BitmapDrawable(res, bitmapInnerPressed) + boundsBoxBitmap = BitmapDrawable(res, bitmapOuter) + width = bitmapOuter.width + height = bitmapOuter.height + bounds = rectOuter + defaultStateInnerBitmap.bounds = rectInner + pressedStateInnerBitmap.bounds = rectInner + virtBounds = bounds + origBounds = outerBitmap.copyBounds() + boundsBoxBitmap.alpha = 0 + boundsBoxBitmap.bounds = virtBounds + setInnerBounds() + } + + fun draw(canvas: Canvas?) { + outerBitmap.draw(canvas!!) + currentStateBitmapDrawable.draw(canvas) + boundsBoxBitmap.draw(canvas) + } + + fun updateStatus(event: MotionEvent): Boolean { + val pointerIndex = event.actionIndex + val xPosition = event.getX(pointerIndex).toInt() + val yPosition = event.getY(pointerIndex).toInt() + val pointerId = event.getPointerId(pointerIndex) + val motionEvent = event.action and MotionEvent.ACTION_MASK + val isActionDown = + motionEvent == MotionEvent.ACTION_DOWN || motionEvent == MotionEvent.ACTION_POINTER_DOWN + val isActionUp = + motionEvent == MotionEvent.ACTION_UP || motionEvent == MotionEvent.ACTION_POINTER_UP + + if (isActionDown) { + if (!bounds.contains(xPosition, yPosition)) { + return false + } + pressedState = true + outerBitmap.alpha = 0 + boundsBoxBitmap.alpha = opacity + if (BooleanSetting.JOYSTICK_REL_CENTER.getBoolean()) { + virtBounds.offset( + xPosition - virtBounds.centerX(), + yPosition - virtBounds.centerY() + ) + } + boundsBoxBitmap.bounds = virtBounds + trackId = pointerId + } + + if (isActionUp) { + if (trackId != pointerId) { + return false + } + pressedState = false + xAxis = 0.0f + yAxis = 0.0f + outerBitmap.alpha = opacity + boundsBoxBitmap.alpha = 0 + virtBounds = Rect( + origBounds.left, + origBounds.top, + origBounds.right, + origBounds.bottom + ) + bounds = Rect( + origBounds.left, + origBounds.top, + origBounds.right, + origBounds.bottom + ) + setInnerBounds() + trackId = -1 + return true + } + + if (trackId == -1) return false + + for (i in 0 until event.pointerCount) { + if (trackId != event.getPointerId(i)) { + continue + } + var touchX = event.getX(i) + var touchY = event.getY(i) + var maxY = virtBounds.bottom.toFloat() + var maxX = virtBounds.right.toFloat() + touchX -= virtBounds.centerX().toFloat() + maxX -= virtBounds.centerX().toFloat() + touchY -= virtBounds.centerY().toFloat() + maxY -= virtBounds.centerY().toFloat() + val axisX = touchX / maxX + val axisY = touchY / maxY + val oldXAxis = xAxis + val oldYAxis = yAxis + + // Clamp the circle pad input to a circle + val angle = atan2(axisY.toDouble(), axisX.toDouble()).toFloat() + var radius = sqrt((axisX * axisX + axisY * axisY).toDouble()).toFloat() + if (radius > 1.0f) { + radius = 1.0f + } + xAxis = cos(angle.toDouble()).toFloat() * radius + yAxis = sin(angle.toDouble()).toFloat() * radius + setInnerBounds() + return oldXAxis != xAxis && oldYAxis != yAxis + } + return false + } + + fun onConfigureTouch(event: MotionEvent): Boolean { + val pointerIndex = event.actionIndex + val fingerPositionX = event.getX(pointerIndex).toInt() + val fingerPositionY = event.getY(pointerIndex).toInt() + + when (event.action) { + MotionEvent.ACTION_DOWN -> { + previousTouchX = fingerPositionX + previousTouchY = fingerPositionY + controlPositionX = fingerPositionX - (width / 2) + controlPositionY = fingerPositionY - (height / 2) + } + + MotionEvent.ACTION_MOVE -> { + controlPositionX += fingerPositionX - previousTouchX + controlPositionY += fingerPositionY - previousTouchY + bounds = Rect( + controlPositionX, + controlPositionY, + outerBitmap.intrinsicWidth + controlPositionX, + outerBitmap.intrinsicHeight + controlPositionY + ) + virtBounds = Rect( + controlPositionX, + controlPositionY, + outerBitmap.intrinsicWidth + controlPositionX, + outerBitmap.intrinsicHeight + controlPositionY + ) + setInnerBounds() + bounds = Rect( + Rect( + controlPositionX, + controlPositionY, + outerBitmap.intrinsicWidth + controlPositionX, + outerBitmap.intrinsicHeight + controlPositionY + ) + ) + previousTouchX = fingerPositionX + previousTouchY = fingerPositionY + } + } + origBounds = outerBitmap.copyBounds() + return true + } + + private fun setInnerBounds() { + var x = virtBounds.centerX() + (xAxis * (virtBounds.width() / 2)).toInt() + var y = virtBounds.centerY() + (yAxis * (virtBounds.height() / 2)).toInt() + if (x > virtBounds.centerX() + virtBounds.width() / 2) { + x = + virtBounds.centerX() + virtBounds.width() / 2 + } + if (x < virtBounds.centerX() - virtBounds.width() / 2) { + x = + virtBounds.centerX() - virtBounds.width() / 2 + } + if (y > virtBounds.centerY() + virtBounds.height() / 2) { + y = + virtBounds.centerY() + virtBounds.height() / 2 + } + if (y < virtBounds.centerY() - virtBounds.height() / 2) { + y = + virtBounds.centerY() - virtBounds.height() / 2 + } + val width = pressedStateInnerBitmap.bounds.width() / 2 + val height = pressedStateInnerBitmap.bounds.height() / 2 + defaultStateInnerBitmap.setBounds( + x - width, + y - height, + x + width, + y + height + ) + pressedStateInnerBitmap.bounds = defaultStateInnerBitmap.bounds + } + + fun setPosition(x: Int, y: Int) { + controlPositionX = x + controlPositionY = y + } + + fun setOpacity(value: Int) { + opacity = value + + defaultStateInnerBitmap.alpha = value + pressedStateInnerBitmap.alpha = value + + if (trackId == -1) { + outerBitmap.alpha = value + boundsBoxBitmap.alpha = 0 + } else { + outerBitmap.alpha = 0 + boundsBoxBitmap.alpha = value + } + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/overlay/model/OverlayControl.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/overlay/model/OverlayControl.kt new file mode 100644 index 0000000..d0d1630 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/overlay/model/OverlayControl.kt @@ -0,0 +1,188 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.overlay.model + +import androidx.annotation.IntegerRes +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.SudachiApplication + +enum class OverlayControl( + val id: String, + val defaultVisibility: Boolean, + @IntegerRes val defaultLandscapePositionResources: Pair, + @IntegerRes val defaultPortraitPositionResources: Pair, + @IntegerRes val defaultFoldablePositionResources: Pair +) { + BUTTON_A( + "button_a", + true, + Pair(R.integer.BUTTON_A_X, R.integer.BUTTON_A_Y), + Pair(R.integer.BUTTON_A_X_PORTRAIT, R.integer.BUTTON_A_Y_PORTRAIT), + Pair(R.integer.BUTTON_A_X_FOLDABLE, R.integer.BUTTON_A_Y_FOLDABLE) + ), + BUTTON_B( + "button_b", + true, + Pair(R.integer.BUTTON_B_X, R.integer.BUTTON_B_Y), + Pair(R.integer.BUTTON_B_X_PORTRAIT, R.integer.BUTTON_B_Y_PORTRAIT), + Pair(R.integer.BUTTON_B_X_FOLDABLE, R.integer.BUTTON_B_Y_FOLDABLE) + ), + BUTTON_X( + "button_x", + true, + Pair(R.integer.BUTTON_X_X, R.integer.BUTTON_X_Y), + Pair(R.integer.BUTTON_X_X_PORTRAIT, R.integer.BUTTON_X_Y_PORTRAIT), + Pair(R.integer.BUTTON_X_X_FOLDABLE, R.integer.BUTTON_X_Y_FOLDABLE) + ), + BUTTON_Y( + "button_y", + true, + Pair(R.integer.BUTTON_Y_X, R.integer.BUTTON_Y_Y), + Pair(R.integer.BUTTON_Y_X_PORTRAIT, R.integer.BUTTON_Y_Y_PORTRAIT), + Pair(R.integer.BUTTON_Y_X_FOLDABLE, R.integer.BUTTON_Y_Y_FOLDABLE) + ), + BUTTON_PLUS( + "button_plus", + true, + Pair(R.integer.BUTTON_PLUS_X, R.integer.BUTTON_PLUS_Y), + Pair(R.integer.BUTTON_PLUS_X_PORTRAIT, R.integer.BUTTON_PLUS_Y_PORTRAIT), + Pair(R.integer.BUTTON_PLUS_X_FOLDABLE, R.integer.BUTTON_PLUS_Y_FOLDABLE) + ), + BUTTON_MINUS( + "button_minus", + true, + Pair(R.integer.BUTTON_MINUS_X, R.integer.BUTTON_MINUS_Y), + Pair(R.integer.BUTTON_MINUS_X_PORTRAIT, R.integer.BUTTON_MINUS_Y_PORTRAIT), + Pair(R.integer.BUTTON_MINUS_X_FOLDABLE, R.integer.BUTTON_MINUS_Y_FOLDABLE) + ), + BUTTON_HOME( + "button_home", + false, + Pair(R.integer.BUTTON_HOME_X, R.integer.BUTTON_HOME_Y), + Pair(R.integer.BUTTON_HOME_X_PORTRAIT, R.integer.BUTTON_HOME_Y_PORTRAIT), + Pair(R.integer.BUTTON_HOME_X_FOLDABLE, R.integer.BUTTON_HOME_Y_FOLDABLE) + ), + BUTTON_CAPTURE( + "button_capture", + false, + Pair(R.integer.BUTTON_CAPTURE_X, R.integer.BUTTON_CAPTURE_Y), + Pair(R.integer.BUTTON_CAPTURE_X_PORTRAIT, R.integer.BUTTON_CAPTURE_Y_PORTRAIT), + Pair(R.integer.BUTTON_CAPTURE_X_FOLDABLE, R.integer.BUTTON_CAPTURE_Y_FOLDABLE) + ), + BUTTON_L( + "button_l", + true, + Pair(R.integer.BUTTON_L_X, R.integer.BUTTON_L_Y), + Pair(R.integer.BUTTON_L_X_PORTRAIT, R.integer.BUTTON_L_Y_PORTRAIT), + Pair(R.integer.BUTTON_L_X_FOLDABLE, R.integer.BUTTON_L_Y_FOLDABLE) + ), + BUTTON_R( + "button_r", + true, + Pair(R.integer.BUTTON_R_X, R.integer.BUTTON_R_Y), + Pair(R.integer.BUTTON_R_X_PORTRAIT, R.integer.BUTTON_R_Y_PORTRAIT), + Pair(R.integer.BUTTON_R_X_FOLDABLE, R.integer.BUTTON_R_Y_FOLDABLE) + ), + BUTTON_ZL( + "button_zl", + true, + Pair(R.integer.BUTTON_ZL_X, R.integer.BUTTON_ZL_Y), + Pair(R.integer.BUTTON_ZL_X_PORTRAIT, R.integer.BUTTON_ZL_Y_PORTRAIT), + Pair(R.integer.BUTTON_ZL_X_FOLDABLE, R.integer.BUTTON_ZL_Y_FOLDABLE) + ), + BUTTON_ZR( + "button_zr", + true, + Pair(R.integer.BUTTON_ZR_X, R.integer.BUTTON_ZR_Y), + Pair(R.integer.BUTTON_ZR_X_PORTRAIT, R.integer.BUTTON_ZR_Y_PORTRAIT), + Pair(R.integer.BUTTON_ZR_X_FOLDABLE, R.integer.BUTTON_ZR_Y_FOLDABLE) + ), + BUTTON_STICK_L( + "button_stick_l", + true, + Pair(R.integer.BUTTON_STICK_L_X, R.integer.BUTTON_STICK_L_Y), + Pair(R.integer.BUTTON_STICK_L_X_PORTRAIT, R.integer.BUTTON_STICK_L_Y_PORTRAIT), + Pair(R.integer.BUTTON_STICK_L_X_FOLDABLE, R.integer.BUTTON_STICK_L_Y_FOLDABLE) + ), + BUTTON_STICK_R( + "button_stick_r", + true, + Pair(R.integer.BUTTON_STICK_R_X, R.integer.BUTTON_STICK_R_Y), + Pair(R.integer.BUTTON_STICK_R_X_PORTRAIT, R.integer.BUTTON_STICK_R_Y_PORTRAIT), + Pair(R.integer.BUTTON_STICK_R_X_FOLDABLE, R.integer.BUTTON_STICK_R_Y_FOLDABLE) + ), + STICK_L( + "stick_l", + true, + Pair(R.integer.STICK_L_X, R.integer.STICK_L_Y), + Pair(R.integer.STICK_L_X_PORTRAIT, R.integer.STICK_L_Y_PORTRAIT), + Pair(R.integer.STICK_L_X_FOLDABLE, R.integer.STICK_L_Y_FOLDABLE) + ), + STICK_R( + "stick_r", + true, + Pair(R.integer.STICK_R_X, R.integer.STICK_R_Y), + Pair(R.integer.STICK_R_X_PORTRAIT, R.integer.STICK_R_Y_PORTRAIT), + Pair(R.integer.STICK_R_X_FOLDABLE, R.integer.STICK_R_Y_FOLDABLE) + ), + COMBINED_DPAD( + "combined_dpad", + true, + Pair(R.integer.COMBINED_DPAD_X, R.integer.COMBINED_DPAD_Y), + Pair(R.integer.COMBINED_DPAD_X_PORTRAIT, R.integer.COMBINED_DPAD_Y_PORTRAIT), + Pair(R.integer.COMBINED_DPAD_X_FOLDABLE, R.integer.COMBINED_DPAD_Y_FOLDABLE) + ); + + fun getDefaultPositionForLayout(layout: OverlayLayout): Pair { + val rawResourcePair: Pair + SudachiApplication.appContext.resources.apply { + rawResourcePair = when (layout) { + OverlayLayout.Landscape -> { + Pair( + getInteger(this@OverlayControl.defaultLandscapePositionResources.first), + getInteger(this@OverlayControl.defaultLandscapePositionResources.second) + ) + } + + OverlayLayout.Portrait -> { + Pair( + getInteger(this@OverlayControl.defaultPortraitPositionResources.first), + getInteger(this@OverlayControl.defaultPortraitPositionResources.second) + ) + } + + OverlayLayout.Foldable -> { + Pair( + getInteger(this@OverlayControl.defaultFoldablePositionResources.first), + getInteger(this@OverlayControl.defaultFoldablePositionResources.second) + ) + } + } + } + + return Pair( + rawResourcePair.first.toDouble() / 1000, + rawResourcePair.second.toDouble() / 1000 + ) + } + + fun toOverlayControlData(): OverlayControlData = + OverlayControlData( + id, + defaultVisibility, + getDefaultPositionForLayout(OverlayLayout.Landscape), + getDefaultPositionForLayout(OverlayLayout.Portrait), + getDefaultPositionForLayout(OverlayLayout.Foldable) + ) + + companion object { + val map: HashMap by lazy { + val hashMap = hashMapOf() + entries.forEach { hashMap[it.id] = it } + hashMap + } + + fun from(id: String): OverlayControl? = map[id] + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/overlay/model/OverlayControlData.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/overlay/model/OverlayControlData.kt new file mode 100644 index 0000000..901187c --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/overlay/model/OverlayControlData.kt @@ -0,0 +1,19 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.overlay.model + +data class OverlayControlData( + val id: String, + var enabled: Boolean, + var landscapePosition: Pair, + var portraitPosition: Pair, + var foldablePosition: Pair +) { + fun positionFromLayout(layout: OverlayLayout): Pair = + when (layout) { + OverlayLayout.Landscape -> landscapePosition + OverlayLayout.Portrait -> portraitPosition + OverlayLayout.Foldable -> foldablePosition + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/overlay/model/OverlayControlDefault.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/overlay/model/OverlayControlDefault.kt new file mode 100644 index 0000000..ec9bd67 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/overlay/model/OverlayControlDefault.kt @@ -0,0 +1,13 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.overlay.model + +import androidx.annotation.IntegerRes + +data class OverlayControlDefault( + val buttonId: String, + @IntegerRes val landscapePositionResource: Pair, + @IntegerRes val portraitPositionResource: Pair, + @IntegerRes val foldablePositionResource: Pair +) diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/overlay/model/OverlayLayout.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/overlay/model/OverlayLayout.kt new file mode 100644 index 0000000..fe3d2d0 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/overlay/model/OverlayLayout.kt @@ -0,0 +1,10 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.overlay.model + +enum class OverlayLayout(val id: String) { + Landscape("Landscape"), + Portrait("Portrait"), + Foldable("Foldable") +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/ui/GamesFragment.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/ui/GamesFragment.kt new file mode 100644 index 0000000..e9eddee --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/ui/GamesFragment.kt @@ -0,0 +1,160 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.ui + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.appcompat.app.AppCompatActivity +import androidx.core.view.ViewCompat +import androidx.core.view.WindowInsetsCompat +import androidx.core.view.updatePadding +import androidx.fragment.app.Fragment +import androidx.fragment.app.activityViewModels +import com.google.android.material.color.MaterialColors +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.adapters.GameAdapter +import org.sudachi.sudachi_emu.databinding.FragmentGamesBinding +import org.sudachi.sudachi_emu.layout.AutofitGridLayoutManager +import org.sudachi.sudachi_emu.model.GamesViewModel +import org.sudachi.sudachi_emu.model.HomeViewModel +import org.sudachi.sudachi_emu.utils.ViewUtils.setVisible +import org.sudachi.sudachi_emu.utils.ViewUtils.updateMargins +import org.sudachi.sudachi_emu.utils.collect + +class GamesFragment : Fragment() { + private var _binding: FragmentGamesBinding? = null + private val binding get() = _binding!! + + private val gamesViewModel: GamesViewModel by activityViewModels() + private val homeViewModel: HomeViewModel by activityViewModels() + + override fun onCreateView( + inflater: LayoutInflater, + container: ViewGroup?, + savedInstanceState: Bundle? + ): View { + _binding = FragmentGamesBinding.inflate(inflater) + return binding.root + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + homeViewModel.setNavigationVisibility(visible = true, animated = true) + homeViewModel.setStatusBarShadeVisibility(true) + + binding.gridGames.apply { + layoutManager = AutofitGridLayoutManager( + requireContext(), + requireContext().resources.getDimensionPixelSize(R.dimen.card_width) + ) + adapter = GameAdapter(requireActivity() as AppCompatActivity) + } + + binding.swipeRefresh.apply { + // Add swipe down to refresh gesture + setOnRefreshListener { + gamesViewModel.reloadGames(false) + } + + // Set theme color to the refresh animation's background + setProgressBackgroundColorSchemeColor( + MaterialColors.getColor( + binding.swipeRefresh, + com.google.android.material.R.attr.colorPrimary + ) + ) + setColorSchemeColors( + MaterialColors.getColor( + binding.swipeRefresh, + com.google.android.material.R.attr.colorOnPrimary + ) + ) + + // Make sure the loading indicator appears even if the layout is told to refresh before being fully drawn + post { + if (_binding == null) { + return@post + } + binding.swipeRefresh.isRefreshing = gamesViewModel.isReloading.value + } + } + + gamesViewModel.isReloading.collect(viewLifecycleOwner) { + binding.swipeRefresh.isRefreshing = it + binding.noticeText.setVisible( + visible = gamesViewModel.games.value.isEmpty() && !it, + gone = false + ) + } + gamesViewModel.games.collect(viewLifecycleOwner) { + (binding.gridGames.adapter as GameAdapter).submitList(it) + } + gamesViewModel.shouldSwapData.collect( + viewLifecycleOwner, + resetState = { gamesViewModel.setShouldSwapData(false) } + ) { + if (it) { + (binding.gridGames.adapter as GameAdapter).submitList(gamesViewModel.games.value) + } + } + gamesViewModel.shouldScrollToTop.collect( + viewLifecycleOwner, + resetState = { gamesViewModel.setShouldScrollToTop(false) } + ) { if (it) scrollToTop() } + + setInsets() + } + + override fun onDestroyView() { + super.onDestroyView() + _binding = null + } + + private fun scrollToTop() { + if (_binding != null) { + binding.gridGames.smoothScrollToPosition(0) + } + } + + private fun setInsets() = + ViewCompat.setOnApplyWindowInsetsListener( + binding.root + ) { view: View, windowInsets: WindowInsetsCompat -> + val barInsets = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars()) + val cutoutInsets = windowInsets.getInsets(WindowInsetsCompat.Type.displayCutout()) + val extraListSpacing = resources.getDimensionPixelSize(R.dimen.spacing_large) + val spacingNavigation = resources.getDimensionPixelSize(R.dimen.spacing_navigation) + val spacingNavigationRail = + resources.getDimensionPixelSize(R.dimen.spacing_navigation_rail) + + binding.gridGames.updatePadding( + top = barInsets.top + extraListSpacing, + bottom = barInsets.bottom + spacingNavigation + extraListSpacing + ) + + binding.swipeRefresh.setProgressViewEndTarget( + false, + barInsets.top + resources.getDimensionPixelSize(R.dimen.spacing_refresh_end) + ) + + val leftInsets = barInsets.left + cutoutInsets.left + val rightInsets = barInsets.right + cutoutInsets.right + val left: Int + val right: Int + if (ViewCompat.getLayoutDirection(view) == ViewCompat.LAYOUT_DIRECTION_LTR) { + left = leftInsets + spacingNavigationRail + right = rightInsets + } else { + left = leftInsets + right = rightInsets + spacingNavigationRail + } + binding.swipeRefresh.updateMargins(left = left, right = right) + + binding.noticeText.updatePadding(bottom = spacingNavigation) + + windowInsets + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/ui/main/MainActivity.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/ui/main/MainActivity.kt new file mode 100644 index 0000000..1a84992 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/ui/main/MainActivity.kt @@ -0,0 +1,692 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.ui.main + +import android.content.Intent +import android.net.Uri +import android.os.Bundle +import android.view.View +import android.view.ViewGroup.MarginLayoutParams +import android.view.WindowManager +import android.view.animation.PathInterpolator +import android.widget.Toast +import androidx.activity.result.contract.ActivityResultContracts +import androidx.activity.viewModels +import androidx.appcompat.app.AppCompatActivity +import androidx.core.content.ContextCompat +import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen +import androidx.core.view.ViewCompat +import androidx.core.view.WindowCompat +import androidx.core.view.WindowInsetsCompat +import androidx.navigation.NavController +import androidx.navigation.fragment.NavHostFragment +import androidx.navigation.ui.setupWithNavController +import androidx.preference.PreferenceManager +import com.google.android.material.color.MaterialColors +import com.google.android.material.navigation.NavigationBarView +import java.io.File +import java.io.FilenameFilter +import org.sudachi.sudachi_emu.HomeNavigationDirections +import org.sudachi.sudachi_emu.NativeLibrary +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.databinding.ActivityMainBinding +import org.sudachi.sudachi_emu.features.settings.model.Settings +import org.sudachi.sudachi_emu.fragments.AddGameFolderDialogFragment +import org.sudachi.sudachi_emu.fragments.ProgressDialogFragment +import org.sudachi.sudachi_emu.fragments.MessageDialogFragment +import org.sudachi.sudachi_emu.model.AddonViewModel +import org.sudachi.sudachi_emu.model.DriverViewModel +import org.sudachi.sudachi_emu.model.GamesViewModel +import org.sudachi.sudachi_emu.model.HomeViewModel +import org.sudachi.sudachi_emu.model.InstallResult +import org.sudachi.sudachi_emu.model.TaskState +import org.sudachi.sudachi_emu.model.TaskViewModel +import org.sudachi.sudachi_emu.utils.* +import org.sudachi.sudachi_emu.utils.ViewUtils.setVisible +import java.io.BufferedInputStream +import java.io.BufferedOutputStream +import java.util.zip.ZipEntry +import java.util.zip.ZipInputStream + +class MainActivity : AppCompatActivity(), ThemeProvider { + private lateinit var binding: ActivityMainBinding + + private val homeViewModel: HomeViewModel by viewModels() + private val gamesViewModel: GamesViewModel by viewModels() + private val taskViewModel: TaskViewModel by viewModels() + private val addonViewModel: AddonViewModel by viewModels() + private val driverViewModel: DriverViewModel by viewModels() + + override var themeId: Int = 0 + + private val CHECKED_DECRYPTION = "CheckedDecryption" + private var checkedDecryption = false + + override fun onCreate(savedInstanceState: Bundle?) { + val splashScreen = installSplashScreen() + splashScreen.setKeepOnScreenCondition { !DirectoryInitialization.areDirectoriesReady } + + ThemeHelper.setTheme(this) + + super.onCreate(savedInstanceState) + + binding = ActivityMainBinding.inflate(layoutInflater) + setContentView(binding.root) + + if (savedInstanceState != null) { + checkedDecryption = savedInstanceState.getBoolean(CHECKED_DECRYPTION) + } + if (!checkedDecryption) { + val firstTimeSetup = PreferenceManager.getDefaultSharedPreferences(applicationContext) + .getBoolean(Settings.PREF_FIRST_APP_LAUNCH, true) + if (!firstTimeSetup) { + checkKeys() + } + checkedDecryption = true + } + + WindowCompat.setDecorFitsSystemWindows(window, false) + window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING) + + window.statusBarColor = + ContextCompat.getColor(applicationContext, android.R.color.transparent) + window.navigationBarColor = + ContextCompat.getColor(applicationContext, android.R.color.transparent) + + binding.statusBarShade.setBackgroundColor( + ThemeHelper.getColorWithOpacity( + MaterialColors.getColor( + binding.root, + com.google.android.material.R.attr.colorSurface + ), + ThemeHelper.SYSTEM_BAR_ALPHA + ) + ) + if (InsetsHelper.getSystemGestureType(applicationContext) != + InsetsHelper.GESTURE_NAVIGATION + ) { + binding.navigationBarShade.setBackgroundColor( + ThemeHelper.getColorWithOpacity( + MaterialColors.getColor( + binding.root, + com.google.android.material.R.attr.colorSurface + ), + ThemeHelper.SYSTEM_BAR_ALPHA + ) + ) + } + + val navHostFragment = + supportFragmentManager.findFragmentById(R.id.fragment_container) as NavHostFragment + setUpNavigation(navHostFragment.navController) + (binding.navigationView as NavigationBarView).setOnItemReselectedListener { + when (it.itemId) { + R.id.gamesFragment -> gamesViewModel.setShouldScrollToTop(true) + R.id.searchFragment -> gamesViewModel.setSearchFocused(true) + R.id.homeSettingsFragment -> { + val action = HomeNavigationDirections.actionGlobalSettingsActivity( + null, + Settings.MenuTag.SECTION_ROOT + ) + navHostFragment.navController.navigate(action) + } + } + } + + // Prevents navigation from being drawn for a short time on recreation if set to hidden + if (!homeViewModel.navigationVisible.value.first) { + binding.navigationView.setVisible(visible = false, gone = false) + binding.statusBarShade.setVisible(visible = false, gone = false) + } + + homeViewModel.navigationVisible.collect(this) { showNavigation(it.first, it.second) } + homeViewModel.statusBarShadeVisible.collect(this) { showStatusBarShade(it) } + homeViewModel.contentToInstall.collect( + this, + resetState = { homeViewModel.setContentToInstall(null) } + ) { + if (it != null) { + installContent(it) + } + } + homeViewModel.checkKeys.collect(this, resetState = { homeViewModel.setCheckKeys(false) }) { + if (it) checkKeys() + } + + setInsets() + } + + private fun checkKeys() { + if (!NativeLibrary.areKeysPresent()) { + MessageDialogFragment.newInstance( + titleId = R.string.keys_missing, + descriptionId = R.string.keys_missing_description, + helpLinkId = R.string.keys_missing_help + ).show(supportFragmentManager, MessageDialogFragment.TAG) + } + } + + override fun onSaveInstanceState(outState: Bundle) { + super.onSaveInstanceState(outState) + outState.putBoolean(CHECKED_DECRYPTION, checkedDecryption) + } + + fun finishSetup(navController: NavController) { + navController.navigate(R.id.action_firstTimeSetupFragment_to_gamesFragment) + (binding.navigationView as NavigationBarView).setupWithNavController(navController) + showNavigation(visible = true, animated = true) + } + + private fun setUpNavigation(navController: NavController) { + val firstTimeSetup = PreferenceManager.getDefaultSharedPreferences(applicationContext) + .getBoolean(Settings.PREF_FIRST_APP_LAUNCH, true) + + if (firstTimeSetup && !homeViewModel.navigatedToSetup) { + navController.navigate(R.id.firstTimeSetupFragment) + homeViewModel.navigatedToSetup = true + } else { + (binding.navigationView as NavigationBarView).setupWithNavController(navController) + } + } + + private fun showNavigation(visible: Boolean, animated: Boolean) { + if (!animated) { + binding.navigationView.setVisible(visible) + return + } + + val smallLayout = resources.getBoolean(R.bool.small_layout) + binding.navigationView.animate().apply { + if (visible) { + binding.navigationView.setVisible(true) + duration = 300 + interpolator = PathInterpolator(0.05f, 0.7f, 0.1f, 1f) + + if (smallLayout) { + binding.navigationView.translationY = + binding.navigationView.height.toFloat() * 2 + translationY(0f) + } else { + if (ViewCompat.getLayoutDirection(binding.navigationView) == + ViewCompat.LAYOUT_DIRECTION_LTR + ) { + binding.navigationView.translationX = + binding.navigationView.width.toFloat() * -2 + translationX(0f) + } else { + binding.navigationView.translationX = + binding.navigationView.width.toFloat() * 2 + translationX(0f) + } + } + } else { + duration = 300 + interpolator = PathInterpolator(0.3f, 0f, 0.8f, 0.15f) + + if (smallLayout) { + translationY(binding.navigationView.height.toFloat() * 2) + } else { + if (ViewCompat.getLayoutDirection(binding.navigationView) == + ViewCompat.LAYOUT_DIRECTION_LTR + ) { + translationX(binding.navigationView.width.toFloat() * -2) + } else { + translationX(binding.navigationView.width.toFloat() * 2) + } + } + } + }.withEndAction { + if (!visible) { + binding.navigationView.setVisible(visible = false, gone = false) + } + }.start() + } + + private fun showStatusBarShade(visible: Boolean) { + binding.statusBarShade.animate().apply { + if (visible) { + binding.statusBarShade.setVisible(true) + binding.statusBarShade.translationY = binding.statusBarShade.height.toFloat() * -2 + duration = 300 + translationY(0f) + interpolator = PathInterpolator(0.05f, 0.7f, 0.1f, 1f) + } else { + duration = 300 + translationY(binding.navigationView.height.toFloat() * -2) + interpolator = PathInterpolator(0.3f, 0f, 0.8f, 0.15f) + } + }.withEndAction { + if (!visible) { + binding.statusBarShade.setVisible(visible = false, gone = false) + } + }.start() + } + + override fun onResume() { + ThemeHelper.setCorrectTheme(this) + super.onResume() + } + + private fun setInsets() = + ViewCompat.setOnApplyWindowInsetsListener( + binding.root + ) { _: View, windowInsets: WindowInsetsCompat -> + val insets = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars()) + val mlpStatusShade = binding.statusBarShade.layoutParams as MarginLayoutParams + mlpStatusShade.height = insets.top + binding.statusBarShade.layoutParams = mlpStatusShade + + // The only situation where we care to have a nav bar shade is when it's at the bottom + // of the screen where scrolling list elements can go behind it. + val mlpNavShade = binding.navigationBarShade.layoutParams as MarginLayoutParams + mlpNavShade.height = insets.bottom + binding.navigationBarShade.layoutParams = mlpNavShade + + windowInsets + } + + override fun setTheme(resId: Int) { + super.setTheme(resId) + themeId = resId + } + + val getGamesDirectory = + registerForActivityResult(ActivityResultContracts.OpenDocumentTree()) { result -> + if (result != null) { + processGamesDir(result) + } + } + + fun processGamesDir(result: Uri) { + contentResolver.takePersistableUriPermission( + result, + Intent.FLAG_GRANT_READ_URI_PERMISSION + ) + + val uriString = result.toString() + val folder = gamesViewModel.folders.value.firstOrNull { it.uriString == uriString } + if (folder != null) { + Toast.makeText( + applicationContext, + R.string.folder_already_added, + Toast.LENGTH_SHORT + ).show() + return + } + + AddGameFolderDialogFragment.newInstance(uriString) + .show(supportFragmentManager, AddGameFolderDialogFragment.TAG) + } + + val getProdKey = + registerForActivityResult(ActivityResultContracts.OpenDocument()) { result -> + if (result != null) { + processKey(result) + } + } + + fun processKey(result: Uri): Boolean { + if (FileUtil.getExtension(result) != "keys") { + MessageDialogFragment.newInstance( + this, + titleId = R.string.reading_keys_failure, + descriptionId = R.string.install_prod_keys_failure_extension_description + ).show(supportFragmentManager, MessageDialogFragment.TAG) + return false + } + + contentResolver.takePersistableUriPermission( + result, + Intent.FLAG_GRANT_READ_URI_PERMISSION + ) + + val dstPath = DirectoryInitialization.userDirectory + "/keys/" + if (FileUtil.copyUriToInternalStorage( + result, + dstPath, + "prod.keys" + ) != null + ) { + if (NativeLibrary.reloadKeys()) { + Toast.makeText( + applicationContext, + R.string.install_keys_success, + Toast.LENGTH_SHORT + ).show() + homeViewModel.setCheckKeys(true) + gamesViewModel.reloadGames(true) + return true + } else { + MessageDialogFragment.newInstance( + this, + titleId = R.string.invalid_keys_error, + descriptionId = R.string.install_keys_failure_description, + helpLinkId = R.string.dumping_keys_quickstart_link + ).show(supportFragmentManager, MessageDialogFragment.TAG) + return false + } + } + return false + } + + val getFirmware = + registerForActivityResult(ActivityResultContracts.OpenDocument()) { result -> + if (result == null) { + return@registerForActivityResult + } + + val filterNCA = FilenameFilter { _, dirName -> dirName.endsWith(".nca") } + + val firmwarePath = + File(DirectoryInitialization.userDirectory + "/nand/system/Contents/registered/") + val cacheFirmwareDir = File("${cacheDir.path}/registered/") + + ProgressDialogFragment.newInstance( + this, + R.string.firmware_installing + ) { progressCallback, _ -> + var messageToShow: Any + try { + FileUtil.unzipToInternalStorage( + result.toString(), + cacheFirmwareDir, + progressCallback + ) + val unfilteredNumOfFiles = cacheFirmwareDir.list()?.size ?: -1 + val filteredNumOfFiles = cacheFirmwareDir.list(filterNCA)?.size ?: -2 + messageToShow = if (unfilteredNumOfFiles != filteredNumOfFiles) { + MessageDialogFragment.newInstance( + this, + titleId = R.string.firmware_installed_failure, + descriptionId = R.string.firmware_installed_failure_description + ) + } else { + firmwarePath.deleteRecursively() + cacheFirmwareDir.copyRecursively(firmwarePath, true) + NativeLibrary.initializeSystem(true) + homeViewModel.setCheckKeys(true) + getString(R.string.save_file_imported_success) + } + } catch (e: Exception) { + Log.error("[MainActivity] Firmware install failed - ${e.message}") + messageToShow = getString(R.string.fatal_error) + } finally { + cacheFirmwareDir.deleteRecursively() + } + messageToShow + }.show(supportFragmentManager, ProgressDialogFragment.TAG) + } + + val getAmiiboKey = + registerForActivityResult(ActivityResultContracts.OpenDocument()) { result -> + if (result == null) { + return@registerForActivityResult + } + + if (FileUtil.getExtension(result) != "bin") { + MessageDialogFragment.newInstance( + this, + titleId = R.string.reading_keys_failure, + descriptionId = R.string.install_amiibo_keys_failure_extension_description + ).show(supportFragmentManager, MessageDialogFragment.TAG) + return@registerForActivityResult + } + + contentResolver.takePersistableUriPermission( + result, + Intent.FLAG_GRANT_READ_URI_PERMISSION + ) + + val dstPath = DirectoryInitialization.userDirectory + "/keys/" + if (FileUtil.copyUriToInternalStorage( + result, + dstPath, + "key_retail.bin" + ) != null + ) { + if (NativeLibrary.reloadKeys()) { + Toast.makeText( + applicationContext, + R.string.install_keys_success, + Toast.LENGTH_SHORT + ).show() + } else { + MessageDialogFragment.newInstance( + this, + titleId = R.string.invalid_keys_error, + descriptionId = R.string.install_keys_failure_description, + helpLinkId = R.string.dumping_keys_quickstart_link + ).show(supportFragmentManager, MessageDialogFragment.TAG) + } + } + } + + val installGameUpdate = registerForActivityResult( + ActivityResultContracts.OpenMultipleDocuments() + ) { documents: List -> + if (documents.isEmpty()) { + return@registerForActivityResult + } + + if (addonViewModel.game == null) { + installContent(documents) + return@registerForActivityResult + } + + ProgressDialogFragment.newInstance( + this@MainActivity, + R.string.verifying_content, + false + ) { _, _ -> + var updatesMatchProgram = true + for (document in documents) { + val valid = NativeLibrary.doesUpdateMatchProgram( + addonViewModel.game!!.programId, + document.toString() + ) + if (!valid) { + updatesMatchProgram = false + break + } + } + + if (updatesMatchProgram) { + homeViewModel.setContentToInstall(documents) + } else { + MessageDialogFragment.newInstance( + this@MainActivity, + titleId = R.string.content_install_notice, + descriptionId = R.string.content_install_notice_description, + positiveAction = { homeViewModel.setContentToInstall(documents) }, + negativeAction = {} + ) + } + }.show(supportFragmentManager, ProgressDialogFragment.TAG) + } + + private fun installContent(documents: List) { + ProgressDialogFragment.newInstance( + this@MainActivity, + R.string.installing_game_content + ) { progressCallback, messageCallback -> + var installSuccess = 0 + var installOverwrite = 0 + var errorBaseGame = 0 + var error = 0 + documents.forEach { + messageCallback.invoke(FileUtil.getFilename(it)) + when ( + InstallResult.from( + NativeLibrary.installFileToNand( + it.toString(), + progressCallback + ) + ) + ) { + InstallResult.Success -> { + installSuccess += 1 + } + + InstallResult.Overwrite -> { + installOverwrite += 1 + } + + InstallResult.BaseInstallAttempted -> { + errorBaseGame += 1 + } + + InstallResult.Failure -> { + error += 1 + } + } + } + + addonViewModel.refreshAddons() + + val separator = System.getProperty("line.separator") ?: "\n" + val installResult = StringBuilder() + if (installSuccess > 0) { + installResult.append( + getString( + R.string.install_game_content_success_install, + installSuccess + ) + ) + installResult.append(separator) + } + if (installOverwrite > 0) { + installResult.append( + getString( + R.string.install_game_content_success_overwrite, + installOverwrite + ) + ) + installResult.append(separator) + } + val errorTotal: Int = errorBaseGame + error + if (errorTotal > 0) { + installResult.append(separator) + installResult.append( + getString( + R.string.install_game_content_failed_count, + errorTotal + ) + ) + installResult.append(separator) + if (errorBaseGame > 0) { + installResult.append(separator) + installResult.append( + getString(R.string.install_game_content_failure_base) + ) + installResult.append(separator) + } + if (error > 0) { + installResult.append( + getString(R.string.install_game_content_failure_description) + ) + installResult.append(separator) + } + return@newInstance MessageDialogFragment.newInstance( + this, + titleId = R.string.install_game_content_failure, + descriptionString = installResult.toString().trim(), + helpLinkId = R.string.install_game_content_help_link + ) + } else { + return@newInstance MessageDialogFragment.newInstance( + this, + titleId = R.string.install_game_content_success, + descriptionString = installResult.toString().trim() + ) + } + }.show(supportFragmentManager, ProgressDialogFragment.TAG) + } + + val exportUserData = registerForActivityResult( + ActivityResultContracts.CreateDocument("application/zip") + ) { result -> + if (result == null) { + return@registerForActivityResult + } + + ProgressDialogFragment.newInstance( + this, + R.string.exporting_user_data, + true + ) { progressCallback, _ -> + val zipResult = FileUtil.zipFromInternalStorage( + File(DirectoryInitialization.userDirectory!!), + DirectoryInitialization.userDirectory!!, + BufferedOutputStream(contentResolver.openOutputStream(result)), + progressCallback, + compression = false + ) + return@newInstance when (zipResult) { + TaskState.Completed -> getString(R.string.user_data_export_success) + TaskState.Failed -> R.string.export_failed + TaskState.Cancelled -> R.string.user_data_export_cancelled + } + }.show(supportFragmentManager, ProgressDialogFragment.TAG) + } + + val importUserData = + registerForActivityResult(ActivityResultContracts.OpenDocument()) { result -> + if (result == null) { + return@registerForActivityResult + } + + ProgressDialogFragment.newInstance( + this, + R.string.importing_user_data + ) { progressCallback, _ -> + val checkStream = + ZipInputStream(BufferedInputStream(contentResolver.openInputStream(result))) + var isSudachiBackup = false + checkStream.use { stream -> + var ze: ZipEntry? = null + while (stream.nextEntry?.also { ze = it } != null) { + val itemName = ze!!.name.trim() + if (itemName == "/config/config.ini" || itemName == "config/config.ini") { + isSudachiBackup = true + return@use + } + } + } + if (!isSudachiBackup) { + return@newInstance MessageDialogFragment.newInstance( + this, + titleId = R.string.invalid_sudachi_backup, + descriptionId = R.string.user_data_import_failed_description + ) + } + + // Clear existing user data + NativeConfig.unloadGlobalConfig() + File(DirectoryInitialization.userDirectory!!).deleteRecursively() + + // Copy archive to internal storage + try { + FileUtil.unzipToInternalStorage( + result.toString(), + File(DirectoryInitialization.userDirectory!!), + progressCallback + ) + } catch (e: Exception) { + return@newInstance MessageDialogFragment.newInstance( + this, + titleId = R.string.import_failed, + descriptionId = R.string.user_data_import_failed_description + ) + } + + // Reinitialize relevant data + NativeLibrary.initializeSystem(true) + NativeConfig.initializeGlobalConfig() + gamesViewModel.reloadGames(false) + driverViewModel.reloadDriverData() + + return@newInstance getString(R.string.user_data_import_success) + }.show(supportFragmentManager, ProgressDialogFragment.TAG) + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/ui/main/ThemeProvider.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/ui/main/ThemeProvider.kt new file mode 100644 index 0000000..baf1994 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/ui/main/ThemeProvider.kt @@ -0,0 +1,11 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.ui.main + +interface ThemeProvider { + /** + * Provides theme ID by overriding an activity's 'setTheme' method and returning that result + */ + var themeId: Int +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/AddonUtil.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/AddonUtil.kt new file mode 100644 index 0000000..5aacbdb --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/AddonUtil.kt @@ -0,0 +1,8 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.utils + +object AddonUtil { + val validAddonDirectories = listOf("cheats", "exefs", "romfs") +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/DirectoryInitialization.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/DirectoryInitialization.kt new file mode 100644 index 0000000..6a5fcd6 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/DirectoryInitialization.kt @@ -0,0 +1,213 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.utils + +import androidx.preference.PreferenceManager +import java.io.IOException +import org.sudachi.sudachi_emu.NativeLibrary +import org.sudachi.sudachi_emu.SudachiApplication +import org.sudachi.sudachi_emu.features.settings.model.BooleanSetting +import org.sudachi.sudachi_emu.features.settings.model.IntSetting +import org.sudachi.sudachi_emu.features.settings.model.Settings +import org.sudachi.sudachi_emu.overlay.model.OverlayControlData +import org.sudachi.sudachi_emu.overlay.model.OverlayControl +import org.sudachi.sudachi_emu.overlay.model.OverlayLayout +import org.sudachi.sudachi_emu.utils.PreferenceUtil.migratePreference + +object DirectoryInitialization { + private var userPath: String? = null + + var areDirectoriesReady: Boolean = false + + fun start() { + if (!areDirectoriesReady) { + initializeInternalStorage() + NativeLibrary.initializeSystem(false) + NativeConfig.initializeGlobalConfig() + migrateSettings() + areDirectoriesReady = true + } + } + + val userDirectory: String? + get() { + check(areDirectoriesReady) { "Directory initialization is not ready!" } + return userPath + } + + private fun initializeInternalStorage() { + try { + userPath = SudachiApplication.appContext.getExternalFilesDir(null)!!.canonicalPath + NativeLibrary.setAppDirectory(userPath!!) + } catch (e: IOException) { + e.printStackTrace() + } + } + + private fun migrateSettings() { + val preferences = PreferenceManager.getDefaultSharedPreferences(SudachiApplication.appContext) + var saveConfig = false + val theme = preferences.migratePreference(Settings.PREF_THEME) + if (theme != null) { + IntSetting.THEME.setInt(theme) + saveConfig = true + } + + val themeMode = preferences.migratePreference(Settings.PREF_THEME_MODE) + if (themeMode != null) { + IntSetting.THEME_MODE.setInt(themeMode) + saveConfig = true + } + + val blackBackgrounds = + preferences.migratePreference(Settings.PREF_BLACK_BACKGROUNDS) + if (blackBackgrounds != null) { + BooleanSetting.BLACK_BACKGROUNDS.setBoolean(blackBackgrounds) + saveConfig = true + } + + val joystickRelCenter = + preferences.migratePreference(Settings.PREF_MENU_SETTINGS_JOYSTICK_REL_CENTER) + if (joystickRelCenter != null) { + BooleanSetting.JOYSTICK_REL_CENTER.setBoolean(joystickRelCenter) + saveConfig = true + } + + val dpadSlide = + preferences.migratePreference(Settings.PREF_MENU_SETTINGS_DPAD_SLIDE) + if (dpadSlide != null) { + BooleanSetting.DPAD_SLIDE.setBoolean(dpadSlide) + saveConfig = true + } + + val hapticFeedback = + preferences.migratePreference(Settings.PREF_MENU_SETTINGS_HAPTICS) + if (hapticFeedback != null) { + BooleanSetting.HAPTIC_FEEDBACK.setBoolean(hapticFeedback) + saveConfig = true + } + + val showPerformanceOverlay = + preferences.migratePreference(Settings.PREF_MENU_SETTINGS_SHOW_FPS) + if (showPerformanceOverlay != null) { + BooleanSetting.SHOW_PERFORMANCE_OVERLAY.setBoolean(showPerformanceOverlay) + saveConfig = true + } + + val showInputOverlay = + preferences.migratePreference(Settings.PREF_MENU_SETTINGS_SHOW_OVERLAY) + if (showInputOverlay != null) { + BooleanSetting.SHOW_INPUT_OVERLAY.setBoolean(showInputOverlay) + saveConfig = true + } + + val overlayOpacity = preferences.migratePreference(Settings.PREF_CONTROL_OPACITY) + if (overlayOpacity != null) { + IntSetting.OVERLAY_OPACITY.setInt(overlayOpacity) + saveConfig = true + } + + val overlayScale = preferences.migratePreference(Settings.PREF_CONTROL_SCALE) + if (overlayScale != null) { + IntSetting.OVERLAY_SCALE.setInt(overlayScale) + saveConfig = true + } + + var setOverlayData = false + val overlayControlData = NativeConfig.getOverlayControlData() + if (overlayControlData.isEmpty()) { + val overlayControlDataMap = + NativeConfig.getOverlayControlData().associateBy { it.id }.toMutableMap() + for (button in Settings.overlayPreferences) { + val buttonId = convertButtonId(button) + var buttonEnabled = preferences.migratePreference(button) + if (buttonEnabled == null) { + buttonEnabled = OverlayControl.map[buttonId]?.defaultVisibility == true + } + + var landscapeXPosition = preferences.migratePreference( + "$button-X${Settings.PREF_LANDSCAPE_SUFFIX}" + )?.toDouble() + var landscapeYPosition = preferences.migratePreference( + "$button-Y${Settings.PREF_LANDSCAPE_SUFFIX}" + )?.toDouble() + if (landscapeXPosition == null || landscapeYPosition == null) { + val landscapePosition = OverlayControl.map[buttonId] + ?.getDefaultPositionForLayout(OverlayLayout.Landscape) ?: Pair(0.0, 0.0) + landscapeXPosition = landscapePosition.first + landscapeYPosition = landscapePosition.second + } + + var portraitXPosition = preferences.migratePreference( + "$button-X${Settings.PREF_PORTRAIT_SUFFIX}" + )?.toDouble() + var portraitYPosition = preferences.migratePreference( + "$button-Y${Settings.PREF_PORTRAIT_SUFFIX}" + )?.toDouble() + if (portraitXPosition == null || portraitYPosition == null) { + val portraitPosition = OverlayControl.map[buttonId] + ?.getDefaultPositionForLayout(OverlayLayout.Portrait) ?: Pair(0.0, 0.0) + portraitXPosition = portraitPosition.first + portraitYPosition = portraitPosition.second + } + + var foldableXPosition = preferences.migratePreference( + "$button-X${Settings.PREF_FOLDABLE_SUFFIX}" + )?.toDouble() + var foldableYPosition = preferences.migratePreference( + "$button-Y${Settings.PREF_FOLDABLE_SUFFIX}" + )?.toDouble() + if (foldableXPosition == null || foldableYPosition == null) { + val foldablePosition = OverlayControl.map[buttonId] + ?.getDefaultPositionForLayout(OverlayLayout.Foldable) ?: Pair(0.0, 0.0) + foldableXPosition = foldablePosition.first + foldableYPosition = foldablePosition.second + } + + val controlData = OverlayControlData( + buttonId, + buttonEnabled, + Pair(landscapeXPosition, landscapeYPosition), + Pair(portraitXPosition, portraitYPosition), + Pair(foldableXPosition, foldableYPosition) + ) + overlayControlDataMap[buttonId] = controlData + setOverlayData = true + } + + if (setOverlayData) { + NativeConfig.setOverlayControlData( + overlayControlDataMap.map { it.value }.toTypedArray() + ) + saveConfig = true + } + } + + if (saveConfig) { + NativeConfig.saveGlobalConfig() + } + } + + private fun convertButtonId(buttonId: String): String = + when (buttonId) { + Settings.PREF_BUTTON_A -> OverlayControl.BUTTON_A.id + Settings.PREF_BUTTON_B -> OverlayControl.BUTTON_B.id + Settings.PREF_BUTTON_X -> OverlayControl.BUTTON_X.id + Settings.PREF_BUTTON_Y -> OverlayControl.BUTTON_Y.id + Settings.PREF_BUTTON_L -> OverlayControl.BUTTON_L.id + Settings.PREF_BUTTON_R -> OverlayControl.BUTTON_R.id + Settings.PREF_BUTTON_ZL -> OverlayControl.BUTTON_ZL.id + Settings.PREF_BUTTON_ZR -> OverlayControl.BUTTON_ZR.id + Settings.PREF_BUTTON_PLUS -> OverlayControl.BUTTON_PLUS.id + Settings.PREF_BUTTON_MINUS -> OverlayControl.BUTTON_MINUS.id + Settings.PREF_BUTTON_DPAD -> OverlayControl.COMBINED_DPAD.id + Settings.PREF_STICK_L -> OverlayControl.STICK_L.id + Settings.PREF_STICK_R -> OverlayControl.STICK_R.id + Settings.PREF_BUTTON_HOME -> OverlayControl.BUTTON_HOME.id + Settings.PREF_BUTTON_SCREENSHOT -> OverlayControl.BUTTON_CAPTURE.id + Settings.PREF_BUTTON_STICK_L -> OverlayControl.BUTTON_STICK_L.id + Settings.PREF_BUTTON_STICK_R -> OverlayControl.BUTTON_STICK_R.id + else -> "" + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/DocumentsTree.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/DocumentsTree.kt new file mode 100644 index 0000000..b9ce009 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/DocumentsTree.kt @@ -0,0 +1,137 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.utils + +import android.net.Uri +import androidx.documentfile.provider.DocumentFile +import java.io.File +import java.util.* +import org.sudachi.sudachi_emu.model.MinimalDocumentFile + +class DocumentsTree { + private var root: DocumentsNode? = null + + fun setRoot(rootUri: Uri?) { + root = null + root = DocumentsNode() + root!!.uri = rootUri + root!!.isDirectory = true + } + + fun openContentUri(filepath: String, openMode: String?): Int { + val node = resolvePath(filepath) ?: return -1 + return FileUtil.openContentUri(node.uri.toString(), openMode) + } + + fun getFileSize(filepath: String): Long { + val node = resolvePath(filepath) + return if (node == null || node.isDirectory) { + 0 + } else { + FileUtil.getFileSize(node.uri.toString()) + } + } + + fun exists(filepath: String): Boolean { + return resolvePath(filepath) != null + } + + fun isDirectory(filepath: String): Boolean { + val node = resolvePath(filepath) + return node != null && node.isDirectory + } + + fun getParentDirectory(filepath: String): String { + val node = resolvePath(filepath)!! + val parentNode = node.parent + if (parentNode != null && parentNode.isDirectory) { + return parentNode.uri!!.toString() + } + return node.uri!!.toString() + } + + fun getFilename(filepath: String): String { + val node = resolvePath(filepath) + if (node != null) { + return node.name!! + } + return filepath + } + + private fun resolvePath(filepath: String): DocumentsNode? { + val tokens = StringTokenizer(filepath, File.separator, false) + var iterator = root + while (tokens.hasMoreTokens()) { + val token = tokens.nextToken() + if (token.isEmpty()) continue + iterator = find(iterator, token) + if (iterator == null) return null + } + return iterator + } + + private fun find(parent: DocumentsNode?, filename: String): DocumentsNode? { + if (parent!!.isDirectory && !parent.loaded) { + structTree(parent) + } + return parent.children[filename] + } + + /** + * Construct current level directory tree + * @param parent parent node of this level + */ + private fun structTree(parent: DocumentsNode) { + val documents = FileUtil.listFiles(parent.uri!!) + for (document in documents) { + val node = DocumentsNode(document) + node.parent = parent + parent.children[node.name] = node + } + parent.loaded = true + } + + private class DocumentsNode { + var parent: DocumentsNode? = null + val children: MutableMap = HashMap() + var name: String? = null + var uri: Uri? = null + var loaded = false + var isDirectory = false + + constructor() + constructor(document: MinimalDocumentFile) { + name = document.filename + uri = document.uri + isDirectory = document.isDirectory + loaded = !isDirectory + } + + private constructor(document: DocumentFile, isCreateDir: Boolean) { + name = document.name + uri = document.uri + isDirectory = isCreateDir + loaded = true + } + + private fun rename(name: String) { + if (parent == null) { + return + } + parent!!.children.remove(this.name) + this.name = name + parent!!.children[name] = this + } + } + + companion object { + fun isNativePath(path: String): Boolean { + return if (path.isNotEmpty()) { + path[0] == '/' + } else { + false + } + } + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/FileUtil.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/FileUtil.kt new file mode 100644 index 0000000..0c56d8d --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/FileUtil.kt @@ -0,0 +1,503 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.utils + +import android.database.Cursor +import android.net.Uri +import android.provider.DocumentsContract +import androidx.documentfile.provider.DocumentFile +import java.io.BufferedInputStream +import java.io.File +import java.io.IOException +import java.io.InputStream +import java.net.URLDecoder +import java.util.zip.ZipEntry +import java.util.zip.ZipInputStream +import org.sudachi.sudachi_emu.SudachiApplication +import org.sudachi.sudachi_emu.model.MinimalDocumentFile +import org.sudachi.sudachi_emu.model.TaskState +import java.io.BufferedOutputStream +import java.io.OutputStream +import java.lang.NullPointerException +import java.nio.charset.StandardCharsets +import java.util.zip.Deflater +import java.util.zip.ZipOutputStream +import kotlin.IllegalStateException + +object FileUtil { + const val PATH_TREE = "tree" + const val DECODE_METHOD = "UTF-8" + const val APPLICATION_OCTET_STREAM = "application/octet-stream" + const val TEXT_PLAIN = "text/plain" + + private val context get() = SudachiApplication.appContext + + /** + * Create a file from directory with filename. + * @param context Application context + * @param directory parent path for file. + * @param filename file display name. + * @return boolean + */ + fun createFile(directory: String?, filename: String): DocumentFile? { + var decodedFilename = filename + try { + val directoryUri = Uri.parse(directory) + val parent = DocumentFile.fromTreeUri(context, directoryUri) ?: return null + decodedFilename = URLDecoder.decode(decodedFilename, DECODE_METHOD) + var mimeType = APPLICATION_OCTET_STREAM + if (decodedFilename.endsWith(".txt")) { + mimeType = TEXT_PLAIN + } + val exists = parent.findFile(decodedFilename) + return exists ?: parent.createFile(mimeType, decodedFilename) + } catch (e: Exception) { + Log.error("[FileUtil]: Cannot create file, error: " + e.message) + } + return null + } + + /** + * Create a directory from directory with filename. + * @param directory parent path for directory. + * @param directoryName directory display name. + * @return boolean + */ + fun createDir(directory: String?, directoryName: String?): DocumentFile? { + var decodedDirectoryName = directoryName + try { + val directoryUri = Uri.parse(directory) + val parent = DocumentFile.fromTreeUri(context, directoryUri) ?: return null + decodedDirectoryName = URLDecoder.decode(decodedDirectoryName, DECODE_METHOD) + val isExist = parent.findFile(decodedDirectoryName) + return isExist ?: parent.createDirectory(decodedDirectoryName) + } catch (e: Exception) { + Log.error("[FileUtil]: Cannot create file, error: " + e.message) + } + return null + } + + /** + * Open content uri and return file descriptor to JNI. + * @param path Native content uri path + * @param openMode will be one of "r", "r", "rw", "wa", "rwa" + * @return file descriptor + */ + @JvmStatic + fun openContentUri(path: String, openMode: String?): Int { + try { + val uri = Uri.parse(path) + val parcelFileDescriptor = context.contentResolver.openFileDescriptor(uri, openMode!!) + if (parcelFileDescriptor == null) { + Log.error("[FileUtil]: Cannot get the file descriptor from uri: $path") + return -1 + } + val fileDescriptor = parcelFileDescriptor.detachFd() + parcelFileDescriptor.close() + return fileDescriptor + } catch (e: Exception) { + Log.error("[FileUtil]: Cannot open content uri, error: " + e.message) + } + return -1 + } + + /** + * Reference: https://stackoverflow.com/questions/42186820/documentfile-is-very-slow + * This function will be faster than DocumentFile.listFiles + * @param uri Directory uri. + * @return CheapDocument lists. + */ + fun listFiles(uri: Uri): Array { + val resolver = context.contentResolver + val columns = arrayOf( + DocumentsContract.Document.COLUMN_DOCUMENT_ID, + DocumentsContract.Document.COLUMN_DISPLAY_NAME, + DocumentsContract.Document.COLUMN_MIME_TYPE + ) + var c: Cursor? = null + val results: MutableList = ArrayList() + try { + val docId: String = if (isRootTreeUri(uri)) { + DocumentsContract.getTreeDocumentId(uri) + } else { + DocumentsContract.getDocumentId(uri) + } + val childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree(uri, docId) + c = resolver.query(childrenUri, columns, null, null, null) + while (c!!.moveToNext()) { + val documentId = c.getString(0) + val documentName = c.getString(1) + val documentMimeType = c.getString(2) + val documentUri = DocumentsContract.buildDocumentUriUsingTree(uri, documentId) + val document = MinimalDocumentFile(documentName, documentMimeType, documentUri) + results.add(document) + } + } catch (e: Exception) { + Log.error("[FileUtil]: Cannot list file error: " + e.message) + } finally { + closeQuietly(c) + } + return results.toTypedArray() + } + + /** + * Check whether given path exists. + * @param path Native content uri path + * @return bool + */ + fun exists(path: String?, suppressLog: Boolean = false): Boolean { + var c: Cursor? = null + try { + val mUri = Uri.parse(path) + val columns = arrayOf(DocumentsContract.Document.COLUMN_DOCUMENT_ID) + c = context.contentResolver.query(mUri, columns, null, null, null) + return c!!.count > 0 + } catch (e: Exception) { + if (!suppressLog) { + Log.info("[FileUtil] Cannot find file from given path, error: " + e.message) + } + } finally { + closeQuietly(c) + } + return false + } + + /** + * Check whether given path is a directory + * @param path content uri path + * @return bool + */ + fun isDirectory(path: String): Boolean { + val resolver = context.contentResolver + val columns = arrayOf( + DocumentsContract.Document.COLUMN_MIME_TYPE + ) + var isDirectory = false + var c: Cursor? = null + try { + val mUri = Uri.parse(path) + c = resolver.query(mUri, columns, null, null, null) + c!!.moveToNext() + val mimeType = c.getString(0) + isDirectory = mimeType == DocumentsContract.Document.MIME_TYPE_DIR + } catch (e: Exception) { + Log.error("[FileUtil]: Cannot list files, error: " + e.message) + } finally { + closeQuietly(c) + } + return isDirectory + } + + /** + * Get file display name from given path + * @param uri content uri + * @return String display name + */ + fun getFilename(uri: Uri): String { + val resolver = SudachiApplication.appContext.contentResolver + val columns = arrayOf( + DocumentsContract.Document.COLUMN_DISPLAY_NAME + ) + var filename = "" + var c: Cursor? = null + try { + c = resolver.query(uri, columns, null, null, null) + c!!.moveToNext() + filename = c.getString(0) + } catch (e: Exception) { + Log.error("[FileUtil]: Cannot get file size, error: " + e.message) + } finally { + closeQuietly(c) + } + return filename + } + + fun getFilesName(path: String): Array { + val uri = Uri.parse(path) + val files: MutableList = ArrayList() + for (file in listFiles(uri)) { + files.add(file.filename) + } + return files.toTypedArray() + } + + /** + * Get file size from given path. + * @param path content uri path + * @return long file size + */ + @JvmStatic + fun getFileSize(path: String): Long { + val resolver = context.contentResolver + val columns = arrayOf( + DocumentsContract.Document.COLUMN_SIZE + ) + var size: Long = 0 + var c: Cursor? = null + try { + val mUri = Uri.parse(path) + c = resolver.query(mUri, columns, null, null, null) + c!!.moveToNext() + size = c.getLong(0) + } catch (e: Exception) { + Log.error("[FileUtil]: Cannot get file size, error: " + e.message) + } finally { + closeQuietly(c) + } + return size + } + + /** + * Creates an input stream with a given [Uri] and copies its data to the given path. This will + * overwrite any pre-existing files. + * + * @param sourceUri The [Uri] to copy data from + * @param destinationParentPath Destination directory + * @param destinationFilename Optionally renames the file once copied + */ + fun copyUriToInternalStorage( + sourceUri: Uri, + destinationParentPath: String, + destinationFilename: String = "" + ): File? = + try { + val fileName = + if (destinationFilename == "") getFilename(sourceUri) else "/$destinationFilename" + val inputStream = context.contentResolver.openInputStream(sourceUri)!! + + val destinationFile = File("$destinationParentPath$fileName") + if (destinationFile.exists()) { + destinationFile.delete() + } + + destinationFile.outputStream().use { fos -> + inputStream.use { it.copyTo(fos) } + } + destinationFile + } catch (e: IOException) { + null + } catch (e: NullPointerException) { + null + } + + /** + * Extracts the given zip file into the given directory. + * @param path String representation of a [Uri] or a typical path delimited by '/' + * @param destDir Location to unzip the contents of [path] into + * @param progressCallback Lambda that is called with the total number of files and the current + * progress through the process. Stops execution as soon as possible if this returns true. + */ + @Throws(SecurityException::class) + fun unzipToInternalStorage( + path: String, + destDir: File, + progressCallback: (max: Long, progress: Long) -> Boolean = { _, _ -> false } + ) { + var totalEntries = 0L + ZipInputStream(getInputStream(path)).use { zis -> + var tempEntry = zis.nextEntry + while (tempEntry != null) { + tempEntry = zis.nextEntry + totalEntries++ + } + } + + var progress = 0L + ZipInputStream(getInputStream(path)).use { zis -> + var entry: ZipEntry? = zis.nextEntry + while (entry != null) { + if (progressCallback.invoke(totalEntries, progress)) { + return@use + } + + val newFile = File(destDir, entry.name) + val destinationDirectory = if (entry.isDirectory) newFile else newFile.parentFile + + if (!newFile.canonicalPath.startsWith(destDir.canonicalPath + File.separator)) { + throw SecurityException("Zip file attempted path traversal! ${entry.name}") + } + + if (!destinationDirectory.isDirectory && !destinationDirectory.mkdirs()) { + throw IOException("Failed to create directory $destinationDirectory") + } + + if (!entry.isDirectory) { + newFile.outputStream().use { fos -> zis.copyTo(fos) } + } + entry = zis.nextEntry + progress++ + } + } + } + + /** + * Creates a zip file from a directory within internal storage + * @param inputFile File representation of the item that will be zipped + * @param rootDir Directory containing the inputFile + * @param outputStream Stream where the zip file will be output + * @param progressCallback Lambda that is called with the total number of files and the current + * progress through the process. Stops execution as soon as possible if this returns true. + * @param compression Disables compression if true + */ + fun zipFromInternalStorage( + inputFile: File, + rootDir: String, + outputStream: BufferedOutputStream, + progressCallback: (max: Long, progress: Long) -> Boolean = { _, _ -> false }, + compression: Boolean = true + ): TaskState { + try { + ZipOutputStream(outputStream).use { zos -> + if (!compression) { + zos.setMethod(ZipOutputStream.DEFLATED) + zos.setLevel(Deflater.NO_COMPRESSION) + } + + var count = 0L + val totalFiles = inputFile.walkTopDown().count().toLong() + inputFile.walkTopDown().forEach { file -> + if (progressCallback.invoke(totalFiles, count)) { + return TaskState.Cancelled + } + + if (!file.isDirectory) { + val entryName = + file.absolutePath.removePrefix(rootDir).removePrefix("/") + val entry = ZipEntry(entryName) + zos.putNextEntry(entry) + if (file.isFile) { + file.inputStream().use { fis -> fis.copyTo(zos) } + } + count++ + } + } + } + } catch (e: Exception) { + Log.error("[FileUtil] Failed creating zip file - ${e.message}") + return TaskState.Failed + } + return TaskState.Completed + } + + /** + * Helper function that copies the contents of a DocumentFile folder into a [File] + * @param file [File] representation of the folder to copy into + * @param progressCallback Lambda that is called with the total number of files and the current + * progress through the process. Stops execution as soon as possible if this returns true. + * @throws IllegalStateException Fails when trying to copy a folder into a file and vice versa + */ + fun DocumentFile.copyFilesTo( + file: File, + progressCallback: (max: Long, progress: Long) -> Boolean = { _, _ -> false } + ) { + file.mkdirs() + if (!this.isDirectory || !file.isDirectory) { + throw IllegalStateException( + "[FileUtil] Tried to copy a folder into a file or vice versa" + ) + } + + var count = 0L + val totalFiles = this.listFiles().size.toLong() + this.listFiles().forEach { + if (progressCallback.invoke(totalFiles, count)) { + return + } + + val newFile = File(file, it.name!!) + if (it.isDirectory) { + newFile.mkdirs() + DocumentFile.fromTreeUri(SudachiApplication.appContext, it.uri)?.copyFilesTo(newFile) + } else { + val inputStream = + SudachiApplication.appContext.contentResolver.openInputStream(it.uri) + BufferedInputStream(inputStream).use { bos -> + if (!newFile.exists()) { + newFile.createNewFile() + } + newFile.outputStream().use { os -> bos.copyTo(os) } + } + } + count++ + } + } + + fun isRootTreeUri(uri: Uri): Boolean { + val paths = uri.pathSegments + return paths.size == 2 && PATH_TREE == paths[0] + } + + fun closeQuietly(closeable: AutoCloseable?) { + if (closeable != null) { + try { + closeable.close() + } catch (rethrown: RuntimeException) { + throw rethrown + } catch (ignored: Exception) { + } + } + } + + fun getExtension(uri: Uri): String { + val fileName = getFilename(uri) + return fileName.substring(fileName.lastIndexOf(".") + 1) + .lowercase() + } + + fun isTreeUriValid(uri: Uri): Boolean { + val resolver = context.contentResolver + val columns = arrayOf( + DocumentsContract.Document.COLUMN_DOCUMENT_ID, + DocumentsContract.Document.COLUMN_DISPLAY_NAME, + DocumentsContract.Document.COLUMN_MIME_TYPE + ) + return try { + val docId: String = if (isRootTreeUri(uri)) { + DocumentsContract.getTreeDocumentId(uri) + } else { + DocumentsContract.getDocumentId(uri) + } + val childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree(uri, docId) + resolver.query(childrenUri, columns, null, null, null) + true + } catch (_: Exception) { + false + } + } + + fun getInputStream(path: String) = if (path.contains("content://")) { + Uri.parse(path).inputStream() + } else { + File(path).inputStream() + } + + fun getOutputStream(path: String) = if (path.contains("content://")) { + Uri.parse(path).outputStream() + } else { + File(path).outputStream() + } + + @Throws(IOException::class) + fun getStringFromFile(file: File): String = + String(file.readBytes(), StandardCharsets.UTF_8) + + @Throws(IOException::class) + fun getStringFromInputStream(stream: InputStream): String = + String(stream.readBytes(), StandardCharsets.UTF_8) + + fun DocumentFile.inputStream(): InputStream = + SudachiApplication.appContext.contentResolver.openInputStream(uri)!! + + fun DocumentFile.outputStream(): OutputStream = + SudachiApplication.appContext.contentResolver.openOutputStream(uri)!! + + fun Uri.inputStream(): InputStream = + SudachiApplication.appContext.contentResolver.openInputStream(this)!! + + fun Uri.outputStream(): OutputStream = + SudachiApplication.appContext.contentResolver.openOutputStream(this)!! + + fun Uri.asDocumentFile(): DocumentFile? = + DocumentFile.fromSingleUri(SudachiApplication.appContext, this) +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/GameHelper.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/GameHelper.kt new file mode 100644 index 0000000..9dce357 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/GameHelper.kt @@ -0,0 +1,152 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.utils + +import android.content.SharedPreferences +import android.net.Uri +import androidx.preference.PreferenceManager +import kotlinx.serialization.encodeToString +import kotlinx.serialization.json.Json +import org.sudachi.sudachi_emu.NativeLibrary +import org.sudachi.sudachi_emu.SudachiApplication +import org.sudachi.sudachi_emu.model.Game +import org.sudachi.sudachi_emu.model.GameDir +import org.sudachi.sudachi_emu.model.MinimalDocumentFile + +object GameHelper { + private const val KEY_OLD_GAME_PATH = "game_path" + const val KEY_GAMES = "Games" + + private lateinit var preferences: SharedPreferences + + fun getGames(): List { + val games = mutableListOf() + val context = SudachiApplication.appContext + preferences = PreferenceManager.getDefaultSharedPreferences(context) + + val gameDirs = mutableListOf() + val oldGamesDir = preferences.getString(KEY_OLD_GAME_PATH, "") ?: "" + if (oldGamesDir.isNotEmpty()) { + gameDirs.add(GameDir(oldGamesDir, true)) + preferences.edit().remove(KEY_OLD_GAME_PATH).apply() + } + gameDirs.addAll(NativeConfig.getGameDirs()) + + // Ensure keys are loaded so that ROM metadata can be decrypted. + NativeLibrary.reloadKeys() + + // Reset metadata so we don't use stale information + GameMetadata.resetMetadata() + + // Remove previous filesystem provider information so we can get up to date version info + NativeLibrary.clearFilesystemProvider() + + val badDirs = mutableListOf() + gameDirs.forEachIndexed { index: Int, gameDir: GameDir -> + val gameDirUri = Uri.parse(gameDir.uriString) + val isValid = FileUtil.isTreeUriValid(gameDirUri) + if (isValid) { + addGamesRecursive( + games, + FileUtil.listFiles(gameDirUri), + if (gameDir.deepScan) 3 else 1 + ) + } else { + badDirs.add(index) + } + } + + // Remove all game dirs with insufficient permissions from config + if (badDirs.isNotEmpty()) { + var offset = 0 + badDirs.forEach { + gameDirs.removeAt(it - offset) + offset++ + } + } + NativeConfig.setGameDirs(gameDirs.toTypedArray()) + + // Cache list of games found on disk + val serializedGames = mutableSetOf() + games.forEach { + serializedGames.add(Json.encodeToString(it)) + } + preferences.edit() + .remove(KEY_GAMES) + .putStringSet(KEY_GAMES, serializedGames) + .apply() + + return games.toList() + } + + private fun addGamesRecursive( + games: MutableList, + files: Array, + depth: Int + ) { + if (depth <= 0) { + return + } + + files.forEach { + if (it.isDirectory) { + addGamesRecursive( + games, + FileUtil.listFiles(it.uri), + depth - 1 + ) + } else { + if (Game.extensions.contains(FileUtil.getExtension(it.uri))) { + val game = getGame(it.uri, true) + if (game != null) { + games.add(game) + } + } + } + } + } + + fun getGame(uri: Uri, addedToLibrary: Boolean): Game? { + val filePath = uri.toString() + if (!GameMetadata.getIsValid(filePath)) { + return null + } + + // Needed to update installed content information + NativeLibrary.addFileToFilesystemProvider(filePath) + + var name = GameMetadata.getTitle(filePath) + + // If the game's title field is empty, use the filename. + if (name.isEmpty()) { + name = FileUtil.getFilename(uri) + } + var programId = GameMetadata.getProgramId(filePath) + + // If the game's ID field is empty, use the filename without extension. + if (programId.isEmpty()) { + programId = name.substring(0, name.lastIndexOf(".")) + } + + val newGame = Game( + name, + filePath, + programId, + GameMetadata.getDeveloper(filePath), + GameMetadata.getVersion(filePath, false), + GameMetadata.getIsHomebrew(filePath) + ) + + if (addedToLibrary) { + val addedTime = preferences.getLong(newGame.keyAddedToLibraryTime, 0L) + if (addedTime == 0L) { + preferences.edit() + .putLong(newGame.keyAddedToLibraryTime, System.currentTimeMillis()) + .apply() + } + } + + return newGame + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/GameIconUtils.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/GameIconUtils.kt new file mode 100644 index 0000000..ef42f54 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/GameIconUtils.kt @@ -0,0 +1,109 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.utils + +import android.graphics.Bitmap +import android.graphics.BitmapFactory +import android.graphics.drawable.LayerDrawable +import android.widget.ImageView +import androidx.core.content.res.ResourcesCompat +import androidx.core.graphics.drawable.IconCompat +import androidx.core.graphics.drawable.toBitmap +import androidx.core.graphics.drawable.toDrawable +import androidx.lifecycle.LifecycleOwner +import coil.ImageLoader +import coil.decode.DataSource +import coil.fetch.DrawableResult +import coil.fetch.FetchResult +import coil.fetch.Fetcher +import coil.key.Keyer +import coil.memory.MemoryCache +import coil.request.ImageRequest +import coil.request.Options +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.SudachiApplication +import org.sudachi.sudachi_emu.model.Game + +class GameIconFetcher( + private val game: Game, + private val options: Options +) : Fetcher { + override suspend fun fetch(): FetchResult { + return DrawableResult( + drawable = decodeGameIcon(game.path)!!.toDrawable(options.context.resources), + isSampled = false, + dataSource = DataSource.DISK + ) + } + + private fun decodeGameIcon(uri: String): Bitmap? { + val data = GameMetadata.getIcon(uri) + return BitmapFactory.decodeByteArray( + data, + 0, + data.size, + BitmapFactory.Options() + ) + } + + class Factory : Fetcher.Factory { + override fun create(data: Game, options: Options, imageLoader: ImageLoader): Fetcher = + GameIconFetcher(data, options) + } +} + +class GameIconKeyer : Keyer { + override fun key(data: Game, options: Options): String = data.path +} + +object GameIconUtils { + private val imageLoader = ImageLoader.Builder(SudachiApplication.appContext) + .components { + add(GameIconKeyer()) + add(GameIconFetcher.Factory()) + } + .memoryCache { + MemoryCache.Builder(SudachiApplication.appContext) + .maxSizePercent(0.25) + .build() + } + .build() + + fun loadGameIcon(game: Game, imageView: ImageView) { + val request = ImageRequest.Builder(SudachiApplication.appContext) + .data(game) + .target(imageView) + .error(R.drawable.default_icon) + .build() + imageLoader.enqueue(request) + } + + suspend fun getGameIcon(lifecycleOwner: LifecycleOwner, game: Game): Bitmap { + val request = ImageRequest.Builder(SudachiApplication.appContext) + .data(game) + .lifecycle(lifecycleOwner) + .error(R.drawable.default_icon) + .build() + return imageLoader.execute(request) + .drawable!!.toBitmap(config = Bitmap.Config.ARGB_8888) + } + + suspend fun getShortcutIcon(lifecycleOwner: LifecycleOwner, game: Game): IconCompat { + val layerDrawable = ResourcesCompat.getDrawable( + SudachiApplication.appContext.resources, + R.drawable.shortcut, + null + ) as LayerDrawable + layerDrawable.setDrawableByLayerId( + R.id.shortcut_foreground, + getGameIcon(lifecycleOwner, game).toDrawable(SudachiApplication.appContext.resources) + ) + val inset = SudachiApplication.appContext.resources + .getDimensionPixelSize(R.dimen.icon_inset) + layerDrawable.setLayerInset(1, inset, inset, inset, inset) + return IconCompat.createWithAdaptiveBitmap( + layerDrawable.toBitmap(config = Bitmap.Config.ARGB_8888) + ) + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/GameMetadata.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/GameMetadata.kt new file mode 100644 index 0000000..3aaee61 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/GameMetadata.kt @@ -0,0 +1,22 @@ +// SPDX-FileCopyrightText: Copyright 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.utils + +object GameMetadata { + external fun getIsValid(path: String): Boolean + + external fun getTitle(path: String): String + + external fun getProgramId(path: String): String + + external fun getDeveloper(path: String): String + + external fun getVersion(path: String, reload: Boolean): String + + external fun getIcon(path: String): ByteArray + + external fun getIsHomebrew(path: String): Boolean + + external fun resetMetadata() +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/GpuDriverHelper.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/GpuDriverHelper.kt new file mode 100644 index 0000000..94ef649 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/GpuDriverHelper.kt @@ -0,0 +1,229 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.utils + +import android.graphics.SurfaceTexture +import android.net.Uri +import android.os.Build +import android.view.Surface +import java.io.File +import java.io.IOException +import org.sudachi.sudachi_emu.NativeLibrary +import org.sudachi.sudachi_emu.SudachiApplication +import org.sudachi.sudachi_emu.features.settings.model.StringSetting +import java.io.FileNotFoundException +import java.util.zip.ZipException +import java.util.zip.ZipFile + +object GpuDriverHelper { + private const val META_JSON_FILENAME = "meta.json" + private var fileRedirectionPath: String? = null + var driverInstallationPath: String? = null + private var hookLibPath: String? = null + + val driverStoragePath get() = DirectoryInitialization.userDirectory!! + "/gpu_drivers/" + + fun initializeDriverParameters() { + try { + // Initialize the file redirection directory. + fileRedirectionPath = SudachiApplication.appContext + .getExternalFilesDir(null)!!.canonicalPath + "/gpu/vk_file_redirect/" + + // Initialize the driver installation directory. + driverInstallationPath = SudachiApplication.appContext + .filesDir.canonicalPath + "/gpu_driver/" + } catch (e: IOException) { + throw RuntimeException(e) + } + + // Initialize directories. + initializeDirectories() + + // Initialize hook libraries directory. + hookLibPath = SudachiApplication.appContext.applicationInfo.nativeLibraryDir + "/" + + // Initialize GPU driver. + NativeLibrary.initializeGpuDriver( + hookLibPath, + driverInstallationPath, + installedCustomDriverData.libraryName, + fileRedirectionPath + ) + } + + fun getDrivers(): MutableList> { + val driverZips = File(driverStoragePath).listFiles() + val drivers: MutableList> = + driverZips + ?.mapNotNull { + val metadata = getMetadataFromZip(it) + metadata.name?.let { _ -> Pair(it.path, metadata) } + } + ?.sortedByDescending { it: Pair -> it.second.name } + ?.distinct() + ?.toMutableList() ?: mutableListOf() + return drivers + } + + fun installDefaultDriver() { + // Removing the installed driver will result in the backend using the default system driver. + File(driverInstallationPath!!).deleteRecursively() + initializeDriverParameters() + } + + fun copyDriverToInternalStorage(driverUri: Uri): Boolean { + // Ensure we have directories. + initializeDirectories() + + // Copy the zip file URI to user data + val copiedFile = + FileUtil.copyUriToInternalStorage(driverUri, driverStoragePath) ?: return false + + // Validate driver + val metadata = getMetadataFromZip(copiedFile) + if (metadata.name == null) { + copiedFile.delete() + return false + } + + if (metadata.minApi > Build.VERSION.SDK_INT) { + copiedFile.delete() + return false + } + return true + } + + /** + * Copies driver zip into user data directory so that it can be exported along with + * other user data and also unzipped into the installation directory + */ + fun installCustomDriver(driverUri: Uri): Boolean { + // Revert to system default in the event the specified driver is bad. + installDefaultDriver() + + // Ensure we have directories. + initializeDirectories() + + // Copy the zip file URI to user data + val copiedFile = + FileUtil.copyUriToInternalStorage(driverUri, driverStoragePath) ?: return false + + // Validate driver + val metadata = getMetadataFromZip(copiedFile) + if (metadata.name == null) { + copiedFile.delete() + return false + } + + if (metadata.minApi > Build.VERSION.SDK_INT) { + copiedFile.delete() + return false + } + + // Unzip the driver. + try { + FileUtil.unzipToInternalStorage( + copiedFile.path, + File(driverInstallationPath!!) + ) + } catch (e: SecurityException) { + return false + } + + // Initialize the driver parameters. + initializeDriverParameters() + + return true + } + + /** + * Unzips driver into installation directory + */ + fun installCustomDriver(driver: File): Boolean { + // Revert to system default in the event the specified driver is bad. + installDefaultDriver() + + // Ensure we have directories. + initializeDirectories() + + // Validate driver + val metadata = getMetadataFromZip(driver) + if (metadata.name == null) { + driver.delete() + return false + } + + // Unzip the driver to the private installation directory + try { + FileUtil.unzipToInternalStorage( + driver.path, + File(driverInstallationPath!!) + ) + } catch (e: SecurityException) { + return false + } + + // Initialize the driver parameters. + initializeDriverParameters() + + return true + } + + /** + * Takes in a zip file and reads the meta.json file for presentation to the UI + * + * @param driver Zip containing driver and meta.json file + * @return A non-null [GpuDriverMetadata] instance that may have null members + */ + fun getMetadataFromZip(driver: File): GpuDriverMetadata { + try { + ZipFile(driver).use { zf -> + val entries = zf.entries() + while (entries.hasMoreElements()) { + val entry = entries.nextElement() + if (!entry.isDirectory && entry.name.lowercase().contains(".json")) { + zf.getInputStream(entry).use { + return GpuDriverMetadata(it, entry.size) + } + } + } + } + } catch (_: ZipException) { + } catch (_: FileNotFoundException) { + } + return GpuDriverMetadata() + } + + external fun supportsCustomDriverLoading(): Boolean + + external fun getSystemDriverInfo( + surface: Surface = Surface(SurfaceTexture(true)), + hookLibPath: String = GpuDriverHelper.hookLibPath!! + ): Array? + + // Parse the custom driver metadata to retrieve the name. + val installedCustomDriverData: GpuDriverMetadata + get() = GpuDriverMetadata(File(driverInstallationPath + META_JSON_FILENAME)) + + val customDriverSettingData: GpuDriverMetadata + get() = getMetadataFromZip(File(StringSetting.DRIVER_PATH.getString())) + + fun initializeDirectories() { + // Ensure the file redirection directory exists. + val fileRedirectionDir = File(fileRedirectionPath!!) + if (!fileRedirectionDir.exists()) { + fileRedirectionDir.mkdirs() + } + // Ensure the driver installation directory exists. + val driverInstallationDir = File(driverInstallationPath!!) + if (!driverInstallationDir.exists()) { + driverInstallationDir.mkdirs() + } + // Ensure the driver storage directory exists + val driverStorageDirectory = File(driverStoragePath) + if (!driverStorageDirectory.exists()) { + driverStorageDirectory.mkdirs() + } + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/GpuDriverMetadata.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/GpuDriverMetadata.kt new file mode 100644 index 0000000..3e00e8a --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/GpuDriverMetadata.kt @@ -0,0 +1,119 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.utils + +import java.io.IOException +import org.json.JSONException +import org.json.JSONObject +import java.io.File +import java.io.InputStream + +class GpuDriverMetadata { + /** + * Tries to get driver metadata information from a meta.json [File] + * + * @param metadataFile meta.json file provided with a GPU driver + */ + constructor(metadataFile: File) { + if (metadataFile.length() > MAX_META_SIZE_BYTES) { + return + } + + try { + val json = JSONObject(FileUtil.getStringFromFile(metadataFile)) + name = json.getString("name") + description = json.getString("description") + author = json.getString("author") + vendor = json.getString("vendor") + version = json.getString("driverVersion") + minApi = json.getInt("minApi") + libraryName = json.getString("libraryName") + } catch (e: JSONException) { + // JSON is malformed, ignore and treat as unsupported metadata. + } catch (e: IOException) { + // File is inaccessible, ignore and treat as unsupported metadata. + } + } + + /** + * Tries to get driver metadata information from an input stream that's intended to be + * from a zip file + * + * @param metadataStream ZipEntry input stream + * @param size Size of the file in bytes + */ + constructor(metadataStream: InputStream, size: Long) { + if (size > MAX_META_SIZE_BYTES) { + return + } + + try { + val json = JSONObject(FileUtil.getStringFromInputStream(metadataStream)) + name = json.getString("name") + description = json.getString("description") + author = json.getString("author") + vendor = json.getString("vendor") + version = json.getString("driverVersion") + minApi = json.getInt("minApi") + libraryName = json.getString("libraryName") + } catch (e: JSONException) { + // JSON is malformed, ignore and treat as unsupported metadata. + } catch (e: IOException) { + // File is inaccessible, ignore and treat as unsupported metadata. + } + } + + /** + * Creates an empty metadata instance + */ + constructor() + + override fun equals(other: Any?): Boolean { + if (other !is GpuDriverMetadata) { + return false + } + + return other.name == name && + other.description == description && + other.author == author && + other.vendor == vendor && + other.version == version && + other.minApi == minApi && + other.libraryName == libraryName + } + + override fun hashCode(): Int { + var result = name?.hashCode() ?: 0 + result = 31 * result + (description?.hashCode() ?: 0) + result = 31 * result + (author?.hashCode() ?: 0) + result = 31 * result + (vendor?.hashCode() ?: 0) + result = 31 * result + (version?.hashCode() ?: 0) + result = 31 * result + minApi + result = 31 * result + (libraryName?.hashCode() ?: 0) + return result + } + + override fun toString(): String = + """ + Name - $name + Description - $description + Author - $author + Vendor - $vendor + Version - $version + Min API - $minApi + Library Name - $libraryName + """.trimMargin().trimIndent() + + var name: String? = null + var description: String? = null + var author: String? = null + var vendor: String? = null + var version: String? = null + var minApi = 0 + var libraryName: String? = null + + companion object { + private const val MAX_META_SIZE_BYTES = 500000 + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/InputHandler.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/InputHandler.kt new file mode 100644 index 0000000..3aa83be --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/InputHandler.kt @@ -0,0 +1,94 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-3.0-or-later + +package org.sudachi.sudachi_emu.utils + +import android.view.InputDevice +import android.view.KeyEvent +import android.view.MotionEvent +import org.sudachi.sudachi_emu.features.input.NativeInput +import org.sudachi.sudachi_emu.features.input.SudachiInputOverlayDevice +import org.sudachi.sudachi_emu.features.input.SudachiPhysicalDevice + +object InputHandler { + var androidControllers = mapOf() + var registeredControllers = mutableListOf() + + fun dispatchKeyEvent(event: KeyEvent): Boolean { + val action = when (event.action) { + KeyEvent.ACTION_DOWN -> NativeInput.ButtonState.PRESSED + KeyEvent.ACTION_UP -> NativeInput.ButtonState.RELEASED + else -> return false + } + + var controllerData = androidControllers[event.device.controllerNumber] + if (controllerData == null) { + updateControllerData() + controllerData = androidControllers[event.device.controllerNumber] ?: return false + } + + NativeInput.onGamePadButtonEvent( + controllerData.getGUID(), + controllerData.getPort(), + event.keyCode, + action + ) + return true + } + + fun dispatchGenericMotionEvent(event: MotionEvent): Boolean { + val controllerData = + androidControllers[event.device.controllerNumber] ?: return false + event.device.motionRanges.forEach { + NativeInput.onGamePadAxisEvent( + controllerData.getGUID(), + controllerData.getPort(), + it.axis, + event.getAxisValue(it.axis) + ) + } + return true + } + + fun getDevices(): Map { + val gameControllerDeviceIds = mutableMapOf() + val deviceIds = InputDevice.getDeviceIds() + var port = 0 + val inputSettings = NativeConfig.getInputSettings(true) + deviceIds.forEach { deviceId -> + InputDevice.getDevice(deviceId)?.apply { + // Verify that the device has gamepad buttons, control sticks, or both. + if (sources and InputDevice.SOURCE_GAMEPAD == InputDevice.SOURCE_GAMEPAD || + sources and InputDevice.SOURCE_JOYSTICK == InputDevice.SOURCE_JOYSTICK + ) { + if (!gameControllerDeviceIds.contains(controllerNumber)) { + gameControllerDeviceIds[controllerNumber] = SudachiPhysicalDevice( + this, + port, + inputSettings[port].useSystemVibrator + ) + } + port++ + } + } + } + return gameControllerDeviceIds + } + + fun updateControllerData() { + androidControllers = getDevices() + androidControllers.forEach { + NativeInput.registerController(it.value) + } + + // Register the input overlay on a dedicated port for all player 1 vibrations + NativeInput.registerController(SudachiInputOverlayDevice(androidControllers.isEmpty(), 100)) + registeredControllers.clear() + NativeInput.getInputDevices().forEach { + registeredControllers.add(ParamPackage(it)) + } + registeredControllers.sortBy { it.get("port", 0) } + } + + fun InputDevice.getGUID(): String = String.format("%016x%016x", productId, vendorId) +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/InsetsHelper.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/InsetsHelper.kt new file mode 100644 index 0000000..01d0a93 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/InsetsHelper.kt @@ -0,0 +1,25 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-3.0-or-later + +package org.sudachi.sudachi_emu.utils + +import android.annotation.SuppressLint +import android.content.Context + +object InsetsHelper { + const val THREE_BUTTON_NAVIGATION = 0 + const val TWO_BUTTON_NAVIGATION = 1 + const val GESTURE_NAVIGATION = 2 + + @SuppressLint("DiscouragedApi") + fun getSystemGestureType(context: Context): Int { + val resources = context.resources + val resourceId = + resources.getIdentifier("config_navBarInteractionMode", "integer", "android") + return if (resourceId != 0) { + resources.getInteger(resourceId) + } else { + 0 + } + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/LifecycleUtils.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/LifecycleUtils.kt new file mode 100644 index 0000000..2158a49 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/LifecycleUtils.kt @@ -0,0 +1,38 @@ +// SPDX-FileCopyrightText: 2024 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.utils + +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.LifecycleOwner +import androidx.lifecycle.lifecycleScope +import androidx.lifecycle.repeatOnLifecycle +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.launch + +/** + * Collects this [Flow] with a given [LifecycleOwner]. + * @param scope [LifecycleOwner] that this [Flow] will be collected with. + * @param repeatState When to repeat collection on this [Flow]. + * @param resetState Optional lambda to reset state of an underlying [MutableStateFlow] after + * [stateCollector] has been run. + * @param stateCollector Lambda that receives new state. + */ +inline fun Flow.collect( + scope: LifecycleOwner, + repeatState: Lifecycle.State = Lifecycle.State.CREATED, + crossinline resetState: () -> Unit = {}, + crossinline stateCollector: (state: T) -> Unit +) { + scope.apply { + lifecycleScope.launch { + repeatOnLifecycle(repeatState) { + this@collect.collect { + stateCollector(it) + resetState() + } + } + } + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/Log.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/Log.kt new file mode 100644 index 0000000..2995648 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/Log.kt @@ -0,0 +1,31 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.utils + +import android.os.Build + +object Log { + // Tracks whether we should share the old log or the current log + var gameLaunched = false + + external fun debug(message: String) + + external fun warning(message: String) + + external fun info(message: String) + + external fun error(message: String) + + external fun critical(message: String) + + fun logDeviceInfo() { + info("Device Manufacturer - ${Build.MANUFACTURER}") + info("Device Model - ${Build.MODEL}") + if (Build.VERSION.SDK_INT > Build.VERSION_CODES.R) { + info("SoC Manufacturer - ${Build.SOC_MANUFACTURER}") + info("SoC Model - ${Build.SOC_MODEL}") + } + info("Total System Memory - ${MemoryUtil.getDeviceRAM()}") + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/MemoryUtil.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/MemoryUtil.kt new file mode 100644 index 0000000..884ab83 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/MemoryUtil.kt @@ -0,0 +1,111 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.utils + +import android.app.ActivityManager +import android.content.Context +import android.os.Build +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.SudachiApplication +import java.util.Locale +import kotlin.math.ceil + +object MemoryUtil { + private val context get() = SudachiApplication.appContext + + private val Float.hundredths: String + get() = String.format(Locale.ROOT, "%.2f", this) + + // Required total system memory + const val REQUIRED_MEMORY = 8 + + const val Kb: Float = 1024F + const val Mb = Kb * 1024 + const val Gb = Mb * 1024 + const val Tb = Gb * 1024 + const val Pb = Tb * 1024 + const val Eb = Pb * 1024 + + fun bytesToSizeUnit(size: Float, roundUp: Boolean = false): String = + when { + size < Kb -> { + context.getString( + R.string.memory_formatted, + size.hundredths, + context.getString(R.string.memory_byte_shorthand) + ) + } + size < Mb -> { + context.getString( + R.string.memory_formatted, + if (roundUp) ceil(size / Kb) else (size / Kb).hundredths, + context.getString(R.string.memory_kilobyte) + ) + } + size < Gb -> { + context.getString( + R.string.memory_formatted, + if (roundUp) ceil(size / Mb) else (size / Mb).hundredths, + context.getString(R.string.memory_megabyte) + ) + } + size < Tb -> { + context.getString( + R.string.memory_formatted, + if (roundUp) ceil(size / Gb) else (size / Gb).hundredths, + context.getString(R.string.memory_gigabyte) + ) + } + size < Pb -> { + context.getString( + R.string.memory_formatted, + if (roundUp) ceil(size / Tb) else (size / Tb).hundredths, + context.getString(R.string.memory_terabyte) + ) + } + size < Eb -> { + context.getString( + R.string.memory_formatted, + if (roundUp) ceil(size / Pb) else (size / Pb).hundredths, + context.getString(R.string.memory_petabyte) + ) + } + else -> { + context.getString( + R.string.memory_formatted, + if (roundUp) ceil(size / Eb) else (size / Eb).hundredths, + context.getString(R.string.memory_exabyte) + ) + } + } + + val totalMemory: Float + get() { + val memInfo = ActivityManager.MemoryInfo() + with(context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager) { + getMemoryInfo(memInfo) + } + + return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { + memInfo.advertisedMem.toFloat() + } else { + memInfo.totalMem.toFloat() + } + } + + fun isLessThan(minimum: Int, size: Float): Boolean = + when (size) { + Kb -> totalMemory < Mb && totalMemory < minimum + Mb -> totalMemory < Gb && (totalMemory / Mb) < minimum + Gb -> totalMemory < Tb && (totalMemory / Gb) < minimum + Tb -> totalMemory < Pb && (totalMemory / Tb) < minimum + Pb -> totalMemory < Eb && (totalMemory / Pb) < minimum + Eb -> totalMemory / Eb < minimum + else -> totalMemory < Kb && totalMemory < minimum + } + + // Devices are unlikely to have 0.5GB increments of memory so we'll just round up to account for + // the potential error created by memInfo.totalMem + fun getDeviceRAM(): String = bytesToSizeUnit(totalMemory, true) +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/NativeConfig.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/NativeConfig.kt new file mode 100644 index 0000000..a8d3694 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/NativeConfig.kt @@ -0,0 +1,186 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.utils + +import org.sudachi.sudachi_emu.model.GameDir +import org.sudachi.sudachi_emu.overlay.model.OverlayControlData + +import org.sudachi.sudachi_emu.features.input.model.PlayerInput + +object NativeConfig { + /** + * Loads global config. + */ + @Synchronized + external fun initializeGlobalConfig() + + /** + * Destroys the stored global config object. This does not save the existing config. + */ + @Synchronized + external fun unloadGlobalConfig() + + /** + * Reads values in the global config file and saves them. + */ + @Synchronized + external fun reloadGlobalConfig() + + /** + * Saves global settings values in memory to disk. + */ + @Synchronized + external fun saveGlobalConfig() + + /** + * Creates per-game config for the specified parameters. Must be unloaded once per-game config + * is closed with [unloadPerGameConfig]. All switchable values that [NativeConfig] gets/sets + * will follow the per-game config until the global config is reloaded. + * + * @param programId String representation of the u64 programId + * @param fileName Filename of the game, including its extension + */ + @Synchronized + external fun initializePerGameConfig(programId: String, fileName: String) + + @Synchronized + external fun isPerGameConfigLoaded(): Boolean + + /** + * Saves per-game settings values in memory to disk. + */ + @Synchronized + external fun savePerGameConfig() + + /** + * Destroys the stored per-game config object. This does not save the config. + */ + @Synchronized + external fun unloadPerGameConfig() + + @Synchronized + external fun getBoolean(key: String, needsGlobal: Boolean): Boolean + + @Synchronized + external fun setBoolean(key: String, value: Boolean) + + @Synchronized + external fun getByte(key: String, needsGlobal: Boolean): Byte + + @Synchronized + external fun setByte(key: String, value: Byte) + + @Synchronized + external fun getShort(key: String, needsGlobal: Boolean): Short + + @Synchronized + external fun setShort(key: String, value: Short) + + @Synchronized + external fun getInt(key: String, needsGlobal: Boolean): Int + + @Synchronized + external fun setInt(key: String, value: Int) + + @Synchronized + external fun getFloat(key: String, needsGlobal: Boolean): Float + + @Synchronized + external fun setFloat(key: String, value: Float) + + @Synchronized + external fun getLong(key: String, needsGlobal: Boolean): Long + + @Synchronized + external fun setLong(key: String, value: Long) + + @Synchronized + external fun getString(key: String, needsGlobal: Boolean): String + + @Synchronized + external fun setString(key: String, value: String) + + external fun getIsRuntimeModifiable(key: String): Boolean + + external fun getPairedSettingKey(key: String): String + + external fun getIsSwitchable(key: String): Boolean + + @Synchronized + external fun usingGlobal(key: String): Boolean + + @Synchronized + external fun setGlobal(key: String, global: Boolean) + + external fun getIsSaveable(key: String): Boolean + + external fun getDefaultToString(key: String): String + + /** + * Gets every [GameDir] in AndroidSettings::values.game_dirs + */ + @Synchronized + external fun getGameDirs(): Array + + /** + * Clears the AndroidSettings::values.game_dirs array and replaces them with the provided array + */ + @Synchronized + external fun setGameDirs(dirs: Array) + + /** + * Adds a single [GameDir] to the AndroidSettings::values.game_dirs array + */ + @Synchronized + external fun addGameDir(dir: GameDir) + + /** + * Gets an array of the addons that are disabled for a given game + * + * @param programId String representation of a game's program ID + * @return An array of disabled addons + */ + @Synchronized + external fun getDisabledAddons(programId: String): Array + + /** + * Clears the disabled addons array corresponding to [programId] and replaces them + * with [disabledAddons] + * + * @param programId String representation of a game's program ID + * @param disabledAddons Replacement array of disabled addons + */ + @Synchronized + external fun setDisabledAddons(programId: String, disabledAddons: Array) + + /** + * Gets an array of [OverlayControlData] from settings + * + * @return An array of [OverlayControlData] + */ + @Synchronized + external fun getOverlayControlData(): Array + + /** + * Clears the AndroidSettings::values.overlay_control_data array and replaces its values + * with [overlayControlData] + * + * @param overlayControlData Replacement array of [OverlayControlData] + */ + @Synchronized + external fun setOverlayControlData(overlayControlData: Array) + + @Synchronized + external fun getInputSettings(global: Boolean): Array + + @Synchronized + external fun setInputSettings(value: Array, global: Boolean) + + /** + * Saves control values for a specific player + * Must be used when per game config is loaded + */ + @Synchronized + external fun saveControlPlayerValues() +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/NfcReader.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/NfcReader.kt new file mode 100644 index 0000000..b855c46 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/NfcReader.kt @@ -0,0 +1,171 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-3.0-or-later + +package org.sudachi.sudachi_emu.utils + +import android.app.Activity +import android.app.PendingIntent +import android.content.Intent +import android.content.IntentFilter +import android.nfc.NfcAdapter +import android.nfc.Tag +import android.nfc.tech.NfcA +import android.os.Build +import android.os.Handler +import android.os.Looper +import java.io.IOException +import org.sudachi.sudachi_emu.features.input.NativeInput + +class NfcReader(private val activity: Activity) { + private var nfcAdapter: NfcAdapter? = null + private var pendingIntent: PendingIntent? = null + + fun initialize() { + nfcAdapter = NfcAdapter.getDefaultAdapter(activity) ?: return + + pendingIntent = PendingIntent.getActivity( + activity, + 0, + Intent(activity, activity.javaClass), + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE + } else { + PendingIntent.FLAG_UPDATE_CURRENT + } + ) + + val tagDetected = IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED) + tagDetected.addCategory(Intent.CATEGORY_DEFAULT) + } + + fun startScanning() { + nfcAdapter?.enableForegroundDispatch(activity, pendingIntent, null, null) + } + + fun stopScanning() { + nfcAdapter?.disableForegroundDispatch(activity) + } + + fun onNewIntent(intent: Intent) { + val action = intent.action + if (NfcAdapter.ACTION_TAG_DISCOVERED != action && + NfcAdapter.ACTION_TECH_DISCOVERED != action && + NfcAdapter.ACTION_NDEF_DISCOVERED != action + ) { + return + } + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + val tag = + intent.getParcelableExtra(NfcAdapter.EXTRA_TAG, Tag::class.java) ?: return + readTagData(tag) + return + } + + val tag = + intent.getParcelableExtra(NfcAdapter.EXTRA_TAG) ?: return + readTagData(tag) + } + + private fun readTagData(tag: Tag) { + if (!tag.techList.contains("android.nfc.tech.NfcA")) { + return + } + + val amiibo = NfcA.get(tag) ?: return + amiibo.connect() + + val tagData = ntag215ReadAll(amiibo) ?: return + NativeInput.onReadNfcTag(tagData) + + nfcAdapter?.ignore( + tag, + 1000, + { NativeInput.onRemoveNfcTag() }, + Handler(Looper.getMainLooper()) + ) + } + + private fun ntag215ReadAll(amiibo: NfcA): ByteArray? { + val bufferSize = amiibo.maxTransceiveLength + val tagSize = 0x21C + val pageSize = 4 + val lastPage = tagSize / pageSize - 1 + val tagData = ByteArray(tagSize) + + // We need to read the ntag in steps otherwise we overflow the buffer + for (i in 0..tagSize step bufferSize - 1) { + val dataStart = i / pageSize + var dataEnd = (i + bufferSize) / pageSize + + if (dataEnd > lastPage) { + dataEnd = lastPage + } + + try { + val data = ntag215FastRead(amiibo, dataStart, dataEnd - 1) + System.arraycopy(data, 0, tagData, i, (dataEnd - dataStart) * pageSize) + } catch (e: IOException) { + return null + } + } + return tagData + } + + private fun ntag215Read(amiibo: NfcA, page: Int): ByteArray? { + return amiibo.transceive( + byteArrayOf( + 0x30.toByte(), + (page and 0xFF).toByte() + ) + ) + } + + private fun ntag215FastRead(amiibo: NfcA, start: Int, end: Int): ByteArray? { + return amiibo.transceive( + byteArrayOf( + 0x3A.toByte(), + (start and 0xFF).toByte(), + (end and 0xFF).toByte() + ) + ) + } + + private fun ntag215PWrite( + amiibo: NfcA, + page: Int, + data1: Int, + data2: Int, + data3: Int, + data4: Int + ): ByteArray? { + return amiibo.transceive( + byteArrayOf( + 0xA2.toByte(), + (page and 0xFF).toByte(), + (data1 and 0xFF).toByte(), + (data2 and 0xFF).toByte(), + (data3 and 0xFF).toByte(), + (data4 and 0xFF).toByte() + ) + ) + } + + private fun ntag215PwdAuth( + amiibo: NfcA, + data1: Int, + data2: Int, + data3: Int, + data4: Int + ): ByteArray? { + return amiibo.transceive( + byteArrayOf( + 0x1B.toByte(), + (data1 and 0xFF).toByte(), + (data2 and 0xFF).toByte(), + (data3 and 0xFF).toByte(), + (data4 and 0xFF).toByte() + ) + ) + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/ParamPackage.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/ParamPackage.kt new file mode 100644 index 0000000..8d9ccc4 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/ParamPackage.kt @@ -0,0 +1,141 @@ +// SPDX-FileCopyrightText: 2024 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.utils + +// Kotlin version of src/common/param_package.h +class ParamPackage(serialized: String = "") { + private val KEY_VALUE_SEPARATOR = ":" + private val PARAM_SEPARATOR = "," + + private val ESCAPE_CHARACTER = "$" + private val KEY_VALUE_SEPARATOR_ESCAPE = "$0" + private val PARAM_SEPARATOR_ESCAPE = "$1" + private val ESCAPE_CHARACTER_ESCAPE = "$2" + + private val EMPTY_PLACEHOLDER = "[empty]" + + val data = mutableMapOf() + + init { + val pairs = serialized.split(PARAM_SEPARATOR) + for (pair in pairs) { + val keyValue = pair.split(KEY_VALUE_SEPARATOR).toMutableList() + if (keyValue.size != 2) { + Log.error("[ParamPackage] Invalid key pair $keyValue") + continue + } + + keyValue.forEachIndexed { i: Int, _: String -> + keyValue[i] = keyValue[i].replace(KEY_VALUE_SEPARATOR_ESCAPE, KEY_VALUE_SEPARATOR) + keyValue[i] = keyValue[i].replace(PARAM_SEPARATOR_ESCAPE, PARAM_SEPARATOR) + keyValue[i] = keyValue[i].replace(ESCAPE_CHARACTER_ESCAPE, ESCAPE_CHARACTER) + } + + set(keyValue[0], keyValue[1]) + } + } + + constructor(params: List>) : this() { + params.forEach { + data[it.first] = it.second + } + } + + fun serialize(): String { + if (data.isEmpty()) { + return EMPTY_PLACEHOLDER + } + + val result = StringBuilder() + data.forEach { + val keyValue = mutableListOf(it.key, it.value) + keyValue.forEachIndexed { i, _ -> + keyValue[i] = keyValue[i].replace(ESCAPE_CHARACTER, ESCAPE_CHARACTER_ESCAPE) + keyValue[i] = keyValue[i].replace(PARAM_SEPARATOR, PARAM_SEPARATOR_ESCAPE) + keyValue[i] = keyValue[i].replace(KEY_VALUE_SEPARATOR, KEY_VALUE_SEPARATOR_ESCAPE) + } + result.append("${keyValue[0]}$KEY_VALUE_SEPARATOR${keyValue[1]}$PARAM_SEPARATOR") + } + return result.removeSuffix(PARAM_SEPARATOR).toString() + } + + fun get(key: String, defaultValue: String): String = + if (has(key)) { + data[key]!! + } else { + Log.debug("[ParamPackage] key $key not found") + defaultValue + } + + fun get(key: String, defaultValue: Int): Int = + if (has(key)) { + try { + data[key]!!.toInt() + } catch (e: NumberFormatException) { + Log.debug("[ParamPackage] failed to convert ${data[key]!!} to int") + defaultValue + } + } else { + Log.debug("[ParamPackage] key $key not found") + defaultValue + } + + private fun Int.toBoolean(): Boolean = + if (this == 1) { + true + } else if (this == 0) { + false + } else { + throw Exception("Tried to convert a value to a boolean that was not 0 or 1!") + } + + fun get(key: String, defaultValue: Boolean): Boolean = + if (has(key)) { + try { + get(key, if (defaultValue) 1 else 0).toBoolean() + } catch (e: Exception) { + Log.debug("[ParamPackage] failed to convert ${data[key]!!} to boolean") + defaultValue + } + } else { + Log.debug("[ParamPackage] key $key not found") + defaultValue + } + + fun get(key: String, defaultValue: Float): Float = + if (has(key)) { + try { + data[key]!!.toFloat() + } catch (e: NumberFormatException) { + Log.debug("[ParamPackage] failed to convert ${data[key]!!} to float") + defaultValue + } + } else { + Log.debug("[ParamPackage] key $key not found") + defaultValue + } + + fun set(key: String, value: String) { + data[key] = value + } + + fun set(key: String, value: Int) { + data[key] = value.toString() + } + + fun Boolean.toInt(): Int = if (this) 1 else 0 + fun set(key: String, value: Boolean) { + data[key] = value.toInt().toString() + } + + fun set(key: String, value: Float) { + data[key] = value.toString() + } + + fun has(key: String): Boolean = data.containsKey(key) + + fun erase(key: String) = data.remove(key) + + fun clear() = data.clear() +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/PreferenceUtil.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/PreferenceUtil.kt new file mode 100644 index 0000000..a3daa27 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/PreferenceUtil.kt @@ -0,0 +1,37 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.utils + +import android.content.SharedPreferences + +object PreferenceUtil { + /** + * Retrieves a shared preference value and then deletes the value in storage. + * @param key Associated key for the value in this preferences instance + * @return Typed value associated with [key]. Null if no such key exists. + */ + inline fun SharedPreferences.migratePreference(key: String): T? { + if (!this.contains(key)) { + return null + } + + val value: Any = when (T::class) { + String::class -> this.getString(key, "")!! + + Boolean::class -> this.getBoolean(key, false) + + Int::class -> this.getInt(key, 0) + + Float::class -> this.getFloat(key, 0f) + + Long::class -> this.getLong(key, 0) + + else -> throw IllegalStateException("Tried to migrate preference with invalid type!") + } + deletePreference(key) + return value as T + } + + fun SharedPreferences.deletePreference(key: String) = this.edit().remove(key).apply() +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/SerializableHelper.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/SerializableHelper.kt new file mode 100644 index 0000000..a8182ab --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/SerializableHelper.kt @@ -0,0 +1,44 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-3.0-or-later + +package org.sudachi.sudachi_emu.utils + +import android.content.Intent +import android.os.Build +import android.os.Bundle +import android.os.Parcelable +import java.io.Serializable + +object SerializableHelper { + inline fun Bundle.serializable(key: String): T? { + return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + getSerializable(key, T::class.java) + } else { + getSerializable(key) as? T + } + } + + inline fun Intent.serializable(key: String): T? { + return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + getSerializableExtra(key, T::class.java) + } else { + getSerializableExtra(key) as? T + } + } + + inline fun Bundle.parcelable(key: String): T? { + return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + getParcelable(key, T::class.java) + } else { + getParcelable(key) as? T + } + } + + inline fun Intent.parcelable(key: String): T? { + return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + getParcelableExtra(key, T::class.java) + } else { + getParcelableExtra(key) as? T + } + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/ThemeHelper.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/ThemeHelper.kt new file mode 100644 index 0000000..0d44249 --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/ThemeHelper.kt @@ -0,0 +1,105 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.utils + +import android.content.res.Configuration +import android.graphics.Color +import android.os.Build +import androidx.annotation.ColorInt +import androidx.appcompat.app.AppCompatActivity +import androidx.appcompat.app.AppCompatDelegate +import androidx.core.view.WindowCompat +import androidx.core.view.WindowInsetsControllerCompat +import kotlin.math.roundToInt +import org.sudachi.sudachi_emu.R +import org.sudachi.sudachi_emu.features.settings.model.BooleanSetting +import org.sudachi.sudachi_emu.features.settings.model.IntSetting +import org.sudachi.sudachi_emu.ui.main.ThemeProvider + +object ThemeHelper { + const val SYSTEM_BAR_ALPHA = 0.9f + + fun setTheme(activity: AppCompatActivity) { + setThemeMode(activity) + when (Theme.from(IntSetting.THEME.getInt())) { + Theme.Default -> activity.setTheme(R.style.Theme_Sudachi_Main) + Theme.MaterialYou -> { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + activity.setTheme(R.style.Theme_Sudachi_Main_MaterialYou) + } else { + activity.setTheme(R.style.Theme_Sudachi_Main) + } + } + } + + // Using a specific night mode check because this could apply incorrectly when using the + // light app mode, dark system mode, and black backgrounds. Launching the settings activity + // will then show light mode colors/navigation bars but with black backgrounds. + if (BooleanSetting.BLACK_BACKGROUNDS.getBoolean() && isNightMode(activity)) { + activity.setTheme(R.style.ThemeOverlay_Sudachi_Dark) + } + } + + @ColorInt + fun getColorWithOpacity(@ColorInt color: Int, alphaFactor: Float): Int { + return Color.argb( + (alphaFactor * Color.alpha(color)).roundToInt(), + Color.red(color), + Color.green(color), + Color.blue(color) + ) + } + + fun setCorrectTheme(activity: AppCompatActivity) { + val currentTheme = (activity as ThemeProvider).themeId + setTheme(activity) + if (currentTheme != (activity as ThemeProvider).themeId) { + activity.recreate() + } + } + + fun setThemeMode(activity: AppCompatActivity) { + val themeMode = IntSetting.THEME_MODE.getInt() + activity.delegate.localNightMode = themeMode + val windowController = WindowCompat.getInsetsController( + activity.window, + activity.window.decorView + ) + when (themeMode) { + AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM -> when (isNightMode(activity)) { + false -> setLightModeSystemBars(windowController) + true -> setDarkModeSystemBars(windowController) + } + AppCompatDelegate.MODE_NIGHT_NO -> setLightModeSystemBars(windowController) + AppCompatDelegate.MODE_NIGHT_YES -> setDarkModeSystemBars(windowController) + } + } + + private fun isNightMode(activity: AppCompatActivity): Boolean { + return when (activity.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK) { + Configuration.UI_MODE_NIGHT_NO -> false + Configuration.UI_MODE_NIGHT_YES -> true + else -> false + } + } + + private fun setLightModeSystemBars(windowController: WindowInsetsControllerCompat) { + windowController.isAppearanceLightStatusBars = true + windowController.isAppearanceLightNavigationBars = true + } + + private fun setDarkModeSystemBars(windowController: WindowInsetsControllerCompat) { + windowController.isAppearanceLightStatusBars = false + windowController.isAppearanceLightNavigationBars = false + } +} + +enum class Theme(val int: Int) { + Default(0), + MaterialYou(1); + + companion object { + fun from(int: Int): Theme = entries.firstOrNull { it.int == int } ?: Default + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/ViewUtils.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/ViewUtils.kt new file mode 100644 index 0000000..4509cdc --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/utils/ViewUtils.kt @@ -0,0 +1,93 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.utils + +import android.text.TextUtils +import android.view.View +import android.view.ViewGroup +import android.widget.TextView + +object ViewUtils { + fun showView(view: View, length: Long = 300) { + view.apply { + alpha = 0f + visibility = View.VISIBLE + isClickable = true + }.animate().apply { + duration = length + alpha(1f) + }.start() + } + + fun hideView(view: View, length: Long = 300) { + if (view.visibility == View.INVISIBLE) { + return + } + + view.apply { + alpha = 1f + isClickable = false + }.animate().apply { + duration = length + alpha(0f) + }.withEndAction { + view.visibility = View.INVISIBLE + }.start() + } + + fun View.updateMargins( + left: Int = -1, + top: Int = -1, + right: Int = -1, + bottom: Int = -1 + ) { + val layoutParams = this.layoutParams as ViewGroup.MarginLayoutParams + layoutParams.apply { + if (left != -1) { + leftMargin = left + } + if (top != -1) { + topMargin = top + } + if (right != -1) { + rightMargin = right + } + if (bottom != -1) { + bottomMargin = bottom + } + } + this.layoutParams = layoutParams + } + + /** + * Shows or hides a view. + * @param visible Whether a view will be made View.VISIBLE or View.INVISIBLE/GONE. + * @param gone Optional parameter for hiding a view. Uses View.GONE if true and View.INVISIBLE otherwise. + */ + fun View.setVisible(visible: Boolean, gone: Boolean = true) { + visibility = if (visible) { + View.VISIBLE + } else { + if (gone) { + View.GONE + } else { + View.INVISIBLE + } + } + } + + /** + * Starts a marquee on some text. + * @param delay Optional parameter for changing the start delay. 3 seconds of delay by default. + */ + fun TextView.marquee(delay: Long = 3000) { + ellipsize = null + marqueeRepeatLimit = -1 + isSingleLine = true + postDelayed({ + ellipsize = TextUtils.TruncateAt.MARQUEE + isSelected = true + }, delay) + } +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/viewholder/AbstractViewHolder.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/viewholder/AbstractViewHolder.kt new file mode 100644 index 0000000..b30b68b --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/viewholder/AbstractViewHolder.kt @@ -0,0 +1,18 @@ +// SPDX-FileCopyrightText: 2024 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.viewholder + +import androidx.recyclerview.widget.RecyclerView +import androidx.viewbinding.ViewBinding +import org.sudachi.sudachi_emu.adapters.AbstractDiffAdapter +import org.sudachi.sudachi_emu.adapters.AbstractListAdapter + +/** + * [RecyclerView.ViewHolder] meant to work together with a [AbstractDiffAdapter] or a + * [AbstractListAdapter] so we can run [bind] on each list item without needing a manual hookup. + */ +abstract class AbstractViewHolder(binding: ViewBinding) : + RecyclerView.ViewHolder(binding.root) { + abstract fun bind(model: Model) +} diff --git a/src/android/app/src/main/java/org/sudachi/sudachi_emu/views/FixedRatioSurfaceView.kt b/src/android/app/src/main/java/org/sudachi/sudachi_emu/views/FixedRatioSurfaceView.kt new file mode 100644 index 0000000..1a2874c --- /dev/null +++ b/src/android/app/src/main/java/org/sudachi/sudachi_emu/views/FixedRatioSurfaceView.kt @@ -0,0 +1,64 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +package org.sudachi.sudachi_emu.views + +import android.content.Context +import android.util.AttributeSet +import android.util.Rational +import android.view.SurfaceView + +class FixedRatioSurfaceView @JvmOverloads constructor( + context: Context, + attrs: AttributeSet? = null, + defStyleAttr: Int = 0 +) : SurfaceView(context, attrs, defStyleAttr) { + private var aspectRatio: Float = 0f // (width / height), 0f is a special value for stretch + + /** + * Sets the desired aspect ratio for this view + * @param ratio the ratio to force the view to, or null to stretch to fit + */ + fun setAspectRatio(ratio: Rational?) { + aspectRatio = ratio?.toFloat() ?: 0f + requestLayout() + } + + override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { + val displayWidth: Float = MeasureSpec.getSize(widthMeasureSpec).toFloat() + val displayHeight: Float = MeasureSpec.getSize(heightMeasureSpec).toFloat() + if (aspectRatio != 0f) { + val displayAspect = displayWidth / displayHeight + if (displayAspect < aspectRatio) { + // Max out width + val halfHeight = displayHeight / 2 + val surfaceHeight = displayWidth / aspectRatio + val newTop: Float = halfHeight - (surfaceHeight / 2) + val newBottom: Float = halfHeight + (surfaceHeight / 2) + super.onMeasure( + widthMeasureSpec, + MeasureSpec.makeMeasureSpec( + newBottom.toInt() - newTop.toInt(), + MeasureSpec.EXACTLY + ) + ) + return + } else { + // Max out height + val halfWidth = displayWidth / 2 + val surfaceWidth = displayHeight * aspectRatio + val newLeft: Float = halfWidth - (surfaceWidth / 2) + val newRight: Float = halfWidth + (surfaceWidth / 2) + super.onMeasure( + MeasureSpec.makeMeasureSpec( + newRight.toInt() - newLeft.toInt(), + MeasureSpec.EXACTLY + ), + heightMeasureSpec + ) + return + } + } + super.onMeasure(widthMeasureSpec, heightMeasureSpec) + } +} diff --git a/src/android/app/src/main/res/drawable/ic_sudachi.xml b/src/android/app/src/main/res/drawable/ic_sudachi.xml new file mode 100644 index 0000000..5e2a8ef --- /dev/null +++ b/src/android/app/src/main/res/drawable/ic_sudachi.xml @@ -0,0 +1,22 @@ + + + + diff --git a/src/android/app/src/main/res/drawable/ic_sudachi_full.xml b/src/android/app/src/main/res/drawable/ic_sudachi_full.xml new file mode 100644 index 0000000..04e4584 --- /dev/null +++ b/src/android/app/src/main/res/drawable/ic_sudachi_full.xml @@ -0,0 +1,12 @@ + + + + diff --git a/src/android/app/src/main/res/drawable/ic_sudachi_title.xml b/src/android/app/src/main/res/drawable/ic_sudachi_title.xml new file mode 100644 index 0000000..b733e52 --- /dev/null +++ b/src/android/app/src/main/res/drawable/ic_sudachi_title.xml @@ -0,0 +1,24 @@ + + + + + + + + diff --git a/src/android/app/src/main/res/values-night/sudachi_colors.xml b/src/android/app/src/main/res/values-night/sudachi_colors.xml new file mode 100644 index 0000000..465204f --- /dev/null +++ b/src/android/app/src/main/res/values-night/sudachi_colors.xml @@ -0,0 +1,37 @@ + + + + #A7DDEC + #003399 + #31323F + #D1E4FF + #BAC8DB + #253140 + #3B4858 + #D6E4F7 + #D6BEE5 + #3A2948 + #524060 + #F2DAFF + #FFB4AB + #93000A + #690005 + #FFDAD6 + #1A1C1E + #E2E2E6 + #1B1B1D + #E2E2E6 + #26282C + #C3C7CF + #8C9199 + #1A1C1E + #E2E2E6 + #0062A2 + #000000 + #9DCAFF + #42474E + + #840099 + #005AE1 + + diff --git a/src/android/app/src/main/res/values/sudachi_colors.xml b/src/android/app/src/main/res/values/sudachi_colors.xml new file mode 100644 index 0000000..7f291c5 --- /dev/null +++ b/src/android/app/src/main/res/values/sudachi_colors.xml @@ -0,0 +1,37 @@ + + + + #990E00 + #FFFFFF + #EEDEDD + #400200 + #775650 + #FFFFFF + #FFDAD4 + #2C1511 + #6F5C2E + #FFFFFF + #FAE0A6 + #251A00 + #BA1A1A + #FFDAD6 + #FFFFFF + #410002 + #FFFBFF + #201A19 + #FFFBFF + #201A19 + #F5DDD9 + #534340 + #857370 + #FBEEEB + #362F2D + #FFB4A6 + #000000 + #B52612 + #D8C2BE + + #99FFE1 + #76C5FF + + diff --git a/src/dedicated_room/sudachi_room.cpp b/src/dedicated_room/sudachi_room.cpp new file mode 100644 index 0000000..169813c --- /dev/null +++ b/src/dedicated_room/sudachi_room.cpp @@ -0,0 +1,403 @@ +// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include +#include +#include +#include +#include +#include + +#ifdef _WIN32 +// windows.h needs to be included before shellapi.h +#include + +#include +#endif + +#include +#include "common/common_types.h" +#include "common/detached_tasks.h" +#include "common/fs/file.h" +#include "common/fs/fs.h" +#include "common/fs/path_util.h" +#include "common/logging/backend.h" +#include "common/logging/log.h" +#include "common/scm_rev.h" +#include "common/settings.h" +#include "common/string_util.h" +#include "core/core.h" +#include "network/announce_multiplayer_session.h" +#include "network/network.h" +#include "network/room.h" +#include "network/verify_user.h" + +#ifdef ENABLE_WEB_SERVICE +#include "web_service/verify_user_jwt.h" +#endif + +#undef _UNICODE +#include +#ifndef _MSC_VER +#include +#endif + +static void PrintHelp(const char* argv0) { + LOG_INFO(Network, + "Usage: {}" + " [options] \n" + "--room-name The name of the room\n" + "--room-description The room description\n" + "--bind-address The bind address for the room\n" + "--port The port used for the room\n" + "--max_members The maximum number of players for this room\n" + "--password The password for the room\n" + "--preferred-game The preferred game for this room\n" + "--preferred-game-id The preferred game-id for this room\n" + "--username The username used for announce\n" + "--token The token used for announce\n" + "--web-api-url sudachi Web API url\n" + "--ban-list-file The file for storing the room ban list\n" + "--log-file The file for storing the room log\n" + "--enable-sudachi-mods Allow sudachi Community Moderators to moderate on your room\n" + "-h, --help Display this help and exit\n" + "-v, --version Output version information and exit\n", + argv0); +} + +static void PrintVersion() { + LOG_INFO(Network, "sudachi dedicated room {} {} Libnetwork: {}", Common::g_scm_branch, + Common::g_scm_desc, Network::network_version); +} + +/// The magic text at the beginning of a sudachi-room ban list file. +static constexpr char BanListMagic[] = "SudachiRoom-BanList-1"; + +static constexpr char token_delimiter{':'}; + +static void PadToken(std::string& token) { + std::size_t outlen = 0; + + std::array output{}; + std::array roundtrip{}; + for (size_t i = 0; i < 3; i++) { + mbedtls_base64_decode(output.data(), output.size(), &outlen, + reinterpret_cast(token.c_str()), + token.length()); + mbedtls_base64_encode(roundtrip.data(), roundtrip.size(), &outlen, output.data(), outlen); + if (memcmp(roundtrip.data(), token.data(), token.size()) == 0) { + break; + } + token.push_back('='); + } +} + +static std::string UsernameFromDisplayToken(const std::string& display_token) { + std::size_t outlen; + + std::array output{}; + mbedtls_base64_decode(output.data(), output.size(), &outlen, + reinterpret_cast(display_token.c_str()), + display_token.length()); + std::string decoded_display_token(reinterpret_cast(&output), outlen); + return decoded_display_token.substr(0, decoded_display_token.find(token_delimiter)); +} + +static std::string TokenFromDisplayToken(const std::string& display_token) { + std::size_t outlen; + + std::array output{}; + mbedtls_base64_decode(output.data(), output.size(), &outlen, + reinterpret_cast(display_token.c_str()), + display_token.length()); + std::string decoded_display_token(reinterpret_cast(&output), outlen); + return decoded_display_token.substr(decoded_display_token.find(token_delimiter) + 1); +} + +static Network::Room::BanList LoadBanList(const std::string& path) { + std::ifstream file; + Common::FS::OpenFileStream(file, path, std::ios_base::in); + if (!file || file.eof()) { + LOG_ERROR(Network, "Could not open ban list!"); + return {}; + } + std::string magic; + std::getline(file, magic); + if (magic != BanListMagic) { + LOG_ERROR(Network, "Ban list is not valid!"); + return {}; + } + + // false = username ban list, true = ip ban list + bool ban_list_type = false; + Network::Room::UsernameBanList username_ban_list; + Network::Room::IPBanList ip_ban_list; + while (!file.eof()) { + std::string line; + std::getline(file, line); + line.erase(std::remove(line.begin(), line.end(), '\0'), line.end()); + line = Common::StripSpaces(line); + if (line.empty()) { + // An empty line marks start of the IP ban list + ban_list_type = true; + continue; + } + if (ban_list_type) { + ip_ban_list.emplace_back(line); + } else { + username_ban_list.emplace_back(line); + } + } + + return {username_ban_list, ip_ban_list}; +} + +static void SaveBanList(const Network::Room::BanList& ban_list, const std::string& path) { + std::ofstream file; + Common::FS::OpenFileStream(file, path, std::ios_base::out); + if (!file) { + LOG_ERROR(Network, "Could not save ban list!"); + return; + } + + file << BanListMagic << "\n"; + + // Username ban list + for (const auto& username : ban_list.first) { + file << username << "\n"; + } + file << "\n"; + + // IP ban list + for (const auto& ip : ban_list.second) { + file << ip << "\n"; + } +} + +static void InitializeLogging(const std::string& log_file) { + Common::Log::Initialize(); + Common::Log::SetColorConsoleBackendEnabled(true); + Common::Log::Start(); +} + +/// Application entry point +int main(int argc, char** argv) { + Common::DetachedTasks detached_tasks; + int option_index = 0; + char* endarg; + + std::string room_name; + std::string room_description; + std::string password; + std::string preferred_game; + std::string username; + std::string token; + std::string web_api_url; + std::string ban_list_file; + std::string log_file = "sudachi-room.log"; + std::string bind_address; + u64 preferred_game_id = 0; + u32 port = Network::DefaultRoomPort; + u32 max_members = 16; + bool enable_sudachi_mods = false; + + static struct option long_options[] = { + {"room-name", required_argument, 0, 'n'}, + {"room-description", required_argument, 0, 'd'}, + {"bind-address", required_argument, 0, 's'}, + {"port", required_argument, 0, 'p'}, + {"max_members", required_argument, 0, 'm'}, + {"password", required_argument, 0, 'w'}, + {"preferred-game", required_argument, 0, 'g'}, + {"preferred-game-id", required_argument, 0, 'i'}, + {"username", optional_argument, 0, 'u'}, + {"token", required_argument, 0, 't'}, + {"web-api-url", required_argument, 0, 'a'}, + {"ban-list-file", required_argument, 0, 'b'}, + {"log-file", required_argument, 0, 'l'}, + {"enable-sudachi-mods", no_argument, 0, 'e'}, + {"help", no_argument, 0, 'h'}, + {"version", no_argument, 0, 'v'}, + {0, 0, 0, 0}, + }; + + InitializeLogging(log_file); + + while (optind < argc) { + int arg = + getopt_long(argc, argv, "n:d:s:p:m:w:g:u:t:a:i:l:hv", long_options, &option_index); + if (arg != -1) { + switch (static_cast(arg)) { + case 'n': + room_name.assign(optarg); + break; + case 'd': + room_description.assign(optarg); + break; + case 's': + bind_address.assign(optarg); + break; + case 'p': + port = strtoul(optarg, &endarg, 0); + break; + case 'm': + max_members = strtoul(optarg, &endarg, 0); + break; + case 'w': + password.assign(optarg); + break; + case 'g': + preferred_game.assign(optarg); + break; + case 'i': + preferred_game_id = strtoull(optarg, &endarg, 16); + break; + case 'u': + username.assign(optarg); + break; + case 't': + token.assign(optarg); + break; + case 'a': + web_api_url.assign(optarg); + break; + case 'b': + ban_list_file.assign(optarg); + break; + case 'l': + log_file.assign(optarg); + break; + case 'e': + enable_sudachi_mods = true; + break; + case 'h': + PrintHelp(argv[0]); + return 0; + case 'v': + PrintVersion(); + return 0; + } + } + } + + if (room_name.empty()) { + LOG_ERROR(Network, "Room name is empty!"); + PrintHelp(argv[0]); + return -1; + } + if (preferred_game.empty()) { + LOG_ERROR(Network, "Preferred game is empty!"); + PrintHelp(argv[0]); + return -1; + } + if (preferred_game_id == 0) { + LOG_ERROR(Network, + "preferred-game-id not set!\nThis should get set to allow users to find your " + "room.\nSet with --preferred-game-id id"); + } + if (max_members > Network::MaxConcurrentConnections || max_members < 2) { + LOG_ERROR(Network, "max_members needs to be in the range 2 - {}!", + Network::MaxConcurrentConnections); + PrintHelp(argv[0]); + return -1; + } + if (bind_address.empty()) { + LOG_INFO(Network, "Bind address is empty: defaulting to 0.0.0.0"); + } + if (port > UINT16_MAX) { + LOG_ERROR(Network, "Port needs to be in the range 0 - 65535!"); + PrintHelp(argv[0]); + return -1; + } + if (ban_list_file.empty()) { + LOG_ERROR(Network, "Ban list file not set!\nThis should get set to load and save room ban " + "list.\nSet with --ban-list-file "); + } + bool announce = true; + if (token.empty() && announce) { + announce = false; + LOG_INFO(Network, "Token is empty: Hosting a private room"); + } + if (web_api_url.empty() && announce) { + announce = false; + LOG_INFO(Network, "Endpoint url is empty: Hosting a private room"); + } + if (announce) { + if (username.empty()) { + LOG_INFO(Network, "Hosting a public room"); + Settings::values.web_api_url = web_api_url; + PadToken(token); + Settings::values.sudachi_username = UsernameFromDisplayToken(token); + username = Settings::values.sudachi_username.GetValue(); + Settings::values.sudachi_token = TokenFromDisplayToken(token); + } else { + LOG_INFO(Network, "Hosting a public room"); + Settings::values.web_api_url = web_api_url; + Settings::values.sudachi_username = username; + Settings::values.sudachi_token = token; + } + } + if (!announce && enable_sudachi_mods) { + enable_sudachi_mods = false; + LOG_INFO(Network, "Can not enable sudachi Moderators for private rooms"); + } + + // Load the ban list + Network::Room::BanList ban_list; + if (!ban_list_file.empty()) { + ban_list = LoadBanList(ban_list_file); + } + + std::unique_ptr verify_backend; + if (announce) { +#ifdef ENABLE_WEB_SERVICE + verify_backend = + std::make_unique(Settings::values.web_api_url.GetValue()); +#else + LOG_INFO(Network, + "sudachi Web Services is not available with this build: validation is disabled."); + verify_backend = std::make_unique(); +#endif + } else { + verify_backend = std::make_unique(); + } + + Network::RoomNetwork network{}; + network.Init(); + if (auto room = network.GetRoom().lock()) { + AnnounceMultiplayerRoom::GameInfo preferred_game_info{.name = preferred_game, + .id = preferred_game_id}; + if (!room->Create(room_name, room_description, bind_address, static_cast(port), + password, max_members, username, preferred_game_info, + std::move(verify_backend), ban_list, enable_sudachi_mods)) { + LOG_INFO(Network, "Failed to create room: "); + return -1; + } + LOG_INFO(Network, "Room is open. Close with Q+Enter..."); + auto announce_session = std::make_unique(network); + if (announce) { + announce_session->Start(); + } + while (room->GetState() == Network::Room::State::Open) { + std::string in; + std::cin >> in; + if (in.size() > 0) { + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + } + if (announce) { + announce_session->Stop(); + } + announce_session.reset(); + // Save the ban list + if (!ban_list_file.empty()) { + SaveBanList(room->GetBanList(), ban_list_file); + } + room->Destroy(); + } + network.Shutdown(); + detached_tasks.WaitForAllTasks(); + return 0; +} diff --git a/src/dedicated_room/sudachi_room.rc b/src/dedicated_room/sudachi_room.rc new file mode 100644 index 0000000..3b767fe --- /dev/null +++ b/src/dedicated_room/sudachi_room.rc @@ -0,0 +1,20 @@ +// SPDX-FileCopyrightText: 2017 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include "winresrc.h" +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +SUDACHI_ICON ICON "../../dist/sudachi.ico" + + +///////////////////////////////////////////////////////////////////////////// +// +// RT_MANIFEST +// + +0 RT_MANIFEST "../../dist/sudachi.manifest" diff --git a/src/sudachi/CMakeLists.txt b/src/sudachi/CMakeLists.txt new file mode 100644 index 0000000..a86f902 --- /dev/null +++ b/src/sudachi/CMakeLists.txt @@ -0,0 +1,480 @@ +# SPDX-FileCopyrightText: 2018 sudachi Emulator Project +# SPDX-License-Identifier: GPL-2.0-or-later + +set(CMAKE_AUTOMOC ON) +set(CMAKE_AUTORCC ON) +set(CMAKE_AUTOUIC ON) +set(CMAKE_INCLUDE_CURRENT_DIR ON) + +# Set the RPATH for Qt Libraries +# This must be done before the `sudachi` target is created +if (SUDACHI_USE_BUNDLED_QT AND (${CMAKE_SYSTEM_NAME} STREQUAL "Linux")) + set(CMAKE_BUILD_RPATH "${CMAKE_BINARY_DIR}/bin/lib/") +endif() + +add_executable(sudachi + Info.plist + about_dialog.cpp + about_dialog.h + aboutdialog.ui + applets/qt_amiibo_settings.cpp + applets/qt_amiibo_settings.h + applets/qt_amiibo_settings.ui + applets/qt_controller.cpp + applets/qt_controller.h + applets/qt_controller.ui + applets/qt_error.cpp + applets/qt_error.h + applets/qt_profile_select.cpp + applets/qt_profile_select.h + applets/qt_software_keyboard.cpp + applets/qt_software_keyboard.h + applets/qt_software_keyboard.ui + applets/qt_web_browser.cpp + applets/qt_web_browser.h + applets/qt_web_browser_scripts.h + bootmanager.cpp + bootmanager.h + compatdb.ui + compatibility_list.cpp + compatibility_list.h + configuration/configuration_shared.cpp + configuration/configuration_shared.h + configuration/configure.ui + configuration/configure_applets.cpp + configuration/configure_applets.h + configuration/configure_applets.ui + configuration/configure_audio.cpp + configuration/configure_audio.h + configuration/configure_audio.ui + configuration/configure_camera.cpp + configuration/configure_camera.h + configuration/configure_camera.ui + configuration/configure_cpu.cpp + configuration/configure_cpu.h + configuration/configure_cpu.ui + configuration/configure_cpu_debug.cpp + configuration/configure_cpu_debug.h + configuration/configure_cpu_debug.ui + configuration/configure_debug.cpp + configuration/configure_debug.h + configuration/configure_debug.ui + configuration/configure_debug_controller.cpp + configuration/configure_debug_controller.h + configuration/configure_debug_controller.ui + configuration/configure_debug_tab.cpp + configuration/configure_debug_tab.h + configuration/configure_debug_tab.ui + configuration/configure_dialog.cpp + configuration/configure_dialog.h + configuration/configure_filesystem.cpp + configuration/configure_filesystem.h + configuration/configure_filesystem.ui + configuration/configure_general.cpp + configuration/configure_general.h + configuration/configure_general.ui + configuration/configure_graphics.cpp + configuration/configure_graphics.h + configuration/configure_graphics.ui + configuration/configure_graphics_advanced.cpp + configuration/configure_graphics_advanced.h + configuration/configure_graphics_advanced.ui + configuration/configure_hotkeys.cpp + configuration/configure_hotkeys.h + configuration/configure_hotkeys.ui + configuration/configure_input.cpp + configuration/configure_input.h + configuration/configure_input.ui + configuration/configure_input_advanced.cpp + configuration/configure_input_advanced.h + configuration/configure_input_advanced.ui + configuration/configure_input_per_game.cpp + configuration/configure_input_per_game.h + configuration/configure_input_per_game.ui + configuration/configure_input_player.cpp + configuration/configure_input_player.h + configuration/configure_input_player.ui + configuration/configure_input_player_widget.cpp + configuration/configure_input_player_widget.h + configuration/configure_input_profile_dialog.cpp + configuration/configure_input_profile_dialog.h + configuration/configure_input_profile_dialog.ui + configuration/configure_linux_tab.cpp + configuration/configure_linux_tab.h + configuration/configure_linux_tab.ui + configuration/configure_mouse_panning.cpp + configuration/configure_mouse_panning.h + configuration/configure_mouse_panning.ui + configuration/configure_motion_touch.cpp + configuration/configure_motion_touch.h + configuration/configure_motion_touch.ui + configuration/configure_per_game.cpp + configuration/configure_per_game.h + configuration/configure_per_game.ui + configuration/configure_per_game_addons.cpp + configuration/configure_per_game_addons.h + configuration/configure_per_game_addons.ui + configuration/configure_profile_manager.cpp + configuration/configure_profile_manager.h + configuration/configure_profile_manager.ui + configuration/configure_ringcon.cpp + configuration/configure_ringcon.h + configuration/configure_ringcon.ui + configuration/configure_network.cpp + configuration/configure_network.h + configuration/configure_network.ui + configuration/configure_system.cpp + configuration/configure_system.h + configuration/configure_system.ui + configuration/configure_tas.cpp + configuration/configure_tas.h + configuration/configure_tas.ui + configuration/configure_touch_from_button.cpp + configuration/configure_touch_from_button.h + configuration/configure_touch_from_button.ui + configuration/configure_touchscreen_advanced.cpp + configuration/configure_touchscreen_advanced.h + configuration/configure_touchscreen_advanced.ui + configuration/configure_touch_widget.h + configuration/configure_ui.cpp + configuration/configure_ui.h + configuration/configure_ui.ui + configuration/configure_vibration.cpp + configuration/configure_vibration.h + configuration/configure_vibration.ui + configuration/configure_web.cpp + configuration/configure_web.h + configuration/configure_web.ui + configuration/input_profiles.cpp + configuration/input_profiles.h + configuration/shared_translation.cpp + configuration/shared_translation.h + configuration/shared_widget.cpp + configuration/shared_widget.h + configuration/qt_config.cpp + configuration/qt_config.h + debugger/console.cpp + debugger/console.h + debugger/controller.cpp + debugger/controller.h + debugger/profiler.cpp + debugger/profiler.h + debugger/wait_tree.cpp + debugger/wait_tree.h + discord.h + game_list.cpp + game_list.h + game_list_p.h + game_list_worker.cpp + game_list_worker.h + hotkeys.cpp + hotkeys.h + install_dialog.cpp + install_dialog.h + loading_screen.cpp + loading_screen.h + loading_screen.ui + main.cpp + main.h + main.ui + multiplayer/chat_room.cpp + multiplayer/chat_room.h + multiplayer/chat_room.ui + multiplayer/client_room.h + multiplayer/client_room.cpp + multiplayer/client_room.ui + multiplayer/direct_connect.cpp + multiplayer/direct_connect.h + multiplayer/direct_connect.ui + multiplayer/host_room.cpp + multiplayer/host_room.h + multiplayer/host_room.ui + multiplayer/lobby.cpp + multiplayer/lobby.h + multiplayer/lobby.ui + multiplayer/lobby_p.h + multiplayer/message.cpp + multiplayer/message.h + multiplayer/moderation_dialog.cpp + multiplayer/moderation_dialog.h + multiplayer/moderation_dialog.ui + multiplayer/state.cpp + multiplayer/state.h + multiplayer/validation.h + play_time_manager.cpp + play_time_manager.h + precompiled_headers.h + qt_common.cpp + qt_common.h + startup_checks.cpp + startup_checks.h + uisettings.cpp + uisettings.h + util/clickable_label.cpp + util/clickable_label.h + util/controller_navigation.cpp + util/controller_navigation.h + util/limitable_input_dialog.cpp + util/limitable_input_dialog.h + util/overlay_dialog.cpp + util/overlay_dialog.h + util/overlay_dialog.ui + util/sequence_dialog/sequence_dialog.cpp + util/sequence_dialog/sequence_dialog.h + util/url_request_interceptor.cpp + util/url_request_interceptor.h + util/util.cpp + util/util.h + vk_device_info.cpp + vk_device_info.h + compatdb.cpp + compatdb.h + sudachi.qrc + sudachi.rc +) + +if (SUDACHI_CRASH_DUMPS) + target_sources(sudachi PRIVATE + breakpad.cpp + breakpad.h + ) + + target_link_libraries(sudachi PRIVATE libbreakpad_client) + target_compile_definitions(sudachi PRIVATE SUDACHI_CRASH_DUMPS) +endif() + +if (CMAKE_CXX_COMPILER_ID STREQUAL "Clang") + target_compile_definitions(sudachi PRIVATE + $<$,15>:CANNOT_EXPLICITLY_INSTANTIATE> + ) +endif() + +file(GLOB COMPAT_LIST + ${PROJECT_BINARY_DIR}/dist/compatibility_list/compatibility_list.qrc + ${PROJECT_BINARY_DIR}/dist/compatibility_list/compatibility_list.json) +file(GLOB_RECURSE ICONS ${PROJECT_SOURCE_DIR}/dist/icons/*) +file(GLOB_RECURSE THEMES ${PROJECT_SOURCE_DIR}/dist/qt_themes/*) + +if (ENABLE_QT_TRANSLATION) + set(SUDACHI_QT_LANGUAGES "${PROJECT_SOURCE_DIR}/dist/languages" CACHE PATH "Path to the translation bundle for the Qt frontend") + option(GENERATE_QT_TRANSLATION "Generate en.ts as the translation source file" OFF) + option(WORKAROUND_BROKEN_LUPDATE "Run lupdate directly through CMake if Qt's convenience wrappers don't work" OFF) + + # Update source TS file if enabled + if (GENERATE_QT_TRANSLATION) + get_target_property(SRCS sudachi SOURCES) + # these calls to qt_create_translation also creates a rule to generate en.qm which conflicts with providing english plurals + # so we have to set a OUTPUT_LOCATION so that we don't have multiple rules to generate en.qm + set_source_files_properties(${SUDACHI_QT_LANGUAGES}/en.ts PROPERTIES OUTPUT_LOCATION "${CMAKE_CURRENT_BINARY_DIR}/translations") + if (WORKAROUND_BROKEN_LUPDATE) + add_custom_command(OUTPUT ${SUDACHI_QT_LANGUAGES}/en.ts + COMMAND lupdate + -source-language en_US + -target-language en_US + ${SRCS} + ${UIS} + -ts ${SUDACHI_QT_LANGUAGES}/en.ts + DEPENDS + ${SRCS} + ${UIS} + WORKING_DIRECTORY + ${CMAKE_CURRENT_SOURCE_DIR} + ) + else() + qt_create_translation(QM_FILES + ${SRCS} + ${UIS} + ${SUDACHI_QT_LANGUAGES}/en.ts + OPTIONS + -source-language en_US + -target-language en_US + ) + endif() + + # Generate plurals into dist/english_plurals/generated_en.ts so it can be used to revise dist/english_plurals/en.ts + set(GENERATED_PLURALS_FILE ${PROJECT_SOURCE_DIR}/dist/english_plurals/generated_en.ts) + set_source_files_properties(${GENERATED_PLURALS_FILE} PROPERTIES OUTPUT_LOCATION "${CMAKE_CURRENT_BINARY_DIR}/plurals") + if (WORKAROUND_BROKEN_LUPDATE) + add_custom_command(OUTPUT ${GENERATED_PLURALS_FILE} + COMMAND lupdate + -source-language en_US + -target-language en_US + ${SRCS} + ${UIS} + -ts ${GENERATED_PLURALS_FILE} + DEPENDS + ${SRCS} + ${UIS} + WORKING_DIRECTORY + ${CMAKE_CURRENT_SOURCE_DIR} + ) + else() + qt_create_translation(QM_FILES ${SRCS} ${UIS} ${GENERATED_PLURALS_FILE} OPTIONS -pluralonly -source-language en_US -target-language en_US) + endif() + + add_custom_target(translation ALL DEPENDS ${SUDACHI_QT_LANGUAGES}/en.ts ${GENERATED_PLURALS_FILE}) + endif() + + # Find all TS files except en.ts + file(GLOB_RECURSE LANGUAGES_TS ${SUDACHI_QT_LANGUAGES}/*.ts) + list(REMOVE_ITEM LANGUAGES_TS ${SUDACHI_QT_LANGUAGES}/en.ts) + + # Compile TS files to QM files + qt_add_translation(LANGUAGES_QM ${LANGUAGES_TS}) + + # Compile english plurals TS file to en.qm + qt_add_translation(LANGUAGES_QM ${PROJECT_SOURCE_DIR}/dist/english_plurals/en.ts) + + # Build a QRC file from the QM file list + set(LANGUAGES_QRC ${CMAKE_CURRENT_BINARY_DIR}/languages.qrc) + file(WRITE ${LANGUAGES_QRC} "\n") + foreach (QM ${LANGUAGES_QM}) + get_filename_component(QM_FILE ${QM} NAME) + file(APPEND ${LANGUAGES_QRC} "${QM_FILE}\n") + endforeach (QM) + file(APPEND ${LANGUAGES_QRC} "") + + # Add the QRC file to package in all QM files + qt_add_resources(LANGUAGES ${LANGUAGES_QRC}) +else() + set(LANGUAGES) +endif() + +target_sources(sudachi + PRIVATE + ${COMPAT_LIST} + ${ICONS} + ${LANGUAGES} + ${THEMES} +) + +if (APPLE) + set(MACOSX_ICON "../../dist/sudachi.icns") + set_source_files_properties(${MACOSX_ICON} PROPERTIES MACOSX_PACKAGE_LOCATION Resources) + target_sources(sudachi PRIVATE ${MACOSX_ICON}) + set_target_properties(sudachi PROPERTIES MACOSX_BUNDLE TRUE) + set_target_properties(sudachi PROPERTIES MACOSX_BUNDLE_INFO_PLIST ${CMAKE_CURRENT_SOURCE_DIR}/Info.plist) + + if (NOT USE_SYSTEM_MOLTENVK) + set(MOLTENVK_PLATFORM "macOS") + set(MOLTENVK_VERSION "v1.2.7") + download_moltenvk_external(${MOLTENVK_PLATFORM} ${MOLTENVK_VERSION}) + endif() + find_library(MOLTENVK_LIBRARY MoltenVK REQUIRED) + message(STATUS "Using MoltenVK at ${MOLTENVK_LIBRARY}.") + set_source_files_properties(${MOLTENVK_LIBRARY} PROPERTIES MACOSX_PACKAGE_LOCATION Frameworks + XCODE_FILE_ATTRIBUTES "CodeSignOnCopy") + target_sources(sudachi PRIVATE ${MOLTENVK_LIBRARY}) + +elseif(WIN32) + # compile as a win32 gui application instead of a console application + if (QT_VERSION VERSION_GREATER_EQUAL 6) + target_link_libraries(sudachi PRIVATE Qt6::EntryPointPrivate) + else() + target_link_libraries(sudachi PRIVATE Qt5::WinMain) + endif() + if(MSVC) + target_link_libraries(sudachi PRIVATE version.lib) + set_target_properties(sudachi PROPERTIES LINK_FLAGS_RELEASE "/SUBSYSTEM:WINDOWS") + elseif(MINGW) + set_target_properties(sudachi PROPERTIES LINK_FLAGS_RELEASE "-Wl,--subsystem,windows") + endif() +endif() + +target_link_libraries(sudachi PRIVATE common core input_common frontend_common network video_core) +target_link_libraries(sudachi PRIVATE Boost::headers glad Qt${QT_MAJOR_VERSION}::Widgets) +target_link_libraries(sudachi PRIVATE ${PLATFORM_LIBRARIES} Threads::Threads) + +target_link_libraries(sudachi PRIVATE Vulkan::Headers) +if (NOT WIN32) + target_include_directories(sudachi PRIVATE ${Qt${QT_MAJOR_VERSION}Gui_PRIVATE_INCLUDE_DIRS}) +endif() +if (UNIX AND NOT APPLE) + target_link_libraries(sudachi PRIVATE Qt${QT_MAJOR_VERSION}::DBus) +endif() + +target_compile_definitions(sudachi PRIVATE + # Use QStringBuilder for string concatenation to reduce + # the overall number of temporary strings created. + -DQT_USE_QSTRINGBUILDER + + # Disable implicit conversions from/to C strings + -DQT_NO_CAST_FROM_ASCII + -DQT_NO_CAST_TO_ASCII + + # Disable implicit type narrowing in signal/slot connect() calls. + -DQT_NO_NARROWING_CONVERSIONS_IN_CONNECT + + # Disable unsafe overloads of QProcess' start() function. + -DQT_NO_PROCESS_COMBINED_ARGUMENT_START + + # Disable implicit QString->QUrl conversions to enforce use of proper resolving functions. + -DQT_NO_URL_CAST_FROM_STRING +) + +if (SUDACHI_ENABLE_COMPATIBILITY_REPORTING) + target_compile_definitions(sudachi PRIVATE -DSUDACHI_ENABLE_COMPATIBILITY_REPORTING) +endif() + +if (USE_DISCORD_PRESENCE) + target_sources(sudachi PUBLIC + discord_impl.cpp + discord_impl.h + ) + target_link_libraries(sudachi PRIVATE DiscordRPC::discord-rpc httplib::httplib Qt${QT_MAJOR_VERSION}::Network) + target_compile_definitions(sudachi PRIVATE -DUSE_DISCORD_PRESENCE) +endif() + +if (ENABLE_WEB_SERVICE) + target_compile_definitions(sudachi PRIVATE -DENABLE_WEB_SERVICE) +endif() + +if (SUDACHI_USE_QT_MULTIMEDIA) + target_link_libraries(sudachi PRIVATE Qt${QT_MAJOR_VERSION}::Multimedia) + target_compile_definitions(sudachi PRIVATE -DSUDACHI_USE_QT_MULTIMEDIA) +endif () + +if (SUDACHI_USE_QT_WEB_ENGINE) + target_link_libraries(sudachi PRIVATE Qt${QT_MAJOR_VERSION}::WebEngineCore Qt${QT_MAJOR_VERSION}::WebEngineWidgets) + target_compile_definitions(sudachi PRIVATE -DSUDACHI_USE_QT_WEB_ENGINE) +endif () + +if(UNIX AND NOT APPLE) + install(TARGETS sudachi) +endif() + +if (WIN32 AND QT_VERSION VERSION_GREATER_EQUAL 6) + set(SUDACHI_EXE_DIR "$") + add_custom_command(TARGET sudachi POST_BUILD COMMAND ${WINDEPLOYQT_EXECUTABLE} "${SUDACHI_EXE_DIR}/sudachi.exe" --dir "${SUDACHI_EXE_DIR}" --libdir "${SUDACHI_EXE_DIR}" --plugindir "${SUDACHI_EXE_DIR}/plugins" --no-compiler-runtime --no-opengl-sw --no-system-d3d-compiler --no-translations --verbose 0) +endif() + +if (SUDACHI_USE_BUNDLED_QT AND QT_VERSION VERSION_LESS 6) + include(CopySudachiQt5Deps) + copy_sudachi_Qt5_deps(sudachi) +endif() + +if (ENABLE_SDL2) + target_link_libraries(sudachi PRIVATE SDL2::SDL2) + target_compile_definitions(sudachi PRIVATE HAVE_SDL2) +endif() + +if (MSVC) + include(CopySudachiSDLDeps) + include(CopySudachiFFmpegDeps) + copy_sudachi_SDL_deps(sudachi) + copy_sudachi_FFmpeg_deps(sudachi) +endif() + +if (NOT APPLE AND ENABLE_OPENGL) + target_compile_definitions(sudachi PRIVATE HAS_OPENGL) +endif() + +if (ARCHITECTURE_x86_64 OR ARCHITECTURE_arm64) + target_link_libraries(sudachi PRIVATE dynarmic::dynarmic) +endif() + +if (SUDACHI_USE_PRECOMPILED_HEADERS) + target_precompile_headers(sudachi PRIVATE precompiled_headers.h) +endif() + +create_target_directory_groups(sudachi) diff --git a/src/sudachi/Info.plist b/src/sudachi/Info.plist new file mode 100644 index 0000000..faa668f --- /dev/null +++ b/src/sudachi/Info.plist @@ -0,0 +1,48 @@ + + + + + + + + CFBundleDevelopmentRegion + English + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleGetInfoString + + CFBundleIconFile + sudachi.icns + CFBundleIdentifier + com.sudachi-emu.sudachi + CFBundleInfoDictionaryVersion + 6.0 + CFBundleLongVersionString + + CFBundleName + sudachi + CFBundlePackageType + APPL + CFBundleShortVersionString + + CFBundleSignature + ???? + CFBundleVersion + + CSResourcesFileMapped + + LSApplicationCategoryType + public.app-category.games + LSRequiresCarbon + + NSHumanReadableCopyright + + NSPrincipalClass + NSApplication + NSHighResolutionCapable + True + + diff --git a/src/sudachi/about_dialog.cpp b/src/sudachi/about_dialog.cpp new file mode 100644 index 0000000..805b94b --- /dev/null +++ b/src/sudachi/about_dialog.cpp @@ -0,0 +1,32 @@ +// SPDX-FileCopyrightText: Copyright 2018 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include +#include "common/scm_rev.h" +#include "ui_aboutdialog.h" +#include "sudachi/about_dialog.h" + +AboutDialog::AboutDialog(QWidget* parent) + : QDialog(parent), ui{std::make_unique()} { + const auto branch_name = std::string(Common::g_scm_branch); + const auto description = std::string(Common::g_scm_desc); + const auto build_id = std::string(Common::g_build_id); + + const auto sudachi_build = fmt::format("Sudachi Development Build | {}-{}", branch_name, description); + const auto override_build = + fmt::format(fmt::runtime(std::string(Common::g_title_bar_format_idle)), build_id); + const auto& sudachi_build_version = override_build.empty() ? sudachi_build : override_build; + + ui->setupUi(this); + // Try and request the icon from Qt theme (Linux?) + const QIcon sudachi_logo = QIcon::fromTheme(QStringLiteral("org.sudachi_emu.sudachi")); + if (!sudachi_logo.isNull()) { + ui->labelLogo->setPixmap(sudachi_logo.pixmap(200)); + } + ui->labelBuildInfo->setText( + ui->labelBuildInfo->text().arg(QString::fromStdString(sudachi_build_version), + QString::fromUtf8(Common::g_build_date).left(10))); +} + +AboutDialog::~AboutDialog() = default; diff --git a/src/sudachi/about_dialog.h b/src/sudachi/about_dialog.h new file mode 100644 index 0000000..06841b6 --- /dev/null +++ b/src/sudachi/about_dialog.h @@ -0,0 +1,22 @@ +// SPDX-FileCopyrightText: Copyright 2018 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include + +namespace Ui { +class AboutDialog; +} + +class AboutDialog : public QDialog { + Q_OBJECT + +public: + explicit AboutDialog(QWidget* parent); + ~AboutDialog() override; + +private: + std::unique_ptr ui; +}; diff --git a/src/sudachi/aboutdialog.ui b/src/sudachi/aboutdialog.ui new file mode 100644 index 0000000..0f962be --- /dev/null +++ b/src/sudachi/aboutdialog.ui @@ -0,0 +1,204 @@ + + + AboutDialog + + + + 0 + 0 + 616 + 294 + + + + About sudachi + + + + + + + + + + + 0 + 0 + + + + + 200 + 200 + + + + + + + :/icons/default/256x256/sudachi.png + + + true + + + + + + + Qt::Orientation::Vertical + + + + 20 + 40 + + + + + + + + + + + + + 0 + 0 + + + + <html><head/><body><p><span style=" font-size:28pt;">sudachi</span></p></body></html> + + + + + + + + 0 + 0 + + + + <html><head/><body><p>%1 (%2)</p></body></html> + + + + + + + + 0 + 0 + + + + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Ubuntu'; font-size:11pt; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:12pt;">sudachi is an experimental open-source emulator for the Nintendo Switch licensed under GPLv3.0+.</span></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'MS Shell Dlg 2'; font-size:8pt;"><br /></p> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:12pt;">This software should not be used to play games you have not legally obtained.</span></p></body></html> + + + Qt::AlignmentFlag::AlignLeading|Qt::AlignmentFlag::AlignLeft|Qt::AlignmentFlag::AlignVCenter + + + true + + + + + + + Qt::Orientation::Vertical + + + + 20 + 40 + + + + + + + + <html><head/><body><p><a href="https://sudachi-emu.org/"><span style=" text-decoration: underline; color:#039be5;">Website</span></a> | <a href="https://github.com/sudachi-emu"><span style=" text-decoration: underline; color:#039be5;">Source Code</span></a> | <a href="https://github.com/sudachi-emu/sudachi/graphs/contributors"><span style=" text-decoration: underline; color:#039be5;">Contributors</span></a> | <a href="https://github.com/sudachi-emu/sudachi/blob/master/LICENSE.txt"><span style=" text-decoration: underline; color:#039be5;">License</span></a></p></body></html> + + + true + + + + + + + + 0 + 0 + + + + <html><head/><body><p><span style=" font-size:7pt;">&quot;Nintendo Switch&quot; is a trademark of Nintendo. sudachi is not affiliated with Nintendo in any way.</span></p></body></html> + + + + + + + + + + + Qt::Orientation::Horizontal + + + QDialogButtonBox::StandardButton::Ok + + + + + + + + + + + + buttonBox + accepted() + AboutDialog + accept() + + + 20 + 20 + + + 20 + 20 + + + + + buttonBox + rejected() + AboutDialog + reject() + + + 20 + 20 + + + 20 + 20 + + + + + diff --git a/src/sudachi/applets/qt_amiibo_settings.cpp b/src/sudachi/applets/qt_amiibo_settings.cpp new file mode 100644 index 0000000..76d5b68 --- /dev/null +++ b/src/sudachi/applets/qt_amiibo_settings.cpp @@ -0,0 +1,274 @@ +// SPDX-FileCopyrightText: Copyright 2022 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include +#include +#include + +#include "common/assert.h" +#include "common/string_util.h" +#include "core/hle/service/nfc/common/device.h" +#include "core/hle/service/nfp/nfp_result.h" +#include "input_common/drivers/virtual_amiibo.h" +#include "input_common/main.h" +#include "ui_qt_amiibo_settings.h" +#ifdef ENABLE_WEB_SERVICE +#include "web_service/web_backend.h" +#endif +#include "sudachi/applets/qt_amiibo_settings.h" +#include "sudachi/main.h" + +QtAmiiboSettingsDialog::QtAmiiboSettingsDialog(QWidget* parent, + Core::Frontend::CabinetParameters parameters_, + InputCommon::InputSubsystem* input_subsystem_, + std::shared_ptr nfp_device_) + : QDialog(parent), ui(std::make_unique()), + input_subsystem{input_subsystem_}, nfp_device{std::move(nfp_device_)}, + parameters(std::move(parameters_)) { + ui->setupUi(this); + + LoadInfo(); + + resize(0, 0); +} + +QtAmiiboSettingsDialog::~QtAmiiboSettingsDialog() = default; + +int QtAmiiboSettingsDialog::exec() { + if (!is_initialized) { + return QDialog::Rejected; + } + return QDialog::exec(); +} + +std::string QtAmiiboSettingsDialog::GetName() const { + return ui->amiiboCustomNameValue->text().toStdString(); +} + +void QtAmiiboSettingsDialog::LoadInfo() { + if (input_subsystem->GetVirtualAmiibo()->ReloadAmiibo() != + InputCommon::VirtualAmiibo::Info::Success) { + return; + } + + if (nfp_device->GetCurrentState() != Service::NFC::DeviceState::TagFound && + nfp_device->GetCurrentState() != Service::NFC::DeviceState::TagMounted) { + return; + } + nfp_device->Mount(Service::NFP::ModelType::Amiibo, Service::NFP::MountTarget::All); + + LoadAmiiboInfo(); + LoadAmiiboData(); + LoadAmiiboGameInfo(); + + ui->amiiboDirectoryValue->setText( + QString::fromStdString(input_subsystem->GetVirtualAmiibo()->GetLastFilePath())); + + SetSettingsDescription(); + is_initialized = true; +} + +void QtAmiiboSettingsDialog::LoadAmiiboInfo() { + Service::NFP::ModelInfo model_info{}; + const auto model_result = nfp_device->GetModelInfo(model_info); + + if (model_result.IsFailure()) { + ui->amiiboImageLabel->setVisible(false); + ui->amiiboInfoGroup->setVisible(false); + return; + } + + const auto amiibo_id = + fmt::format("{:04x}{:02x}{:02x}{:04x}{:02x}02", Common::swap16(model_info.character_id), + model_info.character_variant, model_info.amiibo_type, model_info.model_number, + model_info.series); + + LOG_DEBUG(Frontend, "Loading amiibo id {}", amiibo_id); + // Note: This function is not being used until we host the images on our server + // LoadAmiiboApiInfo(amiibo_id); + ui->amiiboImageLabel->setVisible(false); + ui->amiiboInfoGroup->setVisible(false); +} + +void QtAmiiboSettingsDialog::LoadAmiiboApiInfo(std::string_view amiibo_id) { +#ifdef ENABLE_WEB_SERVICE + // TODO: Host this data on our website + WebService::Client client{"https://amiiboapi.com", {}, {}}; + WebService::Client image_client{"https://raw.githubusercontent.com", {}, {}}; + const auto url_path = fmt::format("/api/amiibo/?id={}", amiibo_id); + + const auto amiibo_json = client.GetJson(url_path, true).returned_data; + if (amiibo_json.empty()) { + ui->amiiboImageLabel->setVisible(false); + ui->amiiboInfoGroup->setVisible(false); + return; + } + + std::string amiibo_series{}; + std::string amiibo_name{}; + std::string amiibo_image_url{}; + std::string amiibo_type{}; + + const auto parsed_amiibo_json_json = nlohmann::json::parse(amiibo_json).at("amiibo"); + parsed_amiibo_json_json.at("amiiboSeries").get_to(amiibo_series); + parsed_amiibo_json_json.at("name").get_to(amiibo_name); + parsed_amiibo_json_json.at("image").get_to(amiibo_image_url); + parsed_amiibo_json_json.at("type").get_to(amiibo_type); + + ui->amiiboSeriesValue->setText(QString::fromStdString(amiibo_series)); + ui->amiiboNameValue->setText(QString::fromStdString(amiibo_name)); + ui->amiiboTypeValue->setText(QString::fromStdString(amiibo_type)); + + if (amiibo_image_url.size() < 34) { + ui->amiiboImageLabel->setVisible(false); + } + + const auto image_url_path = amiibo_image_url.substr(34, amiibo_image_url.size() - 34); + const auto image_data = image_client.GetImage(image_url_path, true).returned_data; + + if (image_data.empty()) { + ui->amiiboImageLabel->setVisible(false); + } + + QPixmap pixmap; + pixmap.loadFromData(reinterpret_cast(image_data.data()), + static_cast(image_data.size())); + pixmap = pixmap.scaled(250, 350, Qt::AspectRatioMode::KeepAspectRatio, + Qt::TransformationMode::SmoothTransformation); + ui->amiiboImageLabel->setPixmap(pixmap); +#endif +} + +void QtAmiiboSettingsDialog::LoadAmiiboData() { + Service::NFP::RegisterInfo register_info{}; + Service::NFP::CommonInfo common_info{}; + const auto register_result = nfp_device->GetRegisterInfo(register_info); + const auto common_result = nfp_device->GetCommonInfo(common_info); + + if (register_result.IsFailure()) { + ui->creationDateValue->setDisabled(true); + ui->modificationDateValue->setDisabled(true); + ui->amiiboCustomNameValue->setReadOnly(false); + ui->amiiboOwnerValue->setReadOnly(false); + return; + } + + if (parameters.mode == Service::NFP::CabinetMode::StartNicknameAndOwnerSettings) { + ui->creationDateValue->setDisabled(true); + ui->modificationDateValue->setDisabled(true); + } + + const auto amiibo_name = std::string(register_info.amiibo_name.data()); + const auto owner_name = + Common::UTF16ToUTF8(register_info.mii_char_info.GetNickname().data.data()); + const auto creation_date = + QDate(register_info.creation_date.year, register_info.creation_date.month, + register_info.creation_date.day); + + ui->amiiboCustomNameValue->setText(QString::fromStdString(amiibo_name)); + ui->amiiboOwnerValue->setText(QString::fromStdString(owner_name)); + ui->amiiboCustomNameValue->setReadOnly(true); + ui->amiiboOwnerValue->setReadOnly(true); + ui->creationDateValue->setDate(creation_date); + + if (common_result.IsFailure()) { + ui->modificationDateValue->setDisabled(true); + return; + } + + const auto modification_date = + QDate(common_info.last_write_date.year, common_info.last_write_date.month, + common_info.last_write_date.day); + ui->modificationDateValue->setDate(modification_date); +} + +void QtAmiiboSettingsDialog::LoadAmiiboGameInfo() { + u32 application_area_id{}; + const auto application_result = nfp_device->GetApplicationAreaId(application_area_id); + + if (application_result.IsFailure()) { + ui->gameIdValue->setVisible(false); + ui->gameIdLabel->setText(tr("No game data present")); + return; + } + + SetGameDataName(application_area_id); +} + +void QtAmiiboSettingsDialog::SetGameDataName(u32 application_area_id) { + static constexpr std::array, 12> game_name_list = { + // 3ds, wii u + std::pair{0x10110E00, "Super Smash Bros (3DS/WiiU)"}, + {0x00132600, "Mario & Luigi: Paper Jam"}, + {0x0014F000, "Animal Crossing: Happy Home Designer"}, + {0x00152600, "Chibi-Robo!: Zip Lash"}, + {0x10161f00, "Mario Party 10"}, + {0x1019C800, "The Legend of Zelda: Twilight Princess HD"}, + // switch + {0x10162B00, "Splatoon 2"}, + {0x1016e100, "Shovel Knight: Treasure Trove"}, + {0x1019C800, "The Legend of Zelda: Breath of the Wild"}, + {0x34F80200, "Super Smash Bros. Ultimate"}, + {0x38600500, "Splatoon 3"}, + {0x3B440400, "The Legend of Zelda: Link's Awakening"}, + }; + + for (const auto& [game_id, game_name] : game_name_list) { + if (application_area_id == game_id) { + ui->gameIdValue->setText(QString::fromStdString(game_name)); + return; + } + } + + const auto application_area_string = fmt::format("{:016x}", application_area_id); + ui->gameIdValue->setText(QString::fromStdString(application_area_string)); +} + +void QtAmiiboSettingsDialog::SetSettingsDescription() { + switch (parameters.mode) { + case Service::NFP::CabinetMode::StartFormatter: + ui->cabinetActionDescriptionLabel->setText( + tr("The following amiibo data will be formatted:")); + break; + case Service::NFP::CabinetMode::StartGameDataEraser: + ui->cabinetActionDescriptionLabel->setText(tr("The following game data will removed:")); + break; + case Service::NFP::CabinetMode::StartNicknameAndOwnerSettings: + ui->cabinetActionDescriptionLabel->setText(tr("Set nickname and owner:")); + break; + case Service::NFP::CabinetMode::StartRestorer: + ui->cabinetActionDescriptionLabel->setText(tr("Do you wish to restore this amiibo?")); + break; + } +} + +QtAmiiboSettings::QtAmiiboSettings(GMainWindow& parent) { + connect(this, &QtAmiiboSettings::MainWindowShowAmiiboSettings, &parent, + &GMainWindow::AmiiboSettingsShowDialog, Qt::QueuedConnection); + connect(this, &QtAmiiboSettings::MainWindowRequestExit, &parent, + &GMainWindow::AmiiboSettingsRequestExit, Qt::QueuedConnection); + connect(&parent, &GMainWindow::AmiiboSettingsFinished, this, + &QtAmiiboSettings::MainWindowFinished, Qt::QueuedConnection); +} + +QtAmiiboSettings::~QtAmiiboSettings() = default; + +void QtAmiiboSettings::Close() const { + callback = {}; + emit MainWindowRequestExit(); +} + +void QtAmiiboSettings::ShowCabinetApplet( + const Core::Frontend::CabinetCallback& callback_, + const Core::Frontend::CabinetParameters& parameters, + std::shared_ptr nfp_device) const { + callback = std::move(callback_); + emit MainWindowShowAmiiboSettings(parameters, nfp_device); +} + +void QtAmiiboSettings::MainWindowFinished(bool is_success, const std::string& name) { + if (callback) { + callback(is_success, name); + } +} diff --git a/src/sudachi/applets/qt_amiibo_settings.h b/src/sudachi/applets/qt_amiibo_settings.h new file mode 100644 index 0000000..e0e2764 --- /dev/null +++ b/src/sudachi/applets/qt_amiibo_settings.h @@ -0,0 +1,85 @@ +// SPDX-FileCopyrightText: Copyright 2022 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include +#include +#include "core/frontend/applets/cabinet.h" + +class GMainWindow; +class QCheckBox; +class QComboBox; +class QDialogButtonBox; +class QGroupBox; +class QLabel; + +namespace InputCommon { +class InputSubsystem; +} + +namespace Ui { +class QtAmiiboSettingsDialog; +} + +namespace Service::NFC { +class NfcDevice; +} // namespace Service::NFC + +class QtAmiiboSettingsDialog final : public QDialog { + Q_OBJECT + +public: + explicit QtAmiiboSettingsDialog(QWidget* parent, Core::Frontend::CabinetParameters parameters_, + InputCommon::InputSubsystem* input_subsystem_, + std::shared_ptr nfp_device_); + ~QtAmiiboSettingsDialog() override; + + int exec() override; + + std::string GetName() const; + +private: + void LoadInfo(); + void LoadAmiiboInfo(); + void LoadAmiiboApiInfo(std::string_view amiibo_id); + void LoadAmiiboData(); + void LoadAmiiboGameInfo(); + void SetGameDataName(u32 application_area_id); + void SetSettingsDescription(); + + std::unique_ptr ui; + + InputCommon::InputSubsystem* input_subsystem; + std::shared_ptr nfp_device; + + // Parameters sent in from the backend HLE applet. + Core::Frontend::CabinetParameters parameters; + + // If false amiibo settings failed to load + bool is_initialized{}; +}; + +class QtAmiiboSettings final : public QObject, public Core::Frontend::CabinetApplet { + Q_OBJECT + +public: + explicit QtAmiiboSettings(GMainWindow& parent); + ~QtAmiiboSettings() override; + + void Close() const override; + void ShowCabinetApplet(const Core::Frontend::CabinetCallback& callback_, + const Core::Frontend::CabinetParameters& parameters, + std::shared_ptr nfp_device) const override; + +signals: + void MainWindowShowAmiiboSettings(const Core::Frontend::CabinetParameters& parameters, + std::shared_ptr nfp_device) const; + void MainWindowRequestExit() const; + +private: + void MainWindowFinished(bool is_success, const std::string& name); + + mutable Core::Frontend::CabinetCallback callback; +}; diff --git a/src/sudachi/applets/qt_amiibo_settings.ui b/src/sudachi/applets/qt_amiibo_settings.ui new file mode 100644 index 0000000..f377a6e --- /dev/null +++ b/src/sudachi/applets/qt_amiibo_settings.ui @@ -0,0 +1,494 @@ + + + QtAmiiboSettingsDialog + + + + 0 + 0 + 839 + 500 + + + + Amiibo Settings + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 10 + + + 20 + + + 15 + + + 0 + + + 15 + + + + + + 12 + 75 + true + + + + + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter + + + false + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + 20 + + + 15 + + + 15 + + + + + + 250 + 350 + + + + + 236 + 350 + + + + + + + Qt::AlignCenter + + + + + + + 0 + + + 8 + + + 15 + + + + + Amiibo Info + + + + + + + + Series + + + + + + + + 0 + 0 + + + + true + + + + + + + Type + + + + + + + + 0 + 0 + + + + true + + + + + + + Name + + + + + + + + 0 + 0 + + + + true + + + + + + + + + + + + Amiibo Data + + + + + + + + Custom Name + + + + + + + + 0 + 0 + + + + 10 + + + + + + + Owner + + + + + + + + 0 + 0 + + + + 10 + + + + + + + Creation Date + + + + + + + true + + + + 1970 + 1 + 1 + + + + dd/MM/yyyy + + + + + + + Modification Date + + + + + + + true + + + + 1970 + 1 + 1 + + + + dd/MM/yyyy + + + + + + + + + + + + + 500 + 0 + + + + Game Data + + + + + + Game Id + + + + + + + + 0 + 0 + + + + true + + + + + + + + + + + 500 + 0 + + + + Mount Amiibo + + + + + + ... + + + + + + + Qt::Horizontal + + + QSizePolicy::Maximum + + + + 60 + 20 + + + + + + + + File Path + + + + + + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + + + + + + + + 15 + + + 15 + + + 8 + + + 20 + + + 8 + + + + + true + + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + + + + + + + + + + + + + + buttonBox + accepted() + QtAmiiboSettingsDialog + accept() + + + buttonBox + rejected() + QtAmiiboSettingsDialog + reject() + + + diff --git a/src/sudachi/applets/qt_controller.cpp b/src/sudachi/applets/qt_controller.cpp new file mode 100644 index 0000000..39780fa --- /dev/null +++ b/src/sudachi/applets/qt_controller.cpp @@ -0,0 +1,778 @@ +// SPDX-FileCopyrightText: Copyright 2020 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include + +#include "common/assert.h" +#include "common/settings.h" +#include "common/settings_enums.h" +#include "common/string_util.h" +#include "core/core.h" +#include "core/hle/service/sm/sm.h" +#include "hid_core/frontend/emulated_controller.h" +#include "hid_core/hid_core.h" +#include "hid_core/hid_types.h" +#include "hid_core/resources/npad/npad.h" +#include "ui_qt_controller.h" +#include "sudachi/applets/qt_controller.h" +#include "sudachi/configuration/configure_input.h" +#include "sudachi/configuration/configure_input_profile_dialog.h" +#include "sudachi/configuration/configure_motion_touch.h" +#include "sudachi/configuration/configure_vibration.h" +#include "sudachi/configuration/input_profiles.h" +#include "sudachi/main.h" +#include "sudachi/util/controller_navigation.h" + +namespace { + +void UpdateController(Core::HID::EmulatedController* controller, + Core::HID::NpadStyleIndex controller_type, bool connected) { + if (controller->IsConnected(true)) { + controller->Disconnect(); + } + controller->SetNpadStyleIndex(controller_type); + if (connected) { + controller->Connect(true); + } +} + +// Returns true if the given controller type is compatible with the given parameters. +bool IsControllerCompatible(Core::HID::NpadStyleIndex controller_type, + Core::Frontend::ControllerParameters parameters) { + switch (controller_type) { + case Core::HID::NpadStyleIndex::Fullkey: + return parameters.allow_pro_controller; + case Core::HID::NpadStyleIndex::JoyconDual: + return parameters.allow_dual_joycons; + case Core::HID::NpadStyleIndex::JoyconLeft: + return parameters.allow_left_joycon; + case Core::HID::NpadStyleIndex::JoyconRight: + return parameters.allow_right_joycon; + case Core::HID::NpadStyleIndex::Handheld: + return parameters.enable_single_mode && parameters.allow_handheld; + case Core::HID::NpadStyleIndex::GameCube: + return parameters.allow_gamecube_controller; + default: + return false; + } +} + +} // namespace + +QtControllerSelectorDialog::QtControllerSelectorDialog( + QWidget* parent, Core::Frontend::ControllerParameters parameters_, + InputCommon::InputSubsystem* input_subsystem_, Core::System& system_) + : QDialog(parent), ui(std::make_unique()), + parameters(std::move(parameters_)), input_subsystem{input_subsystem_}, + input_profiles(std::make_unique()), system{system_} { + ui->setupUi(this); + + player_widgets = { + ui->widgetPlayer1, ui->widgetPlayer2, ui->widgetPlayer3, ui->widgetPlayer4, + ui->widgetPlayer5, ui->widgetPlayer6, ui->widgetPlayer7, ui->widgetPlayer8, + }; + + player_groupboxes = { + ui->groupPlayer1Connected, ui->groupPlayer2Connected, ui->groupPlayer3Connected, + ui->groupPlayer4Connected, ui->groupPlayer5Connected, ui->groupPlayer6Connected, + ui->groupPlayer7Connected, ui->groupPlayer8Connected, + }; + + connected_controller_icons = { + ui->controllerPlayer1, ui->controllerPlayer2, ui->controllerPlayer3, ui->controllerPlayer4, + ui->controllerPlayer5, ui->controllerPlayer6, ui->controllerPlayer7, ui->controllerPlayer8, + }; + + led_patterns_boxes = {{ + {ui->checkboxPlayer1LED1, ui->checkboxPlayer1LED2, ui->checkboxPlayer1LED3, + ui->checkboxPlayer1LED4}, + {ui->checkboxPlayer2LED1, ui->checkboxPlayer2LED2, ui->checkboxPlayer2LED3, + ui->checkboxPlayer2LED4}, + {ui->checkboxPlayer3LED1, ui->checkboxPlayer3LED2, ui->checkboxPlayer3LED3, + ui->checkboxPlayer3LED4}, + {ui->checkboxPlayer4LED1, ui->checkboxPlayer4LED2, ui->checkboxPlayer4LED3, + ui->checkboxPlayer4LED4}, + {ui->checkboxPlayer5LED1, ui->checkboxPlayer5LED2, ui->checkboxPlayer5LED3, + ui->checkboxPlayer5LED4}, + {ui->checkboxPlayer6LED1, ui->checkboxPlayer6LED2, ui->checkboxPlayer6LED3, + ui->checkboxPlayer6LED4}, + {ui->checkboxPlayer7LED1, ui->checkboxPlayer7LED2, ui->checkboxPlayer7LED3, + ui->checkboxPlayer7LED4}, + {ui->checkboxPlayer8LED1, ui->checkboxPlayer8LED2, ui->checkboxPlayer8LED3, + ui->checkboxPlayer8LED4}, + }}; + + explain_text_labels = { + ui->labelPlayer1Explain, ui->labelPlayer2Explain, ui->labelPlayer3Explain, + ui->labelPlayer4Explain, ui->labelPlayer5Explain, ui->labelPlayer6Explain, + ui->labelPlayer7Explain, ui->labelPlayer8Explain, + }; + + emulated_controllers = { + ui->comboPlayer1Emulated, ui->comboPlayer2Emulated, ui->comboPlayer3Emulated, + ui->comboPlayer4Emulated, ui->comboPlayer5Emulated, ui->comboPlayer6Emulated, + ui->comboPlayer7Emulated, ui->comboPlayer8Emulated, + }; + + player_labels = { + ui->labelPlayer1, ui->labelPlayer2, ui->labelPlayer3, ui->labelPlayer4, + ui->labelPlayer5, ui->labelPlayer6, ui->labelPlayer7, ui->labelPlayer8, + }; + + connected_controller_labels = { + ui->labelConnectedPlayer1, ui->labelConnectedPlayer2, ui->labelConnectedPlayer3, + ui->labelConnectedPlayer4, ui->labelConnectedPlayer5, ui->labelConnectedPlayer6, + ui->labelConnectedPlayer7, ui->labelConnectedPlayer8, + }; + + connected_controller_checkboxes = { + ui->checkboxPlayer1Connected, ui->checkboxPlayer2Connected, ui->checkboxPlayer3Connected, + ui->checkboxPlayer4Connected, ui->checkboxPlayer5Connected, ui->checkboxPlayer6Connected, + ui->checkboxPlayer7Connected, ui->checkboxPlayer8Connected, + }; + + ui->labelError->setVisible(false); + + // Setup/load everything prior to setting up connections. + // This avoids unintentionally changing the states of elements while loading them in. + SetSupportedControllers(); + DisableUnsupportedPlayers(); + + for (std::size_t player_index = 0; player_index < NUM_PLAYERS; ++player_index) { + SetEmulatedControllers(player_index); + } + + LoadConfiguration(); + + controller_navigation = new ControllerNavigation(system.HIDCore(), this); + + for (std::size_t i = 0; i < NUM_PLAYERS; ++i) { + SetExplainText(i); + UpdateControllerIcon(i); + UpdateLEDPattern(i); + UpdateBorderColor(i); + + connect(player_groupboxes[i], &QGroupBox::toggled, [this, i](bool checked) { + // Reconnect current controller if it was the last one checked + // (player number was reduced by more than one) + const bool reconnect_first = !checked && i < player_groupboxes.size() - 1 && + player_groupboxes[i + 1]->isChecked(); + + // Ensures that connecting a controller changes the number of players + if (connected_controller_checkboxes[i]->isChecked() != checked) { + // Ensures that the players are always connected in sequential order + PropagatePlayerNumberChanged(i, checked, reconnect_first); + } + }); + connect(connected_controller_checkboxes[i], &QCheckBox::clicked, [this, i](bool checked) { + // Reconnect current controller if it was the last one checked + // (player number was reduced by more than one) + const bool reconnect_first = !checked && + i < connected_controller_checkboxes.size() - 1 && + connected_controller_checkboxes[i + 1]->isChecked(); + + // Ensures that the players are always connected in sequential order + PropagatePlayerNumberChanged(i, checked, reconnect_first); + }); + + connect(emulated_controllers[i], qOverload(&QComboBox::currentIndexChanged), + [this, i](int) { + UpdateControllerIcon(i); + UpdateControllerState(i); + UpdateLEDPattern(i); + CheckIfParametersMet(); + }); + + connect(connected_controller_checkboxes[i], &QCheckBox::stateChanged, [this, i](int state) { + player_groupboxes[i]->setChecked(state == Qt::Checked); + UpdateControllerIcon(i); + UpdateControllerState(i); + UpdateLEDPattern(i); + UpdateBorderColor(i); + CheckIfParametersMet(); + }); + + if (i == 0) { + connect(emulated_controllers[i], qOverload(&QComboBox::currentIndexChanged), + [this, i](int index) { + UpdateDockedState(GetControllerTypeFromIndex(index, i) == + Core::HID::NpadStyleIndex::Handheld); + }); + } + } + + connect(ui->vibrationButton, &QPushButton::clicked, this, + &QtControllerSelectorDialog::CallConfigureVibrationDialog); + + connect(ui->motionButton, &QPushButton::clicked, this, + &QtControllerSelectorDialog::CallConfigureMotionTouchDialog); + + connect(ui->inputConfigButton, &QPushButton::clicked, this, + &QtControllerSelectorDialog::CallConfigureInputProfileDialog); + + connect(ui->buttonBox, &QDialogButtonBox::accepted, this, + &QtControllerSelectorDialog::ApplyConfiguration); + + connect(controller_navigation, &ControllerNavigation::TriggerKeyboardEvent, + [this](Qt::Key key) { + QKeyEvent* event = new QKeyEvent(QEvent::KeyPress, key, Qt::NoModifier); + QCoreApplication::postEvent(this, event); + }); + + // Enhancement: Check if the parameters have already been met before disconnecting controllers. + // If all the parameters are met AND only allows a single player, + // stop the constructor here as we do not need to continue. + if (CheckIfParametersMet() && parameters.enable_single_mode) { + return; + } + + // If keep_controllers_connected is false, forcefully disconnect all controllers + if (!parameters.keep_controllers_connected) { + for (auto player : player_groupboxes) { + player->setChecked(false); + } + } + + resize(0, 0); +} + +QtControllerSelectorDialog::~QtControllerSelectorDialog() { + controller_navigation->UnloadController(); + system.HIDCore().DisableAllControllerConfiguration(); +} + +int QtControllerSelectorDialog::exec() { + if (parameters_met && parameters.enable_single_mode) { + return QDialog::Accepted; + } + return QDialog::exec(); +} + +void QtControllerSelectorDialog::ApplyConfiguration() { + const bool pre_docked_mode = Settings::IsDockedMode(); + const bool docked_mode_selected = ui->radioDocked->isChecked(); + Settings::values.use_docked_mode.SetValue( + docked_mode_selected ? Settings::ConsoleMode::Docked : Settings::ConsoleMode::Handheld); + OnDockedModeChanged(pre_docked_mode, docked_mode_selected, system); + + Settings::values.vibration_enabled.SetValue(ui->vibrationGroup->isChecked()); + Settings::values.motion_enabled.SetValue(ui->motionGroup->isChecked()); +} + +void QtControllerSelectorDialog::LoadConfiguration() { + system.HIDCore().EnableAllControllerConfiguration(); + + const auto* handheld = system.HIDCore().GetEmulatedController(Core::HID::NpadIdType::Handheld); + for (std::size_t index = 0; index < NUM_PLAYERS; ++index) { + const auto* controller = system.HIDCore().GetEmulatedControllerByIndex(index); + const auto connected = + controller->IsConnected(true) || (index == 0 && handheld->IsConnected(true)); + player_groupboxes[index]->setChecked(connected); + connected_controller_checkboxes[index]->setChecked(connected); + emulated_controllers[index]->setCurrentIndex( + GetIndexFromControllerType(controller->GetNpadStyleIndex(true), index)); + } + + UpdateDockedState(handheld->IsConnected(true)); + + ui->vibrationGroup->setChecked(Settings::values.vibration_enabled.GetValue()); + ui->motionGroup->setChecked(Settings::values.motion_enabled.GetValue()); +} + +void QtControllerSelectorDialog::CallConfigureVibrationDialog() { + ConfigureVibration dialog(this, system.HIDCore()); + + dialog.setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint | + Qt::WindowSystemMenuHint); + dialog.setWindowModality(Qt::WindowModal); + + if (dialog.exec() == QDialog::Accepted) { + dialog.ApplyConfiguration(); + } +} + +void QtControllerSelectorDialog::CallConfigureMotionTouchDialog() { + ConfigureMotionTouch dialog(this, input_subsystem); + + dialog.setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint | + Qt::WindowSystemMenuHint); + dialog.setWindowModality(Qt::WindowModal); + + if (dialog.exec() == QDialog::Accepted) { + dialog.ApplyConfiguration(); + } +} + +void QtControllerSelectorDialog::CallConfigureInputProfileDialog() { + ConfigureInputProfileDialog dialog(this, input_subsystem, input_profiles.get(), system); + + dialog.setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint | + Qt::WindowSystemMenuHint); + dialog.setWindowModality(Qt::WindowModal); + dialog.exec(); +} + +void QtControllerSelectorDialog::keyPressEvent(QKeyEvent* evt) { + const auto num_connected_players = static_cast( + std::count_if(player_groupboxes.begin(), player_groupboxes.end(), + [](const QGroupBox* player) { return player->isChecked(); })); + + const auto min_supported_players = parameters.enable_single_mode ? 1 : parameters.min_players; + const auto max_supported_players = parameters.enable_single_mode ? 1 : parameters.max_players; + + if ((evt->key() == Qt::Key_Enter || evt->key() == Qt::Key_Return) && !parameters_met) { + // Display error message when trying to validate using "Enter" and "OK" button is disabled + ui->labelError->setVisible(true); + return; + } else if (evt->key() == Qt::Key_Left && num_connected_players > min_supported_players) { + // Remove a player if possible + connected_controller_checkboxes[num_connected_players - 1]->setChecked(false); + return; + } else if (evt->key() == Qt::Key_Right && num_connected_players < max_supported_players) { + // Add a player, if possible + ui->labelError->setVisible(false); + connected_controller_checkboxes[num_connected_players]->setChecked(true); + return; + } + QDialog::keyPressEvent(evt); +} + +bool QtControllerSelectorDialog::CheckIfParametersMet() { + // Here, we check and validate the current configuration against all applicable parameters. + const auto num_connected_players = static_cast( + std::count_if(player_groupboxes.begin(), player_groupboxes.end(), + [](const QGroupBox* player) { return player->isChecked(); })); + + const auto min_supported_players = parameters.enable_single_mode ? 1 : parameters.min_players; + const auto max_supported_players = parameters.enable_single_mode ? 1 : parameters.max_players; + + // First, check against the number of connected players. + if (num_connected_players < min_supported_players || + num_connected_players > max_supported_players) { + parameters_met = false; + ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(parameters_met); + return parameters_met; + } + + // Next, check against all connected controllers. + const auto all_controllers_compatible = [this] { + for (std::size_t index = 0; index < NUM_PLAYERS; ++index) { + // Skip controllers that are not used, we only care about the currently connected ones. + if (!player_groupboxes[index]->isChecked() || !player_groupboxes[index]->isEnabled()) { + continue; + } + + const auto compatible = IsControllerCompatible( + GetControllerTypeFromIndex(emulated_controllers[index]->currentIndex(), index), + parameters); + + // If any controller is found to be incompatible, return false early. + if (!compatible) { + return false; + } + } + + // Reaching here means all currently connected controllers are compatible. + return true; + }(); + + parameters_met = all_controllers_compatible; + ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(parameters_met); + return parameters_met; +} + +void QtControllerSelectorDialog::SetSupportedControllers() { + const QString theme = [] { + if (QIcon::themeName().contains(QStringLiteral("dark"))) { + return QStringLiteral("_dark"); + } else if (QIcon::themeName().contains(QStringLiteral("midnight"))) { + return QStringLiteral("_midnight"); + } else { + return QString{}; + } + }(); + + if (parameters.enable_single_mode && parameters.allow_handheld) { + ui->controllerSupported1->setStyleSheet( + QStringLiteral("image: url(:/controller/applet_handheld%0); ").arg(theme)); + } else { + ui->controllerSupported1->setStyleSheet( + QStringLiteral("image: url(:/controller/applet_handheld%0_disabled); ").arg(theme)); + } + + if (parameters.allow_dual_joycons) { + ui->controllerSupported2->setStyleSheet( + QStringLiteral("image: url(:/controller/applet_dual_joycon%0); ").arg(theme)); + } else { + ui->controllerSupported2->setStyleSheet( + QStringLiteral("image: url(:/controller/applet_dual_joycon%0_disabled); ").arg(theme)); + } + + if (parameters.allow_left_joycon) { + ui->controllerSupported3->setStyleSheet( + QStringLiteral("image: url(:/controller/applet_joycon_left%0); ").arg(theme)); + } else { + ui->controllerSupported3->setStyleSheet( + QStringLiteral("image: url(:/controller/applet_joycon_left%0_disabled); ").arg(theme)); + } + + if (parameters.allow_right_joycon) { + ui->controllerSupported4->setStyleSheet( + QStringLiteral("image: url(:/controller/applet_joycon_right%0); ").arg(theme)); + } else { + ui->controllerSupported4->setStyleSheet( + QStringLiteral("image: url(:/controller/applet_joycon_right%0_disabled); ").arg(theme)); + } + + if (parameters.allow_pro_controller || parameters.allow_gamecube_controller) { + ui->controllerSupported5->setStyleSheet( + QStringLiteral("image: url(:/controller/applet_pro_controller%0); ").arg(theme)); + } else { + ui->controllerSupported5->setStyleSheet( + QStringLiteral("image: url(:/controller/applet_pro_controller%0_disabled); ") + .arg(theme)); + } + + // enable_single_mode overrides min_players and max_players. + if (parameters.enable_single_mode) { + ui->numberSupportedLabel->setText(QStringLiteral("1")); + return; + } + + if (parameters.min_players == parameters.max_players) { + ui->numberSupportedLabel->setText(QStringLiteral("%1").arg(parameters.max_players)); + } else { + ui->numberSupportedLabel->setText( + QStringLiteral("%1 - %2").arg(parameters.min_players).arg(parameters.max_players)); + } +} + +void QtControllerSelectorDialog::SetEmulatedControllers(std::size_t player_index) { + const auto npad_style_set = system.HIDCore().GetSupportedStyleTag(); + auto& pairs = index_controller_type_pairs[player_index]; + + pairs.clear(); + emulated_controllers[player_index]->clear(); + + const auto add_item = [&](Core::HID::NpadStyleIndex controller_type, + const QString& controller_name) { + pairs.emplace_back(emulated_controllers[player_index]->count(), controller_type); + emulated_controllers[player_index]->addItem(controller_name); + }; + + if (npad_style_set.fullkey == 1) { + add_item(Core::HID::NpadStyleIndex::Fullkey, tr("Pro Controller")); + } + + if (npad_style_set.joycon_dual == 1) { + add_item(Core::HID::NpadStyleIndex::JoyconDual, tr("Dual Joycons")); + } + + if (npad_style_set.joycon_left == 1) { + add_item(Core::HID::NpadStyleIndex::JoyconLeft, tr("Left Joycon")); + } + + if (npad_style_set.joycon_right == 1) { + add_item(Core::HID::NpadStyleIndex::JoyconRight, tr("Right Joycon")); + } + + if (player_index == 0 && npad_style_set.handheld == 1) { + add_item(Core::HID::NpadStyleIndex::Handheld, tr("Handheld")); + } + + if (npad_style_set.gamecube == 1) { + add_item(Core::HID::NpadStyleIndex::GameCube, tr("GameCube Controller")); + } + + // Disable all unsupported controllers + if (!Settings::values.enable_all_controllers) { + return; + } + + if (npad_style_set.palma == 1) { + add_item(Core::HID::NpadStyleIndex::Pokeball, tr("Poke Ball Plus")); + } + + if (npad_style_set.lark == 1) { + add_item(Core::HID::NpadStyleIndex::NES, tr("NES Controller")); + } + + if (npad_style_set.lucia == 1) { + add_item(Core::HID::NpadStyleIndex::SNES, tr("SNES Controller")); + } + + if (npad_style_set.lagoon == 1) { + add_item(Core::HID::NpadStyleIndex::N64, tr("N64 Controller")); + } + + if (npad_style_set.lager == 1) { + add_item(Core::HID::NpadStyleIndex::SegaGenesis, tr("Sega Genesis")); + } +} + +Core::HID::NpadStyleIndex QtControllerSelectorDialog::GetControllerTypeFromIndex( + int index, std::size_t player_index) const { + const auto& pairs = index_controller_type_pairs[player_index]; + + const auto it = std::find_if(pairs.begin(), pairs.end(), + [index](const auto& pair) { return pair.first == index; }); + + if (it == pairs.end()) { + return Core::HID::NpadStyleIndex::Fullkey; + } + + return it->second; +} + +int QtControllerSelectorDialog::GetIndexFromControllerType(Core::HID::NpadStyleIndex type, + std::size_t player_index) const { + const auto& pairs = index_controller_type_pairs[player_index]; + + const auto it = std::find_if(pairs.begin(), pairs.end(), + [type](const auto& pair) { return pair.second == type; }); + + if (it == pairs.end()) { + return 0; + } + + return it->first; +} + +void QtControllerSelectorDialog::UpdateControllerIcon(std::size_t player_index) { + if (!player_groupboxes[player_index]->isChecked()) { + connected_controller_icons[player_index]->setStyleSheet(QString{}); + player_labels[player_index]->show(); + return; + } + + const QString stylesheet = [this, player_index] { + switch (GetControllerTypeFromIndex(emulated_controllers[player_index]->currentIndex(), + player_index)) { + case Core::HID::NpadStyleIndex::Fullkey: + case Core::HID::NpadStyleIndex::GameCube: + return QStringLiteral("image: url(:/controller/applet_pro_controller%0); "); + case Core::HID::NpadStyleIndex::JoyconDual: + return QStringLiteral("image: url(:/controller/applet_dual_joycon%0); "); + case Core::HID::NpadStyleIndex::JoyconLeft: + return QStringLiteral("image: url(:/controller/applet_joycon_left%0); "); + case Core::HID::NpadStyleIndex::JoyconRight: + return QStringLiteral("image: url(:/controller/applet_joycon_right%0); "); + case Core::HID::NpadStyleIndex::Handheld: + return QStringLiteral("image: url(:/controller/applet_handheld%0); "); + default: + return QString{}; + } + }(); + + if (stylesheet.isEmpty()) { + connected_controller_icons[player_index]->setStyleSheet(QString{}); + player_labels[player_index]->show(); + return; + } + + const QString theme = [] { + if (QIcon::themeName().contains(QStringLiteral("dark"))) { + return QStringLiteral("_dark"); + } else if (QIcon::themeName().contains(QStringLiteral("midnight"))) { + return QStringLiteral("_midnight"); + } else { + return QString{}; + } + }(); + + connected_controller_icons[player_index]->setStyleSheet(stylesheet.arg(theme)); + player_labels[player_index]->hide(); +} + +void QtControllerSelectorDialog::UpdateControllerState(std::size_t player_index) { + auto* controller = system.HIDCore().GetEmulatedControllerByIndex(player_index); + + const auto controller_type = GetControllerTypeFromIndex( + emulated_controllers[player_index]->currentIndex(), player_index); + const auto player_connected = player_groupboxes[player_index]->isChecked() && + controller_type != Core::HID::NpadStyleIndex::Handheld; + + if (controller->GetNpadStyleIndex(true) == controller_type && + controller->IsConnected(true) == player_connected) { + return; + } + + // Disconnect the controller first. + UpdateController(controller, controller_type, false); + + // Handheld + if (player_index == 0) { + if (controller_type == Core::HID::NpadStyleIndex::Handheld) { + auto* handheld = + system.HIDCore().GetEmulatedController(Core::HID::NpadIdType::Handheld); + UpdateController(handheld, Core::HID::NpadStyleIndex::Handheld, + player_groupboxes[player_index]->isChecked()); + } + } + + UpdateController(controller, controller_type, player_connected); +} + +void QtControllerSelectorDialog::UpdateLEDPattern(std::size_t player_index) { + if (!player_groupboxes[player_index]->isChecked() || + GetControllerTypeFromIndex(emulated_controllers[player_index]->currentIndex(), + player_index) == Core::HID::NpadStyleIndex::Handheld) { + led_patterns_boxes[player_index][0]->setChecked(false); + led_patterns_boxes[player_index][1]->setChecked(false); + led_patterns_boxes[player_index][2]->setChecked(false); + led_patterns_boxes[player_index][3]->setChecked(false); + return; + } + + const auto* controller = system.HIDCore().GetEmulatedControllerByIndex(player_index); + const auto led_pattern = controller->GetLedPattern(); + led_patterns_boxes[player_index][0]->setChecked(led_pattern.position1); + led_patterns_boxes[player_index][1]->setChecked(led_pattern.position2); + led_patterns_boxes[player_index][2]->setChecked(led_pattern.position3); + led_patterns_boxes[player_index][3]->setChecked(led_pattern.position4); +} + +void QtControllerSelectorDialog::UpdateBorderColor(std::size_t player_index) { + if (!parameters.enable_border_color || + player_index >= static_cast(parameters.max_players) || + player_groupboxes[player_index]->styleSheet().contains(QStringLiteral("QGroupBox"))) { + return; + } + + player_groupboxes[player_index]->setStyleSheet( + player_groupboxes[player_index]->styleSheet().append( + QStringLiteral("QGroupBox#groupPlayer%1Connected:checked " + "{ border: 1px solid rgba(%2, %3, %4, %5); }") + .arg(player_index + 1) + .arg(parameters.border_colors[player_index][0]) + .arg(parameters.border_colors[player_index][1]) + .arg(parameters.border_colors[player_index][2]) + .arg(parameters.border_colors[player_index][3]))); +} + +void QtControllerSelectorDialog::SetExplainText(std::size_t player_index) { + if (!parameters.enable_explain_text || + player_index >= static_cast(parameters.max_players)) { + return; + } + + explain_text_labels[player_index]->setText(QString::fromStdString( + Common::StringFromFixedZeroTerminatedBuffer(parameters.explain_text[player_index].data(), + parameters.explain_text[player_index].size()))); +} + +void QtControllerSelectorDialog::UpdateDockedState(bool is_handheld) { + // Disallow changing the console mode if the controller type is handheld. + ui->radioDocked->setEnabled(!is_handheld); + ui->radioUndocked->setEnabled(!is_handheld); + + ui->radioDocked->setChecked(Settings::IsDockedMode()); + ui->radioUndocked->setChecked(!Settings::IsDockedMode()); + + // Also force into undocked mode if the controller type is handheld. + if (is_handheld) { + ui->radioUndocked->setChecked(true); + } +} + +void QtControllerSelectorDialog::PropagatePlayerNumberChanged(size_t player_index, bool checked, + bool reconnect_current) { + connected_controller_checkboxes[player_index]->setChecked(checked); + // Hide eventual error message about number of controllers + ui->labelError->setVisible(false); + + if (checked) { + // Check all previous buttons when checked + if (player_index > 0) { + PropagatePlayerNumberChanged(player_index - 1, checked); + } + } else { + // Unchecked all following buttons when unchecked + if (player_index < connected_controller_checkboxes.size() - 1) { + PropagatePlayerNumberChanged(player_index + 1, checked); + } + } + + if (reconnect_current) { + connected_controller_checkboxes[player_index]->setCheckState(Qt::Checked); + } +} + +void QtControllerSelectorDialog::DisableUnsupportedPlayers() { + const auto max_supported_players = parameters.enable_single_mode ? 1 : parameters.max_players; + + switch (max_supported_players) { + case 0: + default: + ASSERT(false); + return; + case 1: + ui->widgetSpacer->hide(); + ui->widgetSpacer2->hide(); + ui->widgetSpacer3->hide(); + ui->widgetSpacer4->hide(); + break; + case 2: + ui->widgetSpacer->hide(); + ui->widgetSpacer2->hide(); + ui->widgetSpacer3->hide(); + break; + case 3: + ui->widgetSpacer->hide(); + ui->widgetSpacer2->hide(); + break; + case 4: + ui->widgetSpacer->hide(); + break; + case 5: + case 6: + case 7: + case 8: + break; + } + + for (std::size_t index = max_supported_players; index < NUM_PLAYERS; ++index) { + auto* controller = system.HIDCore().GetEmulatedControllerByIndex(index); + // Disconnect any unsupported players here and disable or hide them if applicable. + UpdateController(controller, controller->GetNpadStyleIndex(true), false); + // Hide the player widgets when max_supported_controllers is less than or equal to 4. + if (max_supported_players <= 4) { + player_widgets[index]->hide(); + } + + // Disable and hide the following to prevent these from interaction. + player_widgets[index]->setDisabled(true); + connected_controller_checkboxes[index]->setDisabled(true); + connected_controller_labels[index]->hide(); + connected_controller_checkboxes[index]->hide(); + } +} + +QtControllerSelector::QtControllerSelector(GMainWindow& parent) { + connect(this, &QtControllerSelector::MainWindowReconfigureControllers, &parent, + &GMainWindow::ControllerSelectorReconfigureControllers, Qt::QueuedConnection); + connect(this, &QtControllerSelector::MainWindowRequestExit, &parent, + &GMainWindow::ControllerSelectorRequestExit, Qt::QueuedConnection); + connect(&parent, &GMainWindow::ControllerSelectorReconfigureFinished, this, + &QtControllerSelector::MainWindowReconfigureFinished, Qt::QueuedConnection); +} + +QtControllerSelector::~QtControllerSelector() = default; + +void QtControllerSelector::Close() const { + callback = {}; + emit MainWindowRequestExit(); +} + +void QtControllerSelector::ReconfigureControllers( + ReconfigureCallback callback_, const Core::Frontend::ControllerParameters& parameters) const { + callback = std::move(callback_); + emit MainWindowReconfigureControllers(parameters); +} + +void QtControllerSelector::MainWindowReconfigureFinished(bool is_success) { + if (callback) { + callback(is_success); + } +} diff --git a/src/sudachi/applets/qt_controller.h b/src/sudachi/applets/qt_controller.h new file mode 100644 index 0000000..7830894 --- /dev/null +++ b/src/sudachi/applets/qt_controller.h @@ -0,0 +1,183 @@ +// SPDX-FileCopyrightText: Copyright 2020 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include +#include +#include "core/frontend/applets/controller.h" + +class GMainWindow; +class QCheckBox; +class QComboBox; +class QDialogButtonBox; +class QGroupBox; +class QLabel; + +class InputProfiles; + +namespace InputCommon { +class InputSubsystem; +} + +namespace Ui { +class QtControllerSelectorDialog; +} + +namespace Core { +class System; +} + +namespace Core::HID { +class HIDCore; +enum class NpadStyleIndex : u8; +} // namespace Core::HID + +class ControllerNavigation; + +class QtControllerSelectorDialog final : public QDialog { + Q_OBJECT + +public: + explicit QtControllerSelectorDialog(QWidget* parent, + Core::Frontend::ControllerParameters parameters_, + InputCommon::InputSubsystem* input_subsystem_, + Core::System& system_); + ~QtControllerSelectorDialog() override; + + int exec() override; + + void keyPressEvent(QKeyEvent* evt) override; + +private: + // Applies the current configuration. + void ApplyConfiguration(); + + // Loads the current input configuration into the frontend applet. + void LoadConfiguration(); + + // Initializes the "Configure Vibration" Dialog. + void CallConfigureVibrationDialog(); + + // Initializes the "Configure Motion / Touch" Dialog. + void CallConfigureMotionTouchDialog(); + + // Initializes the "Create Input Profile" Dialog. + void CallConfigureInputProfileDialog(); + + // Checks the current configuration against the given parameters. + // This sets and returns the value of parameters_met. + bool CheckIfParametersMet(); + + // Sets the controller icons for "Supported Controller Types". + void SetSupportedControllers(); + + // Sets the emulated controllers per player. + void SetEmulatedControllers(std::size_t player_index); + + // Gets the Controller Type for a given controller combobox index per player. + Core::HID::NpadStyleIndex GetControllerTypeFromIndex(int index, std::size_t player_index) const; + + // Gets the controller combobox index for a given Controller Type per player. + int GetIndexFromControllerType(Core::HID::NpadStyleIndex type, std::size_t player_index) const; + + // Updates the controller icons per player. + void UpdateControllerIcon(std::size_t player_index); + + // Updates the controller state (type and connection status) per player. + void UpdateControllerState(std::size_t player_index); + + // Updates the LED pattern per player. + void UpdateLEDPattern(std::size_t player_index); + + // Updates the border color per player. + void UpdateBorderColor(std::size_t player_index); + + // Sets the "Explain Text" per player. + void SetExplainText(std::size_t player_index); + + // Updates the console mode. + void UpdateDockedState(bool is_handheld); + + // Enable preceding controllers or disable following ones + void PropagatePlayerNumberChanged(size_t player_index, bool checked, + bool reconnect_current = false); + + // Disables and disconnects unsupported players based on the given parameters. + void DisableUnsupportedPlayers(); + + std::unique_ptr ui; + + // Parameters sent in from the backend HLE applet. + Core::Frontend::ControllerParameters parameters; + + InputCommon::InputSubsystem* input_subsystem; + + std::unique_ptr input_profiles; + + Core::System& system; + + ControllerNavigation* controller_navigation = nullptr; + + // This is true if and only if all parameters are met. Otherwise, this is false. + // This determines whether the "OK" button can be clicked to exit the applet. + bool parameters_met{false}; + + static constexpr std::size_t NUM_PLAYERS = 8; + + // Widgets encapsulating the groupboxes and comboboxes per player. + std::array player_widgets; + + // Groupboxes encapsulating the controller icons and LED patterns per player. + std::array player_groupboxes; + + // Icons for currently connected controllers/players. + std::array connected_controller_icons; + + // Labels that represent the player numbers in place of the controller icons. + std::array player_labels; + + // LED patterns for currently connected controllers/players. + std::array, NUM_PLAYERS> led_patterns_boxes; + + // Labels representing additional information known as "Explain Text" per player. + std::array explain_text_labels; + + // Comboboxes with a list of emulated controllers per player. + std::array emulated_controllers; + + /// Pairs of emulated controller index and Controller Type enum per player. + std::array>, NUM_PLAYERS> + index_controller_type_pairs; + + // Labels representing the number of connected controllers + // above the "Connected Controllers" checkboxes. + std::array connected_controller_labels; + + // Checkboxes representing the "Connected Controllers". + std::array connected_controller_checkboxes; +}; + +class QtControllerSelector final : public QObject, public Core::Frontend::ControllerApplet { + Q_OBJECT + +public: + explicit QtControllerSelector(GMainWindow& parent); + ~QtControllerSelector() override; + + void Close() const override; + void ReconfigureControllers( + ReconfigureCallback callback_, + const Core::Frontend::ControllerParameters& parameters) const override; + +signals: + void MainWindowReconfigureControllers( + const Core::Frontend::ControllerParameters& parameters) const; + void MainWindowRequestExit() const; + +private: + void MainWindowReconfigureFinished(bool is_success); + + mutable ReconfigureCallback callback; +}; diff --git a/src/sudachi/applets/qt_controller.ui b/src/sudachi/applets/qt_controller.ui new file mode 100644 index 0000000..6f7cb3c --- /dev/null +++ b/src/sudachi/applets/qt_controller.ui @@ -0,0 +1,2699 @@ + + + QtControllerSelectorDialog + + + + 0 + 0 + 839 + 630 + + + + Controller Applet + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 10 + + + 0 + + + 10 + + + 0 + + + 10 + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 70 + 70 + + + + + 70 + 70 + + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 70 + 70 + + + + + 70 + 70 + + + + + 75 + true + + + + Supported Controller Types: + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + true + + + + + + + + + + + 0 + 0 + + + + + 70 + 70 + + + + + 70 + 70 + + + + + + + + + + + + 70 + 70 + + + + + 70 + 70 + + + + + + + + + + + + 70 + 70 + + + + + 70 + 70 + + + + + + + + + + + + 70 + 70 + + + + + 70 + 70 + + + + + + + + + + + + 70 + 70 + + + + + 70 + 70 + + + + + + + + + + + + 70 + 70 + + + + + 70 + 70 + + + + + 0 + + + 0 + + + 16 + + + 14 + + + 16 + + + + + + 75 + true + + + + Players: + + + Qt::AlignCenter + + + false + + + + + + + + 14 + + + + 1 - 8 + + + Qt::AlignCenter + + + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + 5 + + + + + + 5 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 100 + 100 + + + + + 100 + 100 + + + + + + + true + + + false + + + + 7 + + + 14 + + + 7 + + + 14 + + + 4 + + + + + + + + + 16 + + + + + P4 + + + + + + + + + + false + + + + 0 + 10 + + + + + 4 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + + + + + + + + + + + + + + + + + + + 0 + 10 + + + + + 150 + 16777215 + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Qt::AlignCenter + + + + + + + + + + + Pro Controller + + + + + Dual Joycons + + + + + Left Joycon + + + + + Right Joycon + + + + + + + + + Use Current Config + + + + + + + + + + + + 5 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 100 + 100 + + + + + 100 + 100 + + + + + + + true + + + false + + + + 7 + + + 14 + + + 7 + + + 14 + + + 4 + + + + + + + + + 16 + + + + + P2 + + + + + + + + + + false + + + + 0 + 10 + + + + + 4 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + + + + + + + + + + + + + + + + + + + 0 + 10 + + + + + 150 + 16777215 + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Qt::AlignCenter + + + + + + + + + + + Pro Controller + + + + + Dual Joycons + + + + + Left Joycon + + + + + Right Joycon + + + + + + + + + Use Current Config + + + + + + + + + + + + 5 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 100 + 100 + + + + + 100 + 100 + + + + + + + true + + + false + + + + 7 + + + 14 + + + 7 + + + 14 + + + 4 + + + + + + + + + 16 + + + + + P1 + + + + + + + + + + false + + + + 0 + 10 + + + + + 4 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Qt::LeftToRight + + + + + + + + + + + + + + + + + + + + + + + 0 + 10 + + + + + 150 + 16777215 + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Qt::AlignCenter + + + + + + + + + + + Pro Controller + + + + + Dual Joycons + + + + + Left Joycon + + + + + Right Joycon + + + + + Handheld + + + + + + + + + Use Current Config + + + + + + + + + + + + 25 + 0 + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Qt::Horizontal + + + + 25 + 20 + + + + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Qt::Horizontal + + + + 0 + 20 + + + + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Qt::Horizontal + + + + 0 + 20 + + + + + + + + + + + + 5 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 100 + 100 + + + + + 100 + 100 + + + + + + + true + + + false + + + + 7 + + + 14 + + + 7 + + + 14 + + + 4 + + + + + + + + + 16 + + + + + P3 + + + + + + + + + + false + + + + 0 + 10 + + + + + 4 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + + + + + + + + + + + + + + + + + + + 0 + 10 + + + + + 150 + 16777215 + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Qt::AlignCenter + + + + + + + + + + + Pro Controller + + + + + Dual Joycons + + + + + Left Joycon + + + + + Right Joycon + + + + + + + + + Use Current Config + + + + + + + + + + + + 0 + 25 + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Qt::Vertical + + + + 20 + 25 + + + + + + + + + + + + 5 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 100 + 100 + + + + + 100 + 100 + + + + + + + true + + + false + + + + 7 + + + 14 + + + 7 + + + 14 + + + 4 + + + + + + + + + 16 + + + + + P7 + + + + + + + + + + false + + + + 0 + 10 + + + + + 4 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + + + + + + + + + + + + + + + + + + + 0 + 10 + + + + + 150 + 16777215 + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Qt::AlignCenter + + + + + + + + + + + Pro Controller + + + + + Dual Joycons + + + + + Left Joycon + + + + + Right Joycon + + + + + + + + + Use Current Config + + + + + + + + + + + + 5 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 100 + 100 + + + + + 100 + 100 + + + + + + + true + + + false + + + + 7 + + + 14 + + + 7 + + + 14 + + + 4 + + + + + + + + + 16 + + + + + P8 + + + + + + + + + + false + + + + 0 + 10 + + + + + 4 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + + + + + + + + + + + + + + + + + + + 0 + 10 + + + + + 150 + 16777215 + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Qt::AlignCenter + + + + + + + + + + + Pro Controller + + + + + Dual Joycons + + + + + Left Joycon + + + + + Right Joycon + + + + + + + + + Use Current Config + + + + + + + + + + + + 5 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 100 + 100 + + + + + 100 + 100 + + + + + + + true + + + false + + + + 7 + + + 14 + + + 7 + + + 14 + + + 4 + + + + + + + + + 16 + + + + + P5 + + + + + + + + + + false + + + + 0 + 10 + + + + + 4 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Qt::LeftToRight + + + + + + + + + + + + + + + + + + + + + + + 0 + 10 + + + + + 150 + 16777215 + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Qt::AlignCenter + + + + + + + + + + + Pro Controller + + + + + Dual Joycons + + + + + Left Joycon + + + + + Right Joycon + + + + + + + + + Use Current Config + + + + + + + + + + + + 5 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 100 + 100 + + + + + 100 + 100 + + + + + + + true + + + false + + + + 7 + + + 14 + + + 7 + + + 14 + + + 4 + + + + + + + + + 16 + + + + + P6 + + + + + + + + + + false + + + + 0 + 10 + + + + + 4 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + + + + + + + + + + + + + + + + + + + 0 + 10 + + + + + 150 + 16777215 + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Qt::AlignCenter + + + + + + + + + + + Pro Controller + + + + + Dual Joycons + + + + + Left Joycon + + + + + Right Joycon + + + + + + + + + Use Current Config + + + + + + + + + + + + 0 + 25 + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Qt::Vertical + + + + 20 + 25 + + + + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Qt::Horizontal + + + + 0 + 20 + + + + + + + + + + + + 25 + 0 + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Qt::Horizontal + + + + 25 + 20 + + + + + + + + + + + + 0 + 25 + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Qt::Vertical + + + + 20 + 25 + + + + + + + + + + + + + + + + + 15 + + + 15 + + + 8 + + + 15 + + + 15 + + + + + + 16777215 + 16777215 + + + + Console Mode + + + + 6 + + + 8 + + + 6 + + + 3 + + + 6 + + + + + Docked + + + true + + + + + + + Handheld + + + + + + + + + + Vibration + + + true + + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + Configure + + + + + + + + + + Motion + + + true + + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + Configure + + + + + + + + + + Profiles + + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 68 + 16777215 + + + + min-width: 68px; + + + Create + + + + + + + + + + + 5 + + + 0 + + + 0 + + + 0 + + + 3 + + + + + + + + + + + + Controllers + + + + + + + + + + + + + + 1 + + + Qt::AlignCenter + + + + + + + + + + + + + + Qt::LeftToRight + + + false + + + + + + + 2 + + + Qt::AlignCenter + + + + + + + 4 + + + Qt::AlignCenter + + + + + + + 3 + + + Qt::AlignCenter + + + + + + + Connected + + + + + + + + + + + + + + 5 + + + Qt::AlignCenter + + + + + + + + + + + + + + 7 + + + Qt::AlignCenter + + + + + + + + + + + + + + 6 + + + Qt::AlignCenter + + + + + + + 8 + + + Qt::AlignCenter + + + + + + + + + + + + + + + + + Qt::Horizontal + + + + 0 + 20 + + + + + + + + + 7 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + true + + + QLabel { color : red; } + + + Not enough controllers + + + Qt::AlignCenter + + + 0 + + + + + + + true + + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + + + + + + + + + + + + + + + + + buttonBox + accepted() + QtControllerSelectorDialog + accept() + + + buttonBox + rejected() + QtControllerSelectorDialog + reject() + + + diff --git a/src/sudachi/applets/qt_error.cpp b/src/sudachi/applets/qt_error.cpp new file mode 100644 index 0000000..9712a11 --- /dev/null +++ b/src/sudachi/applets/qt_error.cpp @@ -0,0 +1,68 @@ +// SPDX-FileCopyrightText: Copyright 2019 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include "sudachi/applets/qt_error.h" +#include "sudachi/main.h" + +QtErrorDisplay::QtErrorDisplay(GMainWindow& parent) { + connect(this, &QtErrorDisplay::MainWindowDisplayError, &parent, + &GMainWindow::ErrorDisplayDisplayError, Qt::QueuedConnection); + connect(this, &QtErrorDisplay::MainWindowRequestExit, &parent, + &GMainWindow::ErrorDisplayRequestExit, Qt::QueuedConnection); + connect(&parent, &GMainWindow::ErrorDisplayFinished, this, + &QtErrorDisplay::MainWindowFinishedError, Qt::DirectConnection); +} + +QtErrorDisplay::~QtErrorDisplay() = default; + +void QtErrorDisplay::Close() const { + callback = {}; + emit MainWindowRequestExit(); +} + +void QtErrorDisplay::ShowError(Result error, FinishedCallback finished) const { + callback = std::move(finished); + emit MainWindowDisplayError( + tr("Error Code: %1-%2 (0x%3)") + .arg(static_cast(error.GetModule()) + 2000, 4, 10, QChar::fromLatin1('0')) + .arg(error.GetDescription(), 4, 10, QChar::fromLatin1('0')) + .arg(error.raw, 8, 16, QChar::fromLatin1('0')), + tr("An error has occurred.\nPlease try again or contact the developer of the software.")); +} + +void QtErrorDisplay::ShowErrorWithTimestamp(Result error, std::chrono::seconds time, + FinishedCallback finished) const { + callback = std::move(finished); + + const QDateTime date_time = QDateTime::fromSecsSinceEpoch(time.count()); + emit MainWindowDisplayError( + tr("Error Code: %1-%2 (0x%3)") + .arg(static_cast(error.GetModule()) + 2000, 4, 10, QChar::fromLatin1('0')) + .arg(error.GetDescription(), 4, 10, QChar::fromLatin1('0')) + .arg(error.raw, 8, 16, QChar::fromLatin1('0')), + tr("An error occurred on %1 at %2.\nPlease try again or contact the developer of the " + "software.") + .arg(date_time.toString(QStringLiteral("dddd, MMMM d, yyyy"))) + .arg(date_time.toString(QStringLiteral("h:mm:ss A")))); +} + +void QtErrorDisplay::ShowCustomErrorText(Result error, std::string dialog_text, + std::string fullscreen_text, + FinishedCallback finished) const { + callback = std::move(finished); + emit MainWindowDisplayError( + tr("Error Code: %1-%2 (0x%3)") + .arg(static_cast(error.GetModule()) + 2000, 4, 10, QChar::fromLatin1('0')) + .arg(error.GetDescription(), 4, 10, QChar::fromLatin1('0')) + .arg(error.raw, 8, 16, QChar::fromLatin1('0')), + tr("An error has occurred.\n\n%1\n\n%2") + .arg(QString::fromStdString(dialog_text)) + .arg(QString::fromStdString(fullscreen_text))); +} + +void QtErrorDisplay::MainWindowFinishedError() { + if (callback) { + callback(); + } +} diff --git a/src/sudachi/applets/qt_error.h b/src/sudachi/applets/qt_error.h new file mode 100644 index 0000000..ba810e5 --- /dev/null +++ b/src/sudachi/applets/qt_error.h @@ -0,0 +1,34 @@ +// SPDX-FileCopyrightText: Copyright 2019 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include + +#include "core/frontend/applets/error.h" + +class GMainWindow; + +class QtErrorDisplay final : public QObject, public Core::Frontend::ErrorApplet { + Q_OBJECT + +public: + explicit QtErrorDisplay(GMainWindow& parent); + ~QtErrorDisplay() override; + + void Close() const override; + void ShowError(Result error, FinishedCallback finished) const override; + void ShowErrorWithTimestamp(Result error, std::chrono::seconds time, + FinishedCallback finished) const override; + void ShowCustomErrorText(Result error, std::string dialog_text, std::string fullscreen_text, + FinishedCallback finished) const override; + +signals: + void MainWindowDisplayError(QString error_code, QString error_text) const; + void MainWindowRequestExit() const; + +private: + void MainWindowFinishedError(); + + mutable FinishedCallback callback; +}; diff --git a/src/sudachi/applets/qt_profile_select.cpp b/src/sudachi/applets/qt_profile_select.cpp new file mode 100644 index 0000000..3979d1f --- /dev/null +++ b/src/sudachi/applets/qt_profile_select.cpp @@ -0,0 +1,260 @@ +// SPDX-FileCopyrightText: Copyright 2018 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "common/fs/path_util.h" +#include "common/string_util.h" +#include "core/constants.h" +#include "core/core.h" +#include "core/hle/service/acc/profile_manager.h" +#include "sudachi/applets/qt_profile_select.h" +#include "sudachi/main.h" +#include "sudachi/util/controller_navigation.h" + +namespace { +QString FormatUserEntryText(const QString& username, Common::UUID uuid) { + return QtProfileSelectionDialog::tr( + "%1\n%2", "%1 is the profile username, %2 is the formatted UUID (e.g. " + "00112233-4455-6677-8899-AABBCCDDEEFF))") + .arg(username, QString::fromStdString(uuid.FormattedString())); +} + +QString GetImagePath(Common::UUID uuid) { + const auto path = + Common::FS::GetSudachiPath(Common::FS::SudachiPath::NANDDir) / + fmt::format("system/save/8000000000000010/su/avators/{}.jpg", uuid.FormattedString()); + return QString::fromStdString(Common::FS::PathToUTF8String(path)); +} + +QPixmap GetIcon(Common::UUID uuid) { + QPixmap icon{GetImagePath(uuid)}; + + if (!icon) { + icon.fill(Qt::black); + icon.loadFromData(Core::Constants::ACCOUNT_BACKUP_JPEG.data(), + static_cast(Core::Constants::ACCOUNT_BACKUP_JPEG.size())); + } + + return icon.scaled(64, 64, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); +} +} // Anonymous namespace + +QtProfileSelectionDialog::QtProfileSelectionDialog( + Core::System& system, QWidget* parent, + const Core::Frontend::ProfileSelectParameters& parameters) + : QDialog(parent), profile_manager{system.GetProfileManager()} { + outer_layout = new QVBoxLayout; + + instruction_label = new QLabel(); + + scroll_area = new QScrollArea; + + buttons = new QDialogButtonBox(QDialogButtonBox::Cancel | QDialogButtonBox::Ok); + connect(buttons, &QDialogButtonBox::accepted, this, &QtProfileSelectionDialog::accept); + connect(buttons, &QDialogButtonBox::rejected, this, &QtProfileSelectionDialog::reject); + + outer_layout->addWidget(instruction_label); + outer_layout->addWidget(scroll_area); + outer_layout->addWidget(buttons); + + layout = new QVBoxLayout; + tree_view = new QTreeView; + item_model = new QStandardItemModel(tree_view); + tree_view->setModel(item_model); + controller_navigation = new ControllerNavigation(system.HIDCore(), this); + + tree_view->setAlternatingRowColors(true); + tree_view->setSelectionMode(QHeaderView::SingleSelection); + tree_view->setSelectionBehavior(QHeaderView::SelectRows); + tree_view->setVerticalScrollMode(QHeaderView::ScrollPerPixel); + tree_view->setHorizontalScrollMode(QHeaderView::ScrollPerPixel); + tree_view->setSortingEnabled(true); + tree_view->setEditTriggers(QHeaderView::NoEditTriggers); + tree_view->setUniformRowHeights(true); + tree_view->setIconSize({64, 64}); + tree_view->setContextMenuPolicy(Qt::NoContextMenu); + + item_model->insertColumns(0, 1); + item_model->setHeaderData(0, Qt::Horizontal, tr("Users")); + + // We must register all custom types with the Qt Automoc system so that we are able to use it + // with signals/slots. In this case, QList falls under the umbrella of custom types. + qRegisterMetaType>("QList"); + + layout->setContentsMargins(0, 0, 0, 0); + layout->setSpacing(0); + layout->addWidget(tree_view); + + scroll_area->setLayout(layout); + + connect(tree_view, &QTreeView::clicked, this, &QtProfileSelectionDialog::SelectUser); + connect(tree_view, &QTreeView::doubleClicked, this, &QtProfileSelectionDialog::accept); + connect(controller_navigation, &ControllerNavigation::TriggerKeyboardEvent, + [this](Qt::Key key) { + if (!this->isActiveWindow()) { + return; + } + QKeyEvent* event = new QKeyEvent(QEvent::KeyPress, key, Qt::NoModifier); + QCoreApplication::postEvent(tree_view, event); + SelectUser(tree_view->currentIndex()); + }); + + const auto& profiles = profile_manager.GetAllUsers(); + for (const auto& user : profiles) { + Service::Account::ProfileBase profile{}; + if (!profile_manager.GetProfileBase(user, profile)) + continue; + + const auto username = Common::StringFromFixedZeroTerminatedBuffer( + reinterpret_cast(profile.username.data()), profile.username.size()); + + list_items.push_back(QList{new QStandardItem{ + GetIcon(user), FormatUserEntryText(QString::fromStdString(username), user)}}); + } + + for (const auto& item : list_items) + item_model->appendRow(item); + + setLayout(outer_layout); + SetWindowTitle(parameters); + SetDialogPurpose(parameters); + resize(550, 400); +} + +QtProfileSelectionDialog::~QtProfileSelectionDialog() { + controller_navigation->UnloadController(); +}; + +int QtProfileSelectionDialog::exec() { + // Skip profile selection when there's only one. + if (profile_manager.GetUserCount() == 1) { + user_index = 0; + return QDialog::Accepted; + } + return QDialog::exec(); +} + +void QtProfileSelectionDialog::accept() { + QDialog::accept(); +} + +void QtProfileSelectionDialog::reject() { + user_index = 0; + QDialog::reject(); +} + +int QtProfileSelectionDialog::GetIndex() const { + return user_index; +} + +void QtProfileSelectionDialog::SelectUser(const QModelIndex& index) { + user_index = index.row(); +} + +void QtProfileSelectionDialog::SetWindowTitle( + const Core::Frontend::ProfileSelectParameters& parameters) { + using Service::AM::Frontend::UiMode; + switch (parameters.mode) { + case UiMode::UserCreator: + case UiMode::UserCreatorForStarter: + setWindowTitle(tr("Profile Creator")); + return; + case UiMode::EnsureNetworkServiceAccountAvailable: + setWindowTitle(tr("Profile Selector")); + return; + case UiMode::UserIconEditor: + setWindowTitle(tr("Profile Icon Editor")); + return; + case UiMode::UserNicknameEditor: + setWindowTitle(tr("Profile Nickname Editor")); + return; + case UiMode::NintendoAccountAuthorizationRequestContext: + case UiMode::IntroduceExternalNetworkServiceAccount: + case UiMode::IntroduceExternalNetworkServiceAccountForRegistration: + case UiMode::NintendoAccountNnidLinker: + case UiMode::LicenseRequirementsForNetworkService: + case UiMode::LicenseRequirementsForNetworkServiceWithUserContextImpl: + case UiMode::UserCreatorForImmediateNaLoginTest: + case UiMode::UserQualificationPromoter: + case UiMode::UserSelector: + default: + setWindowTitle(tr("Profile Selector")); + } +} + +void QtProfileSelectionDialog::SetDialogPurpose( + const Core::Frontend::ProfileSelectParameters& parameters) { + using Service::AM::Frontend::UserSelectionPurpose; + + switch (parameters.purpose) { + case UserSelectionPurpose::GameCardRegistration: + instruction_label->setText(tr("Who will receive the points?")); + return; + case UserSelectionPurpose::EShopLaunch: + instruction_label->setText(tr("Who is using Nintendo eShop?")); + return; + case UserSelectionPurpose::EShopItemShow: + instruction_label->setText(tr("Who is making this purchase?")); + return; + case UserSelectionPurpose::PicturePost: + instruction_label->setText(tr("Who is posting?")); + return; + case UserSelectionPurpose::NintendoAccountLinkage: + instruction_label->setText(tr("Select a user to link to a Nintendo Account.")); + return; + case UserSelectionPurpose::SettingsUpdate: + instruction_label->setText(tr("Change settings for which user?")); + return; + case UserSelectionPurpose::SaveDataDeletion: + instruction_label->setText(tr("Format data for which user?")); + return; + case UserSelectionPurpose::UserMigration: + instruction_label->setText(tr("Which user will be transferred to another console?")); + return; + case UserSelectionPurpose::SaveDataTransfer: + instruction_label->setText(tr("Send save data for which user?")); + return; + case UserSelectionPurpose::General: + default: + instruction_label->setText(tr("Select a user:")); + return; + } +} + +QtProfileSelector::QtProfileSelector(GMainWindow& parent) { + connect(this, &QtProfileSelector::MainWindowSelectProfile, &parent, + &GMainWindow::ProfileSelectorSelectProfile, Qt::QueuedConnection); + connect(this, &QtProfileSelector::MainWindowRequestExit, &parent, + &GMainWindow::ProfileSelectorRequestExit, Qt::QueuedConnection); + connect(&parent, &GMainWindow::ProfileSelectorFinishedSelection, this, + &QtProfileSelector::MainWindowFinishedSelection, Qt::DirectConnection); +} + +QtProfileSelector::~QtProfileSelector() = default; + +void QtProfileSelector::Close() const { + callback = {}; + emit MainWindowRequestExit(); +} + +void QtProfileSelector::SelectProfile( + SelectProfileCallback callback_, + const Core::Frontend::ProfileSelectParameters& parameters) const { + callback = std::move(callback_); + emit MainWindowSelectProfile(parameters); +} + +void QtProfileSelector::MainWindowFinishedSelection(std::optional uuid) { + if (callback) { + callback(uuid); + } +} diff --git a/src/sudachi/applets/qt_profile_select.h b/src/sudachi/applets/qt_profile_select.h new file mode 100644 index 0000000..3d656a5 --- /dev/null +++ b/src/sudachi/applets/qt_profile_select.h @@ -0,0 +1,87 @@ +// SPDX-FileCopyrightText: Copyright 2018 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include +#include +#include "core/frontend/applets/profile_select.h" + +class ControllerNavigation; +class GMainWindow; +class QDialogButtonBox; +class QGraphicsScene; +class QLabel; +class QScrollArea; +class QStandardItem; +class QStandardItemModel; +class QTreeView; +class QVBoxLayout; + +namespace Core { +class System; +} + +namespace Service::Account { +class ProfileManager; +} + +class QtProfileSelectionDialog final : public QDialog { + Q_OBJECT + +public: + explicit QtProfileSelectionDialog(Core::System& system, QWidget* parent, + const Core::Frontend::ProfileSelectParameters& parameters); + ~QtProfileSelectionDialog() override; + + int exec() override; + void accept() override; + void reject() override; + + int GetIndex() const; + +private: + void SelectUser(const QModelIndex& index); + + void SetWindowTitle(const Core::Frontend::ProfileSelectParameters& parameters); + void SetDialogPurpose(const Core::Frontend::ProfileSelectParameters& parameters); + + int user_index = 0; + + QVBoxLayout* layout; + QTreeView* tree_view; + QStandardItemModel* item_model; + QGraphicsScene* scene; + + std::vector> list_items; + + QVBoxLayout* outer_layout; + QLabel* instruction_label; + QScrollArea* scroll_area; + QDialogButtonBox* buttons; + + Service::Account::ProfileManager& profile_manager; + ControllerNavigation* controller_navigation = nullptr; +}; + +class QtProfileSelector final : public QObject, public Core::Frontend::ProfileSelectApplet { + Q_OBJECT + +public: + explicit QtProfileSelector(GMainWindow& parent); + ~QtProfileSelector() override; + + void Close() const override; + void SelectProfile(SelectProfileCallback callback_, + const Core::Frontend::ProfileSelectParameters& parameters) const override; + +signals: + void MainWindowSelectProfile(const Core::Frontend::ProfileSelectParameters& parameters) const; + void MainWindowRequestExit() const; + +private: + void MainWindowFinishedSelection(std::optional uuid); + + mutable SelectProfileCallback callback; +}; diff --git a/src/sudachi/applets/qt_software_keyboard.cpp b/src/sudachi/applets/qt_software_keyboard.cpp new file mode 100644 index 0000000..94931a2 --- /dev/null +++ b/src/sudachi/applets/qt_software_keyboard.cpp @@ -0,0 +1,1674 @@ +// SPDX-FileCopyrightText: Copyright 2021 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include +#include + +#include "common/logging/log.h" +#include "common/settings.h" +#include "common/string_util.h" +#include "core/core.h" +#include "hid_core/frontend/emulated_controller.h" +#include "hid_core/frontend/input_interpreter.h" +#include "hid_core/hid_core.h" +#include "hid_core/hid_types.h" +#include "ui_qt_software_keyboard.h" +#include "sudachi/applets/qt_software_keyboard.h" +#include "sudachi/main.h" +#include "sudachi/util/overlay_dialog.h" + +namespace { + +using namespace Service::AM::Frontend; + +constexpr float BASE_HEADER_FONT_SIZE = 23.0f; +constexpr float BASE_SUB_FONT_SIZE = 17.0f; +constexpr float BASE_EDITOR_FONT_SIZE = 26.0f; +constexpr float BASE_CHAR_BUTTON_FONT_SIZE = 28.0f; +constexpr float BASE_LABEL_BUTTON_FONT_SIZE = 18.0f; +constexpr float BASE_ICON_BUTTON_SIZE = 36.0f; +[[maybe_unused]] constexpr float BASE_WIDTH = 1280.0f; +constexpr float BASE_HEIGHT = 720.0f; + +} // Anonymous namespace + +QtSoftwareKeyboardDialog::QtSoftwareKeyboardDialog( + QWidget* parent, Core::System& system_, bool is_inline_, + Core::Frontend::KeyboardInitializeParameters initialize_parameters_) + : QDialog(parent), ui{std::make_unique()}, system{system_}, + is_inline{is_inline_}, initialize_parameters{std::move(initialize_parameters_)} { + ui->setupUi(this); + + setWindowFlags(Qt::Dialog | Qt::FramelessWindowHint | Qt::WindowTitleHint | + Qt::WindowSystemMenuHint | Qt::CustomizeWindowHint); + setWindowModality(Qt::WindowModal); + setAttribute(Qt::WA_DeleteOnClose); + setAttribute(Qt::WA_TranslucentBackground); + + keyboard_buttons = {{ + {{ + { + ui->button_1, + ui->button_2, + ui->button_3, + ui->button_4, + ui->button_5, + ui->button_6, + ui->button_7, + ui->button_8, + ui->button_9, + ui->button_0, + ui->button_minus, + ui->button_backspace, + }, + { + ui->button_q, + ui->button_w, + ui->button_e, + ui->button_r, + ui->button_t, + ui->button_y, + ui->button_u, + ui->button_i, + ui->button_o, + ui->button_p, + ui->button_slash, + ui->button_return, + }, + { + ui->button_a, + ui->button_s, + ui->button_d, + ui->button_f, + ui->button_g, + ui->button_h, + ui->button_j, + ui->button_k, + ui->button_l, + ui->button_colon, + ui->button_apostrophe, + ui->button_return, + }, + { + ui->button_z, + ui->button_x, + ui->button_c, + ui->button_v, + ui->button_b, + ui->button_n, + ui->button_m, + ui->button_comma, + ui->button_dot, + ui->button_question, + ui->button_exclamation, + ui->button_ok, + }, + { + ui->button_shift, + ui->button_shift, + ui->button_space, + ui->button_space, + ui->button_space, + ui->button_space, + ui->button_space, + ui->button_space, + ui->button_space, + ui->button_space, + ui->button_space, + ui->button_ok, + }, + }}, + {{ + { + ui->button_hash, + ui->button_left_bracket, + ui->button_right_bracket, + ui->button_dollar, + ui->button_percent, + ui->button_circumflex, + ui->button_ampersand, + ui->button_asterisk, + ui->button_left_parenthesis, + ui->button_right_parenthesis, + ui->button_underscore, + ui->button_backspace_shift, + }, + { + ui->button_q_shift, + ui->button_w_shift, + ui->button_e_shift, + ui->button_r_shift, + ui->button_t_shift, + ui->button_y_shift, + ui->button_u_shift, + ui->button_i_shift, + ui->button_o_shift, + ui->button_p_shift, + ui->button_at, + ui->button_return_shift, + }, + { + ui->button_a_shift, + ui->button_s_shift, + ui->button_d_shift, + ui->button_f_shift, + ui->button_g_shift, + ui->button_h_shift, + ui->button_j_shift, + ui->button_k_shift, + ui->button_l_shift, + ui->button_semicolon, + ui->button_quotation, + ui->button_return_shift, + }, + { + ui->button_z_shift, + ui->button_x_shift, + ui->button_c_shift, + ui->button_v_shift, + ui->button_b_shift, + ui->button_n_shift, + ui->button_m_shift, + ui->button_less_than, + ui->button_greater_than, + ui->button_plus, + ui->button_equal, + ui->button_ok_shift, + }, + { + ui->button_shift_shift, + ui->button_shift_shift, + ui->button_space_shift, + ui->button_space_shift, + ui->button_space_shift, + ui->button_space_shift, + ui->button_space_shift, + ui->button_space_shift, + ui->button_space_shift, + ui->button_space_shift, + ui->button_space_shift, + ui->button_ok_shift, + }, + }}, + }}; + + numberpad_buttons = {{ + { + ui->button_1_num, + ui->button_2_num, + ui->button_3_num, + ui->button_backspace_num, + }, + { + ui->button_4_num, + ui->button_5_num, + ui->button_6_num, + ui->button_ok_num, + }, + { + ui->button_7_num, + ui->button_8_num, + ui->button_9_num, + ui->button_ok_num, + }, + { + ui->button_left_optional_num, + ui->button_0_num, + ui->button_right_optional_num, + ui->button_ok_num, + }, + }}; + + all_buttons = { + ui->button_1, + ui->button_2, + ui->button_3, + ui->button_4, + ui->button_5, + ui->button_6, + ui->button_7, + ui->button_8, + ui->button_9, + ui->button_0, + ui->button_minus, + ui->button_backspace, + ui->button_q, + ui->button_w, + ui->button_e, + ui->button_r, + ui->button_t, + ui->button_y, + ui->button_u, + ui->button_i, + ui->button_o, + ui->button_p, + ui->button_slash, + ui->button_return, + ui->button_a, + ui->button_s, + ui->button_d, + ui->button_f, + ui->button_g, + ui->button_h, + ui->button_j, + ui->button_k, + ui->button_l, + ui->button_colon, + ui->button_apostrophe, + ui->button_z, + ui->button_x, + ui->button_c, + ui->button_v, + ui->button_b, + ui->button_n, + ui->button_m, + ui->button_comma, + ui->button_dot, + ui->button_question, + ui->button_exclamation, + ui->button_ok, + ui->button_shift, + ui->button_space, + ui->button_hash, + ui->button_left_bracket, + ui->button_right_bracket, + ui->button_dollar, + ui->button_percent, + ui->button_circumflex, + ui->button_ampersand, + ui->button_asterisk, + ui->button_left_parenthesis, + ui->button_right_parenthesis, + ui->button_underscore, + ui->button_backspace_shift, + ui->button_q_shift, + ui->button_w_shift, + ui->button_e_shift, + ui->button_r_shift, + ui->button_t_shift, + ui->button_y_shift, + ui->button_u_shift, + ui->button_i_shift, + ui->button_o_shift, + ui->button_p_shift, + ui->button_at, + ui->button_return_shift, + ui->button_a_shift, + ui->button_s_shift, + ui->button_d_shift, + ui->button_f_shift, + ui->button_g_shift, + ui->button_h_shift, + ui->button_j_shift, + ui->button_k_shift, + ui->button_l_shift, + ui->button_semicolon, + ui->button_quotation, + ui->button_z_shift, + ui->button_x_shift, + ui->button_c_shift, + ui->button_v_shift, + ui->button_b_shift, + ui->button_n_shift, + ui->button_m_shift, + ui->button_less_than, + ui->button_greater_than, + ui->button_plus, + ui->button_equal, + ui->button_ok_shift, + ui->button_shift_shift, + ui->button_space_shift, + ui->button_1_num, + ui->button_2_num, + ui->button_3_num, + ui->button_backspace_num, + ui->button_4_num, + ui->button_5_num, + ui->button_6_num, + ui->button_ok_num, + ui->button_7_num, + ui->button_8_num, + ui->button_9_num, + ui->button_left_optional_num, + ui->button_0_num, + ui->button_right_optional_num, + }; + + SetupMouseHover(); + + if (!initialize_parameters.ok_text.empty()) { + ui->button_ok->setText(QString::fromStdU16String(initialize_parameters.ok_text)); + } + + ui->label_header->setText(QString::fromStdU16String(initialize_parameters.header_text)); + ui->label_sub->setText(QString::fromStdU16String(initialize_parameters.sub_text)); + + ui->button_left_optional_num->setText(QChar{initialize_parameters.left_optional_symbol_key}); + ui->button_right_optional_num->setText(QChar{initialize_parameters.right_optional_symbol_key}); + + current_text = initialize_parameters.initial_text; + cursor_position = initialize_parameters.initial_cursor_position; + + SetTextDrawType(); + + for (auto* button : all_buttons) { + connect(button, &QPushButton::clicked, this, [this, button](bool) { + if (is_inline) { + InlineKeyboardButtonClicked(button); + } else { + NormalKeyboardButtonClicked(button); + } + }); + } + + // TODO (Morph): Remove this when InputInterpreter no longer relies on the HID backend + if (system.IsPoweredOn()) { + input_interpreter = std::make_unique(system); + } +} + +QtSoftwareKeyboardDialog::~QtSoftwareKeyboardDialog() { + StopInputThread(); +} + +void QtSoftwareKeyboardDialog::ShowNormalKeyboard(QPoint pos, QSize size) { + if (isVisible()) { + return; + } + + MoveAndResizeWindow(pos, size); + + SetKeyboardType(); + SetPasswordMode(); + SetControllerImage(); + DisableKeyboardButtons(); + SetBackspaceOkEnabled(); + + open(); +} + +void QtSoftwareKeyboardDialog::ShowTextCheckDialog( + Service::AM::Frontend::SwkbdTextCheckResult text_check_result, + std::u16string text_check_message) { + switch (text_check_result) { + case SwkbdTextCheckResult::Success: + case SwkbdTextCheckResult::Silent: + default: + break; + case SwkbdTextCheckResult::Failure: { + StopInputThread(); + + OverlayDialog dialog(this, system, QString{}, QString::fromStdU16String(text_check_message), + QString{}, tr("OK"), Qt::AlignCenter); + dialog.exec(); + + StartInputThread(); + break; + } + case SwkbdTextCheckResult::Confirm: { + StopInputThread(); + + OverlayDialog dialog(this, system, QString{}, QString::fromStdU16String(text_check_message), + tr("Cancel"), tr("OK"), Qt::AlignCenter); + if (dialog.exec() != QDialog::Accepted) { + StartInputThread(); + break; + } + + const auto text = ui->topOSK->currentIndex() == 1 ? ui->text_edit_osk->toPlainText() + : ui->line_edit_osk->text(); + auto text_str = Common::U16StringFromBuffer(text.utf16(), text.size()); + + emit SubmitNormalText(SwkbdResult::Ok, std::move(text_str), true); + break; + } + } +} + +void QtSoftwareKeyboardDialog::ShowInlineKeyboard( + Core::Frontend::InlineAppearParameters appear_parameters, QPoint pos, QSize size) { + MoveAndResizeWindow(pos, size); + + ui->topOSK->setStyleSheet(QStringLiteral("background: rgba(0, 0, 0, 0);")); + + ui->headerOSK->hide(); + ui->subOSK->hide(); + ui->inputOSK->hide(); + ui->charactersOSK->hide(); + ui->inputBoxOSK->hide(); + ui->charactersBoxOSK->hide(); + + initialize_parameters.max_text_length = appear_parameters.max_text_length; + initialize_parameters.min_text_length = appear_parameters.min_text_length; + initialize_parameters.type = appear_parameters.type; + initialize_parameters.key_disable_flags = appear_parameters.key_disable_flags; + initialize_parameters.enable_backspace_button = appear_parameters.enable_backspace_button; + initialize_parameters.enable_return_button = appear_parameters.enable_return_button; + initialize_parameters.disable_cancel_button = appear_parameters.disable_cancel_button; + + SetKeyboardType(); + SetControllerImage(); + DisableKeyboardButtons(); + SetBackspaceOkEnabled(); + + open(); +} + +void QtSoftwareKeyboardDialog::HideInlineKeyboard() { + StopInputThread(); + QDialog::hide(); +} + +void QtSoftwareKeyboardDialog::InlineTextChanged( + Core::Frontend::InlineTextParameters text_parameters) { + current_text = text_parameters.input_text; + cursor_position = text_parameters.cursor_position; + + SetBackspaceOkEnabled(); +} + +void QtSoftwareKeyboardDialog::ExitKeyboard() { + StopInputThread(); + QDialog::done(QDialog::Accepted); +} + +void QtSoftwareKeyboardDialog::open() { + QDialog::open(); + + row = 0; + column = 0; + + switch (bottom_osk_index) { + case BottomOSKIndex::LowerCase: + case BottomOSKIndex::UpperCase: { + const auto* const curr_button = + keyboard_buttons[static_cast(bottom_osk_index)][row][column]; + + // This is a workaround for setFocus() randomly not showing focus in the UI + QCursor::setPos(curr_button->mapToGlobal(curr_button->rect().center())); + break; + } + case BottomOSKIndex::NumberPad: { + const auto* const curr_button = numberpad_buttons[row][column]; + + // This is a workaround for setFocus() randomly not showing focus in the UI + QCursor::setPos(curr_button->mapToGlobal(curr_button->rect().center())); + break; + } + default: + break; + } + + StartInputThread(); +} + +void QtSoftwareKeyboardDialog::reject() { + // Pressing the ESC key in a dialog calls QDialog::reject(). + // We will override this behavior to the "Cancel" action on the software keyboard. + TranslateButtonPress(Core::HID::NpadButton::X); +} + +void QtSoftwareKeyboardDialog::keyPressEvent(QKeyEvent* event) { + if (!is_inline) { + QDialog::keyPressEvent(event); + return; + } + + const auto entered_key = event->key(); + + switch (entered_key) { + case Qt::Key_Escape: + QDialog::keyPressEvent(event); + return; + case Qt::Key_Backspace: + switch (bottom_osk_index) { + case BottomOSKIndex::LowerCase: + ui->button_backspace->click(); + break; + case BottomOSKIndex::UpperCase: + ui->button_backspace_shift->click(); + break; + case BottomOSKIndex::NumberPad: + ui->button_backspace_num->click(); + break; + default: + break; + } + return; + case Qt::Key_Return: + switch (bottom_osk_index) { + case BottomOSKIndex::LowerCase: + ui->button_ok->click(); + break; + case BottomOSKIndex::UpperCase: + ui->button_ok_shift->click(); + break; + case BottomOSKIndex::NumberPad: + ui->button_ok_num->click(); + break; + default: + break; + } + return; + case Qt::Key_Left: + MoveTextCursorDirection(Direction::Left); + return; + case Qt::Key_Right: + MoveTextCursorDirection(Direction::Right); + return; + default: + break; + } + + const auto entered_text = event->text(); + + if (entered_text.isEmpty()) { + return; + } + + InlineTextInsertString(Common::U16StringFromBuffer(entered_text.utf16(), entered_text.size())); +} + +void QtSoftwareKeyboardDialog::MoveAndResizeWindow(QPoint pos, QSize size) { + QDialog::move(pos); + QDialog::resize(size); + + // High DPI + const float dpi_scale = screen()->logicalDotsPerInch() / 96.0f; + + RescaleKeyboardElements(size.width(), size.height(), dpi_scale); +} + +void QtSoftwareKeyboardDialog::RescaleKeyboardElements(float width, float height, float dpi_scale) { + const auto header_font_size = BASE_HEADER_FONT_SIZE * (height / BASE_HEIGHT) / dpi_scale; + const auto sub_font_size = BASE_SUB_FONT_SIZE * (height / BASE_HEIGHT) / dpi_scale; + const auto editor_font_size = BASE_EDITOR_FONT_SIZE * (height / BASE_HEIGHT) / dpi_scale; + const auto char_button_font_size = + BASE_CHAR_BUTTON_FONT_SIZE * (height / BASE_HEIGHT) / dpi_scale; + const auto label_button_font_size = + BASE_LABEL_BUTTON_FONT_SIZE * (height / BASE_HEIGHT) / dpi_scale; + + QFont header_font(QStringLiteral("MS Shell Dlg 2"), header_font_size, QFont::Normal); + QFont sub_font(QStringLiteral("MS Shell Dlg 2"), sub_font_size, QFont::Normal); + QFont editor_font(QStringLiteral("MS Shell Dlg 2"), editor_font_size, QFont::Normal); + QFont char_button_font(QStringLiteral("MS Shell Dlg 2"), char_button_font_size, QFont::Normal); + QFont label_button_font(QStringLiteral("MS Shell Dlg 2"), label_button_font_size, + QFont::Normal); + + ui->label_header->setFont(header_font); + ui->label_sub->setFont(sub_font); + ui->line_edit_osk->setFont(editor_font); + ui->text_edit_osk->setFont(editor_font); + ui->label_characters->setFont(sub_font); + ui->label_characters_box->setFont(sub_font); + + ui->label_shift->setFont(label_button_font); + ui->label_shift_shift->setFont(label_button_font); + ui->label_cancel->setFont(label_button_font); + ui->label_cancel_shift->setFont(label_button_font); + ui->label_cancel_num->setFont(label_button_font); + ui->label_enter->setFont(label_button_font); + ui->label_enter_shift->setFont(label_button_font); + ui->label_enter_num->setFont(label_button_font); + + for (auto* button : all_buttons) { + if (button == ui->button_return || button == ui->button_return_shift) { + button->setFont(label_button_font); + continue; + } + + if (button == ui->button_space || button == ui->button_space_shift) { + button->setFont(label_button_font); + continue; + } + + if (button == ui->button_shift || button == ui->button_shift_shift) { + button->setFont(label_button_font); + button->setIconSize(QSize(BASE_ICON_BUTTON_SIZE, BASE_ICON_BUTTON_SIZE) * + (height / BASE_HEIGHT)); + continue; + } + + if (button == ui->button_backspace || button == ui->button_backspace_shift || + button == ui->button_backspace_num) { + button->setFont(label_button_font); + button->setIconSize(QSize(BASE_ICON_BUTTON_SIZE, BASE_ICON_BUTTON_SIZE) * + (height / BASE_HEIGHT)); + continue; + } + + if (button == ui->button_ok || button == ui->button_ok_shift || + button == ui->button_ok_num) { + button->setFont(label_button_font); + continue; + } + + button->setFont(char_button_font); + } +} + +void QtSoftwareKeyboardDialog::SetKeyboardType() { + switch (initialize_parameters.type) { + case SwkbdType::Normal: + case SwkbdType::Qwerty: + case SwkbdType::Unknown3: + case SwkbdType::Latin: + case SwkbdType::SimplifiedChinese: + case SwkbdType::TraditionalChinese: + case SwkbdType::Korean: + default: { + bottom_osk_index = BottomOSKIndex::LowerCase; + ui->bottomOSK->setCurrentIndex(static_cast(bottom_osk_index)); + + ui->verticalLayout_2->setStretch(0, 320); + ui->verticalLayout_2->setStretch(1, 400); + + ui->gridLineOSK->setRowStretch(5, 94); + ui->gridBoxOSK->setRowStretch(2, 81); + break; + } + case SwkbdType::NumberPad: { + bottom_osk_index = BottomOSKIndex::NumberPad; + ui->bottomOSK->setCurrentIndex(static_cast(bottom_osk_index)); + + ui->verticalLayout_2->setStretch(0, 370); + ui->verticalLayout_2->setStretch(1, 350); + + ui->gridLineOSK->setRowStretch(5, 144); + ui->gridBoxOSK->setRowStretch(2, 131); + break; + } + } +} + +void QtSoftwareKeyboardDialog::SetPasswordMode() { + switch (initialize_parameters.password_mode) { + case SwkbdPasswordMode::Disabled: + default: + ui->line_edit_osk->setEchoMode(QLineEdit::Normal); + break; + case SwkbdPasswordMode::Enabled: + ui->line_edit_osk->setEchoMode(QLineEdit::Password); + break; + } +} + +void QtSoftwareKeyboardDialog::SetTextDrawType() { + switch (initialize_parameters.text_draw_type) { + case SwkbdTextDrawType::Line: + case SwkbdTextDrawType::DownloadCode: { + ui->topOSK->setCurrentIndex(0); + + if (initialize_parameters.max_text_length <= 10) { + ui->gridLineOSK->setColumnStretch(0, 390); + ui->gridLineOSK->setColumnStretch(1, 500); + ui->gridLineOSK->setColumnStretch(2, 390); + } else { + ui->gridLineOSK->setColumnStretch(0, 130); + ui->gridLineOSK->setColumnStretch(1, 1020); + ui->gridLineOSK->setColumnStretch(2, 130); + } + + if (is_inline) { + return; + } + + connect(ui->line_edit_osk, &QLineEdit::textChanged, [this](const QString& changed_string) { + const auto is_valid = ValidateInputText(changed_string); + + const auto text_length = static_cast(changed_string.length()); + + ui->label_characters->setText(QStringLiteral("%1/%2") + .arg(text_length) + .arg(initialize_parameters.max_text_length)); + + ui->button_ok->setEnabled(is_valid); + ui->button_ok_shift->setEnabled(is_valid); + ui->button_ok_num->setEnabled(is_valid); + + ui->line_edit_osk->setFocus(); + }); + + connect(ui->line_edit_osk, &QLineEdit::cursorPositionChanged, + [this](int old_cursor_position, int new_cursor_position) { + ui->button_backspace->setEnabled( + initialize_parameters.enable_backspace_button && new_cursor_position > 0); + ui->button_backspace_shift->setEnabled( + initialize_parameters.enable_backspace_button && new_cursor_position > 0); + ui->button_backspace_num->setEnabled( + initialize_parameters.enable_backspace_button && new_cursor_position > 0); + + ui->line_edit_osk->setFocus(); + }); + + connect( + ui->line_edit_osk, &QLineEdit::returnPressed, this, + [this] { TranslateButtonPress(Core::HID::NpadButton::Plus); }, Qt::QueuedConnection); + + ui->line_edit_osk->setPlaceholderText( + QString::fromStdU16String(initialize_parameters.guide_text)); + ui->line_edit_osk->setText(QString::fromStdU16String(initialize_parameters.initial_text)); + ui->line_edit_osk->setMaxLength(initialize_parameters.max_text_length); + ui->line_edit_osk->setCursorPosition(initialize_parameters.initial_cursor_position); + + ui->label_characters->setText(QStringLiteral("%1/%2") + .arg(initialize_parameters.initial_text.size()) + .arg(initialize_parameters.max_text_length)); + break; + } + case SwkbdTextDrawType::Box: + default: { + ui->topOSK->setCurrentIndex(1); + + if (is_inline) { + return; + } + + connect(ui->text_edit_osk, &QTextEdit::textChanged, [this] { + if (static_cast(ui->text_edit_osk->toPlainText().length()) > + initialize_parameters.max_text_length) { + auto text_cursor = ui->text_edit_osk->textCursor(); + ui->text_edit_osk->setTextCursor(text_cursor); + text_cursor.deletePreviousChar(); + } + + const auto is_valid = ValidateInputText(ui->text_edit_osk->toPlainText()); + + const auto text_length = static_cast(ui->text_edit_osk->toPlainText().length()); + + ui->label_characters_box->setText(QStringLiteral("%1/%2") + .arg(text_length) + .arg(initialize_parameters.max_text_length)); + + ui->button_ok->setEnabled(is_valid); + ui->button_ok_shift->setEnabled(is_valid); + ui->button_ok_num->setEnabled(is_valid); + + ui->text_edit_osk->setFocus(); + }); + + connect(ui->text_edit_osk, &QTextEdit::cursorPositionChanged, [this] { + const auto new_cursor_position = ui->text_edit_osk->textCursor().position(); + + ui->button_backspace->setEnabled(initialize_parameters.enable_backspace_button && + new_cursor_position > 0); + ui->button_backspace_shift->setEnabled(initialize_parameters.enable_backspace_button && + new_cursor_position > 0); + ui->button_backspace_num->setEnabled(initialize_parameters.enable_backspace_button && + new_cursor_position > 0); + + ui->text_edit_osk->setFocus(); + }); + + ui->text_edit_osk->setPlaceholderText( + QString::fromStdU16String(initialize_parameters.guide_text)); + ui->text_edit_osk->setText(QString::fromStdU16String(initialize_parameters.initial_text)); + ui->text_edit_osk->moveCursor(initialize_parameters.initial_cursor_position == 0 + ? QTextCursor::Start + : QTextCursor::End); + + ui->label_characters_box->setText(QStringLiteral("%1/%2") + .arg(initialize_parameters.initial_text.size()) + .arg(initialize_parameters.max_text_length)); + break; + } + } +} + +void QtSoftwareKeyboardDialog::SetControllerImage() { + const auto* handheld = system.HIDCore().GetEmulatedController(Core::HID::NpadIdType::Handheld); + const auto* player_1 = system.HIDCore().GetEmulatedController(Core::HID::NpadIdType::Player1); + const auto controller_type = + handheld->IsConnected() ? handheld->GetNpadStyleIndex() : player_1->GetNpadStyleIndex(); + + const QString theme = [] { + if (QIcon::themeName().contains(QStringLiteral("dark")) || + QIcon::themeName().contains(QStringLiteral("midnight"))) { + return QStringLiteral("_dark"); + } else { + return QString{}; + } + }(); + + switch (controller_type) { + case Core::HID::NpadStyleIndex::Fullkey: + case Core::HID::NpadStyleIndex::GameCube: + ui->icon_controller->setStyleSheet( + QStringLiteral("image: url(:/overlay/controller_pro%1.png);").arg(theme)); + ui->icon_controller_shift->setStyleSheet( + QStringLiteral("image: url(:/overlay/controller_pro%1.png);").arg(theme)); + ui->icon_controller_num->setStyleSheet( + QStringLiteral("image: url(:/overlay/controller_pro%1.png);").arg(theme)); + break; + case Core::HID::NpadStyleIndex::JoyconDual: + ui->icon_controller->setStyleSheet( + QStringLiteral("image: url(:/overlay/controller_dual_joycon%1.png);").arg(theme)); + ui->icon_controller_shift->setStyleSheet( + QStringLiteral("image: url(:/overlay/controller_dual_joycon%1.png);").arg(theme)); + ui->icon_controller_num->setStyleSheet( + QStringLiteral("image: url(:/overlay/controller_dual_joycon%1.png);").arg(theme)); + break; + case Core::HID::NpadStyleIndex::JoyconLeft: + ui->icon_controller->setStyleSheet( + QStringLiteral("image: url(:/overlay/controller_single_joycon_left%1.png);") + .arg(theme)); + ui->icon_controller_shift->setStyleSheet( + QStringLiteral("image: url(:/overlay/controller_single_joycon_left%1.png);") + .arg(theme)); + ui->icon_controller_num->setStyleSheet( + QStringLiteral("image: url(:/overlay/controller_single_joycon_left%1.png);") + .arg(theme)); + break; + case Core::HID::NpadStyleIndex::JoyconRight: + ui->icon_controller->setStyleSheet( + QStringLiteral("image: url(:/overlay/controller_single_joycon_right%1.png);") + .arg(theme)); + ui->icon_controller_shift->setStyleSheet( + QStringLiteral("image: url(:/overlay/controller_single_joycon_right%1.png);") + .arg(theme)); + ui->icon_controller_num->setStyleSheet( + QStringLiteral("image: url(:/overlay/controller_single_joycon_right%1.png);") + .arg(theme)); + break; + case Core::HID::NpadStyleIndex::Handheld: + ui->icon_controller->setStyleSheet( + QStringLiteral("image: url(:/overlay/controller_handheld%1.png);").arg(theme)); + ui->icon_controller_shift->setStyleSheet( + QStringLiteral("image: url(:/overlay/controller_handheld%1.png);").arg(theme)); + ui->icon_controller_num->setStyleSheet( + QStringLiteral("image: url(:/overlay/controller_handheld%1.png);").arg(theme)); + break; + default: + break; + } +} + +void QtSoftwareKeyboardDialog::DisableKeyboardButtons() { + switch (bottom_osk_index) { + case BottomOSKIndex::LowerCase: + case BottomOSKIndex::UpperCase: + default: { + for (const auto& keys : keyboard_buttons) { + for (const auto& rows : keys) { + for (auto* button : rows) { + if (!button) { + continue; + } + + button->setEnabled(true); + } + } + } + + const auto& key_disable_flags = initialize_parameters.key_disable_flags; + + ui->button_space->setDisabled(key_disable_flags.space); + ui->button_space_shift->setDisabled(key_disable_flags.space); + + ui->button_at->setDisabled(key_disable_flags.at || key_disable_flags.username); + + ui->button_percent->setDisabled(key_disable_flags.percent || key_disable_flags.username); + + ui->button_slash->setDisabled(key_disable_flags.slash); + + ui->button_1->setDisabled(key_disable_flags.numbers); + ui->button_2->setDisabled(key_disable_flags.numbers); + ui->button_3->setDisabled(key_disable_flags.numbers); + ui->button_4->setDisabled(key_disable_flags.numbers); + ui->button_5->setDisabled(key_disable_flags.numbers); + ui->button_6->setDisabled(key_disable_flags.numbers); + ui->button_7->setDisabled(key_disable_flags.numbers); + ui->button_8->setDisabled(key_disable_flags.numbers); + ui->button_9->setDisabled(key_disable_flags.numbers); + ui->button_0->setDisabled(key_disable_flags.numbers); + + ui->button_return->setEnabled(initialize_parameters.enable_return_button); + ui->button_return_shift->setEnabled(initialize_parameters.enable_return_button); + break; + } + case BottomOSKIndex::NumberPad: { + for (const auto& rows : numberpad_buttons) { + for (auto* button : rows) { + if (!button) { + continue; + } + + button->setEnabled(true); + } + } + + const auto enable_left_optional = initialize_parameters.left_optional_symbol_key != '\0'; + const auto enable_right_optional = initialize_parameters.right_optional_symbol_key != '\0'; + + ui->button_left_optional_num->setEnabled(enable_left_optional); + ui->button_left_optional_num->setVisible(enable_left_optional); + + ui->button_right_optional_num->setEnabled(enable_right_optional); + ui->button_right_optional_num->setVisible(enable_right_optional); + break; + } + } +} + +void QtSoftwareKeyboardDialog::SetBackspaceOkEnabled() { + if (is_inline) { + ui->button_ok->setEnabled(current_text.size() >= initialize_parameters.min_text_length); + ui->button_ok_shift->setEnabled(current_text.size() >= + initialize_parameters.min_text_length); + ui->button_ok_num->setEnabled(current_text.size() >= initialize_parameters.min_text_length); + + ui->button_backspace->setEnabled(initialize_parameters.enable_backspace_button && + cursor_position > 0); + ui->button_backspace_shift->setEnabled(initialize_parameters.enable_backspace_button && + cursor_position > 0); + ui->button_backspace_num->setEnabled(initialize_parameters.enable_backspace_button && + cursor_position > 0); + } else { + const auto text_length = [this] { + if (ui->topOSK->currentIndex() == 1) { + return static_cast(ui->text_edit_osk->toPlainText().length()); + } else { + return static_cast(ui->line_edit_osk->text().length()); + } + }(); + + const auto normal_cursor_position = [this] { + if (ui->topOSK->currentIndex() == 1) { + return ui->text_edit_osk->textCursor().position(); + } else { + return ui->line_edit_osk->cursorPosition(); + } + }(); + + ui->button_ok->setEnabled(text_length >= initialize_parameters.min_text_length); + ui->button_ok_shift->setEnabled(text_length >= initialize_parameters.min_text_length); + ui->button_ok_num->setEnabled(text_length >= initialize_parameters.min_text_length); + + ui->button_backspace->setEnabled(initialize_parameters.enable_backspace_button && + normal_cursor_position > 0); + ui->button_backspace_shift->setEnabled(initialize_parameters.enable_backspace_button && + normal_cursor_position > 0); + ui->button_backspace_num->setEnabled(initialize_parameters.enable_backspace_button && + normal_cursor_position > 0); + } +} + +bool QtSoftwareKeyboardDialog::ValidateInputText(const QString& input_text) { + const auto& key_disable_flags = initialize_parameters.key_disable_flags; + + const auto input_text_length = static_cast(input_text.length()); + + if (input_text_length < initialize_parameters.min_text_length || + input_text_length > initialize_parameters.max_text_length) { + return false; + } + + if (key_disable_flags.space && input_text.contains(QLatin1Char{' '})) { + return false; + } + + if ((key_disable_flags.at || key_disable_flags.username) && + input_text.contains(QLatin1Char{'@'})) { + return false; + } + + if ((key_disable_flags.percent || key_disable_flags.username) && + input_text.contains(QLatin1Char{'%'})) { + return false; + } + + if (key_disable_flags.slash && input_text.contains(QLatin1Char{'/'})) { + return false; + } + + if ((key_disable_flags.backslash || key_disable_flags.username) && + input_text.contains(QLatin1Char('\\'))) { + return false; + } + + if (key_disable_flags.numbers && + std::any_of(input_text.begin(), input_text.end(), [](QChar c) { return c.isDigit(); })) { + return false; + } + + if (bottom_osk_index == BottomOSKIndex::NumberPad && + std::any_of(input_text.begin(), input_text.end(), [this](QChar c) { + return !c.isDigit() && c != QChar{initialize_parameters.left_optional_symbol_key} && + c != QChar{initialize_parameters.right_optional_symbol_key}; + })) { + return false; + } + + return true; +} + +void QtSoftwareKeyboardDialog::ChangeBottomOSKIndex() { + switch (bottom_osk_index) { + case BottomOSKIndex::LowerCase: + bottom_osk_index = BottomOSKIndex::UpperCase; + ui->bottomOSK->setCurrentIndex(static_cast(bottom_osk_index)); + + ui->button_shift_shift->setStyleSheet( + QStringLiteral("image: url(:/overlay/osk_button_shift_lock_off.png);" + "\nimage-position: left;")); + + ui->button_shift_shift->setIconSize(ui->button_shift->iconSize()); + ui->button_backspace_shift->setIconSize(ui->button_backspace->iconSize()); + break; + case BottomOSKIndex::UpperCase: + if (caps_lock_enabled) { + caps_lock_enabled = false; + + ui->button_shift_shift->setStyleSheet( + QStringLiteral("image: url(:/overlay/osk_button_shift_lock_off.png);" + "\nimage-position: left;")); + + ui->button_shift_shift->setIconSize(ui->button_shift->iconSize()); + ui->button_backspace_shift->setIconSize(ui->button_backspace->iconSize()); + + ui->label_shift_shift->setText(QStringLiteral("Caps Lock")); + + bottom_osk_index = BottomOSKIndex::LowerCase; + ui->bottomOSK->setCurrentIndex(static_cast(bottom_osk_index)); + } else { + caps_lock_enabled = true; + + ui->button_shift_shift->setStyleSheet( + QStringLiteral("image: url(:/overlay/osk_button_shift_lock_on.png);" + "\nimage-position: left;")); + + ui->button_shift_shift->setIconSize(ui->button_shift->iconSize()); + ui->button_backspace_shift->setIconSize(ui->button_backspace->iconSize()); + + ui->label_shift_shift->setText(QStringLiteral("Caps Lock Off")); + } + break; + case BottomOSKIndex::NumberPad: + default: + break; + } +} + +void QtSoftwareKeyboardDialog::NormalKeyboardButtonClicked(QPushButton* button) { + if (button == ui->button_ampersand) { + if (ui->topOSK->currentIndex() == 1) { + ui->text_edit_osk->insertPlainText(QStringLiteral("&")); + } else { + ui->line_edit_osk->insert(QStringLiteral("&")); + } + return; + } + + if (button == ui->button_return || button == ui->button_return_shift) { + if (ui->topOSK->currentIndex() == 1) { + ui->text_edit_osk->insertPlainText(QStringLiteral("\n")); + } else { + ui->line_edit_osk->insert(QStringLiteral("\n")); + } + return; + } + + if (button == ui->button_space || button == ui->button_space_shift) { + if (ui->topOSK->currentIndex() == 1) { + ui->text_edit_osk->insertPlainText(QStringLiteral(" ")); + } else { + ui->line_edit_osk->insert(QStringLiteral(" ")); + } + return; + } + + if (button == ui->button_shift || button == ui->button_shift_shift) { + ChangeBottomOSKIndex(); + return; + } + + if (button == ui->button_backspace || button == ui->button_backspace_shift || + button == ui->button_backspace_num) { + if (ui->topOSK->currentIndex() == 1) { + auto text_cursor = ui->text_edit_osk->textCursor(); + ui->text_edit_osk->setTextCursor(text_cursor); + text_cursor.deletePreviousChar(); + } else { + ui->line_edit_osk->backspace(); + } + return; + } + + if (button == ui->button_ok || button == ui->button_ok_shift || button == ui->button_ok_num) { + const auto text = ui->topOSK->currentIndex() == 1 ? ui->text_edit_osk->toPlainText() + : ui->line_edit_osk->text(); + auto text_str = Common::U16StringFromBuffer(text.utf16(), text.size()); + + emit SubmitNormalText(SwkbdResult::Ok, std::move(text_str)); + return; + } + + if (ui->topOSK->currentIndex() == 1) { + ui->text_edit_osk->insertPlainText(button->text()); + } else { + ui->line_edit_osk->insert(button->text()); + } + + // Revert the keyboard to lowercase if the shift key is active. + if (bottom_osk_index == BottomOSKIndex::UpperCase && !caps_lock_enabled) { + // This is set to true since ChangeBottomOSKIndex will change bottom_osk_index to LowerCase + // if bottom_osk_index is UpperCase and caps_lock_enabled is true. + caps_lock_enabled = true; + ChangeBottomOSKIndex(); + } +} + +void QtSoftwareKeyboardDialog::InlineKeyboardButtonClicked(QPushButton* button) { + if (!button->isEnabled()) { + return; + } + + if (button == ui->button_ampersand) { + InlineTextInsertString(u"&"); + return; + } + + if (button == ui->button_return || button == ui->button_return_shift) { + InlineTextInsertString(u"\n"); + return; + } + + if (button == ui->button_space || button == ui->button_space_shift) { + InlineTextInsertString(u" "); + return; + } + + if (button == ui->button_shift || button == ui->button_shift_shift) { + ChangeBottomOSKIndex(); + return; + } + + if (button == ui->button_backspace || button == ui->button_backspace_shift || + button == ui->button_backspace_num) { + if (cursor_position <= 0 || current_text.empty()) { + cursor_position = 0; + return; + } + + --cursor_position; + + current_text.erase(cursor_position, 1); + + SetBackspaceOkEnabled(); + + emit SubmitInlineText(SwkbdReplyType::ChangedString, current_text, cursor_position); + return; + } + + if (button == ui->button_ok || button == ui->button_ok_shift || button == ui->button_ok_num) { + emit SubmitInlineText(SwkbdReplyType::DecidedEnter, current_text, cursor_position); + return; + } + + const auto button_text = button->text(); + InlineTextInsertString(Common::U16StringFromBuffer(button_text.utf16(), button_text.size())); + + // Revert the keyboard to lowercase if the shift key is active. + if (bottom_osk_index == BottomOSKIndex::UpperCase && !caps_lock_enabled) { + // This is set to true since ChangeBottomOSKIndex will change bottom_osk_index to LowerCase + // if bottom_osk_index is UpperCase and caps_lock_enabled is true. + caps_lock_enabled = true; + ChangeBottomOSKIndex(); + } +} + +void QtSoftwareKeyboardDialog::InlineTextInsertString(std::u16string_view string) { + if ((current_text.size() + string.size()) > initialize_parameters.max_text_length) { + return; + } + + current_text.insert(cursor_position, string); + + cursor_position += static_cast(string.size()); + + SetBackspaceOkEnabled(); + + emit SubmitInlineText(SwkbdReplyType::ChangedString, current_text, cursor_position); +} + +void QtSoftwareKeyboardDialog::SetupMouseHover() { + // setFocus() has a bug where continuously changing focus will cause the focus UI to + // mysteriously disappear. A workaround we have found is using the mouse to hover over + // the buttons to act in place of the button focus. As a result, we will have to set + // a blank cursor when hovering over all the buttons and set a no focus policy so the + // buttons do not stay in focus in addition to the mouse hover. + for (auto* button : all_buttons) { + button->setCursor(QCursor(Qt::BlankCursor)); + button->setFocusPolicy(Qt::NoFocus); + } +} + +template +void QtSoftwareKeyboardDialog::HandleButtonPressedOnce() { + const auto f = [this](Core::HID::NpadButton button) { + if (input_interpreter->IsButtonPressedOnce(button)) { + TranslateButtonPress(button); + } + }; + + (f(T), ...); +} + +template +void QtSoftwareKeyboardDialog::HandleButtonHold() { + const auto f = [this](Core::HID::NpadButton button) { + if (input_interpreter->IsButtonHeld(button)) { + TranslateButtonPress(button); + } + }; + + (f(T), ...); +} + +void QtSoftwareKeyboardDialog::TranslateButtonPress(Core::HID::NpadButton button) { + switch (button) { + case Core::HID::NpadButton::A: + switch (bottom_osk_index) { + case BottomOSKIndex::LowerCase: + case BottomOSKIndex::UpperCase: + keyboard_buttons[static_cast(bottom_osk_index)][row][column]->click(); + break; + case BottomOSKIndex::NumberPad: + numberpad_buttons[row][column]->click(); + break; + default: + break; + } + break; + case Core::HID::NpadButton::B: + switch (bottom_osk_index) { + case BottomOSKIndex::LowerCase: + ui->button_backspace->click(); + break; + case BottomOSKIndex::UpperCase: + ui->button_backspace_shift->click(); + break; + case BottomOSKIndex::NumberPad: + ui->button_backspace_num->click(); + break; + default: + break; + } + break; + case Core::HID::NpadButton::X: + if (is_inline) { + emit SubmitInlineText(SwkbdReplyType::DecidedCancel, current_text, cursor_position); + } else { + const auto text = ui->topOSK->currentIndex() == 1 ? ui->text_edit_osk->toPlainText() + : ui->line_edit_osk->text(); + auto text_str = Common::U16StringFromBuffer(text.utf16(), text.size()); + + emit SubmitNormalText(SwkbdResult::Cancel, std::move(text_str)); + } + break; + case Core::HID::NpadButton::Y: + switch (bottom_osk_index) { + case BottomOSKIndex::LowerCase: + ui->button_space->click(); + break; + case BottomOSKIndex::UpperCase: + ui->button_space_shift->click(); + break; + case BottomOSKIndex::NumberPad: + default: + break; + } + break; + case Core::HID::NpadButton::StickL: + case Core::HID::NpadButton::StickR: + switch (bottom_osk_index) { + case BottomOSKIndex::LowerCase: + ui->button_shift->click(); + break; + case BottomOSKIndex::UpperCase: + ui->button_shift_shift->click(); + break; + case BottomOSKIndex::NumberPad: + default: + break; + } + break; + case Core::HID::NpadButton::L: + MoveTextCursorDirection(Direction::Left); + break; + case Core::HID::NpadButton::R: + MoveTextCursorDirection(Direction::Right); + break; + case Core::HID::NpadButton::Plus: + switch (bottom_osk_index) { + case BottomOSKIndex::LowerCase: + ui->button_ok->click(); + break; + case BottomOSKIndex::UpperCase: + ui->button_ok_shift->click(); + break; + case BottomOSKIndex::NumberPad: + ui->button_ok_num->click(); + break; + default: + break; + } + break; + case Core::HID::NpadButton::Left: + case Core::HID::NpadButton::StickLLeft: + case Core::HID::NpadButton::StickRLeft: + MoveButtonDirection(Direction::Left); + break; + case Core::HID::NpadButton::Up: + case Core::HID::NpadButton::StickLUp: + case Core::HID::NpadButton::StickRUp: + MoveButtonDirection(Direction::Up); + break; + case Core::HID::NpadButton::Right: + case Core::HID::NpadButton::StickLRight: + case Core::HID::NpadButton::StickRRight: + MoveButtonDirection(Direction::Right); + break; + case Core::HID::NpadButton::Down: + case Core::HID::NpadButton::StickLDown: + case Core::HID::NpadButton::StickRDown: + MoveButtonDirection(Direction::Down); + break; + default: + break; + } +} + +void QtSoftwareKeyboardDialog::MoveButtonDirection(Direction direction) { + // Changes the row or column index depending on the direction. + auto move_direction = [this, direction](std::size_t max_rows, std::size_t max_columns) { + switch (direction) { + case Direction::Left: + column = (column + max_columns - 1) % max_columns; + break; + case Direction::Up: + row = (row + max_rows - 1) % max_rows; + break; + case Direction::Right: + column = (column + 1) % max_columns; + break; + case Direction::Down: + row = (row + 1) % max_rows; + break; + default: + break; + } + }; + + // Store the initial row and column. + const auto initial_row = row; + const auto initial_column = column; + + switch (bottom_osk_index) { + case BottomOSKIndex::LowerCase: + case BottomOSKIndex::UpperCase: { + const auto index = static_cast(bottom_osk_index); + + const auto* const prev_button = keyboard_buttons[index][row][column]; + move_direction(NUM_ROWS_NORMAL, NUM_COLUMNS_NORMAL); + auto* curr_button = keyboard_buttons[index][row][column]; + + while (!curr_button || !curr_button->isEnabled() || curr_button == prev_button) { + // If we returned back to where we started from, break the loop. + if (row == initial_row && column == initial_column) { + break; + } + + move_direction(NUM_ROWS_NORMAL, NUM_COLUMNS_NORMAL); + curr_button = keyboard_buttons[index][row][column]; + } + + // This is a workaround for setFocus() randomly not showing focus in the UI + QCursor::setPos(curr_button->mapToGlobal(curr_button->rect().center())); + break; + } + case BottomOSKIndex::NumberPad: { + const auto* const prev_button = numberpad_buttons[row][column]; + move_direction(NUM_ROWS_NUMPAD, NUM_COLUMNS_NUMPAD); + auto* curr_button = numberpad_buttons[row][column]; + + while (!curr_button || !curr_button->isEnabled() || curr_button == prev_button) { + // If we returned back to where we started from, break the loop. + if (row == initial_row && column == initial_column) { + break; + } + + move_direction(NUM_ROWS_NUMPAD, NUM_COLUMNS_NUMPAD); + curr_button = numberpad_buttons[row][column]; + } + + // This is a workaround for setFocus() randomly not showing focus in the UI + QCursor::setPos(curr_button->mapToGlobal(curr_button->rect().center())); + break; + } + default: + break; + } +} + +void QtSoftwareKeyboardDialog::MoveTextCursorDirection(Direction direction) { + switch (direction) { + case Direction::Left: + if (is_inline) { + if (cursor_position <= 0) { + cursor_position = 0; + } else { + --cursor_position; + emit SubmitInlineText(SwkbdReplyType::MovedCursor, current_text, cursor_position); + } + } else { + if (ui->topOSK->currentIndex() == 1) { + ui->text_edit_osk->moveCursor(QTextCursor::Left); + } else { + ui->line_edit_osk->setCursorPosition(ui->line_edit_osk->cursorPosition() - 1); + } + } + break; + case Direction::Right: + if (is_inline) { + if (cursor_position >= static_cast(current_text.size())) { + cursor_position = static_cast(current_text.size()); + } else { + ++cursor_position; + emit SubmitInlineText(SwkbdReplyType::MovedCursor, current_text, cursor_position); + } + } else { + if (ui->topOSK->currentIndex() == 1) { + ui->text_edit_osk->moveCursor(QTextCursor::Right); + } else { + ui->line_edit_osk->setCursorPosition(ui->line_edit_osk->cursorPosition() + 1); + } + } + break; + default: + break; + } +} + +void QtSoftwareKeyboardDialog::StartInputThread() { + if (input_thread_running) { + return; + } + + input_thread_running = true; + + input_thread = std::thread(&QtSoftwareKeyboardDialog::InputThread, this); +} + +void QtSoftwareKeyboardDialog::StopInputThread() { + input_thread_running = false; + + if (input_thread.joinable()) { + input_thread.join(); + } + + if (input_interpreter) { + input_interpreter->ResetButtonStates(); + } +} + +void QtSoftwareKeyboardDialog::InputThread() { + while (input_thread_running) { + input_interpreter->PollInput(); + + HandleButtonPressedOnce< + Core::HID::NpadButton::A, Core::HID::NpadButton::B, Core::HID::NpadButton::X, + Core::HID::NpadButton::Y, Core::HID::NpadButton::StickL, Core::HID::NpadButton::StickR, + Core::HID::NpadButton::L, Core::HID::NpadButton::R, Core::HID::NpadButton::Plus, + Core::HID::NpadButton::Left, Core::HID::NpadButton::Up, Core::HID::NpadButton::Right, + Core::HID::NpadButton::Down, Core::HID::NpadButton::StickLLeft, + Core::HID::NpadButton::StickLUp, Core::HID::NpadButton::StickLRight, + Core::HID::NpadButton::StickLDown, Core::HID::NpadButton::StickRLeft, + Core::HID::NpadButton::StickRUp, Core::HID::NpadButton::StickRRight, + Core::HID::NpadButton::StickRDown>(); + + HandleButtonHold(); + + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + } +} + +QtSoftwareKeyboard::QtSoftwareKeyboard(GMainWindow& main_window) { + connect(this, &QtSoftwareKeyboard::MainWindowInitializeKeyboard, &main_window, + &GMainWindow::SoftwareKeyboardInitialize, Qt::QueuedConnection); + connect(this, &QtSoftwareKeyboard::MainWindowShowNormalKeyboard, &main_window, + &GMainWindow::SoftwareKeyboardShowNormal, Qt::QueuedConnection); + connect(this, &QtSoftwareKeyboard::MainWindowShowTextCheckDialog, &main_window, + &GMainWindow::SoftwareKeyboardShowTextCheck, Qt::QueuedConnection); + connect(this, &QtSoftwareKeyboard::MainWindowShowInlineKeyboard, &main_window, + &GMainWindow::SoftwareKeyboardShowInline, Qt::QueuedConnection); + connect(this, &QtSoftwareKeyboard::MainWindowHideInlineKeyboard, &main_window, + &GMainWindow::SoftwareKeyboardHideInline, Qt::QueuedConnection); + connect(this, &QtSoftwareKeyboard::MainWindowInlineTextChanged, &main_window, + &GMainWindow::SoftwareKeyboardInlineTextChanged, Qt::QueuedConnection); + connect(this, &QtSoftwareKeyboard::MainWindowExitKeyboard, &main_window, + &GMainWindow::SoftwareKeyboardExit, Qt::QueuedConnection); + connect(&main_window, &GMainWindow::SoftwareKeyboardSubmitNormalText, this, + &QtSoftwareKeyboard::SubmitNormalText, Qt::QueuedConnection); + connect(&main_window, &GMainWindow::SoftwareKeyboardSubmitInlineText, this, + &QtSoftwareKeyboard::SubmitInlineText, Qt::QueuedConnection); +} + +QtSoftwareKeyboard::~QtSoftwareKeyboard() = default; + +void QtSoftwareKeyboard::InitializeKeyboard( + bool is_inline, Core::Frontend::KeyboardInitializeParameters initialize_parameters, + SubmitNormalCallback submit_normal_callback_, SubmitInlineCallback submit_inline_callback_) { + if (is_inline) { + submit_inline_callback = std::move(submit_inline_callback_); + } else { + submit_normal_callback = std::move(submit_normal_callback_); + } + + LOG_INFO(Service_AM, + "\nKeyboardInitializeParameters:" + "\nok_text={}" + "\nheader_text={}" + "\nsub_text={}" + "\nguide_text={}" + "\ninitial_text={}" + "\nmax_text_length={}" + "\nmin_text_length={}" + "\ninitial_cursor_position={}" + "\ntype={}" + "\npassword_mode={}" + "\ntext_draw_type={}" + "\nkey_disable_flags={}" + "\nuse_blur_background={}" + "\nenable_backspace_button={}" + "\nenable_return_button={}" + "\ndisable_cancel_button={}", + Common::UTF16ToUTF8(initialize_parameters.ok_text), + Common::UTF16ToUTF8(initialize_parameters.header_text), + Common::UTF16ToUTF8(initialize_parameters.sub_text), + Common::UTF16ToUTF8(initialize_parameters.guide_text), + Common::UTF16ToUTF8(initialize_parameters.initial_text), + initialize_parameters.max_text_length, initialize_parameters.min_text_length, + initialize_parameters.initial_cursor_position, initialize_parameters.type, + initialize_parameters.password_mode, initialize_parameters.text_draw_type, + initialize_parameters.key_disable_flags.raw, initialize_parameters.use_blur_background, + initialize_parameters.enable_backspace_button, + initialize_parameters.enable_return_button, + initialize_parameters.disable_cancel_button); + + emit MainWindowInitializeKeyboard(is_inline, std::move(initialize_parameters)); +} + +void QtSoftwareKeyboard::ShowNormalKeyboard() const { + emit MainWindowShowNormalKeyboard(); +} + +void QtSoftwareKeyboard::ShowTextCheckDialog( + Service::AM::Frontend::SwkbdTextCheckResult text_check_result, + std::u16string text_check_message) const { + emit MainWindowShowTextCheckDialog(text_check_result, std::move(text_check_message)); +} + +void QtSoftwareKeyboard::ShowInlineKeyboard( + Core::Frontend::InlineAppearParameters appear_parameters) const { + LOG_INFO(Service_AM, + "\nInlineAppearParameters:" + "\nmax_text_length={}" + "\nmin_text_length={}" + "\nkey_top_scale_x={}" + "\nkey_top_scale_y={}" + "\nkey_top_translate_x={}" + "\nkey_top_translate_y={}" + "\ntype={}" + "\nkey_disable_flags={}" + "\nkey_top_as_floating={}" + "\nenable_backspace_button={}" + "\nenable_return_button={}" + "\ndisable_cancel_button={}", + appear_parameters.max_text_length, appear_parameters.min_text_length, + appear_parameters.key_top_scale_x, appear_parameters.key_top_scale_y, + appear_parameters.key_top_translate_x, appear_parameters.key_top_translate_y, + appear_parameters.type, appear_parameters.key_disable_flags.raw, + appear_parameters.key_top_as_floating, appear_parameters.enable_backspace_button, + appear_parameters.enable_return_button, appear_parameters.disable_cancel_button); + + emit MainWindowShowInlineKeyboard(std::move(appear_parameters)); +} + +void QtSoftwareKeyboard::HideInlineKeyboard() const { + emit MainWindowHideInlineKeyboard(); +} + +void QtSoftwareKeyboard::InlineTextChanged( + Core::Frontend::InlineTextParameters text_parameters) const { + LOG_INFO(Service_AM, + "\nInlineTextParameters:" + "\ninput_text={}" + "\ncursor_position={}", + Common::UTF16ToUTF8(text_parameters.input_text), text_parameters.cursor_position); + + emit MainWindowInlineTextChanged(std::move(text_parameters)); +} + +void QtSoftwareKeyboard::ExitKeyboard() const { + emit MainWindowExitKeyboard(); +} + +void QtSoftwareKeyboard::SubmitNormalText(Service::AM::Frontend::SwkbdResult result, + std::u16string submitted_text, bool confirmed) const { + submit_normal_callback(result, submitted_text, confirmed); +} + +void QtSoftwareKeyboard::SubmitInlineText(Service::AM::Frontend::SwkbdReplyType reply_type, + std::u16string submitted_text, + s32 cursor_position) const { + submit_inline_callback(reply_type, submitted_text, cursor_position); +} diff --git a/src/sudachi/applets/qt_software_keyboard.h b/src/sudachi/applets/qt_software_keyboard.h new file mode 100644 index 0000000..91e8997 --- /dev/null +++ b/src/sudachi/applets/qt_software_keyboard.h @@ -0,0 +1,287 @@ +// SPDX-FileCopyrightText: Copyright 2021 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include +#include +#include + +#include +#include + +#include "core/frontend/applets/software_keyboard.h" + +class InputInterpreter; + +namespace Core { +class System; +} + +namespace Core::HID { +enum class NpadButton : u64; +} + +namespace Ui { +class QtSoftwareKeyboardDialog; +} + +class GMainWindow; + +class QtSoftwareKeyboardDialog final : public QDialog { + Q_OBJECT + +public: + QtSoftwareKeyboardDialog(QWidget* parent, Core::System& system_, bool is_inline_, + Core::Frontend::KeyboardInitializeParameters initialize_parameters_); + ~QtSoftwareKeyboardDialog() override; + + void ShowNormalKeyboard(QPoint pos, QSize size); + + void ShowTextCheckDialog(Service::AM::Frontend::SwkbdTextCheckResult text_check_result, + std::u16string text_check_message); + + void ShowInlineKeyboard(Core::Frontend::InlineAppearParameters appear_parameters, QPoint pos, + QSize size); + + void HideInlineKeyboard(); + + void InlineTextChanged(Core::Frontend::InlineTextParameters text_parameters); + + void ExitKeyboard(); + +signals: + void SubmitNormalText(Service::AM::Frontend::SwkbdResult result, std::u16string submitted_text, + bool confirmed = false) const; + + void SubmitInlineText(Service::AM::Frontend::SwkbdReplyType reply_type, + std::u16string submitted_text, s32 cursor_position) const; + +public slots: + void open() override; + void reject() override; + +protected: + /// We override the keyPressEvent for inputting text into the inline software keyboard. + void keyPressEvent(QKeyEvent* event) override; + +private: + enum class Direction { + Left, + Up, + Right, + Down, + }; + + enum class BottomOSKIndex { + LowerCase, + UpperCase, + NumberPad, + }; + + /** + * Moves and resizes the window to a specified position and size. + * + * @param pos Top-left window position + * @param size Window size + */ + void MoveAndResizeWindow(QPoint pos, QSize size); + + /** + * Rescales all keyboard elements to account for High DPI displays. + * + * @param width Window width + * @param height Window height + * @param dpi_scale Display scaling factor + */ + void RescaleKeyboardElements(float width, float height, float dpi_scale); + + /// Sets the keyboard type based on initialize_parameters. + void SetKeyboardType(); + + /// Sets the password mode based on initialize_parameters. + void SetPasswordMode(); + + /// Sets the text draw type based on initialize_parameters. + void SetTextDrawType(); + + /// Sets the controller image at the bottom left of the software keyboard. + void SetControllerImage(); + + /// Disables buttons based on initialize_parameters. + void DisableKeyboardButtons(); + + /// Changes whether the backspace or/and ok buttons should be enabled or disabled. + void SetBackspaceOkEnabled(); + + /** + * Validates the input text sent in based on the parameters in initialize_parameters. + * + * @param input_text Input text + * + * @returns True if the input text is valid, false otherwise. + */ + bool ValidateInputText(const QString& input_text); + + /// Switches between LowerCase and UpperCase (Shift and Caps Lock) + void ChangeBottomOSKIndex(); + + /// Processes a keyboard button click from the UI as normal keyboard input. + void NormalKeyboardButtonClicked(QPushButton* button); + + /// Processes a keyboard button click from the UI as inline keyboard input. + void InlineKeyboardButtonClicked(QPushButton* button); + + /** + * Inserts a string of arbitrary length into the current_text at the current cursor position. + * This is only used for the inline software keyboard. + */ + void InlineTextInsertString(std::u16string_view string); + + /// Setup the mouse hover workaround for "focusing" buttons. This should only be called once. + void SetupMouseHover(); + + /** + * Handles button presses and converts them into keyboard input. + * + * @tparam HIDButton The list of buttons that can be converted into keyboard input. + */ + template + void HandleButtonPressedOnce(); + + /** + * Handles button holds and converts them into keyboard input. + * + * @tparam HIDButton The list of buttons that can be converted into keyboard input. + */ + template + void HandleButtonHold(); + + /** + * Translates a button press to focus or click a keyboard button. + * + * @param button The button press to process. + */ + void TranslateButtonPress(Core::HID::NpadButton button); + + /** + * Moves the focus of a button in a certain direction. + * + * @param direction The direction to move. + */ + void MoveButtonDirection(Direction direction); + + /** + * Moves the text cursor in a certain direction. + * + * @param direction The direction to move. + */ + void MoveTextCursorDirection(Direction direction); + + void StartInputThread(); + void StopInputThread(); + + /// The thread where input is being polled and processed. + void InputThread(); + + std::unique_ptr ui; + + Core::System& system; + + // True if it is the inline software keyboard. + bool is_inline; + + // Common software keyboard initialize parameters. + Core::Frontend::KeyboardInitializeParameters initialize_parameters; + + // Used only by the inline software keyboard since the QLineEdit or QTextEdit is hidden. + std::u16string current_text; + s32 cursor_position{0}; + + static constexpr std::size_t NUM_ROWS_NORMAL = 5; + static constexpr std::size_t NUM_COLUMNS_NORMAL = 12; + static constexpr std::size_t NUM_ROWS_NUMPAD = 4; + static constexpr std::size_t NUM_COLUMNS_NUMPAD = 4; + + // Stores the normal keyboard layout. + std::array, NUM_ROWS_NORMAL>, 2> + keyboard_buttons; + // Stores the numberpad keyboard layout. + std::array, NUM_ROWS_NUMPAD> numberpad_buttons; + + // Contains a set of all buttons used in keyboard_buttons and numberpad_buttons. + std::array all_buttons; + + std::size_t row{0}; + std::size_t column{0}; + + BottomOSKIndex bottom_osk_index{BottomOSKIndex::LowerCase}; + std::atomic caps_lock_enabled{false}; + + std::unique_ptr input_interpreter; + + std::thread input_thread; + + std::atomic input_thread_running{}; +}; + +class QtSoftwareKeyboard final : public QObject, public Core::Frontend::SoftwareKeyboardApplet { + Q_OBJECT + +public: + explicit QtSoftwareKeyboard(GMainWindow& parent); + ~QtSoftwareKeyboard() override; + + void Close() const override { + ExitKeyboard(); + } + + void InitializeKeyboard(bool is_inline, + Core::Frontend::KeyboardInitializeParameters initialize_parameters, + SubmitNormalCallback submit_normal_callback_, + SubmitInlineCallback submit_inline_callback_) override; + + void ShowNormalKeyboard() const override; + + void ShowTextCheckDialog(Service::AM::Frontend::SwkbdTextCheckResult text_check_result, + std::u16string text_check_message) const override; + + void ShowInlineKeyboard( + Core::Frontend::InlineAppearParameters appear_parameters) const override; + + void HideInlineKeyboard() const override; + + void InlineTextChanged(Core::Frontend::InlineTextParameters text_parameters) const override; + + void ExitKeyboard() const override; + +signals: + void MainWindowInitializeKeyboard( + bool is_inline, Core::Frontend::KeyboardInitializeParameters initialize_parameters) const; + + void MainWindowShowNormalKeyboard() const; + + void MainWindowShowTextCheckDialog( + Service::AM::Frontend::SwkbdTextCheckResult text_check_result, + std::u16string text_check_message) const; + + void MainWindowShowInlineKeyboard( + Core::Frontend::InlineAppearParameters appear_parameters) const; + + void MainWindowHideInlineKeyboard() const; + + void MainWindowInlineTextChanged(Core::Frontend::InlineTextParameters text_parameters) const; + + void MainWindowExitKeyboard() const; + +private: + void SubmitNormalText(Service::AM::Frontend::SwkbdResult result, std::u16string submitted_text, + bool confirmed) const; + + void SubmitInlineText(Service::AM::Frontend::SwkbdReplyType reply_type, + std::u16string submitted_text, s32 cursor_position) const; + + mutable SubmitNormalCallback submit_normal_callback; + mutable SubmitInlineCallback submit_inline_callback; +}; diff --git a/src/sudachi/applets/qt_software_keyboard.ui b/src/sudachi/applets/qt_software_keyboard.ui new file mode 100644 index 0000000..9661cb2 --- /dev/null +++ b/src/sudachi/applets/qt_software_keyboard.ui @@ -0,0 +1,3541 @@ + + + QtSoftwareKeyboardDialog + + + + 0 + 0 + 1280 + 720 + + + + Software Keyboard + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + 0 + + + + + 0 + 100 + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + 0 + + + 0 + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 17 + + + + 0/32 + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter + + + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + + + + 26 + 50 + false + + + + Qt::StrongFocus + + + + + + 32 + + + Enter Text + + + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Qt::Horizontal + + + + 127 + 20 + + + + + + + + + 23 + + + + + + + + + + + Qt::Horizontal + + + + 127 + 20 + + + + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Qt::Horizontal + + + + 127 + 20 + + + + + + + + + 17 + + + + + + + + + + + Qt::Horizontal + + + + 127 + 20 + + + + + + + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + true + + + + 17 + + + + 0/500 + + + + + + + + + + + 0 + + + 14 + + + 9 + + + 14 + + + 9 + + + + + + 26 + + + + Qt::StrongFocus + + + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:26pt; font-weight:400; font-style:normal;"> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p></body></html> + + + + + + + + + + + + + + + + 0 + + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + 0 + + + + + + 0 + + + 2 + + + 0 + + + 0 + + + 0 + + + + + + + + + + + + Qt::Horizontal + + + + 0 + 20 + + + + + + + + + + + Qt::Horizontal + + + + 0 + 20 + + + + + + + + + + + Qt::Horizontal + + + + 0 + 20 + + + + + + + + + + + Qt::Horizontal + + + + 0 + 20 + + + + + + + + + + + Qt::Horizontal + + + + 0 + 20 + + + + + + + + + + + Qt::Horizontal + + + + 0 + 20 + + + + + + + + + 18 + + + + Shift + + + + + + + Qt::Horizontal + + + + 0 + 20 + + + + + + + + + + + Qt::Horizontal + + + + 0 + 20 + + + + + + + + + 18 + + + + Cancel + + + + + + + Qt::Horizontal + + + + 0 + 20 + + + + + + + + + + + Qt::Horizontal + + + + 0 + 20 + + + + + + + + + 18 + + + + Enter + + + + + + + Qt::Horizontal + + + + 0 + 20 + + + + + + + + + + + + 1 + 1 + + + + + 28 + + + + - + + + + + + + + 1 + 1 + + + + + 28 + + + + ' + + + + + + + + 1 + 1 + + + + + 28 + + + + / + + + + + + + + 1 + 1 + + + + + 28 + + + + ! + + + + + + + + 1 + 1 + + + + + 28 + + + + 7 + + + + + + + + 1 + 1 + + + + + 28 + + + + 8 + + + + + + + + 1 + 1 + + + + + 28 + + + + 0 + + + + + + + + 1 + 1 + + + + + 28 + + + + 9 + + + + + + + + 1 + 1 + + + + + 28 + + + + w + + + + + + + + 1 + 1 + + + + + 28 + + + + r + + + + + + + + 1 + 1 + + + + + 28 + + + + e + + + + + + + + 1 + 1 + + + + + 28 + + + + q + + + + + + + + 1 + 1 + + + + + 28 + + + + u + + + + + + + + 1 + 1 + + + + + 28 + + + + y + + + + + + + + 1 + 1 + + + + + 28 + + + + t + + + + + + + + 1 + 1 + + + + + 28 + + + + o + + + + + + + + 1 + 1 + + + + + 28 + + + + p + + + + + + + + 1 + 1 + + + + + 28 + + + + i + + + + + + + + 1 + 1 + + + + + 28 + + + + a + + + + + + + + 1 + 1 + + + + + 28 + + + + s + + + + + + + + 1 + 1 + + + + + 28 + + + + d + + + + + + + + 1 + 1 + + + + + 28 + + + + f + + + + + + + + 1 + 1 + + + + + 28 + + + + h + + + + + + + + 1 + 1 + + + + + 28 + + + + j + + + + + + + + 1 + 1 + + + + + 28 + + + + g + + + + + + + + 1 + 1 + + + + + 28 + + + + k + + + + + + + + 1 + 1 + + + + + 28 + + + + l + + + + + + + + 1 + 1 + + + + + 28 + + + + : + + + + + + + + 1 + 1 + + + + + 18 + + + + Return + + + + + + + + 1 + 1 + + + + + 18 + + + + OK + + + + + + + + 1 + 1 + + + + + 28 + + + + z + + + + + + + + 1 + 1 + + + + + 28 + + + + c + + + + + + + + 1 + 1 + + + + + 28 + + + + x + + + + + + + + 1 + 1 + + + + + 28 + + + + v + + + + + + + + 1 + 1 + + + + + 28 + + + + m + + + + + + + + 1 + 1 + + + + + 28 + + + + , + + + + + + + + 1 + 1 + + + + + 28 + + + + n + + + + + + + + 1 + 1 + + + + + 28 + + + + b + + + + + + + + 1 + 1 + + + + + 18 + + + + + + + true + + + false + + + + + + + + 1 + 1 + + + + + 28 + + + + ? + + + + + + + + 1 + 1 + + + + + 28 + + + + . + + + + + + + + 1 + 1 + + + + + 28 + + + + 1 + + + + + + + + 1 + 1 + + + + + 28 + + + + 3 + + + + + + + + 1 + 1 + + + + + 28 + + + + 4 + + + + + + + + 1 + 1 + + + + + 28 + + + + 2 + + + + + + + + 1 + 1 + + + + + 28 + + + + 6 + + + + + + + + 1 + 1 + + + + + 28 + + + + 5 + + + + + + + + 1 + 1 + + + + + 18 + + + + Space + + + + + + + + 1 + 1 + + + + + 18 + + + + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Qt::Vertical + + + + 20 + 0 + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + 0 + + + + + + 0 + + + 2 + + + 0 + + + 0 + + + 0 + + + + + + + + + + + + Qt::Horizontal + + + + 0 + 20 + + + + + + + + + + + Qt::Horizontal + + + + 0 + 20 + + + + + + + + + + + Qt::Horizontal + + + + 0 + 20 + + + + + + + + + + + Qt::Horizontal + + + + 0 + 20 + + + + + + + + + + + Qt::Horizontal + + + + 0 + 20 + + + + + + + + + + + Qt::Horizontal + + + + 0 + 20 + + + + + + + + + 18 + + + + Caps Lock + + + + + + + Qt::Horizontal + + + + 0 + 20 + + + + + + + + + + + Qt::Horizontal + + + + 0 + 20 + + + + + + + + + 18 + + + + Cancel + + + + + + + Qt::Horizontal + + + + 0 + 20 + + + + + + + + + + + Qt::Horizontal + + + + 0 + 20 + + + + + + + + + 18 + + + + Enter + + + + + + + Qt::Horizontal + + + + 0 + 20 + + + + + + + + + + + + 1 + 1 + + + + + 28 + + + + _ + + + + + + + + 1 + 1 + + + + + 28 + + + + " + + + + + + + + 1 + 1 + + + + + 28 + + + + @ + + + + + + + + 1 + 1 + + + + + 28 + + + + = + + + + + + + + 1 + 1 + + + + + 28 + + + + && + + + + + + + + 1 + 1 + + + + + 28 + + + + * + + + + + + + + 1 + 1 + + + + + 28 + + + + ) + + + + + + + + 1 + 1 + + + + + 28 + + + + ( + + + + + + + + 1 + 1 + + + + + 28 + + + + W + + + + + + + + 1 + 1 + + + + + 28 + + + + R + + + + + + + + 1 + 1 + + + + + 28 + + + + E + + + + + + + + 1 + 1 + + + + + 28 + + + + Q + + + + + + + + 1 + 1 + + + + + 28 + + + + U + + + + + + + + 1 + 1 + + + + + 28 + + + + Y + + + + + + + + 1 + 1 + + + + + 28 + + + + T + + + + + + + + 1 + 1 + + + + + 28 + + + + O + + + + + + + + 1 + 1 + + + + + 28 + + + + P + + + + + + + + 1 + 1 + + + + + 28 + + + + I + + + + + + + + 1 + 1 + + + + + 28 + + + + A + + + + + + + + 1 + 1 + + + + + 28 + + + + S + + + + + + + + 1 + 1 + + + + + 28 + + + + D + + + + + + + + 1 + 1 + + + + + 28 + + + + F + + + + + + + + 1 + 1 + + + + + 28 + + + + H + + + + + + + + 1 + 1 + + + + + 28 + + + + J + + + + + + + + 1 + 1 + + + + + 28 + + + + G + + + + + + + + 1 + 1 + + + + + 28 + + + + K + + + + + + + + 1 + 1 + + + + + 28 + + + + L + + + + + + + + 1 + 1 + + + + + 28 + + + + ; + + + + + + + + 1 + 1 + + + + + 18 + + + + Return + + + + + + + + 1 + 1 + + + + + 18 + + + + OK + + + + + + + + 1 + 1 + + + + + 28 + + + + Z + + + + + + + + 1 + 1 + + + + + 28 + + + + C + + + + + + + + 1 + 1 + + + + + 28 + + + + X + + + + + + + + 1 + 1 + + + + + 28 + + + + V + + + + + + + + 1 + 1 + + + + + 28 + + + + M + + + + + + + + 1 + 1 + + + + + 28 + + + + < + + + + + + + + 1 + 1 + + + + + 28 + + + + N + + + + + + + + 1 + 1 + + + + + 28 + + + + B + + + + + + + + 1 + 1 + + + + + 18 + + + + + + + true + + + false + + + + + + + + 1 + 1 + + + + + 28 + + + + + + + + + + + + + 1 + 1 + + + + + 28 + + + + > + + + + + + + + 1 + 1 + + + + + 28 + + + + # + + + + + + + + 1 + 1 + + + + + 28 + + + + ] + + + + + + + + 1 + 1 + + + + + 28 + + + + $ + + + + + + + + 1 + 1 + + + + + 28 + + + + [ + + + + + + + + 1 + 1 + + + + + 28 + + + + ^ + + + + + + + + 1 + 1 + + + + + 28 + + + + % + + + + + + + + 1 + 1 + + + + + 18 + + + + Space + + + + + + + + 1 + 1 + + + + + 18 + + + + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Qt::Vertical + + + + 20 + 0 + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + 0 + + + 0 + + + 0 + + + + + + 1 + 1 + + + + + 18 + + + + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Qt::Vertical + + + + 20 + 0 + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + + + + + Qt::Horizontal + + + + 0 + 20 + + + + + + + + + + + Qt::Horizontal + + + + 0 + 20 + + + + + + + + + + + Qt::Horizontal + + + + 0 + 20 + + + + + + + + + + + Qt::Horizontal + + + + 0 + 20 + + + + + + + + + + + Qt::Horizontal + + + + 0 + 20 + + + + + + + + + + + Qt::Horizontal + + + + 0 + 20 + + + + + + + + + 18 + + + + Cancel + + + + + + + Qt::Horizontal + + + + 0 + 20 + + + + + + + + + + + Qt::Horizontal + + + + 0 + 20 + + + + + + + + + 18 + + + + Enter + + + + + + + Qt::Horizontal + + + + 0 + 20 + + + + + + + + + + + + 1 + 1 + + + + + 28 + + + + 6 + + + + + + + + 1 + 1 + + + + + 28 + + + + 4 + + + + + + + + 1 + 1 + + + + + 28 + + + + 9 + + + + + + + + 1 + 1 + + + + + 28 + + + + 5 + + + + + + + + 1 + 1 + + + + + 18 + + + + OK + + + + + + + + 1 + 1 + + + + + 28 + + + + 7 + + + + + + + + 1 + 1 + + + + + 28 + + + + 8 + + + + + + + + 1 + 1 + + + + + 28 + + + + 2 + + + + + + + + 1 + 1 + + + + + 28 + + + + 1 + + + + + + + + 1 + 1 + + + + + 28 + + + + + + + + + + + + 1 + 1 + + + + + 28 + + + + 0 + + + + + + + + 1 + 1 + + + + + 28 + + + + + + + + + + + + 1 + 1 + + + + + 28 + + + + 3 + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Qt::Vertical + + + + 20 + 0 + + + + + + + + + + + + + + + + + button_1 + button_2 + button_3 + button_4 + button_5 + button_6 + button_7 + button_8 + button_9 + button_0 + button_minus + button_backspace + button_q + button_w + button_e + button_r + button_t + button_y + button_u + button_i + button_o + button_p + button_slash + button_return + button_a + button_s + button_d + button_f + button_g + button_h + button_j + button_k + button_l + button_colon + button_apostrophe + button_z + button_x + button_c + button_v + button_b + button_n + button_m + button_comma + button_dot + button_question + button_exclamation + button_ok + button_shift + button_space + button_hash + button_left_bracket + button_right_bracket + button_dollar + button_percent + button_circumflex + button_ampersand + button_asterisk + button_left_parenthesis + button_right_parenthesis + button_underscore + button_backspace_shift + button_q_shift + button_w_shift + button_e_shift + button_r_shift + button_t_shift + button_y_shift + button_u_shift + button_i_shift + button_o_shift + button_p_shift + button_at + button_return_shift + button_a_shift + button_s_shift + button_d_shift + button_f_shift + button_g_shift + button_h_shift + button_j_shift + button_k_shift + button_l_shift + button_semicolon + button_quotation + button_z_shift + button_x_shift + button_c_shift + button_v_shift + button_b_shift + button_n_shift + button_m_shift + button_less_than + button_greater_than + button_plus + button_equal + button_ok_shift + button_shift_shift + button_space_shift + button_1_num + button_2_num + button_3_num + button_backspace_num + button_4_num + button_5_num + button_6_num + button_ok_num + button_7_num + button_8_num + button_9_num + button_left_optional_num + button_0_num + button_right_optional_num + + + + + + diff --git a/src/sudachi/applets/qt_web_browser.cpp b/src/sudachi/applets/qt_web_browser.cpp new file mode 100644 index 0000000..afdbf75 --- /dev/null +++ b/src/sudachi/applets/qt_web_browser.cpp @@ -0,0 +1,449 @@ +// SPDX-FileCopyrightText: Copyright 2020 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#ifdef SUDACHI_USE_QT_WEB_ENGINE +#include + +#include +#include + +#include +#include +#include +#include +#include + +#include "hid_core/frontend/input_interpreter.h" +#include "sudachi/applets/qt_web_browser_scripts.h" +#endif + +#include "common/fs/path_util.h" +#include "core/core.h" +#include "input_common/drivers/keyboard.h" +#include "sudachi/applets/qt_web_browser.h" +#include "sudachi/main.h" +#include "sudachi/util/url_request_interceptor.h" + +#ifdef SUDACHI_USE_QT_WEB_ENGINE + +namespace { + +constexpr int HIDButtonToKey(Core::HID::NpadButton button) { + switch (button) { + case Core::HID::NpadButton::Left: + case Core::HID::NpadButton::StickLLeft: + return Qt::Key_Left; + case Core::HID::NpadButton::Up: + case Core::HID::NpadButton::StickLUp: + return Qt::Key_Up; + case Core::HID::NpadButton::Right: + case Core::HID::NpadButton::StickLRight: + return Qt::Key_Right; + case Core::HID::NpadButton::Down: + case Core::HID::NpadButton::StickLDown: + return Qt::Key_Down; + default: + return 0; + } +} + +} // Anonymous namespace + +QtNXWebEngineView::QtNXWebEngineView(QWidget* parent, Core::System& system, + InputCommon::InputSubsystem* input_subsystem_) + : QWebEngineView(parent), input_subsystem{input_subsystem_}, + url_interceptor(std::make_unique()), + input_interpreter(std::make_unique(system)), + default_profile{QWebEngineProfile::defaultProfile()}, global_settings{ + default_profile->settings()} { + default_profile->setPersistentStoragePath(QString::fromStdString(Common::FS::PathToUTF8String( + Common::FS::GetSudachiPath(Common::FS::SudachiPath::SudachiDir) / "qtwebengine"))); + + QWebEngineScript gamepad; + QWebEngineScript window_nx; + + gamepad.setName(QStringLiteral("gamepad_script.js")); + window_nx.setName(QStringLiteral("window_nx_script.js")); + + gamepad.setSourceCode(QString::fromStdString(GAMEPAD_SCRIPT)); + window_nx.setSourceCode(QString::fromStdString(WINDOW_NX_SCRIPT)); + + gamepad.setInjectionPoint(QWebEngineScript::DocumentCreation); + window_nx.setInjectionPoint(QWebEngineScript::DocumentCreation); + + gamepad.setWorldId(QWebEngineScript::MainWorld); + window_nx.setWorldId(QWebEngineScript::MainWorld); + + gamepad.setRunsOnSubFrames(true); + window_nx.setRunsOnSubFrames(true); + + default_profile->scripts()->insert(gamepad); + default_profile->scripts()->insert(window_nx); + + default_profile->setUrlRequestInterceptor(url_interceptor.get()); + + global_settings->setAttribute(QWebEngineSettings::LocalContentCanAccessRemoteUrls, true); + global_settings->setAttribute(QWebEngineSettings::FullScreenSupportEnabled, true); + global_settings->setAttribute(QWebEngineSettings::AllowRunningInsecureContent, true); + global_settings->setAttribute(QWebEngineSettings::FocusOnNavigationEnabled, true); + global_settings->setAttribute(QWebEngineSettings::AllowWindowActivationFromJavaScript, true); + global_settings->setAttribute(QWebEngineSettings::ShowScrollBars, false); + + global_settings->setFontFamily(QWebEngineSettings::StandardFont, QStringLiteral("Roboto")); + + connect( + page(), &QWebEnginePage::windowCloseRequested, page(), + [this] { + if (page()->url() == url_interceptor->GetRequestedURL()) { + SetFinished(true); + SetExitReason(Service::AM::Frontend::WebExitReason::WindowClosed); + } + }, + Qt::QueuedConnection); +} + +QtNXWebEngineView::~QtNXWebEngineView() { + SetFinished(true); + StopInputThread(); +} + +void QtNXWebEngineView::LoadLocalWebPage(const std::string& main_url, + const std::string& additional_args) { + is_local = true; + + LoadExtractedFonts(); + FocusFirstLinkElement(); + SetUserAgent(UserAgent::WebApplet); + SetFinished(false); + SetExitReason(Service::AM::Frontend::WebExitReason::EndButtonPressed); + SetLastURL("http://localhost/"); + StartInputThread(); + + load(QUrl(QUrl::fromLocalFile(QString::fromStdString(main_url)).toString() + + QString::fromStdString(additional_args))); +} + +void QtNXWebEngineView::LoadExternalWebPage(const std::string& main_url, + const std::string& additional_args) { + is_local = false; + + FocusFirstLinkElement(); + SetUserAgent(UserAgent::WebApplet); + SetFinished(false); + SetExitReason(Service::AM::Frontend::WebExitReason::EndButtonPressed); + SetLastURL("http://localhost/"); + StartInputThread(); + + load(QUrl(QString::fromStdString(main_url) + QString::fromStdString(additional_args))); +} + +void QtNXWebEngineView::SetUserAgent(UserAgent user_agent) { + const QString user_agent_str = [user_agent] { + switch (user_agent) { + case UserAgent::WebApplet: + default: + return QStringLiteral("WebApplet"); + case UserAgent::ShopN: + return QStringLiteral("ShopN"); + case UserAgent::LoginApplet: + return QStringLiteral("LoginApplet"); + case UserAgent::ShareApplet: + return QStringLiteral("ShareApplet"); + case UserAgent::LobbyApplet: + return QStringLiteral("LobbyApplet"); + case UserAgent::WifiWebAuthApplet: + return QStringLiteral("WifiWebAuthApplet"); + } + }(); + + QWebEngineProfile::defaultProfile()->setHttpUserAgent( + QStringLiteral("Mozilla/5.0 (Nintendo Switch; %1) AppleWebKit/606.4 " + "(KHTML, like Gecko) NF/6.0.1.15.4 NintendoBrowser/5.1.0.20389") + .arg(user_agent_str)); +} + +bool QtNXWebEngineView::IsFinished() const { + return finished; +} + +void QtNXWebEngineView::SetFinished(bool finished_) { + finished = finished_; +} + +Service::AM::Frontend::WebExitReason QtNXWebEngineView::GetExitReason() const { + return exit_reason; +} + +void QtNXWebEngineView::SetExitReason(Service::AM::Frontend::WebExitReason exit_reason_) { + exit_reason = exit_reason_; +} + +const std::string& QtNXWebEngineView::GetLastURL() const { + return last_url; +} + +void QtNXWebEngineView::SetLastURL(std::string last_url_) { + last_url = std::move(last_url_); +} + +QString QtNXWebEngineView::GetCurrentURL() const { + return url_interceptor->GetRequestedURL().toString(); +} + +void QtNXWebEngineView::hide() { + SetFinished(true); + StopInputThread(); + + QWidget::hide(); +} + +void QtNXWebEngineView::keyPressEvent(QKeyEvent* event) { + if (is_local) { + input_subsystem->GetKeyboard()->PressKey(event->key()); + } +} + +void QtNXWebEngineView::keyReleaseEvent(QKeyEvent* event) { + if (is_local) { + input_subsystem->GetKeyboard()->ReleaseKey(event->key()); + } +} + +template +void QtNXWebEngineView::HandleWindowFooterButtonPressedOnce() { + const auto f = [this](Core::HID::NpadButton button) { + if (input_interpreter->IsButtonPressedOnce(button)) { + const auto button_index = std::countr_zero(static_cast(button)); + + page()->runJavaScript( + QStringLiteral("sudachi_key_callbacks[%1] == null;").arg(button_index), + [this, button](const QVariant& variant) { + if (variant.toBool()) { + switch (button) { + case Core::HID::NpadButton::A: + SendMultipleKeyPressEvents(); + break; + case Core::HID::NpadButton::B: + SendKeyPressEvent(Qt::Key_B); + break; + case Core::HID::NpadButton::X: + SendKeyPressEvent(Qt::Key_X); + break; + case Core::HID::NpadButton::Y: + SendKeyPressEvent(Qt::Key_Y); + break; + default: + break; + } + } + }); + + page()->runJavaScript( + QStringLiteral("if (sudachi_key_callbacks[%1] != null) { sudachi_key_callbacks[%1](); }") + .arg(button_index)); + } + }; + + (f(T), ...); +} + +template +void QtNXWebEngineView::HandleWindowKeyButtonPressedOnce() { + const auto f = [this](Core::HID::NpadButton button) { + if (input_interpreter->IsButtonPressedOnce(button)) { + SendKeyPressEvent(HIDButtonToKey(button)); + } + }; + + (f(T), ...); +} + +template +void QtNXWebEngineView::HandleWindowKeyButtonHold() { + const auto f = [this](Core::HID::NpadButton button) { + if (input_interpreter->IsButtonHeld(button)) { + SendKeyPressEvent(HIDButtonToKey(button)); + } + }; + + (f(T), ...); +} + +void QtNXWebEngineView::SendKeyPressEvent(int key) { + if (key == 0) { + return; + } + + QCoreApplication::postEvent(focusProxy(), + new QKeyEvent(QKeyEvent::KeyPress, key, Qt::NoModifier)); + QCoreApplication::postEvent(focusProxy(), + new QKeyEvent(QKeyEvent::KeyRelease, key, Qt::NoModifier)); +} + +void QtNXWebEngineView::StartInputThread() { + if (input_thread_running) { + return; + } + + input_thread_running = true; + input_thread = std::thread(&QtNXWebEngineView::InputThread, this); +} + +void QtNXWebEngineView::StopInputThread() { + if (is_local) { + QWidget::releaseKeyboard(); + } + + input_thread_running = false; + if (input_thread.joinable()) { + input_thread.join(); + } +} + +void QtNXWebEngineView::InputThread() { + // Wait for 1 second before allowing any inputs to be processed. + std::this_thread::sleep_for(std::chrono::seconds(1)); + + if (is_local) { + QWidget::grabKeyboard(); + } + + while (input_thread_running) { + input_interpreter->PollInput(); + + HandleWindowFooterButtonPressedOnce(); + + HandleWindowKeyButtonPressedOnce< + Core::HID::NpadButton::Left, Core::HID::NpadButton::Up, Core::HID::NpadButton::Right, + Core::HID::NpadButton::Down, Core::HID::NpadButton::StickLLeft, + Core::HID::NpadButton::StickLUp, Core::HID::NpadButton::StickLRight, + Core::HID::NpadButton::StickLDown>(); + + HandleWindowKeyButtonHold< + Core::HID::NpadButton::Left, Core::HID::NpadButton::Up, Core::HID::NpadButton::Right, + Core::HID::NpadButton::Down, Core::HID::NpadButton::StickLLeft, + Core::HID::NpadButton::StickLUp, Core::HID::NpadButton::StickLRight, + Core::HID::NpadButton::StickLDown>(); + + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + } +} + +void QtNXWebEngineView::LoadExtractedFonts() { + QWebEngineScript nx_font_css; + QWebEngineScript load_nx_font; + + auto fonts_dir_str = Common::FS::PathToUTF8String( + Common::FS::GetSudachiPath(Common::FS::SudachiPath::CacheDir) / "fonts/"); + + std::replace(fonts_dir_str.begin(), fonts_dir_str.end(), '\\', '/'); + + const auto fonts_dir = QString::fromStdString(fonts_dir_str); + + nx_font_css.setName(QStringLiteral("nx_font_css.js")); + load_nx_font.setName(QStringLiteral("load_nx_font.js")); + + nx_font_css.setSourceCode( + QString::fromStdString(NX_FONT_CSS) + .arg(fonts_dir + QStringLiteral("FontStandard.ttf")) + .arg(fonts_dir + QStringLiteral("FontChineseSimplified.ttf")) + .arg(fonts_dir + QStringLiteral("FontExtendedChineseSimplified.ttf")) + .arg(fonts_dir + QStringLiteral("FontChineseTraditional.ttf")) + .arg(fonts_dir + QStringLiteral("FontKorean.ttf")) + .arg(fonts_dir + QStringLiteral("FontNintendoExtended.ttf")) + .arg(fonts_dir + QStringLiteral("FontNintendoExtended2.ttf"))); + load_nx_font.setSourceCode(QString::fromStdString(LOAD_NX_FONT)); + + nx_font_css.setInjectionPoint(QWebEngineScript::DocumentReady); + load_nx_font.setInjectionPoint(QWebEngineScript::Deferred); + + nx_font_css.setWorldId(QWebEngineScript::MainWorld); + load_nx_font.setWorldId(QWebEngineScript::MainWorld); + + nx_font_css.setRunsOnSubFrames(true); + load_nx_font.setRunsOnSubFrames(true); + + default_profile->scripts()->insert(nx_font_css); + default_profile->scripts()->insert(load_nx_font); + + connect( + url_interceptor.get(), &UrlRequestInterceptor::FrameChanged, url_interceptor.get(), + [this] { + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + page()->runJavaScript(QString::fromStdString(LOAD_NX_FONT)); + }, + Qt::QueuedConnection); +} + +void QtNXWebEngineView::FocusFirstLinkElement() { + QWebEngineScript focus_link_element; + + focus_link_element.setName(QStringLiteral("focus_link_element.js")); + focus_link_element.setSourceCode(QString::fromStdString(FOCUS_LINK_ELEMENT_SCRIPT)); + focus_link_element.setWorldId(QWebEngineScript::MainWorld); + focus_link_element.setInjectionPoint(QWebEngineScript::Deferred); + focus_link_element.setRunsOnSubFrames(true); + default_profile->scripts()->insert(focus_link_element); +} + +#endif + +QtWebBrowser::QtWebBrowser(GMainWindow& main_window) { + connect(this, &QtWebBrowser::MainWindowOpenWebPage, &main_window, + &GMainWindow::WebBrowserOpenWebPage, Qt::QueuedConnection); + connect(this, &QtWebBrowser::MainWindowRequestExit, &main_window, + &GMainWindow::WebBrowserRequestExit, Qt::QueuedConnection); + connect(&main_window, &GMainWindow::WebBrowserExtractOfflineRomFS, this, + &QtWebBrowser::MainWindowExtractOfflineRomFS, Qt::QueuedConnection); + connect(&main_window, &GMainWindow::WebBrowserClosed, this, + &QtWebBrowser::MainWindowWebBrowserClosed, Qt::QueuedConnection); +} + +QtWebBrowser::~QtWebBrowser() = default; + +void QtWebBrowser::Close() const { + callback = {}; + emit MainWindowRequestExit(); +} + +void QtWebBrowser::OpenLocalWebPage(const std::string& local_url, + ExtractROMFSCallback extract_romfs_callback_, + OpenWebPageCallback callback_) const { + extract_romfs_callback = std::move(extract_romfs_callback_); + callback = std::move(callback_); + + const auto index = local_url.find('?'); + + if (index == std::string::npos) { + emit MainWindowOpenWebPage(local_url, "", true); + } else { + emit MainWindowOpenWebPage(local_url.substr(0, index), local_url.substr(index), true); + } +} + +void QtWebBrowser::OpenExternalWebPage(const std::string& external_url, + OpenWebPageCallback callback_) const { + callback = std::move(callback_); + + const auto index = external_url.find('?'); + + if (index == std::string::npos) { + emit MainWindowOpenWebPage(external_url, "", false); + } else { + emit MainWindowOpenWebPage(external_url.substr(0, index), external_url.substr(index), + false); + } +} + +void QtWebBrowser::MainWindowExtractOfflineRomFS() { + extract_romfs_callback(); +} + +void QtWebBrowser::MainWindowWebBrowserClosed(Service::AM::Frontend::WebExitReason exit_reason, + std::string last_url) { + if (callback) { + callback(exit_reason, last_url); + } +} diff --git a/src/sudachi/applets/qt_web_browser.h b/src/sudachi/applets/qt_web_browser.h new file mode 100644 index 0000000..247d2df --- /dev/null +++ b/src/sudachi/applets/qt_web_browser.h @@ -0,0 +1,220 @@ +// SPDX-FileCopyrightText: Copyright 2020 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include + +#include + +#ifdef SUDACHI_USE_QT_WEB_ENGINE +#include +#endif + +#include "core/frontend/applets/web_browser.h" + +class GMainWindow; +class InputInterpreter; +class UrlRequestInterceptor; + +namespace Core { +class System; +} + +namespace Core::HID { +enum class NpadButton : u64; +} + +namespace InputCommon { +class InputSubsystem; +} + +#ifdef SUDACHI_USE_QT_WEB_ENGINE + +enum class UserAgent { + WebApplet, + ShopN, + LoginApplet, + ShareApplet, + LobbyApplet, + WifiWebAuthApplet, +}; + +class QWebEngineProfile; +class QWebEngineSettings; + +class QtNXWebEngineView : public QWebEngineView { + Q_OBJECT + +public: + explicit QtNXWebEngineView(QWidget* parent, Core::System& system, + InputCommon::InputSubsystem* input_subsystem_); + ~QtNXWebEngineView() override; + + /** + * Loads a HTML document that exists locally. Cannot be used to load external websites. + * + * @param main_url The url to the file. + * @param additional_args Additional arguments appended to the main url. + */ + void LoadLocalWebPage(const std::string& main_url, const std::string& additional_args); + + /** + * Loads an external website. Cannot be used to load local urls. + * + * @param main_url The url to the website. + * @param additional_args Additional arguments appended to the main url. + */ + void LoadExternalWebPage(const std::string& main_url, const std::string& additional_args); + + /** + * Sets the background color of the web page. + * + * @param color The color to set. + */ + void SetBackgroundColor(QColor color); + + /** + * Sets the user agent of the web browser. + * + * @param user_agent The user agent enum. + */ + void SetUserAgent(UserAgent user_agent); + + [[nodiscard]] bool IsFinished() const; + void SetFinished(bool finished_); + + [[nodiscard]] Service::AM::Frontend::WebExitReason GetExitReason() const; + void SetExitReason(Service::AM::Frontend::WebExitReason exit_reason_); + + [[nodiscard]] const std::string& GetLastURL() const; + void SetLastURL(std::string last_url_); + + /** + * This gets the current URL that has been requested by the webpage. + * This only applies to the main frame. Sub frames and other resources are ignored. + * + * @return Currently requested URL + */ + [[nodiscard]] QString GetCurrentURL() const; + +public slots: + void hide(); + +protected: + void keyPressEvent(QKeyEvent* event) override; + void keyReleaseEvent(QKeyEvent* event) override; + +private: + /** + * Handles button presses to execute functions assigned in sudachi_key_callbacks. + * sudachi_key_callbacks contains specialized functions for the buttons in the window footer + * that can be overridden by games to achieve desired functionality. + * + * @tparam HIDButton The list of buttons contained in sudachi_key_callbacks + */ + template + void HandleWindowFooterButtonPressedOnce(); + + /** + * Handles button presses and converts them into keyboard input. + * This should only be used to convert D-Pad or Analog Stick input into arrow keys. + * + * @tparam HIDButton The list of buttons that can be converted into keyboard input. + */ + template + void HandleWindowKeyButtonPressedOnce(); + + /** + * Handles button holds and converts them into keyboard input. + * This should only be used to convert D-Pad or Analog Stick input into arrow keys. + * + * @tparam HIDButton The list of buttons that can be converted into keyboard input. + */ + template + void HandleWindowKeyButtonHold(); + + /** + * Sends a key press event to QWebEngineView. + * + * @param key Qt key code. + */ + void SendKeyPressEvent(int key); + + /** + * Sends multiple key press events to QWebEngineView. + * + * @tparam int Qt key code. + */ + template + void SendMultipleKeyPressEvents() { + (SendKeyPressEvent(T), ...); + } + + void StartInputThread(); + void StopInputThread(); + + /// The thread where input is being polled and processed. + void InputThread(); + + /// Loads the extracted fonts using JavaScript. + void LoadExtractedFonts(); + + /// Brings focus to the first available link element. + void FocusFirstLinkElement(); + + InputCommon::InputSubsystem* input_subsystem; + + std::unique_ptr url_interceptor; + + std::unique_ptr input_interpreter; + + std::thread input_thread; + + std::atomic input_thread_running{}; + + std::atomic finished{}; + + Service::AM::Frontend::WebExitReason exit_reason{ + Service::AM::Frontend::WebExitReason::EndButtonPressed}; + + std::string last_url{"http://localhost/"}; + + bool is_local{}; + + QWebEngineProfile* default_profile; + QWebEngineSettings* global_settings; +}; + +#endif + +class QtWebBrowser final : public QObject, public Core::Frontend::WebBrowserApplet { + Q_OBJECT + +public: + explicit QtWebBrowser(GMainWindow& parent); + ~QtWebBrowser() override; + + void Close() const override; + void OpenLocalWebPage(const std::string& local_url, + ExtractROMFSCallback extract_romfs_callback_, + OpenWebPageCallback callback_) const override; + + void OpenExternalWebPage(const std::string& external_url, + OpenWebPageCallback callback_) const override; + +signals: + void MainWindowOpenWebPage(const std::string& main_url, const std::string& additional_args, + bool is_local) const; + void MainWindowRequestExit() const; + +private: + void MainWindowExtractOfflineRomFS(); + + void MainWindowWebBrowserClosed(Service::AM::Frontend::WebExitReason exit_reason, + std::string last_url); + + mutable ExtractROMFSCallback extract_romfs_callback; + mutable OpenWebPageCallback callback; +}; diff --git a/src/sudachi/applets/qt_web_browser_scripts.h b/src/sudachi/applets/qt_web_browser_scripts.h new file mode 100644 index 0000000..bc58a94 --- /dev/null +++ b/src/sudachi/applets/qt_web_browser_scripts.h @@ -0,0 +1,198 @@ +// SPDX-FileCopyrightText: Copyright 2020 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +constexpr char NX_FONT_CSS[] = R"( +(function() { + css = document.createElement('style'); + css.type = 'text/css'; + css.id = 'nx_font'; + css.innerText = ` +/* FontStandard */ +@font-face { + font-family: 'FontStandard'; + src: url('%1') format('truetype'); +} + +/* FontChineseSimplified */ +@font-face { + font-family: 'FontChineseSimplified'; + src: url('%2') format('truetype'); +} + +/* FontExtendedChineseSimplified */ +@font-face { + font-family: 'FontExtendedChineseSimplified'; + src: url('%3') format('truetype'); +} + +/* FontChineseTraditional */ +@font-face { + font-family: 'FontChineseTraditional'; + src: url('%4') format('truetype'); +} + +/* FontKorean */ +@font-face { + font-family: 'FontKorean'; + src: url('%5') format('truetype'); +} + +/* FontNintendoExtended */ +@font-face { + font-family: 'NintendoExt003'; + src: url('%6') format('truetype'); +} + +/* FontNintendoExtended2 */ +@font-face { + font-family: 'NintendoExt003'; + src: url('%7') format('truetype'); +} +`; + + document.head.appendChild(css); +})(); +)"; + +constexpr char LOAD_NX_FONT[] = R"( +(function() { + var elements = document.querySelectorAll("*"); + + for (var i = 0; i < elements.length; i++) { + var style = window.getComputedStyle(elements[i], null); + if (style.fontFamily.includes("Arial") || style.fontFamily.includes("Calibri") || + style.fontFamily.includes("Century") || style.fontFamily.includes("Times New Roman")) { + elements[i].style.fontFamily = "FontStandard, FontChineseSimplified, FontExtendedChineseSimplified, FontChineseTraditional, FontKorean, NintendoExt003"; + } else { + elements[i].style.fontFamily = style.fontFamily + ", FontStandard, FontChineseSimplified, FontExtendedChineseSimplified, FontChineseTraditional, FontKorean, NintendoExt003"; + } + } +})(); +)"; + +constexpr char FOCUS_LINK_ELEMENT_SCRIPT[] = R"( +if (document.getElementsByTagName("a").length > 0) { + document.getElementsByTagName("a")[0].focus(); +} +)"; + +constexpr char GAMEPAD_SCRIPT[] = R"( +window.addEventListener("gamepadconnected", function(e) { + console.log("Gamepad connected at index %d: %s. %d buttons, %d axes.", + e.gamepad.index, e.gamepad.id, e.gamepad.buttons.length, e.gamepad.axes.length); +}); + +window.addEventListener("gamepaddisconnected", function(e) { + console.log("Gamepad disconnected from index %d: %s", e.gamepad.index, e.gamepad.id); +}); +)"; + +constexpr char WINDOW_NX_SCRIPT[] = R"( +var end_applet = false; +var sudachi_key_callbacks = []; + +(function() { + class WindowNX { + constructor() { + sudachi_key_callbacks[1] = function() { window.history.back(); }; + sudachi_key_callbacks[2] = function() { window.nx.endApplet(); }; + } + + addEventListener(type, listener, options) { + console.log("nx.addEventListener called, type=%s", type); + + window.addEventListener(type, listener, options); + } + + endApplet() { + console.log("nx.endApplet called"); + + end_applet = true; + } + + playSystemSe(system_se) { + console.log("nx.playSystemSe is not implemented, system_se=%s", system_se); + } + + sendMessage(message) { + console.log("nx.sendMessage is not implemented, message=%s", message); + } + + setCursorScrollSpeed(scroll_speed) { + console.log("nx.setCursorScrollSpeed is not implemented, scroll_speed=%d", scroll_speed); + } + } + + class WindowNXFooter { + setAssign(key, label, func, option) { + console.log("nx.footer.setAssign called, key=%s", key); + + switch (key) { + case "A": + sudachi_key_callbacks[0] = func; + break; + case "B": + sudachi_key_callbacks[1] = func; + break; + case "X": + sudachi_key_callbacks[2] = func; + break; + case "Y": + sudachi_key_callbacks[3] = func; + break; + case "L": + sudachi_key_callbacks[6] = func; + break; + case "R": + sudachi_key_callbacks[7] = func; + break; + } + } + + setFixed(kind) { + console.log("nx.footer.setFixed is not implemented, kind=%s", kind); + } + + unsetAssign(key) { + console.log("nx.footer.unsetAssign called, key=%s", key); + + switch (key) { + case "A": + sudachi_key_callbacks[0] = function() {}; + break; + case "B": + sudachi_key_callbacks[1] = function() {}; + break; + case "X": + sudachi_key_callbacks[2] = function() {}; + break; + case "Y": + sudachi_key_callbacks[3] = function() {}; + break; + case "L": + sudachi_key_callbacks[6] = function() {}; + break; + case "R": + sudachi_key_callbacks[7] = function() {}; + break; + } + } + } + + class WindowNXPlayReport { + incrementCounter(counter_id) { + console.log("nx.playReport.incrementCounter is not implemented, counter_id=%d", counter_id); + } + + setCounterSetIdentifier(counter_id) { + console.log("nx.playReport.setCounterSetIdentifier is not implemented, counter_id=%d", counter_id); + } + } + + window.nx = new WindowNX(); + window.nx.footer = new WindowNXFooter(); + window.nx.playReport = new WindowNXPlayReport(); +})(); +)"; diff --git a/src/sudachi/bootmanager.cpp b/src/sudachi/bootmanager.cpp new file mode 100644 index 0000000..21714b9 --- /dev/null +++ b/src/sudachi/bootmanager.cpp @@ -0,0 +1,1140 @@ +// SPDX-FileCopyrightText: 2014 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include "common/settings_enums.h" +#include "uisettings.h" +#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) && SUDACHI_USE_QT_MULTIMEDIA +#include +#include +#include +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef HAS_OPENGL +#include +#include +#endif + +#include "common/microprofile.h" +#include "common/polyfill_thread.h" +#include "common/scm_rev.h" +#include "common/settings.h" +#include "common/settings_input.h" +#include "common/thread.h" +#include "core/core.h" +#include "core/cpu_manager.h" +#include "core/frontend/framebuffer_layout.h" +#include "core/frontend/graphics_context.h" +#include "input_common/drivers/camera.h" +#include "input_common/drivers/keyboard.h" +#include "input_common/drivers/mouse.h" +#include "input_common/drivers/tas_input.h" +#include "input_common/drivers/touch_screen.h" +#include "input_common/main.h" +#include "video_core/gpu.h" +#include "video_core/rasterizer_interface.h" +#include "video_core/renderer_base.h" +#include "sudachi/bootmanager.h" +#include "sudachi/main.h" +#include "sudachi/qt_common.h" + +class QObject; +class QPaintEngine; +class QSurface; + +constexpr int default_mouse_constrain_timeout = 10; + +EmuThread::EmuThread(Core::System& system) : m_system{system} {} + +EmuThread::~EmuThread() = default; + +void EmuThread::run() { + const char* name = "EmuControlThread"; + MicroProfileOnThreadCreate(name); + Common::SetCurrentThreadName(name); + + auto& gpu = m_system.GPU(); + auto stop_token = m_stop_source.get_token(); + + m_system.RegisterHostThread(); + + // Main process has been loaded. Make the context current to this thread and begin GPU and CPU + // execution. + gpu.ObtainContext(); + + emit LoadProgress(VideoCore::LoadCallbackStage::Prepare, 0, 0); + if (Settings::values.use_disk_shader_cache.GetValue()) { + m_system.Renderer().ReadRasterizer()->LoadDiskResources( + m_system.GetApplicationProcessProgramID(), stop_token, + [this](VideoCore::LoadCallbackStage stage, std::size_t value, std::size_t total) { + emit LoadProgress(stage, value, total); + }); + } + emit LoadProgress(VideoCore::LoadCallbackStage::Complete, 0, 0); + + gpu.ReleaseContext(); + gpu.Start(); + + m_system.GetCpuManager().OnGpuReady(); + + if (m_system.DebuggerEnabled()) { + m_system.InitializeDebugger(); + } + + while (!stop_token.stop_requested()) { + std::unique_lock lk{m_should_run_mutex}; + if (m_should_run) { + m_system.Run(); + m_stopped.Reset(); + + Common::CondvarWait(m_should_run_cv, lk, stop_token, [&] { return !m_should_run; }); + } else { + m_system.Pause(); + m_stopped.Set(); + + EmulationPaused(lk); + Common::CondvarWait(m_should_run_cv, lk, stop_token, [&] { return m_should_run; }); + EmulationResumed(lk); + } + } + + // Shutdown the main emulated process + m_system.DetachDebugger(); + m_system.ShutdownMainProcess(); + +#if MICROPROFILE_ENABLED + MicroProfileOnThreadExit(); +#endif +} + +// Unlock while emitting signals so that the main thread can +// continue pumping events. + +void EmuThread::EmulationPaused(std::unique_lock& lk) { + lk.unlock(); + emit DebugModeEntered(); + lk.lock(); +} + +void EmuThread::EmulationResumed(std::unique_lock& lk) { + lk.unlock(); + emit DebugModeLeft(); + lk.lock(); +} + +#ifdef HAS_OPENGL +class OpenGLSharedContext : public Core::Frontend::GraphicsContext { +public: + /// Create the original context that should be shared from + explicit OpenGLSharedContext(QSurface* surface_) : surface{surface_} { + QSurfaceFormat format; + format.setVersion(4, 6); + format.setProfile(QSurfaceFormat::CompatibilityProfile); + format.setOption(QSurfaceFormat::FormatOption::DeprecatedFunctions); + if (Settings::values.renderer_debug) { + format.setOption(QSurfaceFormat::FormatOption::DebugContext); + } + // TODO: expose a setting for buffer value (ie default/single/double/triple) + format.setSwapBehavior(QSurfaceFormat::DefaultSwapBehavior); + format.setSwapInterval(0); + + context = std::make_unique(); + context->setFormat(format); + if (!context->create()) { + LOG_ERROR(Frontend, "Unable to create main openGL context"); + } + } + + /// Create the shared contexts for rendering and presentation + explicit OpenGLSharedContext(QOpenGLContext* share_context, QSurface* main_surface = nullptr) { + + // disable vsync for any shared contexts + auto format = share_context->format(); + const int swap_interval = + Settings::values.vsync_mode.GetValue() == Settings::VSyncMode::Immediate ? 0 : 1; + + format.setSwapInterval(main_surface ? swap_interval : 0); + + context = std::make_unique(); + context->setShareContext(share_context); + context->setFormat(format); + if (!context->create()) { + LOG_ERROR(Frontend, "Unable to create shared openGL context"); + } + + if (!main_surface) { + offscreen_surface = std::make_unique(nullptr); + offscreen_surface->setFormat(format); + offscreen_surface->create(); + surface = offscreen_surface.get(); + } else { + surface = main_surface; + } + } + + ~OpenGLSharedContext() { + DoneCurrent(); + } + + void SwapBuffers() override { + context->swapBuffers(surface); + } + + void MakeCurrent() override { + // We can't track the current state of the underlying context in this wrapper class because + // Qt may make the underlying context not current for one reason or another. In particular, + // the WebBrowser uses GL, so it seems to conflict if we aren't careful. + // Instead of always just making the context current (which does not have any caching to + // check if the underlying context is already current) we can check for the current context + // in the thread local data by calling `currentContext()` and checking if its ours. + if (QOpenGLContext::currentContext() != context.get()) { + context->makeCurrent(surface); + } + } + + void DoneCurrent() override { + context->doneCurrent(); + } + + QOpenGLContext* GetShareContext() { + return context.get(); + } + + const QOpenGLContext* GetShareContext() const { + return context.get(); + } + +private: + // Avoid using Qt parent system here since we might move the QObjects to new threads + // As a note, this means we should avoid using slots/signals with the objects too + std::unique_ptr context; + std::unique_ptr offscreen_surface{}; + QSurface* surface; +}; +#endif + +class DummyContext : public Core::Frontend::GraphicsContext {}; + +class RenderWidget : public QWidget { +public: + explicit RenderWidget(GRenderWindow* parent) : QWidget(parent), render_window(parent) { + setAttribute(Qt::WA_NativeWindow); + setAttribute(Qt::WA_PaintOnScreen); + if (QtCommon::GetWindowSystemType() == Core::Frontend::WindowSystemType::Wayland) { + setAttribute(Qt::WA_DontCreateNativeAncestors); + } + } + + virtual ~RenderWidget() = default; + + QPaintEngine* paintEngine() const override { + return nullptr; + } + +private: + GRenderWindow* render_window; +}; + +struct OpenGLRenderWidget : public RenderWidget { + explicit OpenGLRenderWidget(GRenderWindow* parent) : RenderWidget(parent) { + windowHandle()->setSurfaceType(QWindow::OpenGLSurface); + } + + void SetContext(std::unique_ptr&& context_) { + context = std::move(context_); + } + +private: + std::unique_ptr context; +}; + +struct VulkanRenderWidget : public RenderWidget { + explicit VulkanRenderWidget(GRenderWindow* parent) : RenderWidget(parent) { + windowHandle()->setSurfaceType(QWindow::VulkanSurface); + } +}; + +struct NullRenderWidget : public RenderWidget { + explicit NullRenderWidget(GRenderWindow* parent) : RenderWidget(parent) {} +}; + +GRenderWindow::GRenderWindow(GMainWindow* parent, EmuThread* emu_thread_, + std::shared_ptr input_subsystem_, + Core::System& system_) + : QWidget(parent), + emu_thread(emu_thread_), input_subsystem{std::move(input_subsystem_)}, system{system_} { + setWindowTitle(QStringLiteral("sudachi %1 | %2-%3") + .arg(QString::fromUtf8(Common::g_build_name), + QString::fromUtf8(Common::g_scm_branch), + QString::fromUtf8(Common::g_scm_desc))); + setAttribute(Qt::WA_AcceptTouchEvents); + auto* layout = new QHBoxLayout(this); + layout->setContentsMargins(0, 0, 0, 0); + setLayout(layout); + input_subsystem->Initialize(); + this->setMouseTracking(true); + + strict_context_required = QGuiApplication::platformName() == QStringLiteral("wayland") || + QGuiApplication::platformName() == QStringLiteral("wayland-egl"); + + connect(this, &GRenderWindow::FirstFrameDisplayed, parent, &GMainWindow::OnLoadComplete); + connect(this, &GRenderWindow::ExecuteProgramSignal, parent, &GMainWindow::OnExecuteProgram, + Qt::QueuedConnection); + connect(this, &GRenderWindow::ExitSignal, parent, &GMainWindow::OnExit, Qt::QueuedConnection); + connect(this, &GRenderWindow::TasPlaybackStateChanged, parent, &GMainWindow::OnTasStateChanged); + + mouse_constrain_timer.setInterval(default_mouse_constrain_timeout); + connect(&mouse_constrain_timer, &QTimer::timeout, this, &GRenderWindow::ConstrainMouse); +} + +void GRenderWindow::ExecuteProgram(std::size_t program_index) { + emit ExecuteProgramSignal(program_index); +} + +void GRenderWindow::Exit() { + emit ExitSignal(); +} + +GRenderWindow::~GRenderWindow() { + input_subsystem->Shutdown(); +} + +void GRenderWindow::OnFrameDisplayed() { + input_subsystem->GetTas()->UpdateThread(); + const InputCommon::TasInput::TasState new_tas_state = + std::get<0>(input_subsystem->GetTas()->GetStatus()); + + if (!first_frame) { + last_tas_state = new_tas_state; + first_frame = true; + emit FirstFrameDisplayed(); + } + + if (new_tas_state != last_tas_state) { + last_tas_state = new_tas_state; + emit TasPlaybackStateChanged(); + } +} + +bool GRenderWindow::IsShown() const { + return !isMinimized(); +} + +// On Qt 5.0+, this correctly gets the size of the framebuffer (pixels). +// +// Older versions get the window size (density independent pixels), +// and hence, do not support DPI scaling ("retina" displays). +// The result will be a viewport that is smaller than the extent of the window. +void GRenderWindow::OnFramebufferSizeChanged() { + // Screen changes potentially incur a change in screen DPI, hence we should update the + // framebuffer size + const qreal pixel_ratio = windowPixelRatio(); + const u32 width = this->width() * pixel_ratio; + const u32 height = this->height() * pixel_ratio; + UpdateCurrentFramebufferLayout(width, height); +} + +void GRenderWindow::BackupGeometry() { + geometry = QWidget::saveGeometry(); +} + +void GRenderWindow::RestoreGeometry() { + // We don't want to back up the geometry here (obviously) + QWidget::restoreGeometry(geometry); +} + +void GRenderWindow::restoreGeometry(const QByteArray& geometry_) { + // Make sure users of this class don't need to deal with backing up the geometry themselves + QWidget::restoreGeometry(geometry_); + BackupGeometry(); +} + +QByteArray GRenderWindow::saveGeometry() { + // If we are a top-level widget, store the current geometry + // otherwise, store the last backup + if (parent() == nullptr) { + return QWidget::saveGeometry(); + } + + return geometry; +} + +qreal GRenderWindow::windowPixelRatio() const { + return devicePixelRatioF(); +} + +std::pair GRenderWindow::ScaleTouch(const QPointF& pos) const { + const qreal pixel_ratio = windowPixelRatio(); + return {static_cast(std::max(std::round(pos.x() * pixel_ratio), qreal{0.0})), + static_cast(std::max(std::round(pos.y() * pixel_ratio), qreal{0.0}))}; +} + +void GRenderWindow::closeEvent(QCloseEvent* event) { + emit Closed(); + QWidget::closeEvent(event); +} + +void GRenderWindow::leaveEvent(QEvent* event) { + if (Settings::values.mouse_panning) { + const QRect& rect = QWidget::geometry(); + QPoint position = QCursor::pos(); + + qint32 x = qBound(rect.left(), position.x(), rect.right()); + qint32 y = qBound(rect.top(), position.y(), rect.bottom()); + // Only start the timer if the mouse has left the window bound. + // The leave event is also triggered when the window looses focus. + if (x != position.x() || y != position.y()) { + mouse_constrain_timer.start(); + } + event->accept(); + } +} + +int GRenderWindow::QtKeyToSwitchKey(Qt::Key qt_key) { + static constexpr std::array, 106> key_map = { + std::pair{Qt::Key_A, Settings::NativeKeyboard::A}, + {Qt::Key_A, Settings::NativeKeyboard::A}, + {Qt::Key_B, Settings::NativeKeyboard::B}, + {Qt::Key_C, Settings::NativeKeyboard::C}, + {Qt::Key_D, Settings::NativeKeyboard::D}, + {Qt::Key_E, Settings::NativeKeyboard::E}, + {Qt::Key_F, Settings::NativeKeyboard::F}, + {Qt::Key_G, Settings::NativeKeyboard::G}, + {Qt::Key_H, Settings::NativeKeyboard::H}, + {Qt::Key_I, Settings::NativeKeyboard::I}, + {Qt::Key_J, Settings::NativeKeyboard::J}, + {Qt::Key_K, Settings::NativeKeyboard::K}, + {Qt::Key_L, Settings::NativeKeyboard::L}, + {Qt::Key_M, Settings::NativeKeyboard::M}, + {Qt::Key_N, Settings::NativeKeyboard::N}, + {Qt::Key_O, Settings::NativeKeyboard::O}, + {Qt::Key_P, Settings::NativeKeyboard::P}, + {Qt::Key_Q, Settings::NativeKeyboard::Q}, + {Qt::Key_R, Settings::NativeKeyboard::R}, + {Qt::Key_S, Settings::NativeKeyboard::S}, + {Qt::Key_T, Settings::NativeKeyboard::T}, + {Qt::Key_U, Settings::NativeKeyboard::U}, + {Qt::Key_V, Settings::NativeKeyboard::V}, + {Qt::Key_W, Settings::NativeKeyboard::W}, + {Qt::Key_X, Settings::NativeKeyboard::X}, + {Qt::Key_Y, Settings::NativeKeyboard::Y}, + {Qt::Key_Z, Settings::NativeKeyboard::Z}, + {Qt::Key_1, Settings::NativeKeyboard::N1}, + {Qt::Key_2, Settings::NativeKeyboard::N2}, + {Qt::Key_3, Settings::NativeKeyboard::N3}, + {Qt::Key_4, Settings::NativeKeyboard::N4}, + {Qt::Key_5, Settings::NativeKeyboard::N5}, + {Qt::Key_6, Settings::NativeKeyboard::N6}, + {Qt::Key_7, Settings::NativeKeyboard::N7}, + {Qt::Key_8, Settings::NativeKeyboard::N8}, + {Qt::Key_9, Settings::NativeKeyboard::N9}, + {Qt::Key_0, Settings::NativeKeyboard::N0}, + {Qt::Key_Return, Settings::NativeKeyboard::Return}, + {Qt::Key_Escape, Settings::NativeKeyboard::Escape}, + {Qt::Key_Backspace, Settings::NativeKeyboard::Backspace}, + {Qt::Key_Tab, Settings::NativeKeyboard::Tab}, + {Qt::Key_Space, Settings::NativeKeyboard::Space}, + {Qt::Key_Minus, Settings::NativeKeyboard::Minus}, + {Qt::Key_Plus, Settings::NativeKeyboard::Plus}, + {Qt::Key_questiondown, Settings::NativeKeyboard::Plus}, + {Qt::Key_BracketLeft, Settings::NativeKeyboard::OpenBracket}, + {Qt::Key_BraceLeft, Settings::NativeKeyboard::OpenBracket}, + {Qt::Key_BracketRight, Settings::NativeKeyboard::CloseBracket}, + {Qt::Key_BraceRight, Settings::NativeKeyboard::CloseBracket}, + {Qt::Key_Bar, Settings::NativeKeyboard::Pipe}, + {Qt::Key_Dead_Tilde, Settings::NativeKeyboard::Tilde}, + {Qt::Key_Ntilde, Settings::NativeKeyboard::Semicolon}, + {Qt::Key_Semicolon, Settings::NativeKeyboard::Semicolon}, + {Qt::Key_Apostrophe, Settings::NativeKeyboard::Quote}, + {Qt::Key_Dead_Grave, Settings::NativeKeyboard::Backquote}, + {Qt::Key_Comma, Settings::NativeKeyboard::Comma}, + {Qt::Key_Period, Settings::NativeKeyboard::Period}, + {Qt::Key_Slash, Settings::NativeKeyboard::Slash}, + {Qt::Key_CapsLock, Settings::NativeKeyboard::CapsLockKey}, + {Qt::Key_F1, Settings::NativeKeyboard::F1}, + {Qt::Key_F2, Settings::NativeKeyboard::F2}, + {Qt::Key_F3, Settings::NativeKeyboard::F3}, + {Qt::Key_F4, Settings::NativeKeyboard::F4}, + {Qt::Key_F5, Settings::NativeKeyboard::F5}, + {Qt::Key_F6, Settings::NativeKeyboard::F6}, + {Qt::Key_F7, Settings::NativeKeyboard::F7}, + {Qt::Key_F8, Settings::NativeKeyboard::F8}, + {Qt::Key_F9, Settings::NativeKeyboard::F9}, + {Qt::Key_F10, Settings::NativeKeyboard::F10}, + {Qt::Key_F11, Settings::NativeKeyboard::F11}, + {Qt::Key_F12, Settings::NativeKeyboard::F12}, + {Qt::Key_Print, Settings::NativeKeyboard::PrintScreen}, + {Qt::Key_ScrollLock, Settings::NativeKeyboard::ScrollLockKey}, + {Qt::Key_Pause, Settings::NativeKeyboard::Pause}, + {Qt::Key_Insert, Settings::NativeKeyboard::Insert}, + {Qt::Key_Home, Settings::NativeKeyboard::Home}, + {Qt::Key_PageUp, Settings::NativeKeyboard::PageUp}, + {Qt::Key_Delete, Settings::NativeKeyboard::Delete}, + {Qt::Key_End, Settings::NativeKeyboard::End}, + {Qt::Key_PageDown, Settings::NativeKeyboard::PageDown}, + {Qt::Key_Right, Settings::NativeKeyboard::Right}, + {Qt::Key_Left, Settings::NativeKeyboard::Left}, + {Qt::Key_Down, Settings::NativeKeyboard::Down}, + {Qt::Key_Up, Settings::NativeKeyboard::Up}, + {Qt::Key_NumLock, Settings::NativeKeyboard::NumLockKey}, + // Numpad keys are missing here + {Qt::Key_F13, Settings::NativeKeyboard::F13}, + {Qt::Key_F14, Settings::NativeKeyboard::F14}, + {Qt::Key_F15, Settings::NativeKeyboard::F15}, + {Qt::Key_F16, Settings::NativeKeyboard::F16}, + {Qt::Key_F17, Settings::NativeKeyboard::F17}, + {Qt::Key_F18, Settings::NativeKeyboard::F18}, + {Qt::Key_F19, Settings::NativeKeyboard::F19}, + {Qt::Key_F20, Settings::NativeKeyboard::F20}, + {Qt::Key_F21, Settings::NativeKeyboard::F21}, + {Qt::Key_F22, Settings::NativeKeyboard::F22}, + {Qt::Key_F23, Settings::NativeKeyboard::F23}, + {Qt::Key_F24, Settings::NativeKeyboard::F24}, + // {Qt::..., Settings::NativeKeyboard::KPComma}, + // {Qt::..., Settings::NativeKeyboard::Ro}, + {Qt::Key_Hiragana_Katakana, Settings::NativeKeyboard::KatakanaHiragana}, + {Qt::Key_yen, Settings::NativeKeyboard::Yen}, + {Qt::Key_Henkan, Settings::NativeKeyboard::Henkan}, + {Qt::Key_Muhenkan, Settings::NativeKeyboard::Muhenkan}, + // {Qt::..., Settings::NativeKeyboard::NumPadCommaPc98}, + {Qt::Key_Hangul, Settings::NativeKeyboard::HangulEnglish}, + {Qt::Key_Hangul_Hanja, Settings::NativeKeyboard::Hanja}, + {Qt::Key_Katakana, Settings::NativeKeyboard::KatakanaKey}, + {Qt::Key_Hiragana, Settings::NativeKeyboard::HiraganaKey}, + {Qt::Key_Zenkaku_Hankaku, Settings::NativeKeyboard::ZenkakuHankaku}, + // Modifier keys are handled by the modifier property + }; + + for (const auto& [qkey, nkey] : key_map) { + if (qt_key == qkey) { + return nkey; + } + } + + return Settings::NativeKeyboard::None; +} + +int GRenderWindow::QtModifierToSwitchModifier(Qt::KeyboardModifiers qt_modifiers) { + int modifier = 0; + + if ((qt_modifiers & Qt::KeyboardModifier::ShiftModifier) != 0) { + modifier |= 1 << Settings::NativeKeyboard::LeftShift; + } + if ((qt_modifiers & Qt::KeyboardModifier::ControlModifier) != 0) { + modifier |= 1 << Settings::NativeKeyboard::LeftControl; + } + if ((qt_modifiers & Qt::KeyboardModifier::AltModifier) != 0) { + modifier |= 1 << Settings::NativeKeyboard::LeftAlt; + } + if ((qt_modifiers & Qt::KeyboardModifier::MetaModifier) != 0) { + modifier |= 1 << Settings::NativeKeyboard::LeftMeta; + } + + // TODO: These keys can't be obtained with Qt::KeyboardModifier + + // if ((qt_modifiers & 0x10) != 0) { + // modifier |= 1 << Settings::NativeKeyboard::RightShift; + // } + // if ((qt_modifiers & 0x20) != 0) { + // modifier |= 1 << Settings::NativeKeyboard::RightControl; + // } + // if ((qt_modifiers & 0x40) != 0) { + // modifier |= 1 << Settings::NativeKeyboard::RightAlt; + // } + // if ((qt_modifiers & 0x80) != 0) { + // modifier |= 1 << Settings::NativeKeyboard::RightMeta; + // } + // if ((qt_modifiers & 0x100) != 0) { + // modifier |= 1 << Settings::NativeKeyboard::CapsLock; + // } + // if ((qt_modifiers & 0x200) != 0) { + // modifier |= 1 << Settings::NativeKeyboard::NumLock; + // } + // if ((qt_modifiers & ???) != 0) { + // modifier |= 1 << Settings::NativeKeyboard::ScrollLock; + // } + // if ((qt_modifiers & ???) != 0) { + // modifier |= 1 << Settings::NativeKeyboard::Katakana; + // } + // if ((qt_modifiers & ???) != 0) { + // modifier |= 1 << Settings::NativeKeyboard::Hiragana; + // } + return modifier; +} + +void GRenderWindow::keyPressEvent(QKeyEvent* event) { + /** + * This feature can be enhanced with the following functions, but they do not provide + * cross-platform behavior. + * + * event->nativeVirtualKey() can distinguish between keys on the numpad. + * event->nativeModifiers() can distinguish between left and right keys and numlock, + * capslock, scroll lock. + */ + if (!event->isAutoRepeat()) { + const auto modifier = QtModifierToSwitchModifier(event->modifiers()); + const auto key = QtKeyToSwitchKey(Qt::Key(event->key())); + input_subsystem->GetKeyboard()->SetKeyboardModifiers(modifier); + input_subsystem->GetKeyboard()->PressKeyboardKey(key); + // This is used for gamepads that can have any key mapped + input_subsystem->GetKeyboard()->PressKey(event->key()); + } +} + +void GRenderWindow::keyReleaseEvent(QKeyEvent* event) { + /** + * This feature can be enhanced with the following functions, but they do not provide + * cross-platform behavior. + * + * event->nativeVirtualKey() can distinguish between keys on the numpad. + * event->nativeModifiers() can distinguish between left and right buttons and numlock, + * capslock, scroll lock. + */ + if (!event->isAutoRepeat()) { + const auto modifier = QtModifierToSwitchModifier(event->modifiers()); + const auto key = QtKeyToSwitchKey(Qt::Key(event->key())); + input_subsystem->GetKeyboard()->SetKeyboardModifiers(modifier); + input_subsystem->GetKeyboard()->ReleaseKeyboardKey(key); + // This is used for gamepads that can have any key mapped + input_subsystem->GetKeyboard()->ReleaseKey(event->key()); + } +} + +InputCommon::MouseButton GRenderWindow::QtButtonToMouseButton(Qt::MouseButton button) { + switch (button) { + case Qt::LeftButton: + return InputCommon::MouseButton::Left; + case Qt::RightButton: + return InputCommon::MouseButton::Right; + case Qt::MiddleButton: + return InputCommon::MouseButton::Wheel; + case Qt::BackButton: + return InputCommon::MouseButton::Backward; + case Qt::ForwardButton: + return InputCommon::MouseButton::Forward; + case Qt::TaskButton: + return InputCommon::MouseButton::Task; + default: + return InputCommon::MouseButton::Extra; + } +} + +void GRenderWindow::mousePressEvent(QMouseEvent* event) { + // Touch input is handled in TouchBeginEvent + if (event->source() == Qt::MouseEventSynthesizedBySystem) { + return; + } + // Qt sometimes returns the parent coordinates. To avoid this we read the global mouse + // coordinates and map them to the current render area + const auto pos = mapFromGlobal(QCursor::pos()); + const auto [x, y] = ScaleTouch(pos); + const auto [touch_x, touch_y] = MapToTouchScreen(x, y); + const auto button = QtButtonToMouseButton(event->button()); + + input_subsystem->GetMouse()->PressMouseButton(button); + input_subsystem->GetMouse()->PressButton(pos.x(), pos.y(), button); + input_subsystem->GetMouse()->PressTouchButton(touch_x, touch_y, button); + + emit MouseActivity(); +} + +void GRenderWindow::mouseMoveEvent(QMouseEvent* event) { + // Touch input is handled in TouchUpdateEvent + if (event->source() == Qt::MouseEventSynthesizedBySystem) { + return; + } + // Qt sometimes returns the parent coordinates. To avoid this we read the global mouse + // coordinates and map them to the current render area + const auto pos = mapFromGlobal(QCursor::pos()); + const auto [x, y] = ScaleTouch(pos); + const auto [touch_x, touch_y] = MapToTouchScreen(x, y); + const int center_x = width() / 2; + const int center_y = height() / 2; + + input_subsystem->GetMouse()->MouseMove(touch_x, touch_y); + input_subsystem->GetMouse()->TouchMove(touch_x, touch_y); + input_subsystem->GetMouse()->Move(pos.x(), pos.y(), center_x, center_y); + + // Center mouse for mouse panning + if (Settings::values.mouse_panning && !Settings::values.mouse_enabled) { + QCursor::setPos(mapToGlobal(QPoint{center_x, center_y})); + } + + // Constrain mouse for mouse emulation with mouse panning + if (Settings::values.mouse_panning && Settings::values.mouse_enabled) { + const auto [clamped_mouse_x, clamped_mouse_y] = ClipToTouchScreen(x, y); + QCursor::setPos(mapToGlobal( + QPoint{static_cast(clamped_mouse_x), static_cast(clamped_mouse_y)})); + } + + mouse_constrain_timer.stop(); + emit MouseActivity(); +} + +void GRenderWindow::mouseReleaseEvent(QMouseEvent* event) { + // Touch input is handled in TouchEndEvent + if (event->source() == Qt::MouseEventSynthesizedBySystem) { + return; + } + + const auto button = QtButtonToMouseButton(event->button()); + input_subsystem->GetMouse()->ReleaseButton(button); +} + +void GRenderWindow::ConstrainMouse() { + if (emu_thread == nullptr || !Settings::values.mouse_panning) { + mouse_constrain_timer.stop(); + return; + } + if (!this->isActiveWindow()) { + mouse_constrain_timer.stop(); + return; + } + + if (Settings::values.mouse_enabled) { + const auto pos = mapFromGlobal(QCursor::pos()); + const int new_pos_x = std::clamp(pos.x(), 0, width()); + const int new_pos_y = std::clamp(pos.y(), 0, height()); + + QCursor::setPos(mapToGlobal(QPoint{new_pos_x, new_pos_y})); + return; + } + + const int center_x = width() / 2; + const int center_y = height() / 2; + + QCursor::setPos(mapToGlobal(QPoint{center_x, center_y})); +} + +void GRenderWindow::wheelEvent(QWheelEvent* event) { + const int x = event->angleDelta().x(); + const int y = event->angleDelta().y(); + input_subsystem->GetMouse()->MouseWheelChange(x, y); +} + +void GRenderWindow::TouchBeginEvent(const QTouchEvent* event) { + QList touch_points = event->touchPoints(); + for (const auto& touch_point : touch_points) { + const auto [x, y] = ScaleTouch(touch_point.pos()); + const auto [touch_x, touch_y] = MapToTouchScreen(x, y); + input_subsystem->GetTouchScreen()->TouchPressed(touch_x, touch_y, touch_point.id()); + } +} + +void GRenderWindow::TouchUpdateEvent(const QTouchEvent* event) { + QList touch_points = event->touchPoints(); + input_subsystem->GetTouchScreen()->ClearActiveFlag(); + for (const auto& touch_point : touch_points) { + const auto [x, y] = ScaleTouch(touch_point.pos()); + const auto [touch_x, touch_y] = MapToTouchScreen(x, y); + input_subsystem->GetTouchScreen()->TouchMoved(touch_x, touch_y, touch_point.id()); + } + input_subsystem->GetTouchScreen()->ReleaseInactiveTouch(); +} + +void GRenderWindow::TouchEndEvent() { + input_subsystem->GetTouchScreen()->ReleaseAllTouch(); +} + +void GRenderWindow::InitializeCamera() { +#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) && SUDACHI_USE_QT_MULTIMEDIA + constexpr auto camera_update_ms = std::chrono::milliseconds{50}; // (50ms, 20Hz) + if (!Settings::values.enable_ir_sensor) { + return; + } + + bool camera_found = false; + const QList cameras = QCameraInfo::availableCameras(); + for (const QCameraInfo& cameraInfo : cameras) { + if (Settings::values.ir_sensor_device.GetValue() == cameraInfo.deviceName().toStdString() || + Settings::values.ir_sensor_device.GetValue() == "Auto") { + camera = std::make_unique(cameraInfo); + if (!camera->isCaptureModeSupported(QCamera::CaptureMode::CaptureViewfinder) && + !camera->isCaptureModeSupported(QCamera::CaptureMode::CaptureStillImage)) { + LOG_ERROR(Frontend, + "Camera doesn't support CaptureViewfinder or CaptureStillImage"); + continue; + } + camera_found = true; + break; + } + } + + if (!camera_found) { + return; + } + + camera_capture = std::make_unique(camera.get()); + + if (!camera_capture->isCaptureDestinationSupported( + QCameraImageCapture::CaptureDestination::CaptureToBuffer)) { + LOG_ERROR(Frontend, "Camera doesn't support saving to buffer"); + return; + } + + const auto camera_width = input_subsystem->GetCamera()->getImageWidth(); + const auto camera_height = input_subsystem->GetCamera()->getImageHeight(); + camera_data.resize(camera_width * camera_height); + camera_capture->setCaptureDestination(QCameraImageCapture::CaptureDestination::CaptureToBuffer); + connect(camera_capture.get(), &QCameraImageCapture::imageCaptured, this, + &GRenderWindow::OnCameraCapture); + camera->unload(); + if (camera->isCaptureModeSupported(QCamera::CaptureMode::CaptureViewfinder)) { + camera->setCaptureMode(QCamera::CaptureViewfinder); + } else if (camera->isCaptureModeSupported(QCamera::CaptureMode::CaptureStillImage)) { + camera->setCaptureMode(QCamera::CaptureStillImage); + } + camera->load(); + camera->start(); + + pending_camera_snapshots = 0; + is_virtual_camera = false; + + camera_timer = std::make_unique(); + connect(camera_timer.get(), &QTimer::timeout, [this] { RequestCameraCapture(); }); + // This timer should be dependent of camera resolution 5ms for every 100 pixels + camera_timer->start(camera_update_ms); +#endif +} + +void GRenderWindow::FinalizeCamera() { +#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) && SUDACHI_USE_QT_MULTIMEDIA + if (camera_timer) { + camera_timer->stop(); + } + if (camera) { + camera->unload(); + } +#endif +} + +void GRenderWindow::RequestCameraCapture() { +#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) && SUDACHI_USE_QT_MULTIMEDIA + if (!Settings::values.enable_ir_sensor) { + return; + } + + // If the camera doesn't capture, test for virtual cameras + if (pending_camera_snapshots > 5) { + is_virtual_camera = true; + } + // Virtual cameras like obs need to reset the camera every capture + if (is_virtual_camera) { + camera->stop(); + camera->start(); + } + + pending_camera_snapshots++; + camera_capture->capture(); +#endif +} + +void GRenderWindow::OnCameraCapture(int requestId, const QImage& img) { +#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) && SUDACHI_USE_QT_MULTIMEDIA + // TODO: Capture directly in the format and resolution needed + const auto camera_width = input_subsystem->GetCamera()->getImageWidth(); + const auto camera_height = input_subsystem->GetCamera()->getImageHeight(); + const auto converted = + img.scaled(static_cast(camera_width), static_cast(camera_height), + Qt::AspectRatioMode::IgnoreAspectRatio, + Qt::TransformationMode::SmoothTransformation) + .mirrored(false, true); + if (camera_data.size() != camera_width * camera_height) { + camera_data.resize(camera_width * camera_height); + } + std::memcpy(camera_data.data(), converted.bits(), camera_width * camera_height * sizeof(u32)); + input_subsystem->GetCamera()->SetCameraData(camera_width, camera_height, camera_data); + pending_camera_snapshots = 0; +#endif +} + +bool GRenderWindow::event(QEvent* event) { + if (event->type() == QEvent::TouchBegin) { + TouchBeginEvent(static_cast(event)); + return true; + } else if (event->type() == QEvent::TouchUpdate) { + TouchUpdateEvent(static_cast(event)); + return true; + } else if (event->type() == QEvent::TouchEnd || event->type() == QEvent::TouchCancel) { + TouchEndEvent(); + return true; + } + + return QWidget::event(event); +} + +void GRenderWindow::focusOutEvent(QFocusEvent* event) { + QWidget::focusOutEvent(event); + input_subsystem->GetKeyboard()->ReleaseAllKeys(); + input_subsystem->GetMouse()->ReleaseAllButtons(); + input_subsystem->GetTouchScreen()->ReleaseAllTouch(); +} + +void GRenderWindow::resizeEvent(QResizeEvent* event) { + QWidget::resizeEvent(event); + OnFramebufferSizeChanged(); +} + +std::unique_ptr GRenderWindow::CreateSharedContext() const { +#ifdef HAS_OPENGL + if (Settings::values.renderer_backend.GetValue() == Settings::RendererBackend::OpenGL) { + auto c = static_cast(main_context.get()); + // Bind the shared contexts to the main surface in case the backend wants to take over + // presentation + return std::make_unique(c->GetShareContext(), + child_widget->windowHandle()); + } +#endif + return std::make_unique(); +} + +bool GRenderWindow::InitRenderTarget() { + ReleaseRenderTarget(); + + { + // Create a dummy render widget so that Qt + // places the render window at the correct position. + const RenderWidget dummy_widget{this}; + } + + first_frame = false; + + switch (Settings::values.renderer_backend.GetValue()) { + case Settings::RendererBackend::OpenGL: + if (!InitializeOpenGL()) { + return false; + } + break; + case Settings::RendererBackend::Vulkan: + if (!InitializeVulkan()) { + return false; + } + break; + case Settings::RendererBackend::Null: + InitializeNull(); + break; + } + + // Update the Window System information with the new render target + window_info = QtCommon::GetWindowSystemInfo(child_widget->windowHandle()); + + child_widget->resize(Layout::ScreenUndocked::Width, Layout::ScreenUndocked::Height); + layout()->addWidget(child_widget); + // Reset minimum required size to avoid resizing issues on the main window after restarting. + setMinimumSize(1, 1); + + resize(Layout::ScreenUndocked::Width, Layout::ScreenUndocked::Height); + + OnMinimalClientAreaChangeRequest(GetActiveConfig().min_client_area_size); + OnFramebufferSizeChanged(); + BackupGeometry(); + + if (Settings::values.renderer_backend.GetValue() == Settings::RendererBackend::OpenGL) { + if (!LoadOpenGL()) { + return false; + } + } + + return true; +} + +void GRenderWindow::ReleaseRenderTarget() { + if (child_widget) { + layout()->removeWidget(child_widget); + child_widget->deleteLater(); + child_widget = nullptr; + } + main_context.reset(); +} + +void GRenderWindow::CaptureScreenshot(const QString& screenshot_path) { + auto& renderer = system.Renderer(); + + if (renderer.IsScreenshotPending()) { + LOG_WARNING(Render, + "A screenshot is already requested or in progress, ignoring the request"); + return; + } + + const Layout::FramebufferLayout layout{[]() { + u32 height = UISettings::values.screenshot_height.GetValue(); + if (height == 0) { + height = Settings::IsDockedMode() ? Layout::ScreenDocked::Height + : Layout::ScreenUndocked::Height; + height *= Settings::values.resolution_info.up_factor; + } + const u32 width = + UISettings::CalculateWidth(height, Settings::values.aspect_ratio.GetValue()); + return Layout::DefaultFrameLayout(width, height); + }()}; + + screenshot_image = QImage(QSize(layout.width, layout.height), QImage::Format_RGB32); + renderer.RequestScreenshot( + screenshot_image.bits(), + [=, this](bool invert_y) { + const std::string std_screenshot_path = screenshot_path.toStdString(); + if (screenshot_image.mirrored(false, invert_y).save(screenshot_path)) { + LOG_INFO(Frontend, "Screenshot saved to \"{}\"", std_screenshot_path); + } else { + LOG_ERROR(Frontend, "Failed to save screenshot to \"{}\"", std_screenshot_path); + } + }, + layout); +} + +bool GRenderWindow::IsLoadingComplete() const { + return first_frame; +} + +void GRenderWindow::OnMinimalClientAreaChangeRequest(std::pair minimal_size) { + setMinimumSize(minimal_size.first, minimal_size.second); +} + +bool GRenderWindow::InitializeOpenGL() { +#ifdef HAS_OPENGL + if (!QOpenGLContext::supportsThreadedOpenGL()) { + QMessageBox::warning(this, tr("OpenGL not available!"), + tr("OpenGL shared contexts are not supported.")); + return false; + } + + // TODO: One of these flags might be interesting: WA_OpaquePaintEvent, WA_NoBackground, + // WA_DontShowOnScreen, WA_DeleteOnClose + auto child = new OpenGLRenderWidget(this); + child_widget = child; + child_widget->windowHandle()->create(); + auto context = std::make_shared(child->windowHandle()); + main_context = context; + child->SetContext( + std::make_unique(context->GetShareContext(), child->windowHandle())); + + return true; +#else + QMessageBox::warning(this, tr("OpenGL not available!"), + tr("sudachi has not been compiled with OpenGL support.")); + return false; +#endif +} + +bool GRenderWindow::InitializeVulkan() { + auto child = new VulkanRenderWidget(this); + child_widget = child; + child_widget->windowHandle()->create(); + main_context = std::make_unique(); + + return true; +} + +void GRenderWindow::InitializeNull() { + child_widget = new NullRenderWidget(this); + main_context = std::make_unique(); +} + +bool GRenderWindow::LoadOpenGL() { + auto context = CreateSharedContext(); + auto scope = context->Acquire(); + if (!gladLoadGL()) { + QMessageBox::warning( + this, tr("Error while initializing OpenGL!"), + tr("Your GPU may not support OpenGL, or you do not have the latest graphics driver.")); + return false; + } + + const QString renderer = + QString::fromUtf8(reinterpret_cast(glGetString(GL_RENDERER))); + + if (!GLAD_GL_VERSION_4_6) { + LOG_ERROR(Frontend, "GPU does not support OpenGL 4.6: {}", renderer.toStdString()); + QMessageBox::warning(this, tr("Error while initializing OpenGL 4.6!"), + tr("Your GPU may not support OpenGL 4.6, or you do not have the " + "latest graphics driver.

GL Renderer:
%1") + .arg(renderer)); + return false; + } + + QStringList unsupported_gl_extensions = GetUnsupportedGLExtensions(); + if (!unsupported_gl_extensions.empty()) { + QMessageBox::warning( + this, tr("Error while initializing OpenGL!"), + tr("Your GPU may not support one or more required OpenGL extensions. Please ensure you " + "have the latest graphics driver.

GL Renderer:
%1

Unsupported " + "extensions:
%2") + .arg(renderer) + .arg(unsupported_gl_extensions.join(QStringLiteral("
")))); + return false; + } + return true; +} + +QStringList GRenderWindow::GetUnsupportedGLExtensions() const { + QStringList unsupported_ext; + + // Extensions required to support some texture formats. + if (!GLAD_GL_EXT_texture_compression_s3tc) { + unsupported_ext.append(QStringLiteral("EXT_texture_compression_s3tc")); + } + if (!GLAD_GL_ARB_texture_compression_rgtc) { + unsupported_ext.append(QStringLiteral("ARB_texture_compression_rgtc")); + } + + if (!unsupported_ext.empty()) { + const std::string gl_renderer{reinterpret_cast(glGetString(GL_RENDERER))}; + LOG_ERROR(Frontend, "GPU does not support all required extensions: {}", gl_renderer); + } + for (const QString& ext : unsupported_ext) { + LOG_ERROR(Frontend, "Unsupported GL extension: {}", ext.toStdString()); + } + + return unsupported_ext; +} + +void GRenderWindow::OnEmulationStarting(EmuThread* emu_thread_) { + emu_thread = emu_thread_; +} + +void GRenderWindow::OnEmulationStopping() { + emu_thread = nullptr; +} + +void GRenderWindow::showEvent(QShowEvent* event) { + QWidget::showEvent(event); + + // windowHandle() is not initialized until the Window is shown, so we connect it here. + connect(windowHandle(), &QWindow::screenChanged, this, &GRenderWindow::OnFramebufferSizeChanged, + Qt::UniqueConnection); +} + +bool GRenderWindow::eventFilter(QObject* object, QEvent* event) { + if (event->type() == QEvent::HoverMove) { + if (Settings::values.mouse_panning || Settings::values.mouse_enabled) { + auto* hover_event = static_cast(event); + mouseMoveEvent(hover_event); + return false; + } + emit MouseActivity(); + } + return false; +} diff --git a/src/sudachi/bootmanager.h b/src/sudachi/bootmanager.h new file mode 100644 index 0000000..52fcb47 --- /dev/null +++ b/src/sudachi/bootmanager.h @@ -0,0 +1,280 @@ +// SPDX-FileCopyrightText: 2014 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "common/common_types.h" +#include "common/logging/log.h" +#include "common/polyfill_thread.h" +#include "common/thread.h" +#include "core/frontend/emu_window.h" + +class GMainWindow; +class QCamera; +class QCameraImageCapture; +class QCloseEvent; +class QFocusEvent; +class QKeyEvent; +class QMouseEvent; +class QObject; +class QResizeEvent; +class QShowEvent; +class QTouchEvent; +class QWheelEvent; + +namespace Core { +class System; +} // namespace Core + +namespace InputCommon { +class InputSubsystem; +enum class MouseButton; +} // namespace InputCommon + +namespace InputCommon::TasInput { +enum class TasState; +} // namespace InputCommon::TasInput + +namespace VideoCore { +enum class LoadCallbackStage; +} // namespace VideoCore + +class EmuThread final : public QThread { + Q_OBJECT + +public: + explicit EmuThread(Core::System& system); + ~EmuThread() override; + + /** + * Start emulation (on new thread) + * @warning Only call when not running! + */ + void run() override; + + /** + * Sets whether the emulation thread should run or not + * @param should_run Boolean value, set the emulation thread to running if true + */ + void SetRunning(bool should_run) { + // TODO: Prevent other threads from modifying the state until we finish. + { + // Notify the running thread to change state. + std::unique_lock run_lk{m_should_run_mutex}; + m_should_run = should_run; + m_should_run_cv.notify_one(); + } + + // Wait until paused, if pausing. + if (!should_run) { + m_stopped.Wait(); + } + } + + /** + * Check if the emulation thread is running or not + * @return True if the emulation thread is running, otherwise false + */ + bool IsRunning() const { + return m_should_run; + } + + /** + * Requests for the emulation thread to immediately stop running + */ + void ForceStop() { + LOG_WARNING(Frontend, "Force stopping EmuThread"); + m_stop_source.request_stop(); + } + +private: + void EmulationPaused(std::unique_lock& lk); + void EmulationResumed(std::unique_lock& lk); + +private: + Core::System& m_system; + + std::stop_source m_stop_source; + std::mutex m_should_run_mutex; + std::condition_variable_any m_should_run_cv; + Common::Event m_stopped; + bool m_should_run{true}; + +signals: + /** + * Emitted when the CPU has halted execution + * + * @warning When connecting to this signal from other threads, make sure to specify either + * Qt::QueuedConnection (invoke slot within the destination object's message thread) or even + * Qt::BlockingQueuedConnection (additionally block source thread until slot returns) + */ + void DebugModeEntered(); + + /** + * Emitted right before the CPU continues execution + * + * @warning When connecting to this signal from other threads, make sure to specify either + * Qt::QueuedConnection (invoke slot within the destination object's message thread) or even + * Qt::BlockingQueuedConnection (additionally block source thread until slot returns) + */ + void DebugModeLeft(); + + void LoadProgress(VideoCore::LoadCallbackStage stage, std::size_t value, std::size_t total); +}; + +class GRenderWindow : public QWidget, public Core::Frontend::EmuWindow { + Q_OBJECT + +public: + explicit GRenderWindow(GMainWindow* parent, EmuThread* emu_thread_, + std::shared_ptr input_subsystem_, + Core::System& system_); + ~GRenderWindow() override; + + // EmuWindow implementation. + void OnFrameDisplayed() override; + bool IsShown() const override; + std::unique_ptr CreateSharedContext() const override; + + void BackupGeometry(); + void RestoreGeometry(); + void restoreGeometry(const QByteArray& geometry_); // overridden + QByteArray saveGeometry(); // overridden + + qreal windowPixelRatio() const; + + std::pair ScaleTouch(const QPointF& pos) const; + + void closeEvent(QCloseEvent* event) override; + void leaveEvent(QEvent* event) override; + + void resizeEvent(QResizeEvent* event) override; + + /// Converts a Qt keyboard key into NativeKeyboard key + static int QtKeyToSwitchKey(Qt::Key qt_keys); + + /// Converts a Qt modifier keys into NativeKeyboard modifier keys + static int QtModifierToSwitchModifier(Qt::KeyboardModifiers qt_modifiers); + + void keyPressEvent(QKeyEvent* event) override; + void keyReleaseEvent(QKeyEvent* event) override; + + /// Converts a Qt mouse button into MouseInput mouse button + static InputCommon::MouseButton QtButtonToMouseButton(Qt::MouseButton button); + + void mousePressEvent(QMouseEvent* event) override; + void mouseMoveEvent(QMouseEvent* event) override; + void mouseReleaseEvent(QMouseEvent* event) override; + void wheelEvent(QWheelEvent* event) override; + + void InitializeCamera(); + void FinalizeCamera(); + + bool event(QEvent* event) override; + + void focusOutEvent(QFocusEvent* event) override; + + bool InitRenderTarget(); + + /// Destroy the previous run's child_widget which should also destroy the child_window + void ReleaseRenderTarget(); + + bool IsLoadingComplete() const; + + void CaptureScreenshot(const QString& screenshot_path); + + /** + * Instructs the window to re-launch the application using the specified program_index. + * @param program_index Specifies the index within the application of the program to launch. + */ + void ExecuteProgram(std::size_t program_index); + + /// Instructs the window to exit the application. + void Exit(); + +public slots: + void OnEmulationStarting(EmuThread* emu_thread_); + void OnEmulationStopping(); + void OnFramebufferSizeChanged(); + +signals: + /// Emitted when the window is closed + void Closed(); + void FirstFrameDisplayed(); + void ExecuteProgramSignal(std::size_t program_index); + void ExitSignal(); + void MouseActivity(); + void TasPlaybackStateChanged(); + +private: + void TouchBeginEvent(const QTouchEvent* event); + void TouchUpdateEvent(const QTouchEvent* event); + void TouchEndEvent(); + void ConstrainMouse(); + + void RequestCameraCapture(); + void OnCameraCapture(int requestId, const QImage& img); + + void OnMinimalClientAreaChangeRequest(std::pair minimal_size) override; + + bool InitializeOpenGL(); + bool InitializeVulkan(); + void InitializeNull(); + bool LoadOpenGL(); + QStringList GetUnsupportedGLExtensions() const; + + EmuThread* emu_thread; + std::shared_ptr input_subsystem; + + // Main context that will be shared with all other contexts that are requested. + // If this is used in a shared context setting, then this should not be used directly, but + // should instead be shared from + std::shared_ptr main_context; + + /// Temporary storage of the screenshot taken + QImage screenshot_image; + + QByteArray geometry; + + QWidget* child_widget = nullptr; + + bool first_frame = false; + InputCommon::TasInput::TasState last_tas_state; + +#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) && SUDACHI_USE_QT_MULTIMEDIA + bool is_virtual_camera; + int pending_camera_snapshots; + std::vector camera_data; + std::unique_ptr camera; + std::unique_ptr camera_capture; + std::unique_ptr camera_timer; +#endif + + QTimer mouse_constrain_timer; + + Core::System& system; + +protected: + void showEvent(QShowEvent* event) override; + bool eventFilter(QObject* object, QEvent* event) override; +}; diff --git a/src/sudachi/breakpad.cpp b/src/sudachi/breakpad.cpp new file mode 100644 index 0000000..7b6ed0c --- /dev/null +++ b/src/sudachi/breakpad.cpp @@ -0,0 +1,77 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include + +#if defined(_WIN32) +#include +#elif defined(__linux__) +#include +#else +#error Minidump creation not supported on this platform +#endif + +#include "common/fs/fs_paths.h" +#include "common/fs/path_util.h" +#include "sudachi/breakpad.h" + +namespace Breakpad { + +static void PruneDumpDirectory(const std::filesystem::path& dump_path) { + // Code in this function should be exception-safe. + struct Entry { + std::filesystem::path path; + std::filesystem::file_time_type last_write_time; + }; + std::vector existing_dumps; + + // Get existing entries. + std::error_code ec; + std::filesystem::directory_iterator dir(dump_path, ec); + for (auto& entry : dir) { + if (entry.is_regular_file()) { + existing_dumps.push_back(Entry{ + .path = entry.path(), + .last_write_time = entry.last_write_time(ec), + }); + } + } + + // Sort descending by creation date. + std::ranges::stable_sort(existing_dumps, [](const auto& a, const auto& b) { + return a.last_write_time > b.last_write_time; + }); + + // Delete older dumps. + for (size_t i = 5; i < existing_dumps.size(); i++) { + std::filesystem::remove(existing_dumps[i].path, ec); + } +} + +#if defined(__linux__) +[[noreturn]] bool DumpCallback(const google_breakpad::MinidumpDescriptor& descriptor, void* context, + bool succeeded) { + // Prevent time- and space-consuming core dumps from being generated, as we have + // already generated a minidump and a core file will not be useful anyway. + _exit(1); +} +#endif + +void InstallCrashHandler() { + // Write crash dumps to profile directory. + const auto dump_path = GetSudachiPath(Common::FS::SudachiPath::CrashDumpsDir); + PruneDumpDirectory(dump_path); + +#if defined(_WIN32) + // TODO: If we switch to MinGW builds for Windows, this needs to be wrapped in a C API. + static google_breakpad::ExceptionHandler eh{dump_path, nullptr, nullptr, nullptr, + google_breakpad::ExceptionHandler::HANDLER_ALL}; +#elif defined(__linux__) + static google_breakpad::MinidumpDescriptor descriptor{dump_path}; + static google_breakpad::ExceptionHandler eh{descriptor, nullptr, DumpCallback, + nullptr, true, -1}; +#endif +} + +} // namespace Breakpad diff --git a/src/sudachi/breakpad.h b/src/sudachi/breakpad.h new file mode 100644 index 0000000..0e20751 --- /dev/null +++ b/src/sudachi/breakpad.h @@ -0,0 +1,10 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +namespace Breakpad { + +void InstallCrashHandler(); + +} diff --git a/src/sudachi/compatdb.cpp b/src/sudachi/compatdb.cpp new file mode 100644 index 0000000..5062c07 --- /dev/null +++ b/src/sudachi/compatdb.cpp @@ -0,0 +1,210 @@ +// SPDX-FileCopyrightText: 2017 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include +#include +#include +#include "common/logging/log.h" +#include "common/telemetry.h" +#include "core/telemetry_session.h" +#include "ui_compatdb.h" +#include "sudachi/compatdb.h" + +CompatDB::CompatDB(Core::TelemetrySession& telemetry_session_, QWidget* parent) + : QWizard(parent, Qt::WindowTitleHint | Qt::WindowCloseButtonHint | Qt::WindowSystemMenuHint), + ui{std::make_unique()}, telemetry_session{telemetry_session_} { + ui->setupUi(this); + + connect(ui->radioButton_GameBoot_Yes, &QRadioButton::clicked, this, &CompatDB::EnableNext); + connect(ui->radioButton_GameBoot_No, &QRadioButton::clicked, this, &CompatDB::EnableNext); + connect(ui->radioButton_Gameplay_Yes, &QRadioButton::clicked, this, &CompatDB::EnableNext); + connect(ui->radioButton_Gameplay_No, &QRadioButton::clicked, this, &CompatDB::EnableNext); + connect(ui->radioButton_NoFreeze_Yes, &QRadioButton::clicked, this, &CompatDB::EnableNext); + connect(ui->radioButton_NoFreeze_No, &QRadioButton::clicked, this, &CompatDB::EnableNext); + connect(ui->radioButton_Complete_Yes, &QRadioButton::clicked, this, &CompatDB::EnableNext); + connect(ui->radioButton_Complete_No, &QRadioButton::clicked, this, &CompatDB::EnableNext); + connect(ui->radioButton_Graphical_Major, &QRadioButton::clicked, this, &CompatDB::EnableNext); + connect(ui->radioButton_Graphical_Minor, &QRadioButton::clicked, this, &CompatDB::EnableNext); + connect(ui->radioButton_Graphical_No, &QRadioButton::clicked, this, &CompatDB::EnableNext); + connect(ui->radioButton_Audio_Major, &QRadioButton::clicked, this, &CompatDB::EnableNext); + connect(ui->radioButton_Audio_Minor, &QRadioButton::clicked, this, &CompatDB::EnableNext); + connect(ui->radioButton_Audio_No, &QRadioButton::clicked, this, &CompatDB::EnableNext); + + connect(button(NextButton), &QPushButton::clicked, this, &CompatDB::Submit); + connect(&testcase_watcher, &QFutureWatcher::finished, this, + &CompatDB::OnTestcaseSubmitted); +} + +CompatDB::~CompatDB() = default; + +enum class CompatDBPage { + Intro = 0, + GameBoot = 1, + GamePlay = 2, + Freeze = 3, + Completion = 4, + Graphical = 5, + Audio = 6, + Final = 7, +}; + +void CompatDB::Submit() { + QButtonGroup* compatibility_GameBoot = new QButtonGroup(this); + compatibility_GameBoot->addButton(ui->radioButton_GameBoot_Yes, 0); + compatibility_GameBoot->addButton(ui->radioButton_GameBoot_No, 1); + + QButtonGroup* compatibility_Gameplay = new QButtonGroup(this); + compatibility_Gameplay->addButton(ui->radioButton_Gameplay_Yes, 0); + compatibility_Gameplay->addButton(ui->radioButton_Gameplay_No, 1); + + QButtonGroup* compatibility_NoFreeze = new QButtonGroup(this); + compatibility_NoFreeze->addButton(ui->radioButton_NoFreeze_Yes, 0); + compatibility_NoFreeze->addButton(ui->radioButton_NoFreeze_No, 1); + + QButtonGroup* compatibility_Complete = new QButtonGroup(this); + compatibility_Complete->addButton(ui->radioButton_Complete_Yes, 0); + compatibility_Complete->addButton(ui->radioButton_Complete_No, 1); + + QButtonGroup* compatibility_Graphical = new QButtonGroup(this); + compatibility_Graphical->addButton(ui->radioButton_Graphical_Major, 0); + compatibility_Graphical->addButton(ui->radioButton_Graphical_Minor, 1); + compatibility_Graphical->addButton(ui->radioButton_Graphical_No, 2); + + QButtonGroup* compatibility_Audio = new QButtonGroup(this); + compatibility_Audio->addButton(ui->radioButton_Audio_Major, 0); + compatibility_Graphical->addButton(ui->radioButton_Audio_Minor, 1); + compatibility_Audio->addButton(ui->radioButton_Audio_No, 2); + + const int compatibility = static_cast(CalculateCompatibility()); + + switch ((static_cast(currentId()))) { + case CompatDBPage::Intro: + break; + case CompatDBPage::GameBoot: + if (compatibility_GameBoot->checkedId() == -1) { + button(NextButton)->setEnabled(false); + } + break; + case CompatDBPage::GamePlay: + if (compatibility_Gameplay->checkedId() == -1) { + button(NextButton)->setEnabled(false); + } + break; + case CompatDBPage::Freeze: + if (compatibility_NoFreeze->checkedId() == -1) { + button(NextButton)->setEnabled(false); + } + break; + case CompatDBPage::Completion: + if (compatibility_Complete->checkedId() == -1) { + button(NextButton)->setEnabled(false); + } + break; + case CompatDBPage::Graphical: + if (compatibility_Graphical->checkedId() == -1) { + button(NextButton)->setEnabled(false); + } + break; + case CompatDBPage::Audio: + if (compatibility_Audio->checkedId() == -1) { + button(NextButton)->setEnabled(false); + } + break; + case CompatDBPage::Final: + back(); + LOG_INFO(Frontend, "Compatibility Rating: {}", compatibility); + telemetry_session.AddField(Common::Telemetry::FieldType::UserFeedback, "Compatibility", + compatibility); + + button(NextButton)->setEnabled(false); + button(NextButton)->setText(tr("Submitting")); + button(CancelButton)->setVisible(false); + + testcase_watcher.setFuture( + QtConcurrent::run([this] { return telemetry_session.SubmitTestcase(); })); + break; + default: + LOG_ERROR(Frontend, "Unexpected page: {}", currentId()); + break; + } +} + +int CompatDB::nextId() const { + switch ((static_cast(currentId()))) { + case CompatDBPage::Intro: + return static_cast(CompatDBPage::GameBoot); + case CompatDBPage::GameBoot: + if (ui->radioButton_GameBoot_No->isChecked()) { + return static_cast(CompatDBPage::Final); + } + return static_cast(CompatDBPage::GamePlay); + case CompatDBPage::GamePlay: + if (ui->radioButton_Gameplay_No->isChecked()) { + return static_cast(CompatDBPage::Final); + } + return static_cast(CompatDBPage::Freeze); + case CompatDBPage::Freeze: + if (ui->radioButton_NoFreeze_No->isChecked()) { + return static_cast(CompatDBPage::Final); + } + return static_cast(CompatDBPage::Completion); + case CompatDBPage::Completion: + if (ui->radioButton_Complete_No->isChecked()) { + return static_cast(CompatDBPage::Final); + } + return static_cast(CompatDBPage::Graphical); + case CompatDBPage::Graphical: + return static_cast(CompatDBPage::Audio); + case CompatDBPage::Audio: + return static_cast(CompatDBPage::Final); + case CompatDBPage::Final: + return -1; + default: + LOG_ERROR(Frontend, "Unexpected page: {}", currentId()); + return static_cast(CompatDBPage::Intro); + } +} + +CompatibilityStatus CompatDB::CalculateCompatibility() const { + if (ui->radioButton_GameBoot_No->isChecked()) { + return CompatibilityStatus::WontBoot; + } + + if (ui->radioButton_Gameplay_No->isChecked()) { + return CompatibilityStatus::IntroMenu; + } + + if (ui->radioButton_NoFreeze_No->isChecked() || ui->radioButton_Complete_No->isChecked()) { + return CompatibilityStatus::Ingame; + } + + if (ui->radioButton_Graphical_Major->isChecked() || ui->radioButton_Audio_Major->isChecked()) { + return CompatibilityStatus::Ingame; + } + + if (ui->radioButton_Graphical_Minor->isChecked() || ui->radioButton_Audio_Minor->isChecked()) { + return CompatibilityStatus::Playable; + } + + return CompatibilityStatus::Perfect; +} + +void CompatDB::OnTestcaseSubmitted() { + if (!testcase_watcher.result()) { + QMessageBox::critical(this, tr("Communication error"), + tr("An error occurred while sending the Testcase")); + button(NextButton)->setEnabled(true); + button(NextButton)->setText(tr("Next")); + button(CancelButton)->setVisible(true); + } else { + next(); + // older versions of QT don't support the "NoCancelButtonOnLastPage" option, this is a + // workaround + button(CancelButton)->setVisible(false); + } +} + +void CompatDB::EnableNext() { + button(NextButton)->setEnabled(true); +} diff --git a/src/sudachi/compatdb.h b/src/sudachi/compatdb.h new file mode 100644 index 0000000..37e1127 --- /dev/null +++ b/src/sudachi/compatdb.h @@ -0,0 +1,43 @@ +// SPDX-FileCopyrightText: 2017 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include +#include +#include "core/telemetry_session.h" + +namespace Ui { +class CompatDB; +} + +enum class CompatibilityStatus { + Perfect = 0, + Playable = 1, + // Unused: Okay = 2, + Ingame = 3, + IntroMenu = 4, + WontBoot = 5, +}; + +class CompatDB : public QWizard { + Q_OBJECT + +public: + explicit CompatDB(Core::TelemetrySession& telemetry_session_, QWidget* parent = nullptr); + ~CompatDB(); + int nextId() const override; + +private: + QFutureWatcher testcase_watcher; + + std::unique_ptr ui; + + void Submit(); + CompatibilityStatus CalculateCompatibility() const; + void OnTestcaseSubmitted(); + void EnableNext(); + + Core::TelemetrySession& telemetry_session; +}; diff --git a/src/sudachi/compatdb.ui b/src/sudachi/compatdb.ui new file mode 100644 index 0000000..2b75960 --- /dev/null +++ b/src/sudachi/compatdb.ui @@ -0,0 +1,398 @@ + + + CompatDB + + + + 0 + 0 + 600 + 482 + + + + + 500 + 410 + + + + Report Compatibility + + + QWizard::DisabledBackButtonOnLastPage|QWizard::HelpButtonOnRight|QWizard::NoBackButtonOnStartPage + + + + Report Game Compatibility + + + 0 + + + + + + <html><head/><body><p><span style=" font-size:10pt;">Should you choose to submit a test case to the </span><a href="https://sudachi-emu.org/game/"><span style=" font-size:10pt; text-decoration: underline; color:#0000ff;">sudachi Compatibility List</span></a><span style=" font-size:10pt;">, The following information will be collected and displayed on the site:</span></p><ul style="margin-top: 0px; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; -qt-list-indent: 1;"><li style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Hardware Information (CPU / GPU / Operating System)</li><li style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Which version of sudachi you are running</li><li style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The connected sudachi account</li></ul></body></html> + + + true + + + true + + + + + + + Qt::Vertical + + + + 20 + 0 + + + + + + + + + Report Game Compatibility + + + 1 + + + + + + + 10 + + + + <html><head/><body><p>Does the game boot?</p></body></html> + + + true + + + + + + + Qt::Vertical + + + + 20 + 0 + + + + + + + + Yes The game starts to output video or audio + + + + + + + No The game doesn't get past the "Launching..." screen + + + + + + + + Report Game Compatibility + + + 2 + + + + + + Yes The game gets past the intro/menu and into gameplay + + + + + + + No The game crashes or freezes while loading or using the menu + + + + + + + + 10 + + + + <html><head/><body><p>Does the game reach gameplay?</p></body></html> + + + true + + + + + + + Qt::Vertical + + + + 20 + 0 + + + + + + + + + Report Game Compatibility + + + 3 + + + + + + Yes The game works without crashes + + + + + + + No The game crashes or freezes during gameplay + + + + + + + + 10 + + + + <html><head/><body><p>Does the game work without crashing, freezing or locking up during gameplay?</p></body></html> + + + true + + + + + + + Qt::Vertical + + + + 20 + 0 + + + + + + + + + Report Game Compatibility + + + 4 + + + + + + Yes The game can be finished without any workarounds + + + + + + + No The game can't progress past a certain area + + + + + + + + 10 + + + + <html><head/><body><p>Is the game completely playable from start to finish?</p></body></html> + + + true + + + + + + + Qt::Vertical + + + + 20 + 0 + + + + + + + + + Report Game Compatibility + + + 5 + + + + + + Major The game has major graphical errors + + + + + + + Minor The game has minor graphical errors + + + + + + + None Everything is rendered as it looks on the Nintendo Switch + + + + + + + + 10 + + + + <html><head/><body><p>Does the game have any graphical glitches?</p></body></html> + + + true + + + + + + + Qt::Vertical + + + + 20 + 0 + + + + + + + + + Report Game Compatibility + + + 6 + + + + + + Major The game has major audio errors + + + + + + + Minor The game has minor audio errors + + + + + + + None Audio is played perfectly + + + + + + + + 10 + + + + <html><head/><body><p>Does the game have any audio glitches / missing effects?</p></body></html> + + + true + + + + + + + Qt::Vertical + + + + 20 + 0 + + + + + + + + + Thank you for your submission! + + + 7 + + + + + + diff --git a/src/sudachi/compatibility_list.cpp b/src/sudachi/compatibility_list.cpp new file mode 100644 index 0000000..4bd0c5a --- /dev/null +++ b/src/sudachi/compatibility_list.cpp @@ -0,0 +1,17 @@ +// SPDX-FileCopyrightText: Copyright 2018 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include + +#include + +#include "sudachi/compatibility_list.h" + +CompatibilityList::const_iterator FindMatchingCompatibilityEntry( + const CompatibilityList& compatibility_list, u64 program_id) { + return std::find_if(compatibility_list.begin(), compatibility_list.end(), + [program_id](const auto& element) { + std::string pid = fmt::format("{:016X}", program_id); + return element.first == pid; + }); +} diff --git a/src/sudachi/compatibility_list.h b/src/sudachi/compatibility_list.h new file mode 100644 index 0000000..00e4b5e --- /dev/null +++ b/src/sudachi/compatibility_list.h @@ -0,0 +1,16 @@ +// SPDX-FileCopyrightText: Copyright 2018 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include + +#include + +#include "common/common_types.h" + +using CompatibilityList = std::unordered_map>; + +CompatibilityList::const_iterator FindMatchingCompatibilityEntry( + const CompatibilityList& compatibility_list, u64 program_id); diff --git a/src/sudachi/configuration/config.cpp b/src/sudachi/configuration/config.cpp new file mode 100644 index 0000000..c9f3399 --- /dev/null +++ b/src/sudachi/configuration/config.cpp @@ -0,0 +1,1309 @@ +// SPDX-FileCopyrightText: 2014 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include +#include +#include +#include "common/fs/fs.h" +#include "common/fs/path_util.h" +#include "common/settings.h" +#include "common/settings_common.h" +#include "common/settings_enums.h" +#include "core/core.h" +#include "core/hle/service/acc/profile_manager.h" +#include "core/hle/service/hid/controllers/npad.h" +#include "input_common/main.h" +#include "network/network.h" +#include "sudachi/configuration/config.h" + +namespace FS = Common::FS; + +Config::Config(const std::string& config_name, ConfigType config_type) + : type(config_type), global{config_type == ConfigType::GlobalConfig} { + Initialize(config_name); +} + +Config::~Config() { + if (global) { + Save(); + } +} + +const std::array Config::default_buttons = { + Qt::Key_C, Qt::Key_X, Qt::Key_V, Qt::Key_Z, Qt::Key_F, + Qt::Key_G, Qt::Key_Q, Qt::Key_E, Qt::Key_R, Qt::Key_T, + Qt::Key_M, Qt::Key_N, Qt::Key_Left, Qt::Key_Up, Qt::Key_Right, + Qt::Key_Down, Qt::Key_Q, Qt::Key_E, 0, 0, + Qt::Key_Q, Qt::Key_E, +}; + +const std::array Config::default_motions = { + Qt::Key_7, + Qt::Key_8, +}; + +const std::array, Settings::NativeAnalog::NumAnalogs> Config::default_analogs{{ + { + Qt::Key_W, + Qt::Key_S, + Qt::Key_A, + Qt::Key_D, + }, + { + Qt::Key_I, + Qt::Key_K, + Qt::Key_J, + Qt::Key_L, + }, +}}; + +const std::array Config::default_stick_mod = { + Qt::Key_Shift, + 0, +}; + +const std::array Config::default_ringcon_analogs{{ + Qt::Key_A, + Qt::Key_D, +}}; + +const std::map Config::anti_aliasing_texts_map = { + {Settings::AntiAliasing::None, QStringLiteral(QT_TRANSLATE_NOOP("GMainWindow", "None"))}, + {Settings::AntiAliasing::Fxaa, QStringLiteral(QT_TRANSLATE_NOOP("GMainWindow", "FXAA"))}, + {Settings::AntiAliasing::Smaa, QStringLiteral(QT_TRANSLATE_NOOP("GMainWindow", "SMAA"))}, +}; + +const std::map Config::scaling_filter_texts_map = { + {Settings::ScalingFilter::NearestNeighbor, + QStringLiteral(QT_TRANSLATE_NOOP("GMainWindow", "Nearest"))}, + {Settings::ScalingFilter::Bilinear, + QStringLiteral(QT_TRANSLATE_NOOP("GMainWindow", "Bilinear"))}, + {Settings::ScalingFilter::Bicubic, QStringLiteral(QT_TRANSLATE_NOOP("GMainWindow", "Bicubic"))}, + {Settings::ScalingFilter::Gaussian, + QStringLiteral(QT_TRANSLATE_NOOP("GMainWindow", "Gaussian"))}, + {Settings::ScalingFilter::ScaleForce, + QStringLiteral(QT_TRANSLATE_NOOP("GMainWindow", "ScaleForce"))}, + {Settings::ScalingFilter::Fsr, QStringLiteral(QT_TRANSLATE_NOOP("GMainWindow", "FSR"))}, +}; + +const std::map Config::use_docked_mode_texts_map = { + {Settings::ConsoleMode::Docked, QStringLiteral(QT_TRANSLATE_NOOP("GMainWindow", "Docked"))}, + {Settings::ConsoleMode::Handheld, QStringLiteral(QT_TRANSLATE_NOOP("GMainWindow", "Handheld"))}, +}; + +const std::map Config::gpu_accuracy_texts_map = { + {Settings::GpuAccuracy::Normal, QStringLiteral(QT_TRANSLATE_NOOP("GMainWindow", "Normal"))}, + {Settings::GpuAccuracy::High, QStringLiteral(QT_TRANSLATE_NOOP("GMainWindow", "High"))}, + {Settings::GpuAccuracy::Extreme, QStringLiteral(QT_TRANSLATE_NOOP("GMainWindow", "Extreme"))}, +}; + +const std::map Config::renderer_backend_texts_map = { + {Settings::RendererBackend::Vulkan, QStringLiteral(QT_TRANSLATE_NOOP("GMainWindow", "Vulkan"))}, + {Settings::RendererBackend::OpenGL, QStringLiteral(QT_TRANSLATE_NOOP("GMainWindow", "OpenGL"))}, + {Settings::RendererBackend::Null, QStringLiteral(QT_TRANSLATE_NOOP("GMainWindow", "Null"))}, +}; + +const std::map Config::shader_backend_texts_map = { + {Settings::ShaderBackend::Glsl, QStringLiteral(QT_TRANSLATE_NOOP("GMainWindow", "GLSL"))}, + {Settings::ShaderBackend::Glasm, QStringLiteral(QT_TRANSLATE_NOOP("GMainWindow", "GLASM"))}, + {Settings::ShaderBackend::SpirV, QStringLiteral(QT_TRANSLATE_NOOP("GMainWindow", "SPIRV"))}, +}; + +// This shouldn't have anything except static initializers (no functions). So +// QKeySequence(...).toString() is NOT ALLOWED HERE. +// This must be in alphabetical order according to action name as it must have the same order as +// UISetting::values.shortcuts, which is alphabetically ordered. +// clang-format off +const std::array Config::default_hotkeys{{ + {QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Audio Mute/Unmute")), QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Main Window")), {QStringLiteral("Ctrl+M"), QStringLiteral("Home+Dpad_Right"), Qt::WindowShortcut, false}}, + {QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Audio Volume Down")), QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Main Window")), {QStringLiteral("-"), QStringLiteral("Home+Dpad_Down"), Qt::ApplicationShortcut, true}}, + {QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Audio Volume Up")), QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Main Window")), {QStringLiteral("="), QStringLiteral("Home+Dpad_Up"), Qt::ApplicationShortcut, true}}, + {QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Capture Screenshot")), QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Main Window")), {QStringLiteral("Ctrl+P"), QStringLiteral("Screenshot"), Qt::WidgetWithChildrenShortcut, false}}, + {QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Change Adapting Filter")), QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Main Window")), {QStringLiteral("F8"), QStringLiteral("Home+L"), Qt::ApplicationShortcut, false}}, + {QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Change Docked Mode")), QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Main Window")), {QStringLiteral("F10"), QStringLiteral("Home+X"), Qt::ApplicationShortcut, false}}, + {QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Change GPU Accuracy")), QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Main Window")), {QStringLiteral("F9"), QStringLiteral("Home+R"), Qt::ApplicationShortcut, false}}, + {QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Continue/Pause Emulation")), QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Main Window")), {QStringLiteral("F4"), QStringLiteral("Home+Plus"), Qt::WindowShortcut, false}}, + {QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Exit Fullscreen")), QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Main Window")), {QStringLiteral("Esc"), QStringLiteral(""), Qt::WindowShortcut, false}}, + {QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Exit sudachi")), QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Main Window")), {QStringLiteral("Ctrl+Q"), QStringLiteral("Home+Minus"), Qt::WindowShortcut, false}}, + {QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Fullscreen")), QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Main Window")), {QStringLiteral("F11"), QStringLiteral("Home+B"), Qt::WindowShortcut, false}}, + {QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Load File")), QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Main Window")), {QStringLiteral("Ctrl+O"), QStringLiteral(""), Qt::WidgetWithChildrenShortcut, false}}, + {QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Load/Remove Amiibo")), QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Main Window")), {QStringLiteral("F2"), QStringLiteral("Home+A"), Qt::WidgetWithChildrenShortcut, false}}, + {QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Restart Emulation")), QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Main Window")), {QStringLiteral("F6"), QStringLiteral("R+Plus+Minus"), Qt::WindowShortcut, false}}, + {QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Stop Emulation")), QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Main Window")), {QStringLiteral("F5"), QStringLiteral("L+Plus+Minus"), Qt::WindowShortcut, false}}, + {QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "TAS Record")), QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Main Window")), {QStringLiteral("Ctrl+F7"), QStringLiteral(""), Qt::ApplicationShortcut, false}}, + {QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "TAS Reset")), QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Main Window")), {QStringLiteral("Ctrl+F6"), QStringLiteral(""), Qt::ApplicationShortcut, false}}, + {QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "TAS Start/Stop")), QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Main Window")), {QStringLiteral("Ctrl+F5"), QStringLiteral(""), Qt::ApplicationShortcut, false}}, + {QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Toggle Filter Bar")), QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Main Window")), {QStringLiteral("Ctrl+F"), QStringLiteral(""), Qt::WindowShortcut, false}}, + {QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Toggle Framerate Limit")), QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Main Window")), {QStringLiteral("Ctrl+U"), QStringLiteral("Home+Y"), Qt::ApplicationShortcut, false}}, + {QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Toggle Mouse Panning")), QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Main Window")), {QStringLiteral("Ctrl+F9"), QStringLiteral(""), Qt::ApplicationShortcut, false}}, + {QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Toggle Renderdoc Capture")), QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Main Window")), {QStringLiteral(""), QStringLiteral(""), Qt::ApplicationShortcut, false}}, + {QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Toggle Status Bar")), QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Main Window")), {QStringLiteral("Ctrl+S"), QStringLiteral(""), Qt::WindowShortcut, false}}, +}}; +// clang-format on + +void Config::Initialize(const std::string& config_name) { + const auto fs_config_loc = FS::GetSudachiPath(FS::SudachiPath::ConfigDir); + const auto config_file = fmt::format("{}.ini", config_name); + + switch (type) { + case ConfigType::GlobalConfig: + qt_config_loc = FS::PathToUTF8String(fs_config_loc / config_file); + void(FS::CreateParentDir(qt_config_loc)); + qt_config = std::make_unique(QString::fromStdString(qt_config_loc), + QSettings::IniFormat); + Reload(); + break; + case ConfigType::PerGameConfig: + qt_config_loc = + FS::PathToUTF8String(fs_config_loc / "custom" / FS::ToU8String(config_file)); + void(FS::CreateParentDir(qt_config_loc)); + qt_config = std::make_unique(QString::fromStdString(qt_config_loc), + QSettings::IniFormat); + Reload(); + break; + case ConfigType::InputProfile: + qt_config_loc = FS::PathToUTF8String(fs_config_loc / "input" / config_file); + void(FS::CreateParentDir(qt_config_loc)); + qt_config = std::make_unique(QString::fromStdString(qt_config_loc), + QSettings::IniFormat); + break; + } +} + +bool Config::IsCustomConfig() { + return type == ConfigType::PerGameConfig; +} + +void Config::ReadPlayerValue(std::size_t player_index) { + const QString player_prefix = [this, player_index] { + if (type == ConfigType::InputProfile) { + return QString{}; + } else { + return QStringLiteral("player_%1_").arg(player_index); + } + }(); + + auto& player = Settings::values.players.GetValue()[player_index]; + if (IsCustomConfig()) { + const auto profile_name = + qt_config->value(QStringLiteral("%1profile_name").arg(player_prefix), QString{}) + .toString() + .toStdString(); + if (profile_name.empty()) { + // Use the global input config + player = Settings::values.players.GetValue(true)[player_index]; + return; + } + player.profile_name = profile_name; + } + + if (player_prefix.isEmpty() && Settings::IsConfiguringGlobal()) { + const auto controller = static_cast( + qt_config + ->value(QStringLiteral("%1type").arg(player_prefix), + static_cast(Settings::ControllerType::ProController)) + .toUInt()); + + if (controller == Settings::ControllerType::LeftJoycon || + controller == Settings::ControllerType::RightJoycon) { + player.controller_type = controller; + } + } else { + player.connected = + ReadSetting(QStringLiteral("%1connected").arg(player_prefix), player_index == 0) + .toBool(); + + player.controller_type = static_cast( + qt_config + ->value(QStringLiteral("%1type").arg(player_prefix), + static_cast(Settings::ControllerType::ProController)) + .toUInt()); + + player.vibration_enabled = + qt_config->value(QStringLiteral("%1vibration_enabled").arg(player_prefix), true) + .toBool(); + + player.vibration_strength = + qt_config->value(QStringLiteral("%1vibration_strength").arg(player_prefix), 100) + .toInt(); + + player.body_color_left = qt_config + ->value(QStringLiteral("%1body_color_left").arg(player_prefix), + Settings::JOYCON_BODY_NEON_BLUE) + .toUInt(); + player.body_color_right = + qt_config + ->value(QStringLiteral("%1body_color_right").arg(player_prefix), + Settings::JOYCON_BODY_NEON_RED) + .toUInt(); + player.button_color_left = + qt_config + ->value(QStringLiteral("%1button_color_left").arg(player_prefix), + Settings::JOYCON_BUTTONS_NEON_BLUE) + .toUInt(); + player.button_color_right = + qt_config + ->value(QStringLiteral("%1button_color_right").arg(player_prefix), + Settings::JOYCON_BUTTONS_NEON_RED) + .toUInt(); + } + + for (int i = 0; i < Settings::NativeButton::NumButtons; ++i) { + const std::string default_param = InputCommon::GenerateKeyboardParam(default_buttons[i]); + auto& player_buttons = player.buttons[i]; + + player_buttons = qt_config + ->value(QStringLiteral("%1").arg(player_prefix) + + QString::fromUtf8(Settings::NativeButton::mapping[i]), + QString::fromStdString(default_param)) + .toString() + .toStdString(); + if (player_buttons.empty()) { + player_buttons = default_param; + } + } + + for (int i = 0; i < Settings::NativeAnalog::NumAnalogs; ++i) { + const std::string default_param = InputCommon::GenerateAnalogParamFromKeys( + default_analogs[i][0], default_analogs[i][1], default_analogs[i][2], + default_analogs[i][3], default_stick_mod[i], 0.5f); + auto& player_analogs = player.analogs[i]; + + player_analogs = qt_config + ->value(QStringLiteral("%1").arg(player_prefix) + + QString::fromUtf8(Settings::NativeAnalog::mapping[i]), + QString::fromStdString(default_param)) + .toString() + .toStdString(); + if (player_analogs.empty()) { + player_analogs = default_param; + } + } + + for (int i = 0; i < Settings::NativeMotion::NumMotions; ++i) { + const std::string default_param = InputCommon::GenerateKeyboardParam(default_motions[i]); + auto& player_motions = player.motions[i]; + + player_motions = qt_config + ->value(QStringLiteral("%1").arg(player_prefix) + + QString::fromUtf8(Settings::NativeMotion::mapping[i]), + QString::fromStdString(default_param)) + .toString() + .toStdString(); + if (player_motions.empty()) { + player_motions = default_param; + } + } +} + +void Config::ReadDebugValues() { + for (int i = 0; i < Settings::NativeButton::NumButtons; ++i) { + const std::string default_param = InputCommon::GenerateKeyboardParam(default_buttons[i]); + auto& debug_pad_buttons = Settings::values.debug_pad_buttons[i]; + + debug_pad_buttons = qt_config + ->value(QStringLiteral("debug_pad_") + + QString::fromUtf8(Settings::NativeButton::mapping[i]), + QString::fromStdString(default_param)) + .toString() + .toStdString(); + if (debug_pad_buttons.empty()) { + debug_pad_buttons = default_param; + } + } + + for (int i = 0; i < Settings::NativeAnalog::NumAnalogs; ++i) { + const std::string default_param = InputCommon::GenerateAnalogParamFromKeys( + default_analogs[i][0], default_analogs[i][1], default_analogs[i][2], + default_analogs[i][3], default_stick_mod[i], 0.5f); + auto& debug_pad_analogs = Settings::values.debug_pad_analogs[i]; + + debug_pad_analogs = qt_config + ->value(QStringLiteral("debug_pad_") + + QString::fromUtf8(Settings::NativeAnalog::mapping[i]), + QString::fromStdString(default_param)) + .toString() + .toStdString(); + if (debug_pad_analogs.empty()) { + debug_pad_analogs = default_param; + } + } +} + +void Config::ReadTouchscreenValues() { + Settings::values.touchscreen.enabled = + ReadSetting(QStringLiteral("touchscreen_enabled"), true).toBool(); + + Settings::values.touchscreen.rotation_angle = + ReadSetting(QStringLiteral("touchscreen_angle"), 0).toUInt(); + Settings::values.touchscreen.diameter_x = + ReadSetting(QStringLiteral("touchscreen_diameter_x"), 15).toUInt(); + Settings::values.touchscreen.diameter_y = + ReadSetting(QStringLiteral("touchscreen_diameter_y"), 15).toUInt(); +} + +void Config::ReadHidbusValues() { + const std::string default_param = InputCommon::GenerateAnalogParamFromKeys( + 0, 0, default_ringcon_analogs[0], default_ringcon_analogs[1], 0, 0.05f); + auto& ringcon_analogs = Settings::values.ringcon_analogs; + + ringcon_analogs = + qt_config->value(QStringLiteral("ring_controller"), QString::fromStdString(default_param)) + .toString() + .toStdString(); + if (ringcon_analogs.empty()) { + ringcon_analogs = default_param; + } +} + +void Config::ReadAudioValues() { + qt_config->beginGroup(QStringLiteral("Audio")); + + ReadCategory(Settings::Category::Audio); + ReadCategory(Settings::Category::UiAudio); + + qt_config->endGroup(); +} + +void Config::ReadControlValues() { + qt_config->beginGroup(QStringLiteral("Controls")); + + ReadCategory(Settings::Category::Controls); + + Settings::values.players.SetGlobal(!IsCustomConfig()); + for (std::size_t p = 0; p < Settings::values.players.GetValue().size(); ++p) { + ReadPlayerValue(p); + } + + // Disable docked mode if handheld is selected + const auto controller_type = Settings::values.players.GetValue()[0].controller_type; + if (controller_type == Settings::ControllerType::Handheld) { + Settings::values.use_docked_mode.SetGlobal(!IsCustomConfig()); + Settings::values.use_docked_mode.SetValue(Settings::ConsoleMode::Handheld); + } + + if (IsCustomConfig()) { + qt_config->endGroup(); + return; + } + ReadDebugValues(); + ReadTouchscreenValues(); + ReadMotionTouchValues(); + ReadHidbusValues(); + + qt_config->endGroup(); +} + +void Config::ReadMotionTouchValues() { + int num_touch_from_button_maps = + qt_config->beginReadArray(QStringLiteral("touch_from_button_maps")); + + if (num_touch_from_button_maps > 0) { + const auto append_touch_from_button_map = [this] { + Settings::TouchFromButtonMap map; + map.name = ReadSetting(QStringLiteral("name"), QStringLiteral("default")) + .toString() + .toStdString(); + const int num_touch_maps = qt_config->beginReadArray(QStringLiteral("entries")); + map.buttons.reserve(num_touch_maps); + for (int i = 0; i < num_touch_maps; i++) { + qt_config->setArrayIndex(i); + std::string touch_mapping = + ReadSetting(QStringLiteral("bind")).toString().toStdString(); + map.buttons.emplace_back(std::move(touch_mapping)); + } + qt_config->endArray(); // entries + Settings::values.touch_from_button_maps.emplace_back(std::move(map)); + }; + + for (int i = 0; i < num_touch_from_button_maps; ++i) { + qt_config->setArrayIndex(i); + append_touch_from_button_map(); + } + } else { + Settings::values.touch_from_button_maps.emplace_back( + Settings::TouchFromButtonMap{"default", {}}); + num_touch_from_button_maps = 1; + } + qt_config->endArray(); + + Settings::values.touch_from_button_map_index = std::clamp( + Settings::values.touch_from_button_map_index.GetValue(), 0, num_touch_from_button_maps - 1); +} + +void Config::ReadCoreValues() { + qt_config->beginGroup(QStringLiteral("Core")); + + ReadCategory(Settings::Category::Core); + + qt_config->endGroup(); +} + +void Config::ReadDataStorageValues() { + qt_config->beginGroup(QStringLiteral("Data Storage")); + + FS::SetSudachiPath( + FS::SudachiPath::NANDDir, + qt_config + ->value(QStringLiteral("nand_directory"), + QString::fromStdString(FS::GetSudachiPathString(FS::SudachiPath::NANDDir))) + .toString() + .toStdString()); + FS::SetSudachiPath( + FS::SudachiPath::SDMCDir, + qt_config + ->value(QStringLiteral("sdmc_directory"), + QString::fromStdString(FS::GetSudachiPathString(FS::SudachiPath::SDMCDir))) + .toString() + .toStdString()); + FS::SetSudachiPath( + FS::SudachiPath::LoadDir, + qt_config + ->value(QStringLiteral("load_directory"), + QString::fromStdString(FS::GetSudachiPathString(FS::SudachiPath::LoadDir))) + .toString() + .toStdString()); + FS::SetSudachiPath( + FS::SudachiPath::DumpDir, + qt_config + ->value(QStringLiteral("dump_directory"), + QString::fromStdString(FS::GetSudachiPathString(FS::SudachiPath::DumpDir))) + .toString() + .toStdString()); + FS::SetSudachiPath(FS::SudachiPath::TASDir, + qt_config + ->value(QStringLiteral("tas_directory"), + QString::fromStdString(FS::GetSudachiPathString(FS::SudachiPath::TASDir))) + .toString() + .toStdString()); + + ReadCategory(Settings::Category::DataStorage); + + qt_config->endGroup(); +} + +void Config::ReadDebuggingValues() { + qt_config->beginGroup(QStringLiteral("Debugging")); + + // Intentionally not using the QT default setting as this is intended to be changed in the ini + Settings::values.record_frame_times = + qt_config->value(QStringLiteral("record_frame_times"), false).toBool(); + + ReadCategory(Settings::Category::Debugging); + ReadCategory(Settings::Category::DebuggingGraphics); + + qt_config->endGroup(); +} + +void Config::ReadServiceValues() { + qt_config->beginGroup(QStringLiteral("Services")); + + ReadCategory(Settings::Category::Services); + + qt_config->endGroup(); +} + +void Config::ReadDisabledAddOnValues() { + const auto size = qt_config->beginReadArray(QStringLiteral("DisabledAddOns")); + + for (int i = 0; i < size; ++i) { + qt_config->setArrayIndex(i); + const auto title_id = ReadSetting(QStringLiteral("title_id"), 0).toULongLong(); + std::vector out; + const auto d_size = qt_config->beginReadArray(QStringLiteral("disabled")); + for (int j = 0; j < d_size; ++j) { + qt_config->setArrayIndex(j); + out.push_back(ReadSetting(QStringLiteral("d"), QString{}).toString().toStdString()); + } + qt_config->endArray(); + Settings::values.disabled_addons.insert_or_assign(title_id, out); + } + + qt_config->endArray(); +} + +void Config::ReadMiscellaneousValues() { + qt_config->beginGroup(QStringLiteral("Miscellaneous")); + + ReadCategory(Settings::Category::Miscellaneous); + + qt_config->endGroup(); +} + +void Config::ReadPathValues() { + qt_config->beginGroup(QStringLiteral("Paths")); + + UISettings::values.roms_path = ReadSetting(QStringLiteral("romsPath")).toString(); + UISettings::values.symbols_path = ReadSetting(QStringLiteral("symbolsPath")).toString(); + UISettings::values.game_dir_deprecated = + ReadSetting(QStringLiteral("gameListRootDir"), QStringLiteral(".")).toString(); + UISettings::values.game_dir_deprecated_deepscan = + ReadSetting(QStringLiteral("gameListDeepScan"), false).toBool(); + const int gamedirs_size = qt_config->beginReadArray(QStringLiteral("gamedirs")); + for (int i = 0; i < gamedirs_size; ++i) { + qt_config->setArrayIndex(i); + UISettings::GameDir game_dir; + game_dir.path = ReadSetting(QStringLiteral("path")).toString(); + game_dir.deep_scan = ReadSetting(QStringLiteral("deep_scan"), false).toBool(); + game_dir.expanded = ReadSetting(QStringLiteral("expanded"), true).toBool(); + UISettings::values.game_dirs.append(game_dir); + } + qt_config->endArray(); + // create NAND and SD card directories if empty, these are not removable through the UI, + // also carries over old game list settings if present + if (UISettings::values.game_dirs.isEmpty()) { + UISettings::GameDir game_dir; + game_dir.path = QStringLiteral("SDMC"); + game_dir.expanded = true; + UISettings::values.game_dirs.append(game_dir); + game_dir.path = QStringLiteral("UserNAND"); + UISettings::values.game_dirs.append(game_dir); + game_dir.path = QStringLiteral("SysNAND"); + UISettings::values.game_dirs.append(game_dir); + if (UISettings::values.game_dir_deprecated != QStringLiteral(".")) { + game_dir.path = UISettings::values.game_dir_deprecated; + game_dir.deep_scan = UISettings::values.game_dir_deprecated_deepscan; + UISettings::values.game_dirs.append(game_dir); + } + } + UISettings::values.recent_files = ReadSetting(QStringLiteral("recentFiles")).toStringList(); + UISettings::values.language = ReadSetting(QStringLiteral("language"), QString{}).toString(); + + qt_config->endGroup(); +} + +void Config::ReadCpuValues() { + qt_config->beginGroup(QStringLiteral("Cpu")); + + ReadCategory(Settings::Category::Cpu); + ReadCategory(Settings::Category::CpuDebug); + ReadCategory(Settings::Category::CpuUnsafe); + + qt_config->endGroup(); +} + +void Config::ReadRendererValues() { + qt_config->beginGroup(QStringLiteral("Renderer")); + + ReadCategory(Settings::Category::Renderer); + ReadCategory(Settings::Category::RendererAdvanced); + ReadCategory(Settings::Category::RendererDebug); + + qt_config->endGroup(); +} + +void Config::ReadScreenshotValues() { + qt_config->beginGroup(QStringLiteral("Screenshots")); + + ReadCategory(Settings::Category::Screenshots); + FS::SetSudachiPath( + FS::SudachiPath::ScreenshotsDir, + qt_config + ->value(QStringLiteral("screenshot_path"), + QString::fromStdString(FS::GetSudachiPathString(FS::SudachiPath::ScreenshotsDir))) + .toString() + .toStdString()); + + qt_config->endGroup(); +} + +void Config::ReadShortcutValues() { + qt_config->beginGroup(QStringLiteral("Shortcuts")); + + for (const auto& [name, group, shortcut] : default_hotkeys) { + qt_config->beginGroup(group); + qt_config->beginGroup(name); + // No longer using ReadSetting for shortcut.second as it inaccurately returns a value of 1 + // for WidgetWithChildrenShortcut which is a value of 3. Needed to fix shortcuts the open + // a file dialog in windowed mode + UISettings::values.shortcuts.push_back( + {name, + group, + {ReadSetting(QStringLiteral("KeySeq"), shortcut.keyseq).toString(), + ReadSetting(QStringLiteral("Controller_KeySeq"), shortcut.controller_keyseq) + .toString(), + shortcut.context, ReadSetting(QStringLiteral("Repeat"), shortcut.repeat).toBool()}}); + qt_config->endGroup(); + qt_config->endGroup(); + } + + qt_config->endGroup(); +} + +void Config::ReadSystemValues() { + qt_config->beginGroup(QStringLiteral("System")); + + ReadCategory(Settings::Category::System); + ReadCategory(Settings::Category::SystemAudio); + + qt_config->endGroup(); +} + +void Config::ReadUIValues() { + qt_config->beginGroup(QStringLiteral("UI")); + + UISettings::values.theme = + ReadSetting( + QStringLiteral("theme"), + QString::fromUtf8(UISettings::themes[static_cast(default_theme)].second)) + .toString(); + + ReadUIGamelistValues(); + ReadUILayoutValues(); + ReadPathValues(); + ReadScreenshotValues(); + ReadShortcutValues(); + ReadMultiplayerValues(); + + ReadCategory(Settings::Category::Ui); + ReadCategory(Settings::Category::UiGeneral); + + qt_config->endGroup(); +} + +void Config::ReadUIGamelistValues() { + qt_config->beginGroup(QStringLiteral("UIGameList")); + + ReadCategory(Settings::Category::UiGameList); + + const int favorites_size = qt_config->beginReadArray(QStringLiteral("favorites")); + for (int i = 0; i < favorites_size; i++) { + qt_config->setArrayIndex(i); + UISettings::values.favorited_ids.append( + ReadSetting(QStringLiteral("program_id")).toULongLong()); + } + qt_config->endArray(); + + qt_config->endGroup(); +} + +void Config::ReadUILayoutValues() { + qt_config->beginGroup(QStringLiteral("UILayout")); + + UISettings::values.geometry = ReadSetting(QStringLiteral("geometry")).toByteArray(); + UISettings::values.state = ReadSetting(QStringLiteral("state")).toByteArray(); + UISettings::values.renderwindow_geometry = + ReadSetting(QStringLiteral("geometryRenderWindow")).toByteArray(); + UISettings::values.gamelist_header_state = + ReadSetting(QStringLiteral("gameListHeaderState")).toByteArray(); + UISettings::values.microprofile_geometry = + ReadSetting(QStringLiteral("microProfileDialogGeometry")).toByteArray(); + + ReadCategory(Settings::Category::UiLayout); + + qt_config->endGroup(); +} + +void Config::ReadWebServiceValues() { + qt_config->beginGroup(QStringLiteral("WebService")); + + ReadCategory(Settings::Category::WebService); + + qt_config->endGroup(); +} + +void Config::ReadMultiplayerValues() { + qt_config->beginGroup(QStringLiteral("Multiplayer")); + + ReadCategory(Settings::Category::Multiplayer); + + // Read ban list back + int size = qt_config->beginReadArray(QStringLiteral("username_ban_list")); + UISettings::values.multiplayer_ban_list.first.resize(size); + for (int i = 0; i < size; ++i) { + qt_config->setArrayIndex(i); + UISettings::values.multiplayer_ban_list.first[i] = + ReadSetting(QStringLiteral("username")).toString().toStdString(); + } + qt_config->endArray(); + size = qt_config->beginReadArray(QStringLiteral("ip_ban_list")); + UISettings::values.multiplayer_ban_list.second.resize(size); + for (int i = 0; i < size; ++i) { + qt_config->setArrayIndex(i); + UISettings::values.multiplayer_ban_list.second[i] = + ReadSetting(QStringLiteral("ip")).toString().toStdString(); + } + qt_config->endArray(); + + qt_config->endGroup(); +} + +void Config::ReadNetworkValues() { + qt_config->beginGroup(QString::fromStdString("Services")); + + ReadCategory(Settings::Category::Network); + + qt_config->endGroup(); +} + +void Config::ReadValues() { + if (global) { + ReadDataStorageValues(); + ReadDebuggingValues(); + ReadDisabledAddOnValues(); + ReadNetworkValues(); + ReadServiceValues(); + ReadUIValues(); + ReadWebServiceValues(); + ReadMiscellaneousValues(); + } + ReadControlValues(); + ReadCoreValues(); + ReadCpuValues(); + ReadRendererValues(); + ReadAudioValues(); + ReadSystemValues(); +} + +void Config::SavePlayerValue(std::size_t player_index) { + const QString player_prefix = [this, player_index] { + if (type == ConfigType::InputProfile) { + return QString{}; + } else { + return QStringLiteral("player_%1_").arg(player_index); + } + }(); + + const auto& player = Settings::values.players.GetValue()[player_index]; + if (IsCustomConfig()) { + if (player.profile_name.empty()) { + // No custom profile selected + return; + } + WriteSetting(QStringLiteral("%1profile_name").arg(player_prefix), + QString::fromStdString(player.profile_name), QString{}); + } + + WriteSetting(QStringLiteral("%1type").arg(player_prefix), + static_cast(player.controller_type), + static_cast(Settings::ControllerType::ProController)); + + if (!player_prefix.isEmpty() || !Settings::IsConfiguringGlobal()) { + WriteSetting(QStringLiteral("%1connected").arg(player_prefix), player.connected, + player_index == 0); + WriteSetting(QStringLiteral("%1vibration_enabled").arg(player_prefix), + player.vibration_enabled, true); + WriteSetting(QStringLiteral("%1vibration_strength").arg(player_prefix), + player.vibration_strength, 100); + WriteSetting(QStringLiteral("%1body_color_left").arg(player_prefix), player.body_color_left, + Settings::JOYCON_BODY_NEON_BLUE); + WriteSetting(QStringLiteral("%1body_color_right").arg(player_prefix), + player.body_color_right, Settings::JOYCON_BODY_NEON_RED); + WriteSetting(QStringLiteral("%1button_color_left").arg(player_prefix), + player.button_color_left, Settings::JOYCON_BUTTONS_NEON_BLUE); + WriteSetting(QStringLiteral("%1button_color_right").arg(player_prefix), + player.button_color_right, Settings::JOYCON_BUTTONS_NEON_RED); + } + + for (int i = 0; i < Settings::NativeButton::NumButtons; ++i) { + const std::string default_param = InputCommon::GenerateKeyboardParam(default_buttons[i]); + WriteSetting(QStringLiteral("%1").arg(player_prefix) + + QString::fromStdString(Settings::NativeButton::mapping[i]), + QString::fromStdString(player.buttons[i]), + QString::fromStdString(default_param)); + } + for (int i = 0; i < Settings::NativeAnalog::NumAnalogs; ++i) { + const std::string default_param = InputCommon::GenerateAnalogParamFromKeys( + default_analogs[i][0], default_analogs[i][1], default_analogs[i][2], + default_analogs[i][3], default_stick_mod[i], 0.5f); + WriteSetting(QStringLiteral("%1").arg(player_prefix) + + QString::fromStdString(Settings::NativeAnalog::mapping[i]), + QString::fromStdString(player.analogs[i]), + QString::fromStdString(default_param)); + } + for (int i = 0; i < Settings::NativeMotion::NumMotions; ++i) { + const std::string default_param = InputCommon::GenerateKeyboardParam(default_motions[i]); + WriteSetting(QStringLiteral("%1").arg(player_prefix) + + QString::fromStdString(Settings::NativeMotion::mapping[i]), + QString::fromStdString(player.motions[i]), + QString::fromStdString(default_param)); + } +} + +void Config::SaveDebugValues() { + for (int i = 0; i < Settings::NativeButton::NumButtons; ++i) { + const std::string default_param = InputCommon::GenerateKeyboardParam(default_buttons[i]); + WriteSetting(QStringLiteral("debug_pad_") + + QString::fromStdString(Settings::NativeButton::mapping[i]), + QString::fromStdString(Settings::values.debug_pad_buttons[i]), + QString::fromStdString(default_param)); + } + for (int i = 0; i < Settings::NativeAnalog::NumAnalogs; ++i) { + const std::string default_param = InputCommon::GenerateAnalogParamFromKeys( + default_analogs[i][0], default_analogs[i][1], default_analogs[i][2], + default_analogs[i][3], default_stick_mod[i], 0.5f); + WriteSetting(QStringLiteral("debug_pad_") + + QString::fromStdString(Settings::NativeAnalog::mapping[i]), + QString::fromStdString(Settings::values.debug_pad_analogs[i]), + QString::fromStdString(default_param)); + } +} + +void Config::SaveTouchscreenValues() { + const auto& touchscreen = Settings::values.touchscreen; + + WriteSetting(QStringLiteral("touchscreen_enabled"), touchscreen.enabled, true); + + WriteSetting(QStringLiteral("touchscreen_angle"), touchscreen.rotation_angle, 0); + WriteSetting(QStringLiteral("touchscreen_diameter_x"), touchscreen.diameter_x, 15); + WriteSetting(QStringLiteral("touchscreen_diameter_y"), touchscreen.diameter_y, 15); +} + +void Config::SaveMotionTouchValues() { + qt_config->beginWriteArray(QStringLiteral("touch_from_button_maps")); + for (std::size_t p = 0; p < Settings::values.touch_from_button_maps.size(); ++p) { + qt_config->setArrayIndex(static_cast(p)); + WriteSetting(QStringLiteral("name"), + QString::fromStdString(Settings::values.touch_from_button_maps[p].name), + QStringLiteral("default")); + qt_config->beginWriteArray(QStringLiteral("entries")); + for (std::size_t q = 0; q < Settings::values.touch_from_button_maps[p].buttons.size(); + ++q) { + qt_config->setArrayIndex(static_cast(q)); + WriteSetting( + QStringLiteral("bind"), + QString::fromStdString(Settings::values.touch_from_button_maps[p].buttons[q])); + } + qt_config->endArray(); + } + qt_config->endArray(); +} + +void Config::SaveHidbusValues() { + const std::string default_param = InputCommon::GenerateAnalogParamFromKeys( + 0, 0, default_ringcon_analogs[0], default_ringcon_analogs[1], 0, 0.05f); + WriteSetting(QStringLiteral("ring_controller"), + QString::fromStdString(Settings::values.ringcon_analogs), + QString::fromStdString(default_param)); +} + +void Config::SaveValues() { + if (global) { + SaveDataStorageValues(); + SaveDebuggingValues(); + SaveDisabledAddOnValues(); + SaveNetworkValues(); + SaveUIValues(); + SaveWebServiceValues(); + SaveMiscellaneousValues(); + } + SaveControlValues(); + SaveCoreValues(); + SaveCpuValues(); + SaveRendererValues(); + SaveAudioValues(); + SaveSystemValues(); + + qt_config->sync(); +} + +void Config::SaveAudioValues() { + qt_config->beginGroup(QStringLiteral("Audio")); + + WriteCategory(Settings::Category::Audio); + WriteCategory(Settings::Category::UiAudio); + + qt_config->endGroup(); +} + +void Config::SaveControlValues() { + qt_config->beginGroup(QStringLiteral("Controls")); + + WriteCategory(Settings::Category::Controls); + + Settings::values.players.SetGlobal(!IsCustomConfig()); + for (std::size_t p = 0; p < Settings::values.players.GetValue().size(); ++p) { + SavePlayerValue(p); + } + if (IsCustomConfig()) { + qt_config->endGroup(); + return; + } + SaveDebugValues(); + SaveTouchscreenValues(); + SaveMotionTouchValues(); + SaveHidbusValues(); + + qt_config->endGroup(); +} + +void Config::SaveCoreValues() { + qt_config->beginGroup(QStringLiteral("Core")); + + WriteCategory(Settings::Category::Core); + + qt_config->endGroup(); +} + +void Config::SaveDataStorageValues() { + qt_config->beginGroup(QStringLiteral("Data Storage")); + + WriteSetting(QStringLiteral("nand_directory"), + QString::fromStdString(FS::GetSudachiPathString(FS::SudachiPath::NANDDir)), + QString::fromStdString(FS::GetSudachiPathString(FS::SudachiPath::NANDDir))); + WriteSetting(QStringLiteral("sdmc_directory"), + QString::fromStdString(FS::GetSudachiPathString(FS::SudachiPath::SDMCDir)), + QString::fromStdString(FS::GetSudachiPathString(FS::SudachiPath::SDMCDir))); + WriteSetting(QStringLiteral("load_directory"), + QString::fromStdString(FS::GetSudachiPathString(FS::SudachiPath::LoadDir)), + QString::fromStdString(FS::GetSudachiPathString(FS::SudachiPath::LoadDir))); + WriteSetting(QStringLiteral("dump_directory"), + QString::fromStdString(FS::GetSudachiPathString(FS::SudachiPath::DumpDir)), + QString::fromStdString(FS::GetSudachiPathString(FS::SudachiPath::DumpDir))); + WriteSetting(QStringLiteral("tas_directory"), + QString::fromStdString(FS::GetSudachiPathString(FS::SudachiPath::TASDir)), + QString::fromStdString(FS::GetSudachiPathString(FS::SudachiPath::TASDir))); + + WriteCategory(Settings::Category::DataStorage); + + qt_config->endGroup(); +} + +void Config::SaveDebuggingValues() { + qt_config->beginGroup(QStringLiteral("Debugging")); + + // Intentionally not using the QT default setting as this is intended to be changed in the ini + qt_config->setValue(QStringLiteral("record_frame_times"), Settings::values.record_frame_times); + + WriteCategory(Settings::Category::Debugging); + WriteCategory(Settings::Category::DebuggingGraphics); + + qt_config->endGroup(); +} + +void Config::SaveNetworkValues() { + qt_config->beginGroup(QStringLiteral("Services")); + + WriteCategory(Settings::Category::Network); + + qt_config->endGroup(); +} + +void Config::SaveDisabledAddOnValues() { + qt_config->beginWriteArray(QStringLiteral("DisabledAddOns")); + + int i = 0; + for (const auto& elem : Settings::values.disabled_addons) { + qt_config->setArrayIndex(i); + WriteSetting(QStringLiteral("title_id"), QVariant::fromValue(elem.first), 0); + qt_config->beginWriteArray(QStringLiteral("disabled")); + for (std::size_t j = 0; j < elem.second.size(); ++j) { + qt_config->setArrayIndex(static_cast(j)); + WriteSetting(QStringLiteral("d"), QString::fromStdString(elem.second[j]), QString{}); + } + qt_config->endArray(); + ++i; + } + + qt_config->endArray(); +} + +void Config::SaveMiscellaneousValues() { + qt_config->beginGroup(QStringLiteral("Miscellaneous")); + + WriteCategory(Settings::Category::Miscellaneous); + + qt_config->endGroup(); +} + +void Config::SavePathValues() { + qt_config->beginGroup(QStringLiteral("Paths")); + + WriteSetting(QStringLiteral("romsPath"), UISettings::values.roms_path); + WriteSetting(QStringLiteral("symbolsPath"), UISettings::values.symbols_path); + qt_config->beginWriteArray(QStringLiteral("gamedirs")); + for (int i = 0; i < UISettings::values.game_dirs.size(); ++i) { + qt_config->setArrayIndex(i); + const auto& game_dir = UISettings::values.game_dirs[i]; + WriteSetting(QStringLiteral("path"), game_dir.path); + WriteSetting(QStringLiteral("deep_scan"), game_dir.deep_scan, false); + WriteSetting(QStringLiteral("expanded"), game_dir.expanded, true); + } + qt_config->endArray(); + WriteSetting(QStringLiteral("recentFiles"), UISettings::values.recent_files); + WriteSetting(QStringLiteral("language"), UISettings::values.language, QString{}); + + qt_config->endGroup(); +} + +void Config::SaveCpuValues() { + qt_config->beginGroup(QStringLiteral("Cpu")); + + WriteCategory(Settings::Category::Cpu); + WriteCategory(Settings::Category::CpuDebug); + WriteCategory(Settings::Category::CpuUnsafe); + + qt_config->endGroup(); +} + +void Config::SaveRendererValues() { + qt_config->beginGroup(QStringLiteral("Renderer")); + + WriteCategory(Settings::Category::Renderer); + WriteCategory(Settings::Category::RendererAdvanced); + WriteCategory(Settings::Category::RendererDebug); + + qt_config->endGroup(); +} + +void Config::SaveScreenshotValues() { + qt_config->beginGroup(QStringLiteral("Screenshots")); + + WriteSetting(QStringLiteral("screenshot_path"), + QString::fromStdString(FS::GetSudachiPathString(FS::SudachiPath::ScreenshotsDir))); + WriteCategory(Settings::Category::Screenshots); + + qt_config->endGroup(); +} + +void Config::SaveShortcutValues() { + qt_config->beginGroup(QStringLiteral("Shortcuts")); + + // Lengths of UISettings::values.shortcuts & default_hotkeys are same. + // However, their ordering must also be the same. + for (std::size_t i = 0; i < default_hotkeys.size(); i++) { + const auto& [name, group, shortcut] = UISettings::values.shortcuts[i]; + const auto& default_hotkey = default_hotkeys[i].shortcut; + + qt_config->beginGroup(group); + qt_config->beginGroup(name); + WriteSetting(QStringLiteral("KeySeq"), shortcut.keyseq, default_hotkey.keyseq); + WriteSetting(QStringLiteral("Controller_KeySeq"), shortcut.controller_keyseq, + default_hotkey.controller_keyseq); + WriteSetting(QStringLiteral("Context"), shortcut.context, default_hotkey.context); + WriteSetting(QStringLiteral("Repeat"), shortcut.repeat, default_hotkey.repeat); + qt_config->endGroup(); + qt_config->endGroup(); + } + + qt_config->endGroup(); +} + +void Config::SaveSystemValues() { + qt_config->beginGroup(QStringLiteral("System")); + + WriteCategory(Settings::Category::System); + WriteCategory(Settings::Category::SystemAudio); + + qt_config->endGroup(); +} + +void Config::SaveUIValues() { + qt_config->beginGroup(QStringLiteral("UI")); + + WriteCategory(Settings::Category::Ui); + WriteCategory(Settings::Category::UiGeneral); + + WriteSetting(QStringLiteral("theme"), UISettings::values.theme, + QString::fromUtf8(UISettings::themes[static_cast(default_theme)].second)); + + SaveUIGamelistValues(); + SaveUILayoutValues(); + SavePathValues(); + SaveScreenshotValues(); + SaveShortcutValues(); + SaveMultiplayerValues(); + + qt_config->endGroup(); +} + +void Config::SaveUIGamelistValues() { + qt_config->beginGroup(QStringLiteral("UIGameList")); + + WriteCategory(Settings::Category::UiGameList); + + qt_config->beginWriteArray(QStringLiteral("favorites")); + for (int i = 0; i < UISettings::values.favorited_ids.size(); i++) { + qt_config->setArrayIndex(i); + WriteSetting(QStringLiteral("program_id"), + QVariant::fromValue(UISettings::values.favorited_ids[i])); + } + qt_config->endArray(); + + qt_config->endGroup(); +} + +void Config::SaveUILayoutValues() { + qt_config->beginGroup(QStringLiteral("UILayout")); + + WriteSetting(QStringLiteral("geometry"), UISettings::values.geometry); + WriteSetting(QStringLiteral("state"), UISettings::values.state); + WriteSetting(QStringLiteral("geometryRenderWindow"), UISettings::values.renderwindow_geometry); + WriteSetting(QStringLiteral("gameListHeaderState"), UISettings::values.gamelist_header_state); + WriteSetting(QStringLiteral("microProfileDialogGeometry"), + UISettings::values.microprofile_geometry); + + WriteCategory(Settings::Category::UiLayout); + + qt_config->endGroup(); +} + +void Config::SaveWebServiceValues() { + qt_config->beginGroup(QStringLiteral("WebService")); + + WriteCategory(Settings::Category::WebService); + + qt_config->endGroup(); +} + +void Config::SaveMultiplayerValues() { + qt_config->beginGroup(QStringLiteral("Multiplayer")); + + WriteCategory(Settings::Category::Multiplayer); + + // Write ban list + qt_config->beginWriteArray(QStringLiteral("username_ban_list")); + for (std::size_t i = 0; i < UISettings::values.multiplayer_ban_list.first.size(); ++i) { + qt_config->setArrayIndex(static_cast(i)); + WriteSetting(QStringLiteral("username"), + QString::fromStdString(UISettings::values.multiplayer_ban_list.first[i])); + } + qt_config->endArray(); + qt_config->beginWriteArray(QStringLiteral("ip_ban_list")); + for (std::size_t i = 0; i < UISettings::values.multiplayer_ban_list.second.size(); ++i) { + qt_config->setArrayIndex(static_cast(i)); + WriteSetting(QStringLiteral("ip"), + QString::fromStdString(UISettings::values.multiplayer_ban_list.second[i])); + } + qt_config->endArray(); + + qt_config->endGroup(); +} + +QVariant Config::ReadSetting(const QString& name) const { + return qt_config->value(name); +} + +QVariant Config::ReadSetting(const QString& name, const QVariant& default_value) const { + QVariant result; + if (qt_config->value(name + QStringLiteral("/default"), false).toBool()) { + result = default_value; + } else { + result = qt_config->value(name, default_value); + } + return result; +} + +void Config::WriteSetting(const QString& name, const QVariant& value) { + qt_config->setValue(name, value); +} + +void Config::WriteSetting(const QString& name, const QVariant& value, + const QVariant& default_value) { + qt_config->setValue(name + QStringLiteral("/default"), value == default_value); + qt_config->setValue(name, value); +} + +void Config::WriteSetting(const QString& name, const QVariant& value, const QVariant& default_value, + bool use_global) { + if (!global) { + qt_config->setValue(name + QStringLiteral("/use_global"), use_global); + } + if (global || !use_global) { + qt_config->setValue(name + QStringLiteral("/default"), value == default_value); + qt_config->setValue(name, value); + } +} + +void Config::Reload() { + ReadValues(); + // To apply default value changes + SaveValues(); +} + +void Config::Save() { + SaveValues(); +} + +void Config::ReadControlPlayerValue(std::size_t player_index) { + qt_config->beginGroup(QStringLiteral("Controls")); + ReadPlayerValue(player_index); + qt_config->endGroup(); +} + +void Config::SaveControlPlayerValue(std::size_t player_index) { + qt_config->beginGroup(QStringLiteral("Controls")); + SavePlayerValue(player_index); + qt_config->endGroup(); +} + +void Config::ClearControlPlayerValues() { + qt_config->beginGroup(QStringLiteral("Controls")); + // If key is an empty string, all keys in the current group() are removed. + qt_config->remove(QString{}); + qt_config->endGroup(); +} + +const std::string& Config::GetConfigFilePath() const { + return qt_config_loc; +} + +static auto FindRelevantList(Settings::Category category) { + auto& map = Settings::values.linkage.by_category; + if (map.contains(category)) { + return Settings::values.linkage.by_category[category]; + } + return UISettings::values.linkage.by_category[category]; +} + +void Config::ReadCategory(Settings::Category category) { + const auto& settings = FindRelevantList(category); + std::for_each(settings.begin(), settings.end(), + [&](const auto& setting) { ReadSettingGeneric(setting); }); +} + +void Config::WriteCategory(Settings::Category category) { + const auto& settings = FindRelevantList(category); + std::for_each(settings.begin(), settings.end(), + [&](const auto& setting) { WriteSettingGeneric(setting); }); +} + +void Config::ReadSettingGeneric(Settings::BasicSetting* const setting) { + if (!setting->Save() || (!setting->Switchable() && !global)) { + return; + } + const QString name = QString::fromStdString(setting->GetLabel()); + const auto default_value = + QVariant::fromValue(QString::fromStdString(setting->DefaultToString())); + + bool use_global = true; + if (setting->Switchable() && !global) { + use_global = qt_config->value(name + QStringLiteral("/use_global"), true).value(); + setting->SetGlobal(use_global); + } + + if (global || !use_global) { + const bool is_default = + qt_config->value(name + QStringLiteral("/default"), true).value(); + if (!is_default) { + setting->LoadString( + qt_config->value(name, default_value).value().toStdString()); + } else { + // Empty string resets the Setting to default + setting->LoadString(""); + } + } +} + +void Config::WriteSettingGeneric(Settings::BasicSetting* const setting) const { + if (!setting->Save()) { + return; + } + const QVariant value = QVariant::fromValue(QString::fromStdString(setting->ToString())); + const QVariant default_value = + QVariant::fromValue(QString::fromStdString(setting->DefaultToString())); + const QString label = QString::fromStdString(setting->GetLabel()); + if (setting->Switchable()) { + if (!global) { + qt_config->setValue(label + QStringLiteral("/use_global"), setting->UsingGlobal()); + } + if (global || !setting->UsingGlobal()) { + qt_config->setValue(label + QStringLiteral("/default"), value == default_value); + qt_config->setValue(label, value); + } + } else if (global) { + qt_config->setValue(label + QStringLiteral("/default"), value == default_value); + qt_config->setValue(label, value); + } +} diff --git a/src/sudachi/configuration/config.h b/src/sudachi/configuration/config.h new file mode 100644 index 0000000..c468bc0 --- /dev/null +++ b/src/sudachi/configuration/config.h @@ -0,0 +1,179 @@ +// SPDX-FileCopyrightText: 2014 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include +#include +#include +#include +#include "common/settings.h" +#include "common/settings_enums.h" +#include "sudachi/uisettings.h" + +class QSettings; + +namespace Core { +class System; +} + +class Config { +public: + enum class ConfigType { + GlobalConfig, + PerGameConfig, + InputProfile, + }; + + explicit Config(const std::string& config_name = "qt-config", + ConfigType config_type = ConfigType::GlobalConfig); + ~Config(); + + void Reload(); + void Save(); + + void ReadControlPlayerValue(std::size_t player_index); + void SaveControlPlayerValue(std::size_t player_index); + void ClearControlPlayerValues(); + + const std::string& GetConfigFilePath() const; + + static const std::array default_buttons; + static const std::array default_motions; + static const std::array, Settings::NativeAnalog::NumAnalogs> default_analogs; + static const std::array default_stick_mod; + static const std::array default_ringcon_analogs; + static const std::array + default_mouse_buttons; + static const std::array default_keyboard_keys; + static const std::array default_keyboard_mods; + static const std::array default_hotkeys; + + static const std::map anti_aliasing_texts_map; + static const std::map scaling_filter_texts_map; + static const std::map use_docked_mode_texts_map; + static const std::map gpu_accuracy_texts_map; + static const std::map renderer_backend_texts_map; + static const std::map shader_backend_texts_map; + + static constexpr UISettings::Theme default_theme{ +#ifdef _WIN32 + UISettings::Theme::DarkColorful +#else + UISettings::Theme::DefaultColorful +#endif + }; + +private: + void Initialize(const std::string& config_name); + bool IsCustomConfig(); + + void ReadValues(); + void ReadPlayerValue(std::size_t player_index); + void ReadDebugValues(); + void ReadKeyboardValues(); + void ReadMouseValues(); + void ReadTouchscreenValues(); + void ReadMotionTouchValues(); + void ReadHidbusValues(); + void ReadIrCameraValues(); + + // Read functions bases off the respective config section names. + void ReadAudioValues(); + void ReadControlValues(); + void ReadCoreValues(); + void ReadDataStorageValues(); + void ReadDebuggingValues(); + void ReadServiceValues(); + void ReadDisabledAddOnValues(); + void ReadMiscellaneousValues(); + void ReadPathValues(); + void ReadCpuValues(); + void ReadRendererValues(); + void ReadScreenshotValues(); + void ReadShortcutValues(); + void ReadSystemValues(); + void ReadUIValues(); + void ReadUIGamelistValues(); + void ReadUILayoutValues(); + void ReadWebServiceValues(); + void ReadMultiplayerValues(); + void ReadNetworkValues(); + + void SaveValues(); + void SavePlayerValue(std::size_t player_index); + void SaveDebugValues(); + void SaveMouseValues(); + void SaveTouchscreenValues(); + void SaveMotionTouchValues(); + void SaveHidbusValues(); + void SaveIrCameraValues(); + + // Save functions based off the respective config section names. + void SaveAudioValues(); + void SaveControlValues(); + void SaveCoreValues(); + void SaveDataStorageValues(); + void SaveDebuggingValues(); + void SaveNetworkValues(); + void SaveDisabledAddOnValues(); + void SaveMiscellaneousValues(); + void SavePathValues(); + void SaveCpuValues(); + void SaveRendererValues(); + void SaveScreenshotValues(); + void SaveShortcutValues(); + void SaveSystemValues(); + void SaveUIValues(); + void SaveUIGamelistValues(); + void SaveUILayoutValues(); + void SaveWebServiceValues(); + void SaveMultiplayerValues(); + + /** + * Reads a setting from the qt_config. + * + * @param name The setting's identifier + * @param default_value The value to use when the setting is not already present in the config + */ + QVariant ReadSetting(const QString& name) const; + QVariant ReadSetting(const QString& name, const QVariant& default_value) const; + + /** + * Writes a setting to the qt_config. + * + * @param name The setting's idetentifier + * @param value Value of the setting + * @param default_value Default of the setting if not present in qt_config + * @param use_global Specifies if the custom or global config should be in use, for custom + * configs + */ + void WriteSetting(const QString& name, const QVariant& value); + void WriteSetting(const QString& name, const QVariant& value, const QVariant& default_value); + void WriteSetting(const QString& name, const QVariant& value, const QVariant& default_value, + bool use_global); + + void ReadCategory(Settings::Category category); + void WriteCategory(Settings::Category category); + void ReadSettingGeneric(Settings::BasicSetting* const setting); + void WriteSettingGeneric(Settings::BasicSetting* const setting) const; + + const ConfigType type; + std::unique_ptr qt_config; + std::string qt_config_loc; + const bool global; +}; + +// These metatype declarations cannot be in common/settings.h because core is devoid of QT +Q_DECLARE_METATYPE(Settings::CpuAccuracy); +Q_DECLARE_METATYPE(Settings::GpuAccuracy); +Q_DECLARE_METATYPE(Settings::FullscreenMode); +Q_DECLARE_METATYPE(Settings::NvdecEmulation); +Q_DECLARE_METATYPE(Settings::ResolutionSetup); +Q_DECLARE_METATYPE(Settings::ScalingFilter); +Q_DECLARE_METATYPE(Settings::AntiAliasing); +Q_DECLARE_METATYPE(Settings::RendererBackend); +Q_DECLARE_METATYPE(Settings::ShaderBackend); +Q_DECLARE_METATYPE(Settings::AstcRecompression); +Q_DECLARE_METATYPE(Settings::AstcDecodeMode); diff --git a/src/sudachi/configuration/configuration_shared.cpp b/src/sudachi/configuration/configuration_shared.cpp new file mode 100644 index 0000000..b53921f --- /dev/null +++ b/src/sudachi/configuration/configuration_shared.cpp @@ -0,0 +1,19 @@ +// SPDX-FileCopyrightText: 2016 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include +#include +#include "sudachi/configuration/configuration_shared.h" + +namespace ConfigurationShared { + +Tab::Tab(std::shared_ptr> group, QWidget* parent) : QWidget(parent) { + if (group != nullptr) { + group->push_back(this); + } +} + +Tab::~Tab() = default; + +} // namespace ConfigurationShared diff --git a/src/sudachi/configuration/configuration_shared.h b/src/sudachi/configuration/configuration_shared.h new file mode 100644 index 0000000..31897a6 --- /dev/null +++ b/src/sudachi/configuration/configuration_shared.h @@ -0,0 +1,27 @@ +// SPDX-FileCopyrightText: 2016 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include +#include +#include +#include + +class QObject; + +namespace ConfigurationShared { + +class Tab : public QWidget { + Q_OBJECT + +public: + explicit Tab(std::shared_ptr> group, QWidget* parent = nullptr); + ~Tab(); + + virtual void ApplyConfiguration() = 0; + virtual void SetConfiguration() = 0; +}; + +} // namespace ConfigurationShared diff --git a/src/sudachi/configuration/configure.ui b/src/sudachi/configuration/configure.ui new file mode 100644 index 0000000..31409ad --- /dev/null +++ b/src/sudachi/configuration/configure.ui @@ -0,0 +1,117 @@ + + + ConfigureDialog + + + + 0 + 0 + 650 + 650 + + + + + 0 + 650 + + + + sudachi Configuration + + + + + + + + + 120 + 0 + + + + + 120 + 16777215 + + + + + + + + -1 + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Some settings are only available when a game is not running. + + + + + + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + + + + + + + + + + buttonBox + accepted() + ConfigureDialog + accept() + + + 20 + 20 + + + 20 + 20 + + + + + buttonBox + rejected() + ConfigureDialog + reject() + + + 20 + 20 + + + 20 + 20 + + + + + diff --git a/src/sudachi/configuration/configure_applets.cpp b/src/sudachi/configuration/configure_applets.cpp new file mode 100644 index 0000000..1d885b1 --- /dev/null +++ b/src/sudachi/configuration/configure_applets.cpp @@ -0,0 +1,84 @@ +// SPDX-FileCopyrightText: 2024 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include "common/settings.h" +#include "core/core.h" +#include "ui_configure_applets.h" +#include "sudachi/configuration/configuration_shared.h" +#include "sudachi/configuration/configure_applets.h" +#include "sudachi/configuration/shared_widget.h" + +ConfigureApplets::ConfigureApplets(Core::System& system_, + std::shared_ptr> group_, + const ConfigurationShared::Builder& builder, QWidget* parent) + : Tab(group_, parent), ui{std::make_unique()}, system{system_} { + ui->setupUi(this); + + Setup(builder); + + SetConfiguration(); +} + +ConfigureApplets::~ConfigureApplets() = default; + +void ConfigureApplets::changeEvent(QEvent* event) { + if (event->type() == QEvent::LanguageChange) { + RetranslateUI(); + } + + QWidget::changeEvent(event); +} + +void ConfigureApplets::RetranslateUI() { + ui->retranslateUi(this); +} + +void ConfigureApplets::Setup(const ConfigurationShared::Builder& builder) { + auto& library_applets_layout = *ui->group_library_applet_modes->layout(); + std::map applets_hold{}; + + std::vector settings; + auto push = [&settings](auto& list) { + for (auto setting : list) { + settings.push_back(setting); + } + }; + + push(Settings::values.linkage.by_category[Settings::Category::LibraryApplet]); + + for (auto setting : settings) { + ConfigurationShared::Widget* widget = builder.BuildWidget(setting, apply_funcs); + + if (widget == nullptr) { + continue; + } + if (!widget->Valid()) { + widget->deleteLater(); + continue; + } + + // Untested applets + if (setting->Id() == Settings::values.data_erase_applet_mode.Id() || + setting->Id() == Settings::values.net_connect_applet_mode.Id() || + setting->Id() == Settings::values.shop_applet_mode.Id() || + setting->Id() == Settings::values.login_share_applet_mode.Id() || + setting->Id() == Settings::values.wifi_web_auth_applet_mode.Id() || + setting->Id() == Settings::values.my_page_applet_mode.Id()) { + widget->setHidden(true); + } + + applets_hold.emplace(setting->Id(), widget); + } + for (const auto& [label, widget] : applets_hold) { + library_applets_layout.addWidget(widget); + } +} + +void ConfigureApplets::SetConfiguration() {} + +void ConfigureApplets::ApplyConfiguration() { + const bool powered_on = system.IsPoweredOn(); + for (const auto& func : apply_funcs) { + func(powered_on); + } +} diff --git a/src/sudachi/configuration/configure_applets.h b/src/sudachi/configuration/configure_applets.h new file mode 100644 index 0000000..53076e4 --- /dev/null +++ b/src/sudachi/configuration/configure_applets.h @@ -0,0 +1,48 @@ +// SPDX-FileCopyrightText: 2024 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include "sudachi/configuration/configuration_shared.h" + +class QCheckBox; +class QLineEdit; +class QComboBox; +class QDateTimeEdit; +namespace Core { +class System; +} + +namespace Ui { +class ConfigureApplets; +} + +namespace ConfigurationShared { +class Builder; +} + +class ConfigureApplets : public ConfigurationShared::Tab { +public: + explicit ConfigureApplets(Core::System& system_, + std::shared_ptr> group, + const ConfigurationShared::Builder& builder, + QWidget* parent = nullptr); + ~ConfigureApplets() override; + + void ApplyConfiguration() override; + void SetConfiguration() override; + +private: + void changeEvent(QEvent* event) override; + void RetranslateUI(); + + void Setup(const ConfigurationShared::Builder& builder); + + std::vector> apply_funcs{}; + + std::unique_ptr ui; + bool enabled = false; + + Core::System& system; +}; diff --git a/src/sudachi/configuration/configure_applets.ui b/src/sudachi/configuration/configure_applets.ui new file mode 100644 index 0000000..6f2ca66 --- /dev/null +++ b/src/sudachi/configuration/configure_applets.ui @@ -0,0 +1,65 @@ + + + ConfigureApplets + + + + 0 + 0 + 605 + 300 + + + + Form + + + Applets + + + + + + + + Applet mode preference + + + + + + + 0 + + + 0 + + + 0 + + + + + + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + diff --git a/src/sudachi/configuration/configure_audio.cpp b/src/sudachi/configuration/configure_audio.cpp new file mode 100644 index 0000000..53e2d82 --- /dev/null +++ b/src/sudachi/configuration/configure_audio.cpp @@ -0,0 +1,278 @@ +// SPDX-FileCopyrightText: Copyright 2018 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include +#include +#include +#include + +#include "audio_core/sink/sink.h" +#include "audio_core/sink/sink_details.h" +#include "common/common_types.h" +#include "common/settings.h" +#include "common/settings_common.h" +#include "core/core.h" +#include "ui_configure_audio.h" +#include "sudachi/configuration/configuration_shared.h" +#include "sudachi/configuration/configure_audio.h" +#include "sudachi/configuration/shared_translation.h" +#include "sudachi/configuration/shared_widget.h" +#include "sudachi/uisettings.h" + +ConfigureAudio::ConfigureAudio(const Core::System& system_, + std::shared_ptr> group_, + const ConfigurationShared::Builder& builder, QWidget* parent) + : Tab(group_, parent), ui(std::make_unique()), system{system_} { + ui->setupUi(this); + Setup(builder); + + SetConfiguration(); +} + +ConfigureAudio::~ConfigureAudio() = default; + +void ConfigureAudio::Setup(const ConfigurationShared::Builder& builder) { + auto& layout = *ui->audio_widget->layout(); + + std::vector settings; + + std::map hold; + + auto push_settings = [&](Settings::Category category) { + for (auto* setting : Settings::values.linkage.by_category[category]) { + settings.push_back(setting); + } + }; + + auto push_ui_settings = [&](Settings::Category category) { + for (auto* setting : UISettings::values.linkage.by_category[category]) { + settings.push_back(setting); + } + }; + + push_settings(Settings::Category::Audio); + push_settings(Settings::Category::SystemAudio); + push_ui_settings(Settings::Category::UiAudio); + + for (auto* setting : settings) { + auto* widget = builder.BuildWidget(setting, apply_funcs); + + if (widget == nullptr) { + continue; + } + if (!widget->Valid()) { + widget->deleteLater(); + continue; + } + + hold.emplace(std::pair{setting->Id(), widget}); + + auto global_sink_match = [this] { + return static_cast(sink_combo_box->currentIndex()) == + Settings::values.sink_id.GetValue(true); + }; + if (setting->Id() == Settings::values.sink_id.Id()) { + // TODO (lat9nq): Let the system manage sink_id + sink_combo_box = widget->combobox; + InitializeAudioSinkComboBox(); + + if (Settings::IsConfiguringGlobal()) { + connect(sink_combo_box, qOverload(&QComboBox::currentIndexChanged), this, + &ConfigureAudio::UpdateAudioDevices); + } else { + restore_sink_button = ConfigurationShared::Widget::CreateRestoreGlobalButton( + Settings::values.sink_id.UsingGlobal(), widget); + widget->layout()->addWidget(restore_sink_button); + connect(restore_sink_button, &QAbstractButton::clicked, [this](bool) { + Settings::values.sink_id.SetGlobal(true); + const int sink_index = static_cast(Settings::values.sink_id.GetValue()); + sink_combo_box->setCurrentIndex(sink_index); + ConfigureAudio::UpdateAudioDevices(sink_index); + Settings::values.audio_output_device_id.SetGlobal(true); + Settings::values.audio_input_device_id.SetGlobal(true); + restore_sink_button->setVisible(false); + }); + connect(sink_combo_box, qOverload(&QComboBox::currentIndexChanged), + [this, global_sink_match](const int slot) { + Settings::values.sink_id.SetGlobal(false); + Settings::values.audio_output_device_id.SetGlobal(false); + Settings::values.audio_input_device_id.SetGlobal(false); + + restore_sink_button->setVisible(true); + restore_sink_button->setEnabled(true); + output_device_combo_box->setCurrentIndex(0); + restore_output_device_button->setVisible(true); + restore_output_device_button->setEnabled(global_sink_match()); + input_device_combo_box->setCurrentIndex(0); + restore_input_device_button->setVisible(true); + restore_input_device_button->setEnabled(global_sink_match()); + ConfigureAudio::UpdateAudioDevices(slot); + }); + } + } else if (setting->Id() == Settings::values.audio_output_device_id.Id()) { + // Keep track of output (and input) device comboboxes to populate them with system + // devices, which are determined at run time + output_device_combo_box = widget->combobox; + + if (!Settings::IsConfiguringGlobal()) { + restore_output_device_button = + ConfigurationShared::Widget::CreateRestoreGlobalButton( + Settings::values.audio_output_device_id.UsingGlobal(), widget); + restore_output_device_button->setEnabled(global_sink_match()); + restore_output_device_button->setVisible( + !Settings::values.audio_output_device_id.UsingGlobal()); + widget->layout()->addWidget(restore_output_device_button); + connect(restore_output_device_button, &QAbstractButton::clicked, [this](bool) { + Settings::values.audio_output_device_id.SetGlobal(true); + SetOutputDevicesFromDeviceID(); + restore_output_device_button->setVisible(false); + }); + connect(output_device_combo_box, qOverload(&QComboBox::currentIndexChanged), + [this, global_sink_match](int) { + if (updating_devices) { + return; + } + Settings::values.audio_output_device_id.SetGlobal(false); + restore_output_device_button->setVisible(true); + restore_output_device_button->setEnabled(global_sink_match()); + }); + } + } else if (setting->Id() == Settings::values.audio_input_device_id.Id()) { + input_device_combo_box = widget->combobox; + + if (!Settings::IsConfiguringGlobal()) { + restore_input_device_button = + ConfigurationShared::Widget::CreateRestoreGlobalButton( + Settings::values.audio_input_device_id.UsingGlobal(), widget); + widget->layout()->addWidget(restore_input_device_button); + connect(restore_input_device_button, &QAbstractButton::clicked, [this](bool) { + Settings::values.audio_input_device_id.SetGlobal(true); + SetInputDevicesFromDeviceID(); + restore_input_device_button->setVisible(false); + }); + connect(input_device_combo_box, qOverload(&QComboBox::currentIndexChanged), + [this, global_sink_match](int) { + if (updating_devices) { + return; + } + Settings::values.audio_input_device_id.SetGlobal(false); + restore_input_device_button->setVisible(true); + restore_input_device_button->setEnabled(global_sink_match()); + }); + } + } + } + + for (const auto& [id, widget] : hold) { + layout.addWidget(widget); + } +} + +void ConfigureAudio::SetConfiguration() { + SetOutputSinkFromSinkID(); + + // The device list cannot be pre-populated (nor listed) until the output sink is known. + UpdateAudioDevices(sink_combo_box->currentIndex()); + + SetOutputDevicesFromDeviceID(); + SetInputDevicesFromDeviceID(); +} + +void ConfigureAudio::SetOutputSinkFromSinkID() { + [[maybe_unused]] const QSignalBlocker blocker(sink_combo_box); + + int new_sink_index = 0; + const QString sink_id = QString::fromStdString(Settings::values.sink_id.ToString()); + for (int index = 0; index < sink_combo_box->count(); index++) { + if (sink_combo_box->itemText(index) == sink_id) { + new_sink_index = index; + break; + } + } + + sink_combo_box->setCurrentIndex(new_sink_index); +} + +void ConfigureAudio::SetOutputDevicesFromDeviceID() { + int new_device_index = 0; + + const QString output_device_id = + QString::fromStdString(Settings::values.audio_output_device_id.GetValue()); + for (int index = 0; index < output_device_combo_box->count(); index++) { + if (output_device_combo_box->itemText(index) == output_device_id) { + new_device_index = index; + break; + } + } + + output_device_combo_box->setCurrentIndex(new_device_index); +} + +void ConfigureAudio::SetInputDevicesFromDeviceID() { + int new_device_index = 0; + const QString input_device_id = + QString::fromStdString(Settings::values.audio_input_device_id.GetValue()); + for (int index = 0; index < input_device_combo_box->count(); index++) { + if (input_device_combo_box->itemText(index) == input_device_id) { + new_device_index = index; + break; + } + } + + input_device_combo_box->setCurrentIndex(new_device_index); +} + +void ConfigureAudio::ApplyConfiguration() { + const bool is_powered_on = system.IsPoweredOn(); + for (const auto& apply_func : apply_funcs) { + apply_func(is_powered_on); + } + + Settings::values.sink_id.LoadString( + sink_combo_box->itemText(sink_combo_box->currentIndex()).toStdString()); + Settings::values.audio_output_device_id.SetValue( + output_device_combo_box->itemText(output_device_combo_box->currentIndex()).toStdString()); + Settings::values.audio_input_device_id.SetValue( + input_device_combo_box->itemText(input_device_combo_box->currentIndex()).toStdString()); +} + +void ConfigureAudio::changeEvent(QEvent* event) { + if (event->type() == QEvent::LanguageChange) { + RetranslateUI(); + } + + QWidget::changeEvent(event); +} + +void ConfigureAudio::UpdateAudioDevices(int sink_index) { + updating_devices = true; + output_device_combo_box->clear(); + output_device_combo_box->addItem(QString::fromUtf8(AudioCore::Sink::auto_device_name)); + + const auto sink_id = + Settings::ToEnum(sink_combo_box->itemText(sink_index).toStdString()); + for (const auto& device : AudioCore::Sink::GetDeviceListForSink(sink_id, false)) { + output_device_combo_box->addItem(QString::fromStdString(device)); + } + + input_device_combo_box->clear(); + input_device_combo_box->addItem(QString::fromUtf8(AudioCore::Sink::auto_device_name)); + for (const auto& device : AudioCore::Sink::GetDeviceListForSink(sink_id, true)) { + input_device_combo_box->addItem(QString::fromStdString(device)); + } + updating_devices = false; +} + +void ConfigureAudio::InitializeAudioSinkComboBox() { + sink_combo_box->clear(); + sink_combo_box->addItem(QString::fromUtf8(AudioCore::Sink::auto_device_name)); + + for (const auto& id : AudioCore::Sink::GetSinkIDs()) { + sink_combo_box->addItem(QString::fromStdString(Settings::CanonicalizeEnum(id))); + } +} + +void ConfigureAudio::RetranslateUI() { + ui->retranslateUi(this); +} diff --git a/src/sudachi/configuration/configure_audio.h b/src/sudachi/configuration/configure_audio.h new file mode 100644 index 0000000..e18812e --- /dev/null +++ b/src/sudachi/configuration/configure_audio.h @@ -0,0 +1,66 @@ +// SPDX-FileCopyrightText: Copyright 2018 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include +#include +#include +#include "sudachi/configuration/configuration_shared.h" + +class QComboBox; + +namespace Core { +class System; +} + +namespace Ui { +class ConfigureAudio; +} + +namespace ConfigurationShared { +class Builder; +} + +class ConfigureAudio : public ConfigurationShared::Tab { + Q_OBJECT + +public: + explicit ConfigureAudio(const Core::System& system_, + std::shared_ptr> group, + const ConfigurationShared::Builder& builder, QWidget* parent = nullptr); + ~ConfigureAudio() override; + + void ApplyConfiguration() override; + void SetConfiguration() override; + +private: + void changeEvent(QEvent* event) override; + + void InitializeAudioSinkComboBox(); + + void RetranslateUI(); + + void UpdateAudioDevices(int sink_index); + + void SetOutputSinkFromSinkID(); + void SetOutputDevicesFromDeviceID(); + void SetInputDevicesFromDeviceID(); + + void Setup(const ConfigurationShared::Builder& builder); + + std::unique_ptr ui; + + const Core::System& system; + + std::vector> apply_funcs{}; + + bool updating_devices = false; + QComboBox* sink_combo_box; + QPushButton* restore_sink_button; + QComboBox* output_device_combo_box; + QPushButton* restore_output_device_button; + QComboBox* input_device_combo_box; + QPushButton* restore_input_device_button; +}; diff --git a/src/sudachi/configuration/configure_audio.ui b/src/sudachi/configuration/configure_audio.ui new file mode 100644 index 0000000..1181aeb --- /dev/null +++ b/src/sudachi/configuration/configure_audio.ui @@ -0,0 +1,67 @@ + + + ConfigureAudio + + + + 0 + 0 + 367 + 368 + + + + Audio + + + + + + Audio + + + + + + + 16777215 + 16777213 + + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + + + + + + Qt::Vertical + + + + 167 + 55 + + + + + + + + + diff --git a/src/sudachi/configuration/configure_camera.cpp b/src/sudachi/configuration/configure_camera.cpp new file mode 100644 index 0000000..343d00b --- /dev/null +++ b/src/sudachi/configuration/configure_camera.cpp @@ -0,0 +1,163 @@ +// Text : Copyright 2022 sudachi Emulator Project +// SPDX-License-Identifier: GPL-3.0-or-later + +#include +#include +#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) && SUDACHI_USE_QT_MULTIMEDIA +#include +#include +#endif +#include +#include + +#include "common/settings.h" +#include "input_common/drivers/camera.h" +#include "input_common/main.h" +#include "ui_configure_camera.h" +#include "sudachi/configuration/configure_camera.h" + +ConfigureCamera::ConfigureCamera(QWidget* parent, InputCommon::InputSubsystem* input_subsystem_) + : QDialog(parent), input_subsystem{input_subsystem_}, + ui(std::make_unique()) { + ui->setupUi(this); + + connect(ui->restore_defaults_button, &QPushButton::clicked, this, + &ConfigureCamera::RestoreDefaults); + connect(ui->preview_button, &QPushButton::clicked, this, &ConfigureCamera::PreviewCamera); + + auto blank_image = QImage(320, 240, QImage::Format::Format_RGB32); + blank_image.fill(Qt::black); + DisplayCapturedFrame(0, blank_image); + + LoadConfiguration(); + resize(0, 0); +} + +ConfigureCamera::~ConfigureCamera() = default; + +void ConfigureCamera::PreviewCamera() { +#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) && SUDACHI_USE_QT_MULTIMEDIA + const auto index = ui->ir_sensor_combo_box->currentIndex(); + bool camera_found = false; + const QList cameras = QCameraInfo::availableCameras(); + for (const QCameraInfo& cameraInfo : cameras) { + if (input_devices[index] == cameraInfo.deviceName().toStdString() || + input_devices[index] == "Auto") { + LOG_INFO(Frontend, "Selected Camera {} {}", cameraInfo.description().toStdString(), + cameraInfo.deviceName().toStdString()); + camera = std::make_unique(cameraInfo); + if (!camera->isCaptureModeSupported(QCamera::CaptureMode::CaptureViewfinder) && + !camera->isCaptureModeSupported(QCamera::CaptureMode::CaptureStillImage)) { + LOG_ERROR(Frontend, + "Camera doesn't support CaptureViewfinder or CaptureStillImage"); + continue; + } + camera_found = true; + break; + } + } + + // Clear previous frame + auto blank_image = QImage(320, 240, QImage::Format::Format_RGB32); + blank_image.fill(Qt::black); + DisplayCapturedFrame(0, blank_image); + + if (!camera_found) { + return; + } + + camera_capture = std::make_unique(camera.get()); + + if (!camera_capture->isCaptureDestinationSupported( + QCameraImageCapture::CaptureDestination::CaptureToBuffer)) { + LOG_ERROR(Frontend, "Camera doesn't support saving to buffer"); + return; + } + + camera_capture->setCaptureDestination(QCameraImageCapture::CaptureDestination::CaptureToBuffer); + connect(camera_capture.get(), &QCameraImageCapture::imageCaptured, this, + &ConfigureCamera::DisplayCapturedFrame); + camera->unload(); + if (camera->isCaptureModeSupported(QCamera::CaptureMode::CaptureViewfinder)) { + camera->setCaptureMode(QCamera::CaptureViewfinder); + } else if (camera->isCaptureModeSupported(QCamera::CaptureMode::CaptureStillImage)) { + camera->setCaptureMode(QCamera::CaptureStillImage); + } + camera->load(); + camera->start(); + + pending_snapshots = 0; + is_virtual_camera = false; + + camera_timer = std::make_unique(); + connect(camera_timer.get(), &QTimer::timeout, [this] { + // If the camera doesn't capture, test for virtual cameras + if (pending_snapshots > 5) { + is_virtual_camera = true; + } + // Virtual cameras like obs need to reset the camera every capture + if (is_virtual_camera) { + camera->stop(); + camera->start(); + } + pending_snapshots++; + camera_capture->capture(); + }); + + camera_timer->start(250); +#endif +} + +void ConfigureCamera::DisplayCapturedFrame(int requestId, const QImage& img) { + LOG_INFO(Frontend, "ImageCaptured {} {}", img.width(), img.height()); + const auto converted = img.scaled(320, 240, Qt::AspectRatioMode::IgnoreAspectRatio, + Qt::TransformationMode::SmoothTransformation); + ui->preview_box->setPixmap(QPixmap::fromImage(converted)); + pending_snapshots = 0; +} + +void ConfigureCamera::changeEvent(QEvent* event) { + if (event->type() == QEvent::LanguageChange) { + RetranslateUI(); + } + + QDialog::changeEvent(event); +} + +void ConfigureCamera::RetranslateUI() { + ui->retranslateUi(this); +} + +void ConfigureCamera::ApplyConfiguration() { + const auto index = ui->ir_sensor_combo_box->currentIndex(); + Settings::values.ir_sensor_device.SetValue(input_devices[index]); +} + +void ConfigureCamera::LoadConfiguration() { + input_devices.clear(); + ui->ir_sensor_combo_box->clear(); + input_devices.push_back("Auto"); + ui->ir_sensor_combo_box->addItem(tr("Auto")); +#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) && SUDACHI_USE_QT_MULTIMEDIA + const auto cameras = QCameraInfo::availableCameras(); + for (const QCameraInfo& cameraInfo : cameras) { + input_devices.push_back(cameraInfo.deviceName().toStdString()); + ui->ir_sensor_combo_box->addItem(cameraInfo.description()); + } +#endif + + const auto current_device = Settings::values.ir_sensor_device.GetValue(); + + const auto devices_it = std::find_if( + input_devices.begin(), input_devices.end(), + [current_device](const std::string& device) { return device == current_device; }); + const int device_index = + devices_it != input_devices.end() + ? static_cast(std::distance(input_devices.begin(), devices_it)) + : 0; + ui->ir_sensor_combo_box->setCurrentIndex(device_index); +} + +void ConfigureCamera::RestoreDefaults() { + ui->ir_sensor_combo_box->setCurrentIndex(0); +} diff --git a/src/sudachi/configuration/configure_camera.h b/src/sudachi/configuration/configure_camera.h new file mode 100644 index 0000000..7911709 --- /dev/null +++ b/src/sudachi/configuration/configure_camera.h @@ -0,0 +1,56 @@ +// Text : Copyright 2022 sudachi Emulator Project +// SPDX-License-Identifier: GPL-3.0-or-later + +#pragma once + +#include +#include + +class QTimer; +class QCamera; +class QCameraImageCapture; + +namespace InputCommon { +class InputSubsystem; +} // namespace InputCommon + +namespace Ui { +class ConfigureCamera; +} + +class ConfigureCamera : public QDialog { + Q_OBJECT + +public: + explicit ConfigureCamera(QWidget* parent, InputCommon::InputSubsystem* input_subsystem_); + ~ConfigureCamera() override; + + void ApplyConfiguration(); + +private: + void changeEvent(QEvent* event) override; + void RetranslateUI(); + + /// Load configuration settings. + void LoadConfiguration(); + + /// Restore all buttons to their default values. + void RestoreDefaults(); + + void DisplayCapturedFrame(int requestId, const QImage& img); + + /// Loads and signals the current selected camera to display a frame + void PreviewCamera(); + + InputCommon::InputSubsystem* input_subsystem; + + bool is_virtual_camera; + int pending_snapshots; +#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) && SUDACHI_USE_QT_MULTIMEDIA + std::unique_ptr camera; + std::unique_ptr camera_capture; +#endif + std::unique_ptr camera_timer; + std::vector input_devices; + std::unique_ptr ui; +}; diff --git a/src/sudachi/configuration/configure_camera.ui b/src/sudachi/configuration/configure_camera.ui new file mode 100644 index 0000000..976a9b1 --- /dev/null +++ b/src/sudachi/configuration/configure_camera.ui @@ -0,0 +1,170 @@ + + + ConfigureCamera + + + + 0 + 0 + 298 + 339 + + + + Configure Infrared Camera + + + + + + + 280 + 0 + + + + Select where the image of the emulated camera comes from. It may be a virtual camera or a real camera. + + + true + + + + + + + Qt::Vertical + + + QSizePolicy::Fixed + + + + 20 + 20 + + + + + + + + Camera Image Source: + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Input device: + + + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + Preview + + + + + + + 320 + 240 + + + + Resolution: 320*240 + + + + + + + Click to preview + + + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + + Restore Defaults + + + + + + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + + + + + + + + + + buttonBox + accepted() + ConfigureCamera + accept() + + + buttonBox + rejected() + ConfigureCamera + reject() + + + diff --git a/src/sudachi/configuration/configure_cpu.cpp b/src/sudachi/configuration/configure_cpu.cpp new file mode 100644 index 0000000..3a34469 --- /dev/null +++ b/src/sudachi/configuration/configure_cpu.cpp @@ -0,0 +1,114 @@ +// SPDX-FileCopyrightText: Copyright 2020 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include +#include +#include +#include "common/common_types.h" +#include "common/settings.h" +#include "common/settings_enums.h" +#include "configuration/shared_widget.h" +#include "core/core.h" +#include "ui_configure_cpu.h" +#include "sudachi/configuration/configuration_shared.h" +#include "sudachi/configuration/configure_cpu.h" + +ConfigureCpu::ConfigureCpu(const Core::System& system_, + std::shared_ptr> group_, + const ConfigurationShared::Builder& builder, QWidget* parent) + : Tab(group_, parent), ui{std::make_unique()}, system{system_}, + combobox_translations(builder.ComboboxTranslations()) { + ui->setupUi(this); + + Setup(builder); + + SetConfiguration(); + + connect(accuracy_combobox, qOverload(&QComboBox::currentIndexChanged), this, + &ConfigureCpu::UpdateGroup); + + connect(backend_combobox, qOverload(&QComboBox::currentIndexChanged), this, + &ConfigureCpu::UpdateGroup); + +#ifdef HAS_NCE + ui->backend_group->setVisible(true); +#endif +} + +ConfigureCpu::~ConfigureCpu() = default; + +void ConfigureCpu::SetConfiguration() {} +void ConfigureCpu::Setup(const ConfigurationShared::Builder& builder) { + auto* accuracy_layout = ui->widget_accuracy->layout(); + auto* backend_layout = ui->widget_backend->layout(); + auto* unsafe_layout = ui->unsafe_widget->layout(); + std::map unsafe_hold{}; + + std::vector settings; + const auto push = [&](Settings::Category category) { + for (const auto setting : Settings::values.linkage.by_category[category]) { + settings.push_back(setting); + } + }; + + push(Settings::Category::Cpu); + push(Settings::Category::CpuUnsafe); + + for (const auto setting : settings) { + auto* widget = builder.BuildWidget(setting, apply_funcs); + + if (widget == nullptr) { + continue; + } + if (!widget->Valid()) { + widget->deleteLater(); + continue; + } + + if (setting->Id() == Settings::values.cpu_accuracy.Id()) { + // Keep track of cpu_accuracy combobox to display/hide the unsafe settings + accuracy_layout->addWidget(widget); + accuracy_combobox = widget->combobox; + } else if (setting->Id() == Settings::values.cpu_backend.Id()) { + backend_layout->addWidget(widget); + backend_combobox = widget->combobox; + } else { + // Presently, all other settings here are unsafe checkboxes + unsafe_hold.insert({setting->Id(), widget}); + } + } + + for (const auto& [label, widget] : unsafe_hold) { + unsafe_layout->addWidget(widget); + } + + UpdateGroup(accuracy_combobox->currentIndex()); + UpdateGroup(backend_combobox->currentIndex()); +} + +void ConfigureCpu::UpdateGroup(int index) { + const auto accuracy = static_cast( + combobox_translations.at(Settings::EnumMetadata::Index())[index] + .first); + ui->unsafe_group->setVisible(accuracy == Settings::CpuAccuracy::Unsafe); +} + +void ConfigureCpu::ApplyConfiguration() { + const bool is_powered_on = system.IsPoweredOn(); + for (const auto& apply_func : apply_funcs) { + apply_func(is_powered_on); + } +} + +void ConfigureCpu::changeEvent(QEvent* event) { + if (event->type() == QEvent::LanguageChange) { + RetranslateUI(); + } + + QWidget::changeEvent(event); +} + +void ConfigureCpu::RetranslateUI() { + ui->retranslateUi(this); +} diff --git a/src/sudachi/configuration/configure_cpu.h b/src/sudachi/configuration/configure_cpu.h new file mode 100644 index 0000000..aba6ed4 --- /dev/null +++ b/src/sudachi/configuration/configure_cpu.h @@ -0,0 +1,55 @@ +// SPDX-FileCopyrightText: Copyright 2020 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include +#include +#include "sudachi/configuration/configuration_shared.h" +#include "sudachi/configuration/shared_translation.h" + +class QComboBox; + +namespace Core { +class System; +} + +namespace Ui { +class ConfigureCpu; +} + +namespace ConfigurationShared { +class Builder; +} + +class ConfigureCpu : public ConfigurationShared::Tab { + Q_OBJECT + +public: + explicit ConfigureCpu(const Core::System& system_, + std::shared_ptr> group, + const ConfigurationShared::Builder& builder, QWidget* parent = nullptr); + ~ConfigureCpu() override; + + void ApplyConfiguration() override; + void SetConfiguration() override; + +private: + void changeEvent(QEvent* event) override; + void RetranslateUI(); + + void UpdateGroup(int index); + + void Setup(const ConfigurationShared::Builder& builder); + + std::unique_ptr ui; + + const Core::System& system; + + const ConfigurationShared::ComboboxTranslationMap& combobox_translations; + std::vector> apply_funcs{}; + + QComboBox* accuracy_combobox; + QComboBox* backend_combobox; +}; diff --git a/src/sudachi/configuration/configure_cpu.ui b/src/sudachi/configuration/configure_cpu.ui new file mode 100644 index 0000000..13fd436 --- /dev/null +++ b/src/sudachi/configuration/configure_cpu.ui @@ -0,0 +1,151 @@ + + + ConfigureCpu + + + + 0 + 0 + 448 + 439 + + + + Form + + + CPU + + + + + + 0 + + + + + General + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + + + We recommend setting accuracy to "Auto". + + + false + + + + + + + + + + CPU Backend + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + + false + + + + + + + Unsafe CPU Optimization Settings + + + + + + These settings reduce accuracy for speed. + + + false + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + + + + + + Qt::Vertical + + + QSizePolicy::Expanding + + + + 20 + 40 + + + + + + + + + + + diff --git a/src/sudachi/configuration/configure_cpu_debug.cpp b/src/sudachi/configuration/configure_cpu_debug.cpp new file mode 100644 index 0000000..a779fea --- /dev/null +++ b/src/sudachi/configuration/configure_cpu_debug.cpp @@ -0,0 +1,78 @@ +// SPDX-FileCopyrightText: Copyright 2020 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include "common/settings.h" +#include "core/core.h" +#include "ui_configure_cpu_debug.h" +#include "sudachi/configuration/configure_cpu_debug.h" + +ConfigureCpuDebug::ConfigureCpuDebug(const Core::System& system_, QWidget* parent) + : QWidget(parent), ui{std::make_unique()}, system{system_} { + ui->setupUi(this); + + SetConfiguration(); +} + +ConfigureCpuDebug::~ConfigureCpuDebug() = default; + +void ConfigureCpuDebug::SetConfiguration() { + const bool runtime_lock = !system.IsPoweredOn(); + + ui->cpuopt_page_tables->setEnabled(runtime_lock); + ui->cpuopt_page_tables->setChecked(Settings::values.cpuopt_page_tables.GetValue()); + ui->cpuopt_block_linking->setEnabled(runtime_lock); + ui->cpuopt_block_linking->setChecked(Settings::values.cpuopt_block_linking.GetValue()); + ui->cpuopt_return_stack_buffer->setEnabled(runtime_lock); + ui->cpuopt_return_stack_buffer->setChecked( + Settings::values.cpuopt_return_stack_buffer.GetValue()); + ui->cpuopt_fast_dispatcher->setEnabled(runtime_lock); + ui->cpuopt_fast_dispatcher->setChecked(Settings::values.cpuopt_fast_dispatcher.GetValue()); + ui->cpuopt_context_elimination->setEnabled(runtime_lock); + ui->cpuopt_context_elimination->setChecked( + Settings::values.cpuopt_context_elimination.GetValue()); + ui->cpuopt_const_prop->setEnabled(runtime_lock); + ui->cpuopt_const_prop->setChecked(Settings::values.cpuopt_const_prop.GetValue()); + ui->cpuopt_misc_ir->setEnabled(runtime_lock); + ui->cpuopt_misc_ir->setChecked(Settings::values.cpuopt_misc_ir.GetValue()); + ui->cpuopt_reduce_misalign_checks->setEnabled(runtime_lock); + ui->cpuopt_reduce_misalign_checks->setChecked( + Settings::values.cpuopt_reduce_misalign_checks.GetValue()); + ui->cpuopt_fastmem->setEnabled(runtime_lock); + ui->cpuopt_fastmem->setChecked(Settings::values.cpuopt_fastmem.GetValue()); + ui->cpuopt_fastmem_exclusives->setEnabled(runtime_lock); + ui->cpuopt_fastmem_exclusives->setChecked( + Settings::values.cpuopt_fastmem_exclusives.GetValue()); + ui->cpuopt_recompile_exclusives->setEnabled(runtime_lock); + ui->cpuopt_recompile_exclusives->setChecked( + Settings::values.cpuopt_recompile_exclusives.GetValue()); + ui->cpuopt_ignore_memory_aborts->setEnabled(runtime_lock); + ui->cpuopt_ignore_memory_aborts->setChecked( + Settings::values.cpuopt_ignore_memory_aborts.GetValue()); +} + +void ConfigureCpuDebug::ApplyConfiguration() { + Settings::values.cpuopt_page_tables = ui->cpuopt_page_tables->isChecked(); + Settings::values.cpuopt_block_linking = ui->cpuopt_block_linking->isChecked(); + Settings::values.cpuopt_return_stack_buffer = ui->cpuopt_return_stack_buffer->isChecked(); + Settings::values.cpuopt_fast_dispatcher = ui->cpuopt_fast_dispatcher->isChecked(); + Settings::values.cpuopt_context_elimination = ui->cpuopt_context_elimination->isChecked(); + Settings::values.cpuopt_const_prop = ui->cpuopt_const_prop->isChecked(); + Settings::values.cpuopt_misc_ir = ui->cpuopt_misc_ir->isChecked(); + Settings::values.cpuopt_reduce_misalign_checks = ui->cpuopt_reduce_misalign_checks->isChecked(); + Settings::values.cpuopt_fastmem = ui->cpuopt_fastmem->isChecked(); + Settings::values.cpuopt_fastmem_exclusives = ui->cpuopt_fastmem_exclusives->isChecked(); + Settings::values.cpuopt_recompile_exclusives = ui->cpuopt_recompile_exclusives->isChecked(); + Settings::values.cpuopt_ignore_memory_aborts = ui->cpuopt_ignore_memory_aborts->isChecked(); +} + +void ConfigureCpuDebug::changeEvent(QEvent* event) { + if (event->type() == QEvent::LanguageChange) { + RetranslateUI(); + } + + QWidget::changeEvent(event); +} + +void ConfigureCpuDebug::RetranslateUI() { + ui->retranslateUi(this); +} diff --git a/src/sudachi/configuration/configure_cpu_debug.h b/src/sudachi/configuration/configure_cpu_debug.h new file mode 100644 index 0000000..362faa7 --- /dev/null +++ b/src/sudachi/configuration/configure_cpu_debug.h @@ -0,0 +1,35 @@ +// SPDX-FileCopyrightText: Copyright 2020 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include + +namespace Core { +class System; +} + +namespace Ui { +class ConfigureCpuDebug; +} + +class ConfigureCpuDebug : public QWidget { + Q_OBJECT + +public: + explicit ConfigureCpuDebug(const Core::System& system_, QWidget* parent = nullptr); + ~ConfigureCpuDebug() override; + + void ApplyConfiguration(); + +private: + void changeEvent(QEvent* event) override; + void RetranslateUI(); + + void SetConfiguration(); + + std::unique_ptr ui; + + const Core::System& system; +}; diff --git a/src/sudachi/configuration/configure_cpu_debug.ui b/src/sudachi/configuration/configure_cpu_debug.ui new file mode 100644 index 0000000..3010f7f --- /dev/null +++ b/src/sudachi/configuration/configure_cpu_debug.ui @@ -0,0 +1,223 @@ + + + ConfigureCpuDebug + + + + 0 + 0 + 592 + 503 + + + + Form + + + CPU + + + + + + + + Toggle CPU Optimizations + + + + + + <html><head/><body><p><span style=" font-weight:600;">For debugging only.</span><br/>If you're not sure what these do, keep all of these enabled. <br/>These settings, when disabled, only take effect when CPU Debugging is enabled. </p></body></html> + + + false + + + + + + + + <div style="white-space: nowrap">This optimization speeds up memory accesses by the guest program.</div> + <div style="white-space: nowrap">Enabling it inlines accesses to PageTable::pointers into emitted code.</div> + <div style="white-space: nowrap">Disabling this forces all memory accesses to go through the Memory::Read/Memory::Write functions.</div> + + + + Enable inline page tables + + + + + + + + <div>This optimization avoids dispatcher lookups by allowing emitted basic blocks to jump directly to other basic blocks if the destination PC is static.</div> + + + + Enable block linking + + + + + + + + <div>This optimization avoids dispatcher lookups by keeping track potential return addresses of BL instructions. This approximates what happens with a return stack buffer on a real CPU.</div> + + + + Enable return stack buffer + + + + + + + + <div>Enable a two-tiered dispatch system. A faster dispatcher written in assembly has a small MRU cache of jump destinations is used first. If that fails, dispatch falls back to the slower C++ dispatcher.</div> + + + + Enable fast dispatcher + + + + + + + + <div>Enables an IR optimization that reduces unnecessary accesses to the CPU context structure.</div> + + + + Enable context elimination + + + + + + + + <div>Enables IR optimizations that involve constant propagation.</div> + + + + Enable constant propagation + + + + + + + + <div>Enables miscellaneous IR optimizations.</div> + + + + Enable miscellaneous optimizations + + + + + + + + <div style="white-space: nowrap">When enabled, a misalignment is only triggered when an access crosses a page boundary.</div> + <div style="white-space: nowrap">When disabled, a misalignment is triggered on all misaligned accesses.</div> + + + + Enable misalignment check reduction + + + + + + + + <div style="white-space: nowrap">This optimization speeds up memory accesses by the guest program.</div> + <div style="white-space: nowrap">Enabling it causes guest memory reads/writes to be done directly into memory and make use of Host's MMU.</div> + <div style="white-space: nowrap">Disabling this forces all memory accesses to use Software MMU Emulation.</div> + + + + Enable Host MMU Emulation (general memory instructions) + + + + + + + + <div style="white-space: nowrap">This optimization speeds up exclusive memory accesses by the guest program.</div> + <div style="white-space: nowrap">Enabling it causes guest exclusive memory reads/writes to be done directly into memory and make use of Host's MMU.</div> + <div style="white-space: nowrap">Disabling this forces all exclusive memory accesses to use Software MMU Emulation.</div> + + + + Enable Host MMU Emulation (exclusive memory instructions) + + + + + + + + <div style="white-space: nowrap">This optimization speeds up exclusive memory accesses by the guest program.</div> + <div style="white-space: nowrap">Enabling it reduces the overhead of fastmem failure of exclusive memory accesses.</div> + + + + Enable recompilation of exclusive memory instructions + + + + + + + + <div style="white-space: nowrap">This optimization speeds up memory accesses by allowing invalid memory accesses to succeed.</div> + <div style="white-space: nowrap">Enabling it reduces the overhead of all memory accesses and has no impact on programs that don't access invalid memory.</div> + + + + Enable fallbacks for invalid memory accesses + + + + + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + CPU settings are available only when game is not running. + + + true + + + + + + + + diff --git a/src/sudachi/configuration/configure_debug.cpp b/src/sudachi/configuration/configure_debug.cpp new file mode 100644 index 0000000..a58ddf7 --- /dev/null +++ b/src/sudachi/configuration/configure_debug.cpp @@ -0,0 +1,130 @@ +// SPDX-FileCopyrightText: 2016 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include +#include +#include "common/fs/path_util.h" +#include "common/logging/backend.h" +#include "common/logging/filter.h" +#include "common/settings.h" +#include "core/core.h" +#include "ui_configure_debug.h" +#include "sudachi/configuration/configure_debug.h" +#include "sudachi/debugger/console.h" +#include "sudachi/uisettings.h" + +ConfigureDebug::ConfigureDebug(const Core::System& system_, QWidget* parent) + : QScrollArea(parent), ui{std::make_unique()}, system{system_} { + ui->setupUi(this); + SetConfiguration(); + + connect(ui->open_log_button, &QPushButton::clicked, []() { + const auto path = + QString::fromStdString(Common::FS::GetSudachiPathString(Common::FS::SudachiPath::LogDir)); + QDesktopServices::openUrl(QUrl::fromLocalFile(path)); + }); + + connect(ui->toggle_gdbstub, &QCheckBox::toggled, + [&]() { ui->gdbport_spinbox->setEnabled(ui->toggle_gdbstub->isChecked()); }); +} + +ConfigureDebug::~ConfigureDebug() = default; + +void ConfigureDebug::SetConfiguration() { + const bool runtime_lock = !system.IsPoweredOn(); + ui->toggle_gdbstub->setChecked(Settings::values.use_gdbstub.GetValue()); + ui->gdbport_spinbox->setEnabled(Settings::values.use_gdbstub.GetValue()); + ui->gdbport_spinbox->setValue(Settings::values.gdbstub_port.GetValue()); + ui->toggle_console->setEnabled(runtime_lock); + ui->toggle_console->setChecked(UISettings::values.show_console.GetValue()); + ui->log_filter_edit->setText(QString::fromStdString(Settings::values.log_filter.GetValue())); + ui->homebrew_args_edit->setText( + QString::fromStdString(Settings::values.program_args.GetValue())); + ui->fs_access_log->setEnabled(runtime_lock); + ui->fs_access_log->setChecked(Settings::values.enable_fs_access_log.GetValue()); + ui->reporting_services->setChecked(Settings::values.reporting_services.GetValue()); + ui->dump_audio_commands->setChecked(Settings::values.dump_audio_commands.GetValue()); + ui->quest_flag->setChecked(Settings::values.quest_flag.GetValue()); + ui->use_debug_asserts->setChecked(Settings::values.use_debug_asserts.GetValue()); + ui->use_auto_stub->setChecked(Settings::values.use_auto_stub.GetValue()); + ui->enable_all_controllers->setChecked(Settings::values.enable_all_controllers.GetValue()); + ui->enable_renderdoc_hotkey->setEnabled(runtime_lock); + ui->enable_renderdoc_hotkey->setChecked(Settings::values.enable_renderdoc_hotkey.GetValue()); + ui->disable_buffer_reorder->setEnabled(runtime_lock); + ui->disable_buffer_reorder->setChecked(Settings::values.disable_buffer_reorder.GetValue()); + ui->enable_graphics_debugging->setEnabled(runtime_lock); + ui->enable_graphics_debugging->setChecked(Settings::values.renderer_debug.GetValue()); + ui->enable_shader_feedback->setEnabled(runtime_lock); + ui->enable_shader_feedback->setChecked(Settings::values.renderer_shader_feedback.GetValue()); + ui->enable_cpu_debugging->setEnabled(runtime_lock); + ui->enable_cpu_debugging->setChecked(Settings::values.cpu_debug_mode.GetValue()); + ui->enable_nsight_aftermath->setEnabled(runtime_lock); + ui->enable_nsight_aftermath->setChecked(Settings::values.enable_nsight_aftermath.GetValue()); + ui->dump_shaders->setEnabled(runtime_lock); + ui->dump_shaders->setChecked(Settings::values.dump_shaders.GetValue()); + ui->dump_macros->setEnabled(runtime_lock); + ui->dump_macros->setChecked(Settings::values.dump_macros.GetValue()); + ui->disable_macro_jit->setEnabled(runtime_lock); + ui->disable_macro_jit->setChecked(Settings::values.disable_macro_jit.GetValue()); + ui->disable_macro_hle->setEnabled(runtime_lock); + ui->disable_macro_hle->setChecked(Settings::values.disable_macro_hle.GetValue()); + ui->disable_loop_safety_checks->setEnabled(runtime_lock); + ui->disable_loop_safety_checks->setChecked( + Settings::values.disable_shader_loop_safety_checks.GetValue()); + ui->extended_logging->setChecked(Settings::values.extended_logging.GetValue()); + ui->perform_vulkan_check->setChecked(Settings::values.perform_vulkan_check.GetValue()); + +#ifdef SUDACHI_USE_QT_WEB_ENGINE + ui->disable_web_applet->setChecked(UISettings::values.disable_web_applet.GetValue()); +#else + ui->disable_web_applet->setEnabled(false); + ui->disable_web_applet->setText(tr("Web applet not compiled")); +#endif +} + +void ConfigureDebug::ApplyConfiguration() { + Settings::values.use_gdbstub = ui->toggle_gdbstub->isChecked(); + Settings::values.gdbstub_port = ui->gdbport_spinbox->value(); + UISettings::values.show_console = ui->toggle_console->isChecked(); + Settings::values.log_filter = ui->log_filter_edit->text().toStdString(); + Settings::values.program_args = ui->homebrew_args_edit->text().toStdString(); + Settings::values.enable_fs_access_log = ui->fs_access_log->isChecked(); + Settings::values.reporting_services = ui->reporting_services->isChecked(); + Settings::values.dump_audio_commands = ui->dump_audio_commands->isChecked(); + Settings::values.quest_flag = ui->quest_flag->isChecked(); + Settings::values.use_debug_asserts = ui->use_debug_asserts->isChecked(); + Settings::values.use_auto_stub = ui->use_auto_stub->isChecked(); + Settings::values.enable_all_controllers = ui->enable_all_controllers->isChecked(); + Settings::values.renderer_debug = ui->enable_graphics_debugging->isChecked(); + Settings::values.enable_renderdoc_hotkey = ui->enable_renderdoc_hotkey->isChecked(); + Settings::values.disable_buffer_reorder = ui->disable_buffer_reorder->isChecked(); + Settings::values.renderer_shader_feedback = ui->enable_shader_feedback->isChecked(); + Settings::values.cpu_debug_mode = ui->enable_cpu_debugging->isChecked(); + Settings::values.enable_nsight_aftermath = ui->enable_nsight_aftermath->isChecked(); + Settings::values.dump_shaders = ui->dump_shaders->isChecked(); + Settings::values.dump_macros = ui->dump_macros->isChecked(); + Settings::values.disable_shader_loop_safety_checks = + ui->disable_loop_safety_checks->isChecked(); + Settings::values.disable_macro_jit = ui->disable_macro_jit->isChecked(); + Settings::values.disable_macro_hle = ui->disable_macro_hle->isChecked(); + Settings::values.extended_logging = ui->extended_logging->isChecked(); + Settings::values.perform_vulkan_check = ui->perform_vulkan_check->isChecked(); + UISettings::values.disable_web_applet = ui->disable_web_applet->isChecked(); + Debugger::ToggleConsole(); + Common::Log::Filter filter; + filter.ParseFilterString(Settings::values.log_filter.GetValue()); + Common::Log::SetGlobalFilter(filter); +} + +void ConfigureDebug::changeEvent(QEvent* event) { + if (event->type() == QEvent::LanguageChange) { + RetranslateUI(); + } + + QWidget::changeEvent(event); +} + +void ConfigureDebug::RetranslateUI() { + ui->retranslateUi(this); +} diff --git a/src/sudachi/configuration/configure_debug.h b/src/sudachi/configuration/configure_debug.h new file mode 100644 index 0000000..030a0b7 --- /dev/null +++ b/src/sudachi/configuration/configure_debug.h @@ -0,0 +1,37 @@ +// SPDX-FileCopyrightText: 2016 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include + +namespace Core { +class System; +} + +namespace Ui { +class ConfigureDebug; +} + +class ConfigureDebug : public QScrollArea { + Q_OBJECT + +public: + explicit ConfigureDebug(const Core::System& system_, QWidget* parent = nullptr); + ~ConfigureDebug() override; + + void ApplyConfiguration(); + +private: + void changeEvent(QEvent* event) override; + + void RetranslateUI(); + void SetConfiguration(); + + std::unique_ptr ui; + + const Core::System& system; + + bool crash_dump_warning_shown{false}; +}; diff --git a/src/sudachi/configuration/configure_debug.ui b/src/sudachi/configuration/configure_debug.ui new file mode 100644 index 0000000..4be6d93 --- /dev/null +++ b/src/sudachi/configuration/configure_debug.ui @@ -0,0 +1,576 @@ + + + ConfigureDebug + + + + 0 + 0 + 831 + 760 + + + + true + + + + + 0 + 0 + 842 + 741 + + + + + + + 0 + + + + + + 0 + 0 + + + + Debugger + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop + + + false + + + false + + + + + + + 0 + 0 + + + + + QLayout::SetDefaultConstraint + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 0 + 0 + + + + Enable GDB Stub + + + + + + + + 0 + 0 + + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 0 + 0 + + + + Port: + + + + + + + + 0 + 0 + + + + 1024 + + + 65535 + + + + + + + + + + + + + + + + + 0 + 0 + + + + Logging + + + + + + Open Log Location + + + + + + + + 0 + 0 + + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 0 + 0 + + + + Global Log Filter + + + + + + + + + + + + + true + + + When checked, the max size of the log increases from 100 MB to 1 GB + + + Enable Extended Logging** + + + + + + + Show Log in Console + + + + + + + + + + + + Homebrew + + + + + + + + Arguments String + + + + + + + + + + + + + + + + + Graphics + + + + + + When checked, it executes shaders without loop logic changes + + + Disable Loop safety checks + + + + + + + true + + + When checked, it will dump all the macro programs of the GPU + + + Dump Maxwell Macros + + + + + + + When checked, it enables Nsight Aftermath crash dumps + + + Enable Nsight Aftermath + + + + + + + true + + + When checked, it will dump all the original assembler shaders from the disk shader cache or game as found + + + Dump Game Shaders + + + + + + + Enable Renderdoc Hotkey + + + + + + + true + + + When checked, it disables the macro Just In Time compiler. Enabling this makes games run slower + + + Disable Macro JIT + + + + + + + true + + + When checked, it disables the macro HLE functions. Enabling this makes games run slower + + + Disable Macro HLE + + + + + + + true + + + When checked, the graphics API enters a slower debugging mode + + + Enable Graphics Debugging + + + + + + + Qt::Vertical + + + QSizePolicy::Preferred + + + + 20 + 0 + + + + + + + + When checked, sudachi will log statistics about the compiled pipeline cache + + + Enable Shader Feedback + + + + + + + <html><head/><body><p>When checked, disables reordering of mapped memory uploads which allows to associate uploads with specific draws. May reduce performance in some cases.</p></body></html> + + + Disable Buffer Reorder + + + + + + + + + + Advanced + + + + + + Enables sudachi to check for a working Vulkan environment when the program starts up. Disable this if this is causing issues with external programs seeing sudachi. + + + Perform Startup Vulkan Check + + + + + + + Disable Web Applet + + + + + + + Enable All Controller Types + + + + + + + Enable Auto-Stub** + + + + + + + Kiosk (Quest) Mode + + + + + + + Enable CPU Debugging + + + + + + + Enable Debug Asserts + + + + + + + Qt::Vertical + + + QSizePolicy::Expanding + + + + 20 + 0 + + + + + + + + + + + Debugging + + + + + + Enable FS Access Log + + + + + + + Enable this to output the latest generated audio command list to the console. Only affects games using the audio renderer. + + + Dump Audio Commands To Console** + + + + + + + Enable Verbose Reporting Services** + + + + + + + Qt::Vertical + + + QSizePolicy::Expanding + + + + 20 + 0 + + + + + + + + + + + + + Qt::Vertical + + + + 20 + 0 + + + + + + + + + 0 + 0 + + + + + true + + + + **This will be reset automatically when sudachi closes. + + + 20 + + + + + + + + log_filter_edit + toggle_console + extended_logging + open_log_button + homebrew_args_edit + enable_graphics_debugging + enable_shader_feedback + enable_nsight_aftermath + fs_access_log + reporting_services + quest_flag + enable_cpu_debugging + use_debug_asserts + + + + diff --git a/src/sudachi/configuration/configure_debug_controller.cpp b/src/sudachi/configuration/configure_debug_controller.cpp new file mode 100644 index 0000000..1da836a --- /dev/null +++ b/src/sudachi/configuration/configure_debug_controller.cpp @@ -0,0 +1,44 @@ +// SPDX-FileCopyrightText: Copyright 2020 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include "hid_core/hid_core.h" +#include "ui_configure_debug_controller.h" +#include "sudachi/configuration/configure_debug_controller.h" +#include "sudachi/configuration/configure_input_player.h" + +ConfigureDebugController::ConfigureDebugController(QWidget* parent, + InputCommon::InputSubsystem* input_subsystem, + InputProfiles* profiles, + Core::HID::HIDCore& hid_core, bool is_powered_on) + : QDialog(parent), ui(std::make_unique()), + debug_controller(new ConfigureInputPlayer(this, 9, nullptr, input_subsystem, profiles, + hid_core, is_powered_on, true)) { + ui->setupUi(this); + + ui->controllerLayout->addWidget(debug_controller); + + connect(ui->clear_all_button, &QPushButton::clicked, this, + [this] { debug_controller->ClearAll(); }); + connect(ui->restore_defaults_button, &QPushButton::clicked, this, + [this] { debug_controller->RestoreDefaults(); }); + + RetranslateUI(); +} + +ConfigureDebugController::~ConfigureDebugController() = default; + +void ConfigureDebugController::ApplyConfiguration() { + debug_controller->ApplyConfiguration(); +} + +void ConfigureDebugController::changeEvent(QEvent* event) { + if (event->type() == QEvent::LanguageChange) { + RetranslateUI(); + } + + QDialog::changeEvent(event); +} + +void ConfigureDebugController::RetranslateUI() { + ui->retranslateUi(this); +} diff --git a/src/sudachi/configuration/configure_debug_controller.h b/src/sudachi/configuration/configure_debug_controller.h new file mode 100644 index 0000000..dc85f6d --- /dev/null +++ b/src/sudachi/configuration/configure_debug_controller.h @@ -0,0 +1,45 @@ +// SPDX-FileCopyrightText: Copyright 2020 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include + +class QPushButton; + +class ConfigureInputPlayer; + +class InputProfiles; + +namespace Core::HID { +class HIDCore; +} + +namespace InputCommon { +class InputSubsystem; +} + +namespace Ui { +class ConfigureDebugController; +} + +class ConfigureDebugController : public QDialog { + Q_OBJECT + +public: + explicit ConfigureDebugController(QWidget* parent, InputCommon::InputSubsystem* input_subsystem, + InputProfiles* profiles, Core::HID::HIDCore& hid_core, + bool is_powered_on); + ~ConfigureDebugController() override; + + void ApplyConfiguration(); + +private: + void changeEvent(QEvent* event) override; + void RetranslateUI(); + + std::unique_ptr ui; + + ConfigureInputPlayer* debug_controller; +}; diff --git a/src/sudachi/configuration/configure_debug_controller.ui b/src/sudachi/configuration/configure_debug_controller.ui new file mode 100644 index 0000000..7b7e658 --- /dev/null +++ b/src/sudachi/configuration/configure_debug_controller.ui @@ -0,0 +1,77 @@ + + + ConfigureDebugController + + + + 0 + 0 + 780 + 500 + + + + Configure Debug Controller + + + + 2 + + + 9 + + + 9 + + + 9 + + + 9 + + + + + + + + + + Clear + + + + + + + Defaults + + + + + + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + + + + + + + + + + buttonBox + accepted() + ConfigureDebugController + accept() + + + buttonBox + rejected() + ConfigureDebugController + reject() + + + diff --git a/src/sudachi/configuration/configure_debug_tab.cpp b/src/sudachi/configuration/configure_debug_tab.cpp new file mode 100644 index 0000000..962e673 --- /dev/null +++ b/src/sudachi/configuration/configure_debug_tab.cpp @@ -0,0 +1,45 @@ +// SPDX-FileCopyrightText: Copyright 2021 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include "ui_configure_debug_tab.h" +#include "sudachi/configuration/configure_cpu_debug.h" +#include "sudachi/configuration/configure_debug.h" +#include "sudachi/configuration/configure_debug_tab.h" + +ConfigureDebugTab::ConfigureDebugTab(const Core::System& system_, QWidget* parent) + : QWidget(parent), ui{std::make_unique()}, + debug_tab{std::make_unique(system_, this)}, + cpu_debug_tab{std::make_unique(system_, this)} { + ui->setupUi(this); + + ui->tabWidget->addTab(debug_tab.get(), tr("Debug")); + ui->tabWidget->addTab(cpu_debug_tab.get(), tr("CPU")); + + SetConfiguration(); +} + +ConfigureDebugTab::~ConfigureDebugTab() = default; + +void ConfigureDebugTab::ApplyConfiguration() { + debug_tab->ApplyConfiguration(); + cpu_debug_tab->ApplyConfiguration(); +} + +void ConfigureDebugTab::SetCurrentIndex(int index) { + ui->tabWidget->setCurrentIndex(index); +} + +void ConfigureDebugTab::changeEvent(QEvent* event) { + if (event->type() == QEvent::LanguageChange) { + RetranslateUI(); + } + + QWidget::changeEvent(event); +} + +void ConfigureDebugTab::RetranslateUI() { + ui->retranslateUi(this); +} + +void ConfigureDebugTab::SetConfiguration() {} diff --git a/src/sudachi/configuration/configure_debug_tab.h b/src/sudachi/configuration/configure_debug_tab.h new file mode 100644 index 0000000..dc01eb8 --- /dev/null +++ b/src/sudachi/configuration/configure_debug_tab.h @@ -0,0 +1,41 @@ +// SPDX-FileCopyrightText: Copyright 2021 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include + +class ConfigureDebug; +class ConfigureCpuDebug; + +namespace Core { +class System; +} + +namespace Ui { +class ConfigureDebugTab; +} + +class ConfigureDebugTab : public QWidget { + Q_OBJECT + +public: + explicit ConfigureDebugTab(const Core::System& system_, QWidget* parent = nullptr); + ~ConfigureDebugTab() override; + + void ApplyConfiguration(); + + void SetCurrentIndex(int index); + +private: + void changeEvent(QEvent* event) override; + void RetranslateUI(); + + void SetConfiguration(); + + std::unique_ptr ui; + + std::unique_ptr debug_tab; + std::unique_ptr cpu_debug_tab; +}; diff --git a/src/sudachi/configuration/configure_debug_tab.ui b/src/sudachi/configuration/configure_debug_tab.ui new file mode 100644 index 0000000..15ec747 --- /dev/null +++ b/src/sudachi/configuration/configure_debug_tab.ui @@ -0,0 +1,31 @@ + + + ConfigureDebugTab + + + + 0 + 0 + 320 + 240 + + + + Form + + + Debug + + + + + + -1 + + + + + + + + diff --git a/src/sudachi/configuration/configure_dialog.cpp b/src/sudachi/configuration/configure_dialog.cpp new file mode 100644 index 0000000..a8bf0ae --- /dev/null +++ b/src/sudachi/configuration/configure_dialog.cpp @@ -0,0 +1,213 @@ +// SPDX-FileCopyrightText: 2016 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include "common/logging/log.h" +#include "common/settings.h" +#include "common/settings_enums.h" +#include "core/core.h" +#include "ui_configure.h" +#include "vk_device_info.h" +#include "sudachi/configuration/configure_applets.h" +#include "sudachi/configuration/configure_audio.h" +#include "sudachi/configuration/configure_cpu.h" +#include "sudachi/configuration/configure_debug_tab.h" +#include "sudachi/configuration/configure_dialog.h" +#include "sudachi/configuration/configure_filesystem.h" +#include "sudachi/configuration/configure_general.h" +#include "sudachi/configuration/configure_graphics.h" +#include "sudachi/configuration/configure_graphics_advanced.h" +#include "sudachi/configuration/configure_hotkeys.h" +#include "sudachi/configuration/configure_input.h" +#include "sudachi/configuration/configure_input_player.h" +#include "sudachi/configuration/configure_network.h" +#include "sudachi/configuration/configure_profile_manager.h" +#include "sudachi/configuration/configure_system.h" +#include "sudachi/configuration/configure_ui.h" +#include "sudachi/configuration/configure_web.h" +#include "sudachi/hotkeys.h" +#include "sudachi/uisettings.h" + +ConfigureDialog::ConfigureDialog(QWidget* parent, HotkeyRegistry& registry_, + InputCommon::InputSubsystem* input_subsystem, + std::vector& vk_device_records, + Core::System& system_, bool enable_web_config) + : QDialog(parent), ui{std::make_unique()}, + registry(registry_), system{system_}, builder{std::make_unique( + this, !system_.IsPoweredOn())}, + applets_tab{std::make_unique(system_, nullptr, *builder, this)}, + audio_tab{std::make_unique(system_, nullptr, *builder, this)}, + cpu_tab{std::make_unique(system_, nullptr, *builder, this)}, + debug_tab_tab{std::make_unique(system_, this)}, + filesystem_tab{std::make_unique(this)}, + general_tab{std::make_unique(system_, nullptr, *builder, this)}, + graphics_advanced_tab{ + std::make_unique(system_, nullptr, *builder, this)}, + ui_tab{std::make_unique(system_, this)}, + graphics_tab{std::make_unique( + system_, vk_device_records, [&]() { graphics_advanced_tab->ExposeComputeOption(); }, + [this](Settings::AspectRatio ratio, Settings::ResolutionSetup setup) { + ui_tab->UpdateScreenshotInfo(ratio, setup); + }, + nullptr, *builder, this)}, + hotkeys_tab{std::make_unique(system_.HIDCore(), this)}, + input_tab{std::make_unique(system_, this)}, + network_tab{std::make_unique(system_, this)}, + profile_tab{std::make_unique(system_, this)}, + system_tab{std::make_unique(system_, nullptr, *builder, this)}, + web_tab{std::make_unique(this)} { + Settings::SetConfiguringGlobal(true); + + ui->setupUi(this); + + ui->tabWidget->addTab(applets_tab.get(), tr("Applets")); + ui->tabWidget->addTab(audio_tab.get(), tr("Audio")); + ui->tabWidget->addTab(cpu_tab.get(), tr("CPU")); + ui->tabWidget->addTab(debug_tab_tab.get(), tr("Debug")); + ui->tabWidget->addTab(filesystem_tab.get(), tr("Filesystem")); + ui->tabWidget->addTab(general_tab.get(), tr("General")); + ui->tabWidget->addTab(graphics_tab.get(), tr("Graphics")); + ui->tabWidget->addTab(graphics_advanced_tab.get(), tr("GraphicsAdvanced")); + ui->tabWidget->addTab(hotkeys_tab.get(), tr("Hotkeys")); + ui->tabWidget->addTab(input_tab.get(), tr("Controls")); + ui->tabWidget->addTab(profile_tab.get(), tr("Profiles")); + ui->tabWidget->addTab(network_tab.get(), tr("Network")); + ui->tabWidget->addTab(system_tab.get(), tr("System")); + ui->tabWidget->addTab(ui_tab.get(), tr("Game List")); + ui->tabWidget->addTab(web_tab.get(), tr("Web")); + + web_tab->SetWebServiceConfigEnabled(enable_web_config); + hotkeys_tab->Populate(registry); + + input_tab->Initialize(input_subsystem); + + general_tab->SetResetCallback([&] { this->close(); }); + + SetConfiguration(); + PopulateSelectionList(); + + connect(ui->tabWidget, &QTabWidget::currentChanged, this, [this](int index) { + if (index != -1) { + debug_tab_tab->SetCurrentIndex(0); + } + }); + connect(ui_tab.get(), &ConfigureUi::LanguageChanged, this, &ConfigureDialog::OnLanguageChanged); + connect(ui->selectorList, &QListWidget::itemSelectionChanged, this, + &ConfigureDialog::UpdateVisibleTabs); + + if (system.IsPoweredOn()) { + QPushButton* apply_button = ui->buttonBox->addButton(QDialogButtonBox::Apply); + connect(apply_button, &QAbstractButton::clicked, this, + &ConfigureDialog::HandleApplyButtonClicked); + } + + adjustSize(); + ui->selectorList->setCurrentRow(0); + + // Selects the leftmost button on the bottom bar (Cancel as of writing) + ui->buttonBox->setFocus(); +} + +ConfigureDialog::~ConfigureDialog() = default; + +void ConfigureDialog::SetConfiguration() {} + +void ConfigureDialog::ApplyConfiguration() { + general_tab->ApplyConfiguration(); + ui_tab->ApplyConfiguration(); + system_tab->ApplyConfiguration(); + profile_tab->ApplyConfiguration(); + filesystem_tab->ApplyConfiguration(); + input_tab->ApplyConfiguration(); + hotkeys_tab->ApplyConfiguration(registry); + cpu_tab->ApplyConfiguration(); + graphics_tab->ApplyConfiguration(); + graphics_advanced_tab->ApplyConfiguration(); + audio_tab->ApplyConfiguration(); + debug_tab_tab->ApplyConfiguration(); + web_tab->ApplyConfiguration(); + network_tab->ApplyConfiguration(); + applets_tab->ApplyConfiguration(); + system.ApplySettings(); + Settings::LogSettings(); +} + +void ConfigureDialog::changeEvent(QEvent* event) { + if (event->type() == QEvent::LanguageChange) { + RetranslateUI(); + } + + QDialog::changeEvent(event); +} + +void ConfigureDialog::RetranslateUI() { + const int old_row = ui->selectorList->currentRow(); + const int old_index = ui->tabWidget->currentIndex(); + + ui->retranslateUi(this); + + PopulateSelectionList(); + ui->selectorList->setCurrentRow(old_row); + + UpdateVisibleTabs(); + ui->tabWidget->setCurrentIndex(old_index); +} + +void ConfigureDialog::HandleApplyButtonClicked() { + UISettings::values.configuration_applied = true; + ApplyConfiguration(); +} + +Q_DECLARE_METATYPE(QList); + +void ConfigureDialog::PopulateSelectionList() { + const std::array>, 6> items{ + {{tr("General"), + {general_tab.get(), hotkeys_tab.get(), ui_tab.get(), web_tab.get(), debug_tab_tab.get()}}, + {tr("System"), + {system_tab.get(), profile_tab.get(), network_tab.get(), filesystem_tab.get(), + applets_tab.get()}}, + {tr("CPU"), {cpu_tab.get()}}, + {tr("Graphics"), {graphics_tab.get(), graphics_advanced_tab.get()}}, + {tr("Audio"), {audio_tab.get()}}, + {tr("Controls"), input_tab->GetSubTabs()}}, + }; + + [[maybe_unused]] const QSignalBlocker blocker(ui->selectorList); + + ui->selectorList->clear(); + for (const auto& entry : items) { + auto* const item = new QListWidgetItem(entry.first); + item->setData(Qt::UserRole, QVariant::fromValue(entry.second)); + + ui->selectorList->addItem(item); + } +} + +void ConfigureDialog::OnLanguageChanged(const QString& locale) { + emit LanguageChanged(locale); + // Reloading the game list is needed to force retranslation. + UISettings::values.is_game_list_reload_pending = true; + // first apply the configuration, and then restore the display + ApplyConfiguration(); + RetranslateUI(); + SetConfiguration(); +} + +void ConfigureDialog::UpdateVisibleTabs() { + const auto items = ui->selectorList->selectedItems(); + if (items.isEmpty()) { + return; + } + + [[maybe_unused]] const QSignalBlocker blocker(ui->tabWidget); + + ui->tabWidget->clear(); + + const auto tabs = qvariant_cast>(items[0]->data(Qt::UserRole)); + + for (auto* const tab : tabs) { + LOG_DEBUG(Frontend, "{}", tab->accessibleName().toStdString()); + ui->tabWidget->addTab(tab, tab->accessibleName()); + } +} diff --git a/src/sudachi/configuration/configure_dialog.h b/src/sudachi/configuration/configure_dialog.h new file mode 100644 index 0000000..0ccd831 --- /dev/null +++ b/src/sudachi/configuration/configure_dialog.h @@ -0,0 +1,94 @@ +// SPDX-FileCopyrightText: 2016 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include +#include +#include "configuration/shared_widget.h" +#include "sudachi/configuration/configuration_shared.h" +#include "sudachi/configuration/shared_translation.h" +#include "sudachi/vk_device_info.h" + +namespace Core { +class System; +} + +class ConfigureApplets; +class ConfigureAudio; +class ConfigureCpu; +class ConfigureDebugTab; +class ConfigureFilesystem; +class ConfigureGeneral; +class ConfigureGraphics; +class ConfigureGraphicsAdvanced; +class ConfigureHotkeys; +class ConfigureInput; +class ConfigureProfileManager; +class ConfigureSystem; +class ConfigureNetwork; +class ConfigureUi; +class ConfigureWeb; + +class HotkeyRegistry; + +namespace InputCommon { +class InputSubsystem; +} + +namespace Ui { +class ConfigureDialog; +} + +class ConfigureDialog : public QDialog { + Q_OBJECT + +public: + explicit ConfigureDialog(QWidget* parent, HotkeyRegistry& registry_, + InputCommon::InputSubsystem* input_subsystem, + std::vector& vk_device_records, + Core::System& system_, bool enable_web_config = true); + ~ConfigureDialog() override; + + void ApplyConfiguration(); + +private slots: + void OnLanguageChanged(const QString& locale); + +signals: + void LanguageChanged(const QString& locale); + +private: + void changeEvent(QEvent* event) override; + void RetranslateUI(); + + void HandleApplyButtonClicked(); + + void SetConfiguration(); + void UpdateVisibleTabs(); + void PopulateSelectionList(); + + std::unique_ptr ui; + HotkeyRegistry& registry; + + Core::System& system; + std::unique_ptr builder; + std::vector tab_group; + + std::unique_ptr applets_tab; + std::unique_ptr audio_tab; + std::unique_ptr cpu_tab; + std::unique_ptr debug_tab_tab; + std::unique_ptr filesystem_tab; + std::unique_ptr general_tab; + std::unique_ptr graphics_advanced_tab; + std::unique_ptr ui_tab; + std::unique_ptr graphics_tab; + std::unique_ptr hotkeys_tab; + std::unique_ptr input_tab; + std::unique_ptr network_tab; + std::unique_ptr profile_tab; + std::unique_ptr system_tab; + std::unique_ptr web_tab; +}; diff --git a/src/sudachi/configuration/configure_filesystem.cpp b/src/sudachi/configuration/configure_filesystem.cpp new file mode 100644 index 0000000..f93e4dc --- /dev/null +++ b/src/sudachi/configuration/configure_filesystem.cpp @@ -0,0 +1,155 @@ +// SPDX-FileCopyrightText: Copyright 2019 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include +#include "common/fs/fs.h" +#include "common/fs/path_util.h" +#include "common/settings.h" +#include "ui_configure_filesystem.h" +#include "sudachi/configuration/configure_filesystem.h" +#include "sudachi/uisettings.h" + +ConfigureFilesystem::ConfigureFilesystem(QWidget* parent) + : QWidget(parent), ui(std::make_unique()) { + ui->setupUi(this); + SetConfiguration(); + + connect(ui->nand_directory_button, &QToolButton::pressed, this, + [this] { SetDirectory(DirectoryTarget::NAND, ui->nand_directory_edit); }); + connect(ui->sdmc_directory_button, &QToolButton::pressed, this, + [this] { SetDirectory(DirectoryTarget::SD, ui->sdmc_directory_edit); }); + connect(ui->gamecard_path_button, &QToolButton::pressed, this, + [this] { SetDirectory(DirectoryTarget::Gamecard, ui->gamecard_path_edit); }); + connect(ui->dump_path_button, &QToolButton::pressed, this, + [this] { SetDirectory(DirectoryTarget::Dump, ui->dump_path_edit); }); + connect(ui->load_path_button, &QToolButton::pressed, this, + [this] { SetDirectory(DirectoryTarget::Load, ui->load_path_edit); }); + + connect(ui->reset_game_list_cache, &QPushButton::pressed, this, + &ConfigureFilesystem::ResetMetadata); + + connect(ui->gamecard_inserted, &QCheckBox::stateChanged, this, + &ConfigureFilesystem::UpdateEnabledControls); + connect(ui->gamecard_current_game, &QCheckBox::stateChanged, this, + &ConfigureFilesystem::UpdateEnabledControls); +} + +ConfigureFilesystem::~ConfigureFilesystem() = default; + +void ConfigureFilesystem::changeEvent(QEvent* event) { + if (event->type() == QEvent::LanguageChange) { + RetranslateUI(); + } + + QWidget::changeEvent(event); +} + +void ConfigureFilesystem::SetConfiguration() { + ui->nand_directory_edit->setText( + QString::fromStdString(Common::FS::GetSudachiPathString(Common::FS::SudachiPath::NANDDir))); + ui->sdmc_directory_edit->setText( + QString::fromStdString(Common::FS::GetSudachiPathString(Common::FS::SudachiPath::SDMCDir))); + ui->gamecard_path_edit->setText( + QString::fromStdString(Settings::values.gamecard_path.GetValue())); + ui->dump_path_edit->setText( + QString::fromStdString(Common::FS::GetSudachiPathString(Common::FS::SudachiPath::DumpDir))); + ui->load_path_edit->setText( + QString::fromStdString(Common::FS::GetSudachiPathString(Common::FS::SudachiPath::LoadDir))); + + ui->gamecard_inserted->setChecked(Settings::values.gamecard_inserted.GetValue()); + ui->gamecard_current_game->setChecked(Settings::values.gamecard_current_game.GetValue()); + ui->dump_exefs->setChecked(Settings::values.dump_exefs.GetValue()); + ui->dump_nso->setChecked(Settings::values.dump_nso.GetValue()); + + ui->cache_game_list->setChecked(UISettings::values.cache_game_list.GetValue()); + + UpdateEnabledControls(); +} + +void ConfigureFilesystem::ApplyConfiguration() { + Common::FS::SetSudachiPath(Common::FS::SudachiPath::NANDDir, + ui->nand_directory_edit->text().toStdString()); + Common::FS::SetSudachiPath(Common::FS::SudachiPath::SDMCDir, + ui->sdmc_directory_edit->text().toStdString()); + Common::FS::SetSudachiPath(Common::FS::SudachiPath::DumpDir, + ui->dump_path_edit->text().toStdString()); + Common::FS::SetSudachiPath(Common::FS::SudachiPath::LoadDir, + ui->load_path_edit->text().toStdString()); + + Settings::values.gamecard_inserted = ui->gamecard_inserted->isChecked(); + Settings::values.gamecard_current_game = ui->gamecard_current_game->isChecked(); + Settings::values.dump_exefs = ui->dump_exefs->isChecked(); + Settings::values.dump_nso = ui->dump_nso->isChecked(); + + UISettings::values.cache_game_list = ui->cache_game_list->isChecked(); +} + +void ConfigureFilesystem::SetDirectory(DirectoryTarget target, QLineEdit* edit) { + QString caption; + + switch (target) { + case DirectoryTarget::NAND: + caption = tr("Select Emulated NAND Directory..."); + break; + case DirectoryTarget::SD: + caption = tr("Select Emulated SD Directory..."); + break; + case DirectoryTarget::Gamecard: + caption = tr("Select Gamecard Path..."); + break; + case DirectoryTarget::Dump: + caption = tr("Select Dump Directory..."); + break; + case DirectoryTarget::Load: + caption = tr("Select Mod Load Directory..."); + break; + } + + QString str; + if (target == DirectoryTarget::Gamecard) { + str = QFileDialog::getOpenFileName(this, caption, QFileInfo(edit->text()).dir().path(), + QStringLiteral("NX Gamecard;*.xci")); + } else { + str = QFileDialog::getExistingDirectory(this, caption, edit->text()); + } + + if (str.isNull() || str.isEmpty()) { + return; + } + + if (str.back() != QChar::fromLatin1('/')) { + str.append(QChar::fromLatin1('/')); + } + + edit->setText(str); +} + +void ConfigureFilesystem::ResetMetadata() { + if (!Common::FS::Exists(Common::FS::GetSudachiPath(Common::FS::SudachiPath::CacheDir) / + "game_list/")) { + QMessageBox::information(this, tr("Reset Metadata Cache"), + tr("The metadata cache is already empty.")); + } else if (Common::FS::RemoveDirRecursively( + Common::FS::GetSudachiPath(Common::FS::SudachiPath::CacheDir) / "game_list")) { + QMessageBox::information(this, tr("Reset Metadata Cache"), + tr("The operation completed successfully.")); + UISettings::values.is_game_list_reload_pending.exchange(true); + } else { + QMessageBox::warning( + this, tr("Reset Metadata Cache"), + tr("The metadata cache couldn't be deleted. It might be in use or non-existent.")); + } +} + +void ConfigureFilesystem::UpdateEnabledControls() { + ui->gamecard_current_game->setEnabled(ui->gamecard_inserted->isChecked()); + ui->gamecard_path_edit->setEnabled(ui->gamecard_inserted->isChecked() && + !ui->gamecard_current_game->isChecked()); + ui->gamecard_path_button->setEnabled(ui->gamecard_inserted->isChecked() && + !ui->gamecard_current_game->isChecked()); +} + +void ConfigureFilesystem::RetranslateUI() { + ui->retranslateUi(this); +} diff --git a/src/sudachi/configuration/configure_filesystem.h b/src/sudachi/configuration/configure_filesystem.h new file mode 100644 index 0000000..8d1f4cf --- /dev/null +++ b/src/sudachi/configuration/configure_filesystem.h @@ -0,0 +1,43 @@ +// SPDX-FileCopyrightText: Copyright 2019 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include + +class QLineEdit; + +namespace Ui { +class ConfigureFilesystem; +} + +class ConfigureFilesystem : public QWidget { + Q_OBJECT + +public: + explicit ConfigureFilesystem(QWidget* parent = nullptr); + ~ConfigureFilesystem() override; + + void ApplyConfiguration(); + +private: + void changeEvent(QEvent* event) override; + + void RetranslateUI(); + void SetConfiguration(); + + enum class DirectoryTarget { + NAND, + SD, + Gamecard, + Dump, + Load, + }; + + void SetDirectory(DirectoryTarget target, QLineEdit* edit); + void ResetMetadata(); + void UpdateEnabledControls(); + + std::unique_ptr ui; +}; diff --git a/src/sudachi/configuration/configure_filesystem.ui b/src/sudachi/configuration/configure_filesystem.ui new file mode 100644 index 0000000..2f6030b --- /dev/null +++ b/src/sudachi/configuration/configure_filesystem.ui @@ -0,0 +1,244 @@ + + + ConfigureFilesystem + + + + 0 + 0 + 453 + 561 + + + + Form + + + Filesystem + + + + + + + + Storage Directories + + + + + + NAND + + + + + + + ... + + + + + + + + + + + + + SD Card + + + + + + + ... + + + + + + + Qt::Horizontal + + + QSizePolicy::Maximum + + + + 60 + 20 + + + + + + + + + + + Gamecard + + + + + + Path + + + + + + + + + + Inserted + + + + + + + Current Game + + + + + + + ... + + + + + + + + + + Patch Manager + + + + + + + + + + + + ... + + + + + + + ... + + + + + + + + + Dump Decompressed NSOs + + + + + + + Dump ExeFS + + + + + + + + + Mod Load Root + + + + + + + Dump Root + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 40 + 20 + + + + + + + + + + + Caching + + + + + + + + Cache Game List Metadata + + + + + + + Reset Metadata Cache + + + + + + + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + diff --git a/src/sudachi/configuration/configure_general.cpp b/src/sudachi/configuration/configure_general.cpp new file mode 100644 index 0000000..a7bc3d7 --- /dev/null +++ b/src/sudachi/configuration/configure_general.cpp @@ -0,0 +1,128 @@ +// SPDX-FileCopyrightText: 2016 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include +#include +#include +#include "common/settings.h" +#include "core/core.h" +#include "ui_configure_general.h" +#include "sudachi/configuration/configuration_shared.h" +#include "sudachi/configuration/configure_general.h" +#include "sudachi/configuration/shared_widget.h" +#include "sudachi/uisettings.h" + +ConfigureGeneral::ConfigureGeneral(const Core::System& system_, + std::shared_ptr> group_, + const ConfigurationShared::Builder& builder, QWidget* parent) + : Tab(group_, parent), ui{std::make_unique()}, system{system_} { + ui->setupUi(this); + + Setup(builder); + + SetConfiguration(); + + connect(ui->button_reset_defaults, &QPushButton::clicked, this, + &ConfigureGeneral::ResetDefaults); + + if (!Settings::IsConfiguringGlobal()) { + ui->button_reset_defaults->setVisible(false); + } +} + +ConfigureGeneral::~ConfigureGeneral() = default; + +void ConfigureGeneral::SetConfiguration() {} + +void ConfigureGeneral::Setup(const ConfigurationShared::Builder& builder) { + QLayout& general_layout = *ui->general_widget->layout(); + QLayout& linux_layout = *ui->linux_widget->layout(); + + std::map general_hold{}; + std::map linux_hold{}; + + std::vector settings; + + auto push = [&settings](auto& list) { + for (auto setting : list) { + settings.push_back(setting); + } + }; + + push(UISettings::values.linkage.by_category[Settings::Category::UiGeneral]); + push(Settings::values.linkage.by_category[Settings::Category::Linux]); + + // Only show Linux group on Unix +#ifndef __unix__ + ui->LinuxGroupBox->setVisible(false); +#endif + + for (const auto setting : settings) { + auto* widget = builder.BuildWidget(setting, apply_funcs); + + if (widget == nullptr) { + continue; + } + if (!widget->Valid()) { + widget->deleteLater(); + continue; + } + + switch (setting->GetCategory()) { + case Settings::Category::UiGeneral: + general_hold.emplace(setting->Id(), widget); + break; + case Settings::Category::Linux: + linux_hold.emplace(setting->Id(), widget); + break; + default: + widget->deleteLater(); + } + } + + for (const auto& [id, widget] : general_hold) { + general_layout.addWidget(widget); + } + for (const auto& [id, widget] : linux_hold) { + linux_layout.addWidget(widget); + } +} + +// Called to set the callback when resetting settings to defaults +void ConfigureGeneral::SetResetCallback(std::function callback) { + reset_callback = std::move(callback); +} + +void ConfigureGeneral::ResetDefaults() { + QMessageBox::StandardButton answer = QMessageBox::question( + this, tr("sudachi"), + tr("This reset all settings and remove all per-game configurations. This will not delete " + "game directories, profiles, or input profiles. Proceed?"), + QMessageBox::Yes | QMessageBox::No, QMessageBox::No); + if (answer == QMessageBox::No) { + return; + } + UISettings::values.reset_to_defaults = true; + UISettings::values.is_game_list_reload_pending.exchange(true); + reset_callback(); +} + +void ConfigureGeneral::ApplyConfiguration() { + bool powered_on = system.IsPoweredOn(); + for (const auto& func : apply_funcs) { + func(powered_on); + } +} + +void ConfigureGeneral::changeEvent(QEvent* event) { + if (event->type() == QEvent::LanguageChange) { + RetranslateUI(); + } + + QWidget::changeEvent(event); +} + +void ConfigureGeneral::RetranslateUI() { + ui->retranslateUi(this); +} diff --git a/src/sudachi/configuration/configure_general.h b/src/sudachi/configuration/configure_general.h new file mode 100644 index 0000000..7e04cf9 --- /dev/null +++ b/src/sudachi/configuration/configure_general.h @@ -0,0 +1,55 @@ +// SPDX-FileCopyrightText: 2016 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include +#include +#include +#include "sudachi/configuration/configuration_shared.h" + +namespace Core { +class System; +} + +class ConfigureDialog; +class HotkeyRegistry; + +namespace Ui { +class ConfigureGeneral; +} + +namespace ConfigurationShared { +class Builder; +} + +class ConfigureGeneral : public ConfigurationShared::Tab { + Q_OBJECT + +public: + explicit ConfigureGeneral(const Core::System& system_, + std::shared_ptr> group, + const ConfigurationShared::Builder& builder, + QWidget* parent = nullptr); + ~ConfigureGeneral() override; + + void SetResetCallback(std::function callback); + void ResetDefaults(); + void ApplyConfiguration() override; + void SetConfiguration() override; + +private: + void Setup(const ConfigurationShared::Builder& builder); + + void changeEvent(QEvent* event) override; + void RetranslateUI(); + + std::function reset_callback; + + std::unique_ptr ui; + + std::vector> apply_funcs{}; + + const Core::System& system; +}; diff --git a/src/sudachi/configuration/configure_general.ui b/src/sudachi/configuration/configure_general.ui new file mode 100644 index 0000000..ef20891 --- /dev/null +++ b/src/sudachi/configuration/configure_general.ui @@ -0,0 +1,134 @@ + + + ConfigureGeneral + + + + 0 + 0 + 744 + 568 + + + + Form + + + General + + + + + + + + General + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + + + + + + Linux + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + 6 + + + 5 + + + 5 + + + 5 + + + 5 + + + + + Reset All Settings + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + + + diff --git a/src/sudachi/configuration/configure_graphics.cpp b/src/sudachi/configuration/configure_graphics.cpp new file mode 100644 index 0000000..bb3eed3 --- /dev/null +++ b/src/sudachi/configuration/configure_graphics.cpp @@ -0,0 +1,552 @@ +// SPDX-FileCopyrightText: 2016 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "common/common_types.h" +#include "common/dynamic_library.h" +#include "common/logging/log.h" +#include "common/settings.h" +#include "common/settings_enums.h" +#include "core/core.h" +#include "ui_configure_graphics.h" +#include "sudachi/configuration/configuration_shared.h" +#include "sudachi/configuration/configure_graphics.h" +#include "sudachi/configuration/shared_widget.h" +#include "sudachi/qt_common.h" +#include "sudachi/uisettings.h" +#include "sudachi/vk_device_info.h" + +static const std::vector default_present_modes{VK_PRESENT_MODE_IMMEDIATE_KHR, + VK_PRESENT_MODE_FIFO_KHR}; + +// Converts a setting to a present mode (or vice versa) +static constexpr VkPresentModeKHR VSyncSettingToMode(Settings::VSyncMode mode) { + switch (mode) { + case Settings::VSyncMode::Immediate: + return VK_PRESENT_MODE_IMMEDIATE_KHR; + case Settings::VSyncMode::Mailbox: + return VK_PRESENT_MODE_MAILBOX_KHR; + case Settings::VSyncMode::Fifo: + return VK_PRESENT_MODE_FIFO_KHR; + case Settings::VSyncMode::FifoRelaxed: + return VK_PRESENT_MODE_FIFO_RELAXED_KHR; + default: + return VK_PRESENT_MODE_FIFO_KHR; + } +} + +static constexpr Settings::VSyncMode PresentModeToSetting(VkPresentModeKHR mode) { + switch (mode) { + case VK_PRESENT_MODE_IMMEDIATE_KHR: + return Settings::VSyncMode::Immediate; + case VK_PRESENT_MODE_MAILBOX_KHR: + return Settings::VSyncMode::Mailbox; + case VK_PRESENT_MODE_FIFO_KHR: + return Settings::VSyncMode::Fifo; + case VK_PRESENT_MODE_FIFO_RELAXED_KHR: + return Settings::VSyncMode::FifoRelaxed; + default: + return Settings::VSyncMode::Fifo; + } +} + +ConfigureGraphics::ConfigureGraphics( + const Core::System& system_, std::vector& records_, + const std::function& expose_compute_option_, + const std::function& + update_aspect_ratio_, + std::shared_ptr> group_, + const ConfigurationShared::Builder& builder, QWidget* parent) + : ConfigurationShared::Tab(group_, parent), ui{std::make_unique()}, + records{records_}, expose_compute_option{expose_compute_option_}, + update_aspect_ratio{update_aspect_ratio_}, system{system_}, + combobox_translations{builder.ComboboxTranslations()}, + shader_mapping{ + combobox_translations.at(Settings::EnumMetadata::Index())} { + vulkan_device = Settings::values.vulkan_device.GetValue(); + RetrieveVulkanDevices(); + + ui->setupUi(this); + + Setup(builder); + + for (const auto& device : vulkan_devices) { + vulkan_device_combobox->addItem(device); + } + + UpdateBackgroundColorButton(QColor::fromRgb(Settings::values.bg_red.GetValue(), + Settings::values.bg_green.GetValue(), + Settings::values.bg_blue.GetValue())); + UpdateAPILayout(); + PopulateVSyncModeSelection(false); //< must happen after UpdateAPILayout + + // VSync setting needs to be determined after populating the VSync combobox + const auto vsync_mode_setting = Settings::values.vsync_mode.GetValue(); + const auto vsync_mode = VSyncSettingToMode(vsync_mode_setting); + int index{}; + for (const auto mode : vsync_mode_combobox_enum_map) { + if (mode == vsync_mode) { + break; + } + index++; + } + if (static_cast(index) < vsync_mode_combobox_enum_map.size()) { + vsync_mode_combobox->setCurrentIndex(index); + } + + connect(api_combobox, qOverload(&QComboBox::activated), this, [this] { + UpdateAPILayout(); + PopulateVSyncModeSelection(false); + }); + connect(vulkan_device_combobox, qOverload(&QComboBox::activated), this, + [this](int device) { + UpdateDeviceSelection(device); + PopulateVSyncModeSelection(false); + }); + connect(shader_backend_combobox, qOverload(&QComboBox::activated), this, + [this](int backend) { UpdateShaderBackendSelection(backend); }); + + connect(ui->bg_button, &QPushButton::clicked, this, [this] { + const QColor new_bg_color = QColorDialog::getColor(bg_color); + if (!new_bg_color.isValid()) { + return; + } + UpdateBackgroundColorButton(new_bg_color); + }); + + const auto& update_screenshot_info = [this, &builder]() { + const auto& combobox_enumerations = builder.ComboboxTranslations().at( + Settings::EnumMetadata::Index()); + const auto ratio_index = aspect_ratio_combobox->currentIndex(); + const auto ratio = + static_cast(combobox_enumerations[ratio_index].first); + + const auto& combobox_enumerations_resolution = builder.ComboboxTranslations().at( + Settings::EnumMetadata::Index()); + const auto res_index = resolution_combobox->currentIndex(); + const auto setup = static_cast( + combobox_enumerations_resolution[res_index].first); + + update_aspect_ratio(ratio, setup); + }; + + connect(aspect_ratio_combobox, QOverload::of(&QComboBox::currentIndexChanged), + update_screenshot_info); + connect(resolution_combobox, QOverload::of(&QComboBox::currentIndexChanged), + update_screenshot_info); + + api_combobox->setEnabled(!UISettings::values.has_broken_vulkan && api_combobox->isEnabled()); + ui->api_widget->setEnabled( + (!UISettings::values.has_broken_vulkan || Settings::IsConfiguringGlobal()) && + ui->api_widget->isEnabled()); + + if (Settings::IsConfiguringGlobal()) { + ui->bg_widget->setEnabled(Settings::values.bg_red.UsingGlobal()); + } +} + +void ConfigureGraphics::PopulateVSyncModeSelection(bool use_setting) { + const Settings::RendererBackend backend{GetCurrentGraphicsBackend()}; + if (backend == Settings::RendererBackend::Null) { + vsync_mode_combobox->setEnabled(false); + return; + } + vsync_mode_combobox->setEnabled(true); + + const int current_index = //< current selected vsync mode from combobox + vsync_mode_combobox->currentIndex(); + const auto current_mode = //< current selected vsync mode as a VkPresentModeKHR + current_index == -1 || use_setting + ? VSyncSettingToMode(Settings::values.vsync_mode.GetValue()) + : vsync_mode_combobox_enum_map[current_index]; + int index{}; + const int device{vulkan_device_combobox->currentIndex()}; //< current selected Vulkan device + + const auto& present_modes = //< relevant vector of present modes for the selected device or API + backend == Settings::RendererBackend::Vulkan && device > -1 ? device_present_modes[device] + : default_present_modes; + + vsync_mode_combobox->clear(); + vsync_mode_combobox_enum_map.clear(); + vsync_mode_combobox_enum_map.reserve(present_modes.size()); + for (const auto present_mode : present_modes) { + const auto mode_name = TranslateVSyncMode(present_mode, backend); + if (mode_name.isEmpty()) { + continue; + } + + vsync_mode_combobox->insertItem(index, mode_name); + vsync_mode_combobox_enum_map.push_back(present_mode); + if (present_mode == current_mode) { + vsync_mode_combobox->setCurrentIndex(index); + } + index++; + } + + if (!Settings::IsConfiguringGlobal()) { + vsync_restore_global_button->setVisible(!Settings::values.vsync_mode.UsingGlobal()); + + const Settings::VSyncMode global_vsync_mode = Settings::values.vsync_mode.GetValue(true); + vsync_restore_global_button->setEnabled( + (backend == Settings::RendererBackend::OpenGL && + (global_vsync_mode == Settings::VSyncMode::Immediate || + global_vsync_mode == Settings::VSyncMode::Fifo)) || + backend == Settings::RendererBackend::Vulkan); + } +} + +void ConfigureGraphics::UpdateVsyncSetting() const { + const Settings::RendererBackend backend{GetCurrentGraphicsBackend()}; + if (backend == Settings::RendererBackend::Null) { + return; + } + + const auto mode = vsync_mode_combobox_enum_map[vsync_mode_combobox->currentIndex()]; + const auto vsync_mode = PresentModeToSetting(mode); + Settings::values.vsync_mode.SetValue(vsync_mode); +} + +void ConfigureGraphics::UpdateDeviceSelection(int device) { + if (device == -1) { + return; + } + if (GetCurrentGraphicsBackend() == Settings::RendererBackend::Vulkan) { + vulkan_device = device; + } +} + +void ConfigureGraphics::UpdateShaderBackendSelection(int backend) { + if (backend == -1) { + return; + } + if (GetCurrentGraphicsBackend() == Settings::RendererBackend::OpenGL) { + shader_backend = static_cast(backend); + } +} + +ConfigureGraphics::~ConfigureGraphics() = default; + +void ConfigureGraphics::SetConfiguration() {} + +void ConfigureGraphics::Setup(const ConfigurationShared::Builder& builder) { + QLayout* api_layout = ui->api_widget->layout(); + QWidget* api_grid_widget = new QWidget(this); + QVBoxLayout* api_grid_layout = new QVBoxLayout(api_grid_widget); + api_grid_layout->setContentsMargins(0, 0, 0, 0); + api_layout->addWidget(api_grid_widget); + + QLayout& graphics_layout = *ui->graphics_widget->layout(); + + std::map hold_graphics; + std::vector hold_api; + + for (const auto setting : Settings::values.linkage.by_category[Settings::Category::Renderer]) { + ConfigurationShared::Widget* widget = [&]() { + if (setting->Id() == Settings::values.fsr_sharpening_slider.Id()) { + // FSR needs a reversed slider and a 0.5 multiplier + return builder.BuildWidget( + setting, apply_funcs, ConfigurationShared::RequestType::ReverseSlider, true, + 0.5f, nullptr, tr("%", "FSR sharpening percentage (e.g. 50%)")); + } else { + return builder.BuildWidget(setting, apply_funcs); + } + }(); + + if (widget == nullptr) { + continue; + } + if (!widget->Valid()) { + widget->deleteLater(); + continue; + } + + if (setting->Id() == Settings::values.renderer_backend.Id()) { + // Add the renderer combobox now so it's at the top + api_grid_layout->addWidget(widget); + api_combobox = widget->combobox; + api_restore_global_button = widget->restore_button; + + if (!Settings::IsConfiguringGlobal()) { + QObject::connect(api_restore_global_button, &QAbstractButton::clicked, + [this](bool) { UpdateAPILayout(); }); + + // Detach API's restore button and place it where we want + // Lets us put it on the side, and it will automatically scale if there's a + // second combobox (shader_backend, vulkan_device) + widget->layout()->removeWidget(api_restore_global_button); + api_layout->addWidget(api_restore_global_button); + } + } else if (setting->Id() == Settings::values.vulkan_device.Id()) { + // Keep track of vulkan_device's combobox so we can populate it + hold_api.push_back(widget); + vulkan_device_combobox = widget->combobox; + vulkan_device_widget = widget; + } else if (setting->Id() == Settings::values.shader_backend.Id()) { + // Keep track of shader_backend's combobox so we can populate it + hold_api.push_back(widget); + shader_backend_combobox = widget->combobox; + shader_backend_widget = widget; + } else if (setting->Id() == Settings::values.vsync_mode.Id()) { + // Keep track of vsync_mode's combobox so we can populate it + vsync_mode_combobox = widget->combobox; + + // Since vsync is populated at runtime, we have to manually set up the button for + // restoring the global setting. + if (!Settings::IsConfiguringGlobal()) { + QPushButton* restore_button = + ConfigurationShared::Widget::CreateRestoreGlobalButton( + Settings::values.vsync_mode.UsingGlobal(), widget); + restore_button->setEnabled(true); + widget->layout()->addWidget(restore_button); + + QObject::connect(restore_button, &QAbstractButton::clicked, + [restore_button, this](bool) { + Settings::values.vsync_mode.SetGlobal(true); + PopulateVSyncModeSelection(true); + + restore_button->setVisible(false); + }); + + std::function set_non_global = [restore_button, this]() { + Settings::values.vsync_mode.SetGlobal(false); + UpdateVsyncSetting(); + restore_button->setVisible(true); + }; + QObject::connect(widget->combobox, QOverload::of(&QComboBox::activated), + [set_non_global]() { set_non_global(); }); + vsync_restore_global_button = restore_button; + } + hold_graphics.emplace(setting->Id(), widget); + } else if (setting->Id() == Settings::values.aspect_ratio.Id()) { + // Keep track of the aspect ratio combobox to update other UI tabs that need it + aspect_ratio_combobox = widget->combobox; + hold_graphics.emplace(setting->Id(), widget); + } else if (setting->Id() == Settings::values.resolution_setup.Id()) { + // Keep track of the resolution combobox to update other UI tabs that need it + resolution_combobox = widget->combobox; + hold_graphics.emplace(setting->Id(), widget); + } else { + hold_graphics.emplace(setting->Id(), widget); + } + } + + for (const auto& [id, widget] : hold_graphics) { + graphics_layout.addWidget(widget); + } + + for (auto widget : hold_api) { + api_grid_layout->addWidget(widget); + } + + // Background color is too specific to build into the new system, so we manage it here + // (3 settings, all collected into a single widget with a QColor to manage on top) + if (Settings::IsConfiguringGlobal()) { + apply_funcs.push_back([this](bool powered_on) { + Settings::values.bg_red.SetValue(static_cast(bg_color.red())); + Settings::values.bg_green.SetValue(static_cast(bg_color.green())); + Settings::values.bg_blue.SetValue(static_cast(bg_color.blue())); + }); + } else { + QPushButton* bg_restore_button = ConfigurationShared::Widget::CreateRestoreGlobalButton( + Settings::values.bg_red.UsingGlobal(), ui->bg_widget); + ui->bg_widget->layout()->addWidget(bg_restore_button); + + QObject::connect(bg_restore_button, &QAbstractButton::clicked, + [bg_restore_button, this](bool) { + const int r = Settings::values.bg_red.GetValue(true); + const int g = Settings::values.bg_green.GetValue(true); + const int b = Settings::values.bg_blue.GetValue(true); + UpdateBackgroundColorButton(QColor::fromRgb(r, g, b)); + + bg_restore_button->setVisible(false); + bg_restore_button->setEnabled(false); + }); + + QObject::connect(ui->bg_button, &QAbstractButton::clicked, [bg_restore_button](bool) { + bg_restore_button->setVisible(true); + bg_restore_button->setEnabled(true); + }); + + apply_funcs.push_back([bg_restore_button, this](bool powered_on) { + const bool using_global = !bg_restore_button->isEnabled(); + Settings::values.bg_red.SetGlobal(using_global); + Settings::values.bg_green.SetGlobal(using_global); + Settings::values.bg_blue.SetGlobal(using_global); + if (!using_global) { + Settings::values.bg_red.SetValue(static_cast(bg_color.red())); + Settings::values.bg_green.SetValue(static_cast(bg_color.green())); + Settings::values.bg_blue.SetValue(static_cast(bg_color.blue())); + } + }); + } +} + +const QString ConfigureGraphics::TranslateVSyncMode(VkPresentModeKHR mode, + Settings::RendererBackend backend) const { + switch (mode) { + case VK_PRESENT_MODE_IMMEDIATE_KHR: + return backend == Settings::RendererBackend::OpenGL + ? tr("Off") + : QStringLiteral("Immediate (%1)").arg(tr("VSync Off")); + case VK_PRESENT_MODE_MAILBOX_KHR: + return QStringLiteral("Mailbox (%1)").arg(tr("Recommended")); + case VK_PRESENT_MODE_FIFO_KHR: + return backend == Settings::RendererBackend::OpenGL + ? tr("On") + : QStringLiteral("FIFO (%1)").arg(tr("VSync On")); + case VK_PRESENT_MODE_FIFO_RELAXED_KHR: + return QStringLiteral("FIFO Relaxed"); + default: + return {}; + break; + } +} + +int ConfigureGraphics::FindIndex(u32 enumeration, int value) const { + for (u32 i = 0; i < combobox_translations.at(enumeration).size(); i++) { + if (combobox_translations.at(enumeration)[i].first == static_cast(value)) { + return i; + } + } + return -1; +} + +void ConfigureGraphics::ApplyConfiguration() { + const bool powered_on = system.IsPoweredOn(); + for (const auto& func : apply_funcs) { + func(powered_on); + } + + UpdateVsyncSetting(); + + Settings::values.vulkan_device.SetGlobal(true); + Settings::values.shader_backend.SetGlobal(true); + if (Settings::IsConfiguringGlobal() || + (!Settings::IsConfiguringGlobal() && api_restore_global_button->isEnabled())) { + auto backend = static_cast( + combobox_translations + .at(Settings::EnumMetadata< + Settings::RendererBackend>::Index())[api_combobox->currentIndex()] + .first); + switch (backend) { + case Settings::RendererBackend::OpenGL: + Settings::values.shader_backend.SetGlobal(Settings::IsConfiguringGlobal()); + Settings::values.shader_backend.SetValue(static_cast( + shader_mapping[shader_backend_combobox->currentIndex()].first)); + break; + case Settings::RendererBackend::Vulkan: + Settings::values.vulkan_device.SetGlobal(Settings::IsConfiguringGlobal()); + Settings::values.vulkan_device.SetValue(vulkan_device_combobox->currentIndex()); + break; + case Settings::RendererBackend::Null: + break; + } + } +} + +void ConfigureGraphics::changeEvent(QEvent* event) { + if (event->type() == QEvent::LanguageChange) { + RetranslateUI(); + } + + QWidget::changeEvent(event); +} + +void ConfigureGraphics::RetranslateUI() { + ui->retranslateUi(this); +} + +void ConfigureGraphics::UpdateBackgroundColorButton(QColor color) { + bg_color = color; + + QPixmap pixmap(ui->bg_button->size()); + pixmap.fill(bg_color); + + const QIcon color_icon(pixmap); + ui->bg_button->setIcon(color_icon); +} + +void ConfigureGraphics::UpdateAPILayout() { + bool runtime_lock = !system.IsPoweredOn(); + bool need_global = !(Settings::IsConfiguringGlobal() || api_restore_global_button->isEnabled()); + vulkan_device = Settings::values.vulkan_device.GetValue(need_global); + shader_backend = Settings::values.shader_backend.GetValue(need_global); + vulkan_device_widget->setEnabled(!need_global && runtime_lock); + shader_backend_widget->setEnabled(!need_global && runtime_lock); + + const auto current_backend = GetCurrentGraphicsBackend(); + const bool is_opengl = current_backend == Settings::RendererBackend::OpenGL; + const bool is_vulkan = current_backend == Settings::RendererBackend::Vulkan; + + vulkan_device_widget->setVisible(is_vulkan); + shader_backend_widget->setVisible(is_opengl); + + if (is_opengl) { + shader_backend_combobox->setCurrentIndex( + FindIndex(Settings::EnumMetadata::Index(), + static_cast(shader_backend))); + } else if (is_vulkan && static_cast(vulkan_device) < vulkan_device_combobox->count()) { + vulkan_device_combobox->setCurrentIndex(vulkan_device); + } +} + +void ConfigureGraphics::RetrieveVulkanDevices() { + vulkan_devices.clear(); + vulkan_devices.reserve(records.size()); + device_present_modes.clear(); + device_present_modes.reserve(records.size()); + for (const auto& record : records) { + vulkan_devices.push_back(QString::fromStdString(record.name)); + device_present_modes.push_back(record.vsync_support); + + if (record.has_broken_compute) { + expose_compute_option(); + } + } +} + +Settings::RendererBackend ConfigureGraphics::GetCurrentGraphicsBackend() const { + const auto selected_backend = [&]() { + if (!Settings::IsConfiguringGlobal() && !api_restore_global_button->isEnabled()) { + return Settings::values.renderer_backend.GetValue(true); + } + return static_cast( + combobox_translations.at(Settings::EnumMetadata::Index()) + .at(api_combobox->currentIndex()) + .first); + }(); + + if (selected_backend == Settings::RendererBackend::Vulkan && + UISettings::values.has_broken_vulkan) { + return Settings::RendererBackend::OpenGL; + } + return selected_backend; +} diff --git a/src/sudachi/configuration/configure_graphics.h b/src/sudachi/configuration/configure_graphics.h new file mode 100644 index 0000000..ddb7d3a --- /dev/null +++ b/src/sudachi/configuration/configure_graphics.h @@ -0,0 +1,116 @@ +// SPDX-FileCopyrightText: 2016 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "common/common_types.h" +#include "common/settings_enums.h" +#include "configuration/shared_translation.h" +#include "vk_device_info.h" +#include "sudachi/configuration/configuration_shared.h" + +class QPushButton; +class QEvent; +class QObject; +class QComboBox; + +namespace Settings { +enum class NvdecEmulation : u32; +enum class RendererBackend : u32; +enum class ShaderBackend : u32; +} // namespace Settings + +namespace Core { +class System; +} + +namespace Ui { +class ConfigureGraphics; +} + +namespace ConfigurationShared { +class Builder; +} + +class ConfigureGraphics : public ConfigurationShared::Tab { + Q_OBJECT + +public: + explicit ConfigureGraphics( + const Core::System& system_, std::vector& records, + const std::function& expose_compute_option, + const std::function& + update_aspect_ratio, + std::shared_ptr> group, + const ConfigurationShared::Builder& builder, QWidget* parent = nullptr); + ~ConfigureGraphics() override; + + void ApplyConfiguration() override; + void SetConfiguration() override; + +private: + void changeEvent(QEvent* event) override; + void RetranslateUI(); + + void Setup(const ConfigurationShared::Builder& builder); + + void PopulateVSyncModeSelection(bool use_setting); + void UpdateVsyncSetting() const; + void UpdateBackgroundColorButton(QColor color); + void UpdateAPILayout(); + void UpdateDeviceSelection(int device); + void UpdateShaderBackendSelection(int backend); + + void RetrieveVulkanDevices(); + + /* Turns a Vulkan present mode into a textual string for a UI + * (and eventually for a human to read) */ + const QString TranslateVSyncMode(VkPresentModeKHR mode, + Settings::RendererBackend backend) const; + + Settings::RendererBackend GetCurrentGraphicsBackend() const; + + int FindIndex(u32 enumeration, int value) const; + + std::unique_ptr ui; + QColor bg_color; + + std::vector> apply_funcs{}; + + std::vector& records; + std::vector vulkan_devices; + std::vector> device_present_modes; + std::vector + vsync_mode_combobox_enum_map{}; //< Keeps track of which present mode corresponds to which + // selection in the combobox + u32 vulkan_device{}; + Settings::ShaderBackend shader_backend{}; + const std::function& expose_compute_option; + const std::function update_aspect_ratio; + + const Core::System& system; + const ConfigurationShared::ComboboxTranslationMap& combobox_translations; + const std::vector>& shader_mapping; + + QPushButton* api_restore_global_button; + QComboBox* vulkan_device_combobox; + QComboBox* api_combobox; + QComboBox* shader_backend_combobox; + QComboBox* vsync_mode_combobox; + QPushButton* vsync_restore_global_button; + QWidget* vulkan_device_widget; + QWidget* api_widget; + QWidget* shader_backend_widget; + QComboBox* aspect_ratio_combobox; + QComboBox* resolution_combobox; +}; diff --git a/src/sudachi/configuration/configure_graphics.ui b/src/sudachi/configuration/configure_graphics.ui new file mode 100644 index 0000000..d09415d --- /dev/null +++ b/src/sudachi/configuration/configure_graphics.ui @@ -0,0 +1,151 @@ + + + ConfigureGraphics + + + + 0 + 0 + 541 + 759 + + + + Form + + + Graphics + + + + + + + + API Settings + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + + + + + + + 16777215 + 16777215 + + + + Graphics Settings + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 0 + 0 + + + + Background Color: + + + + + + + + 0 + 0 + + + + + 40 + 16777215 + + + + + + + + + + + + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + diff --git a/src/sudachi/configuration/configure_graphics_advanced.cpp b/src/sudachi/configuration/configure_graphics_advanced.cpp new file mode 100644 index 0000000..8a54df7 --- /dev/null +++ b/src/sudachi/configuration/configure_graphics_advanced.cpp @@ -0,0 +1,82 @@ +// SPDX-FileCopyrightText: Copyright 2020 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include +#include +#include "common/settings.h" +#include "core/core.h" +#include "ui_configure_graphics_advanced.h" +#include "sudachi/configuration/configuration_shared.h" +#include "sudachi/configuration/configure_graphics_advanced.h" +#include "sudachi/configuration/shared_translation.h" +#include "sudachi/configuration/shared_widget.h" + +ConfigureGraphicsAdvanced::ConfigureGraphicsAdvanced( + const Core::System& system_, std::shared_ptr> group_, + const ConfigurationShared::Builder& builder, QWidget* parent) + : Tab(group_, parent), ui{std::make_unique()}, system{system_} { + + ui->setupUi(this); + + Setup(builder); + + SetConfiguration(); + + checkbox_enable_compute_pipelines->setVisible(false); +} + +ConfigureGraphicsAdvanced::~ConfigureGraphicsAdvanced() = default; + +void ConfigureGraphicsAdvanced::SetConfiguration() {} + +void ConfigureGraphicsAdvanced::Setup(const ConfigurationShared::Builder& builder) { + auto& layout = *ui->populate_target->layout(); + std::map hold{}; // A map will sort the data for us + + for (auto setting : + Settings::values.linkage.by_category[Settings::Category::RendererAdvanced]) { + ConfigurationShared::Widget* widget = builder.BuildWidget(setting, apply_funcs); + + if (widget == nullptr) { + continue; + } + if (!widget->Valid()) { + widget->deleteLater(); + continue; + } + + hold.emplace(setting->Id(), widget); + + // Keep track of enable_compute_pipelines so we can display it when needed + if (setting->Id() == Settings::values.enable_compute_pipelines.Id()) { + checkbox_enable_compute_pipelines = widget; + } + } + for (const auto& [id, widget] : hold) { + layout.addWidget(widget); + } +} + +void ConfigureGraphicsAdvanced::ApplyConfiguration() { + const bool is_powered_on = system.IsPoweredOn(); + for (const auto& func : apply_funcs) { + func(is_powered_on); + } +} + +void ConfigureGraphicsAdvanced::changeEvent(QEvent* event) { + if (event->type() == QEvent::LanguageChange) { + RetranslateUI(); + } + + QWidget::changeEvent(event); +} + +void ConfigureGraphicsAdvanced::RetranslateUI() { + ui->retranslateUi(this); +} + +void ConfigureGraphicsAdvanced::ExposeComputeOption() { + checkbox_enable_compute_pipelines->setVisible(true); +} diff --git a/src/sudachi/configuration/configure_graphics_advanced.h b/src/sudachi/configuration/configure_graphics_advanced.h new file mode 100644 index 0000000..0483b99 --- /dev/null +++ b/src/sudachi/configuration/configure_graphics_advanced.h @@ -0,0 +1,49 @@ +// SPDX-FileCopyrightText: Copyright 2020 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include +#include +#include "sudachi/configuration/configuration_shared.h" + +namespace Core { +class System; +} + +namespace Ui { +class ConfigureGraphicsAdvanced; +} + +namespace ConfigurationShared { +class Builder; +} + +class ConfigureGraphicsAdvanced : public ConfigurationShared::Tab { + Q_OBJECT + +public: + explicit ConfigureGraphicsAdvanced( + const Core::System& system_, std::shared_ptr> group, + const ConfigurationShared::Builder& builder, QWidget* parent = nullptr); + ~ConfigureGraphicsAdvanced() override; + + void ApplyConfiguration() override; + void SetConfiguration() override; + + void ExposeComputeOption(); + +private: + void Setup(const ConfigurationShared::Builder& builder); + void changeEvent(QEvent* event) override; + void RetranslateUI(); + + std::unique_ptr ui; + + const Core::System& system; + + std::vector> apply_funcs; + + QWidget* checkbox_enable_compute_pipelines{}; +}; diff --git a/src/sudachi/configuration/configure_graphics_advanced.ui b/src/sudachi/configuration/configure_graphics_advanced.ui new file mode 100644 index 0000000..37a854c --- /dev/null +++ b/src/sudachi/configuration/configure_graphics_advanced.ui @@ -0,0 +1,68 @@ + + + ConfigureGraphicsAdvanced + + + + 0 + 0 + 404 + 376 + + + + Form + + + Advanced + + + + + + + + Advanced Graphics Settings + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + diff --git a/src/sudachi/configuration/configure_hotkeys.cpp b/src/sudachi/configuration/configure_hotkeys.cpp new file mode 100644 index 0000000..619dc95 --- /dev/null +++ b/src/sudachi/configuration/configure_hotkeys.cpp @@ -0,0 +1,423 @@ +// SPDX-FileCopyrightText: 2017 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include +#include +#include + +#include "hid_core/frontend/emulated_controller.h" +#include "hid_core/hid_core.h" + +#include "frontend_common/config.h" +#include "ui_configure_hotkeys.h" +#include "sudachi/configuration/configure_hotkeys.h" +#include "sudachi/hotkeys.h" +#include "sudachi/uisettings.h" +#include "sudachi/util/sequence_dialog/sequence_dialog.h" + +constexpr int name_column = 0; +constexpr int hotkey_column = 1; +constexpr int controller_column = 2; + +ConfigureHotkeys::ConfigureHotkeys(Core::HID::HIDCore& hid_core, QWidget* parent) + : QWidget(parent), ui(std::make_unique()), + timeout_timer(std::make_unique()), poll_timer(std::make_unique()) { + ui->setupUi(this); + setFocusPolicy(Qt::ClickFocus); + + model = new QStandardItemModel(this); + model->setColumnCount(3); + + connect(ui->hotkey_list, &QTreeView::doubleClicked, this, &ConfigureHotkeys::Configure); + connect(ui->hotkey_list, &QTreeView::customContextMenuRequested, this, + &ConfigureHotkeys::PopupContextMenu); + ui->hotkey_list->setContextMenuPolicy(Qt::CustomContextMenu); + ui->hotkey_list->setModel(model); + + ui->hotkey_list->header()->setStretchLastSection(false); + ui->hotkey_list->header()->setSectionResizeMode(name_column, QHeaderView::ResizeMode::Stretch); + ui->hotkey_list->header()->setMinimumSectionSize(150); + + connect(ui->button_restore_defaults, &QPushButton::clicked, this, + &ConfigureHotkeys::RestoreDefaults); + connect(ui->button_clear_all, &QPushButton::clicked, this, &ConfigureHotkeys::ClearAll); + + controller = hid_core.GetEmulatedController(Core::HID::NpadIdType::Player1); + + connect(timeout_timer.get(), &QTimer::timeout, [this] { + const bool is_button_pressed = pressed_buttons != Core::HID::NpadButton::None || + pressed_home_button || pressed_capture_button; + SetPollingResult(!is_button_pressed); + }); + + connect(poll_timer.get(), &QTimer::timeout, [this] { + pressed_buttons |= controller->GetNpadButtons().raw; + pressed_home_button |= this->controller->GetHomeButtons().home != 0; + pressed_capture_button |= this->controller->GetCaptureButtons().capture != 0; + if (pressed_buttons != Core::HID::NpadButton::None || pressed_home_button || + pressed_capture_button) { + const QString button_name = + GetButtonCombinationName(pressed_buttons, pressed_home_button, + pressed_capture_button) + + QStringLiteral("..."); + model->setData(button_model_index, button_name); + } + }); + RetranslateUI(); +} + +ConfigureHotkeys::~ConfigureHotkeys() = default; + +void ConfigureHotkeys::Populate(const HotkeyRegistry& registry) { + for (const auto& group : registry.hotkey_groups) { + QString parent_item_data = QString::fromStdString(group.first); + auto* parent_item = + new QStandardItem(QCoreApplication::translate("Hotkeys", qPrintable(parent_item_data))); + parent_item->setEditable(false); + parent_item->setData(parent_item_data); + for (const auto& hotkey : group.second) { + QString hotkey_action_data = QString::fromStdString(hotkey.first); + auto* action = new QStandardItem( + QCoreApplication::translate("Hotkeys", qPrintable(hotkey_action_data))); + auto* keyseq = + new QStandardItem(hotkey.second.keyseq.toString(QKeySequence::NativeText)); + auto* controller_keyseq = + new QStandardItem(QString::fromStdString(hotkey.second.controller_keyseq)); + action->setEditable(false); + action->setData(hotkey_action_data); + keyseq->setEditable(false); + controller_keyseq->setEditable(false); + parent_item->appendRow({action, keyseq, controller_keyseq}); + } + model->appendRow(parent_item); + } + + ui->hotkey_list->expandAll(); + ui->hotkey_list->resizeColumnToContents(hotkey_column); + ui->hotkey_list->resizeColumnToContents(controller_column); +} + +void ConfigureHotkeys::changeEvent(QEvent* event) { + if (event->type() == QEvent::LanguageChange) { + RetranslateUI(); + } + + QWidget::changeEvent(event); +} + +void ConfigureHotkeys::RetranslateUI() { + ui->retranslateUi(this); + + model->setHorizontalHeaderLabels({tr("Action"), tr("Hotkey"), tr("Controller Hotkey")}); + for (int key_id = 0; key_id < model->rowCount(); key_id++) { + QStandardItem* parent = model->item(key_id, 0); + parent->setText( + QCoreApplication::translate("Hotkeys", qPrintable(parent->data().toString()))); + for (int key_column_id = 0; key_column_id < parent->rowCount(); key_column_id++) { + QStandardItem* action = parent->child(key_column_id, name_column); + action->setText( + QCoreApplication::translate("Hotkeys", qPrintable(action->data().toString()))); + } + } +} + +void ConfigureHotkeys::Configure(QModelIndex index) { + if (!index.parent().isValid()) { + return; + } + + // Controller configuration is selected + if (index.column() == controller_column) { + ConfigureController(index); + return; + } + + // Swap to the hotkey column + index = index.sibling(index.row(), hotkey_column); + + const auto previous_key = model->data(index); + + SequenceDialog hotkey_dialog{this}; + + const int return_code = hotkey_dialog.exec(); + const auto key_sequence = hotkey_dialog.GetSequence(); + if (return_code == QDialog::Rejected || key_sequence.isEmpty()) { + return; + } + const auto [key_sequence_used, used_action] = IsUsedKey(key_sequence); + + if (key_sequence_used && key_sequence != QKeySequence(previous_key.toString())) { + QMessageBox::warning( + this, tr("Conflicting Key Sequence"), + tr("The entered key sequence is already assigned to: %1").arg(used_action)); + } else { + model->setData(index, key_sequence.toString(QKeySequence::NativeText)); + } +} +void ConfigureHotkeys::ConfigureController(QModelIndex index) { + if (timeout_timer->isActive()) { + return; + } + + const auto previous_key = model->data(index); + + input_setter = [this, index, previous_key](const bool cancel) { + if (cancel) { + model->setData(index, previous_key); + return; + } + + const QString button_string = + GetButtonCombinationName(pressed_buttons, pressed_home_button, pressed_capture_button); + + const auto [key_sequence_used, used_action] = IsUsedControllerKey(button_string); + + if (key_sequence_used) { + QMessageBox::warning( + this, tr("Conflicting Key Sequence"), + tr("The entered key sequence is already assigned to: %1").arg(used_action)); + model->setData(index, previous_key); + } else { + model->setData(index, button_string); + } + }; + + button_model_index = index; + pressed_buttons = Core::HID::NpadButton::None; + pressed_home_button = false; + pressed_capture_button = false; + + model->setData(index, tr("[waiting]")); + timeout_timer->start(2500); // Cancel after 2.5 seconds + poll_timer->start(100); // Check for new inputs every 100ms + // We need to disable configuration to be able to read npad buttons + controller->DisableConfiguration(); +} + +void ConfigureHotkeys::SetPollingResult(const bool cancel) { + timeout_timer->stop(); + poll_timer->stop(); + (*input_setter)(cancel); + // Re-Enable configuration + controller->EnableConfiguration(); + + input_setter = std::nullopt; +} + +QString ConfigureHotkeys::GetButtonCombinationName(Core::HID::NpadButton button, + const bool home = false, + const bool capture = false) const { + Core::HID::NpadButtonState state{button}; + QString button_combination; + if (home) { + button_combination.append(QStringLiteral("Home+")); + } + if (capture) { + button_combination.append(QStringLiteral("Screenshot+")); + } + if (state.a) { + button_combination.append(QStringLiteral("A+")); + } + if (state.b) { + button_combination.append(QStringLiteral("B+")); + } + if (state.x) { + button_combination.append(QStringLiteral("X+")); + } + if (state.y) { + button_combination.append(QStringLiteral("Y+")); + } + if (state.l || state.right_sl || state.left_sl) { + button_combination.append(QStringLiteral("L+")); + } + if (state.r || state.right_sr || state.left_sr) { + button_combination.append(QStringLiteral("R+")); + } + if (state.zl) { + button_combination.append(QStringLiteral("ZL+")); + } + if (state.zr) { + button_combination.append(QStringLiteral("ZR+")); + } + if (state.left) { + button_combination.append(QStringLiteral("Dpad_Left+")); + } + if (state.right) { + button_combination.append(QStringLiteral("Dpad_Right+")); + } + if (state.up) { + button_combination.append(QStringLiteral("Dpad_Up+")); + } + if (state.down) { + button_combination.append(QStringLiteral("Dpad_Down+")); + } + if (state.stick_l) { + button_combination.append(QStringLiteral("Left_Stick+")); + } + if (state.stick_r) { + button_combination.append(QStringLiteral("Right_Stick+")); + } + if (state.minus) { + button_combination.append(QStringLiteral("Minus+")); + } + if (state.plus) { + button_combination.append(QStringLiteral("Plus+")); + } + if (button_combination.isEmpty()) { + return tr("Invalid"); + } else { + button_combination.chop(1); + return button_combination; + } +} + +std::pair ConfigureHotkeys::IsUsedKey(QKeySequence key_sequence) const { + for (int r = 0; r < model->rowCount(); ++r) { + const QStandardItem* const parent = model->item(r, 0); + + for (int r2 = 0; r2 < parent->rowCount(); ++r2) { + const QStandardItem* const key_seq_item = parent->child(r2, hotkey_column); + const auto key_seq_str = key_seq_item->text(); + const auto key_seq = QKeySequence::fromString(key_seq_str, QKeySequence::NativeText); + + if (key_sequence == key_seq) { + return std::make_pair(true, parent->child(r2, 0)->text()); + } + } + } + + return std::make_pair(false, QString()); +} + +std::pair ConfigureHotkeys::IsUsedControllerKey(const QString& key_sequence) const { + for (int r = 0; r < model->rowCount(); ++r) { + const QStandardItem* const parent = model->item(r, 0); + + for (int r2 = 0; r2 < parent->rowCount(); ++r2) { + const QStandardItem* const key_seq_item = parent->child(r2, controller_column); + const auto key_seq_str = key_seq_item->text(); + + if (key_sequence == key_seq_str) { + return std::make_pair(true, parent->child(r2, 0)->text()); + } + } + } + + return std::make_pair(false, QString()); +} + +void ConfigureHotkeys::ApplyConfiguration(HotkeyRegistry& registry) { + for (int key_id = 0; key_id < model->rowCount(); key_id++) { + const QStandardItem* parent = model->item(key_id, 0); + for (int key_column_id = 0; key_column_id < parent->rowCount(); key_column_id++) { + const QStandardItem* action = parent->child(key_column_id, name_column); + const QStandardItem* keyseq = parent->child(key_column_id, hotkey_column); + const QStandardItem* controller_keyseq = + parent->child(key_column_id, controller_column); + for (auto& [group, sub_actions] : registry.hotkey_groups) { + if (group != parent->data().toString().toStdString()) + continue; + for (auto& [action_name, hotkey] : sub_actions) { + if (action_name != action->data().toString().toStdString()) + continue; + hotkey.keyseq = QKeySequence(keyseq->text()); + hotkey.controller_keyseq = controller_keyseq->text().toStdString(); + } + } + } + } + + registry.SaveHotkeys(); +} + +void ConfigureHotkeys::RestoreDefaults() { + for (int r = 0; r < model->rowCount(); ++r) { + const QStandardItem* parent = model->item(r, 0); + const int hotkey_size = static_cast(UISettings::default_hotkeys.size()); + + if (hotkey_size != parent->rowCount()) { + QMessageBox::warning(this, tr("Invalid hotkey settings"), + tr("An error occurred. Please report this issue on github.")); + return; + } + + for (int r2 = 0; r2 < parent->rowCount(); ++r2) { + model->item(r, 0) + ->child(r2, hotkey_column) + ->setText(QString::fromStdString(UISettings::default_hotkeys[r2].shortcut.keyseq)); + model->item(r, 0) + ->child(r2, controller_column) + ->setText(QString::fromStdString( + UISettings::default_hotkeys[r2].shortcut.controller_keyseq)); + } + } +} + +void ConfigureHotkeys::ClearAll() { + for (int r = 0; r < model->rowCount(); ++r) { + const QStandardItem* parent = model->item(r, 0); + + for (int r2 = 0; r2 < parent->rowCount(); ++r2) { + model->item(r, 0)->child(r2, hotkey_column)->setText(QString{}); + model->item(r, 0)->child(r2, controller_column)->setText(QString{}); + } + } +} + +void ConfigureHotkeys::PopupContextMenu(const QPoint& menu_location) { + QModelIndex index = ui->hotkey_list->indexAt(menu_location); + if (!index.parent().isValid()) { + return; + } + + // Swap to the hotkey column if the controller hotkey column is not selected + if (index.column() != controller_column) { + index = index.sibling(index.row(), hotkey_column); + } + + QMenu context_menu; + + QAction* restore_default = context_menu.addAction(tr("Restore Default")); + QAction* clear = context_menu.addAction(tr("Clear")); + + connect(restore_default, &QAction::triggered, [this, index] { + if (index.column() == controller_column) { + RestoreControllerHotkey(index); + return; + } + RestoreHotkey(index); + }); + connect(clear, &QAction::triggered, [this, index] { model->setData(index, QString{}); }); + + context_menu.exec(ui->hotkey_list->viewport()->mapToGlobal(menu_location)); +} + +void ConfigureHotkeys::RestoreControllerHotkey(QModelIndex index) { + const QString& default_key_sequence = + QString::fromStdString(UISettings::default_hotkeys[index.row()].shortcut.controller_keyseq); + const auto [key_sequence_used, used_action] = IsUsedControllerKey(default_key_sequence); + + if (key_sequence_used && default_key_sequence != model->data(index).toString()) { + QMessageBox::warning( + this, tr("Conflicting Button Sequence"), + tr("The default button sequence is already assigned to: %1").arg(used_action)); + } else { + model->setData(index, default_key_sequence); + } +} + +void ConfigureHotkeys::RestoreHotkey(QModelIndex index) { + const QKeySequence& default_key_sequence = QKeySequence::fromString( + QString::fromStdString(UISettings::default_hotkeys[index.row()].shortcut.keyseq), + QKeySequence::NativeText); + const auto [key_sequence_used, used_action] = IsUsedKey(default_key_sequence); + + if (key_sequence_used && default_key_sequence != QKeySequence(model->data(index).toString())) { + QMessageBox::warning( + this, tr("Conflicting Key Sequence"), + tr("The default key sequence is already assigned to: %1").arg(used_action)); + } else { + model->setData(index, default_key_sequence.toString(QKeySequence::NativeText)); + } +} diff --git a/src/sudachi/configuration/configure_hotkeys.h b/src/sudachi/configuration/configure_hotkeys.h new file mode 100644 index 0000000..20ea3b5 --- /dev/null +++ b/src/sudachi/configuration/configure_hotkeys.h @@ -0,0 +1,74 @@ +// SPDX-FileCopyrightText: 2017 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include +#include + +namespace Common { +class ParamPackage; +} + +namespace Core::HID { +class HIDCore; +class EmulatedController; +enum class NpadButton : u64; +} // namespace Core::HID + +namespace Ui { +class ConfigureHotkeys; +} + +class HotkeyRegistry; +class QStandardItemModel; + +class ConfigureHotkeys : public QWidget { + Q_OBJECT + +public: + explicit ConfigureHotkeys(Core::HID::HIDCore& hid_core_, QWidget* parent = nullptr); + ~ConfigureHotkeys() override; + + void ApplyConfiguration(HotkeyRegistry& registry); + + /** + * Populates the hotkey list widget using data from the provided registry. + * Called every time the Configure dialog is opened. + * @param registry The HotkeyRegistry whose data is used to populate the list. + */ + void Populate(const HotkeyRegistry& registry); + +private: + void changeEvent(QEvent* event) override; + void RetranslateUI(); + + void Configure(QModelIndex index); + void ConfigureController(QModelIndex index); + std::pair IsUsedKey(QKeySequence key_sequence) const; + std::pair IsUsedControllerKey(const QString& key_sequence) const; + + void RestoreDefaults(); + void ClearAll(); + void PopupContextMenu(const QPoint& menu_location); + void RestoreControllerHotkey(QModelIndex index); + void RestoreHotkey(QModelIndex index); + + void SetPollingResult(bool cancel); + QString GetButtonCombinationName(Core::HID::NpadButton button, bool home, bool capture) const; + + std::unique_ptr ui; + + QStandardItemModel* model; + + bool pressed_home_button; + bool pressed_capture_button; + QModelIndex button_model_index; + Core::HID::NpadButton pressed_buttons; + + Core::HID::EmulatedController* controller; + std::unique_ptr timeout_timer; + std::unique_ptr poll_timer; + std::optional> input_setter; +}; diff --git a/src/sudachi/configuration/configure_hotkeys.ui b/src/sudachi/configuration/configure_hotkeys.ui new file mode 100644 index 0000000..a6902a5 --- /dev/null +++ b/src/sudachi/configuration/configure_hotkeys.ui @@ -0,0 +1,76 @@ + + + ConfigureHotkeys + + + + 0 + 0 + 439 + 510 + + + + Hotkey Settings + + + Hotkeys + + + + + + + + Double-click on a binding to change it. + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Clear All + + + + + + + Restore Defaults + + + + + + + + + + + QAbstractItemView::NoEditTriggers + + + false + + + + + + + + + + diff --git a/src/sudachi/configuration/configure_input.cpp b/src/sudachi/configuration/configure_input.cpp new file mode 100644 index 0000000..d3a0a06 --- /dev/null +++ b/src/sudachi/configuration/configure_input.cpp @@ -0,0 +1,309 @@ +// SPDX-FileCopyrightText: 2016 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include + +#include "common/settings.h" +#include "common/settings_enums.h" +#include "core/core.h" +#include "core/hle/service/am/am.h" +#include "core/hle/service/am/applet_manager.h" +#include "core/hle/service/sm/sm.h" +#include "hid_core/frontend/emulated_controller.h" +#include "hid_core/hid_core.h" +#include "ui_configure_input.h" +#include "ui_configure_input_advanced.h" +#include "ui_configure_input_player.h" +#include "sudachi/configuration/configure_camera.h" +#include "sudachi/configuration/configure_debug_controller.h" +#include "sudachi/configuration/configure_input.h" +#include "sudachi/configuration/configure_input_advanced.h" +#include "sudachi/configuration/configure_input_player.h" +#include "sudachi/configuration/configure_motion_touch.h" +#include "sudachi/configuration/configure_ringcon.h" +#include "sudachi/configuration/configure_touchscreen_advanced.h" +#include "sudachi/configuration/configure_vibration.h" +#include "sudachi/configuration/input_profiles.h" + +namespace { +template +void CallConfigureDialog(ConfigureInput& parent, Args&&... args) { + Dialog dialog(&parent, std::forward(args)...); + + const auto res = dialog.exec(); + if (res == QDialog::Accepted) { + dialog.ApplyConfiguration(); + } +} +} // Anonymous namespace + +void OnDockedModeChanged(bool last_state, bool new_state, Core::System& system) { + if (last_state == new_state) { + return; + } + + if (!system.IsPoweredOn()) { + return; + } + + system.GetAppletManager().OperationModeChanged(); +} + +ConfigureInput::ConfigureInput(Core::System& system_, QWidget* parent) + : QWidget(parent), ui(std::make_unique()), + profiles(std::make_unique()), system{system_} { + ui->setupUi(this); +} + +ConfigureInput::~ConfigureInput() = default; + +void ConfigureInput::Initialize(InputCommon::InputSubsystem* input_subsystem, + std::size_t max_players) { + const bool is_powered_on = system.IsPoweredOn(); + auto& hid_core = system.HIDCore(); + player_controllers = { + new ConfigureInputPlayer(this, 0, ui->consoleInputSettings, input_subsystem, profiles.get(), + hid_core, is_powered_on), + new ConfigureInputPlayer(this, 1, ui->consoleInputSettings, input_subsystem, profiles.get(), + hid_core, is_powered_on), + new ConfigureInputPlayer(this, 2, ui->consoleInputSettings, input_subsystem, profiles.get(), + hid_core, is_powered_on), + new ConfigureInputPlayer(this, 3, ui->consoleInputSettings, input_subsystem, profiles.get(), + hid_core, is_powered_on), + new ConfigureInputPlayer(this, 4, ui->consoleInputSettings, input_subsystem, profiles.get(), + hid_core, is_powered_on), + new ConfigureInputPlayer(this, 5, ui->consoleInputSettings, input_subsystem, profiles.get(), + hid_core, is_powered_on), + new ConfigureInputPlayer(this, 6, ui->consoleInputSettings, input_subsystem, profiles.get(), + hid_core, is_powered_on), + new ConfigureInputPlayer(this, 7, ui->consoleInputSettings, input_subsystem, profiles.get(), + hid_core, is_powered_on), + }; + + player_tabs = { + ui->tabPlayer1, ui->tabPlayer2, ui->tabPlayer3, ui->tabPlayer4, + ui->tabPlayer5, ui->tabPlayer6, ui->tabPlayer7, ui->tabPlayer8, + }; + + connected_controller_checkboxes = { + ui->checkboxPlayer1Connected, ui->checkboxPlayer2Connected, ui->checkboxPlayer3Connected, + ui->checkboxPlayer4Connected, ui->checkboxPlayer5Connected, ui->checkboxPlayer6Connected, + ui->checkboxPlayer7Connected, ui->checkboxPlayer8Connected, + }; + + std::array connected_controller_labels = { + ui->label, ui->label_3, ui->label_4, ui->label_5, + ui->label_6, ui->label_7, ui->label_8, ui->label_9, + }; + + for (std::size_t i = 0; i < player_tabs.size(); ++i) { + player_tabs[i]->setLayout(new QHBoxLayout(player_tabs[i])); + player_tabs[i]->layout()->addWidget(player_controllers[i]); + connect(player_controllers[i], &ConfigureInputPlayer::Connected, [this, i](bool checked) { + // Ensures that connecting a controller changes the number of players + if (connected_controller_checkboxes[i]->isChecked() != checked) { + // Ensures that the players are always connected in sequential order + PropagatePlayerNumberChanged(i, checked); + } + }); + connect(connected_controller_checkboxes[i], &QCheckBox::clicked, [this, i](bool checked) { + // Reconnect current controller if it was the last one checked + // (player number was reduced by more than one) + const bool reconnect_first = !checked && + i < connected_controller_checkboxes.size() - 1 && + connected_controller_checkboxes[i + 1]->isChecked(); + + // Ensures that the players are always connected in sequential order + PropagatePlayerNumberChanged(i, checked, reconnect_first); + }); + connect(player_controllers[i], &ConfigureInputPlayer::RefreshInputDevices, this, + &ConfigureInput::UpdateAllInputDevices); + connect(player_controllers[i], &ConfigureInputPlayer::RefreshInputProfiles, this, + &ConfigureInput::UpdateAllInputProfiles, Qt::QueuedConnection); + connect(connected_controller_checkboxes[i], &QCheckBox::stateChanged, [this, i](int state) { + // Keep activated controllers synced with the "Connected Controllers" checkboxes + player_controllers[i]->ConnectPlayer(state == Qt::Checked); + }); + + // Remove/hide all the elements that exceed max_players, if applicable. + if (i >= max_players) { + ui->tabWidget->removeTab(static_cast(max_players)); + connected_controller_checkboxes[i]->hide(); + connected_controller_labels[i]->hide(); + } + } + // Only the first player can choose handheld mode so connect the signal just to player 1 + connect(player_controllers[0], &ConfigureInputPlayer::HandheldStateChanged, + [this](bool is_handheld) { UpdateDockedState(is_handheld); }); + + advanced = new ConfigureInputAdvanced(hid_core, this); + ui->tabAdvanced->setLayout(new QHBoxLayout(ui->tabAdvanced)); + ui->tabAdvanced->layout()->addWidget(advanced); + + connect(advanced, &ConfigureInputAdvanced::CallDebugControllerDialog, + [this, input_subsystem, &hid_core, is_powered_on] { + CallConfigureDialog( + *this, input_subsystem, profiles.get(), hid_core, is_powered_on); + }); + connect(advanced, &ConfigureInputAdvanced::CallTouchscreenConfigDialog, + [this] { CallConfigureDialog(*this); }); + connect(advanced, &ConfigureInputAdvanced::CallMotionTouchConfigDialog, + [this, input_subsystem] { + CallConfigureDialog(*this, input_subsystem); + }); + connect(advanced, &ConfigureInputAdvanced::CallRingControllerDialog, + [this, input_subsystem, &hid_core] { + CallConfigureDialog(*this, input_subsystem, hid_core); + }); + connect(advanced, &ConfigureInputAdvanced::CallCameraDialog, [this, input_subsystem] { + CallConfigureDialog(*this, input_subsystem); + }); + + connect(ui->vibrationButton, &QPushButton::clicked, + [this, &hid_core] { CallConfigureDialog(*this, hid_core); }); + + connect(ui->motionButton, &QPushButton::clicked, [this, input_subsystem] { + CallConfigureDialog(*this, input_subsystem); + }); + + connect(ui->buttonClearAll, &QPushButton::clicked, [this] { ClearAll(); }); + connect(ui->buttonRestoreDefaults, &QPushButton::clicked, [this] { RestoreDefaults(); }); + + RetranslateUI(); + LoadConfiguration(); +} + +void ConfigureInput::PropagatePlayerNumberChanged(size_t player_index, bool checked, + bool reconnect_current) { + connected_controller_checkboxes[player_index]->setChecked(checked); + + if (checked) { + // Check all previous buttons when checked + if (player_index > 0) { + PropagatePlayerNumberChanged(player_index - 1, checked); + } + } else { + // Unchecked all following buttons when unchecked + if (player_index < connected_controller_checkboxes.size() - 1) { + PropagatePlayerNumberChanged(player_index + 1, checked); + } + } + + if (reconnect_current) { + connected_controller_checkboxes[player_index]->setCheckState(Qt::Checked); + } +} + +QList ConfigureInput::GetSubTabs() const { + return { + ui->tabPlayer1, ui->tabPlayer2, ui->tabPlayer3, ui->tabPlayer4, ui->tabPlayer5, + ui->tabPlayer6, ui->tabPlayer7, ui->tabPlayer8, ui->tabAdvanced, + }; +} + +void ConfigureInput::ApplyConfiguration() { + const bool was_global = Settings::values.players.UsingGlobal(); + Settings::values.players.SetGlobal(true); + for (auto* controller : player_controllers) { + controller->ApplyConfiguration(); + } + + advanced->ApplyConfiguration(); + + const bool pre_docked_mode = Settings::IsDockedMode(); + const bool docked_mode_selected = ui->radioDocked->isChecked(); + Settings::values.use_docked_mode.SetValue( + docked_mode_selected ? Settings::ConsoleMode::Docked : Settings::ConsoleMode::Handheld); + OnDockedModeChanged(pre_docked_mode, docked_mode_selected, system); + + Settings::values.vibration_enabled.SetValue(ui->vibrationGroup->isChecked()); + Settings::values.motion_enabled.SetValue(ui->motionGroup->isChecked()); + Settings::values.players.SetGlobal(was_global); +} + +void ConfigureInput::changeEvent(QEvent* event) { + if (event->type() == QEvent::LanguageChange) { + RetranslateUI(); + } + + QWidget::changeEvent(event); +} + +void ConfigureInput::RetranslateUI() { + ui->retranslateUi(this); +} + +void ConfigureInput::LoadConfiguration() { + const auto* handheld = system.HIDCore().GetEmulatedController(Core::HID::NpadIdType::Handheld); + + LoadPlayerControllerIndices(); + UpdateDockedState(handheld->IsConnected()); + + ui->vibrationGroup->setChecked(Settings::values.vibration_enabled.GetValue()); + ui->motionGroup->setChecked(Settings::values.motion_enabled.GetValue()); +} + +void ConfigureInput::LoadPlayerControllerIndices() { + for (std::size_t i = 0; i < connected_controller_checkboxes.size(); ++i) { + if (i == 0) { + auto* handheld = + system.HIDCore().GetEmulatedController(Core::HID::NpadIdType::Handheld); + if (handheld->IsConnected()) { + connected_controller_checkboxes[i]->setChecked(true); + continue; + } + } + const auto* controller = system.HIDCore().GetEmulatedControllerByIndex(i); + connected_controller_checkboxes[i]->setChecked(controller->IsConnected()); + } +} + +void ConfigureInput::ClearAll() { + // We don't have a good way to know what tab is active, but we can find out by getting the + // parent of the consoleInputSettings + auto* player_tab = static_cast(ui->consoleInputSettings->parent()); + player_tab->ClearAll(); +} + +void ConfigureInput::RestoreDefaults() { + // We don't have a good way to know what tab is active, but we can find out by getting the + // parent of the consoleInputSettings + auto* player_tab = static_cast(ui->consoleInputSettings->parent()); + player_tab->RestoreDefaults(); + + ui->radioDocked->setChecked(true); + ui->radioUndocked->setChecked(false); + ui->vibrationGroup->setChecked(true); + ui->motionGroup->setChecked(true); +} + +void ConfigureInput::UpdateDockedState(bool is_handheld) { + // Disallow changing the console mode if the controller type is handheld. + ui->radioDocked->setEnabled(!is_handheld); + ui->radioUndocked->setEnabled(!is_handheld); + + ui->radioDocked->setChecked(Settings::IsDockedMode()); + ui->radioUndocked->setChecked(!Settings::IsDockedMode()); + + // Also force into undocked mode if the controller type is handheld. + if (is_handheld) { + ui->radioUndocked->setChecked(true); + } +} + +void ConfigureInput::UpdateAllInputDevices() { + for (const auto& player : player_controllers) { + player->UpdateInputDeviceCombobox(); + } +} + +void ConfigureInput::UpdateAllInputProfiles(std::size_t player_index) { + for (std::size_t i = 0; i < player_controllers.size(); ++i) { + if (i == player_index) { + continue; + } + + player_controllers[i]->UpdateInputProfiles(); + } +} diff --git a/src/sudachi/configuration/configure_input.h b/src/sudachi/configuration/configure_input.h new file mode 100644 index 0000000..beb503d --- /dev/null +++ b/src/sudachi/configuration/configure_input.h @@ -0,0 +1,81 @@ +// SPDX-FileCopyrightText: 2016 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include + +#include +#include +#include + +namespace Core { +class System; +} + +class QCheckBox; +class QString; +class QTimer; + +class ConfigureInputAdvanced; +class ConfigureInputPlayer; + +class InputProfiles; + +namespace InputCommon { +class InputSubsystem; +} + +namespace Ui { +class ConfigureInput; +} + +void OnDockedModeChanged(bool last_state, bool new_state, Core::System& system); + +class ConfigureInput : public QWidget { + Q_OBJECT + +public: + explicit ConfigureInput(Core::System& system_, QWidget* parent = nullptr); + ~ConfigureInput() override; + + /// Initializes the input dialog with the given input subsystem. + void Initialize(InputCommon::InputSubsystem* input_subsystem_, std::size_t max_players = 8); + + /// Save all button configurations to settings file. + void ApplyConfiguration(); + + QList GetSubTabs() const; + +private: + void changeEvent(QEvent* event) override; + void RetranslateUI(); + void ClearAll(); + + void UpdateDockedState(bool is_handheld); + void UpdateAllInputDevices(); + void UpdateAllInputProfiles(std::size_t player_index); + // Enable preceding controllers or disable following ones + void PropagatePlayerNumberChanged(size_t player_index, bool checked, + bool reconnect_current = false); + + /// Load configuration settings. + void LoadConfiguration(); + void LoadPlayerControllerIndices(); + + /// Restore all buttons to their default values. + void RestoreDefaults(); + + std::unique_ptr ui; + + std::unique_ptr profiles; + + std::array player_controllers; + std::array player_tabs; + // Checkboxes representing the "Connected Controllers". + std::array connected_controller_checkboxes; + ConfigureInputAdvanced* advanced; + + Core::System& system; +}; diff --git a/src/sudachi/configuration/configure_input.ui b/src/sudachi/configuration/configure_input.ui new file mode 100644 index 0000000..d517740 --- /dev/null +++ b/src/sudachi/configuration/configure_input.ui @@ -0,0 +1,548 @@ + + + ConfigureInput + + + + 0 + 0 + 680 + 540 + + + + ConfigureInput + + + + 2 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + 0 + + + + Player 1 + + + Player 1 + + + + + Player 2 + + + Player 2 + + + + + Player 3 + + + Player 3 + + + + + Player 4 + + + Player 4 + + + + + Player 5 + + + Player 5 + + + + + Player 6 + + + Player 6 + + + + + Player 7 + + + Player 7 + + + + + Player 8 + + + Player 8 + + + + + Advanced + + + Advanced + + + + + + + + + 3 + + + 0 + + + 3 + + + 0 + + + 0 + + + + + + 16777215 + 16777215 + + + + Console Mode + + + + 6 + + + 8 + + + 6 + + + 3 + + + 6 + + + + + Docked + + + true + + + + + + + Handheld + + + + + + + + + + Vibration + + + true + + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + Configure + + + + + + + + + + Motion + + + true + + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + Configure + + + + + + + + + + + 5 + + + 0 + + + 0 + + + 0 + + + 3 + + + + + + + + + + + + Controllers + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1 + + + Qt::AlignCenter + + + + + + + + + + + + + + + + + + + + + Qt::LeftToRight + + + true + + + + + + + + + + + + + + 2 + + + Qt::AlignCenter + + + + + + + 3 + + + Qt::AlignCenter + + + + + + + 4 + + + Qt::AlignCenter + + + + + + + 5 + + + Qt::AlignCenter + + + + + + + 6 + + + Qt::AlignCenter + + + + + + + 7 + + + Qt::AlignCenter + + + + + + + 8 + + + Qt::AlignCenter + + + + + + + Connected + + + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 0 + 0 + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + + 0 + 0 + + + + + 0 + 0 + + + + Qt::LeftToRight + + + min-width: 68px; + + + Defaults + + + + + + + + 0 + 0 + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + + 0 + 0 + + + + + 0 + 0 + + + + Qt::LeftToRight + + + min-width: 68px; + + + Clear + + + + + + + + + + + diff --git a/src/sudachi/configuration/configure_input_advanced.cpp b/src/sudachi/configuration/configure_input_advanced.cpp new file mode 100644 index 0000000..7148c4e --- /dev/null +++ b/src/sudachi/configuration/configure_input_advanced.cpp @@ -0,0 +1,204 @@ +// SPDX-FileCopyrightText: Copyright 2020 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include "common/settings.h" +#include "core/core.h" +#include "hid_core/frontend/emulated_controller.h" +#include "hid_core/hid_core.h" +#include "ui_configure_input_advanced.h" +#include "sudachi/configuration/configure_input_advanced.h" + +ConfigureInputAdvanced::ConfigureInputAdvanced(Core::HID::HIDCore& hid_core_, QWidget* parent) + : QWidget(parent), ui(std::make_unique()), hid_core{hid_core_} { + ui->setupUi(this); + + controllers_color_buttons = {{ + { + ui->player1_left_body_button, + ui->player1_left_buttons_button, + ui->player1_right_body_button, + ui->player1_right_buttons_button, + }, + { + ui->player2_left_body_button, + ui->player2_left_buttons_button, + ui->player2_right_body_button, + ui->player2_right_buttons_button, + }, + { + ui->player3_left_body_button, + ui->player3_left_buttons_button, + ui->player3_right_body_button, + ui->player3_right_buttons_button, + }, + { + ui->player4_left_body_button, + ui->player4_left_buttons_button, + ui->player4_right_body_button, + ui->player4_right_buttons_button, + }, + { + ui->player5_left_body_button, + ui->player5_left_buttons_button, + ui->player5_right_body_button, + ui->player5_right_buttons_button, + }, + { + ui->player6_left_body_button, + ui->player6_left_buttons_button, + ui->player6_right_body_button, + ui->player6_right_buttons_button, + }, + { + ui->player7_left_body_button, + ui->player7_left_buttons_button, + ui->player7_right_body_button, + ui->player7_right_buttons_button, + }, + { + ui->player8_left_body_button, + ui->player8_left_buttons_button, + ui->player8_right_body_button, + ui->player8_right_buttons_button, + }, + }}; + + for (std::size_t player_idx = 0; player_idx < controllers_color_buttons.size(); ++player_idx) { + auto& color_buttons = controllers_color_buttons[player_idx]; + for (std::size_t button_idx = 0; button_idx < color_buttons.size(); ++button_idx) { + connect(color_buttons[button_idx], &QPushButton::clicked, this, + [this, player_idx, button_idx] { + OnControllerButtonClick(player_idx, button_idx); + }); + } + } + + connect(ui->mouse_enabled, &QCheckBox::stateChanged, this, + &ConfigureInputAdvanced::UpdateUIEnabled); + connect(ui->debug_enabled, &QCheckBox::stateChanged, this, + &ConfigureInputAdvanced::UpdateUIEnabled); + connect(ui->touchscreen_enabled, &QCheckBox::stateChanged, this, + &ConfigureInputAdvanced::UpdateUIEnabled); + connect(ui->enable_ring_controller, &QCheckBox::stateChanged, this, + &ConfigureInputAdvanced::UpdateUIEnabled); + + connect(ui->debug_configure, &QPushButton::clicked, this, + [this] { CallDebugControllerDialog(); }); + connect(ui->touchscreen_advanced, &QPushButton::clicked, this, + [this] { CallTouchscreenConfigDialog(); }); + connect(ui->buttonMotionTouch, &QPushButton::clicked, this, + [this] { CallMotionTouchConfigDialog(); }); + connect(ui->ring_controller_configure, &QPushButton::clicked, this, + [this] { CallRingControllerDialog(); }); + connect(ui->camera_configure, &QPushButton::clicked, this, [this] { CallCameraDialog(); }); + +#ifndef _WIN32 + ui->enable_raw_input->setVisible(false); +#endif + + LoadConfiguration(); +} + +ConfigureInputAdvanced::~ConfigureInputAdvanced() = default; + +void ConfigureInputAdvanced::OnControllerButtonClick(std::size_t player_idx, + std::size_t button_idx) { + const QColor new_bg_color = QColorDialog::getColor(controllers_colors[player_idx][button_idx]); + if (!new_bg_color.isValid()) { + return; + } + controllers_colors[player_idx][button_idx] = new_bg_color; + controllers_color_buttons[player_idx][button_idx]->setStyleSheet( + QStringLiteral("background-color: %1; min-width: 60px;") + .arg(controllers_colors[player_idx][button_idx].name())); +} + +void ConfigureInputAdvanced::ApplyConfiguration() { + for (std::size_t player_idx = 0; player_idx < controllers_color_buttons.size(); ++player_idx) { + auto& player = Settings::values.players.GetValue()[player_idx]; + std::array colors{}; + std::transform(controllers_colors[player_idx].begin(), controllers_colors[player_idx].end(), + colors.begin(), [](QColor color) { return color.rgb(); }); + + player.body_color_left = colors[0]; + player.button_color_left = colors[1]; + player.body_color_right = colors[2]; + player.button_color_right = colors[3]; + + hid_core.GetEmulatedControllerByIndex(player_idx)->ReloadColorsFromSettings(); + } + + Settings::values.debug_pad_enabled = ui->debug_enabled->isChecked(); + Settings::values.mouse_enabled = ui->mouse_enabled->isChecked(); + Settings::values.keyboard_enabled = ui->keyboard_enabled->isChecked(); + Settings::values.emulate_analog_keyboard = ui->emulate_analog_keyboard->isChecked(); + Settings::values.touchscreen.enabled = ui->touchscreen_enabled->isChecked(); + Settings::values.enable_raw_input = ui->enable_raw_input->isChecked(); + Settings::values.enable_udp_controller = ui->enable_udp_controller->isChecked(); + Settings::values.controller_navigation = ui->controller_navigation->isChecked(); + Settings::values.enable_ring_controller = ui->enable_ring_controller->isChecked(); + Settings::values.enable_ir_sensor = ui->enable_ir_sensor->isChecked(); + Settings::values.enable_joycon_driver = ui->enable_joycon_driver->isChecked(); + Settings::values.enable_procon_driver = ui->enable_procon_driver->isChecked(); + Settings::values.random_amiibo_id = ui->random_amiibo_id->isChecked(); +} + +void ConfigureInputAdvanced::LoadConfiguration() { + for (std::size_t player_idx = 0; player_idx < controllers_color_buttons.size(); ++player_idx) { + auto& player = Settings::values.players.GetValue()[player_idx]; + std::array colors = { + player.body_color_left, + player.button_color_left, + player.body_color_right, + player.button_color_right, + }; + + std::transform(colors.begin(), colors.end(), controllers_colors[player_idx].begin(), + [](u32 rgb) { return QColor::fromRgb(rgb); }); + + for (std::size_t button_idx = 0; button_idx < colors.size(); ++button_idx) { + controllers_color_buttons[player_idx][button_idx]->setStyleSheet( + QStringLiteral("background-color: %1; min-width: 60px;") + .arg(controllers_colors[player_idx][button_idx].name())); + } + } + + ui->debug_enabled->setChecked(Settings::values.debug_pad_enabled.GetValue()); + ui->mouse_enabled->setChecked(Settings::values.mouse_enabled.GetValue()); + ui->keyboard_enabled->setChecked(Settings::values.keyboard_enabled.GetValue()); + ui->emulate_analog_keyboard->setChecked(Settings::values.emulate_analog_keyboard.GetValue()); + ui->touchscreen_enabled->setChecked(Settings::values.touchscreen.enabled); + ui->enable_raw_input->setChecked(Settings::values.enable_raw_input.GetValue()); + ui->enable_udp_controller->setChecked(Settings::values.enable_udp_controller.GetValue()); + ui->controller_navigation->setChecked(Settings::values.controller_navigation.GetValue()); + ui->enable_ring_controller->setChecked(Settings::values.enable_ring_controller.GetValue()); + ui->enable_ir_sensor->setChecked(Settings::values.enable_ir_sensor.GetValue()); + ui->enable_joycon_driver->setChecked(Settings::values.enable_joycon_driver.GetValue()); + ui->enable_procon_driver->setChecked(Settings::values.enable_procon_driver.GetValue()); + ui->random_amiibo_id->setChecked(Settings::values.random_amiibo_id.GetValue()); + + UpdateUIEnabled(); +} + +void ConfigureInputAdvanced::changeEvent(QEvent* event) { + if (event->type() == QEvent::LanguageChange) { + RetranslateUI(); + } + + QWidget::changeEvent(event); +} + +void ConfigureInputAdvanced::RetranslateUI() { + ui->retranslateUi(this); +} + +void ConfigureInputAdvanced::UpdateUIEnabled() { + ui->debug_configure->setEnabled(ui->debug_enabled->isChecked()); + ui->touchscreen_advanced->setEnabled(ui->touchscreen_enabled->isChecked()); + ui->ring_controller_configure->setEnabled(ui->enable_ring_controller->isChecked()); +#if QT_VERSION > QT_VERSION_CHECK(6, 0, 0) || !defined(SUDACHI_USE_QT_MULTIMEDIA) + ui->enable_ir_sensor->setEnabled(false); + ui->camera_configure->setEnabled(false); +#endif +} diff --git a/src/sudachi/configuration/configure_input_advanced.h b/src/sudachi/configuration/configure_input_advanced.h new file mode 100644 index 0000000..4f00c30 --- /dev/null +++ b/src/sudachi/configuration/configure_input_advanced.h @@ -0,0 +1,53 @@ +// SPDX-FileCopyrightText: Copyright 2020 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include +#include + +class QColor; +class QPushButton; + +namespace Ui { +class ConfigureInputAdvanced; +} + +namespace Core::HID { +class HIDCore; +} // namespace Core::HID + +class ConfigureInputAdvanced : public QWidget { + Q_OBJECT + +public: + explicit ConfigureInputAdvanced(Core::HID::HIDCore& hid_core_, QWidget* parent = nullptr); + ~ConfigureInputAdvanced() override; + + void ApplyConfiguration(); + +signals: + void CallDebugControllerDialog(); + void CallMouseConfigDialog(); + void CallTouchscreenConfigDialog(); + void CallMotionTouchConfigDialog(); + void CallRingControllerDialog(); + void CallCameraDialog(); + +private: + void changeEvent(QEvent* event) override; + void RetranslateUI(); + void UpdateUIEnabled(); + + void OnControllerButtonClick(std::size_t player_idx, std::size_t button_idx); + + void LoadConfiguration(); + + std::unique_ptr ui; + + std::array, 8> controllers_colors; + std::array, 8> controllers_color_buttons; + + Core::HID::HIDCore& hid_core; +}; diff --git a/src/sudachi/configuration/configure_input_advanced.ui b/src/sudachi/configuration/configure_input_advanced.ui new file mode 100644 index 0000000..6c74afc --- /dev/null +++ b/src/sudachi/configuration/configure_input_advanced.ui @@ -0,0 +1,2821 @@ + + + ConfigureInputAdvanced + + + + 0 + 0 + 710 + 580 + + + + Configure Input + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 9 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 3 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Joycon Colors + + + + 9 + + + 9 + + + 9 + + + 9 + + + + + + 6 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Player 1 + + + + 6 + + + 6 + + + 0 + + + 6 + + + 6 + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + L Body + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 0 + 0 + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + + + + + + + + + + + L Button + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 0 + 0 + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + + + + + + + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + R Body + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 0 + 0 + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + + + + + + + + + + + R Button + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 0 + 0 + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + + + + + + + + + + + + + + + + + Player 2 + + + + 6 + + + 6 + + + 0 + + + 6 + + + 6 + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + L Body + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 0 + 0 + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + + + + + + + + + + + L Button + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 0 + 0 + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + + + + + + + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + R Body + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 0 + 0 + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + + + + + + + + + + + R Button + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 0 + 0 + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + + + + + + + + + + + + + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Player 3 + + + + 6 + + + 6 + + + 0 + + + 6 + + + 6 + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + L Body + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 0 + 0 + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + + + + + + + + + + + L Button + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 0 + 0 + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + + + + + + + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + R Body + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 0 + 0 + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + + + + + + + + + + + R Button + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 0 + 0 + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + + + + + + + + + + + + + + + + + Player 4 + + + + 6 + + + 6 + + + 0 + + + 6 + + + 6 + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + L Body + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 0 + 0 + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + + + + + + + + + + + L Button + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 0 + 0 + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + + + + + + + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + R Body + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 0 + 0 + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + + + + + + + + + + + R Button + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 0 + 0 + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + + + + + + + + + + + + + + + + + + + + + + + + 6 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Player 5 + + + + 6 + + + 6 + + + 0 + + + 6 + + + 6 + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + L Body + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 0 + 0 + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + + + + + + + + + + + L Button + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 0 + 0 + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + + + + + + + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + R Body + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 0 + 0 + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + + + + + + + + + + + R Button + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 0 + 0 + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + + + + + + + + + + + + + + + + + Player 6 + + + + 6 + + + 6 + + + 0 + + + 6 + + + 6 + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + L Body + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 0 + 0 + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + + + + + + + + + + + L Button + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 0 + 0 + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + + + + + + + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + R Body + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 0 + 0 + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + + + + + + + + + + + R Button + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 0 + 0 + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + + + + + + + + + + + + + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Player 7 + + + + 6 + + + 6 + + + 0 + + + 6 + + + 6 + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + L Body + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 0 + 0 + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + + + + + + + + + + + L Button + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 0 + 0 + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + + + + + + + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + R Body + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 0 + 0 + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + + + + + + + + + + + R Button + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 0 + 0 + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + + + + + + + + + + + + + + + + + Player 8 + + + + 6 + + + 6 + + + 0 + + + 6 + + + 6 + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + L Body + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 0 + 0 + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + + + + + + + + + + + L Button + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 0 + 0 + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + + + + + + + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + R Body + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 0 + 0 + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + + + + + + + + + + + R Button + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 0 + 0 + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 3 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Emulated Devices + + + + + + + 0 + 23 + + + + Keyboard + + + + + + + + 0 + 23 + + + + Mouse + + + + + + + Touchscreen + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 76 + 20 + + + + + + + + Advanced + + + + + + + Debug Controller + + + + + + + Configure + + + + + + + Ring Controller + + + + + + + Configure + + + + + + + Infrared Camera + + + + + + + Configure + + + + + + + + + + Other + + + + + + + 0 + 23 + + + + Emulate Analog with Keyboard Input + + + + + + + Requires restarting sudachi + + + + 0 + 23 + + + + Enable XInput 8 player support (disables web applet) + + + + + + + + 0 + 23 + + + + Enable UDP controllers (not needed for motion) + + + + + + + + 0 + 23 + + + + Controller navigation + + + + + + + Requires restarting sudachi + + + + 0 + 23 + + + + Enable direct JoyCon driver + + + + + + + Requires restarting sudachi + + + + 0 + 23 + + + + Enable direct Pro Controller driver [EXPERIMENTAL] + + + + + + + Allows unlimited uses of the same Amiibo in games that would otherwise limit you to one use. + + + + 0 + 23 + + + + Use random Amiibo ID + + + + + + + Motion / Touch + + + + + + + Configure + + + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + + + + + + + + + + + diff --git a/src/sudachi/configuration/configure_input_per_game.cpp b/src/sudachi/configuration/configure_input_per_game.cpp new file mode 100644 index 0000000..55780a9 --- /dev/null +++ b/src/sudachi/configuration/configure_input_per_game.cpp @@ -0,0 +1,115 @@ +// SPDX-FileCopyrightText: 2022 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include "common/settings.h" +#include "core/core.h" +#include "frontend_common/config.h" +#include "hid_core/frontend/emulated_controller.h" +#include "hid_core/hid_core.h" +#include "ui_configure_input_per_game.h" +#include "sudachi/configuration/configure_input_per_game.h" +#include "sudachi/configuration/input_profiles.h" + +ConfigureInputPerGame::ConfigureInputPerGame(Core::System& system_, QtConfig* config_, + QWidget* parent) + : QWidget(parent), ui(std::make_unique()), + profiles(std::make_unique()), system{system_}, config{config_} { + ui->setupUi(this); + const std::array labels = { + ui->label_player_1, ui->label_player_2, ui->label_player_3, ui->label_player_4, + ui->label_player_5, ui->label_player_6, ui->label_player_7, ui->label_player_8, + }; + profile_comboboxes = { + ui->profile_player_1, ui->profile_player_2, ui->profile_player_3, ui->profile_player_4, + ui->profile_player_5, ui->profile_player_6, ui->profile_player_7, ui->profile_player_8, + }; + + Settings::values.players.SetGlobal(false); + + const auto& profile_names = profiles->GetInputProfileNames(); + const auto populate_profiles = [this, &profile_names](size_t player_index) { + const auto previous_profile = + Settings::values.players.GetValue()[player_index].profile_name; + + auto* const player_combobox = profile_comboboxes[player_index]; + player_combobox->addItem(tr("Use global input configuration")); + + for (size_t index = 0; index < profile_names.size(); ++index) { + const auto& profile_name = profile_names[index]; + player_combobox->addItem(QString::fromStdString(profile_name)); + if (profile_name == previous_profile) { + // offset by 1 since the first element is the global config + player_combobox->setCurrentIndex(static_cast(index + 1)); + } + } + }; + for (size_t index = 0; index < profile_comboboxes.size(); ++index) { + labels[index]->setText(tr("Player %1 profile").arg(index + 1)); + populate_profiles(index); + } + + LoadConfiguration(); +} + +void ConfigureInputPerGame::ApplyConfiguration() { + LoadConfiguration(); + SaveConfiguration(); +} + +void ConfigureInputPerGame::LoadConfiguration() { + static constexpr size_t HANDHELD_INDEX = 8; + + auto& hid_core = system.HIDCore(); + for (size_t player_index = 0; player_index < profile_comboboxes.size(); ++player_index) { + Settings::values.players.SetGlobal(false); + + auto* emulated_controller = hid_core.GetEmulatedControllerByIndex(player_index); + auto* const player_combobox = profile_comboboxes[player_index]; + + const auto selection_index = player_combobox->currentIndex(); + if (selection_index == 0) { + Settings::values.players.GetValue()[player_index].profile_name = ""; + if (player_index == 0) { + Settings::values.players.GetValue()[HANDHELD_INDEX] = {}; + } + Settings::values.players.SetGlobal(true); + emulated_controller->ReloadFromSettings(); + continue; + } + const auto profile_name = player_combobox->itemText(selection_index).toStdString(); + if (profile_name.empty()) { + continue; + } + auto& player = Settings::values.players.GetValue()[player_index]; + player.profile_name = profile_name; + // Read from the profile into the custom player settings + profiles->LoadProfile(profile_name, player_index); + // Make sure the controller is connected + player.connected = true; + + emulated_controller->ReloadFromSettings(); + + if (player_index > 0) { + continue; + } + // Handle Handheld cases + auto& handheld_player = Settings::values.players.GetValue()[HANDHELD_INDEX]; + auto* handheld_controller = hid_core.GetEmulatedController(Core::HID::NpadIdType::Handheld); + if (player.controller_type == Settings::ControllerType::Handheld) { + handheld_player = player; + } else { + handheld_player = {}; + } + handheld_controller->ReloadFromSettings(); + } +} + +void ConfigureInputPerGame::SaveConfiguration() { + Settings::values.players.SetGlobal(false); + + // Clear all controls from the config in case the user reverted back to globals + config->ClearControlPlayerValues(); + for (size_t index = 0; index < Settings::values.players.GetValue().size(); ++index) { + config->SaveQtControlPlayerValues(index); + } +} diff --git a/src/sudachi/configuration/configure_input_per_game.h b/src/sudachi/configuration/configure_input_per_game.h new file mode 100644 index 0000000..4345daa --- /dev/null +++ b/src/sudachi/configuration/configure_input_per_game.h @@ -0,0 +1,46 @@ +// SPDX-FileCopyrightText: 2022 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include + +#include + +#include "ui_configure_input_per_game.h" +#include "sudachi/configuration/input_profiles.h" +#include "sudachi/configuration/qt_config.h" + +class QComboBox; + +namespace Core { +class System; +} // namespace Core + +class Config; + +class ConfigureInputPerGame : public QWidget { + Q_OBJECT + +public: + explicit ConfigureInputPerGame(Core::System& system_, QtConfig* config_, + QWidget* parent = nullptr); + + /// Load and Save configurations to settings file. + void ApplyConfiguration(); + +private: + /// Load configuration from settings file. + void LoadConfiguration(); + + /// Save configuration to settings file. + void SaveConfiguration(); + + std::unique_ptr ui; + std::unique_ptr profiles; + + std::array profile_comboboxes; + + Core::System& system; + QtConfig* config; +}; diff --git a/src/sudachi/configuration/configure_input_per_game.ui b/src/sudachi/configuration/configure_input_per_game.ui new file mode 100644 index 0000000..fbd8eab --- /dev/null +++ b/src/sudachi/configuration/configure_input_per_game.ui @@ -0,0 +1,333 @@ + + + ConfigureInputPerGame + + + + 0 + 0 + 541 + 759 + + + + Form + + + Graphics + + + + + + 0 + + + + + Input Profiles + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Player 1 Profile + + + + + + + + 0 + 0 + + + + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Player 2 Profile + + + + + + + + 0 + 0 + + + + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Player 3 Profile + + + + + + + + 0 + 0 + + + + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Player 4 Profile + + + + + + + + 0 + 0 + + + + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Player 5 Profile + + + + + + + + 0 + 0 + + + + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Player 6 Profile + + + + + + + + 0 + 0 + + + + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Player 7 Profile + + + + + + + + 0 + 0 + + + + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Player 8 Profile + + + + + + + + 0 + 0 + + + + + + + + + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + diff --git a/src/sudachi/configuration/configure_input_player.cpp b/src/sudachi/configuration/configure_input_player.cpp new file mode 100644 index 0000000..a189a7f --- /dev/null +++ b/src/sudachi/configuration/configure_input_player.cpp @@ -0,0 +1,1670 @@ +// SPDX-FileCopyrightText: 2016 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "common/assert.h" +#include "common/param_package.h" +#include "configuration/qt_config.h" +#include "frontend_common/config.h" +#include "hid_core/frontend/emulated_controller.h" +#include "hid_core/hid_core.h" +#include "hid_core/hid_types.h" +#include "input_common/drivers/keyboard.h" +#include "input_common/drivers/mouse.h" +#include "input_common/main.h" +#include "ui_configure_input_player.h" +#include "sudachi/bootmanager.h" +#include "sudachi/configuration/configure_input_player.h" +#include "sudachi/configuration/configure_input_player_widget.h" +#include "sudachi/configuration/configure_mouse_panning.h" +#include "sudachi/configuration/input_profiles.h" +#include "sudachi/util/limitable_input_dialog.h" + +const std::array + ConfigureInputPlayer::analog_sub_buttons{{ + "up", + "down", + "left", + "right", + }}; + +namespace { + +QString GetKeyName(int key_code) { + switch (key_code) { + case Qt::Key_Shift: + return QObject::tr("Shift"); + case Qt::Key_Control: + return QObject::tr("Ctrl"); + case Qt::Key_Alt: + return QObject::tr("Alt"); + case Qt::Key_Meta: + return {}; + default: + return QKeySequence(key_code).toString(); + } +} + +QString GetButtonName(Common::Input::ButtonNames button_name) { + switch (button_name) { + case Common::Input::ButtonNames::ButtonLeft: + return QObject::tr("Left"); + case Common::Input::ButtonNames::ButtonRight: + return QObject::tr("Right"); + case Common::Input::ButtonNames::ButtonDown: + return QObject::tr("Down"); + case Common::Input::ButtonNames::ButtonUp: + return QObject::tr("Up"); + case Common::Input::ButtonNames::TriggerZ: + return QObject::tr("Z"); + case Common::Input::ButtonNames::TriggerR: + return QObject::tr("R"); + case Common::Input::ButtonNames::TriggerL: + return QObject::tr("L"); + case Common::Input::ButtonNames::TriggerZR: + return QObject::tr("ZR"); + case Common::Input::ButtonNames::TriggerZL: + return QObject::tr("ZL"); + case Common::Input::ButtonNames::TriggerSR: + return QObject::tr("SR"); + case Common::Input::ButtonNames::TriggerSL: + return QObject::tr("SL"); + case Common::Input::ButtonNames::ButtonStickL: + return QObject::tr("Stick L"); + case Common::Input::ButtonNames::ButtonStickR: + return QObject::tr("Stick R"); + case Common::Input::ButtonNames::ButtonA: + return QObject::tr("A"); + case Common::Input::ButtonNames::ButtonB: + return QObject::tr("B"); + case Common::Input::ButtonNames::ButtonX: + return QObject::tr("X"); + case Common::Input::ButtonNames::ButtonY: + return QObject::tr("Y"); + case Common::Input::ButtonNames::ButtonStart: + return QObject::tr("Start"); + case Common::Input::ButtonNames::ButtonPlus: + return QObject::tr("Plus"); + case Common::Input::ButtonNames::ButtonMinus: + return QObject::tr("Minus"); + case Common::Input::ButtonNames::ButtonHome: + return QObject::tr("Home"); + case Common::Input::ButtonNames::ButtonCapture: + return QObject::tr("Capture"); + case Common::Input::ButtonNames::L1: + return QObject::tr("L1"); + case Common::Input::ButtonNames::L2: + return QObject::tr("L2"); + case Common::Input::ButtonNames::L3: + return QObject::tr("L3"); + case Common::Input::ButtonNames::R1: + return QObject::tr("R1"); + case Common::Input::ButtonNames::R2: + return QObject::tr("R2"); + case Common::Input::ButtonNames::R3: + return QObject::tr("R3"); + case Common::Input::ButtonNames::Circle: + return QObject::tr("Circle"); + case Common::Input::ButtonNames::Cross: + return QObject::tr("Cross"); + case Common::Input::ButtonNames::Square: + return QObject::tr("Square"); + case Common::Input::ButtonNames::Triangle: + return QObject::tr("Triangle"); + case Common::Input::ButtonNames::Share: + return QObject::tr("Share"); + case Common::Input::ButtonNames::Options: + return QObject::tr("Options"); + case Common::Input::ButtonNames::Home: + return QObject::tr("Home"); + case Common::Input::ButtonNames::Touch: + return QObject::tr("Touch"); + case Common::Input::ButtonNames::ButtonMouseWheel: + return QObject::tr("Wheel", "Indicates the mouse wheel"); + case Common::Input::ButtonNames::ButtonBackward: + return QObject::tr("Backward"); + case Common::Input::ButtonNames::ButtonForward: + return QObject::tr("Forward"); + case Common::Input::ButtonNames::ButtonTask: + return QObject::tr("Task"); + case Common::Input::ButtonNames::ButtonExtra: + return QObject::tr("Extra"); + default: + return QObject::tr("[undefined]"); + } +} + +QString GetDirectionName(const std::string& direction) { + if (direction == "left") { + return QObject::tr("Left"); + } + if (direction == "right") { + return QObject::tr("Right"); + } + if (direction == "up") { + return QObject::tr("Up"); + } + if (direction == "down") { + return QObject::tr("Down"); + } + UNIMPLEMENTED_MSG("Unimplemented direction name={}", direction); + return QString::fromStdString(direction); +} + +void SetAnalogParam(const Common::ParamPackage& input_param, Common::ParamPackage& analog_param, + const std::string& button_name) { + // The poller returned a complete axis, so set all the buttons + if (input_param.Has("axis_x") && input_param.Has("axis_y")) { + analog_param = input_param; + return; + } + // Check if the current configuration has either no engine or an axis binding. + // Clears out the old binding and adds one with analog_from_button. + if (!analog_param.Has("engine") || analog_param.Has("axis_x") || analog_param.Has("axis_y")) { + analog_param = { + {"engine", "analog_from_button"}, + }; + } + analog_param.Set(button_name, input_param.Serialize()); +} +} // namespace + +QString ConfigureInputPlayer::ButtonToText(const Common::ParamPackage& param) { + if (!param.Has("engine")) { + return QObject::tr("[not set]"); + } + + const QString toggle = QString::fromStdString(param.Get("toggle", false) ? "~" : ""); + const QString inverted = QString::fromStdString(param.Get("inverted", false) ? "!" : ""); + const QString invert = QString::fromStdString(param.Get("invert", "+") == "-" ? "-" : ""); + const QString turbo = QString::fromStdString(param.Get("turbo", false) ? "$" : ""); + const auto common_button_name = input_subsystem->GetButtonName(param); + + // Retrieve the names from Qt + if (param.Get("engine", "") == "keyboard") { + const QString button_str = GetKeyName(param.Get("code", 0)); + return QObject::tr("%1%2%3%4").arg(turbo, toggle, inverted, button_str); + } + + if (common_button_name == Common::Input::ButtonNames::Invalid) { + return QObject::tr("[invalid]"); + } + + if (common_button_name == Common::Input::ButtonNames::Engine) { + return QString::fromStdString(param.Get("engine", "")); + } + + if (common_button_name == Common::Input::ButtonNames::Value) { + if (param.Has("hat")) { + const QString hat = GetDirectionName(param.Get("direction", "")); + return QObject::tr("%1%2%3Hat %4").arg(turbo, toggle, inverted, hat); + } + if (param.Has("axis")) { + const QString axis = QString::fromStdString(param.Get("axis", "")); + return QObject::tr("%1%2%3Axis %4").arg(toggle, inverted, invert, axis); + } + if (param.Has("axis_x") && param.Has("axis_y") && param.Has("axis_z")) { + const QString axis_x = QString::fromStdString(param.Get("axis_x", "")); + const QString axis_y = QString::fromStdString(param.Get("axis_y", "")); + const QString axis_z = QString::fromStdString(param.Get("axis_z", "")); + return QObject::tr("%1%2Axis %3,%4,%5").arg(toggle, inverted, axis_x, axis_y, axis_z); + } + if (param.Has("motion")) { + const QString motion = QString::fromStdString(param.Get("motion", "")); + return QObject::tr("%1%2Motion %3").arg(toggle, inverted, motion); + } + if (param.Has("button")) { + const QString button = QString::fromStdString(param.Get("button", "")); + return QObject::tr("%1%2%3Button %4").arg(turbo, toggle, inverted, button); + } + } + + QString button_name = GetButtonName(common_button_name); + if (param.Has("hat")) { + return QObject::tr("%1%2%3Hat %4").arg(turbo, toggle, inverted, button_name); + } + if (param.Has("axis")) { + return QObject::tr("%1%2%3Axis %4").arg(toggle, inverted, invert, button_name); + } + if (param.Has("motion")) { + return QObject::tr("%1%2Axis %3").arg(toggle, inverted, button_name); + } + if (param.Has("button")) { + return QObject::tr("%1%2%3Button %4").arg(turbo, toggle, inverted, button_name); + } + + return QObject::tr("[unknown]"); +} + +QString ConfigureInputPlayer::AnalogToText(const Common::ParamPackage& param, + const std::string& dir) { + if (!param.Has("engine")) { + return QObject::tr("[not set]"); + } + + if (param.Get("engine", "") == "analog_from_button") { + return ButtonToText(Common::ParamPackage{param.Get(dir, "")}); + } + + if (!param.Has("axis_x") || !param.Has("axis_y")) { + return QObject::tr("[unknown]"); + } + + const auto engine_str = param.Get("engine", ""); + const QString axis_x_str = QString::fromStdString(param.Get("axis_x", "")); + const QString axis_y_str = QString::fromStdString(param.Get("axis_y", "")); + const bool invert_x = param.Get("invert_x", "+") == "-"; + const bool invert_y = param.Get("invert_y", "+") == "-"; + + if (dir == "modifier") { + return QObject::tr("[unused]"); + } + + if (dir == "left") { + const QString invert_x_str = QString::fromStdString(invert_x ? "+" : "-"); + return QObject::tr("Axis %1%2").arg(axis_x_str, invert_x_str); + } + if (dir == "right") { + const QString invert_x_str = QString::fromStdString(invert_x ? "-" : "+"); + return QObject::tr("Axis %1%2").arg(axis_x_str, invert_x_str); + } + if (dir == "up") { + const QString invert_y_str = QString::fromStdString(invert_y ? "-" : "+"); + return QObject::tr("Axis %1%2").arg(axis_y_str, invert_y_str); + } + if (dir == "down") { + const QString invert_y_str = QString::fromStdString(invert_y ? "+" : "-"); + return QObject::tr("Axis %1%2").arg(axis_y_str, invert_y_str); + } + + return QObject::tr("[unknown]"); +} + +ConfigureInputPlayer::ConfigureInputPlayer(QWidget* parent, std::size_t player_index_, + QWidget* bottom_row_, + InputCommon::InputSubsystem* input_subsystem_, + InputProfiles* profiles_, Core::HID::HIDCore& hid_core_, + bool is_powered_on_, bool debug_) + : QWidget(parent), + ui(std::make_unique()), player_index{player_index_}, debug{debug_}, + is_powered_on{is_powered_on_}, input_subsystem{input_subsystem_}, profiles(profiles_), + timeout_timer(std::make_unique()), + poll_timer(std::make_unique()), bottom_row{bottom_row_}, hid_core{hid_core_} { + if (player_index == 0) { + auto* emulated_controller_p1 = + hid_core.GetEmulatedController(Core::HID::NpadIdType::Player1); + auto* emulated_controller_handheld = + hid_core.GetEmulatedController(Core::HID::NpadIdType::Handheld); + emulated_controller_p1->SaveCurrentConfig(); + emulated_controller_p1->EnableConfiguration(); + emulated_controller_handheld->SaveCurrentConfig(); + emulated_controller_handheld->EnableConfiguration(); + if (emulated_controller_handheld->IsConnected(true)) { + emulated_controller_p1->Disconnect(); + emulated_controller = emulated_controller_handheld; + } else { + emulated_controller = emulated_controller_p1; + } + } else { + emulated_controller = hid_core.GetEmulatedControllerByIndex(player_index); + emulated_controller->SaveCurrentConfig(); + emulated_controller->EnableConfiguration(); + } + ui->setupUi(this); + + setFocusPolicy(Qt::ClickFocus); + + button_map = { + ui->buttonA, ui->buttonB, ui->buttonX, ui->buttonY, + ui->buttonLStick, ui->buttonRStick, ui->buttonL, ui->buttonR, + ui->buttonZL, ui->buttonZR, ui->buttonPlus, ui->buttonMinus, + ui->buttonDpadLeft, ui->buttonDpadUp, ui->buttonDpadRight, ui->buttonDpadDown, + ui->buttonSLLeft, ui->buttonSRLeft, ui->buttonHome, ui->buttonScreenshot, + ui->buttonSLRight, ui->buttonSRRight, + }; + + analog_map_buttons = {{ + { + ui->buttonLStickUp, + ui->buttonLStickDown, + ui->buttonLStickLeft, + ui->buttonLStickRight, + }, + { + ui->buttonRStickUp, + ui->buttonRStickDown, + ui->buttonRStickLeft, + ui->buttonRStickRight, + }, + }}; + + motion_map = { + ui->buttonMotionLeft, + ui->buttonMotionRight, + }; + + analog_map_deadzone_label = {ui->labelLStickDeadzone, ui->labelRStickDeadzone}; + analog_map_deadzone_slider = {ui->sliderLStickDeadzone, ui->sliderRStickDeadzone}; + analog_map_modifier_groupbox = {ui->buttonLStickModGroup, ui->buttonRStickModGroup}; + analog_map_modifier_button = {ui->buttonLStickMod, ui->buttonRStickMod}; + analog_map_modifier_label = {ui->labelLStickModifierRange, ui->labelRStickModifierRange}; + analog_map_modifier_slider = {ui->sliderLStickModifierRange, ui->sliderRStickModifierRange}; + analog_map_range_groupbox = {ui->buttonLStickRangeGroup, ui->buttonRStickRangeGroup}; + analog_map_range_spinbox = {ui->spinboxLStickRange, ui->spinboxRStickRange}; + + ui->controllerFrame->SetController(emulated_controller); + + for (int button_id = 0; button_id < Settings::NativeButton::NumButtons; ++button_id) { + auto* const button = button_map[button_id]; + + if (button == nullptr) { + continue; + } + + connect(button, &QPushButton::clicked, [=, this] { + HandleClick( + button, button_id, + [=, this](const Common::ParamPackage& params) { + emulated_controller->SetButtonParam(button_id, params); + }, + InputCommon::Polling::InputType::Button); + }); + + button->setContextMenuPolicy(Qt::CustomContextMenu); + connect(button, &QPushButton::customContextMenuRequested, + [=, this](const QPoint& menu_location) { + QMenu context_menu; + Common::ParamPackage param = emulated_controller->GetButtonParam(button_id); + context_menu.addAction(tr("Clear"), [&] { + emulated_controller->SetButtonParam(button_id, {}); + button_map[button_id]->setText(tr("[not set]")); + }); + if (param.Has("code") || param.Has("button") || param.Has("hat")) { + context_menu.addAction(tr("Invert button"), [&] { + const bool invert_value = !param.Get("inverted", false); + param.Set("inverted", invert_value); + button_map[button_id]->setText(ButtonToText(param)); + emulated_controller->SetButtonParam(button_id, param); + }); + context_menu.addAction(tr("Toggle button"), [&] { + const bool toggle_value = !param.Get("toggle", false); + param.Set("toggle", toggle_value); + button_map[button_id]->setText(ButtonToText(param)); + emulated_controller->SetButtonParam(button_id, param); + }); + context_menu.addAction(tr("Turbo button"), [&] { + const bool turbo_value = !param.Get("turbo", false); + param.Set("turbo", turbo_value); + button_map[button_id]->setText(ButtonToText(param)); + emulated_controller->SetButtonParam(button_id, param); + }); + } + if (param.Has("axis")) { + context_menu.addAction(tr("Invert axis"), [&] { + const bool toggle_value = !(param.Get("invert", "+") == "-"); + param.Set("invert", toggle_value ? "-" : "+"); + button_map[button_id]->setText(ButtonToText(param)); + emulated_controller->SetButtonParam(button_id, param); + }); + context_menu.addAction(tr("Invert button"), [&] { + const bool invert_value = !param.Get("inverted", false); + param.Set("inverted", invert_value); + button_map[button_id]->setText(ButtonToText(param)); + emulated_controller->SetButtonParam(button_id, param); + }); + context_menu.addAction(tr("Set threshold"), [&] { + const int button_threshold = + static_cast(param.Get("threshold", 0.5f) * 100.0f); + const int new_threshold = QInputDialog::getInt( + this, tr("Set threshold"), tr("Choose a value between 0% and 100%"), + button_threshold, 0, 100); + param.Set("threshold", new_threshold / 100.0f); + + if (button_id == Settings::NativeButton::ZL) { + ui->sliderZLThreshold->setValue(new_threshold); + } + if (button_id == Settings::NativeButton::ZR) { + ui->sliderZRThreshold->setValue(new_threshold); + } + emulated_controller->SetButtonParam(button_id, param); + }); + context_menu.addAction(tr("Toggle axis"), [&] { + const bool toggle_value = !param.Get("toggle", false); + param.Set("toggle", toggle_value); + button_map[button_id]->setText(ButtonToText(param)); + emulated_controller->SetButtonParam(button_id, param); + }); + } + context_menu.exec(button_map[button_id]->mapToGlobal(menu_location)); + }); + } + + for (int motion_id = 0; motion_id < Settings::NativeMotion::NumMotions; ++motion_id) { + auto* const button = motion_map[motion_id]; + if (button == nullptr) { + continue; + } + + connect(button, &QPushButton::clicked, [=, this] { + HandleClick( + button, motion_id, + [=, this](const Common::ParamPackage& params) { + emulated_controller->SetMotionParam(motion_id, params); + }, + InputCommon::Polling::InputType::Motion); + }); + + button->setContextMenuPolicy(Qt::CustomContextMenu); + + connect(button, &QPushButton::customContextMenuRequested, + [=, this](const QPoint& menu_location) { + QMenu context_menu; + Common::ParamPackage param = emulated_controller->GetMotionParam(motion_id); + context_menu.addAction(tr("Clear"), [&] { + emulated_controller->SetMotionParam(motion_id, {}); + motion_map[motion_id]->setText(tr("[not set]")); + }); + if (param.Has("motion")) { + context_menu.addAction(tr("Set gyro threshold"), [&] { + const int gyro_threshold = + static_cast(param.Get("threshold", 0.007f) * 1000.0f); + const int new_threshold = QInputDialog::getInt( + this, tr("Set threshold"), tr("Choose a value between 0% and 100%"), + gyro_threshold, 0, 100); + param.Set("threshold", new_threshold / 1000.0f); + emulated_controller->SetMotionParam(motion_id, param); + }); + context_menu.addAction(tr("Calibrate sensor"), [&] { + emulated_controller->StartMotionCalibration(); + }); + } + context_menu.exec(motion_map[motion_id]->mapToGlobal(menu_location)); + }); + } + + connect(ui->sliderZLThreshold, &QSlider::valueChanged, [=, this] { + Common::ParamPackage param = + emulated_controller->GetButtonParam(Settings::NativeButton::ZL); + if (param.Has("threshold")) { + const auto slider_value = ui->sliderZLThreshold->value(); + param.Set("threshold", slider_value / 100.0f); + emulated_controller->SetButtonParam(Settings::NativeButton::ZL, param); + } + }); + + connect(ui->sliderZRThreshold, &QSlider::valueChanged, [=, this] { + Common::ParamPackage param = + emulated_controller->GetButtonParam(Settings::NativeButton::ZR); + if (param.Has("threshold")) { + const auto slider_value = ui->sliderZRThreshold->value(); + param.Set("threshold", slider_value / 100.0f); + emulated_controller->SetButtonParam(Settings::NativeButton::ZR, param); + } + }); + + for (int analog_id = 0; analog_id < Settings::NativeAnalog::NumAnalogs; ++analog_id) { + for (int sub_button_id = 0; sub_button_id < ANALOG_SUB_BUTTONS_NUM; ++sub_button_id) { + auto* const analog_button = analog_map_buttons[analog_id][sub_button_id]; + + if (analog_button == nullptr) { + continue; + } + + connect(analog_button, &QPushButton::clicked, [=, this] { + if (!map_analog_stick_accepted) { + map_analog_stick_accepted = + QMessageBox::information( + this, tr("Map Analog Stick"), + tr("After pressing OK, first move your joystick horizontally, and then " + "vertically.\nTo invert the axes, first move your joystick " + "vertically, and then horizontally."), + QMessageBox::Ok | QMessageBox::Cancel) == QMessageBox::Ok; + if (!map_analog_stick_accepted) { + return; + } + } + HandleClick( + analog_map_buttons[analog_id][sub_button_id], analog_id, + [=, this](const Common::ParamPackage& params) { + Common::ParamPackage param = emulated_controller->GetStickParam(analog_id); + SetAnalogParam(params, param, analog_sub_buttons[sub_button_id]); + // Correct axis direction for inverted sticks + if (input_subsystem->IsStickInverted(param)) { + switch (analog_id) { + case Settings::NativeAnalog::LStick: { + const bool invert_value = param.Get("invert_x", "+") == "-"; + const std::string invert_str = invert_value ? "+" : "-"; + param.Set("invert_x", invert_str); + break; + } + case Settings::NativeAnalog::RStick: { + const bool invert_value = param.Get("invert_y", "+") == "-"; + const std::string invert_str = invert_value ? "+" : "-"; + param.Set("invert_y", invert_str); + break; + } + default: + break; + } + } + emulated_controller->SetStickParam(analog_id, param); + }, + InputCommon::Polling::InputType::Stick); + }); + + analog_button->setContextMenuPolicy(Qt::CustomContextMenu); + + connect(analog_button, &QPushButton::customContextMenuRequested, + [=, this](const QPoint& menu_location) { + QMenu context_menu; + Common::ParamPackage param = emulated_controller->GetStickParam(analog_id); + context_menu.addAction(tr("Clear"), [&] { + if (param.Get("engine", "") != "analog_from_button") { + emulated_controller->SetStickParam(analog_id, {}); + for (auto button : analog_map_buttons[analog_id]) { + button->setText(tr("[not set]")); + } + return; + } + switch (sub_button_id) { + case 0: + param.Erase("up"); + break; + case 1: + param.Erase("down"); + break; + case 2: + param.Erase("left"); + break; + case 3: + param.Erase("right"); + break; + } + emulated_controller->SetStickParam(analog_id, param); + analog_map_buttons[analog_id][sub_button_id]->setText(tr("[not set]")); + }); + context_menu.addAction(tr("Center axis"), [&] { + const auto stick_value = + emulated_controller->GetSticksValues()[analog_id]; + const float offset_x = stick_value.x.properties.offset; + const float offset_y = stick_value.y.properties.offset; + float raw_value_x = stick_value.x.raw_value; + float raw_value_y = stick_value.y.raw_value; + // See Core::HID::SanitizeStick() to obtain the original raw axis value + if (std::abs(offset_x) < 0.5f) { + if (raw_value_x > 0) { + raw_value_x *= 1 + offset_x; + } else { + raw_value_x *= 1 - offset_x; + } + } + if (std::abs(offset_x) < 0.5f) { + if (raw_value_y > 0) { + raw_value_y *= 1 + offset_y; + } else { + raw_value_y *= 1 - offset_y; + } + } + param.Set("offset_x", -raw_value_x + offset_x); + param.Set("offset_y", -raw_value_y + offset_y); + emulated_controller->SetStickParam(analog_id, param); + }); + context_menu.addAction(tr("Invert axis"), [&] { + if (sub_button_id == 2 || sub_button_id == 3) { + const bool invert_value = param.Get("invert_x", "+") == "-"; + const std::string invert_str = invert_value ? "+" : "-"; + param.Set("invert_x", invert_str); + emulated_controller->SetStickParam(analog_id, param); + } + if (sub_button_id == 0 || sub_button_id == 1) { + const bool invert_value = param.Get("invert_y", "+") == "-"; + const std::string invert_str = invert_value ? "+" : "-"; + param.Set("invert_y", invert_str); + emulated_controller->SetStickParam(analog_id, param); + } + for (int analog_sub_button_id = 0; + analog_sub_button_id < ANALOG_SUB_BUTTONS_NUM; + ++analog_sub_button_id) { + analog_map_buttons[analog_id][analog_sub_button_id]->setText( + AnalogToText(param, analog_sub_buttons[analog_sub_button_id])); + } + }); + context_menu.exec(analog_map_buttons[analog_id][sub_button_id]->mapToGlobal( + menu_location)); + }); + } + + // Handle clicks for the modifier buttons as well. + connect(analog_map_modifier_button[analog_id], &QPushButton::clicked, [=, this] { + HandleClick( + analog_map_modifier_button[analog_id], analog_id, + [=, this](const Common::ParamPackage& params) { + Common::ParamPackage param = emulated_controller->GetStickParam(analog_id); + param.Set("modifier", params.Serialize()); + emulated_controller->SetStickParam(analog_id, param); + }, + InputCommon::Polling::InputType::Button); + }); + + analog_map_modifier_button[analog_id]->setContextMenuPolicy(Qt::CustomContextMenu); + + connect( + analog_map_modifier_button[analog_id], &QPushButton::customContextMenuRequested, + [=, this](const QPoint& menu_location) { + QMenu context_menu; + Common::ParamPackage param = emulated_controller->GetStickParam(analog_id); + context_menu.addAction(tr("Clear"), [&] { + param.Set("modifier", ""); + analog_map_modifier_button[analog_id]->setText(tr("[not set]")); + emulated_controller->SetStickParam(analog_id, param); + }); + context_menu.addAction(tr("Toggle button"), [&] { + Common::ParamPackage modifier_param = + Common::ParamPackage{param.Get("modifier", "")}; + const bool toggle_value = !modifier_param.Get("toggle", false); + modifier_param.Set("toggle", toggle_value); + param.Set("modifier", modifier_param.Serialize()); + analog_map_modifier_button[analog_id]->setText(ButtonToText(modifier_param)); + emulated_controller->SetStickParam(analog_id, param); + }); + context_menu.addAction(tr("Invert button"), [&] { + Common::ParamPackage modifier_param = + Common::ParamPackage{param.Get("modifier", "")}; + const bool invert_value = !modifier_param.Get("inverted", false); + modifier_param.Set("inverted", invert_value); + param.Set("modifier", modifier_param.Serialize()); + analog_map_modifier_button[analog_id]->setText(ButtonToText(modifier_param)); + emulated_controller->SetStickParam(analog_id, param); + }); + context_menu.exec( + analog_map_modifier_button[analog_id]->mapToGlobal(menu_location)); + }); + + connect(analog_map_range_spinbox[analog_id], qOverload(&QSpinBox::valueChanged), + [=, this] { + Common::ParamPackage param = emulated_controller->GetStickParam(analog_id); + const auto spinbox_value = analog_map_range_spinbox[analog_id]->value(); + param.Set("range", spinbox_value / 100.0f); + emulated_controller->SetStickParam(analog_id, param); + }); + + connect(analog_map_deadzone_slider[analog_id], &QSlider::valueChanged, [=, this] { + Common::ParamPackage param = emulated_controller->GetStickParam(analog_id); + const auto slider_value = analog_map_deadzone_slider[analog_id]->value(); + analog_map_deadzone_label[analog_id]->setText(tr("Deadzone: %1%").arg(slider_value)); + param.Set("deadzone", slider_value / 100.0f); + emulated_controller->SetStickParam(analog_id, param); + }); + + connect(analog_map_modifier_slider[analog_id], &QSlider::valueChanged, [=, this] { + Common::ParamPackage param = emulated_controller->GetStickParam(analog_id); + const auto slider_value = analog_map_modifier_slider[analog_id]->value(); + analog_map_modifier_label[analog_id]->setText( + tr("Modifier Range: %1%").arg(slider_value)); + param.Set("modifier_scale", slider_value / 100.0f); + emulated_controller->SetStickParam(analog_id, param); + }); + } + + if (player_index_ == 0) { + connect(ui->mousePanningButton, &QPushButton::clicked, [this, input_subsystem_] { + const auto right_stick_param = + emulated_controller->GetStickParam(Settings::NativeAnalog::RStick); + ConfigureMousePanning dialog(this, input_subsystem_, + right_stick_param.Get("deadzone", 0.0f), + right_stick_param.Get("range", 1.0f)); + if (dialog.exec() == QDialog::Accepted) { + dialog.ApplyConfiguration(); + } + }); + } else { + ui->mousePanningWidget->hide(); + } + + // Player Connected checkbox + connect(ui->groupConnectedController, &QGroupBox::toggled, + [this](bool checked) { emit Connected(checked); }); + + if (player_index == 0) { + connect(ui->comboControllerType, qOverload(&QComboBox::currentIndexChanged), + [this](int index) { + emit HandheldStateChanged(GetControllerTypeFromIndex(index) == + Core::HID::NpadStyleIndex::Handheld); + }); + } + + if (debug || player_index == 9) { + ui->groupConnectedController->setCheckable(false); + } + + // The Debug Controller can only choose the Pro Controller. + if (debug) { + ui->buttonScreenshot->setEnabled(false); + ui->buttonHome->setEnabled(false); + ui->comboControllerType->addItem(tr("Pro Controller")); + } else { + SetConnectableControllers(); + } + + UpdateControllerAvailableButtons(); + UpdateControllerEnabledButtons(); + UpdateControllerButtonNames(); + UpdateMotionButtons(); + connect(ui->comboControllerType, qOverload(&QComboBox::currentIndexChanged), [this](int) { + UpdateControllerAvailableButtons(); + UpdateControllerEnabledButtons(); + UpdateControllerButtonNames(); + UpdateMotionButtons(); + const Core::HID::NpadStyleIndex type = + GetControllerTypeFromIndex(ui->comboControllerType->currentIndex()); + + if (player_index == 0) { + auto* emulated_controller_p1 = + hid_core.GetEmulatedController(Core::HID::NpadIdType::Player1); + auto* emulated_controller_handheld = + hid_core.GetEmulatedController(Core::HID::NpadIdType::Handheld); + bool is_connected = emulated_controller->IsConnected(true); + + emulated_controller_p1->SetNpadStyleIndex(type); + emulated_controller_handheld->SetNpadStyleIndex(type); + if (is_connected) { + if (type == Core::HID::NpadStyleIndex::Handheld) { + emulated_controller_p1->Disconnect(); + emulated_controller_handheld->Connect(true); + emulated_controller = emulated_controller_handheld; + } else { + emulated_controller_handheld->Disconnect(); + emulated_controller_p1->Connect(true); + emulated_controller = emulated_controller_p1; + } + } + ui->controllerFrame->SetController(emulated_controller); + } + emulated_controller->SetNpadStyleIndex(type); + }); + + connect(ui->comboDevices, qOverload(&QComboBox::activated), this, + &ConfigureInputPlayer::UpdateMappingWithDefaults); + ui->comboDevices->installEventFilter(this); + + ui->comboDevices->setCurrentIndex(-1); + + timeout_timer->setSingleShot(true); + connect(timeout_timer.get(), &QTimer::timeout, [this] { SetPollingResult({}, true); }); + + connect(poll_timer.get(), &QTimer::timeout, [this] { + const auto& params = input_subsystem->GetNextInput(); + if (params.Has("engine") && IsInputAcceptable(params)) { + SetPollingResult(params, false); + return; + } + }); + + UpdateInputProfiles(); + + connect(ui->buttonProfilesNew, &QPushButton::clicked, this, + &ConfigureInputPlayer::CreateProfile); + connect(ui->buttonProfilesDelete, &QPushButton::clicked, this, + &ConfigureInputPlayer::DeleteProfile); + connect(ui->comboProfiles, qOverload(&QComboBox::activated), this, + &ConfigureInputPlayer::LoadProfile); + connect(ui->buttonProfilesSave, &QPushButton::clicked, this, + &ConfigureInputPlayer::SaveProfile); + + LoadConfiguration(); +} + +ConfigureInputPlayer::~ConfigureInputPlayer() { + if (player_index == 0) { + auto* emulated_controller_p1 = + hid_core.GetEmulatedController(Core::HID::NpadIdType::Player1); + auto* emulated_controller_handheld = + hid_core.GetEmulatedController(Core::HID::NpadIdType::Handheld); + emulated_controller_p1->DisableConfiguration(); + emulated_controller_handheld->DisableConfiguration(); + } else { + emulated_controller->DisableConfiguration(); + } +} + +void ConfigureInputPlayer::ApplyConfiguration() { + if (player_index == 0) { + auto* emulated_controller_p1 = + hid_core.GetEmulatedController(Core::HID::NpadIdType::Player1); + auto* emulated_controller_handheld = + hid_core.GetEmulatedController(Core::HID::NpadIdType::Handheld); + emulated_controller_p1->DisableConfiguration(); + emulated_controller_p1->SaveCurrentConfig(); + emulated_controller_p1->EnableConfiguration(); + emulated_controller_handheld->DisableConfiguration(); + emulated_controller_handheld->SaveCurrentConfig(); + emulated_controller_handheld->EnableConfiguration(); + return; + } + emulated_controller->DisableConfiguration(); + emulated_controller->SaveCurrentConfig(); + emulated_controller->EnableConfiguration(); +} + +void ConfigureInputPlayer::showEvent(QShowEvent* event) { + if (bottom_row == nullptr) { + return; + } + QWidget::showEvent(event); + ui->main->addWidget(bottom_row); +} + +void ConfigureInputPlayer::changeEvent(QEvent* event) { + if (event->type() == QEvent::LanguageChange) { + RetranslateUI(); + } + + QWidget::changeEvent(event); +} + +void ConfigureInputPlayer::RetranslateUI() { + ui->retranslateUi(this); + UpdateUI(); +} + +void ConfigureInputPlayer::LoadConfiguration() { + emulated_controller->ReloadFromSettings(); + + UpdateUI(); + UpdateInputDeviceCombobox(); + + if (debug) { + return; + } + + const int comboBoxIndex = + GetIndexFromControllerType(emulated_controller->GetNpadStyleIndex(true)); + ui->comboControllerType->setCurrentIndex(comboBoxIndex); + ui->groupConnectedController->setChecked(emulated_controller->IsConnected(true)); +} + +void ConfigureInputPlayer::ConnectPlayer(bool connected) { + ui->groupConnectedController->setChecked(connected); + if (connected) { + emulated_controller->Connect(true); + } else { + emulated_controller->Disconnect(); + } +} + +void ConfigureInputPlayer::UpdateInputDeviceCombobox() { + // Skip input device persistence if "Input Devices" is set to "Any". + if (ui->comboDevices->currentIndex() == 0) { + UpdateInputDevices(); + return; + } + + const auto devices = emulated_controller->GetMappedDevices(); + UpdateInputDevices(); + + if (devices.empty()) { + return; + } + + if (devices.size() > 2) { + ui->comboDevices->setCurrentIndex(0); + return; + } + + const auto first_engine = devices[0].Get("engine", ""); + const auto first_guid = devices[0].Get("guid", ""); + const auto first_port = devices[0].Get("port", 0); + const auto first_pad = devices[0].Get("pad", 0); + + if (devices.size() == 1) { + const auto devices_it = std::find_if( + input_devices.begin(), input_devices.end(), + [first_engine, first_guid, first_port, first_pad](const Common::ParamPackage& param) { + return param.Get("engine", "") == first_engine && + param.Get("guid", "") == first_guid && param.Get("port", 0) == first_port && + param.Get("pad", 0) == first_pad; + }); + const int device_index = + devices_it != input_devices.end() + ? static_cast(std::distance(input_devices.begin(), devices_it)) + : 0; + ui->comboDevices->setCurrentIndex(device_index); + return; + } + + const auto second_engine = devices[1].Get("engine", ""); + const auto second_guid = devices[1].Get("guid", ""); + const auto second_port = devices[1].Get("port", 0); + + const bool is_keyboard_mouse = (first_engine == "keyboard" || first_engine == "mouse") && + (second_engine == "keyboard" || second_engine == "mouse"); + + if (is_keyboard_mouse) { + ui->comboDevices->setCurrentIndex(2); + return; + } + + const bool is_engine_equal = first_engine == second_engine; + const bool is_port_equal = first_port == second_port; + + if (is_engine_equal && is_port_equal) { + const auto devices_it = std::find_if( + input_devices.begin(), input_devices.end(), + [first_engine, first_guid, second_guid, first_port](const Common::ParamPackage& param) { + const bool is_guid_valid = + (param.Get("guid", "") == first_guid && + param.Get("guid2", "") == second_guid) || + (param.Get("guid", "") == second_guid && param.Get("guid2", "") == first_guid); + return param.Get("engine", "") == first_engine && is_guid_valid && + param.Get("port", 0) == first_port; + }); + const int device_index = + devices_it != input_devices.end() + ? static_cast(std::distance(input_devices.begin(), devices_it)) + : 0; + ui->comboDevices->setCurrentIndex(device_index); + } else { + ui->comboDevices->setCurrentIndex(0); + } +} + +void ConfigureInputPlayer::RestoreDefaults() { + UpdateMappingWithDefaults(); +} + +void ConfigureInputPlayer::ClearAll() { + for (int button_id = 0; button_id < Settings::NativeButton::NumButtons; ++button_id) { + const auto* const button = button_map[button_id]; + if (button == nullptr) { + continue; + } + emulated_controller->SetButtonParam(button_id, {}); + } + + for (int analog_id = 0; analog_id < Settings::NativeAnalog::NumAnalogs; ++analog_id) { + for (int sub_button_id = 0; sub_button_id < ANALOG_SUB_BUTTONS_NUM; ++sub_button_id) { + const auto* const analog_button = analog_map_buttons[analog_id][sub_button_id]; + if (analog_button == nullptr) { + continue; + } + emulated_controller->SetStickParam(analog_id, {}); + } + } + + for (int motion_id = 0; motion_id < Settings::NativeMotion::NumMotions; ++motion_id) { + const auto* const motion_button = motion_map[motion_id]; + if (motion_button == nullptr) { + continue; + } + emulated_controller->SetMotionParam(motion_id, {}); + } + + UpdateUI(); + UpdateInputDevices(); +} + +void ConfigureInputPlayer::UpdateUI() { + for (int button = 0; button < Settings::NativeButton::NumButtons; ++button) { + const Common::ParamPackage param = emulated_controller->GetButtonParam(button); + button_map[button]->setText(ButtonToText(param)); + } + + const Common::ParamPackage ZL_param = + emulated_controller->GetButtonParam(Settings::NativeButton::ZL); + if (ZL_param.Has("threshold")) { + const int button_threshold = static_cast(ZL_param.Get("threshold", 0.5f) * 100.0f); + ui->sliderZLThreshold->setValue(button_threshold); + } + + const Common::ParamPackage ZR_param = + emulated_controller->GetButtonParam(Settings::NativeButton::ZR); + if (ZR_param.Has("threshold")) { + const int button_threshold = static_cast(ZR_param.Get("threshold", 0.5f) * 100.0f); + ui->sliderZRThreshold->setValue(button_threshold); + } + + for (int motion_id = 0; motion_id < Settings::NativeMotion::NumMotions; ++motion_id) { + const Common::ParamPackage param = emulated_controller->GetMotionParam(motion_id); + motion_map[motion_id]->setText(ButtonToText(param)); + } + + for (int analog_id = 0; analog_id < Settings::NativeAnalog::NumAnalogs; ++analog_id) { + const Common::ParamPackage param = emulated_controller->GetStickParam(analog_id); + for (int sub_button_id = 0; sub_button_id < ANALOG_SUB_BUTTONS_NUM; ++sub_button_id) { + auto* const analog_button = analog_map_buttons[analog_id][sub_button_id]; + + if (analog_button == nullptr) { + continue; + } + + analog_button->setText(AnalogToText(param, analog_sub_buttons[sub_button_id])); + } + + analog_map_modifier_button[analog_id]->setText( + ButtonToText(Common::ParamPackage{param.Get("modifier", "")})); + + const auto deadzone_label = analog_map_deadzone_label[analog_id]; + const auto deadzone_slider = analog_map_deadzone_slider[analog_id]; + const auto modifier_groupbox = analog_map_modifier_groupbox[analog_id]; + const auto modifier_label = analog_map_modifier_label[analog_id]; + const auto modifier_slider = analog_map_modifier_slider[analog_id]; + const auto range_groupbox = analog_map_range_groupbox[analog_id]; + const auto range_spinbox = analog_map_range_spinbox[analog_id]; + + int slider_value; + const bool is_controller = input_subsystem->IsController(param); + + if (is_controller) { + slider_value = static_cast(param.Get("deadzone", 0.15f) * 100); + deadzone_label->setText(tr("Deadzone: %1%").arg(slider_value)); + deadzone_slider->setValue(slider_value); + range_spinbox->setValue(static_cast(param.Get("range", 0.95f) * 100)); + } else { + slider_value = static_cast(param.Get("modifier_scale", 0.5f) * 100); + modifier_label->setText(tr("Modifier Range: %1%").arg(slider_value)); + modifier_slider->setValue(slider_value); + } + + deadzone_label->setVisible(is_controller); + deadzone_slider->setVisible(is_controller); + modifier_groupbox->setVisible(!is_controller); + modifier_label->setVisible(!is_controller); + modifier_slider->setVisible(!is_controller); + range_groupbox->setVisible(is_controller); + } +} + +void ConfigureInputPlayer::SetConnectableControllers() { + const auto npad_style_set = hid_core.GetSupportedStyleTag(); + index_controller_type_pairs.clear(); + ui->comboControllerType->clear(); + + const auto add_item = [&](Core::HID::NpadStyleIndex controller_type, + const QString& controller_name) { + index_controller_type_pairs.emplace_back(ui->comboControllerType->count(), controller_type); + ui->comboControllerType->addItem(controller_name); + }; + + if (npad_style_set.fullkey == 1) { + add_item(Core::HID::NpadStyleIndex::Fullkey, tr("Pro Controller")); + } + + if (npad_style_set.joycon_dual == 1) { + add_item(Core::HID::NpadStyleIndex::JoyconDual, tr("Dual Joycons")); + } + + if (npad_style_set.joycon_left == 1) { + add_item(Core::HID::NpadStyleIndex::JoyconLeft, tr("Left Joycon")); + } + + if (npad_style_set.joycon_right == 1) { + add_item(Core::HID::NpadStyleIndex::JoyconRight, tr("Right Joycon")); + } + + if (player_index == 0 && npad_style_set.handheld == 1) { + add_item(Core::HID::NpadStyleIndex::Handheld, tr("Handheld")); + } + + if (npad_style_set.gamecube == 1) { + add_item(Core::HID::NpadStyleIndex::GameCube, tr("GameCube Controller")); + } + + // Disable all unsupported controllers + if (!Settings::values.enable_all_controllers) { + return; + } + + if (npad_style_set.palma == 1) { + add_item(Core::HID::NpadStyleIndex::Pokeball, tr("Poke Ball Plus")); + } + + if (npad_style_set.lark == 1) { + add_item(Core::HID::NpadStyleIndex::NES, tr("NES Controller")); + } + + if (npad_style_set.lucia == 1) { + add_item(Core::HID::NpadStyleIndex::SNES, tr("SNES Controller")); + } + + if (npad_style_set.lagoon == 1) { + add_item(Core::HID::NpadStyleIndex::N64, tr("N64 Controller")); + } + + if (npad_style_set.lager == 1) { + add_item(Core::HID::NpadStyleIndex::SegaGenesis, tr("Sega Genesis")); + } +} + +Core::HID::NpadStyleIndex ConfigureInputPlayer::GetControllerTypeFromIndex(int index) const { + const auto it = + std::find_if(index_controller_type_pairs.begin(), index_controller_type_pairs.end(), + [index](const auto& pair) { return pair.first == index; }); + + if (it == index_controller_type_pairs.end()) { + return Core::HID::NpadStyleIndex::Fullkey; + } + + return it->second; +} + +int ConfigureInputPlayer::GetIndexFromControllerType(Core::HID::NpadStyleIndex type) const { + const auto it = + std::find_if(index_controller_type_pairs.begin(), index_controller_type_pairs.end(), + [type](const auto& pair) { return pair.second == type; }); + + if (it == index_controller_type_pairs.end()) { + return -1; + } + + return it->first; +} + +void ConfigureInputPlayer::UpdateInputDevices() { + input_devices = input_subsystem->GetInputDevices(); + ui->comboDevices->clear(); + for (const auto& device : input_devices) { + ui->comboDevices->addItem(QString::fromStdString(device.Get("display", "Unknown")), {}); + } +} + +void ConfigureInputPlayer::UpdateControllerAvailableButtons() { + auto layout = GetControllerTypeFromIndex(ui->comboControllerType->currentIndex()); + if (debug) { + layout = Core::HID::NpadStyleIndex::Fullkey; + } + + // List of all the widgets that will be hidden by any of the following layouts that need + // "unhidden" after the controller type changes + const std::array layout_show = { + ui->buttonShoulderButtonsSLSRLeft, + ui->buttonShoulderButtonsSLSRRight, + ui->horizontalSpacerShoulderButtonsWidget, + ui->horizontalSpacerShoulderButtonsWidget2, + ui->horizontalSpacerShoulderButtonsWidget3, + ui->horizontalSpacerShoulderButtonsWidget4, + ui->buttonShoulderButtonsLeft, + ui->buttonMiscButtonsMinusScreenshot, + ui->bottomLeft, + ui->buttonShoulderButtonsRight, + ui->buttonMiscButtonsPlusHome, + ui->bottomRight, + ui->buttonMiscButtonsMinusGroup, + ui->buttonMiscButtonsScreenshotGroup, + }; + + for (auto* widget : layout_show) { + widget->show(); + } + + std::vector layout_hidden; + switch (layout) { + case Core::HID::NpadStyleIndex::Fullkey: + case Core::HID::NpadStyleIndex::Handheld: + layout_hidden = { + ui->buttonShoulderButtonsSLSRLeft, + ui->buttonShoulderButtonsSLSRRight, + ui->horizontalSpacerShoulderButtonsWidget2, + ui->horizontalSpacerShoulderButtonsWidget4, + }; + break; + case Core::HID::NpadStyleIndex::JoyconLeft: + layout_hidden = { + ui->buttonShoulderButtonsSLSRRight, + ui->horizontalSpacerShoulderButtonsWidget2, + ui->horizontalSpacerShoulderButtonsWidget3, + ui->buttonShoulderButtonsRight, + ui->buttonMiscButtonsPlusHome, + ui->bottomRight, + }; + break; + case Core::HID::NpadStyleIndex::JoyconRight: + layout_hidden = { + ui->buttonShoulderButtonsSLSRLeft, ui->horizontalSpacerShoulderButtonsWidget, + ui->horizontalSpacerShoulderButtonsWidget4, ui->buttonShoulderButtonsLeft, + ui->buttonMiscButtonsMinusScreenshot, ui->bottomLeft, + }; + break; + case Core::HID::NpadStyleIndex::GameCube: + layout_hidden = { + ui->buttonShoulderButtonsSLSRLeft, + ui->buttonShoulderButtonsSLSRRight, + ui->horizontalSpacerShoulderButtonsWidget2, + ui->horizontalSpacerShoulderButtonsWidget4, + ui->buttonMiscButtonsMinusGroup, + ui->buttonMiscButtonsScreenshotGroup, + }; + break; + default: + break; + } + + for (auto* widget : layout_hidden) { + widget->hide(); + } +} + +void ConfigureInputPlayer::UpdateControllerEnabledButtons() { + auto layout = GetControllerTypeFromIndex(ui->comboControllerType->currentIndex()); + if (debug) { + layout = Core::HID::NpadStyleIndex::Fullkey; + } + + // List of all the widgets that will be disabled by any of the following layouts that need + // "enabled" after the controller type changes + const std::array layout_enable = { + ui->buttonLStickPressedGroup, + ui->groupRStickPressed, + ui->buttonShoulderButtonsButtonLGroup, + }; + + for (auto* widget : layout_enable) { + widget->setEnabled(true); + } + + std::vector layout_disable; + switch (layout) { + case Core::HID::NpadStyleIndex::Fullkey: + case Core::HID::NpadStyleIndex::JoyconDual: + case Core::HID::NpadStyleIndex::Handheld: + case Core::HID::NpadStyleIndex::JoyconLeft: + case Core::HID::NpadStyleIndex::JoyconRight: + break; + case Core::HID::NpadStyleIndex::GameCube: + layout_disable = { + ui->buttonHome, + ui->buttonLStickPressedGroup, + ui->groupRStickPressed, + ui->buttonShoulderButtonsButtonLGroup, + }; + break; + default: + break; + } + + for (auto* widget : layout_disable) { + widget->setEnabled(false); + } +} + +void ConfigureInputPlayer::UpdateMotionButtons() { + if (debug) { + // Motion isn't used with the debug controller, hide both groupboxes. + ui->buttonMotionLeftGroup->hide(); + ui->buttonMotionRightGroup->hide(); + return; + } + + // Show/hide the "Motion 1/2" groupboxes depending on the currently selected controller. + switch (GetControllerTypeFromIndex(ui->comboControllerType->currentIndex())) { + case Core::HID::NpadStyleIndex::Fullkey: + case Core::HID::NpadStyleIndex::JoyconLeft: + case Core::HID::NpadStyleIndex::Handheld: + // Show "Motion 1" and hide "Motion 2". + ui->buttonMotionLeftGroup->show(); + ui->buttonMotionRightGroup->hide(); + break; + case Core::HID::NpadStyleIndex::JoyconRight: + // Show "Motion 2" and hide "Motion 1". + ui->buttonMotionLeftGroup->hide(); + ui->buttonMotionRightGroup->show(); + break; + case Core::HID::NpadStyleIndex::GameCube: + // Hide both "Motion 1/2". + ui->buttonMotionLeftGroup->hide(); + ui->buttonMotionRightGroup->hide(); + break; + case Core::HID::NpadStyleIndex::JoyconDual: + default: + // Show both "Motion 1/2". + ui->buttonMotionLeftGroup->show(); + ui->buttonMotionRightGroup->show(); + break; + } +} + +void ConfigureInputPlayer::UpdateControllerButtonNames() { + auto layout = GetControllerTypeFromIndex(ui->comboControllerType->currentIndex()); + if (debug) { + layout = Core::HID::NpadStyleIndex::Fullkey; + } + + switch (layout) { + case Core::HID::NpadStyleIndex::Fullkey: + case Core::HID::NpadStyleIndex::JoyconDual: + case Core::HID::NpadStyleIndex::Handheld: + case Core::HID::NpadStyleIndex::JoyconLeft: + case Core::HID::NpadStyleIndex::JoyconRight: + ui->buttonMiscButtonsPlusGroup->setTitle(tr("Plus")); + ui->buttonShoulderButtonsButtonZLGroup->setTitle(tr("ZL")); + ui->buttonShoulderButtonsZRGroup->setTitle(tr("ZR")); + ui->buttonShoulderButtonsRGroup->setTitle(tr("R")); + ui->LStick->setTitle(tr("Left Stick")); + ui->RStick->setTitle(tr("Right Stick")); + break; + case Core::HID::NpadStyleIndex::GameCube: + ui->buttonMiscButtonsPlusGroup->setTitle(tr("Start / Pause")); + ui->buttonShoulderButtonsButtonZLGroup->setTitle(tr("L")); + ui->buttonShoulderButtonsZRGroup->setTitle(tr("R")); + ui->buttonShoulderButtonsRGroup->setTitle(tr("Z")); + ui->LStick->setTitle(tr("Control Stick")); + ui->RStick->setTitle(tr("C-Stick")); + break; + default: + break; + } +} + +void ConfigureInputPlayer::UpdateMappingWithDefaults() { + if (ui->comboDevices->currentIndex() == 0) { + return; + } + + for (int button_id = 0; button_id < Settings::NativeButton::NumButtons; ++button_id) { + const auto* const button = button_map[button_id]; + if (button == nullptr) { + continue; + } + emulated_controller->SetButtonParam(button_id, {}); + } + + for (int analog_id = 0; analog_id < Settings::NativeAnalog::NumAnalogs; ++analog_id) { + for (int sub_button_id = 0; sub_button_id < ANALOG_SUB_BUTTONS_NUM; ++sub_button_id) { + const auto* const analog_button = analog_map_buttons[analog_id][sub_button_id]; + if (analog_button == nullptr) { + continue; + } + emulated_controller->SetStickParam(analog_id, {}); + } + } + + for (int motion_id = 0; motion_id < Settings::NativeMotion::NumMotions; ++motion_id) { + const auto* const motion_button = motion_map[motion_id]; + if (motion_button == nullptr) { + continue; + } + emulated_controller->SetMotionParam(motion_id, {}); + } + + // Reset keyboard or mouse bindings + if (ui->comboDevices->currentIndex() == 1 || ui->comboDevices->currentIndex() == 2) { + for (int button_id = 0; button_id < Settings::NativeButton::NumButtons; ++button_id) { + emulated_controller->SetButtonParam( + button_id, Common::ParamPackage{InputCommon::GenerateKeyboardParam( + QtConfig::default_buttons[button_id])}); + } + for (int analog_id = 0; analog_id < Settings::NativeAnalog::NumAnalogs; ++analog_id) { + Common::ParamPackage analog_param{}; + for (int sub_button_id = 0; sub_button_id < ANALOG_SUB_BUTTONS_NUM; ++sub_button_id) { + Common::ParamPackage params{InputCommon::GenerateKeyboardParam( + QtConfig::default_analogs[analog_id][sub_button_id])}; + SetAnalogParam(params, analog_param, analog_sub_buttons[sub_button_id]); + } + + analog_param.Set("modifier", InputCommon::GenerateKeyboardParam( + QtConfig::default_stick_mod[analog_id])); + emulated_controller->SetStickParam(analog_id, analog_param); + } + + for (int motion_id = 0; motion_id < Settings::NativeMotion::NumMotions; ++motion_id) { + emulated_controller->SetMotionParam( + motion_id, Common::ParamPackage{InputCommon::GenerateKeyboardParam( + QtConfig::default_motions[motion_id])}); + } + + // If mouse is selected we want to override with mappings from the driver + if (ui->comboDevices->currentIndex() == 1) { + UpdateUI(); + return; + } + } + + // Reset controller bindings + const auto& device = input_devices[ui->comboDevices->currentIndex()]; + auto button_mappings = input_subsystem->GetButtonMappingForDevice(device); + auto analog_mappings = input_subsystem->GetAnalogMappingForDevice(device); + auto motion_mappings = input_subsystem->GetMotionMappingForDevice(device); + + for (const auto& button_mapping : button_mappings) { + const std::size_t index = button_mapping.first; + emulated_controller->SetButtonParam(index, button_mapping.second); + } + for (const auto& analog_mapping : analog_mappings) { + const std::size_t index = analog_mapping.first; + emulated_controller->SetStickParam(index, analog_mapping.second); + } + for (const auto& motion_mapping : motion_mappings) { + const std::size_t index = motion_mapping.first; + emulated_controller->SetMotionParam(index, motion_mapping.second); + } + + UpdateUI(); +} + +void ConfigureInputPlayer::HandleClick( + QPushButton* button, std::size_t button_id, + std::function new_input_setter, + InputCommon::Polling::InputType type) { + if (timeout_timer->isActive()) { + return; + } + if (button == ui->buttonMotionLeft || button == ui->buttonMotionRight) { + button->setText(tr("Shake!")); + } else { + button->setText(tr("[waiting]")); + } + button->setFocus(); + + input_setter = std::move(new_input_setter); + + input_subsystem->BeginMapping(type); + + QWidget::grabMouse(); + QWidget::grabKeyboard(); + + if (type == InputCommon::Polling::InputType::Button) { + ui->controllerFrame->BeginMappingButton(button_id); + } else if (type == InputCommon::Polling::InputType::Stick) { + ui->controllerFrame->BeginMappingAnalog(button_id); + } + + timeout_timer->start(4000); // Cancel after 4 seconds + poll_timer->start(25); // Check for new inputs every 25ms +} + +void ConfigureInputPlayer::SetPollingResult(const Common::ParamPackage& params, bool abort) { + timeout_timer->stop(); + poll_timer->stop(); + input_subsystem->StopMapping(); + + QWidget::releaseMouse(); + QWidget::releaseKeyboard(); + + if (!abort) { + (*input_setter)(params); + } + + UpdateUI(); + UpdateInputDeviceCombobox(); + ui->controllerFrame->EndMapping(); + + input_setter = std::nullopt; +} + +bool ConfigureInputPlayer::IsInputAcceptable(const Common::ParamPackage& params) const { + if (ui->comboDevices->currentIndex() == 0) { + return true; + } + + if (params.Has("motion")) { + return true; + } + + // Keyboard/Mouse + if (ui->comboDevices->currentIndex() == 1 || ui->comboDevices->currentIndex() == 2) { + return params.Get("engine", "") == "keyboard" || params.Get("engine", "") == "mouse"; + } + + const auto& current_input_device = input_devices[ui->comboDevices->currentIndex()]; + return params.Get("engine", "") == current_input_device.Get("engine", "") && + (params.Get("guid", "") == current_input_device.Get("guid", "") || + params.Get("guid", "") == current_input_device.Get("guid2", "")) && + params.Get("port", 0) == current_input_device.Get("port", 0); +} + +void ConfigureInputPlayer::mousePressEvent(QMouseEvent* event) { + if (!input_setter || !event) { + return; + } + + const auto button = GRenderWindow::QtButtonToMouseButton(event->button()); + input_subsystem->GetMouse()->PressButton(0, 0, button); +} + +void ConfigureInputPlayer::wheelEvent(QWheelEvent* event) { + const int x = event->angleDelta().x(); + const int y = event->angleDelta().y(); + input_subsystem->GetMouse()->MouseWheelChange(x, y); +} + +void ConfigureInputPlayer::keyPressEvent(QKeyEvent* event) { + if (!input_setter || !event) { + return; + } + event->ignore(); + if (event->key() != Qt::Key_Escape) { + input_subsystem->GetKeyboard()->PressKey(event->key()); + } +} + +bool ConfigureInputPlayer::eventFilter(QObject* object, QEvent* event) { + if (object == ui->comboDevices && event->type() == QEvent::MouseButtonPress) { + RefreshInputDevices(); + } + return object->eventFilter(object, event); +} + +void ConfigureInputPlayer::CreateProfile() { + const auto profile_name = + LimitableInputDialog::GetText(this, tr("New Profile"), tr("Enter a profile name:"), 1, 30, + LimitableInputDialog::InputLimiter::Filesystem); + + if (profile_name.isEmpty()) { + return; + } + + if (!InputProfiles::IsProfileNameValid(profile_name.toStdString())) { + QMessageBox::critical(this, tr("Create Input Profile"), + tr("The given profile name is not valid!")); + return; + } + + ApplyConfiguration(); + + if (!profiles->CreateProfile(profile_name.toStdString(), player_index)) { + QMessageBox::critical(this, tr("Create Input Profile"), + tr("Failed to create the input profile \"%1\"").arg(profile_name)); + UpdateInputProfiles(); + emit RefreshInputProfiles(player_index); + return; + } + + emit RefreshInputProfiles(player_index); + + ui->comboProfiles->addItem(profile_name); + ui->comboProfiles->setCurrentIndex(ui->comboProfiles->count() - 1); +} + +void ConfigureInputPlayer::DeleteProfile() { + const QString profile_name = ui->comboProfiles->itemText(ui->comboProfiles->currentIndex()); + + if (profile_name.isEmpty()) { + return; + } + + if (!profiles->DeleteProfile(profile_name.toStdString())) { + QMessageBox::critical(this, tr("Delete Input Profile"), + tr("Failed to delete the input profile \"%1\"").arg(profile_name)); + UpdateInputProfiles(); + emit RefreshInputProfiles(player_index); + return; + } + + emit RefreshInputProfiles(player_index); + + ui->comboProfiles->removeItem(ui->comboProfiles->currentIndex()); + ui->comboProfiles->setCurrentIndex(-1); +} + +void ConfigureInputPlayer::LoadProfile() { + const QString profile_name = ui->comboProfiles->itemText(ui->comboProfiles->currentIndex()); + + if (profile_name.isEmpty()) { + return; + } + + ApplyConfiguration(); + + if (!profiles->LoadProfile(profile_name.toStdString(), player_index)) { + QMessageBox::critical(this, tr("Load Input Profile"), + tr("Failed to load the input profile \"%1\"").arg(profile_name)); + UpdateInputProfiles(); + emit RefreshInputProfiles(player_index); + return; + } + + LoadConfiguration(); +} + +void ConfigureInputPlayer::SaveProfile() { + static constexpr size_t HANDHELD_INDEX = 8; + const QString profile_name = ui->comboProfiles->itemText(ui->comboProfiles->currentIndex()); + + if (profile_name.isEmpty()) { + return; + } + + ApplyConfiguration(); + + // When we're in handheld mode, only the handheld emulated controller bindings are updated + const bool is_handheld = player_index == 0 && emulated_controller->GetNpadIdType() == + Core::HID::NpadIdType::Handheld; + const auto profile_player_index = is_handheld ? HANDHELD_INDEX : player_index; + + if (!profiles->SaveProfile(profile_name.toStdString(), profile_player_index)) { + QMessageBox::critical(this, tr("Save Input Profile"), + tr("Failed to save the input profile \"%1\"").arg(profile_name)); + UpdateInputProfiles(); + emit RefreshInputProfiles(player_index); + return; + } +} + +void ConfigureInputPlayer::UpdateInputProfiles() { + ui->comboProfiles->clear(); + + // Set current profile as empty by default + int profile_index = -1; + + // Add every available profile and search the player profile to set it as current one + auto& current_profile = Settings::values.players.GetValue()[player_index].profile_name; + std::vector profile_names = profiles->GetInputProfileNames(); + std::string profile_name; + for (size_t i = 0; i < profile_names.size(); i++) { + profile_name = profile_names[i]; + ui->comboProfiles->addItem(QString::fromStdString(profile_name)); + if (current_profile == profile_name) { + profile_index = (int)i; + } + } + + LOG_DEBUG(Frontend, "Setting the current input profile to index {}", profile_index); + ui->comboProfiles->setCurrentIndex(profile_index); +} diff --git a/src/sudachi/configuration/configure_input_player.h b/src/sudachi/configuration/configure_input_player.h new file mode 100644 index 0000000..fda09e9 --- /dev/null +++ b/src/sudachi/configuration/configure_input_player.h @@ -0,0 +1,228 @@ +// SPDX-FileCopyrightText: 2016 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include +#include +#include +#include +#include + +#include + +#include "common/param_package.h" +#include "common/settings.h" +#include "ui_configure_input.h" + +class QCheckBox; +class QKeyEvent; +class QLabel; +class QPushButton; +class QSlider; +class QSpinBox; +class QString; +class QTimer; +class QWidget; + +class InputProfiles; + +namespace InputCommon { +class InputSubsystem; +} + +namespace InputCommon::Polling { +enum class InputType; +} // namespace InputCommon::Polling + +namespace Ui { +class ConfigureInputPlayer; +} // namespace Ui + +namespace Core::HID { +class HIDCore; +class EmulatedController; +enum class NpadStyleIndex : u8; +} // namespace Core::HID + +class ConfigureInputPlayer : public QWidget { + Q_OBJECT + +public: + explicit ConfigureInputPlayer(QWidget* parent, std::size_t player_index, QWidget* bottom_row, + InputCommon::InputSubsystem* input_subsystem_, + InputProfiles* profiles_, Core::HID::HIDCore& hid_core_, + bool is_powered_on_, bool debug = false); + ~ConfigureInputPlayer() override; + + /// Save all button configurations to settings file. + void ApplyConfiguration(); + + /// Set the connection state checkbox (used to sync state). + void ConnectPlayer(bool connected); + + /// Update the input devices combobox. + void UpdateInputDeviceCombobox(); + + /// Updates the list of controller profiles. + void UpdateInputProfiles(); + + /// Restore all buttons to their default values. + void RestoreDefaults(); + + /// Clear all input configuration. + void ClearAll(); + +signals: + /// Emitted when this controller is (dis)connected by the user. + void Connected(bool connected); + /// Emitted when the Handheld mode is selected (undocked with dual joycons attached). + void HandheldStateChanged(bool is_handheld); + /// Emitted when the input devices combobox is being refreshed. + void RefreshInputDevices(); + /** + * Emitted when the input profiles combobox is being refreshed. + * The player_index represents the current player's index, and the profile combobox + * will not be updated for this index as they are already updated by other mechanisms. + */ + void RefreshInputProfiles(std::size_t player_index); + +protected: + void showEvent(QShowEvent* event) override; + +private: + QString ButtonToText(const Common::ParamPackage& param); + + QString AnalogToText(const Common::ParamPackage& param, const std::string& dir); + + void changeEvent(QEvent* event) override; + void RetranslateUI(); + + /// Load configuration settings. + void LoadConfiguration(); + + /// Called when the button was pressed. + void HandleClick(QPushButton* button, std::size_t button_id, + std::function new_input_setter, + InputCommon::Polling::InputType type); + + /// Finish polling and configure input using the input_setter. + void SetPollingResult(const Common::ParamPackage& params, bool abort); + + /// Checks whether a given input can be accepted. + bool IsInputAcceptable(const Common::ParamPackage& params) const; + + /// Handle mouse button press events. + void mousePressEvent(QMouseEvent* event) override; + + /// Handle mouse wheel move events. + void wheelEvent(QWheelEvent* event) override; + + /// Handle key press events. + void keyPressEvent(QKeyEvent* event) override; + + /// Handle combobox list refresh + bool eventFilter(QObject* object, QEvent* event) override; + + /// Update UI to reflect current configuration. + void UpdateUI(); + + /// Sets the available controllers. + void SetConnectableControllers(); + + /// Gets the Controller Type for a given controller combobox index. + Core::HID::NpadStyleIndex GetControllerTypeFromIndex(int index) const; + + /// Gets the controller combobox index for a given Controller Type. + int GetIndexFromControllerType(Core::HID::NpadStyleIndex type) const; + + /// Update the available input devices. + void UpdateInputDevices(); + + /// Hides and disables controller settings based on the current controller type. + void UpdateControllerAvailableButtons(); + + /// Disables controller settings based on the current controller type. + void UpdateControllerEnabledButtons(); + + /// Shows or hides motion groupboxes based on the current controller type. + void UpdateMotionButtons(); + + /// Alters the button names based on the current controller type. + void UpdateControllerButtonNames(); + + /// Gets the default controller mapping for this device and auto configures the input to match. + void UpdateMappingWithDefaults(); + + /// Creates a controller profile. + void CreateProfile(); + + /// Deletes the selected controller profile. + void DeleteProfile(); + + /// Loads the selected controller profile. + void LoadProfile(); + + /// Saves the current controller configuration into a selected controller profile. + void SaveProfile(); + + std::unique_ptr ui; + + std::size_t player_index; + bool debug; + bool is_powered_on; + + InputCommon::InputSubsystem* input_subsystem; + + InputProfiles* profiles; + + std::unique_ptr timeout_timer; + std::unique_ptr poll_timer; + + /// Stores a pair of "Connected Controllers" combobox index and Controller Type enum. + std::vector> index_controller_type_pairs; + + /// This will be the the setting function when an input is awaiting configuration. + std::optional> input_setter; + + Core::HID::EmulatedController* emulated_controller; + + static constexpr int ANALOG_SUB_BUTTONS_NUM = 4; + + /// Each button input is represented by a QPushButton. + std::array button_map; + + /// A group of four QPushButtons represent one analog input. The buttons each represent up, + /// down, left, right, respectively. + std::array, Settings::NativeAnalog::NumAnalogs> + analog_map_buttons; + + /// Each motion input is represented by a QPushButton. + std::array motion_map; + + std::array analog_map_deadzone_label; + std::array analog_map_deadzone_slider; + std::array analog_map_modifier_groupbox; + std::array analog_map_modifier_button; + std::array analog_map_modifier_label; + std::array analog_map_modifier_slider; + std::array analog_map_range_groupbox; + std::array analog_map_range_spinbox; + + static const std::array analog_sub_buttons; + + /// A flag to indicate that the "Map Analog Stick" pop-up has been shown and accepted once. + bool map_analog_stick_accepted{}; + + /// List of physical devices users can map with. If a SDL backed device is selected, then you + /// can use this device to get a default mapping. + std::vector input_devices; + + /// Bottom row is where console wide settings are held, and its "owned" by the parent + /// ConfigureInput widget. On show, add this widget to the main layout. This will change the + /// parent of the widget to this widget (but that's fine). + QWidget* bottom_row; + + Core::HID::HIDCore& hid_core; +}; diff --git a/src/sudachi/configuration/configure_input_player.ui b/src/sudachi/configuration/configure_input_player.ui new file mode 100644 index 0000000..1eec462 --- /dev/null +++ b/src/sudachi/configuration/configure_input_player.ui @@ -0,0 +1,3323 @@ + + + ConfigureInputPlayer + + + + 0 + 0 + 780 + 487 + + + + Configure Input + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + 3 + + + 0 + + + + + Qt::LeftToRight + + + Connect Controller + + + false + + + true + + + + 5 + + + 5 + + + 5 + + + 5 + + + + + + 0 + 21 + + + + + + + + + + + Input Device + + + + 3 + + + 5 + + + 5 + + + 5 + + + 5 + + + + + 60 + + + + + + + + + + + 0 + 0 + + + + Profile + + + + 3 + + + 5 + + + 5 + + + 5 + + + 5 + + + + + + 0 + 21 + + + + + + + + + 68 + 16777215 + + + + min-width: 68px; + + + Save + + + + + + + + 68 + 16777215 + + + + min-width: 68px; + + + New + + + + + + + + 68 + 16777215 + + + + min-width: 68px; + + + Delete + + + + + + + + + + + + + 0 + 0 + + + + + QLayout::SetMinimumSize + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 0 + + + QLayout::SetDefaultConstraint + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 0 + 0 + + + + Left Stick + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop + + + + 0 + + + QLayout::SetDefaultConstraint + + + 3 + + + 6 + + + 3 + + + 0 + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Qt::Horizontal + + + + 20 + 20 + + + + + + + + Up + + + Qt::AlignCenter + + + false + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + Up + + + + + + + + + + Qt::Horizontal + + + + 20 + 20 + + + + + + + + + + + 3 + + + + + Left + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + Left + + + + + + + + + + Right + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + Right + + + + + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Qt::Horizontal + + + + 20 + 20 + + + + + + + + Down + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + Down + + + + + + + + + + Qt::Horizontal + + + + 20 + 20 + + + + + + + + + + + 3 + + + + + Pressed + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + Pressed + + + + + + + + + + Modifier + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + Modifier + + + + + + + + + + Range + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 68 + 21 + + + + + 68 + 16777215 + + + + % + + + 25 + + + 150 + + + 95 + + + + + + + + + + + + 3 + + + QLayout::SetDefaultConstraint + + + 0 + + + 2 + + + 0 + + + 3 + + + + + + + Deadzone: 0% + + + Qt::AlignHCenter + + + + + + + + + 100 + + + Qt::Horizontal + + + + + + + + + Modifier Range: 0% + + + Qt::AlignHCenter + + + + + + + + + 100 + + + Qt::Horizontal + + + + + + + + + + + + Qt::Vertical + + + + 20 + 0 + + + + + + + + + 0 + 0 + + + + D-Pad + + + false + + + false + + + + 0 + + + 3 + + + 6 + + + 3 + + + 3 + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Qt::Horizontal + + + + 20 + 20 + + + + + + + + Up + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + Up + + + + + + + + + + Qt::Horizontal + + + + 20 + 20 + + + + + + + + + + + 3 + + + + + Left + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + Left + + + + + + + + + + Right + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + Right + + + + + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Qt::Horizontal + + + + 20 + 20 + + + + + + + + Down + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + Down + + + + + + + + + + Qt::Horizontal + + + + 20 + 20 + + + + + + + + + + + + + + Qt::Vertical + + + + 20 + 0 + + + + + + + + + + + + 6 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + 3 + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + SL + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + SL + + + + + + + + + + SR + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + SR + + + + + + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Qt::Horizontal + + + + 0 + 20 + + + + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + L + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + L + + + + + + + + + + + 0 + 0 + + + + ZL + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + ZL + + + + + + + + 70 + 15 + + + + 100 + + + Qt::Horizontal + + + + + + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Qt::Horizontal + + + + 0 + 20 + + + + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Minus + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + Minus + + + + + + + + + + Capture + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + Capture + + + + + + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Plus + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + Plus + + + + + + + + + + Home + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + Home + + + + + + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Qt::Horizontal + + + + 0 + 20 + + + + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + R + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + R + + + + + + + + + + + 0 + 0 + + + + ZR + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + ZR + + + + + + + + 70 + 15 + + + + 100 + + + Qt::Horizontal + + + + + + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Qt::Horizontal + + + + 0 + 20 + + + + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + SL + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + SL + + + + + + + + + + SR + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + SR + + + + + + + + + + + + + + + + 0 + 0 + + + + + 75 + true + + + + image: url(:/controller/pro); + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + + + 3 + + + 0 + + + + + Qt::Horizontal + + + + 20 + 20 + + + + + + + + Motion 1 + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + Left + + + + + + + + + + Motion 2 + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + Right + + + + + + + + + + Qt::Horizontal + + + + 20 + 20 + + + + + + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 0 + 0 + + + + Face Buttons + + + false + + + false + + + + 0 + + + 3 + + + 6 + + + 3 + + + 3 + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Qt::Horizontal + + + + 20 + 20 + + + + + + + + X + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + X + + + + + + + + + + Qt::Horizontal + + + + 20 + 20 + + + + + + + + + + + 3 + + + + + Y + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + Y + + + + + + + + + + A + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + A + + + + + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Qt::Horizontal + + + + 20 + 20 + + + + + + + + B + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + B + + + + + + + + + + Qt::Horizontal + + + + 20 + 20 + + + + + + + + + + + + + + Qt::Vertical + + + + 20 + 0 + + + + + + + + + 0 + 0 + + + + Right Stick + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter + + + false + + + false + + + + 0 + + + 3 + + + 6 + + + 3 + + + 0 + + + + + + 0 + 0 + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Qt::Horizontal + + + + 20 + 20 + + + + + + + + Up + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + Up + + + + + + + + + + Qt::Horizontal + + + + 20 + 20 + + + + + + + + + + + 3 + + + + + Left + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + Left + + + + + + + + + + Right + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + Right + + + + + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Qt::Horizontal + + + + 20 + 20 + + + + + + + + Down + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + Down + + + + + + + + + + Qt::Horizontal + + + + 20 + 20 + + + + + + + + + + + 3 + + + + + Pressed + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + Pressed + + + + + + + + + + Modifier + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 68 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + Modifier + + + + + + + + + + Range + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 68 + 21 + + + + + 68 + 16777215 + + + + % + + + 25 + + + 150 + + + 95 + + + + + + + + + + + + 3 + + + 0 + + + 2 + + + 0 + + + 3 + + + + + + + Deadzone: 0% + + + Qt::AlignHCenter + + + + + + + + + 100 + + + Qt::Horizontal + + + + + + + + + Modifier Range: 0% + + + Qt::AlignHCenter + + + + + + + + + 100 + + + Qt::Horizontal + + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 3 + + + + + Qt::Horizontal + + + + 20 + 20 + + + + + + + + Mouse panning + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + Configure + + + + + + + + + + Qt::Horizontal + + + + 20 + 20 + + + + + + + + + + + + + + Qt::Vertical + + + + 20 + 0 + + + + + + + + + + + + + + + + + PlayerControlPreview + QFrame +
sudachi/configuration/configure_input_player_widget.h
+ 1 +
+
+ + + + +
diff --git a/src/sudachi/configuration/configure_input_player_widget.cpp b/src/sudachi/configuration/configure_input_player_widget.cpp new file mode 100644 index 0000000..dca86d9 --- /dev/null +++ b/src/sudachi/configuration/configure_input_player_widget.cpp @@ -0,0 +1,3007 @@ +// SPDX-FileCopyrightText: Copyright 2020 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include +#include +#include + +#include "hid_core/frontend/emulated_controller.h" +#include "sudachi/configuration/configure_input_player_widget.h" + +PlayerControlPreview::PlayerControlPreview(QWidget* parent) : QFrame(parent) { + is_controller_set = false; + QTimer* timer = new QTimer(this); + connect(timer, &QTimer::timeout, this, QOverload<>::of(&PlayerControlPreview::UpdateInput)); + + // refresh at 60hz + timer->start(16); +} + +PlayerControlPreview::~PlayerControlPreview() { + UnloadController(); +}; + +void PlayerControlPreview::SetController(Core::HID::EmulatedController* controller_) { + UnloadController(); + is_controller_set = true; + controller = controller_; + Core::HID::ControllerUpdateCallback engine_callback{ + .on_change = [this](Core::HID::ControllerTriggerType type) { ControllerUpdate(type); }, + .is_npad_service = false, + }; + callback_key = controller->SetCallback(engine_callback); + ControllerUpdate(Core::HID::ControllerTriggerType::All); +} + +void PlayerControlPreview::UnloadController() { + if (is_controller_set) { + controller->DeleteCallback(callback_key); + is_controller_set = false; + } +} + +void PlayerControlPreview::BeginMappingButton(std::size_t button_id) { + button_mapping_index = button_id; + mapping_active = true; +} + +void PlayerControlPreview::BeginMappingAnalog(std::size_t stick_id) { + button_mapping_index = Settings::NativeButton::LStick + stick_id; + analog_mapping_index = stick_id; + mapping_active = true; +} + +void PlayerControlPreview::EndMapping() { + button_mapping_index = Settings::NativeButton::BUTTON_NS_END; + analog_mapping_index = Settings::NativeAnalog::NumAnalogs; + mapping_active = false; + blink_counter = 0; + ResetInputs(); +} + +void PlayerControlPreview::UpdateColors() { + if (QIcon::themeName().contains(QStringLiteral("dark")) || + QIcon::themeName().contains(QStringLiteral("midnight"))) { + colors.primary = QColor(204, 204, 204); + colors.button = QColor(35, 38, 41); + colors.button2 = QColor(26, 27, 30); + colors.slider_arrow = QColor(14, 15, 18); + colors.font2 = QColor(255, 255, 255); + colors.indicator = QColor(170, 238, 255); + colors.deadzone = QColor(204, 136, 136); + colors.slider_button = colors.button; + } + + if (QIcon::themeName().contains(QStringLiteral("dark"))) { + colors.outline = QColor(160, 160, 160); + } else if (QIcon::themeName().contains(QStringLiteral("midnight"))) { + colors.outline = QColor(145, 145, 145); + } else { + colors.outline = QColor(0, 0, 0); + colors.primary = QColor(225, 225, 225); + colors.button = QColor(109, 111, 114); + colors.button2 = QColor(77, 80, 84); + colors.slider_arrow = QColor(65, 68, 73); + colors.font2 = QColor(0, 0, 0); + colors.indicator = QColor(0, 0, 200); + colors.deadzone = QColor(170, 0, 0); + colors.slider_button = QColor(153, 149, 149); + } + + // Constant colors + colors.highlight = QColor(170, 0, 0); + colors.highlight2 = QColor(119, 0, 0); + colors.slider = QColor(103, 106, 110); + colors.transparent = QColor(0, 0, 0, 0); + colors.font = QColor(255, 255, 255); + colors.led_on = QColor(255, 255, 0); + colors.led_off = QColor(170, 238, 255); + colors.indicator2 = QColor(59, 165, 93); + colors.charging = QColor(250, 168, 26); + colors.button_turbo = QColor(217, 158, 4); + + colors.left = colors.primary; + colors.right = colors.primary; + + const auto color_left = controller->GetColorsValues()[0].body; + const auto color_right = controller->GetColorsValues()[1].body; + if (color_left != 0 && color_right != 0) { + colors.left = QColor(color_left); + colors.right = QColor(color_right); + } +} + +void PlayerControlPreview::ResetInputs() { + button_values.fill({ + .value = false, + }); + stick_values.fill({ + .x = {.value = 0, .properties = {0, 1, 0}}, + .y = {.value = 0, .properties = {0, 1, 0}}, + }); + trigger_values.fill({ + .analog = {.value = 0, .properties = {0, 1, 0}}, + .pressed = {.value = false}, + }); + update(); +} + +void PlayerControlPreview::ControllerUpdate(Core::HID::ControllerTriggerType type) { + if (type == Core::HID::ControllerTriggerType::All) { + ControllerUpdate(Core::HID::ControllerTriggerType::Color); + ControllerUpdate(Core::HID::ControllerTriggerType::Type); + ControllerUpdate(Core::HID::ControllerTriggerType::Connected); + ControllerUpdate(Core::HID::ControllerTriggerType::Button); + ControllerUpdate(Core::HID::ControllerTriggerType::Stick); + ControllerUpdate(Core::HID::ControllerTriggerType::Trigger); + ControllerUpdate(Core::HID::ControllerTriggerType::Battery); + return; + } + + switch (type) { + case Core::HID::ControllerTriggerType::Connected: + is_connected = true; + led_pattern = controller->GetLedPattern(); + needs_redraw = true; + break; + case Core::HID::ControllerTriggerType::Disconnected: + is_connected = false; + led_pattern.raw = 0; + needs_redraw = true; + break; + case Core::HID::ControllerTriggerType::Type: + controller_type = controller->GetNpadStyleIndex(true); + needs_redraw = true; + break; + case Core::HID::ControllerTriggerType::Color: + UpdateColors(); + needs_redraw = true; + break; + case Core::HID::ControllerTriggerType::Button: + button_values = controller->GetButtonsValues(); + needs_redraw = true; + break; + case Core::HID::ControllerTriggerType::Stick: + using namespace Settings::NativeAnalog; + stick_values = controller->GetSticksValues(); + // Y axis is inverted + stick_values[LStick].y.value = -stick_values[LStick].y.value; + stick_values[LStick].y.raw_value = -stick_values[LStick].y.raw_value; + stick_values[RStick].y.value = -stick_values[RStick].y.value; + stick_values[RStick].y.raw_value = -stick_values[RStick].y.raw_value; + needs_redraw = true; + break; + case Core::HID::ControllerTriggerType::Trigger: + trigger_values = controller->GetTriggersValues(); + needs_redraw = true; + break; + case Core::HID::ControllerTriggerType::Battery: + battery_values = controller->GetBatteryValues(); + needs_redraw = true; + break; + case Core::HID::ControllerTriggerType::Motion: + motion_values = controller->GetMotions(); + needs_redraw = true; + break; + default: + break; + } +} + +void PlayerControlPreview::UpdateInput() { + if (mapping_active) { + + for (std::size_t index = 0; index < button_values.size(); ++index) { + bool blink = index == button_mapping_index; + if (analog_mapping_index == Settings::NativeAnalog::NumAnalogs) { + blink &= blink_counter > 25; + } + if (button_values[index].value != blink) { + needs_redraw = true; + } + button_values[index].value = blink; + } + + for (std::size_t index = 0; index < stick_values.size(); ++index) { + const bool blink_analog = index == analog_mapping_index; + if (blink_analog) { + needs_redraw = true; + stick_values[index].x.value = blink_counter < 25 ? -blink_counter / 25.0f : 0; + stick_values[index].y.value = + blink_counter > 25 ? -(blink_counter - 25) / 25.0f : 0; + } + } + } + if (needs_redraw) { + update(); + } + + if (mapping_active) { + blink_counter = (blink_counter + 1) % 50; + } +} + +void PlayerControlPreview::paintEvent(QPaintEvent* event) { + QFrame::paintEvent(event); + QPainter p(this); + p.setRenderHint(QPainter::Antialiasing); + const QPointF center = rect().center(); + + switch (controller_type) { + case Core::HID::NpadStyleIndex::Handheld: + DrawHandheldController(p, center); + break; + case Core::HID::NpadStyleIndex::JoyconDual: + DrawDualController(p, center); + break; + case Core::HID::NpadStyleIndex::JoyconLeft: + DrawLeftController(p, center); + break; + case Core::HID::NpadStyleIndex::JoyconRight: + DrawRightController(p, center); + break; + case Core::HID::NpadStyleIndex::GameCube: + DrawGCController(p, center); + break; + case Core::HID::NpadStyleIndex::Fullkey: + default: + DrawProController(p, center); + break; + } +} + +void PlayerControlPreview::DrawLeftController(QPainter& p, const QPointF center) { + { + using namespace Settings::NativeButton; + + // Sideview left joystick + DrawJoystickSideview(p, center + QPoint(142, -69), + -stick_values[Settings::NativeAnalog::LStick].y.value, 1.15f, + button_values[LStick]); + + // Topview D-pad buttons + p.setPen(colors.outline); + button_color = colors.button; + DrawRoundButton(p, center + QPoint(-163, -21), button_values[DLeft], 11, 5, Direction::Up); + DrawRoundButton(p, center + QPoint(-117, -21), button_values[DRight], 11, 5, Direction::Up); + + // Topview left joystick + DrawJoystickSideview(p, center + QPointF(-140.5f, -28), + -stick_values[Settings::NativeAnalog::LStick].x.value + 15.0f, 1.15f, + button_values[LStick]); + + // Topview minus button + p.setPen(colors.outline); + button_color = colors.button; + DrawRoundButton(p, center + QPoint(-111, -22), button_values[Minus], 8, 4, Direction::Up, + 1); + + // Left trigger + DrawLeftTriggers(p, center, button_values[L]); + DrawRoundButton(p, center + QPoint(151, -146), button_values[L], 8, 4, Direction::Down); + DrawLeftZTriggers(p, center, button_values[ZL]); + + // Sideview D-pad buttons + DrawRoundButton(p, center + QPoint(135, 14), button_values[DLeft], 5, 11, Direction::Right); + DrawRoundButton(p, center + QPoint(135, 36), button_values[DDown], 5, 11, Direction::Right); + DrawRoundButton(p, center + QPoint(135, -10), button_values[DUp], 5, 11, Direction::Right); + DrawRoundButton(p, center + QPoint(135, 14), button_values[DRight], 5, 11, + Direction::Right); + DrawRoundButton(p, center + QPoint(135, 71), button_values[Screenshot], 3, 8, + Direction::Right, 1); + + // Sideview minus button + DrawRoundButton(p, center + QPoint(135, -118), button_values[Minus], 4, 2.66f, + Direction::Right, 1); + + // Sideview SL and SR buttons + button_color = colors.slider_button; + DrawRoundButton(p, center + QPoint(59, 52), button_values[SRLeft], 5, 12, Direction::Left); + DrawRoundButton(p, center + QPoint(59, -69), button_values[SLLeft], 5, 12, Direction::Left); + + DrawLeftBody(p, center); + + // Left trigger top view + DrawLeftTriggersTopView(p, center, button_values[L]); + DrawLeftZTriggersTopView(p, center, button_values[ZL]); + } + + { + // Draw joysticks + using namespace Settings::NativeAnalog; + DrawJoystick(p, + center + QPointF(9, -69) + + (QPointF(stick_values[LStick].x.value, stick_values[LStick].y.value) * 8), + 1.8f, button_values[Settings::NativeButton::LStick]); + DrawRawJoystick(p, center + QPointF(-140, 90), QPointF(0, 0)); + } + + { + // Draw motion cubes + using namespace Settings::NativeMotion; + p.setPen(colors.outline); + p.setBrush(colors.transparent); + Draw3dCube(p, center + QPointF(-140, 90), + motion_values[Settings::NativeMotion::MotionLeft].euler, 20.0f); + } + + using namespace Settings::NativeButton; + + // D-pad constants + const QPointF dpad_center = center + QPoint(9, 14); + constexpr int dpad_distance = 23; + constexpr int dpad_radius = 11; + constexpr float dpad_arrow_size = 1.2f; + + // D-pad buttons + p.setPen(colors.outline); + button_color = colors.button; + DrawCircleButton(p, dpad_center + QPoint(dpad_distance, 0), button_values[DRight], dpad_radius); + DrawCircleButton(p, dpad_center + QPoint(0, dpad_distance), button_values[DDown], dpad_radius); + DrawCircleButton(p, dpad_center + QPoint(0, -dpad_distance), button_values[DUp], dpad_radius); + DrawCircleButton(p, dpad_center + QPoint(-dpad_distance, 0), button_values[DLeft], dpad_radius); + + // D-pad arrows + p.setPen(colors.font2); + p.setBrush(colors.font2); + DrawArrow(p, dpad_center + QPoint(dpad_distance, 0), Direction::Right, dpad_arrow_size); + DrawArrow(p, dpad_center + QPoint(0, dpad_distance), Direction::Down, dpad_arrow_size); + DrawArrow(p, dpad_center + QPoint(0, -dpad_distance), Direction::Up, dpad_arrow_size); + DrawArrow(p, dpad_center + QPoint(-dpad_distance, 0), Direction::Left, dpad_arrow_size); + + // SR and SL buttons + p.setPen(colors.outline); + button_color = colors.slider_button; + DrawRoundButton(p, center + QPoint(155, 52), button_values[SRLeft], 5.2f, 12, Direction::None, + 4); + DrawRoundButton(p, center + QPoint(155, -69), button_values[SLLeft], 5.2f, 12, Direction::None, + 4); + + // SR and SL text + p.setPen(colors.transparent); + p.setBrush(colors.font2); + DrawSymbol(p, center + QPointF(155, 52), Symbol::SR, 1.0f); + DrawSymbol(p, center + QPointF(155, -69), Symbol::SL, 1.0f); + + // Minus button + button_color = colors.button; + DrawMinusButton(p, center + QPoint(39, -118), button_values[Minus], 16); + + // Screenshot button + DrawRoundButton(p, center + QPoint(26, 71), button_values[Screenshot], 8, 8); + p.setPen(colors.font2); + p.setBrush(colors.font2); + DrawCircle(p, center + QPoint(26, 71), 5); + + // Draw battery + DrawBattery(p, center + QPoint(-160, -140), + battery_values[Core::HID::EmulatedDeviceIndex::LeftIndex]); +} + +void PlayerControlPreview::DrawRightController(QPainter& p, const QPointF center) { + { + using namespace Settings::NativeButton; + + // Sideview right joystick + DrawJoystickSideview(p, center + QPoint(173 - 315, 11), + stick_values[Settings::NativeAnalog::RStick].y.value + 10.0f, 1.15f, + button_values[Settings::NativeButton::RStick]); + + // Topview right joystick + DrawJoystickSideview(p, center + QPointF(140, -28), + -stick_values[Settings::NativeAnalog::RStick].x.value + 15.0f, 1.15f, + button_values[RStick]); + + // Topview face buttons + p.setPen(colors.outline); + button_color = colors.button; + DrawRoundButton(p, center + QPoint(163, -21), button_values[A], 11, 5, Direction::Up); + DrawRoundButton(p, center + QPoint(140, -21), button_values[B], 11, 5, Direction::Up); + DrawRoundButton(p, center + QPoint(140, -21), button_values[X], 11, 5, Direction::Up); + DrawRoundButton(p, center + QPoint(117, -21), button_values[Y], 11, 5, Direction::Up); + + // Topview plus button + p.setPen(colors.outline); + button_color = colors.button; + DrawRoundButton(p, center + QPoint(111, -22), button_values[Plus], 8, 4, Direction::Up, 1); + DrawRoundButton(p, center + QPoint(111, -22), button_values[Plus], 2.66f, 4, Direction::Up, + 1); + + // Right trigger + p.setPen(colors.outline); + button_color = colors.button; + DrawRightTriggers(p, center, button_values[R]); + DrawRoundButton(p, center + QPoint(-151, -146), button_values[R], 8, 4, Direction::Down); + DrawRightZTriggers(p, center, button_values[ZR]); + + // Sideview face buttons + DrawRoundButton(p, center + QPoint(-135, -73), button_values[A], 5, 11, Direction::Left); + DrawRoundButton(p, center + QPoint(-135, -50), button_values[B], 5, 11, Direction::Left); + DrawRoundButton(p, center + QPoint(-135, -95), button_values[X], 5, 11, Direction::Left); + DrawRoundButton(p, center + QPoint(-135, -73), button_values[Y], 5, 11, Direction::Left); + + // Sideview home and plus button + DrawRoundButton(p, center + QPoint(-135, 66), button_values[Home], 3, 12, Direction::Left); + DrawRoundButton(p, center + QPoint(-135, -118), button_values[Plus], 4, 8, Direction::Left, + 1); + DrawRoundButton(p, center + QPoint(-135, -118), button_values[Plus], 4, 2.66f, + Direction::Left, 1); + + // Sideview SL and SR buttons + button_color = colors.slider_button; + DrawRoundButton(p, center + QPoint(-59, 52), button_values[SLRight], 5, 11, + Direction::Right); + DrawRoundButton(p, center + QPoint(-59, -69), button_values[SRRight], 5, 11, + Direction::Right); + + DrawRightBody(p, center); + + // Right trigger top view + DrawRightTriggersTopView(p, center, button_values[R]); + DrawRightZTriggersTopView(p, center, button_values[ZR]); + } + + { + // Draw joysticks + using namespace Settings::NativeAnalog; + DrawJoystick(p, + center + QPointF(-9, 11) + + (QPointF(stick_values[RStick].x.value, stick_values[RStick].y.value) * 8), + 1.8f, button_values[Settings::NativeButton::RStick]); + DrawRawJoystick(p, QPointF(0, 0), center + QPointF(140, 90)); + } + + { + // Draw motion cubes + using namespace Settings::NativeMotion; + p.setPen(colors.outline); + p.setBrush(colors.transparent); + Draw3dCube(p, center + QPointF(140, 90), + motion_values[Settings::NativeMotion::MotionRight].euler, 20.0f); + } + + using namespace Settings::NativeButton; + + // Face buttons constants + const QPointF face_center = center + QPoint(-9, -73); + constexpr int face_distance = 23; + constexpr int face_radius = 11; + constexpr float text_size = 1.1f; + + // Face buttons + p.setPen(colors.outline); + button_color = colors.button; + DrawCircleButton(p, face_center + QPoint(face_distance, 0), button_values[A], face_radius); + DrawCircleButton(p, face_center + QPoint(0, face_distance), button_values[B], face_radius); + DrawCircleButton(p, face_center + QPoint(0, -face_distance), button_values[X], face_radius); + DrawCircleButton(p, face_center + QPoint(-face_distance, 0), button_values[Y], face_radius); + + // Face buttons text + p.setPen(colors.transparent); + p.setBrush(colors.font); + DrawSymbol(p, face_center + QPoint(face_distance, 0), Symbol::A, text_size); + DrawSymbol(p, face_center + QPoint(0, face_distance), Symbol::B, text_size); + DrawSymbol(p, face_center + QPoint(0, -face_distance), Symbol::X, text_size); + DrawSymbol(p, face_center + QPoint(-face_distance, 1), Symbol::Y, text_size); + + // SR and SL buttons + p.setPen(colors.outline); + button_color = colors.slider_button; + DrawRoundButton(p, center + QPoint(-155, 52), button_values[SLRight], 5, 12, Direction::None, + 4.0f); + DrawRoundButton(p, center + QPoint(-155, -69), button_values[SRRight], 5, 12, Direction::None, + 4.0f); + + // SR and SL text + p.setPen(colors.transparent); + p.setBrush(colors.font2); + p.rotate(-180); + DrawSymbol(p, QPointF(-center.x(), -center.y()) + QPointF(155, 69), Symbol::SR, 1.0f); + DrawSymbol(p, QPointF(-center.x(), -center.y()) + QPointF(155, -52), Symbol::SL, 1.0f); + p.rotate(180); + + // Plus Button + DrawPlusButton(p, center + QPoint(-40, -118), button_values[Plus], 16); + + // Home Button + p.setPen(colors.outline); + button_color = colors.slider_button; + DrawCircleButton(p, center + QPoint(-26, 66), button_values[Home], 12); + button_color = colors.button; + DrawCircleButton(p, center + QPoint(-26, 66), button_values[Home], 9); + p.setPen(colors.transparent); + p.setBrush(colors.font2); + DrawSymbol(p, center + QPoint(-26, 66), Symbol::House, 5); + + // Draw battery + DrawBattery(p, center + QPoint(120, -140), + battery_values[Core::HID::EmulatedDeviceIndex::RightIndex]); +} + +void PlayerControlPreview::DrawDualController(QPainter& p, const QPointF center) { + { + using namespace Settings::NativeButton; + + // Left/Right trigger + DrawDualTriggers(p, center, button_values[L], button_values[R]); + + // Topview right joystick + DrawJoystickSideview(p, center + QPointF(180, -78), + -stick_values[Settings::NativeAnalog::RStick].x.value + 15.0f, 1, + button_values[RStick]); + + // Topview face buttons + p.setPen(colors.outline); + button_color = colors.button; + DrawRoundButton(p, center + QPoint(200, -71), button_values[A], 10, 5, Direction::Up); + DrawRoundButton(p, center + QPoint(180, -71), button_values[B], 10, 5, Direction::Up); + DrawRoundButton(p, center + QPoint(180, -71), button_values[X], 10, 5, Direction::Up); + DrawRoundButton(p, center + QPoint(160, -71), button_values[Y], 10, 5, Direction::Up); + + // Topview plus button + p.setPen(colors.outline); + button_color = colors.button; + DrawRoundButton(p, center + QPoint(154, -72), button_values[Plus], 7, 4, Direction::Up, 1); + DrawRoundButton(p, center + QPoint(154, -72), button_values[Plus], 2.33f, 4, Direction::Up, + 1); + + // Topview D-pad buttons + p.setPen(colors.outline); + button_color = colors.button; + DrawRoundButton(p, center + QPoint(-200, -71), button_values[DLeft], 10, 5, Direction::Up); + DrawRoundButton(p, center + QPoint(-160, -71), button_values[DRight], 10, 5, Direction::Up); + + // Topview left joystick + DrawJoystickSideview(p, center + QPointF(-180.5f, -78), + -stick_values[Settings::NativeAnalog::LStick].x.value + 15.0f, 1, + button_values[LStick]); + + // Topview minus button + p.setPen(colors.outline); + button_color = colors.button; + DrawRoundButton(p, center + QPoint(-154, -72), button_values[Minus], 7, 4, Direction::Up, + 1); + + // Left SR and SL sideview buttons + button_color = colors.slider_button; + DrawRoundButton(p, center + QPoint(-20, -62), button_values[SLLeft], 4, 11, + Direction::Left); + DrawRoundButton(p, center + QPoint(-20, 47), button_values[SRLeft], 4, 11, Direction::Left); + + // Right SR and SL sideview buttons + button_color = colors.slider_button; + DrawRoundButton(p, center + QPoint(20, 47), button_values[SLRight], 4, 11, + Direction::Right); + DrawRoundButton(p, center + QPoint(20, -62), button_values[SRRight], 4, 11, + Direction::Right); + + DrawDualBody(p, center); + + // Right trigger top view + DrawDualTriggersTopView(p, center, button_values[L], button_values[R]); + DrawDualZTriggersTopView(p, center, button_values[ZL], button_values[ZR]); + } + + { + // Draw joysticks + using namespace Settings::NativeAnalog; + const auto l_stick = QPointF(stick_values[LStick].x.value, stick_values[LStick].y.value); + const auto l_button = button_values[Settings::NativeButton::LStick]; + const auto r_stick = QPointF(stick_values[RStick].x.value, stick_values[RStick].y.value); + const auto r_button = button_values[Settings::NativeButton::RStick]; + + DrawJoystick(p, center + QPointF(-65, -65) + (l_stick * 7), 1.62f, l_button); + DrawJoystick(p, center + QPointF(65, 12) + (r_stick * 7), 1.62f, r_button); + DrawRawJoystick(p, center + QPointF(-180, 90), center + QPointF(180, 90)); + } + + { + // Draw motion cubes + using namespace Settings::NativeMotion; + p.setPen(colors.outline); + p.setBrush(colors.transparent); + Draw3dCube(p, center + QPointF(-180, 90), + motion_values[Settings::NativeMotion::MotionLeft].euler, 20.0f); + Draw3dCube(p, center + QPointF(180, 90), + motion_values[Settings::NativeMotion::MotionRight].euler, 20.0f); + } + + using namespace Settings::NativeButton; + + // Face buttons constants + const QPointF face_center = center + QPoint(65, -65); + constexpr int face_distance = 20; + constexpr int face_radius = 10; + constexpr float text_size = 1.0f; + + // Face buttons + p.setPen(colors.outline); + button_color = colors.button; + DrawCircleButton(p, face_center + QPoint(face_distance, 0), button_values[A], face_radius); + DrawCircleButton(p, face_center + QPoint(0, face_distance), button_values[B], face_radius); + DrawCircleButton(p, face_center + QPoint(0, -face_distance), button_values[X], face_radius); + DrawCircleButton(p, face_center + QPoint(-face_distance, 0), button_values[Y], face_radius); + + // Face buttons text + p.setPen(colors.transparent); + p.setBrush(colors.font); + DrawSymbol(p, face_center + QPoint(face_distance, 0), Symbol::A, text_size); + DrawSymbol(p, face_center + QPoint(0, face_distance), Symbol::B, text_size); + DrawSymbol(p, face_center + QPoint(0, -face_distance), Symbol::X, text_size); + DrawSymbol(p, face_center + QPoint(-face_distance, 1), Symbol::Y, text_size); + + // D-pad constants + const QPointF dpad_center = center + QPoint(-65, 12); + constexpr int dpad_distance = 20; + constexpr int dpad_radius = 10; + constexpr float dpad_arrow_size = 1.1f; + + // D-pad buttons + p.setPen(colors.outline); + button_color = colors.button; + DrawCircleButton(p, dpad_center + QPoint(dpad_distance, 0), button_values[DRight], dpad_radius); + DrawCircleButton(p, dpad_center + QPoint(0, dpad_distance), button_values[DDown], dpad_radius); + DrawCircleButton(p, dpad_center + QPoint(0, -dpad_distance), button_values[DUp], dpad_radius); + DrawCircleButton(p, dpad_center + QPoint(-dpad_distance, 0), button_values[DLeft], dpad_radius); + + // D-pad arrows + p.setPen(colors.font2); + p.setBrush(colors.font2); + DrawArrow(p, dpad_center + QPoint(dpad_distance, 0), Direction::Right, dpad_arrow_size); + DrawArrow(p, dpad_center + QPoint(0, dpad_distance), Direction::Down, dpad_arrow_size); + DrawArrow(p, dpad_center + QPoint(0, -dpad_distance), Direction::Up, dpad_arrow_size); + DrawArrow(p, dpad_center + QPoint(-dpad_distance, 0), Direction::Left, dpad_arrow_size); + + // Minus and Plus button + button_color = colors.button; + DrawMinusButton(p, center + QPoint(-39, -106), button_values[Minus], 14); + DrawPlusButton(p, center + QPoint(39, -106), button_values[Plus], 14); + + // Screenshot button + p.setPen(colors.outline); + DrawRoundButton(p, center + QPoint(-52, 63), button_values[Screenshot], 8, 8); + p.setPen(colors.font2); + p.setBrush(colors.font2); + DrawCircle(p, center + QPoint(-52, 63), 5); + + // Home Button + p.setPen(colors.outline); + button_color = colors.slider_button; + DrawCircleButton(p, center + QPoint(50, 60), button_values[Home], 11); + button_color = colors.button; + DrawCircleButton(p, center + QPoint(50, 60), button_values[Home], 8.5f); + p.setPen(colors.transparent); + p.setBrush(colors.font2); + DrawSymbol(p, center + QPoint(50, 60), Symbol::House, 4.2f); + + // Draw battery + DrawBattery(p, center + QPoint(-200, -10), + battery_values[Core::HID::EmulatedDeviceIndex::LeftIndex]); + DrawBattery(p, center + QPoint(160, -10), + battery_values[Core::HID::EmulatedDeviceIndex::RightIndex]); +} + +void PlayerControlPreview::DrawHandheldController(QPainter& p, const QPointF center) { + DrawHandheldTriggers(p, center, button_values[Settings::NativeButton::L], + button_values[Settings::NativeButton::R]); + DrawHandheldBody(p, center); + { + // Draw joysticks + using namespace Settings::NativeAnalog; + const auto l_stick = QPointF(stick_values[LStick].x.value, stick_values[LStick].y.value); + const auto l_button = button_values[Settings::NativeButton::LStick]; + const auto r_stick = QPointF(stick_values[RStick].x.value, stick_values[RStick].y.value); + const auto r_button = button_values[Settings::NativeButton::RStick]; + + DrawJoystick(p, center + QPointF(-171, -41) + (l_stick * 4), 1.0f, l_button); + DrawJoystick(p, center + QPointF(171, 8) + (r_stick * 4), 1.0f, r_button); + DrawRawJoystick(p, center + QPointF(-50, 0), center + QPointF(50, 0)); + } + + { + // Draw motion cubes + using namespace Settings::NativeMotion; + p.setPen(colors.outline); + p.setBrush(colors.transparent); + Draw3dCube(p, center + QPointF(0, -115), + motion_values[Settings::NativeMotion::MotionLeft].euler, 15.0f); + } + + using namespace Settings::NativeButton; + + // Face buttons constants + const QPointF face_center = center + QPoint(171, -41); + constexpr float face_distance = 12.8f; + constexpr float face_radius = 6.4f; + constexpr float text_size = 0.6f; + + // Face buttons + p.setPen(colors.outline); + button_color = colors.button; + DrawCircleButton(p, face_center + QPointF(face_distance, 0), button_values[A], face_radius); + DrawCircleButton(p, face_center + QPointF(0, face_distance), button_values[B], face_radius); + DrawCircleButton(p, face_center + QPointF(0, -face_distance), button_values[X], face_radius); + DrawCircleButton(p, face_center + QPointF(-face_distance, 0), button_values[Y], face_radius); + + // Face buttons text + p.setPen(colors.transparent); + p.setBrush(colors.font); + DrawSymbol(p, face_center + QPointF(face_distance, 0), Symbol::A, text_size); + DrawSymbol(p, face_center + QPointF(0, face_distance), Symbol::B, text_size); + DrawSymbol(p, face_center + QPointF(0, -face_distance), Symbol::X, text_size); + DrawSymbol(p, face_center + QPointF(-face_distance, 1), Symbol::Y, text_size); + + // D-pad constants + const QPointF dpad_center = center + QPoint(-171, 8); + constexpr float dpad_distance = 12.8f; + constexpr float dpad_radius = 6.4f; + constexpr float dpad_arrow_size = 0.68f; + + // D-pad buttons + p.setPen(colors.outline); + button_color = colors.button; + DrawCircleButton(p, dpad_center + QPointF(dpad_distance, 0), button_values[DRight], + dpad_radius); + DrawCircleButton(p, dpad_center + QPointF(0, dpad_distance), button_values[DDown], dpad_radius); + DrawCircleButton(p, dpad_center + QPointF(0, -dpad_distance), button_values[DUp], dpad_radius); + DrawCircleButton(p, dpad_center + QPointF(-dpad_distance, 0), button_values[DLeft], + dpad_radius); + + // D-pad arrows + p.setPen(colors.font2); + p.setBrush(colors.font2); + DrawArrow(p, dpad_center + QPointF(dpad_distance, 0), Direction::Right, dpad_arrow_size); + DrawArrow(p, dpad_center + QPointF(0, dpad_distance), Direction::Down, dpad_arrow_size); + DrawArrow(p, dpad_center + QPointF(0, -dpad_distance), Direction::Up, dpad_arrow_size); + DrawArrow(p, dpad_center + QPointF(-dpad_distance, 0), Direction::Left, dpad_arrow_size); + + // ZL and ZR buttons + p.setPen(colors.outline); + DrawTriggerButton(p, center + QPoint(-210, -120), Direction::Left, button_values[ZL]); + DrawTriggerButton(p, center + QPoint(210, -120), Direction::Right, button_values[ZR]); + p.setPen(colors.transparent); + p.setBrush(colors.font); + DrawSymbol(p, center + QPoint(-210, -120), Symbol::ZL, 1.5f); + DrawSymbol(p, center + QPoint(210, -120), Symbol::ZR, 1.5f); + + // Minus and Plus button + p.setPen(colors.outline); + button_color = colors.button; + DrawMinusButton(p, center + QPoint(-155, -67), button_values[Minus], 8); + DrawPlusButton(p, center + QPoint(155, -67), button_values[Plus], 8); + + // Screenshot button + p.setPen(colors.outline); + DrawRoundButton(p, center + QPoint(-162, 39), button_values[Screenshot], 5, 5); + p.setPen(colors.font2); + p.setBrush(colors.font2); + DrawCircle(p, center + QPoint(-162, 39), 3); + + // Home Button + p.setPen(colors.outline); + button_color = colors.slider_button; + DrawCircleButton(p, center + QPoint(161, 37), button_values[Home], 7); + button_color = colors.button; + DrawCircleButton(p, center + QPoint(161, 37), button_values[Home], 5); + p.setPen(colors.transparent); + p.setBrush(colors.font2); + DrawSymbol(p, center + QPoint(161, 37), Symbol::House, 2.75f); + + // Draw battery + DrawBattery(p, center + QPoint(-188, 95), + battery_values[Core::HID::EmulatedDeviceIndex::LeftIndex]); + DrawBattery(p, center + QPoint(150, 95), + battery_values[Core::HID::EmulatedDeviceIndex::RightIndex]); +} + +void PlayerControlPreview::DrawProController(QPainter& p, const QPointF center) { + DrawProTriggers(p, center, button_values[Settings::NativeButton::L], + button_values[Settings::NativeButton::R]); + DrawProBody(p, center); + { + // Draw joysticks + using namespace Settings::NativeAnalog; + const auto l_stick = QPointF(stick_values[LStick].x.value, stick_values[LStick].y.value); + const auto r_stick = QPointF(stick_values[RStick].x.value, stick_values[RStick].y.value); + DrawProJoystick(p, center + QPointF(-111, -55), l_stick, 11, + button_values[Settings::NativeButton::LStick]); + DrawProJoystick(p, center + QPointF(51, 0), r_stick, 11, + button_values[Settings::NativeButton::RStick]); + DrawRawJoystick(p, center + QPointF(-50, 105), center + QPointF(50, 105)); + } + + { + // Draw motion cubes + using namespace Settings::NativeMotion; + p.setPen(colors.button); + p.setBrush(colors.transparent); + Draw3dCube(p, center + QPointF(0, -100), + motion_values[Settings::NativeMotion::MotionLeft].euler, 15.0f); + } + + using namespace Settings::NativeButton; + + // Face buttons constants + const QPointF face_center = center + QPoint(105, -56); + constexpr int face_distance = 31; + constexpr int face_radius = 15; + constexpr float text_size = 1.5f; + + // Face buttons + p.setPen(colors.outline); + button_color = colors.button; + DrawCircleButton(p, face_center + QPoint(face_distance, 0), button_values[A], face_radius); + DrawCircleButton(p, face_center + QPoint(0, face_distance), button_values[B], face_radius); + DrawCircleButton(p, face_center + QPoint(0, -face_distance), button_values[X], face_radius); + DrawCircleButton(p, face_center + QPoint(-face_distance, 0), button_values[Y], face_radius); + + // Face buttons text + p.setPen(colors.transparent); + p.setBrush(colors.font); + DrawSymbol(p, face_center + QPoint(face_distance, 0), Symbol::A, text_size); + DrawSymbol(p, face_center + QPoint(0, face_distance), Symbol::B, text_size); + DrawSymbol(p, face_center + QPoint(0, -face_distance), Symbol::X, text_size); + DrawSymbol(p, face_center + QPoint(-face_distance, 1), Symbol::Y, text_size); + + // D-pad buttons + const QPointF dpad_position = center + QPoint(-61, 0); + DrawArrowButton(p, dpad_position, Direction::Up, button_values[DUp]); + DrawArrowButton(p, dpad_position, Direction::Left, button_values[DLeft]); + DrawArrowButton(p, dpad_position, Direction::Right, button_values[DRight]); + DrawArrowButton(p, dpad_position, Direction::Down, button_values[DDown]); + DrawArrowButtonOutline(p, dpad_position); + + // ZL and ZR buttons + p.setPen(colors.outline); + DrawTriggerButton(p, center + QPoint(-210, -120), Direction::Left, button_values[ZL]); + DrawTriggerButton(p, center + QPoint(210, -120), Direction::Right, button_values[ZR]); + p.setPen(colors.transparent); + p.setBrush(colors.font); + DrawSymbol(p, center + QPoint(-210, -120), Symbol::ZL, 1.5f); + DrawSymbol(p, center + QPoint(210, -120), Symbol::ZR, 1.5f); + + // Minus and Plus buttons + p.setPen(colors.outline); + DrawCircleButton(p, center + QPoint(-50, -86), button_values[Minus], 9); + DrawCircleButton(p, center + QPoint(50, -86), button_values[Plus], 9); + + // Minus and Plus symbols + p.setPen(colors.font2); + p.setBrush(colors.font2); + DrawRectangle(p, center + QPoint(-50, -86), 9, 1.5f); + DrawRectangle(p, center + QPoint(50, -86), 9, 1.5f); + DrawRectangle(p, center + QPoint(50, -86), 1.5f, 9); + + // Screenshot button + p.setPen(colors.outline); + DrawRoundButton(p, center + QPoint(-29, -56), button_values[Screenshot], 7, 7); + p.setPen(colors.font2); + p.setBrush(colors.font2); + DrawCircle(p, center + QPoint(-29, -56), 4.5f); + + // Home Button + p.setPen(colors.outline); + button_color = colors.slider_button; + DrawCircleButton(p, center + QPoint(29, -56), button_values[Home], 10.0f); + button_color = colors.button; + DrawCircleButton(p, center + QPoint(29, -56), button_values[Home], 7.1f); + p.setPen(colors.transparent); + p.setBrush(colors.font2); + DrawSymbol(p, center + QPoint(29, -56), Symbol::House, 3.9f); + + // Draw battery + DrawBattery(p, center + QPoint(-20, -160), + battery_values[Core::HID::EmulatedDeviceIndex::LeftIndex]); +} + +void PlayerControlPreview::DrawGCController(QPainter& p, const QPointF center) { + DrawGCTriggers(p, center, trigger_values[0], trigger_values[1]); + DrawGCButtonZ(p, center, button_values[Settings::NativeButton::R]); + DrawGCBody(p, center); + { + // Draw joysticks + using namespace Settings::NativeAnalog; + const auto l_stick = QPointF(stick_values[LStick].x.value, stick_values[LStick].y.value); + const auto r_stick = QPointF(stick_values[RStick].x.value, stick_values[RStick].y.value); + DrawGCJoystick(p, center + QPointF(-111, -44) + (l_stick * 10), {}); + button_color = colors.button2; + DrawCircleButton(p, center + QPointF(61, 37) + (r_stick * 9.5f), {}, 15); + p.setPen(colors.transparent); + p.setBrush(colors.font); + DrawSymbol(p, center + QPointF(61, 37) + (r_stick * 9.5f), Symbol::C, 1.0f); + DrawRawJoystick(p, center + QPointF(-198, -125), center + QPointF(198, -125)); + } + + using namespace Settings::NativeButton; + + // Face buttons constants + constexpr float text_size = 1.1f; + + // Face buttons + p.setPen(colors.outline); + button_color = colors.button; + DrawCircleButton(p, center + QPoint(111, -44), button_values[A], 21); + DrawCircleButton(p, center + QPoint(70, -23), button_values[B], 13); + DrawGCButtonX(p, center, button_values[Settings::NativeButton::X]); + DrawGCButtonY(p, center, button_values[Settings::NativeButton::Y]); + + // Face buttons text + p.setPen(colors.transparent); + p.setBrush(colors.font); + DrawSymbol(p, center + QPoint(111, -44), Symbol::A, 1.5f); + DrawSymbol(p, center + QPoint(70, -23), Symbol::B, text_size); + DrawSymbol(p, center + QPoint(151, -53), Symbol::X, text_size); + DrawSymbol(p, center + QPoint(100, -83), Symbol::Y, text_size); + + // D-pad buttons + const QPointF dpad_position = center + QPoint(-61, 37); + const float dpad_size = 0.8f; + DrawArrowButton(p, dpad_position, Direction::Up, button_values[DUp], dpad_size); + DrawArrowButton(p, dpad_position, Direction::Left, button_values[DLeft], dpad_size); + DrawArrowButton(p, dpad_position, Direction::Right, button_values[DRight], dpad_size); + DrawArrowButton(p, dpad_position, Direction::Down, button_values[DDown], dpad_size); + DrawArrowButtonOutline(p, dpad_position, dpad_size); + + // Minus and Plus buttons + p.setPen(colors.outline); + DrawCircleButton(p, center + QPoint(0, -44), button_values[Plus], 8); + + // Draw battery + DrawBattery(p, center + QPoint(-20, 110), + battery_values[Core::HID::EmulatedDeviceIndex::LeftIndex]); +} + +constexpr std::array symbol_a = { + -1.085f, -5.2f, 1.085f, -5.2f, 5.085f, 5.0f, 2.785f, 5.0f, 1.785f, + 2.65f, -1.785f, 2.65f, -2.785f, 5.0f, -5.085f, 5.0f, -1.4f, 1.0f, + 0.0f, -2.8f, 1.4f, 1.0f, -1.4f, 1.0f, -5.085f, 5.0f, +}; +constexpr std::array symbol_b = { + -4.0f, 0.0f, -4.0f, 0.0f, -4.0f, -0.1f, -3.8f, -5.1f, 1.8f, -5.0f, 2.3f, -4.9f, 2.6f, + -4.8f, 2.8f, -4.7f, 2.9f, -4.6f, 3.1f, -4.5f, 3.2f, -4.4f, 3.4f, -4.3f, 3.4f, -4.2f, + 3.5f, -4.1f, 3.7f, -4.0f, 3.7f, -3.9f, 3.8f, -3.8f, 3.8f, -3.7f, 3.9f, -3.6f, 3.9f, + -3.5f, 4.0f, -3.4f, 4.0f, -3.3f, 4.1f, -3.1f, 4.1f, -3.0f, 4.0f, -2.0f, 4.0f, -1.9f, + 3.9f, -1.7f, 3.9f, -1.6f, 3.8f, -1.5f, 3.8f, -1.4f, 3.7f, -1.3f, 3.7f, -1.2f, 3.6f, + -1.1f, 3.6f, -1.0f, 3.5f, -0.9f, 3.3f, -0.8f, 3.3f, -0.7f, 3.2f, -0.6f, 3.0f, -0.5f, + 2.9f, -0.4f, 2.7f, -0.3f, 2.9f, -0.2f, 3.2f, -0.1f, 3.3f, 0.0f, 3.5f, 0.1f, 3.6f, + 0.2f, 3.8f, 0.3f, 3.9f, 0.4f, 4.0f, 0.6f, 4.1f, 0.7f, 4.3f, 0.8f, 4.3f, 0.9f, + 4.4f, 1.0f, 4.4f, 1.1f, 4.5f, 1.3f, 4.5f, 1.4f, 4.6f, 1.6f, 4.6f, 1.7f, 4.5f, + 2.8f, 4.5f, 2.9f, 4.4f, 3.1f, 4.4f, 3.2f, 4.3f, 3.4f, 4.3f, 3.5f, 4.2f, 3.6f, + 4.2f, 3.7f, 4.1f, 3.8f, 4.1f, 3.9f, 4.0f, 4.0f, 3.9f, 4.2f, 3.8f, 4.3f, 3.6f, + 4.4f, 3.6f, 4.5f, 3.4f, 4.6f, 3.3f, 4.7f, 3.1f, 4.8f, 2.8f, 4.9f, 2.6f, 5.0f, + 2.1f, 5.1f, -4.0f, 5.0f, -4.0f, 4.9f, + + -4.0f, 0.0f, 1.1f, 3.4f, 1.1f, 3.4f, 1.5f, 3.3f, 1.8f, 3.2f, 2.0f, 3.1f, 2.1f, + 3.0f, 2.3f, 2.9f, 2.3f, 2.8f, 2.4f, 2.7f, 2.4f, 2.6f, 2.5f, 2.3f, 2.5f, 2.2f, + 2.4f, 1.7f, 2.4f, 1.6f, 2.3f, 1.4f, 2.3f, 1.3f, 2.2f, 1.2f, 2.2f, 1.1f, 2.1f, + 1.0f, 1.9f, 0.9f, 1.6f, 0.8f, 1.4f, 0.7f, -1.9f, 0.6f, -1.9f, 0.7f, -1.8f, 3.4f, + 1.1f, 3.4f, -4.0f, 0.0f, + + 0.3f, -1.1f, 0.3f, -1.1f, 1.3f, -1.2f, 1.5f, -1.3f, 1.8f, -1.4f, 1.8f, -1.5f, 1.9f, + -1.6f, 2.0f, -1.8f, 2.0f, -1.9f, 2.1f, -2.0f, 2.1f, -2.1f, 2.0f, -2.7f, 2.0f, -2.8f, + 1.9f, -2.9f, 1.9f, -3.0f, 1.8f, -3.1f, 1.6f, -3.2f, 1.6f, -3.3f, 1.3f, -3.4f, -1.9f, + -3.3f, -1.9f, -3.2f, -1.8f, -1.0f, 0.2f, -1.1f, 0.3f, -1.1f, -4.0f, 0.0f, +}; + +constexpr std::array symbol_y = { + -4.79f, -4.9f, -2.44f, -4.9f, 0.0f, -0.9f, 2.44f, -4.9f, 4.79f, + -4.9f, 1.05f, 1.0f, 1.05f, 5.31f, -1.05f, 5.31f, -1.05f, 1.0f, + +}; + +constexpr std::array symbol_x = { + -4.4f, -5.0f, -2.0f, -5.0f, 0.0f, -1.7f, 2.0f, -5.0f, 4.4f, -5.0f, 1.2f, 0.0f, + 4.4f, 5.0f, 2.0f, 5.0f, 0.0f, 1.7f, -2.0f, 5.0f, -4.4f, 5.0f, -1.2f, 0.0f, + +}; + +constexpr std::array symbol_l = { + 2.4f, -3.23f, 2.4f, 2.1f, 5.43f, 2.1f, 5.43f, 3.22f, 0.98f, 3.22f, 0.98f, -3.23f, 2.4f, -3.23f, +}; + +constexpr std::array symbol_r = { + 1.0f, 0.0f, 1.0f, -0.1f, 1.1f, -3.3f, 4.3f, -3.2f, 5.1f, -3.1f, 5.4f, -3.0f, 5.6f, -2.9f, + 5.7f, -2.8f, 5.9f, -2.7f, 5.9f, -2.6f, 6.0f, -2.5f, 6.1f, -2.3f, 6.2f, -2.2f, 6.2f, -2.1f, + 6.3f, -2.0f, 6.3f, -1.9f, 6.2f, -0.8f, 6.2f, -0.7f, 6.1f, -0.6f, 6.1f, -0.5f, 6.0f, -0.4f, + 6.0f, -0.3f, 5.9f, -0.2f, 5.7f, -0.1f, 5.7f, 0.0f, 5.6f, 0.1f, 5.4f, 0.2f, 5.1f, 0.3f, + 4.7f, 0.4f, 4.7f, 0.5f, 4.9f, 0.6f, 5.0f, 0.7f, 5.2f, 0.8f, 5.2f, 0.9f, 5.3f, 1.0f, + 5.5f, 1.1f, 5.5f, 1.2f, 5.6f, 1.3f, 5.7f, 1.5f, 5.8f, 1.6f, 5.9f, 1.8f, 6.0f, 1.9f, + 6.1f, 2.1f, 6.2f, 2.2f, 6.2f, 2.3f, 6.3f, 2.4f, 6.4f, 2.6f, 6.5f, 2.7f, 6.6f, 2.9f, + 6.7f, 3.0f, 6.7f, 3.1f, 6.8f, 3.2f, 6.8f, 3.3f, 5.3f, 3.2f, 5.2f, 3.1f, 5.2f, 3.0f, + 5.1f, 2.9f, 5.0f, 2.7f, 4.9f, 2.6f, 4.8f, 2.4f, 4.7f, 2.3f, 4.6f, 2.1f, 4.5f, 2.0f, + 4.4f, 1.8f, 4.3f, 1.7f, 4.1f, 1.4f, 4.0f, 1.3f, 3.9f, 1.1f, 3.8f, 1.0f, 3.6f, 0.9f, + 3.6f, 0.8f, 3.5f, 0.7f, 3.3f, 0.6f, 2.9f, 0.5f, 2.3f, 0.6f, 2.3f, 0.7f, 2.2f, 3.3f, + 1.0f, 3.2f, 1.0f, 3.1f, 1.0f, 0.0f, + + 4.2f, -0.5f, 4.4f, -0.6f, 4.7f, -0.7f, 4.8f, -0.8f, 4.9f, -1.0f, 5.0f, -1.1f, 5.0f, -1.2f, + 4.9f, -1.7f, 4.9f, -1.8f, 4.8f, -1.9f, 4.8f, -2.0f, 4.6f, -2.1f, 4.3f, -2.2f, 2.3f, -2.1f, + 2.3f, -2.0f, 2.4f, -0.5f, 4.2f, -0.5f, 1.0f, 0.0f, +}; + +constexpr std::array symbol_zl = { + -2.6f, -2.13f, -5.6f, -2.13f, -5.6f, -3.23f, -0.8f, -3.23f, -0.8f, -2.13f, -4.4f, 2.12f, + -0.7f, 2.12f, -0.7f, 3.22f, -6.0f, 3.22f, -6.0f, 2.12f, 2.4f, -3.23f, 2.4f, 2.1f, + 5.43f, 2.1f, 5.43f, 3.22f, 0.98f, 3.22f, 0.98f, -3.23f, 2.4f, -3.23f, -6.0f, 2.12f, +}; + +constexpr std::array symbol_sl = { + -3.0f, -3.65f, -2.76f, -4.26f, -2.33f, -4.76f, -1.76f, -5.09f, -1.13f, -5.26f, -0.94f, + -4.77f, -0.87f, -4.11f, -1.46f, -3.88f, -1.91f, -3.41f, -2.05f, -2.78f, -1.98f, -2.13f, + -1.59f, -1.61f, -0.96f, -1.53f, -0.56f, -2.04f, -0.38f, -2.67f, -0.22f, -3.31f, 0.0f, + -3.93f, 0.34f, -4.49f, 0.86f, -4.89f, 1.49f, -5.05f, 2.14f, -4.95f, 2.69f, -4.6f, + 3.07f, -4.07f, 3.25f, -3.44f, 3.31f, -2.78f, 3.25f, -2.12f, 3.07f, -1.49f, 2.7f, + -0.95f, 2.16f, -0.58f, 1.52f, -0.43f, 1.41f, -0.99f, 1.38f, -1.65f, 1.97f, -1.91f, + 2.25f, -2.49f, 2.25f, -3.15f, 1.99f, -3.74f, 1.38f, -3.78f, 1.06f, -3.22f, 0.88f, + -2.58f, 0.71f, -1.94f, 0.49f, -1.32f, 0.13f, -0.77f, -0.4f, -0.4f, -1.04f, -0.25f, + -1.69f, -0.32f, -2.28f, -0.61f, -2.73f, -1.09f, -2.98f, -1.69f, -3.09f, -2.34f, + + 3.23f, 2.4f, -2.1f, 2.4f, -2.1f, 5.43f, -3.22f, 5.43f, -3.22f, 0.98f, 3.23f, + 0.98f, 3.23f, 2.4f, -3.09f, -2.34f, +}; +constexpr std::array symbol_zr = { + -2.6f, -2.13f, -5.6f, -2.13f, -5.6f, -3.23f, -0.8f, -3.23f, -0.8f, -2.13f, -4.4f, 2.12f, -0.7f, + 2.12f, -0.7f, 3.22f, -6.0f, 3.22f, -6.0f, 2.12f, + + 1.0f, 0.0f, 1.0f, -0.1f, 1.1f, -3.3f, 4.3f, -3.2f, 5.1f, -3.1f, 5.4f, -3.0f, 5.6f, + -2.9f, 5.7f, -2.8f, 5.9f, -2.7f, 5.9f, -2.6f, 6.0f, -2.5f, 6.1f, -2.3f, 6.2f, -2.2f, + 6.2f, -2.1f, 6.3f, -2.0f, 6.3f, -1.9f, 6.2f, -0.8f, 6.2f, -0.7f, 6.1f, -0.6f, 6.1f, + -0.5f, 6.0f, -0.4f, 6.0f, -0.3f, 5.9f, -0.2f, 5.7f, -0.1f, 5.7f, 0.0f, 5.6f, 0.1f, + 5.4f, 0.2f, 5.1f, 0.3f, 4.7f, 0.4f, 4.7f, 0.5f, 4.9f, 0.6f, 5.0f, 0.7f, 5.2f, + 0.8f, 5.2f, 0.9f, 5.3f, 1.0f, 5.5f, 1.1f, 5.5f, 1.2f, 5.6f, 1.3f, 5.7f, 1.5f, + 5.8f, 1.6f, 5.9f, 1.8f, 6.0f, 1.9f, 6.1f, 2.1f, 6.2f, 2.2f, 6.2f, 2.3f, 6.3f, + 2.4f, 6.4f, 2.6f, 6.5f, 2.7f, 6.6f, 2.9f, 6.7f, 3.0f, 6.7f, 3.1f, 6.8f, 3.2f, + 6.8f, 3.3f, 5.3f, 3.2f, 5.2f, 3.1f, 5.2f, 3.0f, 5.1f, 2.9f, 5.0f, 2.7f, 4.9f, + 2.6f, 4.8f, 2.4f, 4.7f, 2.3f, 4.6f, 2.1f, 4.5f, 2.0f, 4.4f, 1.8f, 4.3f, 1.7f, + 4.1f, 1.4f, 4.0f, 1.3f, 3.9f, 1.1f, 3.8f, 1.0f, 3.6f, 0.9f, 3.6f, 0.8f, 3.5f, + 0.7f, 3.3f, 0.6f, 2.9f, 0.5f, 2.3f, 0.6f, 2.3f, 0.7f, 2.2f, 3.3f, 1.0f, 3.2f, + 1.0f, 3.1f, 1.0f, 0.0f, + + 4.2f, -0.5f, 4.4f, -0.6f, 4.7f, -0.7f, 4.8f, -0.8f, 4.9f, -1.0f, 5.0f, -1.1f, 5.0f, + -1.2f, 4.9f, -1.7f, 4.9f, -1.8f, 4.8f, -1.9f, 4.8f, -2.0f, 4.6f, -2.1f, 4.3f, -2.2f, + 2.3f, -2.1f, 2.3f, -2.0f, 2.4f, -0.5f, 4.2f, -0.5f, 1.0f, 0.0f, -6.0f, 2.12f, +}; + +constexpr std::array symbol_sr = { + -3.0f, -3.65f, -2.76f, -4.26f, -2.33f, -4.76f, -1.76f, -5.09f, -1.13f, -5.26f, -0.94f, -4.77f, + -0.87f, -4.11f, -1.46f, -3.88f, -1.91f, -3.41f, -2.05f, -2.78f, -1.98f, -2.13f, -1.59f, -1.61f, + -0.96f, -1.53f, -0.56f, -2.04f, -0.38f, -2.67f, -0.22f, -3.31f, 0.0f, -3.93f, 0.34f, -4.49f, + 0.86f, -4.89f, 1.49f, -5.05f, 2.14f, -4.95f, 2.69f, -4.6f, 3.07f, -4.07f, 3.25f, -3.44f, + 3.31f, -2.78f, 3.25f, -2.12f, 3.07f, -1.49f, 2.7f, -0.95f, 2.16f, -0.58f, 1.52f, -0.43f, + 1.41f, -0.99f, 1.38f, -1.65f, 1.97f, -1.91f, 2.25f, -2.49f, 2.25f, -3.15f, 1.99f, -3.74f, + 1.38f, -3.78f, 1.06f, -3.22f, 0.88f, -2.58f, 0.71f, -1.94f, 0.49f, -1.32f, 0.13f, -0.77f, + -0.4f, -0.4f, -1.04f, -0.25f, -1.69f, -0.32f, -2.28f, -0.61f, -2.73f, -1.09f, -2.98f, -1.69f, + -3.09f, -2.34f, + + -1.0f, 0.0f, 0.1f, 1.0f, 3.3f, 1.1f, 3.2f, 4.3f, 3.1f, 5.1f, 3.0f, 5.4f, + 2.9f, 5.6f, 2.8f, 5.7f, 2.7f, 5.9f, 2.6f, 5.9f, 2.5f, 6.0f, 2.3f, 6.1f, + 2.2f, 6.2f, 2.1f, 6.2f, 2.0f, 6.3f, 1.9f, 6.3f, 0.8f, 6.2f, 0.7f, 6.2f, + 0.6f, 6.1f, 0.5f, 6.1f, 0.4f, 6.0f, 0.3f, 6.0f, 0.2f, 5.9f, 0.1f, 5.7f, + 0.0f, 5.7f, -0.1f, 5.6f, -0.2f, 5.4f, -0.3f, 5.1f, -0.4f, 4.7f, -0.5f, 4.7f, + -0.6f, 4.9f, -0.7f, 5.0f, -0.8f, 5.2f, -0.9f, 5.2f, -1.0f, 5.3f, -1.1f, 5.5f, + -1.2f, 5.5f, -1.3f, 5.6f, -1.5f, 5.7f, -1.6f, 5.8f, -1.8f, 5.9f, -1.9f, 6.0f, + -2.1f, 6.1f, -2.2f, 6.2f, -2.3f, 6.2f, -2.4f, 6.3f, -2.6f, 6.4f, -2.7f, 6.5f, + -2.9f, 6.6f, -3.0f, 6.7f, -3.1f, 6.7f, -3.2f, 6.8f, -3.3f, 6.8f, -3.2f, 5.3f, + -3.1f, 5.2f, -3.0f, 5.2f, -2.9f, 5.1f, -2.7f, 5.0f, -2.6f, 4.9f, -2.4f, 4.8f, + -2.3f, 4.7f, -2.1f, 4.6f, -2.0f, 4.5f, -1.8f, 4.4f, -1.7f, 4.3f, -1.4f, 4.1f, + -1.3f, 4.0f, -1.1f, 3.9f, -1.0f, 3.8f, -0.9f, 3.6f, -0.8f, 3.6f, -0.7f, 3.5f, + -0.6f, 3.3f, -0.5f, 2.9f, -0.6f, 2.3f, -0.7f, 2.3f, -3.3f, 2.2f, -3.2f, 1.0f, + -3.1f, 1.0f, 0.0f, 1.0f, + + 0.5f, 4.2f, 0.6f, 4.4f, 0.7f, 4.7f, 0.8f, 4.8f, 1.0f, 4.9f, 1.1f, 5.0f, + 1.2f, 5.0f, 1.7f, 4.9f, 1.8f, 4.9f, 1.9f, 4.8f, 2.0f, 4.8f, 2.1f, 4.6f, + 2.2f, 4.3f, 2.1f, 2.3f, 2.0f, 2.3f, 0.5f, 2.4f, 0.5f, 4.2f, -0.0f, 1.0f, + -3.09f, -2.34f, + +}; + +constexpr std::array symbol_c = { + 2.86f, 7.57f, 0.99f, 7.94f, -0.91f, 7.87f, -2.73f, 7.31f, -4.23f, 6.14f, -5.2f, 4.51f, + -5.65f, 2.66f, -5.68f, 0.75f, -5.31f, -1.12f, -4.43f, -2.81f, -3.01f, -4.08f, -1.24f, -4.78f, + 0.66f, -4.94f, 2.54f, -4.67f, 4.33f, -4.0f, 4.63f, -2.27f, 3.37f, -2.7f, 1.6f, -3.4f, + -0.3f, -3.5f, -2.09f, -2.87f, -3.34f, -1.45f, -3.91f, 0.37f, -3.95f, 2.27f, -3.49f, 4.12f, + -2.37f, 5.64f, -0.65f, 6.44f, 1.25f, 6.47f, 3.06f, 5.89f, 4.63f, 4.92f, 4.63f, 6.83f, +}; + +constexpr std::array symbol_charging = { + 6.5f, -1.0f, 1.0f, -1.0f, 1.0f, -3.0f, -6.5f, 1.0f, -1.0f, 1.0f, -1.0f, 3.0f, +}; + +constexpr std::array house = { + -1.3f, 0.0f, -0.93f, 0.0f, -0.93f, 1.15f, 0.93f, 1.15f, 0.93f, 0.0f, 1.3f, 0.0f, + 0.0f, -1.2f, -1.3f, 0.0f, -0.43f, 0.0f, -0.43f, .73f, 0.43f, .73f, 0.43f, 0.0f, +}; + +constexpr std::array up_arrow_button = { + 9.1f, -9.1f, 9.1f, -30.0f, 8.1f, -30.1f, 7.7f, -30.1f, -8.6f, -30.0f, -9.0f, + -29.8f, -9.3f, -29.5f, -9.5f, -29.1f, -9.1f, -28.7f, -9.1f, -9.1f, 0.0f, 0.6f, +}; + +constexpr std::array up_arrow_symbol = { + 0.0f, -3.0f, -3.0f, 2.0f, 3.0f, 2.0f, +}; + +constexpr std::array trigger_button = { + 5.5f, -12.6f, 5.8f, -12.6f, 6.7f, -12.5f, 8.1f, -12.3f, 8.6f, -12.2f, 9.2f, -12.0f, + 9.5f, -11.9f, 9.9f, -11.8f, 10.6f, -11.5f, 11.0f, -11.3f, 11.2f, -11.2f, 11.4f, -11.1f, + 11.8f, -10.9f, 12.0f, -10.8f, 12.2f, -10.7f, 12.4f, -10.5f, 12.6f, -10.4f, 12.8f, -10.3f, + 13.6f, -9.7f, 13.8f, -9.6f, 13.9f, -9.4f, 14.1f, -9.3f, 14.8f, -8.6f, 15.0f, -8.5f, + 15.1f, -8.3f, 15.6f, -7.8f, 15.7f, -7.6f, 16.1f, -7.0f, 16.3f, -6.8f, 16.4f, -6.6f, + 16.5f, -6.4f, 16.8f, -6.0f, 16.9f, -5.8f, 17.0f, -5.6f, 17.1f, -5.4f, 17.2f, -5.2f, + 17.3f, -5.0f, 17.4f, -4.8f, 17.5f, -4.6f, 17.6f, -4.4f, 17.7f, -4.1f, 17.8f, -3.9f, + 17.9f, -3.5f, 18.0f, -3.3f, 18.1f, -3.0f, 18.2f, -2.6f, 18.2f, -2.3f, 18.3f, -2.1f, + 18.3f, -1.9f, 18.4f, -1.4f, 18.5f, -1.2f, 18.6f, -0.3f, 18.6f, 0.0f, 18.3f, 13.9f, + -17.0f, 13.8f, -17.0f, 13.6f, -16.4f, -11.4f, -16.3f, -11.6f, -16.1f, -11.8f, -15.7f, -12.0f, + -15.5f, -12.1f, -15.1f, -12.3f, -14.6f, -12.4f, -13.4f, -12.5f, +}; + +constexpr std::array pro_left_trigger = { + -65.2f, -132.6f, -68.2f, -134.1f, -71.3f, -135.5f, -74.4f, -136.7f, -77.6f, + -137.6f, -80.9f, -138.1f, -84.3f, -138.3f, -87.6f, -138.3f, -91.0f, -138.1f, + -94.3f, -137.8f, -97.6f, -137.3f, -100.9f, -136.7f, -107.5f, -135.3f, -110.7f, + -134.5f, -120.4f, -131.8f, -123.6f, -130.8f, -126.8f, -129.7f, -129.9f, -128.5f, + -132.9f, -127.1f, -135.9f, -125.6f, -138.8f, -123.9f, -141.6f, -122.0f, -144.1f, + -119.8f, -146.3f, -117.3f, -148.4f, -114.7f, -150.4f, -112.0f, -152.3f, -109.2f, + -155.3f, -104.0f, -152.0f, -104.3f, -148.7f, -104.5f, -145.3f, -104.8f, -35.5f, + -117.2f, -38.5f, -118.7f, -41.4f, -120.3f, -44.4f, -121.8f, -50.4f, -124.9f, +}; + +constexpr std::array pro_body_top = { + 0.0f, -115.4f, -4.4f, -116.1f, -69.7f, -131.3f, -66.4f, -131.9f, -63.1f, -132.3f, + -56.4f, -133.0f, -53.1f, -133.3f, -49.8f, -133.5f, -43.1f, -133.8f, -39.8f, -134.0f, + -36.5f, -134.1f, -16.4f, -134.4f, -13.1f, -134.4f, 0.0f, -134.1f, +}; + +constexpr std::array pro_left_handle = { + -178.7f, -47.5f, -179.0f, -46.1f, -179.3f, -44.6f, -182.0f, -29.8f, -182.3f, -28.4f, + -182.6f, -26.9f, -182.8f, -25.4f, -183.1f, -23.9f, -183.3f, -22.4f, -183.6f, -21.0f, + -183.8f, -19.5f, -184.1f, -18.0f, -184.3f, -16.5f, -184.6f, -15.1f, -184.8f, -13.6f, + -185.1f, -12.1f, -185.3f, -10.6f, -185.6f, -9.1f, -185.8f, -7.7f, -186.1f, -6.2f, + -186.3f, -4.7f, -186.6f, -3.2f, -186.8f, -1.7f, -187.1f, -0.3f, -187.3f, 1.2f, + -187.6f, 2.7f, -187.8f, 4.2f, -188.3f, 7.1f, -188.5f, 8.6f, -188.8f, 10.1f, + -189.0f, 11.6f, -189.3f, 13.1f, -189.5f, 14.5f, -190.0f, 17.5f, -190.2f, 19.0f, + -190.5f, 20.5f, -190.7f, 21.9f, -191.2f, 24.9f, -191.4f, 26.4f, -191.7f, 27.9f, + -191.9f, 29.3f, -192.4f, 32.3f, -192.6f, 33.8f, -193.1f, 36.8f, -193.3f, 38.2f, + -193.8f, 41.2f, -194.0f, 42.7f, -194.7f, 47.1f, -194.9f, 48.6f, -199.0f, 82.9f, + -199.1f, 84.4f, -199.1f, 85.9f, -199.2f, 87.4f, -199.2f, 88.9f, -199.1f, 94.9f, + -198.9f, 96.4f, -198.8f, 97.8f, -198.5f, 99.3f, -198.3f, 100.8f, -198.0f, 102.3f, + -197.7f, 103.7f, -197.4f, 105.2f, -197.0f, 106.7f, -196.6f, 108.1f, -195.7f, 111.0f, + -195.2f, 112.4f, -194.1f, 115.2f, -193.5f, 116.5f, -192.8f, 117.9f, -192.1f, 119.2f, + -190.6f, 121.8f, -189.8f, 123.1f, -188.9f, 124.3f, -187.0f, 126.6f, -186.0f, 127.7f, + -183.9f, 129.8f, -182.7f, 130.8f, -180.3f, 132.6f, -179.1f, 133.4f, -177.8f, 134.1f, + -176.4f, 134.8f, -175.1f, 135.5f, -173.7f, 136.0f, -169.4f, 137.3f, -167.9f, 137.7f, + -166.5f, 138.0f, -165.0f, 138.3f, -163.5f, 138.4f, -162.0f, 138.4f, -160.5f, 138.3f, + -159.0f, 138.0f, -157.6f, 137.7f, -156.1f, 137.3f, -154.7f, 136.9f, -153.2f, 136.5f, + -151.8f, 136.0f, -150.4f, 135.4f, -149.1f, 134.8f, -147.7f, 134.1f, -146.5f, 133.3f, + -145.2f, 132.5f, -144.0f, 131.6f, -142.8f, 130.6f, -141.7f, 129.6f, -139.6f, 127.5f, + -138.6f, 126.4f, -137.7f, 125.2f, -135.1f, 121.5f, -134.3f, 120.3f, -133.5f, 119.0f, + -131.9f, 116.5f, -131.1f, 115.2f, -128.8f, 111.3f, -128.0f, 110.1f, -127.2f, 108.8f, + -126.5f, 107.5f, -125.7f, 106.2f, -125.0f, 104.9f, -124.2f, 103.6f, -123.5f, 102.3f, + -122.0f, 99.6f, -121.3f, 98.3f, -115.8f, 87.7f, -115.1f, 86.4f, -114.4f, 85.0f, + -113.7f, 83.7f, -112.3f, 81.0f, -111.6f, 79.7f, -110.1f, 77.1f, -109.4f, 75.8f, + -108.0f, 73.1f, -107.2f, 71.8f, -106.4f, 70.6f, -105.7f, 69.3f, -104.8f, 68.0f, + -104.0f, 66.8f, -103.1f, 65.6f, -101.1f, 63.3f, -100.0f, 62.3f, -98.8f, 61.4f, + -97.6f, 60.6f, -97.9f, 59.5f, -98.8f, 58.3f, -101.5f, 54.6f, -102.4f, 53.4f, +}; + +constexpr std::array pro_body = { + -0.7f, -129.1f, -54.3f, -129.1f, -55.0f, -129.1f, -57.8f, -129.0f, -58.5f, -129.0f, + -60.7f, -128.9f, -61.4f, -128.9f, -62.8f, -128.8f, -63.5f, -128.8f, -65.7f, -128.7f, + -66.4f, -128.7f, -67.8f, -128.6f, -68.5f, -128.6f, -69.2f, -128.5f, -70.0f, -128.5f, + -70.7f, -128.4f, -71.4f, -128.4f, -72.1f, -128.3f, -72.8f, -128.3f, -73.5f, -128.2f, + -74.2f, -128.2f, -74.9f, -128.1f, -75.7f, -128.1f, -76.4f, -128.0f, -77.1f, -128.0f, + -77.8f, -127.9f, -78.5f, -127.9f, -79.2f, -127.8f, -80.6f, -127.7f, -81.4f, -127.6f, + -82.1f, -127.5f, -82.8f, -127.5f, -83.5f, -127.4f, -84.9f, -127.3f, -85.6f, -127.2f, + -87.0f, -127.1f, -87.7f, -127.0f, -88.5f, -126.9f, -89.2f, -126.8f, -89.9f, -126.8f, + -90.6f, -126.7f, -94.1f, -126.3f, -94.8f, -126.2f, -113.2f, -123.3f, -113.9f, -123.2f, + -114.6f, -123.0f, -115.3f, -122.9f, -116.7f, -122.6f, -117.4f, -122.5f, -118.1f, -122.3f, + -118.8f, -122.2f, -119.5f, -122.0f, -120.9f, -121.7f, -121.6f, -121.5f, -122.3f, -121.4f, + -122.9f, -121.2f, -123.6f, -121.0f, -126.4f, -120.3f, -127.1f, -120.1f, -127.8f, -119.8f, + -128.4f, -119.6f, -129.1f, -119.4f, -131.2f, -118.7f, -132.5f, -118.3f, -133.2f, -118.0f, + -133.8f, -117.7f, -134.5f, -117.4f, -135.1f, -117.2f, -135.8f, -116.9f, -136.4f, -116.5f, + -137.0f, -116.2f, -137.7f, -115.8f, -138.3f, -115.4f, -138.9f, -115.1f, -139.5f, -114.7f, + -160.0f, -100.5f, -160.5f, -100.0f, -162.5f, -97.9f, -162.9f, -97.4f, -163.4f, -96.8f, + -163.8f, -96.2f, -165.3f, -93.8f, -165.7f, -93.2f, -166.0f, -92.6f, -166.4f, -91.9f, + -166.7f, -91.3f, -167.3f, -90.0f, -167.6f, -89.4f, -167.8f, -88.7f, -168.1f, -88.0f, + -168.4f, -87.4f, -168.6f, -86.7f, -168.9f, -86.0f, -169.1f, -85.4f, -169.3f, -84.7f, + -169.6f, -84.0f, -169.8f, -83.3f, -170.2f, -82.0f, -170.4f, -81.3f, -172.8f, -72.3f, + -173.0f, -71.6f, -173.5f, -69.5f, -173.7f, -68.8f, -173.9f, -68.2f, -174.0f, -67.5f, + -174.2f, -66.8f, -174.5f, -65.4f, -174.7f, -64.7f, -174.8f, -64.0f, -175.0f, -63.3f, + -175.3f, -61.9f, -175.5f, -61.2f, -175.8f, -59.8f, -176.0f, -59.1f, -176.1f, -58.4f, + -176.3f, -57.7f, -176.6f, -56.3f, -176.8f, -55.6f, -176.9f, -54.9f, -177.1f, -54.2f, + -177.3f, -53.6f, -177.4f, -52.9f, -177.6f, -52.2f, -177.9f, -50.8f, -178.1f, -50.1f, + -178.2f, -49.4f, -178.2f, -48.7f, -177.8f, -48.1f, -177.1f, -46.9f, -176.7f, -46.3f, + -176.4f, -45.6f, -176.0f, -45.0f, -175.3f, -43.8f, -174.9f, -43.2f, -174.2f, -42.0f, + -173.4f, -40.7f, -173.1f, -40.1f, -172.7f, -39.5f, -172.0f, -38.3f, -171.6f, -37.7f, + -170.5f, -35.9f, -170.1f, -35.3f, -169.7f, -34.6f, -169.3f, -34.0f, -168.6f, -32.8f, + -168.2f, -32.2f, -166.3f, -29.2f, -165.9f, -28.6f, -163.2f, -24.4f, -162.8f, -23.8f, + -141.8f, 6.8f, -141.4f, 7.4f, -139.4f, 10.3f, -139.0f, 10.9f, -138.5f, 11.5f, + -138.1f, 12.1f, -137.3f, 13.2f, -136.9f, 13.8f, -136.0f, 15.0f, -135.6f, 15.6f, + -135.2f, 16.1f, -134.8f, 16.7f, -133.9f, 17.9f, -133.5f, 18.4f, -133.1f, 19.0f, + -131.8f, 20.7f, -131.4f, 21.3f, -130.1f, 23.0f, -129.7f, 23.6f, -128.4f, 25.3f, + -128.0f, 25.9f, -126.7f, 27.6f, -126.3f, 28.2f, -125.4f, 29.3f, -125.0f, 29.9f, + -124.1f, 31.0f, -123.7f, 31.6f, -122.8f, 32.7f, -122.4f, 33.3f, -121.5f, 34.4f, + -121.1f, 35.0f, -120.6f, 35.6f, -120.2f, 36.1f, -119.7f, 36.7f, -119.3f, 37.2f, + -118.9f, 37.8f, -118.4f, 38.4f, -118.0f, 38.9f, -117.5f, 39.5f, -117.1f, 40.0f, + -116.6f, 40.6f, -116.2f, 41.1f, -115.7f, 41.7f, -115.2f, 42.2f, -114.8f, 42.8f, + -114.3f, 43.3f, -113.9f, 43.9f, -113.4f, 44.4f, -112.4f, 45.5f, -112.0f, 46.0f, + -111.5f, 46.5f, -110.5f, 47.6f, -110.0f, 48.1f, -109.6f, 48.6f, -109.1f, 49.2f, + -108.6f, 49.7f, -107.7f, 50.8f, -107.2f, 51.3f, -105.7f, 52.9f, -105.3f, 53.4f, + -104.8f, 53.9f, -104.3f, 54.5f, -103.8f, 55.0f, -100.7f, 58.0f, -100.2f, 58.4f, + -99.7f, 58.9f, -99.1f, 59.3f, -97.2f, 60.3f, -96.5f, 60.1f, -95.9f, 59.7f, + -95.3f, 59.4f, -94.6f, 59.1f, -93.9f, 58.9f, -92.6f, 58.5f, -91.9f, 58.4f, + -91.2f, 58.2f, -90.5f, 58.1f, -89.7f, 58.0f, -89.0f, 57.9f, -86.2f, 57.6f, + -85.5f, 57.5f, -84.1f, 57.4f, -83.4f, 57.3f, -82.6f, 57.3f, -81.9f, 57.2f, + -81.2f, 57.2f, -80.5f, 57.1f, -79.8f, 57.1f, -78.4f, 57.0f, -77.7f, 57.0f, + -75.5f, 56.9f, -74.8f, 56.9f, -71.9f, 56.8f, -71.2f, 56.8f, 0.0f, 56.8f, +}; + +constexpr std::array gc_body = { + 0.0f, -138.03f, -4.91f, -138.01f, -8.02f, -137.94f, -11.14f, -137.82f, -14.25f, + -137.67f, -17.37f, -137.48f, -20.48f, -137.25f, -23.59f, -137.0f, -26.69f, -136.72f, + -29.8f, -136.41f, -32.9f, -136.07f, -35.99f, -135.71f, -39.09f, -135.32f, -42.18f, + -134.91f, -45.27f, -134.48f, -48.35f, -134.03f, -51.43f, -133.55f, -54.51f, -133.05f, + -57.59f, -132.52f, -60.66f, -131.98f, -63.72f, -131.41f, -66.78f, -130.81f, -69.84f, + -130.2f, -72.89f, -129.56f, -75.94f, -128.89f, -78.98f, -128.21f, -82.02f, -127.49f, + -85.05f, -126.75f, -88.07f, -125.99f, -91.09f, -125.19f, -94.1f, -124.37f, -97.1f, + -123.52f, -100.09f, -122.64f, -103.07f, -121.72f, -106.04f, -120.77f, -109.0f, -119.79f, + -111.95f, -118.77f, -114.88f, -117.71f, -117.8f, -116.61f, -120.7f, -115.46f, -123.58f, + -114.27f, -126.44f, -113.03f, -129.27f, -111.73f, -132.08f, -110.38f, -134.86f, -108.96f, + -137.6f, -107.47f, -140.3f, -105.91f, -142.95f, -104.27f, -145.55f, -102.54f, -148.07f, + -100.71f, -150.51f, -98.77f, -152.86f, -96.71f, -155.09f, -94.54f, -157.23f, -92.27f, + -159.26f, -89.9f, -161.2f, -87.46f, -163.04f, -84.94f, -164.78f, -82.35f, -166.42f, + -79.7f, -167.97f, -77.0f, -169.43f, -74.24f, -170.8f, -71.44f, -172.09f, -68.6f, + -173.29f, -65.72f, -174.41f, -62.81f, -175.45f, -59.87f, -176.42f, -56.91f, -177.31f, + -53.92f, -178.14f, -50.91f, -178.9f, -47.89f, -179.6f, -44.85f, -180.24f, -41.8f, + -180.82f, -38.73f, -181.34f, -35.66f, -181.8f, -32.57f, -182.21f, -29.48f, -182.57f, + -26.38f, -182.88f, -23.28f, -183.15f, -20.17f, -183.36f, -17.06f, -183.54f, -13.95f, + -183.71f, -10.84f, -184.0f, -7.73f, -184.23f, -4.62f, -184.44f, -1.51f, -184.62f, + 1.6f, -184.79f, 4.72f, -184.95f, 7.83f, -185.11f, 10.95f, -185.25f, 14.06f, + -185.38f, 17.18f, -185.51f, 20.29f, -185.63f, 23.41f, -185.74f, 26.53f, -185.85f, + 29.64f, -185.95f, 32.76f, -186.04f, 35.88f, -186.12f, 39.0f, -186.19f, 42.11f, + -186.26f, 45.23f, -186.32f, 48.35f, -186.37f, 51.47f, -186.41f, 54.59f, -186.44f, + 57.7f, -186.46f, 60.82f, -186.46f, 63.94f, -186.44f, 70.18f, -186.41f, 73.3f, + -186.36f, 76.42f, -186.3f, 79.53f, -186.22f, 82.65f, -186.12f, 85.77f, -185.99f, + 88.88f, -185.84f, 92.0f, -185.66f, 95.11f, -185.44f, 98.22f, -185.17f, 101.33f, + -184.85f, 104.43f, -184.46f, 107.53f, -183.97f, 110.61f, -183.37f, 113.67f, -182.65f, + 116.7f, -181.77f, 119.69f, -180.71f, 122.62f, -179.43f, 125.47f, -177.89f, 128.18f, + -176.05f, 130.69f, -173.88f, 132.92f, -171.36f, 134.75f, -168.55f, 136.1f, -165.55f, + 136.93f, -162.45f, 137.29f, -156.23f, 137.03f, -153.18f, 136.41f, -150.46f, 134.9f, + -148.14f, 132.83f, -146.14f, 130.43f, -144.39f, 127.85f, -142.83f, 125.16f, -141.41f, + 122.38f, -140.11f, 119.54f, -138.9f, 116.67f, -137.77f, 113.76f, -136.7f, 110.84f, + -135.68f, 107.89f, -134.71f, 104.93f, -133.77f, 101.95f, -132.86f, 98.97f, -131.97f, + 95.98f, -131.09f, 92.99f, -130.23f, 89.99f, -129.36f, 86.99f, -128.49f, 84.0f, + -127.63f, 81.0f, -126.76f, 78.01f, -125.9f, 75.01f, -124.17f, 69.02f, -123.31f, + 66.02f, -121.59f, 60.03f, -120.72f, 57.03f, -119.86f, 54.03f, -118.13f, 48.04f, + -117.27f, 45.04f, -115.55f, 39.05f, -114.68f, 36.05f, -113.82f, 33.05f, -112.96f, + 30.06f, -110.4f, 28.29f, -107.81f, 26.55f, -105.23f, 24.8f, -97.48f, 19.55f, + -94.9f, 17.81f, -92.32f, 16.06f, -87.15f, 12.56f, -84.57f, 10.81f, -81.99f, + 9.07f, -79.4f, 7.32f, -76.82f, 5.57f, -69.07f, 0.33f, -66.49f, -1.42f, + -58.74f, -6.66f, -56.16f, -8.41f, -48.4f, -13.64f, -45.72f, -15.22f, -42.93f, + -16.62f, -40.07f, -17.86f, -37.15f, -18.96f, -34.19f, -19.94f, -31.19f, -20.79f, + -28.16f, -21.55f, -25.12f, -22.21f, -22.05f, -22.79f, -18.97f, -23.28f, -15.88f, + -23.7f, -12.78f, -24.05f, -9.68f, -24.33f, -6.57f, -24.55f, -3.45f, -24.69f, + 0.0f, -24.69f, +}; + +constexpr std::array gc_left_body = { + -74.59f, -97.22f, -70.17f, -94.19f, -65.95f, -90.89f, -62.06f, -87.21f, -58.58f, + -83.14f, -55.58f, -78.7f, -53.08f, -73.97f, -51.05f, -69.01f, -49.46f, -63.89f, + -48.24f, -58.67f, -47.36f, -53.39f, -46.59f, -48.09f, -45.7f, -42.8f, -44.69f, + -37.54f, -43.54f, -32.31f, -42.25f, -27.11f, -40.8f, -21.95f, -39.19f, -16.84f, + -37.38f, -11.8f, -35.34f, -6.84f, -33.04f, -2.0f, -30.39f, 2.65f, -27.26f, + 7.0f, -23.84f, 11.11f, -21.19f, 15.76f, -19.18f, 20.73f, -17.73f, 25.88f, + -16.82f, 31.16f, -16.46f, 36.5f, -16.7f, 41.85f, -17.63f, 47.13f, -19.31f, + 52.21f, -21.8f, 56.95f, -24.91f, 61.3f, -28.41f, 65.36f, -32.28f, 69.06f, + -36.51f, 72.35f, -41.09f, 75.13f, -45.97f, 77.32f, -51.1f, 78.86f, -56.39f, + 79.7f, -61.74f, 79.84f, -67.07f, 79.3f, -72.3f, 78.15f, -77.39f, 76.48f, + -82.29f, 74.31f, -86.76f, 71.37f, -90.7f, 67.75f, -94.16f, 63.66f, -97.27f, + 59.3f, -100.21f, 54.81f, -103.09f, 50.3f, -106.03f, 45.82f, -109.11f, 41.44f, + -112.37f, 37.19f, -115.85f, 33.11f, -119.54f, 29.22f, -123.45f, 25.56f, -127.55f, + 22.11f, -131.77f, 18.81f, -136.04f, 15.57f, -140.34f, 12.37f, -144.62f, 9.15f, + -148.86f, 5.88f, -153.03f, 2.51f, -157.05f, -1.03f, -160.83f, -4.83f, -164.12f, + -9.05f, -166.71f, -13.73f, -168.91f, -18.62f, -170.77f, -23.64f, -172.3f, -28.78f, + -173.49f, -34.0f, -174.3f, -39.3f, -174.72f, -44.64f, -174.72f, -49.99f, -174.28f, + -55.33f, -173.37f, -60.61f, -172.0f, -65.79f, -170.17f, -70.82f, -167.79f, -75.62f, + -164.84f, -80.09f, -161.43f, -84.22f, -157.67f, -88.03f, -153.63f, -91.55f, -149.37f, + -94.81f, -144.94f, -97.82f, -140.37f, -100.61f, -135.65f, -103.16f, -130.73f, -105.26f, + -125.62f, -106.86f, -120.37f, -107.95f, -115.05f, -108.56f, -109.7f, -108.69f, -104.35f, + -108.36f, -99.05f, -107.6f, -93.82f, -106.41f, -88.72f, -104.79f, -83.78f, -102.7f, +}; + +constexpr std::array left_gc_trigger = { + -99.69f, -125.04f, -101.81f, -126.51f, -104.02f, -127.85f, -106.3f, -129.06f, -108.65f, + -130.12f, -111.08f, -130.99f, -113.58f, -131.62f, -116.14f, -131.97f, -121.26f, -131.55f, + -123.74f, -130.84f, -126.17f, -129.95f, -128.53f, -128.9f, -130.82f, -127.71f, -133.03f, + -126.38f, -135.15f, -124.92f, -137.18f, -123.32f, -139.11f, -121.6f, -140.91f, -119.75f, + -142.55f, -117.77f, -144.0f, -115.63f, -145.18f, -113.34f, -146.17f, -110.95f, -147.05f, + -108.53f, -147.87f, -106.08f, -148.64f, -103.61f, -149.37f, -101.14f, -149.16f, -100.12f, + -147.12f, -101.71f, -144.99f, -103.16f, -142.8f, -104.53f, -140.57f, -105.83f, -138.31f, + -107.08f, -136.02f, -108.27f, -133.71f, -109.42f, -131.38f, -110.53f, -129.04f, -111.61f, + -126.68f, -112.66f, -124.31f, -113.68f, -121.92f, -114.67f, -119.53f, -115.64f, -117.13f, + -116.58f, -114.72f, -117.51f, -112.3f, -118.41f, -109.87f, -119.29f, -107.44f, -120.16f, + -105.0f, -121.0f, -100.11f, -122.65f, +}; + +constexpr std::array gc_button_x = { + 142.1f, -50.67f, 142.44f, -48.65f, 142.69f, -46.62f, 142.8f, -44.57f, 143.0f, -42.54f, + 143.56f, -40.57f, 144.42f, -38.71f, 145.59f, -37.04f, 147.08f, -35.64f, 148.86f, -34.65f, + 150.84f, -34.11f, 152.88f, -34.03f, 154.89f, -34.38f, 156.79f, -35.14f, 158.49f, -36.28f, + 159.92f, -37.74f, 161.04f, -39.45f, 161.85f, -41.33f, 162.4f, -43.3f, 162.72f, -45.32f, + 162.85f, -47.37f, 162.82f, -49.41f, 162.67f, -51.46f, 162.39f, -53.48f, 162.0f, -55.5f, + 161.51f, -57.48f, 160.9f, -59.44f, 160.17f, -61.35f, 159.25f, -63.18f, 158.19f, -64.93f, + 157.01f, -66.61f, 155.72f, -68.2f, 154.31f, -69.68f, 152.78f, -71.04f, 151.09f, -72.2f, + 149.23f, -73.04f, 147.22f, -73.36f, 145.19f, -73.11f, 143.26f, -72.42f, 141.51f, -71.37f, + 140.0f, -69.99f, 138.82f, -68.32f, 138.13f, -66.4f, 138.09f, -64.36f, 138.39f, -62.34f, + 139.05f, -60.41f, 139.91f, -58.55f, 140.62f, -56.63f, 141.21f, -54.67f, 141.67f, -52.67f, +}; + +constexpr std::array gc_button_y = { + 104.02f, -75.23f, 106.01f, -75.74f, 108.01f, -76.15f, 110.04f, -76.42f, 112.05f, -76.78f, + 113.97f, -77.49f, 115.76f, -78.49f, 117.33f, -79.79f, 118.6f, -81.39f, 119.46f, -83.25f, + 119.84f, -85.26f, 119.76f, -87.3f, 119.24f, -89.28f, 118.33f, -91.11f, 117.06f, -92.71f, + 115.49f, -94.02f, 113.7f, -95.01f, 111.77f, -95.67f, 109.76f, -96.05f, 107.71f, -96.21f, + 105.67f, -96.18f, 103.63f, -95.99f, 101.61f, -95.67f, 99.61f, -95.24f, 97.63f, -94.69f, + 95.69f, -94.04f, 93.79f, -93.28f, 91.94f, -92.4f, 90.19f, -91.34f, 88.53f, -90.14f, + 86.95f, -88.84f, 85.47f, -87.42f, 84.1f, -85.9f, 82.87f, -84.26f, 81.85f, -82.49f, + 81.15f, -80.57f, 81.0f, -78.54f, 81.41f, -76.54f, 82.24f, -74.67f, 83.43f, -73.01f, + 84.92f, -71.61f, 86.68f, -70.57f, 88.65f, -70.03f, 90.69f, -70.15f, 92.68f, -70.61f, + 94.56f, -71.42f, 96.34f, -72.43f, 98.2f, -73.29f, 100.11f, -74.03f, 102.06f, -74.65f, +}; + +constexpr std::array gc_button_z = { + 95.74f, -126.41f, 98.34f, -126.38f, 100.94f, -126.24f, 103.53f, -126.01f, 106.11f, -125.7f, + 108.69f, -125.32f, 111.25f, -124.87f, 113.8f, -124.34f, 116.33f, -123.73f, 118.84f, -123.05f, + 121.33f, -122.3f, 123.79f, -121.47f, 126.23f, -120.56f, 128.64f, -119.58f, 131.02f, -118.51f, + 133.35f, -117.37f, 135.65f, -116.14f, 137.9f, -114.84f, 140.1f, -113.46f, 142.25f, -111.99f, + 144.35f, -110.45f, 146.38f, -108.82f, 148.35f, -107.13f, 150.25f, -105.35f, 151.89f, -103.38f, + 151.43f, -100.86f, 149.15f, -100.15f, 146.73f, -101.06f, 144.36f, -102.12f, 141.98f, -103.18f, + 139.6f, -104.23f, 137.22f, -105.29f, 134.85f, -106.35f, 132.47f, -107.41f, 127.72f, -109.53f, + 125.34f, -110.58f, 122.96f, -111.64f, 120.59f, -112.7f, 118.21f, -113.76f, 113.46f, -115.88f, + 111.08f, -116.93f, 108.7f, -117.99f, 106.33f, -119.05f, 103.95f, -120.11f, 99.2f, -122.23f, + 96.82f, -123.29f, 94.44f, -124.34f, +}; + +constexpr std::array left_joycon_body = { + -145.0f, -78.9f, -145.0f, -77.9f, -145.0f, 85.6f, -145.0f, 85.6f, -168.3f, 85.5f, + -169.3f, 85.4f, -171.3f, 85.1f, -172.3f, 84.9f, -173.4f, 84.7f, -174.3f, 84.5f, + -175.3f, 84.2f, -176.3f, 83.8f, -177.3f, 83.5f, -178.2f, 83.1f, -179.2f, 82.7f, + -180.1f, 82.2f, -181.0f, 81.8f, -181.9f, 81.3f, -182.8f, 80.7f, -183.7f, 80.2f, + -184.5f, 79.6f, -186.2f, 78.3f, -186.9f, 77.7f, -187.7f, 77.0f, -189.2f, 75.6f, + -189.9f, 74.8f, -190.6f, 74.1f, -191.3f, 73.3f, -191.9f, 72.5f, -192.5f, 71.6f, + -193.1f, 70.8f, -193.7f, 69.9f, -194.3f, 69.1f, -194.8f, 68.2f, -196.2f, 65.5f, + -196.6f, 64.5f, -197.0f, 63.6f, -197.4f, 62.6f, -198.1f, 60.7f, -198.4f, 59.7f, + -198.6f, 58.7f, -199.2f, 55.6f, -199.3f, 54.6f, -199.5f, 51.5f, -199.5f, 50.5f, + -199.5f, -49.4f, -199.4f, -50.5f, -199.3f, -51.5f, -199.1f, -52.5f, -198.2f, -56.5f, + -197.9f, -57.5f, -197.2f, -59.4f, -196.8f, -60.4f, -196.4f, -61.3f, -195.9f, -62.2f, + -194.3f, -64.9f, -193.7f, -65.7f, -193.1f, -66.6f, -192.5f, -67.4f, -191.8f, -68.2f, + -191.2f, -68.9f, -190.4f, -69.7f, -188.2f, -71.8f, -187.4f, -72.5f, -186.6f, -73.1f, + -185.8f, -73.8f, -185.0f, -74.4f, -184.1f, -74.9f, -183.2f, -75.5f, -182.4f, -76.0f, + -181.5f, -76.5f, -179.6f, -77.5f, -178.7f, -77.9f, -177.8f, -78.4f, -176.8f, -78.8f, + -175.9f, -79.1f, -174.9f, -79.5f, -173.9f, -79.8f, -170.9f, -80.6f, -169.9f, -80.8f, + -167.9f, -81.1f, -166.9f, -81.2f, -165.8f, -81.2f, -145.0f, -80.9f, +}; + +constexpr std::array left_joycon_trigger = { + -166.8f, -83.3f, -167.9f, -83.2f, -168.9f, -83.1f, -170.0f, -83.0f, -171.0f, -82.8f, + -172.1f, -82.6f, -173.1f, -82.4f, -174.2f, -82.1f, -175.2f, -81.9f, -176.2f, -81.5f, + -177.2f, -81.2f, -178.2f, -80.8f, -180.1f, -80.0f, -181.1f, -79.5f, -182.0f, -79.0f, + -183.0f, -78.5f, -183.9f, -78.0f, -184.8f, -77.4f, -185.7f, -76.9f, -186.6f, -76.3f, + -187.4f, -75.6f, -188.3f, -75.0f, -189.1f, -74.3f, -192.2f, -71.5f, -192.9f, -70.7f, + -193.7f, -69.9f, -194.3f, -69.1f, -195.0f, -68.3f, -195.6f, -67.4f, -196.8f, -65.7f, + -197.3f, -64.7f, -197.8f, -63.8f, -198.2f, -62.8f, -198.9f, -60.8f, -198.6f, -59.8f, + -197.6f, -59.7f, -196.6f, -60.0f, -195.6f, -60.5f, -194.7f, -60.9f, -193.7f, -61.4f, + -192.8f, -61.9f, -191.8f, -62.4f, -190.9f, -62.8f, -189.9f, -63.3f, -189.0f, -63.8f, + -187.1f, -64.8f, -186.2f, -65.2f, -185.2f, -65.7f, -184.3f, -66.2f, -183.3f, -66.7f, + -182.4f, -67.1f, -181.4f, -67.6f, -180.5f, -68.1f, -179.5f, -68.6f, -178.6f, -69.0f, + -177.6f, -69.5f, -176.7f, -70.0f, -175.7f, -70.5f, -174.8f, -70.9f, -173.8f, -71.4f, + -172.9f, -71.9f, -171.9f, -72.4f, -171.0f, -72.8f, -170.0f, -73.3f, -169.1f, -73.8f, + -168.1f, -74.3f, -167.2f, -74.7f, -166.2f, -75.2f, -165.3f, -75.7f, -164.3f, -76.2f, + -163.4f, -76.6f, -162.4f, -77.1f, -161.5f, -77.6f, -160.5f, -78.1f, -159.6f, -78.5f, + -158.7f, -79.0f, -157.7f, -79.5f, -156.8f, -80.0f, -155.8f, -80.4f, -154.9f, -80.9f, + -154.2f, -81.6f, -154.3f, -82.6f, -155.2f, -83.3f, -156.2f, -83.3f, +}; + +constexpr std::array handheld_body = { + -137.3f, -81.9f, -137.6f, -81.8f, -137.8f, -81.6f, -138.0f, -81.3f, -138.1f, -81.1f, + -138.1f, -80.8f, -138.2f, -78.7f, -138.2f, -78.4f, -138.3f, -78.1f, -138.7f, -77.3f, + -138.9f, -77.0f, -139.0f, -76.8f, -139.2f, -76.5f, -139.5f, -76.3f, -139.7f, -76.1f, + -139.9f, -76.0f, -140.2f, -75.8f, -140.5f, -75.7f, -140.7f, -75.6f, -141.0f, -75.5f, + -141.9f, -75.3f, -142.2f, -75.3f, -142.5f, -75.2f, -143.0f, -74.9f, -143.2f, -74.7f, + -143.3f, -74.4f, -143.0f, -74.1f, -143.0f, 85.3f, -143.0f, 85.6f, -142.7f, 85.8f, + -142.4f, 85.9f, -142.2f, 85.9f, 143.0f, 85.6f, 143.1f, 85.4f, 143.3f, 85.1f, + 143.0f, 84.8f, 143.0f, -74.9f, 142.8f, -75.1f, 142.5f, -75.2f, 141.9f, -75.3f, + 141.6f, -75.3f, 141.3f, -75.4f, 141.1f, -75.4f, 140.8f, -75.5f, 140.5f, -75.7f, + 140.2f, -75.8f, 140.0f, -76.0f, 139.7f, -76.1f, 139.5f, -76.3f, 139.1f, -76.8f, + 138.9f, -77.0f, 138.6f, -77.5f, 138.4f, -77.8f, 138.3f, -78.1f, 138.3f, -78.3f, + 138.2f, -78.6f, 138.2f, -78.9f, 138.1f, -79.2f, 138.1f, -79.5f, 138.0f, -81.3f, + 137.8f, -81.6f, 137.6f, -81.8f, 137.3f, -81.9f, 137.1f, -81.9f, 120.0f, -70.0f, + -120.0f, -70.0f, -120.0f, 70.0f, 120.0f, 70.0f, 120.0f, -70.0f, 137.1f, -81.9f, +}; + +constexpr std::array handheld_bezel = { + -131.4f, -75.9f, -132.2f, -75.7f, -132.9f, -75.3f, -134.2f, -74.3f, -134.7f, -73.6f, + -135.1f, -72.8f, -135.4f, -72.0f, -135.5f, -71.2f, -135.5f, -70.4f, -135.2f, 76.7f, + -134.8f, 77.5f, -134.3f, 78.1f, -133.7f, 78.8f, -133.1f, 79.2f, -132.3f, 79.6f, + -131.5f, 79.9f, -130.7f, 80.0f, -129.8f, 80.0f, 132.2f, 79.7f, 133.0f, 79.3f, + 133.7f, 78.8f, 134.3f, 78.3f, 134.8f, 77.6f, 135.1f, 76.8f, 135.5f, 75.2f, + 135.5f, 74.3f, 135.2f, -72.7f, 134.8f, -73.5f, 134.4f, -74.2f, 133.8f, -74.8f, + 133.1f, -75.3f, 132.3f, -75.6f, 130.7f, -76.0f, 129.8f, -76.0f, -112.9f, -62.2f, + 112.9f, -62.2f, 112.9f, 62.2f, -112.9f, 62.2f, -112.9f, -62.2f, 129.8f, -76.0f, +}; + +constexpr std::array handheld_buttons = { + -82.48f, -82.95f, -82.53f, -82.95f, -106.69f, -82.96f, -106.73f, -82.98f, -106.78f, -83.01f, + -106.81f, -83.05f, -106.83f, -83.1f, -106.83f, -83.15f, -106.82f, -83.93f, -106.81f, -83.99f, + -106.8f, -84.04f, -106.78f, -84.08f, -106.76f, -84.13f, -106.73f, -84.18f, -106.7f, -84.22f, + -106.6f, -84.34f, -106.56f, -84.37f, -106.51f, -84.4f, -106.47f, -84.42f, -106.42f, -84.45f, + -106.37f, -84.47f, -106.32f, -84.48f, -106.17f, -84.5f, -98.9f, -84.48f, -98.86f, -84.45f, + -98.83f, -84.41f, -98.81f, -84.36f, -98.8f, -84.31f, -98.8f, -84.26f, -98.79f, -84.05f, + -90.26f, -84.1f, -90.26f, -84.15f, -90.25f, -84.36f, -90.23f, -84.41f, -90.2f, -84.45f, + -90.16f, -84.48f, -90.11f, -84.5f, -82.79f, -84.49f, -82.74f, -84.48f, -82.69f, -84.46f, + -82.64f, -84.45f, -82.59f, -84.42f, -82.55f, -84.4f, -82.5f, -84.37f, -82.46f, -84.33f, + -82.42f, -84.3f, -82.39f, -84.26f, -82.3f, -84.13f, -82.28f, -84.08f, -82.25f, -83.98f, + -82.24f, -83.93f, -82.23f, -83.83f, -82.23f, -83.78f, -82.24f, -83.1f, -82.26f, -83.05f, + -82.29f, -83.01f, -82.33f, -82.97f, -82.38f, -82.95f, +}; + +constexpr std::array left_joycon_slider = { + -23.7f, -118.2f, -23.7f, -117.3f, -23.7f, 96.6f, -22.8f, 96.6f, -21.5f, 97.2f, -21.5f, + 98.1f, -21.2f, 106.7f, -20.8f, 107.5f, -20.1f, 108.2f, -19.2f, 108.2f, -16.4f, 108.1f, + -15.8f, 107.5f, -15.8f, 106.5f, -15.8f, 62.8f, -16.3f, 61.9f, -15.8f, 61.0f, -17.3f, + 60.3f, -19.1f, 58.9f, -19.1f, 58.1f, -19.1f, 57.2f, -19.1f, 34.5f, -17.9f, 33.9f, + -17.2f, 33.2f, -16.6f, 32.4f, -16.2f, 31.6f, -15.8f, 30.7f, -15.8f, 29.7f, -15.8f, + 28.8f, -15.8f, -46.4f, -16.3f, -47.3f, -15.8f, -48.1f, -17.4f, -48.8f, -19.1f, -49.4f, + -19.1f, -50.1f, -19.1f, -51.0f, -19.1f, -51.9f, -19.1f, -73.7f, -19.1f, -74.5f, -17.5f, + -75.2f, -16.4f, -76.7f, -16.0f, -77.6f, -15.8f, -78.5f, -15.8f, -79.4f, -15.8f, -80.4f, + -15.8f, -118.2f, -15.8f, -118.2f, -18.3f, -118.2f, +}; + +constexpr std::array left_joycon_sideview = { + -158.8f, -133.5f, -159.8f, -133.5f, -173.5f, -133.3f, -174.5f, -133.0f, -175.4f, -132.6f, + -176.2f, -132.1f, -177.0f, -131.5f, -177.7f, -130.9f, -178.3f, -130.1f, -179.4f, -128.5f, + -179.8f, -127.6f, -180.4f, -125.7f, -180.6f, -124.7f, -180.7f, -123.8f, -180.7f, -122.8f, + -180.0f, 128.8f, -179.6f, 129.7f, -179.1f, 130.5f, -177.9f, 132.1f, -177.2f, 132.7f, + -176.4f, 133.3f, -175.6f, 133.8f, -174.7f, 134.3f, -173.8f, 134.6f, -172.8f, 134.8f, + -170.9f, 135.0f, -169.9f, 135.0f, -156.1f, 134.8f, -155.2f, 134.6f, -154.2f, 134.3f, + -153.3f, 134.0f, -152.4f, 133.6f, -151.6f, 133.1f, -150.7f, 132.6f, -149.9f, 132.0f, + -149.2f, 131.4f, -148.5f, 130.7f, -147.1f, 129.2f, -146.5f, 128.5f, -146.0f, 127.7f, + -145.5f, 126.8f, -145.0f, 126.0f, -144.6f, 125.1f, -144.2f, 124.1f, -143.9f, 123.2f, + -143.7f, 122.2f, -143.6f, 121.3f, -143.5f, 120.3f, -143.5f, 119.3f, -144.4f, -123.4f, + -144.8f, -124.3f, -145.3f, -125.1f, -145.8f, -126.0f, -146.3f, -126.8f, -147.0f, -127.5f, + -147.6f, -128.3f, -148.3f, -129.0f, -149.0f, -129.6f, -149.8f, -130.3f, -150.6f, -130.8f, + -151.4f, -131.4f, -152.2f, -131.9f, -153.1f, -132.3f, -155.9f, -133.3f, -156.8f, -133.5f, + -157.8f, -133.5f, +}; + +constexpr std::array left_joycon_body_trigger = { + -146.1f, -124.3f, -146.0f, -122.0f, -145.8f, -119.7f, -145.7f, -117.4f, -145.4f, -112.8f, + -145.3f, -110.5f, -145.0f, -105.9f, -144.9f, -103.6f, -144.6f, -99.1f, -144.5f, -96.8f, + -144.5f, -89.9f, -144.5f, -87.6f, -144.5f, -83.0f, -144.5f, -80.7f, -144.5f, -80.3f, + -142.4f, -82.4f, -141.4f, -84.5f, -140.2f, -86.4f, -138.8f, -88.3f, -137.4f, -90.1f, + -134.5f, -93.6f, -133.0f, -95.3f, -130.0f, -98.8f, -128.5f, -100.6f, -127.1f, -102.4f, + -125.8f, -104.3f, -124.7f, -106.3f, -123.9f, -108.4f, -125.1f, -110.2f, -127.4f, -110.3f, + -129.7f, -110.3f, -134.2f, -110.5f, -136.4f, -111.4f, -138.1f, -112.8f, -139.4f, -114.7f, + -140.5f, -116.8f, -141.4f, -118.9f, -143.3f, -123.1f, -144.6f, -124.9f, -146.2f, -126.0f, +}; + +constexpr std::array left_joycon_topview = { + -184.8f, -20.8f, -185.6f, -21.1f, -186.4f, -21.5f, -187.1f, -22.1f, -187.8f, -22.6f, + -188.4f, -23.2f, -189.6f, -24.5f, -190.2f, -25.2f, -190.7f, -25.9f, -191.1f, -26.7f, + -191.4f, -27.5f, -191.6f, -28.4f, -191.7f, -29.2f, -191.7f, -30.1f, -191.5f, -47.7f, + -191.2f, -48.5f, -191.0f, -49.4f, -190.7f, -50.2f, -190.3f, -51.0f, -190.0f, -51.8f, + -189.6f, -52.6f, -189.1f, -53.4f, -188.6f, -54.1f, -187.5f, -55.4f, -186.9f, -56.1f, + -186.2f, -56.7f, -185.5f, -57.2f, -184.0f, -58.1f, -183.3f, -58.5f, -182.5f, -58.9f, + -181.6f, -59.2f, -180.8f, -59.5f, -179.9f, -59.7f, -179.1f, -59.9f, -178.2f, -60.0f, + -174.7f, -60.1f, -168.5f, -60.2f, -162.4f, -60.3f, -156.2f, -60.4f, -149.2f, -60.5f, + -143.0f, -60.6f, -136.9f, -60.7f, -130.7f, -60.8f, -123.7f, -60.9f, -117.5f, -61.0f, + -110.5f, -61.1f, -94.4f, -60.4f, -94.4f, -59.5f, -94.4f, -20.6f, +}; + +constexpr std::array left_joycon_slider_topview = { + -95.1f, -51.5f, -95.0f, -51.5f, -91.2f, -51.6f, -91.2f, -51.7f, -91.1f, -52.4f, -91.1f, -52.6f, + -91.0f, -54.1f, -86.3f, -54.0f, -86.0f, -53.9f, -85.9f, -53.8f, -85.6f, -53.4f, -85.5f, -53.2f, + -85.5f, -53.1f, -85.4f, -52.9f, -85.4f, -52.8f, -85.3f, -52.4f, -85.3f, -52.3f, -85.4f, -27.2f, + -85.4f, -27.1f, -85.5f, -27.0f, -85.5f, -26.9f, -85.6f, -26.7f, -85.6f, -26.6f, -85.7f, -26.5f, + -85.9f, -26.4f, -86.0f, -26.3f, -86.4f, -26.0f, -86.5f, -25.9f, -86.7f, -25.8f, -87.1f, -25.7f, + -90.4f, -25.8f, -90.7f, -25.9f, -90.8f, -26.0f, -90.9f, -26.3f, -91.0f, -26.4f, -91.0f, -26.5f, + -91.1f, -26.7f, -91.1f, -26.9f, -91.2f, -28.9f, -95.2f, -29.1f, -95.2f, -29.2f, +}; + +constexpr std::array left_joycon_sideview_zl = { + -148.9f, -128.2f, -148.7f, -126.6f, -148.4f, -124.9f, -148.2f, -123.3f, -147.9f, -121.7f, + -147.7f, -120.1f, -147.4f, -118.5f, -147.2f, -116.9f, -146.9f, -115.3f, -146.4f, -112.1f, + -146.1f, -110.5f, -145.9f, -108.9f, -145.6f, -107.3f, -144.2f, -107.3f, -142.6f, -107.5f, + -141.0f, -107.8f, -137.8f, -108.3f, -136.2f, -108.6f, -131.4f, -109.4f, -129.8f, -109.7f, + -125.6f, -111.4f, -124.5f, -112.7f, -123.9f, -114.1f, -123.8f, -115.8f, -123.8f, -117.4f, + -123.9f, -120.6f, -124.5f, -122.1f, -125.8f, -123.1f, -127.4f, -123.4f, -129.0f, -123.6f, + -130.6f, -124.0f, -132.1f, -124.4f, -133.7f, -124.8f, -135.3f, -125.3f, -136.8f, -125.9f, + -138.3f, -126.4f, -139.9f, -126.9f, -141.4f, -127.5f, -142.9f, -128.0f, -144.5f, -128.5f, + -146.0f, -129.0f, -147.6f, -129.4f, +}; + +constexpr std::array left_joystick_sideview = { + -14.7f, -3.8f, -15.2f, -5.6f, -15.2f, -7.6f, -15.5f, -17.6f, -17.4f, -18.3f, -19.4f, -18.2f, + -21.3f, -17.6f, -22.8f, -16.4f, -23.4f, -14.5f, -23.4f, -12.5f, -24.1f, -8.6f, -24.8f, -6.7f, + -25.3f, -4.8f, -25.7f, -2.8f, -25.9f, -0.8f, -26.0f, 1.2f, -26.0f, 3.2f, -25.8f, 5.2f, + -25.5f, 7.2f, -25.0f, 9.2f, -24.4f, 11.1f, -23.7f, 13.0f, -23.4f, 14.9f, -23.4f, 16.9f, + -23.3f, 18.9f, -22.0f, 20.5f, -20.2f, 21.3f, -18.3f, 21.6f, -16.3f, 21.4f, -15.3f, 19.9f, + -15.3f, 17.8f, -15.2f, 7.8f, -13.5f, 6.4f, -12.4f, 7.2f, -11.4f, 8.9f, -10.2f, 10.5f, + -8.7f, 11.8f, -7.1f, 13.0f, -5.3f, 14.0f, -3.5f, 14.7f, -1.5f, 15.0f, 0.5f, 15.0f, + 2.5f, 14.7f, 4.4f, 14.2f, 6.3f, 13.4f, 8.0f, 12.4f, 9.6f, 11.1f, 10.9f, 9.6f, + 12.0f, 7.9f, 12.7f, 6.0f, 13.2f, 4.1f, 13.3f, 2.1f, 13.2f, 0.1f, 12.9f, -1.9f, + 12.2f, -3.8f, 11.3f, -5.6f, 10.2f, -7.2f, 8.8f, -8.6f, 7.1f, -9.8f, 5.4f, -10.8f, + 3.5f, -11.5f, 1.5f, -11.9f, -0.5f, -12.0f, -2.5f, -11.8f, -4.4f, -11.3f, -6.2f, -10.4f, + -8.0f, -9.4f, -9.6f, -8.2f, -10.9f, -6.7f, -11.9f, -4.9f, -12.8f, -3.2f, -13.5f, -3.8f, +}; + +constexpr std::array left_joystick_L_topview = { + -186.7f, -43.7f, -186.4f, -43.7f, -110.6f, -43.4f, -110.6f, -43.1f, -110.7f, -34.3f, + -110.7f, -34.0f, -110.8f, -33.7f, -111.1f, -32.9f, -111.2f, -32.6f, -111.4f, -32.3f, + -111.5f, -32.1f, -111.7f, -31.8f, -111.8f, -31.5f, -112.0f, -31.3f, -112.2f, -31.0f, + -112.4f, -30.8f, -112.8f, -30.3f, -113.0f, -30.1f, -114.1f, -29.1f, -114.3f, -28.9f, + -114.6f, -28.7f, -114.8f, -28.6f, -115.1f, -28.4f, -115.3f, -28.3f, -115.6f, -28.1f, + -115.9f, -28.0f, -116.4f, -27.8f, -116.7f, -27.7f, -117.3f, -27.6f, -117.6f, -27.5f, + -182.9f, -27.6f, -183.5f, -27.7f, -183.8f, -27.8f, -184.4f, -27.9f, -184.6f, -28.1f, + -184.9f, -28.2f, -185.4f, -28.5f, -185.7f, -28.7f, -185.9f, -28.8f, -186.2f, -29.0f, + -186.4f, -29.2f, -187.0f, -29.9f, -187.2f, -30.1f, -187.6f, -30.6f, -187.8f, -30.8f, + -187.9f, -31.1f, -188.1f, -31.3f, -188.2f, -31.6f, -188.4f, -31.9f, -188.5f, -32.1f, + -188.6f, -32.4f, -188.8f, -33.3f, -188.9f, -33.6f, -188.9f, -33.9f, -188.8f, -39.9f, + -188.8f, -40.2f, -188.7f, -41.1f, -188.7f, -41.4f, -188.6f, -41.7f, -188.0f, -43.1f, + -187.9f, -43.4f, -187.6f, -43.6f, -187.3f, -43.7f, +}; + +constexpr std::array left_joystick_ZL_topview = { + -179.4f, -53.3f, -177.4f, -53.3f, -111.2f, -53.3f, -111.3f, -53.3f, -111.5f, -58.6f, + -111.8f, -60.5f, -112.2f, -62.4f, -113.1f, -66.1f, -113.8f, -68.0f, -114.5f, -69.8f, + -115.3f, -71.5f, -116.3f, -73.2f, -117.3f, -74.8f, -118.5f, -76.4f, -119.8f, -77.8f, + -121.2f, -79.1f, -122.8f, -80.2f, -124.4f, -81.2f, -126.2f, -82.0f, -128.1f, -82.6f, + -130.0f, -82.9f, -131.9f, -83.0f, -141.5f, -82.9f, -149.3f, -82.8f, -153.1f, -82.6f, + -155.0f, -82.1f, -156.8f, -81.6f, -158.7f, -80.9f, -160.4f, -80.2f, -162.2f, -79.3f, + -163.8f, -78.3f, -165.4f, -77.2f, -166.9f, -76.0f, -168.4f, -74.7f, -169.7f, -73.3f, + -172.1f, -70.3f, -173.2f, -68.7f, -174.2f, -67.1f, -175.2f, -65.4f, -176.1f, -63.7f, + -178.7f, -58.5f, -179.6f, -56.8f, -180.4f, -55.1f, -181.3f, -53.3f, +}; + +void PlayerControlPreview::DrawProBody(QPainter& p, const QPointF center) { + std::array qleft_handle; + std::array qright_handle; + std::array qbody; + constexpr int radius1 = 32; + + for (std::size_t point = 0; point < pro_left_handle.size() / 2; ++point) { + const float left_x = pro_left_handle[point * 2 + 0]; + const float left_y = pro_left_handle[point * 2 + 1]; + + qleft_handle[point] = center + QPointF(left_x, left_y); + qright_handle[point] = center + QPointF(-left_x, left_y); + } + for (std::size_t point = 0; point < pro_body.size() / 2; ++point) { + const float body_x = pro_body[point * 2 + 0]; + const float body_y = pro_body[point * 2 + 1]; + + qbody[point] = center + QPointF(body_x, body_y); + qbody[pro_body.size() - 1 - point] = center + QPointF(-body_x, body_y); + } + + // Draw left handle body + p.setPen(colors.outline); + p.setBrush(colors.left); + DrawPolygon(p, qleft_handle); + + // Draw right handle body + p.setBrush(colors.right); + DrawPolygon(p, qright_handle); + + // Draw body + p.setBrush(colors.primary); + DrawPolygon(p, qbody); + + // Draw joycon circles + p.setBrush(colors.transparent); + p.drawEllipse(center + QPoint(-111, -55), radius1, radius1); + p.drawEllipse(center + QPoint(51, 0), radius1, radius1); +} + +void PlayerControlPreview::DrawGCBody(QPainter& p, const QPointF center) { + std::array qleft_handle; + std::array qright_handle; + std::array qbody; + std::array left_hex; + std::array right_hex; + constexpr float angle = 2 * 3.1415f / 8; + + for (std::size_t point = 0; point < gc_left_body.size() / 2; ++point) { + const float body_x = gc_left_body[point * 2 + 0]; + const float body_y = gc_left_body[point * 2 + 1]; + + qleft_handle[point] = center + QPointF(body_x, body_y); + qright_handle[point] = center + QPointF(-body_x, body_y); + } + for (std::size_t point = 0; point < gc_body.size() / 2; ++point) { + const float body_x = gc_body[point * 2 + 0]; + const float body_y = gc_body[point * 2 + 1]; + + qbody[point] = center + QPointF(body_x, body_y); + qbody[gc_body.size() - 1 - point] = center + QPointF(-body_x, body_y); + } + for (std::size_t point = 0; point < 8; ++point) { + const float point_cos = std::cos(point * angle); + const float point_sin = std::sin(point * angle); + + left_hex[point] = center + QPointF(34 * point_cos - 111, 34 * point_sin - 44); + right_hex[point] = center + QPointF(26 * point_cos + 61, 26 * point_sin + 37); + } + + // Draw body + p.setPen(colors.outline); + p.setBrush(colors.primary); + DrawPolygon(p, qbody); + + // Draw left handle body + p.setBrush(colors.left); + DrawPolygon(p, qleft_handle); + + // Draw right handle body + p.setBrush(colors.right); + DrawPolygon(p, qright_handle); + + DrawText(p, center + QPoint(0, -58), 4.7f, tr("START/PAUSE")); + + // Draw right joystick body + p.setBrush(colors.button); + DrawCircle(p, center + QPointF(61, 37), 23.5f); + + // Draw joystick details + p.setBrush(colors.transparent); + DrawPolygon(p, left_hex); + DrawPolygon(p, right_hex); +} + +void PlayerControlPreview::DrawHandheldBody(QPainter& p, const QPointF center) { + const std::size_t body_outline_end = handheld_body.size() / 2 - 6; + const std::size_t bezel_outline_end = handheld_bezel.size() / 2 - 6; + const std::size_t bezel_inline_size = 4; + const std::size_t bezel_inline_start = 35; + std::array left_joycon; + std::array right_joycon; + std::array qhandheld_body; + std::array qhandheld_body_outline; + std::array qhandheld_bezel; + std::array qhandheld_bezel_inline; + std::array qhandheld_bezel_outline; + std::array qhandheld_buttons; + + for (std::size_t point = 0; point < left_joycon_body.size() / 2; ++point) { + left_joycon[point] = + center + QPointF(left_joycon_body[point * 2], left_joycon_body[point * 2 + 1]); + right_joycon[point] = + center + QPointF(-left_joycon_body[point * 2], left_joycon_body[point * 2 + 1]); + } + for (std::size_t point = 0; point < body_outline_end; ++point) { + qhandheld_body_outline[point] = + center + QPointF(handheld_body[point * 2], handheld_body[point * 2 + 1]); + } + for (std::size_t point = 0; point < handheld_body.size() / 2; ++point) { + qhandheld_body[point] = + center + QPointF(handheld_body[point * 2], handheld_body[point * 2 + 1]); + } + for (std::size_t point = 0; point < handheld_bezel.size() / 2; ++point) { + qhandheld_bezel[point] = + center + QPointF(handheld_bezel[point * 2], handheld_bezel[point * 2 + 1]); + } + for (std::size_t point = 0; point < bezel_outline_end; ++point) { + qhandheld_bezel_outline[point] = + center + QPointF(handheld_bezel[point * 2], handheld_bezel[point * 2 + 1]); + } + for (std::size_t point = 0; point < bezel_inline_size; ++point) { + qhandheld_bezel_inline[point] = + center + QPointF(handheld_bezel[(point + bezel_inline_start) * 2], + handheld_bezel[(point + bezel_inline_start) * 2 + 1]); + } + for (std::size_t point = 0; point < handheld_buttons.size() / 2; ++point) { + qhandheld_buttons[point] = + center + QPointF(handheld_buttons[point * 2], handheld_buttons[point * 2 + 1]); + } + + // Draw left joycon + p.setPen(colors.outline); + p.setBrush(colors.left); + DrawPolygon(p, left_joycon); + + // Draw right joycon + p.setPen(colors.outline); + p.setBrush(colors.right); + DrawPolygon(p, right_joycon); + + // Draw Handheld buttons + p.setPen(colors.outline); + p.setBrush(colors.button); + DrawPolygon(p, qhandheld_buttons); + + // Draw handheld body + p.setPen(colors.transparent); + p.setBrush(colors.primary); + DrawPolygon(p, qhandheld_body); + p.setPen(colors.outline); + p.setBrush(colors.transparent); + DrawPolygon(p, qhandheld_body_outline); + + // Draw Handheld bezel + p.setPen(colors.transparent); + p.setBrush(colors.button); + DrawPolygon(p, qhandheld_bezel); + p.setPen(colors.outline); + p.setBrush(colors.transparent); + DrawPolygon(p, qhandheld_bezel_outline); + DrawPolygon(p, qhandheld_bezel_inline); +} + +void PlayerControlPreview::DrawDualBody(QPainter& p, const QPointF center) { + std::array left_joycon; + std::array right_joycon; + std::array qleft_joycon_slider; + std::array qright_joycon_slider; + std::array qleft_joycon_slider_topview; + std::array qright_joycon_slider_topview; + std::array qleft_joycon_topview; + std::array qright_joycon_topview; + constexpr float size = 1.61f; + constexpr float size2 = 0.9f; + constexpr float offset = 209.3f; + + for (std::size_t point = 0; point < left_joycon_body.size() / 2; ++point) { + const float body_x = left_joycon_body[point * 2 + 0]; + const float body_y = left_joycon_body[point * 2 + 1]; + + left_joycon[point] = center + QPointF(body_x * size + offset, body_y * size - 1); + right_joycon[point] = center + QPointF(-body_x * size - offset, body_y * size - 1); + } + for (std::size_t point = 0; point < left_joycon_slider.size() / 2; ++point) { + const float slider_x = left_joycon_slider[point * 2 + 0]; + const float slider_y = left_joycon_slider[point * 2 + 1]; + + qleft_joycon_slider[point] = center + QPointF(slider_x, slider_y); + qright_joycon_slider[point] = center + QPointF(-slider_x, slider_y); + } + for (std::size_t point = 0; point < left_joycon_topview.size() / 2; ++point) { + const float top_view_x = left_joycon_topview[point * 2 + 0]; + const float top_view_y = left_joycon_topview[point * 2 + 1]; + + qleft_joycon_topview[point] = + center + QPointF(top_view_x * size2 - 52, top_view_y * size2 - 52); + qright_joycon_topview[point] = + center + QPointF(-top_view_x * size2 + 52, top_view_y * size2 - 52); + } + for (std::size_t point = 0; point < left_joycon_slider_topview.size() / 2; ++point) { + const float top_view_x = left_joycon_slider_topview[point * 2 + 0]; + const float top_view_y = left_joycon_slider_topview[point * 2 + 1]; + + qleft_joycon_slider_topview[point] = + center + QPointF(top_view_x * size2 - 52, top_view_y * size2 - 52); + qright_joycon_slider_topview[point] = + center + QPointF(-top_view_x * size2 + 52, top_view_y * size2 - 52); + } + + // right joycon body + p.setPen(colors.outline); + p.setBrush(colors.right); + DrawPolygon(p, right_joycon); + + // Left joycon body + p.setPen(colors.outline); + p.setBrush(colors.left); + DrawPolygon(p, left_joycon); + + // Slider release button top view + p.setBrush(colors.button); + DrawRoundRectangle(p, center + QPoint(-149, -108), 12, 11, 2); + DrawRoundRectangle(p, center + QPoint(149, -108), 12, 11, 2); + + // Joycon slider top view + p.setBrush(colors.slider); + DrawPolygon(p, qleft_joycon_slider_topview); + p.drawLine(center + QPointF(-133.8f, -99.0f), center + QPointF(-133.8f, -78.5f)); + DrawPolygon(p, qright_joycon_slider_topview); + p.drawLine(center + QPointF(133.8f, -99.0f), center + QPointF(133.8f, -78.5f)); + + // Joycon body top view + p.setBrush(colors.left); + DrawPolygon(p, qleft_joycon_topview); + p.setBrush(colors.right); + DrawPolygon(p, qright_joycon_topview); + + // Right Sideview body + p.setBrush(colors.slider); + DrawPolygon(p, qright_joycon_slider); + + // Left Sideview body + p.setBrush(colors.slider); + DrawPolygon(p, qleft_joycon_slider); +} + +void PlayerControlPreview::DrawLeftBody(QPainter& p, const QPointF center) { + std::array left_joycon; + std::array qleft_joycon_sideview; + std::array qleft_joycon_trigger; + std::array qleft_joycon_slider; + std::array qleft_joycon_slider_topview; + std::array qleft_joycon_topview; + constexpr float size = 1.78f; + constexpr float size2 = 1.1115f; + constexpr float offset = 312.39f; + constexpr float offset2 = 335; + + for (std::size_t point = 0; point < left_joycon_body.size() / 2; ++point) { + left_joycon[point] = center + QPointF(left_joycon_body[point * 2] * size + offset, + left_joycon_body[point * 2 + 1] * size - 1); + } + + for (std::size_t point = 0; point < left_joycon_sideview.size() / 2; ++point) { + qleft_joycon_sideview[point] = + center + QPointF(left_joycon_sideview[point * 2] * size2 + offset2, + left_joycon_sideview[point * 2 + 1] * size2 + 2); + } + for (std::size_t point = 0; point < left_joycon_slider.size() / 2; ++point) { + qleft_joycon_slider[point] = center + QPointF(left_joycon_slider[point * 2] * size2 + 81, + left_joycon_slider[point * 2 + 1] * size2); + } + for (std::size_t point = 0; point < left_joycon_body_trigger.size() / 2; ++point) { + qleft_joycon_trigger[point] = + center + QPointF(left_joycon_body_trigger[point * 2] * size2 + offset2, + left_joycon_body_trigger[point * 2 + 1] * size2 + 2); + } + for (std::size_t point = 0; point < left_joycon_topview.size() / 2; ++point) { + qleft_joycon_topview[point] = + center + QPointF(left_joycon_topview[point * 2], left_joycon_topview[point * 2 + 1]); + } + for (std::size_t point = 0; point < left_joycon_slider_topview.size() / 2; ++point) { + qleft_joycon_slider_topview[point] = + center + QPointF(left_joycon_slider_topview[point * 2], + left_joycon_slider_topview[point * 2 + 1]); + } + + // Joycon body + p.setPen(colors.outline); + p.setBrush(colors.left); + DrawPolygon(p, left_joycon); + DrawPolygon(p, qleft_joycon_trigger); + + // Slider release button top view + p.setBrush(colors.button); + DrawRoundRectangle(p, center + QPoint(-107, -62), 14, 12, 2); + + // Joycon slider top view + p.setBrush(colors.slider); + DrawPolygon(p, qleft_joycon_slider_topview); + p.drawLine(center + QPointF(-91.1f, -51.7f), center + QPointF(-91.1f, -26.5f)); + + // Joycon body top view + p.setBrush(colors.left); + DrawPolygon(p, qleft_joycon_topview); + + // Slider release button + p.setBrush(colors.button); + DrawRoundRectangle(p, center + QPoint(175, -110), 12, 14, 2); + + // Sideview body + p.setBrush(colors.left); + DrawPolygon(p, qleft_joycon_sideview); + p.setBrush(colors.slider); + DrawPolygon(p, qleft_joycon_slider); + + const QPointF sideview_center = QPointF(155, 0) + center; + + // Sideview slider body + p.setBrush(colors.slider); + DrawRoundRectangle(p, sideview_center + QPointF(0, -5), 28, 253, 3); + p.setBrush(colors.button2); + DrawRoundRectangle(p, sideview_center + QPointF(0, 97), 22.44f, 44.66f, 3); + + // Slider decorations + p.setPen(colors.outline); + p.setBrush(colors.slider_arrow); + DrawArrow(p, sideview_center + QPoint(0, 83), Direction::Down, 2.2f); + DrawArrow(p, sideview_center + QPoint(0, 96), Direction::Down, 2.2f); + DrawArrow(p, sideview_center + QPoint(0, 109), Direction::Down, 2.2f); + DrawCircle(p, sideview_center + QPointF(0, 19), 4.44f); + + // LED indicators + const float led_size = 5.0f; + const QPointF led_position = sideview_center + QPointF(0, -36); + int led_count = 0; + p.setBrush(led_pattern.position1 ? colors.led_on : colors.led_off); + DrawRectangle(p, led_position + QPointF(0, 12 * led_count++), led_size, led_size); + p.setBrush(led_pattern.position2 ? colors.led_on : colors.led_off); + DrawRectangle(p, led_position + QPointF(0, 12 * led_count++), led_size, led_size); + p.setBrush(led_pattern.position3 ? colors.led_on : colors.led_off); + DrawRectangle(p, led_position + QPointF(0, 12 * led_count++), led_size, led_size); + p.setBrush(led_pattern.position4 ? colors.led_on : colors.led_off); + DrawRectangle(p, led_position + QPointF(0, 12 * led_count++), led_size, led_size); +} + +void PlayerControlPreview::DrawRightBody(QPainter& p, const QPointF center) { + std::array right_joycon; + std::array qright_joycon_sideview; + std::array qright_joycon_trigger; + std::array qright_joycon_slider; + std::array qright_joycon_slider_topview; + std::array qright_joycon_topview; + constexpr float size = 1.78f; + constexpr float size2 = 1.1115f; + constexpr float offset = 312.39f; + constexpr float offset2 = 335; + + for (std::size_t point = 0; point < left_joycon_body.size() / 2; ++point) { + right_joycon[point] = center + QPointF(-left_joycon_body[point * 2] * size - offset, + left_joycon_body[point * 2 + 1] * size - 1); + } + + for (std::size_t point = 0; point < left_joycon_sideview.size() / 2; ++point) { + qright_joycon_sideview[point] = + center + QPointF(-left_joycon_sideview[point * 2] * size2 - offset2, + left_joycon_sideview[point * 2 + 1] * size2 + 2); + } + for (std::size_t point = 0; point < left_joycon_body_trigger.size() / 2; ++point) { + qright_joycon_trigger[point] = + center + QPointF(-left_joycon_body_trigger[point * 2] * size2 - offset2, + left_joycon_body_trigger[point * 2 + 1] * size2 + 2); + } + for (std::size_t point = 0; point < left_joycon_slider.size() / 2; ++point) { + qright_joycon_slider[point] = center + QPointF(-left_joycon_slider[point * 2] * size2 - 81, + left_joycon_slider[point * 2 + 1] * size2); + } + for (std::size_t point = 0; point < left_joycon_topview.size() / 2; ++point) { + qright_joycon_topview[point] = + center + QPointF(-left_joycon_topview[point * 2], left_joycon_topview[point * 2 + 1]); + } + for (std::size_t point = 0; point < left_joycon_slider_topview.size() / 2; ++point) { + qright_joycon_slider_topview[point] = + center + QPointF(-left_joycon_slider_topview[point * 2], + left_joycon_slider_topview[point * 2 + 1]); + } + + // Joycon body + p.setPen(colors.outline); + p.setBrush(colors.left); + DrawPolygon(p, right_joycon); + DrawPolygon(p, qright_joycon_trigger); + + // Slider release button top view + p.setBrush(colors.button); + DrawRoundRectangle(p, center + QPoint(107, -62), 14, 12, 2); + + // Joycon slider top view + p.setBrush(colors.slider); + DrawPolygon(p, qright_joycon_slider_topview); + p.drawLine(center + QPointF(91.1f, -51.7f), center + QPointF(91.1f, -26.5f)); + + // Joycon body top view + p.setBrush(colors.left); + DrawPolygon(p, qright_joycon_topview); + + // Slider release button + p.setBrush(colors.button); + DrawRoundRectangle(p, center + QPoint(-175, -110), 12, 14, 2); + + // Sideview body + p.setBrush(colors.left); + DrawPolygon(p, qright_joycon_sideview); + p.setBrush(colors.slider); + DrawPolygon(p, qright_joycon_slider); + + const QPointF sideview_center = QPointF(-155, 0) + center; + + // Sideview slider body + p.setBrush(colors.slider); + DrawRoundRectangle(p, sideview_center + QPointF(0, -5), 28, 253, 3); + p.setBrush(colors.button2); + DrawRoundRectangle(p, sideview_center + QPointF(0, 97), 22.44f, 44.66f, 3); + + // Slider decorations + p.setPen(colors.outline); + p.setBrush(colors.slider_arrow); + DrawArrow(p, sideview_center + QPoint(0, 83), Direction::Down, 2.2f); + DrawArrow(p, sideview_center + QPoint(0, 96), Direction::Down, 2.2f); + DrawArrow(p, sideview_center + QPoint(0, 109), Direction::Down, 2.2f); + DrawCircle(p, sideview_center + QPointF(0, 19), 4.44f); + + // LED indicators + const float led_size = 5.0f; + const QPointF led_position = sideview_center + QPointF(0, -36); + int led_count = 0; + p.setBrush(led_pattern.position1 ? colors.led_on : colors.led_off); + DrawRectangle(p, led_position + QPointF(0, 12 * led_count++), led_size, led_size); + p.setBrush(led_pattern.position2 ? colors.led_on : colors.led_off); + DrawRectangle(p, led_position + QPointF(0, 12 * led_count++), led_size, led_size); + p.setBrush(led_pattern.position3 ? colors.led_on : colors.led_off); + DrawRectangle(p, led_position + QPointF(0, 12 * led_count++), led_size, led_size); + p.setBrush(led_pattern.position4 ? colors.led_on : colors.led_off); + DrawRectangle(p, led_position + QPointF(0, 12 * led_count++), led_size, led_size); +} + +void PlayerControlPreview::DrawProTriggers(QPainter& p, const QPointF center, + const Common::Input::ButtonStatus& left_pressed, + const Common::Input::ButtonStatus& right_pressed) { + std::array qleft_trigger; + std::array qright_trigger; + std::array qbody_top; + + for (std::size_t point = 0; point < pro_left_trigger.size() / 2; ++point) { + const float trigger_x = pro_left_trigger[point * 2 + 0]; + const float trigger_y = pro_left_trigger[point * 2 + 1]; + + qleft_trigger[point] = + center + QPointF(trigger_x, trigger_y + (left_pressed.value ? 2 : 0)); + qright_trigger[point] = + center + QPointF(-trigger_x, trigger_y + (right_pressed.value ? 2 : 0)); + } + + for (std::size_t point = 0; point < pro_body_top.size() / 2; ++point) { + const float top_x = pro_body_top[point * 2 + 0]; + const float top_y = pro_body_top[point * 2 + 1]; + + qbody_top[pro_body_top.size() - 1 - point] = center + QPointF(-top_x, top_y); + qbody_top[point] = center + QPointF(top_x, top_y); + } + + // Pro body detail + p.setPen(colors.outline); + p.setBrush(colors.primary); + DrawPolygon(p, qbody_top); + + // Left trigger + p.setBrush(left_pressed.value ? colors.highlight : colors.button); + DrawPolygon(p, qleft_trigger); + + // Right trigger + p.setBrush(right_pressed.value ? colors.highlight : colors.button); + DrawPolygon(p, qright_trigger); +} + +void PlayerControlPreview::DrawGCTriggers(QPainter& p, const QPointF center, + Common::Input::TriggerStatus left_trigger, + Common::Input::TriggerStatus right_trigger) { + std::array qleft_trigger; + std::array qright_trigger; + + for (std::size_t point = 0; point < left_gc_trigger.size() / 2; ++point) { + const float trigger_x = left_gc_trigger[point * 2 + 0]; + const float trigger_y = left_gc_trigger[point * 2 + 1]; + + qleft_trigger[point] = + center + QPointF(trigger_x, trigger_y + (left_trigger.analog.value * 10.0f)); + qright_trigger[point] = + center + QPointF(-trigger_x, trigger_y + (right_trigger.analog.value * 10.0f)); + } + + // Left trigger + p.setPen(colors.outline); + p.setBrush(left_trigger.pressed.value ? colors.highlight : colors.button); + DrawPolygon(p, qleft_trigger); + + // Right trigger + p.setBrush(right_trigger.pressed.value ? colors.highlight : colors.button); + DrawPolygon(p, qright_trigger); + + // Draw L text + p.setPen(colors.transparent); + p.setBrush(colors.font); + DrawSymbol(p, center + QPointF(-132, -119 + (left_trigger.analog.value * 10.0f)), Symbol::L, + 1.7f); + + // Draw R text + p.setPen(colors.transparent); + p.setBrush(colors.font); + DrawSymbol(p, center + QPointF(121.5f, -119 + (right_trigger.analog.value * 10.0f)), Symbol::R, + 1.7f); +} + +void PlayerControlPreview::DrawHandheldTriggers(QPainter& p, const QPointF center, + const Common::Input::ButtonStatus& left_pressed, + const Common::Input::ButtonStatus& right_pressed) { + std::array qleft_trigger; + std::array qright_trigger; + + for (std::size_t point = 0; point < left_joycon_trigger.size() / 2; ++point) { + const float left_trigger_x = left_joycon_trigger[point * 2 + 0]; + const float left_trigger_y = left_joycon_trigger[point * 2 + 1]; + + qleft_trigger[point] = + center + QPointF(left_trigger_x, left_trigger_y + (left_pressed.value ? 0.5f : 0)); + qright_trigger[point] = + center + QPointF(-left_trigger_x, left_trigger_y + (right_pressed.value ? 0.5f : 0)); + } + + // Left trigger + p.setPen(colors.outline); + p.setBrush(left_pressed.value ? colors.highlight : colors.button); + DrawPolygon(p, qleft_trigger); + + // Right trigger + p.setBrush(right_pressed.value ? colors.highlight : colors.button); + DrawPolygon(p, qright_trigger); +} + +void PlayerControlPreview::DrawDualTriggers(QPainter& p, const QPointF center, + const Common::Input::ButtonStatus& left_pressed, + const Common::Input::ButtonStatus& right_pressed) { + std::array qleft_trigger; + std::array qright_trigger; + constexpr float size = 1.62f; + constexpr float offset = 210.6f; + for (std::size_t point = 0; point < left_joycon_trigger.size() / 2; ++point) { + const float left_trigger_x = left_joycon_trigger[point * 2 + 0]; + const float left_trigger_y = left_joycon_trigger[point * 2 + 1]; + + qleft_trigger[point] = + center + QPointF(left_trigger_x * size + offset, + left_trigger_y * size + (left_pressed.value ? 0.5f : 0)); + qright_trigger[point] = + center + QPointF(-left_trigger_x * size - offset, + left_trigger_y * size + (right_pressed.value ? 0.5f : 0)); + } + + // Left trigger + p.setPen(colors.outline); + p.setBrush(left_pressed.value ? colors.highlight : colors.button); + DrawPolygon(p, qleft_trigger); + + // Right trigger + p.setBrush(right_pressed.value ? colors.highlight : colors.button); + DrawPolygon(p, qright_trigger); +} + +void PlayerControlPreview::DrawDualTriggersTopView( + QPainter& p, const QPointF center, const Common::Input::ButtonStatus& left_pressed, + const Common::Input::ButtonStatus& right_pressed) { + std::array qleft_trigger; + std::array qright_trigger; + constexpr float size = 0.9f; + + for (std::size_t point = 0; point < left_joystick_L_topview.size() / 2; ++point) { + const float top_view_x = left_joystick_L_topview[point * 2 + 0]; + const float top_view_y = left_joystick_L_topview[point * 2 + 1]; + + qleft_trigger[point] = center + QPointF(top_view_x * size - 50, top_view_y * size - 52); + } + for (std::size_t point = 0; point < left_joystick_L_topview.size() / 2; ++point) { + const float top_view_x = left_joystick_L_topview[point * 2 + 0]; + const float top_view_y = left_joystick_L_topview[point * 2 + 1]; + + qright_trigger[point] = center + QPointF(-top_view_x * size + 50, top_view_y * size - 52); + } + + p.setPen(colors.outline); + p.setBrush(left_pressed.value ? colors.highlight : colors.button); + DrawPolygon(p, qleft_trigger); + p.setBrush(right_pressed.value ? colors.highlight : colors.button); + DrawPolygon(p, qright_trigger); + + // Draw L text + p.setPen(colors.transparent); + p.setBrush(colors.font2); + DrawSymbol(p, center + QPointF(-183, -84), Symbol::L, 1.0f); + + // Draw R text + p.setPen(colors.transparent); + p.setBrush(colors.font2); + DrawSymbol(p, center + QPointF(177, -84), Symbol::R, 1.0f); +} + +void PlayerControlPreview::DrawDualZTriggersTopView( + QPainter& p, const QPointF center, const Common::Input::ButtonStatus& left_pressed, + const Common::Input::ButtonStatus& right_pressed) { + std::array qleft_trigger; + std::array qright_trigger; + constexpr float size = 0.9f; + + for (std::size_t point = 0; point < left_joystick_ZL_topview.size() / 2; ++point) { + qleft_trigger[point] = + center + QPointF(left_joystick_ZL_topview[point * 2] * size - 52, + left_joystick_ZL_topview[point * 2 + 1] * size - 52); + } + for (std::size_t point = 0; point < left_joystick_ZL_topview.size() / 2; ++point) { + qright_trigger[point] = + center + QPointF(-left_joystick_ZL_topview[point * 2] * size + 52, + left_joystick_ZL_topview[point * 2 + 1] * size - 52); + } + + p.setPen(colors.outline); + p.setBrush(left_pressed.value ? colors.highlight : colors.button); + DrawPolygon(p, qleft_trigger); + p.setBrush(right_pressed.value ? colors.highlight : colors.button); + DrawPolygon(p, qright_trigger); + + // Draw ZL text + p.setPen(colors.transparent); + p.setBrush(colors.font2); + DrawSymbol(p, center + QPointF(-180, -113), Symbol::ZL, 1.0f); + + // Draw ZR text + p.setPen(colors.transparent); + p.setBrush(colors.font2); + DrawSymbol(p, center + QPointF(180, -113), Symbol::ZR, 1.0f); +} + +void PlayerControlPreview::DrawLeftTriggers(QPainter& p, const QPointF center, + const Common::Input::ButtonStatus& left_pressed) { + std::array qleft_trigger; + constexpr float size = 1.78f; + constexpr float offset = 311.5f; + + for (std::size_t point = 0; point < left_joycon_trigger.size() / 2; ++point) { + qleft_trigger[point] = center + QPointF(left_joycon_trigger[point * 2] * size + offset, + left_joycon_trigger[point * 2 + 1] * size - + (left_pressed.value ? 0.5f : 1.0f)); + } + + p.setPen(colors.outline); + p.setBrush(left_pressed.value ? colors.highlight : colors.button); + DrawPolygon(p, qleft_trigger); +} + +void PlayerControlPreview::DrawLeftZTriggers(QPainter& p, const QPointF center, + const Common::Input::ButtonStatus& left_pressed) { + std::array qleft_trigger; + constexpr float size = 1.1115f; + constexpr float offset2 = 335; + + for (std::size_t point = 0; point < left_joycon_sideview_zl.size() / 2; ++point) { + qleft_trigger[point] = center + QPointF(left_joycon_sideview_zl[point * 2] * size + offset2, + left_joycon_sideview_zl[point * 2 + 1] * size + + (left_pressed.value ? 1.5f : 1.0f)); + } + + p.setPen(colors.outline); + p.setBrush(left_pressed.value ? colors.highlight : colors.button); + DrawPolygon(p, qleft_trigger); + p.drawArc(center.x() + 158, center.y() + (left_pressed.value ? -203.5f : -204.0f), 77, 77, + 225 * 16, 44 * 16); +} + +void PlayerControlPreview::DrawLeftTriggersTopView( + QPainter& p, const QPointF center, const Common::Input::ButtonStatus& left_pressed) { + std::array qleft_trigger; + + for (std::size_t point = 0; point < left_joystick_L_topview.size() / 2; ++point) { + qleft_trigger[point] = center + QPointF(left_joystick_L_topview[point * 2], + left_joystick_L_topview[point * 2 + 1]); + } + + p.setPen(colors.outline); + p.setBrush(left_pressed.value ? colors.highlight : colors.button); + DrawPolygon(p, qleft_trigger); + + // Draw L text + p.setPen(colors.transparent); + p.setBrush(colors.font2); + DrawSymbol(p, center + QPointF(-143, -36), Symbol::L, 1.0f); +} + +void PlayerControlPreview::DrawLeftZTriggersTopView( + QPainter& p, const QPointF center, const Common::Input::ButtonStatus& left_pressed) { + std::array qleft_trigger; + + for (std::size_t point = 0; point < left_joystick_ZL_topview.size() / 2; ++point) { + qleft_trigger[point] = center + QPointF(left_joystick_ZL_topview[point * 2], + left_joystick_ZL_topview[point * 2 + 1]); + } + + p.setPen(colors.outline); + p.setBrush(left_pressed.value ? colors.highlight : colors.button); + DrawPolygon(p, qleft_trigger); + + // Draw ZL text + p.setPen(colors.transparent); + p.setBrush(colors.font2); + DrawSymbol(p, center + QPointF(-140, -68), Symbol::ZL, 1.0f); +} + +void PlayerControlPreview::DrawRightTriggers(QPainter& p, const QPointF center, + const Common::Input::ButtonStatus& right_pressed) { + std::array qright_trigger; + constexpr float size = 1.78f; + constexpr float offset = 311.5f; + + for (std::size_t point = 0; point < left_joycon_trigger.size() / 2; ++point) { + qright_trigger[point] = center + QPointF(-left_joycon_trigger[point * 2] * size - offset, + left_joycon_trigger[point * 2 + 1] * size - + (right_pressed.value ? 0.5f : 1.0f)); + } + + p.setPen(colors.outline); + p.setBrush(right_pressed.value ? colors.highlight : colors.button); + DrawPolygon(p, qright_trigger); +} + +void PlayerControlPreview::DrawRightZTriggers(QPainter& p, const QPointF center, + const Common::Input::ButtonStatus& right_pressed) { + std::array qright_trigger; + constexpr float size = 1.1115f; + constexpr float offset2 = 335; + + for (std::size_t point = 0; point < left_joycon_sideview_zl.size() / 2; ++point) { + qright_trigger[point] = + center + QPointF(-left_joycon_sideview_zl[point * 2] * size - offset2, + left_joycon_sideview_zl[point * 2 + 1] * size + + (right_pressed.value ? 0.5f : 0) + 1); + } + + p.setPen(colors.outline); + p.setBrush(right_pressed.value ? colors.highlight : colors.button); + DrawPolygon(p, qright_trigger); + p.drawArc(center.x() - 236, center.y() + (right_pressed.value ? -203.5f : -204.0f), 77, 77, + 271 * 16, 44 * 16); +} + +void PlayerControlPreview::DrawRightTriggersTopView( + QPainter& p, const QPointF center, const Common::Input::ButtonStatus& right_pressed) { + std::array qright_trigger; + + for (std::size_t point = 0; point < left_joystick_L_topview.size() / 2; ++point) { + qright_trigger[point] = center + QPointF(-left_joystick_L_topview[point * 2], + left_joystick_L_topview[point * 2 + 1]); + } + + p.setPen(colors.outline); + p.setBrush(right_pressed.value ? colors.highlight : colors.button); + DrawPolygon(p, qright_trigger); + + // Draw R text + p.setPen(colors.transparent); + p.setBrush(colors.font2); + DrawSymbol(p, center + QPointF(137, -36), Symbol::R, 1.0f); +} + +void PlayerControlPreview::DrawRightZTriggersTopView( + QPainter& p, const QPointF center, const Common::Input::ButtonStatus& right_pressed) { + std::array qright_trigger; + + for (std::size_t point = 0; point < left_joystick_ZL_topview.size() / 2; ++point) { + qright_trigger[point] = center + QPointF(-left_joystick_ZL_topview[point * 2], + left_joystick_ZL_topview[point * 2 + 1]); + } + + p.setPen(colors.outline); + p.setBrush(right_pressed.value ? colors.highlight : colors.button); + DrawPolygon(p, qright_trigger); + + // Draw ZR text + p.setPen(colors.transparent); + p.setBrush(colors.font2); + DrawSymbol(p, center + QPointF(140, -68), Symbol::ZR, 1.0f); +} + +void PlayerControlPreview::DrawJoystick(QPainter& p, const QPointF center, float size, + const Common::Input::ButtonStatus& pressed) { + const float radius1 = 13.0f * size; + const float radius2 = 9.0f * size; + + // Outer circle + p.setPen(colors.outline); + p.setBrush(pressed.value ? colors.highlight : colors.button); + DrawCircle(p, center, radius1); + + // Cross + p.drawLine(center - QPoint(radius1, 0), center + QPoint(radius1, 0)); + p.drawLine(center - QPoint(0, radius1), center + QPoint(0, radius1)); + + // Inner circle + p.setBrush(pressed.value ? colors.highlight2 : colors.button2); + DrawCircle(p, center, radius2); +} + +void PlayerControlPreview::DrawJoystickSideview(QPainter& p, const QPointF center, float angle, + float size, + const Common::Input::ButtonStatus& pressed) { + QVector joystick; + joystick.reserve(static_cast(left_joystick_sideview.size() / 2)); + + for (std::size_t point = 0; point < left_joystick_sideview.size() / 2; ++point) { + joystick.append(QPointF(left_joystick_sideview[point * 2] * size + (pressed.value ? 1 : 0), + left_joystick_sideview[point * 2 + 1] * size - 1)); + } + + // Rotate joystick + QTransform t; + t.translate(center.x(), center.y()); + t.rotate(18 * angle); + QPolygonF p2 = t.map(QPolygonF(joystick)); + + // Draw joystick + p.setPen(colors.outline); + p.setBrush(pressed.value ? colors.highlight : colors.button); + p.drawPolygon(p2); + p.drawLine(p2.at(1), p2.at(30)); + p.drawLine(p2.at(32), p2.at(71)); +} + +void PlayerControlPreview::DrawProJoystick(QPainter& p, const QPointF center, const QPointF offset, + float offset_scalar, + const Common::Input::ButtonStatus& pressed) { + const float radius1 = 24.0f; + const float radius2 = 17.0f; + + const QPointF offset_center = center + offset * offset_scalar; + + const auto amplitude = static_cast( + 1.0 - std::sqrt((offset.x() * offset.x()) + (offset.y() * offset.y())) * 0.1f); + + const float rotation = + ((offset.x() == 0) ? atan(1) * 2 : atan(offset.y() / offset.x())) * (180 / (atan(1) * 4)); + + p.save(); + p.translate(offset_center); + p.rotate(rotation); + + // Outer circle + p.setPen(colors.outline); + p.setBrush(pressed.value ? colors.highlight : colors.button); + p.drawEllipse(QPointF(0, 0), radius1 * amplitude, radius1); + + // Inner circle + p.setBrush(pressed.value ? colors.highlight2 : colors.button2); + + const float inner_offset = + (radius1 - radius2) * 0.4f * ((offset.x() == 0 && offset.y() < 0) ? -1.0f : 1.0f); + const float offset_factor = (1.0f - amplitude) / 0.1f; + + p.drawEllipse(QPointF((offset.x() < 0) ? -inner_offset : inner_offset, 0) * offset_factor, + radius2 * amplitude, radius2); + + p.restore(); +} + +void PlayerControlPreview::DrawGCJoystick(QPainter& p, const QPointF center, + const Common::Input::ButtonStatus& pressed) { + // Outer circle + p.setPen(colors.outline); + p.setBrush(pressed.value ? colors.highlight : colors.button); + DrawCircle(p, center, 26.0f); + + // Inner circle + p.setBrush(pressed.value ? colors.highlight2 : colors.button2); + DrawCircle(p, center, 19.0f); + p.setBrush(colors.transparent); + DrawCircle(p, center, 13.5f); + DrawCircle(p, center, 7.5f); +} + +void PlayerControlPreview::DrawRawJoystick(QPainter& p, QPointF center_left, QPointF center_right) { + using namespace Settings::NativeAnalog; + if (center_right != QPointF(0, 0)) { + DrawJoystickProperties(p, center_right, stick_values[RStick].x.properties); + p.setPen(colors.indicator); + p.setBrush(colors.indicator); + DrawJoystickDot(p, center_right, stick_values[RStick], true); + p.setPen(colors.indicator2); + p.setBrush(colors.indicator2); + DrawJoystickDot(p, center_right, stick_values[RStick], false); + } + + if (center_left != QPointF(0, 0)) { + DrawJoystickProperties(p, center_left, stick_values[LStick].x.properties); + p.setPen(colors.indicator); + p.setBrush(colors.indicator); + DrawJoystickDot(p, center_left, stick_values[LStick], true); + p.setPen(colors.indicator2); + p.setBrush(colors.indicator2); + DrawJoystickDot(p, center_left, stick_values[LStick], false); + } +} + +void PlayerControlPreview::DrawJoystickProperties( + QPainter& p, const QPointF center, const Common::Input::AnalogProperties& properties) { + constexpr float size = 45.0f; + const float range = size * properties.range; + const float deadzone = size * properties.deadzone; + + // Max range zone circle + p.setPen(colors.outline); + p.setBrush(colors.transparent); + QPen pen = p.pen(); + pen.setStyle(Qt::DotLine); + p.setPen(pen); + DrawCircle(p, center, range); + + // Deadzone circle + pen.setColor(colors.deadzone); + p.setPen(pen); + DrawCircle(p, center, deadzone); +} + +void PlayerControlPreview::DrawJoystickDot(QPainter& p, const QPointF center, + const Common::Input::StickStatus& stick, bool raw) { + constexpr float size = 45.0f; + const float range = size * stick.x.properties.range; + + if (raw) { + const QPointF value = QPointF(stick.x.raw_value, stick.y.raw_value) * size; + DrawCircle(p, center + value, 2); + return; + } + + const QPointF value = QPointF(stick.x.value, stick.y.value) * range; + DrawCircle(p, center + value, 2); +} + +void PlayerControlPreview::DrawRoundButton(QPainter& p, QPointF center, + const Common::Input::ButtonStatus& pressed, float width, + float height, Direction direction, float radius) { + if (pressed.value) { + switch (direction) { + case Direction::Left: + center.setX(center.x() - 1); + break; + case Direction::Right: + center.setX(center.x() + 1); + break; + case Direction::Down: + center.setY(center.y() + 1); + break; + case Direction::Up: + center.setY(center.y() - 1); + break; + case Direction::None: + break; + } + } + QRectF rect = {center.x() - width, center.y() - height, width * 2.0f, height * 2.0f}; + p.setBrush(GetButtonColor(button_color, pressed.value, pressed.turbo)); + p.drawRoundedRect(rect, radius, radius); +} +void PlayerControlPreview::DrawMinusButton(QPainter& p, const QPointF center, + const Common::Input::ButtonStatus& pressed, + int button_size) { + p.setPen(colors.outline); + p.setBrush(GetButtonColor(colors.button, pressed.value, pressed.turbo)); + DrawRectangle(p, center, button_size, button_size / 3.0f); +} +void PlayerControlPreview::DrawPlusButton(QPainter& p, const QPointF center, + const Common::Input::ButtonStatus& pressed, + int button_size) { + // Draw outer line + p.setPen(colors.outline); + p.setBrush(GetButtonColor(colors.button, pressed.value, pressed.turbo)); + DrawRectangle(p, center, button_size, button_size / 3.0f); + DrawRectangle(p, center, button_size / 3.0f, button_size); + + // Scale down size + button_size *= 0.88f; + + // Draw inner color + p.setPen(colors.transparent); + DrawRectangle(p, center, button_size, button_size / 3.0f); + DrawRectangle(p, center, button_size / 3.0f, button_size); +} + +void PlayerControlPreview::DrawGCButtonX(QPainter& p, const QPointF center, + const Common::Input::ButtonStatus& pressed) { + std::array button_x; + + for (std::size_t point = 0; point < gc_button_x.size() / 2; ++point) { + button_x[point] = center + QPointF(gc_button_x[point * 2], gc_button_x[point * 2 + 1]); + } + + p.setPen(colors.outline); + p.setBrush(GetButtonColor(colors.button, pressed.value, pressed.turbo)); + DrawPolygon(p, button_x); +} + +void PlayerControlPreview::DrawGCButtonY(QPainter& p, const QPointF center, + const Common::Input::ButtonStatus& pressed) { + std::array button_x; + + for (std::size_t point = 0; point < gc_button_y.size() / 2; ++point) { + button_x[point] = center + QPointF(gc_button_y[point * 2], gc_button_y[point * 2 + 1]); + } + + p.setPen(colors.outline); + p.setBrush(GetButtonColor(colors.button, pressed.value, pressed.turbo)); + DrawPolygon(p, button_x); +} + +void PlayerControlPreview::DrawGCButtonZ(QPainter& p, const QPointF center, + const Common::Input::ButtonStatus& pressed) { + std::array button_x; + + for (std::size_t point = 0; point < gc_button_z.size() / 2; ++point) { + button_x[point] = center + QPointF(gc_button_z[point * 2], + gc_button_z[point * 2 + 1] + (pressed.value ? 1 : 0)); + } + + p.setPen(colors.outline); + p.setBrush(GetButtonColor(colors.button2, pressed.value, pressed.turbo)); + DrawPolygon(p, button_x); +} + +void PlayerControlPreview::DrawCircleButton(QPainter& p, const QPointF center, + const Common::Input::ButtonStatus& pressed, + float button_size) { + + p.setBrush(GetButtonColor(button_color, pressed.value, pressed.turbo)); + p.drawEllipse(center, button_size, button_size); +} + +void PlayerControlPreview::DrawArrowButtonOutline(QPainter& p, const QPointF center, float size) { + const std::size_t arrow_points = up_arrow_button.size() / 2; + std::array arrow_button_outline; + + for (std::size_t point = 0; point < arrow_points - 1; ++point) { + const float up_arrow_x = up_arrow_button[point * 2 + 0]; + const float up_arrow_y = up_arrow_button[point * 2 + 1]; + + arrow_button_outline[point] = center + QPointF(up_arrow_x * size, up_arrow_y * size); + arrow_button_outline[(arrow_points - 1) * 2 - point - 1] = + center + QPointF(up_arrow_y * size, up_arrow_x * size); + arrow_button_outline[(arrow_points - 1) * 2 + point] = + center + QPointF(-up_arrow_x * size, -up_arrow_y * size); + arrow_button_outline[(arrow_points - 1) * 4 - point - 1] = + center + QPointF(-up_arrow_y * size, -up_arrow_x * size); + } + // Draw arrow button outline + p.setPen(colors.outline); + p.setBrush(colors.transparent); + DrawPolygon(p, arrow_button_outline); +} + +void PlayerControlPreview::DrawArrowButton(QPainter& p, const QPointF center, + const Direction direction, + const Common::Input::ButtonStatus& pressed, float size) { + std::array arrow_button; + QPoint offset; + + for (std::size_t point = 0; point < up_arrow_button.size() / 2; ++point) { + const float up_arrow_x = up_arrow_button[point * 2 + 0]; + const float up_arrow_y = up_arrow_button[point * 2 + 1]; + + switch (direction) { + case Direction::Up: + arrow_button[point] = center + QPointF(up_arrow_x * size, up_arrow_y * size); + break; + case Direction::Right: + arrow_button[point] = center + QPointF(-up_arrow_y * size, up_arrow_x * size); + break; + case Direction::Down: + arrow_button[point] = center + QPointF(up_arrow_x * size, -up_arrow_y * size); + break; + case Direction::Left: + // Compiler doesn't optimize this correctly check why + arrow_button[point] = center + QPointF(up_arrow_y * size, up_arrow_x * size); + break; + case Direction::None: + break; + } + } + + // Draw arrow button + p.setPen(pressed.value ? colors.highlight : colors.button); + p.setBrush(GetButtonColor(colors.button, pressed.value, pressed.turbo)); + DrawPolygon(p, arrow_button); + + switch (direction) { + case Direction::Up: + offset = QPoint(0, -20 * size); + break; + case Direction::Right: + offset = QPoint(20 * size, 0); + break; + case Direction::Down: + offset = QPoint(0, 20 * size); + break; + case Direction::Left: + offset = QPoint(-20 * size, 0); + break; + case Direction::None: + offset = QPoint(0, 0); + break; + } + + // Draw arrow icon + p.setPen(colors.font2); + p.setBrush(colors.font2); + DrawArrow(p, center + offset, direction, size); +} + +void PlayerControlPreview::DrawTriggerButton(QPainter& p, const QPointF center, + const Direction direction, + const Common::Input::ButtonStatus& pressed) { + std::array qtrigger_button; + + for (std::size_t point = 0; point < trigger_button.size() / 2; ++point) { + const float trigger_button_x = trigger_button[point * 2 + 0]; + const float trigger_button_y = trigger_button[point * 2 + 1]; + + switch (direction) { + case Direction::Left: + qtrigger_button[point] = center + QPointF(-trigger_button_x, trigger_button_y); + break; + case Direction::Right: + qtrigger_button[point] = center + QPointF(trigger_button_x, trigger_button_y); + break; + case Direction::Up: + case Direction::Down: + case Direction::None: + break; + } + } + + // Draw arrow button + p.setPen(colors.outline); + p.setBrush(GetButtonColor(colors.button, pressed.value, pressed.turbo)); + DrawPolygon(p, qtrigger_button); +} + +QColor PlayerControlPreview::GetButtonColor(QColor default_color, bool is_pressed, bool turbo) { + if (is_pressed && turbo) { + return colors.button_turbo; + } + if (is_pressed) { + return colors.highlight; + } + return default_color; +} + +void PlayerControlPreview::DrawBattery(QPainter& p, QPointF center, + Common::Input::BatteryLevel battery) { + if (battery == Common::Input::BatteryLevel::None) { + return; + } + // Draw outline + p.setPen(QPen(colors.button, 5)); + p.setBrush(colors.transparent); + p.drawRoundedRect(center.x(), center.y(), 34, 16, 2, 2); + + p.setPen(QPen(colors.button, 3)); + p.drawRect(center.x() + 35, center.y() + 4.5f, 4, 7); + + // Draw Battery shape + p.setPen(QPen(colors.indicator2, 3)); + p.setBrush(colors.transparent); + p.drawRoundedRect(center.x(), center.y(), 34, 16, 2, 2); + + p.setPen(QPen(colors.indicator2, 1)); + p.setBrush(colors.indicator2); + p.drawRect(center.x() + 35, center.y() + 4.5f, 4, 7); + switch (battery) { + case Common::Input::BatteryLevel::Charging: + p.drawRect(center.x(), center.y(), 34, 16); + p.setPen(colors.slider); + p.setBrush(colors.charging); + DrawSymbol(p, center + QPointF(17.0f, 8.0f), Symbol::Charging, 2.1f); + break; + case Common::Input::BatteryLevel::Full: + p.drawRect(center.x(), center.y(), 34, 16); + break; + case Common::Input::BatteryLevel::Medium: + p.drawRect(center.x(), center.y(), 25, 16); + break; + case Common::Input::BatteryLevel::Low: + p.drawRect(center.x(), center.y(), 17, 16); + break; + case Common::Input::BatteryLevel::Critical: + p.drawRect(center.x(), center.y(), 6, 16); + break; + case Common::Input::BatteryLevel::Empty: + p.drawRect(center.x(), center.y(), 3, 16); + break; + default: + break; + } +} + +void PlayerControlPreview::DrawSymbol(QPainter& p, const QPointF center, Symbol symbol, + float icon_size) { + std::array house_icon; + std::array a_icon; + std::array b_icon; + std::array x_icon; + std::array y_icon; + std::array l_icon; + std::array r_icon; + std::array c_icon; + std::array zl_icon; + std::array sl_icon; + std::array zr_icon; + std::array sr_icon; + std::array charging_icon; + switch (symbol) { + case Symbol::House: + for (std::size_t point = 0; point < house.size() / 2; ++point) { + house_icon[point] = center + QPointF(house[point * 2] * icon_size, + (house[point * 2 + 1] - 0.025f) * icon_size); + } + p.drawPolygon(house_icon.data(), static_cast(house_icon.size())); + break; + case Symbol::A: + for (std::size_t point = 0; point < symbol_a.size() / 2; ++point) { + a_icon[point] = center + QPointF(symbol_a[point * 2] * icon_size, + symbol_a[point * 2 + 1] * icon_size); + } + p.drawPolygon(a_icon.data(), static_cast(a_icon.size())); + break; + case Symbol::B: + for (std::size_t point = 0; point < symbol_b.size() / 2; ++point) { + b_icon[point] = center + QPointF(symbol_b[point * 2] * icon_size, + symbol_b[point * 2 + 1] * icon_size); + } + p.drawPolygon(b_icon.data(), static_cast(b_icon.size())); + break; + case Symbol::X: + for (std::size_t point = 0; point < symbol_x.size() / 2; ++point) { + x_icon[point] = center + QPointF(symbol_x[point * 2] * icon_size, + symbol_x[point * 2 + 1] * icon_size); + } + p.drawPolygon(x_icon.data(), static_cast(x_icon.size())); + break; + case Symbol::Y: + for (std::size_t point = 0; point < symbol_y.size() / 2; ++point) { + y_icon[point] = center + QPointF(symbol_y[point * 2] * icon_size, + (symbol_y[point * 2 + 1] - 1.0f) * icon_size); + } + p.drawPolygon(y_icon.data(), static_cast(y_icon.size())); + break; + case Symbol::L: + for (std::size_t point = 0; point < symbol_l.size() / 2; ++point) { + l_icon[point] = center + QPointF(symbol_l[point * 2] * icon_size, + (symbol_l[point * 2 + 1] - 1.0f) * icon_size); + } + p.drawPolygon(l_icon.data(), static_cast(l_icon.size())); + break; + case Symbol::R: + for (std::size_t point = 0; point < symbol_r.size() / 2; ++point) { + r_icon[point] = center + QPointF(symbol_r[point * 2] * icon_size, + (symbol_r[point * 2 + 1] - 1.0f) * icon_size); + } + p.drawPolygon(r_icon.data(), static_cast(r_icon.size())); + break; + case Symbol::C: + for (std::size_t point = 0; point < symbol_c.size() / 2; ++point) { + c_icon[point] = center + QPointF(symbol_c[point * 2] * icon_size, + (symbol_c[point * 2 + 1] - 1.0f) * icon_size); + } + p.drawPolygon(c_icon.data(), static_cast(c_icon.size())); + break; + case Symbol::ZL: + for (std::size_t point = 0; point < symbol_zl.size() / 2; ++point) { + zl_icon[point] = center + QPointF(symbol_zl[point * 2] * icon_size, + symbol_zl[point * 2 + 1] * icon_size); + } + p.drawPolygon(zl_icon.data(), static_cast(zl_icon.size())); + break; + case Symbol::SL: + for (std::size_t point = 0; point < symbol_sl.size() / 2; ++point) { + sl_icon[point] = center + QPointF(symbol_sl[point * 2] * icon_size, + symbol_sl[point * 2 + 1] * icon_size); + } + p.drawPolygon(sl_icon.data(), static_cast(sl_icon.size())); + break; + case Symbol::ZR: + for (std::size_t point = 0; point < symbol_zr.size() / 2; ++point) { + zr_icon[point] = center + QPointF(symbol_zr[point * 2] * icon_size, + symbol_zr[point * 2 + 1] * icon_size); + } + p.drawPolygon(zr_icon.data(), static_cast(zr_icon.size())); + break; + case Symbol::SR: + for (std::size_t point = 0; point < symbol_sr.size() / 2; ++point) { + sr_icon[point] = center + QPointF(symbol_sr[point * 2] * icon_size, + symbol_sr[point * 2 + 1] * icon_size); + } + p.drawPolygon(sr_icon.data(), static_cast(sr_icon.size())); + break; + case Symbol::Charging: + for (std::size_t point = 0; point < symbol_charging.size() / 2; ++point) { + charging_icon[point] = center + QPointF(symbol_charging[point * 2] * icon_size, + symbol_charging[point * 2 + 1] * icon_size); + } + p.drawPolygon(charging_icon.data(), static_cast(charging_icon.size())); + break; + } +} + +void PlayerControlPreview::DrawArrow(QPainter& p, const QPointF center, const Direction direction, + float size) { + + std::array arrow_symbol; + + for (std::size_t point = 0; point < up_arrow_symbol.size() / 2; ++point) { + const float up_arrow_x = up_arrow_symbol[point * 2 + 0]; + const float up_arrow_y = up_arrow_symbol[point * 2 + 1]; + + switch (direction) { + case Direction::Up: + arrow_symbol[point] = center + QPointF(up_arrow_x * size, up_arrow_y * size); + break; + case Direction::Left: + arrow_symbol[point] = center + QPointF(up_arrow_y * size, up_arrow_x * size); + break; + case Direction::Right: + arrow_symbol[point] = center + QPointF(-up_arrow_y * size, up_arrow_x * size); + break; + case Direction::Down: + arrow_symbol[point] = center + QPointF(up_arrow_x * size, -up_arrow_y * size); + break; + case Direction::None: + break; + } + } + + DrawPolygon(p, arrow_symbol); +} + +// Draw motion functions +void PlayerControlPreview::Draw3dCube(QPainter& p, QPointF center, const Common::Vec3f& euler, + float size) { + std::array cube{ + Common::Vec3f{-0.7f, -1, -0.5f}, + {-0.7f, 1, -0.5f}, + {0.7f, 1, -0.5f}, + {0.7f, -1, -0.5f}, + {-0.7f, -1, 0.5f}, + {-0.7f, 1, 0.5f}, + {0.7f, 1, 0.5f}, + {0.7f, -1, 0.5f}, + }; + + for (Common::Vec3f& point : cube) { + point.RotateFromOrigin(euler.x, euler.y, euler.z); + point *= size; + } + + const std::array front_face{ + center + QPointF{cube[0].x, cube[0].y}, + center + QPointF{cube[1].x, cube[1].y}, + center + QPointF{cube[2].x, cube[2].y}, + center + QPointF{cube[3].x, cube[3].y}, + }; + const std::array back_face{ + center + QPointF{cube[4].x, cube[4].y}, + center + QPointF{cube[5].x, cube[5].y}, + center + QPointF{cube[6].x, cube[6].y}, + center + QPointF{cube[7].x, cube[7].y}, + }; + + DrawPolygon(p, front_face); + DrawPolygon(p, back_face); + p.drawLine(center + QPointF{cube[0].x, cube[0].y}, center + QPointF{cube[4].x, cube[4].y}); + p.drawLine(center + QPointF{cube[1].x, cube[1].y}, center + QPointF{cube[5].x, cube[5].y}); + p.drawLine(center + QPointF{cube[2].x, cube[2].y}, center + QPointF{cube[6].x, cube[6].y}); + p.drawLine(center + QPointF{cube[3].x, cube[3].y}, center + QPointF{cube[7].x, cube[7].y}); +} + +template +void PlayerControlPreview::DrawPolygon(QPainter& p, const std::array& polygon) { + p.drawPolygon(polygon.data(), static_cast(polygon.size())); +} + +void PlayerControlPreview::DrawCircle(QPainter& p, const QPointF center, float size) { + p.drawEllipse(center, size, size); +} + +void PlayerControlPreview::DrawRectangle(QPainter& p, const QPointF center, float width, + float height) { + const QRectF rect = QRectF(center.x() - (width / 2), center.y() - (height / 2), width, height); + p.drawRect(rect); +} +void PlayerControlPreview::DrawRoundRectangle(QPainter& p, const QPointF center, float width, + float height, float round) { + const QRectF rect = QRectF(center.x() - (width / 2), center.y() - (height / 2), width, height); + p.drawRoundedRect(rect, round, round); +} + +void PlayerControlPreview::DrawText(QPainter& p, const QPointF center, float text_size, + const QString& text) { + SetTextFont(p, text_size); + const QFontMetrics fm(p.font()); + const QPointF offset = {fm.horizontalAdvance(text) / 2.0f, -text_size / 2.0f}; + p.drawText(center - offset, text); +} + +void PlayerControlPreview::SetTextFont(QPainter& p, float text_size, const QString& font_family) { + QFont font = p.font(); + font.setPointSizeF(text_size); + font.setFamily(font_family); + p.setFont(font); +} diff --git a/src/sudachi/configuration/configure_input_player_widget.h b/src/sudachi/configuration/configure_input_player_widget.h new file mode 100644 index 0000000..50bb862 --- /dev/null +++ b/src/sudachi/configuration/configure_input_player_widget.h @@ -0,0 +1,230 @@ +// SPDX-FileCopyrightText: Copyright 2020 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include +#include + +#include "common/input.h" +#include "common/settings_input.h" +#include "common/vector_math.h" +#include "hid_core/frontend/emulated_controller.h" +#include "hid_core/hid_types.h" + +class QLabel; + +using AnalogParam = std::array; +using ButtonParam = std::array; + +// Widget for representing controller animations +class PlayerControlPreview : public QFrame { + Q_OBJECT + +public: + explicit PlayerControlPreview(QWidget* parent); + ~PlayerControlPreview() override; + + // Sets the emulated controller to be displayed + void SetController(Core::HID::EmulatedController* controller); + + // Disables events from the emulated controller + void UnloadController(); + + // Starts blinking animation at the button specified + void BeginMappingButton(std::size_t button_id); + + // Starts moving animation at the stick specified + void BeginMappingAnalog(std::size_t stick_id); + + // Stops any ongoing animation + void EndMapping(); + + // Handles emulated controller events + void ControllerUpdate(Core::HID::ControllerTriggerType type); + + // Updates input on scheduled interval + void UpdateInput(); + +protected: + void paintEvent(QPaintEvent* event) override; + +private: + enum class Direction : std::size_t { + None, + Up, + Right, + Down, + Left, + }; + + enum class Symbol { + House, + A, + B, + X, + Y, + L, + R, + C, + SL, + ZL, + ZR, + SR, + Charging, + }; + + struct ColorMapping { + QColor outline{}; + QColor primary{}; + QColor left{}; + QColor right{}; + QColor button{}; + QColor button2{}; + QColor button_turbo{}; + QColor font{}; + QColor font2{}; + QColor highlight{}; + QColor highlight2{}; + QColor transparent{}; + QColor indicator{}; + QColor indicator2{}; + QColor led_on{}; + QColor led_off{}; + QColor slider{}; + QColor slider_button{}; + QColor slider_arrow{}; + QColor deadzone{}; + QColor charging{}; + }; + + void UpdateColors(); + void ResetInputs(); + + // Draw controller functions + void DrawHandheldController(QPainter& p, QPointF center); + void DrawDualController(QPainter& p, QPointF center); + void DrawLeftController(QPainter& p, QPointF center); + void DrawRightController(QPainter& p, QPointF center); + void DrawProController(QPainter& p, QPointF center); + void DrawGCController(QPainter& p, QPointF center); + + // Draw body functions + void DrawHandheldBody(QPainter& p, QPointF center); + void DrawDualBody(QPainter& p, QPointF center); + void DrawLeftBody(QPainter& p, QPointF center); + void DrawRightBody(QPainter& p, QPointF center); + void DrawProBody(QPainter& p, QPointF center); + void DrawGCBody(QPainter& p, QPointF center); + + // Draw triggers functions + void DrawProTriggers(QPainter& p, QPointF center, + const Common::Input::ButtonStatus& left_pressed, + const Common::Input::ButtonStatus& right_pressed); + void DrawGCTriggers(QPainter& p, QPointF center, Common::Input::TriggerStatus left_trigger, + Common::Input::TriggerStatus right_trigger); + void DrawHandheldTriggers(QPainter& p, QPointF center, + const Common::Input::ButtonStatus& left_pressed, + const Common::Input::ButtonStatus& right_pressed); + void DrawDualTriggers(QPainter& p, QPointF center, + const Common::Input::ButtonStatus& left_pressed, + const Common::Input::ButtonStatus& right_pressed); + void DrawDualTriggersTopView(QPainter& p, QPointF center, + const Common::Input::ButtonStatus& left_pressed, + const Common::Input::ButtonStatus& right_pressed); + void DrawDualZTriggersTopView(QPainter& p, QPointF center, + const Common::Input::ButtonStatus& left_pressed, + const Common::Input::ButtonStatus& right_pressed); + void DrawLeftTriggers(QPainter& p, QPointF center, + const Common::Input::ButtonStatus& left_pressed); + void DrawLeftZTriggers(QPainter& p, QPointF center, + const Common::Input::ButtonStatus& left_pressed); + void DrawLeftTriggersTopView(QPainter& p, QPointF center, + const Common::Input::ButtonStatus& left_pressed); + void DrawLeftZTriggersTopView(QPainter& p, QPointF center, + const Common::Input::ButtonStatus& left_pressed); + void DrawRightTriggers(QPainter& p, QPointF center, + const Common::Input::ButtonStatus& right_pressed); + void DrawRightZTriggers(QPainter& p, QPointF center, + const Common::Input::ButtonStatus& right_pressed); + void DrawRightTriggersTopView(QPainter& p, QPointF center, + const Common::Input::ButtonStatus& right_pressed); + void DrawRightZTriggersTopView(QPainter& p, QPointF center, + const Common::Input::ButtonStatus& right_pressed); + + // Draw joystick functions + void DrawJoystick(QPainter& p, QPointF center, float size, + const Common::Input::ButtonStatus& pressed); + void DrawJoystickSideview(QPainter& p, QPointF center, float angle, float size, + const Common::Input::ButtonStatus& pressed); + void DrawRawJoystick(QPainter& p, QPointF center_left, QPointF center_right); + void DrawJoystickProperties(QPainter& p, QPointF center, + const Common::Input::AnalogProperties& properties); + void DrawJoystickDot(QPainter& p, QPointF center, const Common::Input::StickStatus& stick, + bool raw); + void DrawProJoystick(QPainter& p, QPointF center, QPointF offset, float scalar, + const Common::Input::ButtonStatus& pressed); + void DrawGCJoystick(QPainter& p, QPointF center, const Common::Input::ButtonStatus& pressed); + + // Draw button functions + void DrawCircleButton(QPainter& p, QPointF center, const Common::Input::ButtonStatus& pressed, + float button_size); + void DrawRoundButton(QPainter& p, QPointF center, const Common::Input::ButtonStatus& pressed, + float width, float height, Direction direction = Direction::None, + float radius = 2); + void DrawMinusButton(QPainter& p, QPointF center, const Common::Input::ButtonStatus& pressed, + int button_size); + void DrawPlusButton(QPainter& p, QPointF center, const Common::Input::ButtonStatus& pressed, + int button_size); + void DrawGCButtonX(QPainter& p, QPointF center, const Common::Input::ButtonStatus& pressed); + void DrawGCButtonY(QPainter& p, QPointF center, const Common::Input::ButtonStatus& pressed); + void DrawGCButtonZ(QPainter& p, QPointF center, const Common::Input::ButtonStatus& pressed); + void DrawArrowButtonOutline(QPainter& p, const QPointF center, float size = 1.0f); + void DrawArrowButton(QPainter& p, QPointF center, Direction direction, + const Common::Input::ButtonStatus& pressed, float size = 1.0f); + void DrawTriggerButton(QPainter& p, QPointF center, Direction direction, + const Common::Input::ButtonStatus& pressed); + QColor GetButtonColor(QColor default_color, bool is_pressed, bool turbo); + + // Draw battery functions + void DrawBattery(QPainter& p, QPointF center, Common::Input::BatteryLevel battery); + + // Draw icon functions + void DrawSymbol(QPainter& p, QPointF center, Symbol symbol, float icon_size); + void DrawArrow(QPainter& p, QPointF center, Direction direction, float size); + + // Draw motion functions + void Draw3dCube(QPainter& p, QPointF center, const Common::Vec3f& euler, float size); + + // Draw primitive types + template + void DrawPolygon(QPainter& p, const std::array& polygon); + void DrawCircle(QPainter& p, QPointF center, float size); + void DrawRectangle(QPainter& p, QPointF center, float width, float height); + void DrawRoundRectangle(QPainter& p, QPointF center, float width, float height, float round); + void DrawText(QPainter& p, QPointF center, float text_size, const QString& text); + void SetTextFont(QPainter& p, float text_size, + const QString& font_family = QStringLiteral("sans-serif")); + + bool is_controller_set{}; + bool is_connected{}; + bool needs_redraw{}; + Core::HID::NpadStyleIndex controller_type; + + bool mapping_active{}; + int blink_counter{}; + int callback_key; + QColor button_color{}; + ColorMapping colors{}; + Core::HID::LedPattern led_pattern{0, 0, 0, 0}; + std::size_t player_index{}; + Core::HID::EmulatedController* controller; + std::size_t button_mapping_index{Settings::NativeButton::NumButtons}; + std::size_t analog_mapping_index{Settings::NativeAnalog::NumAnalogs}; + Core::HID::ButtonValues button_values{}; + Core::HID::SticksValues stick_values{}; + Core::HID::TriggerValues trigger_values{}; + Core::HID::BatteryValues battery_values{}; + Core::HID::MotionState motion_values{}; +}; diff --git a/src/sudachi/configuration/configure_input_profile_dialog.cpp b/src/sudachi/configuration/configure_input_profile_dialog.cpp new file mode 100644 index 0000000..1b68a26 --- /dev/null +++ b/src/sudachi/configuration/configure_input_profile_dialog.cpp @@ -0,0 +1,39 @@ +// SPDX-FileCopyrightText: Copyright 2020 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include "core/core.h" +#include "ui_configure_input_profile_dialog.h" +#include "sudachi/configuration/configure_input_player.h" +#include "sudachi/configuration/configure_input_profile_dialog.h" + +ConfigureInputProfileDialog::ConfigureInputProfileDialog( + QWidget* parent, InputCommon::InputSubsystem* input_subsystem, InputProfiles* profiles, + Core::System& system) + : QDialog(parent), ui(std::make_unique()), + profile_widget(new ConfigureInputPlayer(this, 9, nullptr, input_subsystem, profiles, + system.HIDCore(), system.IsPoweredOn(), false)) { + ui->setupUi(this); + + ui->controllerLayout->addWidget(profile_widget); + + connect(ui->clear_all_button, &QPushButton::clicked, this, + [this] { profile_widget->ClearAll(); }); + connect(ui->restore_defaults_button, &QPushButton::clicked, this, + [this] { profile_widget->RestoreDefaults(); }); + + RetranslateUI(); +} + +ConfigureInputProfileDialog::~ConfigureInputProfileDialog() = default; + +void ConfigureInputProfileDialog::changeEvent(QEvent* event) { + if (event->type() == QEvent::LanguageChange) { + RetranslateUI(); + } + + QDialog::changeEvent(event); +} + +void ConfigureInputProfileDialog::RetranslateUI() { + ui->retranslateUi(this); +} diff --git a/src/sudachi/configuration/configure_input_profile_dialog.h b/src/sudachi/configuration/configure_input_profile_dialog.h new file mode 100644 index 0000000..4b8334c --- /dev/null +++ b/src/sudachi/configuration/configure_input_profile_dialog.h @@ -0,0 +1,43 @@ +// SPDX-FileCopyrightText: Copyright 2020 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include + +class QPushButton; + +class ConfigureInputPlayer; + +class InputProfiles; + +namespace Core { +class System; +} + +namespace InputCommon { +class InputSubsystem; +} + +namespace Ui { +class ConfigureInputProfileDialog; +} + +class ConfigureInputProfileDialog : public QDialog { + Q_OBJECT + +public: + explicit ConfigureInputProfileDialog(QWidget* parent, + InputCommon::InputSubsystem* input_subsystem, + InputProfiles* profiles, Core::System& system); + ~ConfigureInputProfileDialog() override; + +private: + void changeEvent(QEvent* event) override; + void RetranslateUI(); + + std::unique_ptr ui; + + ConfigureInputPlayer* profile_widget; +}; diff --git a/src/sudachi/configuration/configure_input_profile_dialog.ui b/src/sudachi/configuration/configure_input_profile_dialog.ui new file mode 100644 index 0000000..726cf69 --- /dev/null +++ b/src/sudachi/configuration/configure_input_profile_dialog.ui @@ -0,0 +1,71 @@ + + + ConfigureInputProfileDialog + + + + 0 + 0 + 70 + 540 + + + + Create Input Profile + + + + 2 + + + 9 + + + 9 + + + 9 + + + 9 + + + + + + + + + + Clear + + + + + + + Defaults + + + + + + + QDialogButtonBox::Ok + + + + + + + + + + + buttonBox + accepted() + ConfigureInputProfileDialog + accept() + + + diff --git a/src/sudachi/configuration/configure_linux_tab.cpp b/src/sudachi/configuration/configure_linux_tab.cpp new file mode 100644 index 0000000..d5256a7 --- /dev/null +++ b/src/sudachi/configuration/configure_linux_tab.cpp @@ -0,0 +1,75 @@ +// SPDX-FileCopyrightText: Copyright 2019 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include "common/settings.h" +#include "core/core.h" +#include "ui_configure_linux_tab.h" +#include "sudachi/configuration/configuration_shared.h" +#include "sudachi/configuration/configure_linux_tab.h" +#include "sudachi/configuration/shared_widget.h" + +ConfigureLinuxTab::ConfigureLinuxTab(const Core::System& system_, + std::shared_ptr> group_, + const ConfigurationShared::Builder& builder, QWidget* parent) + : Tab(group_, parent), ui(std::make_unique()), system{system_} { + ui->setupUi(this); + + Setup(builder); + + SetConfiguration(); +} + +ConfigureLinuxTab::~ConfigureLinuxTab() = default; + +void ConfigureLinuxTab::SetConfiguration() {} +void ConfigureLinuxTab::Setup(const ConfigurationShared::Builder& builder) { + QLayout& linux_layout = *ui->linux_widget->layout(); + + std::map linux_hold{}; + + std::vector settings; + const auto push = [&](Settings::Category category) { + for (const auto setting : Settings::values.linkage.by_category[category]) { + settings.push_back(setting); + } + }; + + push(Settings::Category::Linux); + + for (auto* setting : settings) { + auto* widget = builder.BuildWidget(setting, apply_funcs); + + if (widget == nullptr) { + continue; + } + if (!widget->Valid()) { + widget->deleteLater(); + continue; + } + + linux_hold.insert({setting->Id(), widget}); + } + + for (const auto& [id, widget] : linux_hold) { + linux_layout.addWidget(widget); + } +} + +void ConfigureLinuxTab::ApplyConfiguration() { + const bool is_powered_on = system.IsPoweredOn(); + for (const auto& apply_func : apply_funcs) { + apply_func(is_powered_on); + } +} + +void ConfigureLinuxTab::changeEvent(QEvent* event) { + if (event->type() == QEvent::LanguageChange) { + RetranslateUI(); + } + + QWidget::changeEvent(event); +} + +void ConfigureLinuxTab::RetranslateUI() { + ui->retranslateUi(this); +} diff --git a/src/sudachi/configuration/configure_linux_tab.h b/src/sudachi/configuration/configure_linux_tab.h new file mode 100644 index 0000000..c7b85d8 --- /dev/null +++ b/src/sudachi/configuration/configure_linux_tab.h @@ -0,0 +1,44 @@ +// SPDX-FileCopyrightText: Copyright 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include + +namespace Core { +class System; +} + +namespace Ui { +class ConfigureLinuxTab; +} + +namespace ConfigurationShared { +class Builder; +} + +class ConfigureLinuxTab : public ConfigurationShared::Tab { + Q_OBJECT + +public: + explicit ConfigureLinuxTab(const Core::System& system_, + std::shared_ptr> group, + const ConfigurationShared::Builder& builder, + QWidget* parent = nullptr); + ~ConfigureLinuxTab() override; + + void ApplyConfiguration() override; + void SetConfiguration() override; + +private: + void changeEvent(QEvent* event) override; + void RetranslateUI(); + + void Setup(const ConfigurationShared::Builder& builder); + + std::unique_ptr ui; + + const Core::System& system; + + std::vector> apply_funcs{}; +}; diff --git a/src/sudachi/configuration/configure_linux_tab.ui b/src/sudachi/configuration/configure_linux_tab.ui new file mode 100644 index 0000000..f8e07f5 --- /dev/null +++ b/src/sudachi/configuration/configure_linux_tab.ui @@ -0,0 +1,53 @@ + + + ConfigureLinuxTab + + + Linux + + + + + + Linux + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + diff --git a/src/sudachi/configuration/configure_motion_touch.cpp b/src/sudachi/configuration/configure_motion_touch.cpp new file mode 100644 index 0000000..0d92ada --- /dev/null +++ b/src/sudachi/configuration/configure_motion_touch.cpp @@ -0,0 +1,326 @@ +// SPDX-FileCopyrightText: 2018 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include + +#include +#include +#include + +#include "common/logging/log.h" +#include "common/settings.h" +#include "input_common/drivers/udp_client.h" +#include "input_common/helpers/udp_protocol.h" +#include "input_common/main.h" +#include "ui_configure_motion_touch.h" +#include "sudachi/configuration/configure_motion_touch.h" +#include "sudachi/configuration/configure_touch_from_button.h" + +CalibrationConfigurationDialog::CalibrationConfigurationDialog(QWidget* parent, + const std::string& host, u16 port) + : QDialog(parent) { + layout = new QVBoxLayout; + status_label = new QLabel(tr("Communicating with the server...")); + cancel_button = new QPushButton(tr("Cancel")); + connect(cancel_button, &QPushButton::clicked, this, [this] { + if (!completed) { + job->Stop(); + } + accept(); + }); + layout->addWidget(status_label); + layout->addWidget(cancel_button); + setLayout(layout); + + using namespace InputCommon::CemuhookUDP; + job = std::make_unique( + host, port, + [this](CalibrationConfigurationJob::Status status) { + QMetaObject::invokeMethod(this, [status, this] { + QString text; + switch (status) { + case CalibrationConfigurationJob::Status::Ready: + text = tr("Touch the top left corner
of your touchpad."); + break; + case CalibrationConfigurationJob::Status::Stage1Completed: + text = tr("Now touch the bottom right corner
of your touchpad."); + break; + case CalibrationConfigurationJob::Status::Completed: + text = tr("Configuration completed!"); + break; + default: + break; + } + UpdateLabelText(text); + }); + if (status == CalibrationConfigurationJob::Status::Completed) { + QMetaObject::invokeMethod(this, [this] { UpdateButtonText(tr("OK")); }); + } + }, + [this](u16 min_x_, u16 min_y_, u16 max_x_, u16 max_y_) { + completed = true; + min_x = min_x_; + min_y = min_y_; + max_x = max_x_; + max_y = max_y_; + }); +} + +CalibrationConfigurationDialog::~CalibrationConfigurationDialog() = default; + +void CalibrationConfigurationDialog::UpdateLabelText(const QString& text) { + status_label->setText(text); +} + +void CalibrationConfigurationDialog::UpdateButtonText(const QString& text) { + cancel_button->setText(text); +} + +ConfigureMotionTouch::ConfigureMotionTouch(QWidget* parent, + InputCommon::InputSubsystem* input_subsystem_) + : QDialog(parent), input_subsystem{input_subsystem_}, + ui(std::make_unique()) { + ui->setupUi(this); + + ui->udp_learn_more->setOpenExternalLinks(true); + ui->udp_learn_more->setText( + tr("Learn More")); + + SetConfiguration(); + UpdateUiDisplay(); + ConnectEvents(); +} + +ConfigureMotionTouch::~ConfigureMotionTouch() = default; + +void ConfigureMotionTouch::SetConfiguration() { + const Common::ParamPackage touch_param(Settings::values.touch_device.GetValue()); + + touch_from_button_maps = Settings::values.touch_from_button_maps; + for (const auto& touch_map : touch_from_button_maps) { + ui->touch_from_button_map->addItem(QString::fromStdString(touch_map.name)); + } + ui->touch_from_button_map->setCurrentIndex( + Settings::values.touch_from_button_map_index.GetValue()); + + min_x = touch_param.Get("min_x", 100); + min_y = touch_param.Get("min_y", 50); + max_x = touch_param.Get("max_x", 1800); + max_y = touch_param.Get("max_y", 850); + + ui->udp_server->setText(QString::fromStdString("127.0.0.1")); + ui->udp_port->setText(QString::number(26760)); + + udp_server_list_model = new QStringListModel(this); + udp_server_list_model->setStringList({}); + ui->udp_server_list->setModel(udp_server_list_model); + + std::stringstream ss(Settings::values.udp_input_servers.GetValue()); + std::string token; + + while (std::getline(ss, token, ',')) { + const int row = udp_server_list_model->rowCount(); + udp_server_list_model->insertRows(row, 1); + const QModelIndex index = udp_server_list_model->index(row); + udp_server_list_model->setData(index, QString::fromStdString(token)); + } +} + +void ConfigureMotionTouch::UpdateUiDisplay() { + const QString cemuhook_udp = QStringLiteral("cemuhookudp"); + + ui->touch_calibration->setVisible(true); + ui->touch_calibration_config->setVisible(true); + ui->touch_calibration_label->setVisible(true); + ui->touch_calibration->setText( + QStringLiteral("(%1, %2) - (%3, %4)").arg(min_x).arg(min_y).arg(max_x).arg(max_y)); + + ui->udp_config_group_box->setVisible(true); +} + +void ConfigureMotionTouch::ConnectEvents() { + connect(ui->udp_test, &QPushButton::clicked, this, &ConfigureMotionTouch::OnCemuhookUDPTest); + connect(ui->udp_add, &QPushButton::clicked, this, &ConfigureMotionTouch::OnUDPAddServer); + connect(ui->udp_remove, &QPushButton::clicked, this, &ConfigureMotionTouch::OnUDPDeleteServer); + connect(ui->touch_calibration_config, &QPushButton::clicked, this, + &ConfigureMotionTouch::OnConfigureTouchCalibration); + connect(ui->touch_from_button_config_btn, &QPushButton::clicked, this, + &ConfigureMotionTouch::OnConfigureTouchFromButton); + connect(ui->buttonBox, &QDialogButtonBox::accepted, this, + &ConfigureMotionTouch::ApplyConfiguration); + connect(ui->buttonBox, &QDialogButtonBox::rejected, this, [this] { + if (CanCloseDialog()) { + reject(); + } + }); +} + +void ConfigureMotionTouch::OnUDPAddServer() { + // Validator for IP address + const QRegularExpression re(QStringLiteral( + R"re(^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$)re")); + bool ok; + const QString port_text = ui->udp_port->text(); + const QString server_text = ui->udp_server->text(); + const QString server_string = tr("%1:%2").arg(server_text, port_text); + const int port_number = port_text.toInt(&ok, 10); + const int row = udp_server_list_model->rowCount(); + + if (!ok) { + QMessageBox::warning(this, tr("sudachi"), tr("Port number has invalid characters")); + return; + } + if (port_number < 0 || port_number > 65353) { + QMessageBox::warning(this, tr("sudachi"), tr("Port has to be in range 0 and 65353")); + return; + } + if (!re.match(server_text).hasMatch()) { + QMessageBox::warning(this, tr("sudachi"), tr("IP address is not valid")); + return; + } + // Search for duplicates + for (const auto& item : udp_server_list_model->stringList()) { + if (item == server_string) { + QMessageBox::warning(this, tr("sudachi"), tr("This UDP server already exists")); + return; + } + } + // Limit server count to 8 + if (row == 8) { + QMessageBox::warning(this, tr("sudachi"), tr("Unable to add more than 8 servers")); + return; + } + + udp_server_list_model->insertRows(row, 1); + QModelIndex index = udp_server_list_model->index(row); + udp_server_list_model->setData(index, server_string); + ui->udp_server_list->setCurrentIndex(index); +} + +void ConfigureMotionTouch::OnUDPDeleteServer() { + udp_server_list_model->removeRows(ui->udp_server_list->currentIndex().row(), 1); +} + +void ConfigureMotionTouch::OnCemuhookUDPTest() { + ui->udp_test->setEnabled(false); + ui->udp_test->setText(tr("Testing")); + udp_test_in_progress = true; + InputCommon::CemuhookUDP::TestCommunication( + ui->udp_server->text().toStdString(), static_cast(ui->udp_port->text().toInt()), + [this] { + LOG_INFO(Frontend, "UDP input test success"); + QMetaObject::invokeMethod(this, [this] { ShowUDPTestResult(true); }); + }, + [this] { + LOG_ERROR(Frontend, "UDP input test failed"); + QMetaObject::invokeMethod(this, [this] { ShowUDPTestResult(false); }); + }); +} + +void ConfigureMotionTouch::OnConfigureTouchCalibration() { + ui->touch_calibration_config->setEnabled(false); + ui->touch_calibration_config->setText(tr("Configuring")); + CalibrationConfigurationDialog dialog(this, ui->udp_server->text().toStdString(), + static_cast(ui->udp_port->text().toUInt())); + dialog.exec(); + if (dialog.completed) { + min_x = dialog.min_x; + min_y = dialog.min_y; + max_x = dialog.max_x; + max_y = dialog.max_y; + LOG_INFO(Frontend, + "UDP touchpad calibration config success: min_x={}, min_y={}, max_x={}, max_y={}", + min_x, min_y, max_x, max_y); + UpdateUiDisplay(); + } else { + LOG_ERROR(Frontend, "UDP touchpad calibration config failed"); + } + ui->touch_calibration_config->setEnabled(true); + ui->touch_calibration_config->setText(tr("Configure")); +} + +void ConfigureMotionTouch::closeEvent(QCloseEvent* event) { + if (CanCloseDialog()) { + event->accept(); + } else { + event->ignore(); + } +} + +void ConfigureMotionTouch::ShowUDPTestResult(bool result) { + udp_test_in_progress = false; + if (result) { + QMessageBox::information(this, tr("Test Successful"), + tr("Successfully received data from the server.")); + } else { + QMessageBox::warning(this, tr("Test Failed"), + tr("Could not receive valid data from the server.
Please verify " + "that the server is set up correctly and " + "the address and port are correct.")); + } + ui->udp_test->setEnabled(true); + ui->udp_test->setText(tr("Test")); +} + +void ConfigureMotionTouch::OnConfigureTouchFromButton() { + ConfigureTouchFromButton dialog{this, touch_from_button_maps, input_subsystem, + ui->touch_from_button_map->currentIndex()}; + if (dialog.exec() != QDialog::Accepted) { + return; + } + touch_from_button_maps = dialog.GetMaps(); + + while (ui->touch_from_button_map->count() > 0) { + ui->touch_from_button_map->removeItem(0); + } + for (const auto& touch_map : touch_from_button_maps) { + ui->touch_from_button_map->addItem(QString::fromStdString(touch_map.name)); + } + ui->touch_from_button_map->setCurrentIndex(dialog.GetSelectedIndex()); +} + +bool ConfigureMotionTouch::CanCloseDialog() { + if (udp_test_in_progress) { + QMessageBox::warning(this, tr("sudachi"), + tr("UDP Test or calibration configuration is in progress.
Please " + "wait for them to finish.")); + return false; + } + return true; +} + +void ConfigureMotionTouch::ApplyConfiguration() { + if (!CanCloseDialog()) { + return; + } + + Common::ParamPackage touch_param{}; + touch_param.Set("min_x", min_x); + touch_param.Set("min_y", min_y); + touch_param.Set("max_x", max_x); + touch_param.Set("max_y", max_y); + + Settings::values.touch_device = touch_param.Serialize(); + Settings::values.touch_from_button_map_index = ui->touch_from_button_map->currentIndex(); + Settings::values.touch_from_button_maps = touch_from_button_maps; + Settings::values.udp_input_servers = GetUDPServerString(); + input_subsystem->ReloadInputDevices(); + + accept(); +} + +std::string ConfigureMotionTouch::GetUDPServerString() const { + QString input_servers; + + for (const auto& item : udp_server_list_model->stringList()) { + input_servers += item; + input_servers += QLatin1Char{','}; + } + + // Remove last comma + input_servers.chop(1); + return input_servers.toStdString(); +} diff --git a/src/sudachi/configuration/configure_motion_touch.h b/src/sudachi/configuration/configure_motion_touch.h new file mode 100644 index 0000000..a5db0de --- /dev/null +++ b/src/sudachi/configuration/configure_motion_touch.h @@ -0,0 +1,93 @@ +// SPDX-FileCopyrightText: 2018 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include + +class QLabel; +class QPushButton; +class QStringListModel; +class QVBoxLayout; + +namespace InputCommon { +class InputSubsystem; +} + +namespace InputCommon::CemuhookUDP { +class CalibrationConfigurationJob; +} + +namespace Ui { +class ConfigureMotionTouch; +} + +/// A dialog for touchpad calibration configuration. +class CalibrationConfigurationDialog : public QDialog { + Q_OBJECT + +public: + explicit CalibrationConfigurationDialog(QWidget* parent, const std::string& host, u16 port); + ~CalibrationConfigurationDialog() override; + +private: + Q_INVOKABLE void UpdateLabelText(const QString& text); + Q_INVOKABLE void UpdateButtonText(const QString& text); + + QVBoxLayout* layout; + QLabel* status_label; + QPushButton* cancel_button; + std::unique_ptr job; + + // Configuration results + bool completed{}; + u16 min_x{}; + u16 min_y{}; + u16 max_x{}; + u16 max_y{}; + + friend class ConfigureMotionTouch; +}; + +class ConfigureMotionTouch : public QDialog { + Q_OBJECT + +public: + explicit ConfigureMotionTouch(QWidget* parent, InputCommon::InputSubsystem* input_subsystem_); + ~ConfigureMotionTouch() override; + +public slots: + void ApplyConfiguration(); + +private slots: + void OnUDPAddServer(); + void OnUDPDeleteServer(); + void OnCemuhookUDPTest(); + void OnConfigureTouchCalibration(); + void OnConfigureTouchFromButton(); + +private: + void closeEvent(QCloseEvent* event) override; + Q_INVOKABLE void ShowUDPTestResult(bool result); + void SetConfiguration(); + void UpdateUiDisplay(); + void ConnectEvents(); + bool CanCloseDialog(); + std::string GetUDPServerString() const; + + InputCommon::InputSubsystem* input_subsystem; + + std::unique_ptr ui; + QStringListModel* udp_server_list_model; + + // Coordinate system of the CemuhookUDP touch provider + int min_x{}; + int min_y{}; + int max_x{}; + int max_y{}; + + bool udp_test_in_progress{}; + + std::vector touch_from_button_maps; +}; diff --git a/src/sudachi/configuration/configure_motion_touch.ui b/src/sudachi/configuration/configure_motion_touch.ui new file mode 100644 index 0000000..0237fae --- /dev/null +++ b/src/sudachi/configuration/configure_motion_touch.ui @@ -0,0 +1,297 @@ + + + ConfigureMotionTouch + + + Configure Motion / Touch + + + + + + + + + Touch + + + + + + + + UDP Calibration: + + + + + + + (100, 50) - (1800, 850) + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + + + + + + 0 + 0 + + + + Configure + + + + + + + + + + + Touch from button profile: + + + + + + + + + + + 0 + 0 + + + + Configure + + + + + + + + + + + + CemuhookUDP Config + + + + + + You may use any Cemuhook compatible UDP input source to provide motion and touch input. + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop + + + true + + + + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + 3 + + + 3 + + + 0 + + + + + Server: + + + + + + + + 0 + 0 + + + + + + + + + + 3 + + + 0 + + + + + Port: + + + + + + + + 0 + 0 + + + + + + + + + + 3 + + + 0 + + + + + Learn More + + + + + + + + 0 + 0 + + + + Test + + + + + + + + 0 + 0 + + + + Add Server + + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + 0 + + + + + + 0 + 0 + + + + Remove Server + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + + + + + + + Qt::Vertical + + + + 167 + 55 + + + + + + + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + + + + + + + diff --git a/src/sudachi/configuration/configure_mouse_panning.cpp b/src/sudachi/configuration/configure_mouse_panning.cpp new file mode 100644 index 0000000..f618a52 --- /dev/null +++ b/src/sudachi/configuration/configure_mouse_panning.cpp @@ -0,0 +1,90 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include + +#include "common/settings.h" +#include "ui_configure_mouse_panning.h" +#include "sudachi/configuration/configure_mouse_panning.h" + +ConfigureMousePanning::ConfigureMousePanning(QWidget* parent, + InputCommon::InputSubsystem* input_subsystem_, + float right_stick_deadzone, float right_stick_range) + : QDialog(parent), input_subsystem{input_subsystem_}, + ui(std::make_unique()) { + ui->setupUi(this); + SetConfiguration(right_stick_deadzone, right_stick_range); + ConnectEvents(); +} + +ConfigureMousePanning::~ConfigureMousePanning() = default; + +void ConfigureMousePanning::closeEvent(QCloseEvent* event) { + event->accept(); +} + +void ConfigureMousePanning::SetConfiguration(float right_stick_deadzone, float right_stick_range) { + ui->enable->setChecked(Settings::values.mouse_panning.GetValue()); + ui->x_sensitivity->setValue(Settings::values.mouse_panning_x_sensitivity.GetValue()); + ui->y_sensitivity->setValue(Settings::values.mouse_panning_y_sensitivity.GetValue()); + ui->deadzone_counterweight->setValue( + Settings::values.mouse_panning_deadzone_counterweight.GetValue()); + ui->decay_strength->setValue(Settings::values.mouse_panning_decay_strength.GetValue()); + ui->min_decay->setValue(Settings::values.mouse_panning_min_decay.GetValue()); + + if (right_stick_deadzone > 0.0f || right_stick_range != 1.0f) { + const QString right_stick_deadzone_str = + QString::fromStdString(std::to_string(static_cast(right_stick_deadzone * 100.0f))); + const QString right_stick_range_str = + QString::fromStdString(std::to_string(static_cast(right_stick_range * 100.0f))); + + ui->warning_label->setText( + tr("Mouse panning works better with a deadzone of 0% and a range of 100%.\nCurrent " + "values are %1% and %2% respectively.") + .arg(right_stick_deadzone_str, right_stick_range_str)); + } + + if (Settings::values.mouse_enabled) { + ui->warning_label->setText( + tr("Emulated mouse is enabled. This is incompatible with mouse panning.")); + } +} + +void ConfigureMousePanning::SetDefaultConfiguration() { + ui->x_sensitivity->setValue(Settings::values.mouse_panning_x_sensitivity.GetDefault()); + ui->y_sensitivity->setValue(Settings::values.mouse_panning_y_sensitivity.GetDefault()); + ui->deadzone_counterweight->setValue( + Settings::values.mouse_panning_deadzone_counterweight.GetDefault()); + ui->decay_strength->setValue(Settings::values.mouse_panning_decay_strength.GetDefault()); + ui->min_decay->setValue(Settings::values.mouse_panning_min_decay.GetDefault()); +} + +void ConfigureMousePanning::ConnectEvents() { + connect(ui->default_button, &QPushButton::clicked, this, + &ConfigureMousePanning::SetDefaultConfiguration); + connect(ui->button_box, &QDialogButtonBox::accepted, this, + &ConfigureMousePanning::ApplyConfiguration); + connect(ui->button_box, &QDialogButtonBox::rejected, this, [this] { reject(); }); +} + +void ConfigureMousePanning::ApplyConfiguration() { + Settings::values.mouse_panning = ui->enable->isChecked(); + Settings::values.mouse_panning_x_sensitivity = static_cast(ui->x_sensitivity->value()); + Settings::values.mouse_panning_y_sensitivity = static_cast(ui->y_sensitivity->value()); + Settings::values.mouse_panning_deadzone_counterweight = + static_cast(ui->deadzone_counterweight->value()); + Settings::values.mouse_panning_decay_strength = static_cast(ui->decay_strength->value()); + Settings::values.mouse_panning_min_decay = static_cast(ui->min_decay->value()); + + if (Settings::values.mouse_enabled && Settings::values.mouse_panning) { + Settings::values.mouse_panning = false; + QMessageBox::critical( + this, tr("Emulated mouse is enabled"), + tr("Real mouse input and mouse panning are incompatible. Please disable the " + "emulated mouse in input advanced settings to allow mouse panning.")); + return; + } + + accept(); +} diff --git a/src/sudachi/configuration/configure_mouse_panning.h b/src/sudachi/configuration/configure_mouse_panning.h new file mode 100644 index 0000000..40f6264 --- /dev/null +++ b/src/sudachi/configuration/configure_mouse_panning.h @@ -0,0 +1,36 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include + +namespace InputCommon { +class InputSubsystem; +} + +namespace Ui { +class ConfigureMousePanning; +} + +class ConfigureMousePanning : public QDialog { + Q_OBJECT + +public: + explicit ConfigureMousePanning(QWidget* parent, InputCommon::InputSubsystem* input_subsystem_, + float right_stick_deadzone, float right_stick_range); + ~ConfigureMousePanning() override; + +public slots: + void ApplyConfiguration(); + +private: + void closeEvent(QCloseEvent* event) override; + void SetConfiguration(float right_stick_deadzone, float right_stick_range); + void SetDefaultConfiguration(); + void ConnectEvents(); + + InputCommon::InputSubsystem* input_subsystem; + std::unique_ptr ui; +}; diff --git a/src/sudachi/configuration/configure_mouse_panning.ui b/src/sudachi/configuration/configure_mouse_panning.ui new file mode 100644 index 0000000..84fb7ee --- /dev/null +++ b/src/sudachi/configuration/configure_mouse_panning.ui @@ -0,0 +1,212 @@ + + + ConfigureMousePanning + + + Configure mouse panning + + + + + + Enable mouse panning + + + Can be toggled via a hotkey. Default hotkey is Ctrl + F9 + + + + + + + + + Sensitivity + + + + + + Horizontal + + + + + + + Qt::AlignCenter + + + % + + + 1 + + + 100 + + + 50 + + + + + + + Vertical + + + + + + + Qt::AlignCenter + + + % + + + 1 + + + 100 + + + 50 + + + + + + + + + + Deadzone counterweight + + + Counteracts a game's built-in deadzone + + + + + + Deadzone + + + + + + + Qt::AlignCenter + + + % + + + 0 + + + 100 + + + 0 + + + + + + + + + + Stick decay + + + + + + Strength + + + + + + + Qt::AlignCenter + + + % + + + 0 + + + 100 + + + 22 + + + + + + + Minimum + + + + + + + Qt::AlignCenter + + + % + + + 0 + + + 100 + + + 5 + + + + + + + + + + + + + + + + + + + + + Default + + + + + + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + + + + + + + + + diff --git a/src/sudachi/configuration/configure_network.cpp b/src/sudachi/configuration/configure_network.cpp new file mode 100644 index 0000000..6fe15e6 --- /dev/null +++ b/src/sudachi/configuration/configure_network.cpp @@ -0,0 +1,48 @@ +// SPDX-FileCopyrightText: Copyright 2019 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include "common/settings.h" +#include "core/core.h" +#include "core/internal_network/network_interface.h" +#include "ui_configure_network.h" +#include "sudachi/configuration/configure_network.h" + +ConfigureNetwork::ConfigureNetwork(const Core::System& system_, QWidget* parent) + : QWidget(parent), ui(std::make_unique()), system{system_} { + ui->setupUi(this); + + ui->network_interface->addItem(tr("None")); + for (const auto& iface : Network::GetAvailableNetworkInterfaces()) { + ui->network_interface->addItem(QString::fromStdString(iface.name)); + } + + this->SetConfiguration(); +} + +ConfigureNetwork::~ConfigureNetwork() = default; + +void ConfigureNetwork::ApplyConfiguration() { + Settings::values.network_interface = ui->network_interface->currentText().toStdString(); +} + +void ConfigureNetwork::changeEvent(QEvent* event) { + if (event->type() == QEvent::LanguageChange) { + RetranslateUI(); + } + + QWidget::changeEvent(event); +} + +void ConfigureNetwork::RetranslateUI() { + ui->retranslateUi(this); +} + +void ConfigureNetwork::SetConfiguration() { + const bool runtime_lock = !system.IsPoweredOn(); + + const std::string& network_interface = Settings::values.network_interface.GetValue(); + + ui->network_interface->setCurrentText(QString::fromStdString(network_interface)); + ui->network_interface->setEnabled(runtime_lock); +} diff --git a/src/sudachi/configuration/configure_network.h b/src/sudachi/configuration/configure_network.h new file mode 100644 index 0000000..9051276 --- /dev/null +++ b/src/sudachi/configuration/configure_network.h @@ -0,0 +1,30 @@ +// SPDX-FileCopyrightText: Copyright 2019 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include + +namespace Ui { +class ConfigureNetwork; +} + +class ConfigureNetwork : public QWidget { + Q_OBJECT + +public: + explicit ConfigureNetwork(const Core::System& system_, QWidget* parent = nullptr); + ~ConfigureNetwork() override; + + void ApplyConfiguration(); + +private: + void changeEvent(QEvent*) override; + void RetranslateUI(); + void SetConfiguration(); + + std::unique_ptr ui; + + const Core::System& system; +}; diff --git a/src/sudachi/configuration/configure_network.ui b/src/sudachi/configuration/configure_network.ui new file mode 100644 index 0000000..f10e973 --- /dev/null +++ b/src/sudachi/configuration/configure_network.ui @@ -0,0 +1,60 @@ + + + ConfigureNetwork + + + + 0 + 0 + 433 + 561 + + + + Form + + + Network + + + + + + + + General + + + + + + + + + Network Interface + + + + + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + diff --git a/src/sudachi/configuration/configure_per_game.cpp b/src/sudachi/configuration/configure_per_game.cpp new file mode 100644 index 0000000..ab889e5 --- /dev/null +++ b/src/sudachi/configuration/configure_per_game.cpp @@ -0,0 +1,204 @@ +// SPDX-FileCopyrightText: Copyright 2020 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include + +#include "common/fs/fs_util.h" +#include "common/settings_enums.h" +#include "common/settings_input.h" +#include "configuration/shared_widget.h" +#include "core/core.h" +#include "core/file_sys/control_metadata.h" +#include "core/file_sys/patch_manager.h" +#include "core/file_sys/xts_archive.h" +#include "core/loader/loader.h" +#include "frontend_common/config.h" +#include "ui_configure_per_game.h" +#include "sudachi/configuration/configuration_shared.h" +#include "sudachi/configuration/configure_audio.h" +#include "sudachi/configuration/configure_cpu.h" +#include "sudachi/configuration/configure_graphics.h" +#include "sudachi/configuration/configure_graphics_advanced.h" +#include "sudachi/configuration/configure_input_per_game.h" +#include "sudachi/configuration/configure_linux_tab.h" +#include "sudachi/configuration/configure_per_game.h" +#include "sudachi/configuration/configure_per_game_addons.h" +#include "sudachi/configuration/configure_system.h" +#include "sudachi/uisettings.h" +#include "sudachi/util/util.h" +#include "sudachi/vk_device_info.h" + +ConfigurePerGame::ConfigurePerGame(QWidget* parent, u64 title_id_, const std::string& file_name, + std::vector& vk_device_records, + Core::System& system_) + : QDialog(parent), + ui(std::make_unique()), title_id{title_id_}, system{system_}, + builder{std::make_unique(this, !system_.IsPoweredOn())}, + tab_group{std::make_shared>()} { + const auto file_path = std::filesystem::path(Common::FS::ToU8String(file_name)); + const auto config_file_name = title_id == 0 ? Common::FS::PathToUTF8String(file_path.filename()) + : fmt::format("{:016X}", title_id); + game_config = std::make_unique(config_file_name, Config::ConfigType::PerGameConfig); + addons_tab = std::make_unique(system_, this); + audio_tab = std::make_unique(system_, tab_group, *builder, this); + cpu_tab = std::make_unique(system_, tab_group, *builder, this); + graphics_advanced_tab = + std::make_unique(system_, tab_group, *builder, this); + graphics_tab = std::make_unique( + system_, vk_device_records, [&]() { graphics_advanced_tab->ExposeComputeOption(); }, + [](Settings::AspectRatio, Settings::ResolutionSetup) {}, tab_group, *builder, this); + input_tab = std::make_unique(system_, game_config.get(), this); + linux_tab = std::make_unique(system_, tab_group, *builder, this); + system_tab = std::make_unique(system_, tab_group, *builder, this); + + ui->setupUi(this); + + ui->tabWidget->addTab(addons_tab.get(), tr("Add-Ons")); + ui->tabWidget->addTab(system_tab.get(), tr("System")); + ui->tabWidget->addTab(cpu_tab.get(), tr("CPU")); + ui->tabWidget->addTab(graphics_tab.get(), tr("Graphics")); + ui->tabWidget->addTab(graphics_advanced_tab.get(), tr("Adv. Graphics")); + ui->tabWidget->addTab(audio_tab.get(), tr("Audio")); + ui->tabWidget->addTab(input_tab.get(), tr("Input Profiles")); + + // Only show Linux tab on Unix + linux_tab->setVisible(false); +#ifdef __unix__ + linux_tab->setVisible(true); + ui->tabWidget->addTab(linux_tab.get(), tr("Linux")); +#endif + + setFocusPolicy(Qt::ClickFocus); + setWindowTitle(tr("Properties")); + + addons_tab->SetTitleId(title_id); + + scene = new QGraphicsScene; + ui->icon_view->setScene(scene); + + if (system.IsPoweredOn()) { + QPushButton* apply_button = ui->buttonBox->addButton(QDialogButtonBox::Apply); + connect(apply_button, &QAbstractButton::clicked, this, + &ConfigurePerGame::HandleApplyButtonClicked); + } + + LoadConfiguration(); +} + +ConfigurePerGame::~ConfigurePerGame() = default; + +void ConfigurePerGame::ApplyConfiguration() { + for (const auto tab : *tab_group) { + tab->ApplyConfiguration(); + } + addons_tab->ApplyConfiguration(); + input_tab->ApplyConfiguration(); + + if (Settings::IsDockedMode() && Settings::values.players.GetValue()[0].controller_type == + Settings::ControllerType::Handheld) { + Settings::values.use_docked_mode.SetValue(Settings::ConsoleMode::Handheld); + Settings::values.use_docked_mode.SetGlobal(true); + } + + system.ApplySettings(); + Settings::LogSettings(); + + game_config->SaveAllValues(); +} + +void ConfigurePerGame::changeEvent(QEvent* event) { + if (event->type() == QEvent::LanguageChange) { + RetranslateUI(); + } + + QDialog::changeEvent(event); +} + +void ConfigurePerGame::RetranslateUI() { + ui->retranslateUi(this); +} + +void ConfigurePerGame::HandleApplyButtonClicked() { + UISettings::values.configuration_applied = true; + ApplyConfiguration(); +} + +void ConfigurePerGame::LoadFromFile(FileSys::VirtualFile file_) { + file = std::move(file_); + LoadConfiguration(); +} + +void ConfigurePerGame::LoadConfiguration() { + if (file == nullptr) { + return; + } + + addons_tab->LoadFromFile(file); + + ui->display_title_id->setText( + QStringLiteral("%1").arg(title_id, 16, 16, QLatin1Char{'0'}).toUpper()); + + const FileSys::PatchManager pm{title_id, system.GetFileSystemController(), + system.GetContentProvider()}; + const auto control = pm.GetControlMetadata(); + const auto loader = Loader::GetLoader(system, file); + + if (control.first != nullptr) { + ui->display_version->setText(QString::fromStdString(control.first->GetVersionString())); + ui->display_name->setText(QString::fromStdString(control.first->GetApplicationName())); + ui->display_developer->setText(QString::fromStdString(control.first->GetDeveloperName())); + } else { + std::string title; + if (loader->ReadTitle(title) == Loader::ResultStatus::Success) + ui->display_name->setText(QString::fromStdString(title)); + + FileSys::NACP nacp; + if (loader->ReadControlData(nacp) == Loader::ResultStatus::Success) + ui->display_developer->setText(QString::fromStdString(nacp.GetDeveloperName())); + + ui->display_version->setText(QStringLiteral("1.0.0")); + } + + if (control.second != nullptr) { + scene->clear(); + + QPixmap map; + const auto bytes = control.second->ReadAllBytes(); + map.loadFromData(bytes.data(), static_cast(bytes.size())); + + scene->addPixmap(map.scaled(ui->icon_view->width(), ui->icon_view->height(), + Qt::IgnoreAspectRatio, Qt::SmoothTransformation)); + } else { + std::vector bytes; + if (loader->ReadIcon(bytes) == Loader::ResultStatus::Success) { + scene->clear(); + + QPixmap map; + map.loadFromData(bytes.data(), static_cast(bytes.size())); + + scene->addPixmap(map.scaled(ui->icon_view->width(), ui->icon_view->height(), + Qt::IgnoreAspectRatio, Qt::SmoothTransformation)); + } + } + + ui->display_filename->setText(QString::fromStdString(file->GetName())); + + ui->display_format->setText( + QString::fromStdString(Loader::GetFileTypeString(loader->GetFileType()))); + + const auto valueText = ReadableByteSize(file->GetSize()); + ui->display_size->setText(valueText); +} diff --git a/src/sudachi/configuration/configure_per_game.h b/src/sudachi/configuration/configure_per_game.h new file mode 100644 index 0000000..89dc540 --- /dev/null +++ b/src/sudachi/configuration/configure_per_game.h @@ -0,0 +1,91 @@ +// SPDX-FileCopyrightText: Copyright 2020 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include +#include + +#include +#include + +#include "configuration/shared_widget.h" +#include "core/file_sys/vfs/vfs_types.h" +#include "frontend_common/config.h" +#include "vk_device_info.h" +#include "sudachi/configuration/configuration_shared.h" +#include "sudachi/configuration/qt_config.h" +#include "sudachi/configuration/shared_translation.h" + +namespace Core { +class System; +} + +namespace InputCommon { +class InputSubsystem; +} + +class ConfigurePerGameAddons; +class ConfigureAudio; +class ConfigureCpu; +class ConfigureGraphics; +class ConfigureGraphicsAdvanced; +class ConfigureInputPerGame; +class ConfigureLinuxTab; +class ConfigureSystem; + +class QGraphicsScene; +class QStandardItem; +class QStandardItemModel; +class QTreeView; +class QVBoxLayout; + +namespace Ui { +class ConfigurePerGame; +} + +class ConfigurePerGame : public QDialog { + Q_OBJECT + +public: + // Cannot use std::filesystem::path due to https://bugreports.qt.io/browse/QTBUG-73263 + explicit ConfigurePerGame(QWidget* parent, u64 title_id_, const std::string& file_name, + std::vector& vk_device_records, + Core::System& system_); + ~ConfigurePerGame() override; + + /// Save all button configurations to settings file + void ApplyConfiguration(); + + void LoadFromFile(FileSys::VirtualFile file_); + +private: + void changeEvent(QEvent* event) override; + void RetranslateUI(); + + void HandleApplyButtonClicked(); + + void LoadConfiguration(); + + std::unique_ptr ui; + FileSys::VirtualFile file; + u64 title_id; + + QGraphicsScene* scene; + + std::unique_ptr game_config; + + Core::System& system; + std::unique_ptr builder; + std::shared_ptr> tab_group; + + std::unique_ptr addons_tab; + std::unique_ptr audio_tab; + std::unique_ptr cpu_tab; + std::unique_ptr graphics_advanced_tab; + std::unique_ptr graphics_tab; + std::unique_ptr input_tab; + std::unique_ptr linux_tab; + std::unique_ptr system_tab; +}; diff --git a/src/sudachi/configuration/configure_per_game.ui b/src/sudachi/configuration/configure_per_game.ui new file mode 100644 index 0000000..99ba2fd --- /dev/null +++ b/src/sudachi/configuration/configure_per_game.ui @@ -0,0 +1,299 @@ + + + ConfigurePerGame + + + + 0 + 0 + 900 + 607 + + + + + 900 + 0 + + + + Dialog + + + + + + + + + 0 + 0 + + + + Info + + + + + + + 0 + 0 + + + + + 256 + 256 + + + + + 256 + 256 + + + + Qt::ScrollBarAlwaysOff + + + Qt::ScrollBarAlwaysOff + + + false + + + + + + + + + true + + + true + + + + + + + true + + + true + + + + + + + Name + + + + + + + Title ID + + + + + + + true + + + true + + + + + + + true + + + true + + + + + + + true + + + true + + + + + + + Filename + + + + + + + true + + + true + + + + + + + true + + + true + + + + + + + Format + + + + + + + Version + + + + + + + Size + + + + + + + Developer + + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + + + + + + + + true + + + -1 + + + true + + + false + + + false + + + + + + + + + + + + + Some settings are only available when a game is not running. + + + + + + + + 0 + 0 + + + + Qt::Horizontal + + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + + + + + + + + + + buttonBox + accepted() + ConfigurePerGame + accept() + + + 20 + 20 + + + 20 + 20 + + + + + buttonBox + rejected() + ConfigurePerGame + reject() + + + 20 + 20 + + + 20 + 20 + + + + + diff --git a/src/sudachi/configuration/configure_per_game_addons.cpp b/src/sudachi/configuration/configure_per_game_addons.cpp new file mode 100644 index 0000000..0a39296 --- /dev/null +++ b/src/sudachi/configuration/configure_per_game_addons.cpp @@ -0,0 +1,143 @@ +// SPDX-FileCopyrightText: 2016 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "common/fs/fs.h" +#include "common/fs/path_util.h" +#include "core/core.h" +#include "core/file_sys/patch_manager.h" +#include "core/file_sys/xts_archive.h" +#include "core/loader/loader.h" +#include "ui_configure_per_game_addons.h" +#include "sudachi/configuration/configure_input.h" +#include "sudachi/configuration/configure_per_game_addons.h" +#include "sudachi/uisettings.h" + +ConfigurePerGameAddons::ConfigurePerGameAddons(Core::System& system_, QWidget* parent) + : QWidget(parent), ui{std::make_unique()}, system{system_} { + ui->setupUi(this); + + layout = new QVBoxLayout; + tree_view = new QTreeView; + item_model = new QStandardItemModel(tree_view); + tree_view->setModel(item_model); + tree_view->setAlternatingRowColors(true); + tree_view->setSelectionMode(QHeaderView::SingleSelection); + tree_view->setSelectionBehavior(QHeaderView::SelectRows); + tree_view->setVerticalScrollMode(QHeaderView::ScrollPerPixel); + tree_view->setHorizontalScrollMode(QHeaderView::ScrollPerPixel); + tree_view->setSortingEnabled(true); + tree_view->setEditTriggers(QHeaderView::NoEditTriggers); + tree_view->setUniformRowHeights(true); + tree_view->setContextMenuPolicy(Qt::NoContextMenu); + + item_model->insertColumns(0, 2); + item_model->setHeaderData(0, Qt::Horizontal, tr("Patch Name")); + item_model->setHeaderData(1, Qt::Horizontal, tr("Version")); + + tree_view->header()->setStretchLastSection(false); + tree_view->header()->setSectionResizeMode(0, QHeaderView::ResizeMode::Stretch); + tree_view->header()->setMinimumSectionSize(150); + + // We must register all custom types with the Qt Automoc system so that we are able to use it + // with signals/slots. In this case, QList falls under the umbrella of custom types. + qRegisterMetaType>("QList"); + + layout->setContentsMargins(0, 0, 0, 0); + layout->setSpacing(0); + layout->addWidget(tree_view); + + ui->scrollArea->setLayout(layout); + + ui->scrollArea->setEnabled(!system.IsPoweredOn()); + + connect(item_model, &QStandardItemModel::itemChanged, + [] { UISettings::values.is_game_list_reload_pending.exchange(true); }); +} + +ConfigurePerGameAddons::~ConfigurePerGameAddons() = default; + +void ConfigurePerGameAddons::ApplyConfiguration() { + std::vector disabled_addons; + + for (const auto& item : list_items) { + const auto disabled = item.front()->checkState() == Qt::Unchecked; + if (disabled) + disabled_addons.push_back(item.front()->text().toStdString()); + } + + auto current = Settings::values.disabled_addons[title_id]; + std::sort(disabled_addons.begin(), disabled_addons.end()); + std::sort(current.begin(), current.end()); + if (disabled_addons != current) { + Common::FS::RemoveFile(Common::FS::GetSudachiPath(Common::FS::SudachiPath::CacheDir) / + "game_list" / fmt::format("{:016X}.pv.txt", title_id)); + } + + Settings::values.disabled_addons[title_id] = disabled_addons; +} + +void ConfigurePerGameAddons::LoadFromFile(FileSys::VirtualFile file_) { + file = std::move(file_); + LoadConfiguration(); +} + +void ConfigurePerGameAddons::SetTitleId(u64 id) { + this->title_id = id; +} + +void ConfigurePerGameAddons::changeEvent(QEvent* event) { + if (event->type() == QEvent::LanguageChange) { + RetranslateUI(); + } + + QWidget::changeEvent(event); +} + +void ConfigurePerGameAddons::RetranslateUI() { + ui->retranslateUi(this); +} + +void ConfigurePerGameAddons::LoadConfiguration() { + if (file == nullptr) { + return; + } + + const FileSys::PatchManager pm{title_id, system.GetFileSystemController(), + system.GetContentProvider()}; + const auto loader = Loader::GetLoader(system, file); + + FileSys::VirtualFile update_raw; + loader->ReadUpdateRaw(update_raw); + + const auto& disabled = Settings::values.disabled_addons[title_id]; + + for (const auto& patch : pm.GetPatches(update_raw)) { + const auto name = QString::fromStdString(patch.name); + + auto* const first_item = new QStandardItem; + first_item->setText(name); + first_item->setCheckable(true); + + const auto patch_disabled = + std::find(disabled.begin(), disabled.end(), name.toStdString()) != disabled.end(); + + first_item->setCheckState(patch_disabled ? Qt::Unchecked : Qt::Checked); + + list_items.push_back(QList{ + first_item, new QStandardItem{QString::fromStdString(patch.version)}}); + item_model->appendRow(list_items.back()); + } + + tree_view->resizeColumnToContents(1); +} diff --git a/src/sudachi/configuration/configure_per_game_addons.h b/src/sudachi/configuration/configure_per_game_addons.h new file mode 100644 index 0000000..32dc5dd --- /dev/null +++ b/src/sudachi/configuration/configure_per_game_addons.h @@ -0,0 +1,58 @@ +// SPDX-FileCopyrightText: 2016 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include + +#include + +#include "core/file_sys/vfs/vfs_types.h" + +namespace Core { +class System; +} + +class QGraphicsScene; +class QStandardItem; +class QStandardItemModel; +class QTreeView; +class QVBoxLayout; + +namespace Ui { +class ConfigurePerGameAddons; +} + +class ConfigurePerGameAddons : public QWidget { + Q_OBJECT + +public: + explicit ConfigurePerGameAddons(Core::System& system_, QWidget* parent = nullptr); + ~ConfigurePerGameAddons() override; + + /// Save all button configurations to settings file + void ApplyConfiguration(); + + void LoadFromFile(FileSys::VirtualFile file_); + + void SetTitleId(u64 id); + +private: + void changeEvent(QEvent* event) override; + void RetranslateUI(); + + void LoadConfiguration(); + + std::unique_ptr ui; + FileSys::VirtualFile file; + u64 title_id; + + QVBoxLayout* layout; + QTreeView* tree_view; + QStandardItemModel* item_model; + + std::vector> list_items; + + Core::System& system; +}; diff --git a/src/sudachi/configuration/configure_per_game_addons.ui b/src/sudachi/configuration/configure_per_game_addons.ui new file mode 100644 index 0000000..f9cf6f2 --- /dev/null +++ b/src/sudachi/configuration/configure_per_game_addons.ui @@ -0,0 +1,41 @@ + + + ConfigurePerGameAddons + + + + 0 + 0 + 400 + 300 + + + + Form + + + Add-Ons + + + + + + true + + + + + 0 + 0 + 380 + 280 + + + + + + + + + + diff --git a/src/sudachi/configuration/configure_profile_manager.cpp b/src/sudachi/configuration/configure_profile_manager.cpp new file mode 100644 index 0000000..49109c0 --- /dev/null +++ b/src/sudachi/configuration/configure_profile_manager.cpp @@ -0,0 +1,372 @@ +// SPDX-FileCopyrightText: 2016 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "common/assert.h" +#include "common/fs/path_util.h" +#include "common/settings.h" +#include "common/string_util.h" +#include "core/core.h" +#include "core/hle/service/acc/profile_manager.h" +#include "ui_configure_profile_manager.h" +#include "sudachi/configuration/configure_profile_manager.h" +#include "sudachi/util/limitable_input_dialog.h" + +namespace { +// Same backup JPEG used by acc IProfile::GetImage if no jpeg found +constexpr std::array backup_jpeg{ + 0xff, 0xd8, 0xff, 0xdb, 0x00, 0x43, 0x00, 0x03, 0x02, 0x02, 0x02, 0x02, 0x02, 0x03, 0x02, 0x02, + 0x02, 0x03, 0x03, 0x03, 0x03, 0x04, 0x06, 0x04, 0x04, 0x04, 0x04, 0x04, 0x08, 0x06, 0x06, 0x05, + 0x06, 0x09, 0x08, 0x0a, 0x0a, 0x09, 0x08, 0x09, 0x09, 0x0a, 0x0c, 0x0f, 0x0c, 0x0a, 0x0b, 0x0e, + 0x0b, 0x09, 0x09, 0x0d, 0x11, 0x0d, 0x0e, 0x0f, 0x10, 0x10, 0x11, 0x10, 0x0a, 0x0c, 0x12, 0x13, + 0x12, 0x10, 0x13, 0x0f, 0x10, 0x10, 0x10, 0xff, 0xc9, 0x00, 0x0b, 0x08, 0x00, 0x01, 0x00, 0x01, + 0x01, 0x01, 0x11, 0x00, 0xff, 0xcc, 0x00, 0x06, 0x00, 0x10, 0x10, 0x05, 0xff, 0xda, 0x00, 0x08, + 0x01, 0x01, 0x00, 0x00, 0x3f, 0x00, 0xd2, 0xcf, 0x20, 0xff, 0xd9, +}; + +QString GetImagePath(const Common::UUID& uuid) { + const auto path = + Common::FS::GetSudachiPath(Common::FS::SudachiPath::NANDDir) / + fmt::format("system/save/8000000000000010/su/avators/{}.jpg", uuid.FormattedString()); + return QString::fromStdString(Common::FS::PathToUTF8String(path)); +} + +QString GetAccountUsername(const Service::Account::ProfileManager& manager, Common::UUID uuid) { + Service::Account::ProfileBase profile{}; + if (!manager.GetProfileBase(uuid, profile)) { + return {}; + } + + const auto text = Common::StringFromFixedZeroTerminatedBuffer( + reinterpret_cast(profile.username.data()), profile.username.size()); + return QString::fromStdString(text); +} + +QString FormatUserEntryText(const QString& username, Common::UUID uuid) { + return ConfigureProfileManager::tr("%1\n%2", + "%1 is the profile username, %2 is the formatted UUID (e.g. " + "00112233-4455-6677-8899-AABBCCDDEEFF))") + .arg(username, QString::fromStdString(uuid.FormattedString())); +} + +QPixmap GetIcon(const Common::UUID& uuid) { + QPixmap icon{GetImagePath(uuid)}; + + if (!icon) { + icon.fill(Qt::black); + icon.loadFromData(backup_jpeg.data(), static_cast(backup_jpeg.size())); + } + + return icon.scaled(64, 64, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); +} + +QString GetProfileUsernameFromUser(QWidget* parent, const QString& description_text) { + return LimitableInputDialog::GetText(parent, ConfigureProfileManager::tr("Enter Username"), + description_text, 1, + static_cast(Service::Account::profile_username_size)); +} +} // Anonymous namespace + +ConfigureProfileManager::ConfigureProfileManager(Core::System& system_, QWidget* parent) + : QWidget(parent), ui{std::make_unique()}, + profile_manager{system_.GetProfileManager()}, system{system_} { + ui->setupUi(this); + + tree_view = new QTreeView; + item_model = new QStandardItemModel(tree_view); + item_model->insertColumns(0, 1); + tree_view->setModel(item_model); + tree_view->setAlternatingRowColors(true); + tree_view->setSelectionMode(QHeaderView::SingleSelection); + tree_view->setSelectionBehavior(QHeaderView::SelectRows); + tree_view->setVerticalScrollMode(QHeaderView::ScrollPerPixel); + tree_view->setHorizontalScrollMode(QHeaderView::ScrollPerPixel); + tree_view->setSortingEnabled(true); + tree_view->setEditTriggers(QHeaderView::NoEditTriggers); + tree_view->setUniformRowHeights(true); + tree_view->setIconSize({64, 64}); + tree_view->setContextMenuPolicy(Qt::NoContextMenu); + + // We must register all custom types with the Qt Automoc system so that we are able to use it + // with signals/slots. In this case, QList falls under the umbrells of custom types. + qRegisterMetaType>("QList"); + + layout = new QVBoxLayout; + layout->setContentsMargins(0, 0, 0, 0); + layout->setSpacing(0); + layout->addWidget(tree_view); + + ui->scrollArea->setLayout(layout); + + connect(tree_view, &QTreeView::clicked, this, &ConfigureProfileManager::SelectUser); + + connect(ui->pm_add, &QPushButton::clicked, this, &ConfigureProfileManager::AddUser); + connect(ui->pm_rename, &QPushButton::clicked, this, &ConfigureProfileManager::RenameUser); + connect(ui->pm_remove, &QPushButton::clicked, this, + &ConfigureProfileManager::ConfirmDeleteUser); + connect(ui->pm_set_image, &QPushButton::clicked, this, &ConfigureProfileManager::SetUserImage); + + confirm_dialog = new ConfigureProfileManagerDeleteDialog(this); + + scene = new QGraphicsScene; + ui->current_user_icon->setScene(scene); + + RetranslateUI(); + SetConfiguration(); +} + +ConfigureProfileManager::~ConfigureProfileManager() = default; + +void ConfigureProfileManager::changeEvent(QEvent* event) { + if (event->type() == QEvent::LanguageChange) { + RetranslateUI(); + } + + QWidget::changeEvent(event); +} + +void ConfigureProfileManager::RetranslateUI() { + ui->retranslateUi(this); + item_model->setHeaderData(0, Qt::Horizontal, tr("Users")); +} + +void ConfigureProfileManager::SetConfiguration() { + enabled = !system.IsPoweredOn(); + item_model->removeRows(0, item_model->rowCount()); + list_items.clear(); + + PopulateUserList(); + UpdateCurrentUser(); +} + +void ConfigureProfileManager::PopulateUserList() { + const auto& profiles = profile_manager.GetAllUsers(); + for (const auto& user : profiles) { + Service::Account::ProfileBase profile{}; + if (!profile_manager.GetProfileBase(user, profile)) + continue; + + const auto username = Common::StringFromFixedZeroTerminatedBuffer( + reinterpret_cast(profile.username.data()), profile.username.size()); + + list_items.push_back(QList{new QStandardItem{ + GetIcon(user), FormatUserEntryText(QString::fromStdString(username), user)}}); + } + + for (const auto& item : list_items) + item_model->appendRow(item); +} + +void ConfigureProfileManager::UpdateCurrentUser() { + ui->pm_add->setEnabled(profile_manager.GetUserCount() < Service::Account::MAX_USERS); + + const auto& current_user = profile_manager.GetUser(Settings::values.current_user.GetValue()); + ASSERT(current_user); + const auto username = GetAccountUsername(profile_manager, *current_user); + + scene->clear(); + scene->addPixmap( + GetIcon(*current_user).scaled(48, 48, Qt::IgnoreAspectRatio, Qt::SmoothTransformation)); + ui->current_user_username->setText(username); +} + +void ConfigureProfileManager::ApplyConfiguration() { + if (!enabled) { + return; + } +} + +void ConfigureProfileManager::SelectUser(const QModelIndex& index) { + Settings::values.current_user = + std::clamp(index.row(), 0, static_cast(profile_manager.GetUserCount() - 1)); + + UpdateCurrentUser(); + + ui->pm_remove->setEnabled(profile_manager.GetUserCount() >= 2); + ui->pm_rename->setEnabled(true); + ui->pm_set_image->setEnabled(true); +} + +void ConfigureProfileManager::AddUser() { + const auto username = + GetProfileUsernameFromUser(this, tr("Enter a username for the new user:")); + if (username.isEmpty()) { + return; + } + + const auto uuid = Common::UUID::MakeRandom(); + profile_manager.CreateNewUser(uuid, username.toStdString()); + profile_manager.WriteUserSaveFile(); + + item_model->appendRow(new QStandardItem{GetIcon(uuid), FormatUserEntryText(username, uuid)}); +} + +void ConfigureProfileManager::RenameUser() { + const auto user = tree_view->currentIndex().row(); + const auto uuid = profile_manager.GetUser(user); + ASSERT(uuid); + + Service::Account::ProfileBase profile{}; + if (!profile_manager.GetProfileBase(*uuid, profile)) + return; + + const auto new_username = GetProfileUsernameFromUser(this, tr("Enter a new username:")); + if (new_username.isEmpty()) { + return; + } + + const auto username_std = new_username.toStdString(); + std::fill(profile.username.begin(), profile.username.end(), '\0'); + std::copy(username_std.begin(), username_std.end(), profile.username.begin()); + + profile_manager.SetProfileBase(*uuid, profile); + profile_manager.WriteUserSaveFile(); + + item_model->setItem( + user, 0, + new QStandardItem{GetIcon(*uuid), + FormatUserEntryText(QString::fromStdString(username_std), *uuid)}); + UpdateCurrentUser(); +} + +void ConfigureProfileManager::ConfirmDeleteUser() { + const auto index = tree_view->currentIndex().row(); + const auto uuid = profile_manager.GetUser(index); + ASSERT(uuid); + const auto username = GetAccountUsername(profile_manager, *uuid); + + confirm_dialog->SetInfo(username, *uuid, [this, uuid]() { DeleteUser(*uuid); }); + confirm_dialog->show(); +} + +void ConfigureProfileManager::DeleteUser(const Common::UUID& uuid) { + if (Settings::values.current_user.GetValue() == tree_view->currentIndex().row()) { + Settings::values.current_user = 0; + } + UpdateCurrentUser(); + + if (!profile_manager.RemoveUser(uuid)) { + return; + } + + profile_manager.WriteUserSaveFile(); + + item_model->removeRows(tree_view->currentIndex().row(), 1); + tree_view->clearSelection(); + + ui->pm_remove->setEnabled(false); + ui->pm_rename->setEnabled(false); +} + +void ConfigureProfileManager::SetUserImage() { + const auto index = tree_view->currentIndex().row(); + const auto uuid = profile_manager.GetUser(index); + ASSERT(uuid); + + const auto file = QFileDialog::getOpenFileName(this, tr("Select User Image"), QString(), + tr("JPEG Images (*.jpg *.jpeg)")); + + if (file.isEmpty()) { + return; + } + + const auto image_path = GetImagePath(*uuid); + if (QFile::exists(image_path) && !QFile::remove(image_path)) { + QMessageBox::warning( + this, tr("Error deleting image"), + tr("Error occurred attempting to overwrite previous image at: %1.").arg(image_path)); + return; + } + + const auto raw_path = QString::fromStdString(Common::FS::PathToUTF8String( + Common::FS::GetSudachiPath(Common::FS::SudachiPath::NANDDir) / "system/save/8000000000000010")); + const QFileInfo raw_info{raw_path}; + if (raw_info.exists() && !raw_info.isDir() && !QFile::remove(raw_path)) { + QMessageBox::warning(this, tr("Error deleting file"), + tr("Unable to delete existing file: %1.").arg(raw_path)); + return; + } + + const QString absolute_dst_path = QFileInfo{image_path}.absolutePath(); + if (!QDir{raw_path}.mkpath(absolute_dst_path)) { + QMessageBox::warning( + this, tr("Error creating user image directory"), + tr("Unable to create directory %1 for storing user images.").arg(absolute_dst_path)); + return; + } + + if (!QFile::copy(file, image_path)) { + QMessageBox::warning(this, tr("Error copying user image"), + tr("Unable to copy image from %1 to %2").arg(file, image_path)); + return; + } + + // Profile image must be 256x256 + QImage image(image_path); + if (image.width() != 256 || image.height() != 256) { + image = image.scaled(256, 256, Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation); + if (!image.save(image_path)) { + QMessageBox::warning(this, tr("Error resizing user image"), + tr("Unable to resize image")); + return; + } + } + + const auto username = GetAccountUsername(profile_manager, *uuid); + item_model->setItem(index, 0, + new QStandardItem{GetIcon(*uuid), FormatUserEntryText(username, *uuid)}); + UpdateCurrentUser(); +} + +ConfigureProfileManagerDeleteDialog::ConfigureProfileManagerDeleteDialog(QWidget* parent) + : QDialog{parent} { + auto dialog_vbox_layout = new QVBoxLayout(this); + dialog_button_box = + new QDialogButtonBox(QDialogButtonBox::Yes | QDialogButtonBox::No, Qt::Horizontal, parent); + auto label_message = + new QLabel(tr("Delete this user? All of the user's save data will be deleted."), this); + label_info = new QLabel(this); + auto dialog_hbox_layout_widget = new QWidget(this); + auto dialog_hbox_layout = new QHBoxLayout(dialog_hbox_layout_widget); + icon_scene = new QGraphicsScene(0, 0, 64, 64, this); + auto icon_view = new QGraphicsView(icon_scene, this); + + dialog_hbox_layout_widget->setLayout(dialog_hbox_layout); + icon_view->setMaximumSize(64, 64); + icon_view->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + icon_view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + this->setLayout(dialog_vbox_layout); + this->setWindowTitle(tr("Confirm Delete")); + this->setSizeGripEnabled(false); + dialog_vbox_layout->addWidget(label_message); + dialog_vbox_layout->addWidget(dialog_hbox_layout_widget); + dialog_vbox_layout->addWidget(dialog_button_box); + dialog_hbox_layout->addWidget(icon_view); + dialog_hbox_layout->addWidget(label_info); + + connect(dialog_button_box, &QDialogButtonBox::rejected, this, [this]() { close(); }); +} + +ConfigureProfileManagerDeleteDialog::~ConfigureProfileManagerDeleteDialog() = default; + +void ConfigureProfileManagerDeleteDialog::SetInfo(const QString& username, const Common::UUID& uuid, + std::function accept_callback) { + label_info->setText( + tr("Name: %1\nUUID: %2").arg(username, QString::fromStdString(uuid.FormattedString()))); + icon_scene->clear(); + icon_scene->addPixmap(GetIcon(uuid)); + + connect(dialog_button_box, &QDialogButtonBox::accepted, this, [this, accept_callback]() { + close(); + accept_callback(); + }); +} diff --git a/src/sudachi/configuration/configure_profile_manager.h b/src/sudachi/configuration/configure_profile_manager.h new file mode 100644 index 0000000..39560fd --- /dev/null +++ b/src/sudachi/configuration/configure_profile_manager.h @@ -0,0 +1,90 @@ +// SPDX-FileCopyrightText: 2016 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include + +#include +#include +#include + +namespace Common { +struct UUID; +} + +namespace Core { +class System; +} + +class QGraphicsScene; +class QDialogButtonBox; +class QLabel; +class QStandardItem; +class QStandardItemModel; +class QTreeView; +class QVBoxLayout; + +namespace Service::Account { +class ProfileManager; +} + +namespace Ui { +class ConfigureProfileManager; +} + +class ConfigureProfileManagerDeleteDialog : public QDialog { +public: + explicit ConfigureProfileManagerDeleteDialog(QWidget* parent); + ~ConfigureProfileManagerDeleteDialog(); + + void SetInfo(const QString& username, const Common::UUID& uuid, + std::function accept_callback); + +private: + QDialogButtonBox* dialog_button_box; + QGraphicsScene* icon_scene; + QLabel* label_info; +}; + +class ConfigureProfileManager : public QWidget { + Q_OBJECT + +public: + explicit ConfigureProfileManager(Core::System& system_, QWidget* parent = nullptr); + ~ConfigureProfileManager() override; + + void ApplyConfiguration(); + +private: + void changeEvent(QEvent* event) override; + void RetranslateUI(); + + void SetConfiguration(); + + void PopulateUserList(); + void UpdateCurrentUser(); + + void SelectUser(const QModelIndex& index); + void AddUser(); + void RenameUser(); + void ConfirmDeleteUser(); + void DeleteUser(const Common::UUID& uuid); + void SetUserImage(); + + QVBoxLayout* layout; + QTreeView* tree_view; + QStandardItemModel* item_model; + QGraphicsScene* scene; + + ConfigureProfileManagerDeleteDialog* confirm_dialog; + + std::vector> list_items; + + std::unique_ptr ui; + bool enabled = false; + + Service::Account::ProfileManager& profile_manager; + const Core::System& system; +}; diff --git a/src/sudachi/configuration/configure_profile_manager.ui b/src/sudachi/configuration/configure_profile_manager.ui new file mode 100644 index 0000000..bd6dea4 --- /dev/null +++ b/src/sudachi/configuration/configure_profile_manager.ui @@ -0,0 +1,181 @@ + + + ConfigureProfileManager + + + + 0 + 0 + 390 + 483 + + + + Form + + + Profiles + + + + + + + + Profile Manager + + + + QLayout::SetNoConstraint + + + + + + + + 0 + 0 + + + + Current User + + + + + + + + 48 + 48 + + + + + 48 + 48 + + + + QFrame::NoFrame + + + QFrame::Plain + + + Qt::ScrollBarAlwaysOff + + + Qt::ScrollBarAlwaysOff + + + false + + + + + + + + 0 + 0 + + + + Username + + + + + + + + + + 0 + 0 + + + + QFrame::StyledPanel + + + false + + + + + + + + + false + + + Set Image + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Add + + + + + + + false + + + Rename + + + + + + + false + + + Remove + + + + + + + + + + + + Profile management is available only when game is not running. + + + true + + + + + + + + + + diff --git a/src/sudachi/configuration/configure_ringcon.cpp b/src/sudachi/configuration/configure_ringcon.cpp new file mode 100644 index 0000000..00a5dba --- /dev/null +++ b/src/sudachi/configuration/configure_ringcon.cpp @@ -0,0 +1,497 @@ +// SPDX-FileCopyrightText: Copyright 2022 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include +#include +#include +#include +#include + +#include "configuration/qt_config.h" +#include "hid_core/frontend/emulated_controller.h" +#include "hid_core/hid_core.h" +#include "input_common/drivers/keyboard.h" +#include "input_common/drivers/mouse.h" +#include "input_common/main.h" +#include "ui_configure_ringcon.h" +#include "sudachi/bootmanager.h" +#include "sudachi/configuration/configure_ringcon.h" + +const std::array + ConfigureRingController::analog_sub_buttons{{ + "left", + "right", + }}; + +namespace { + +QString GetKeyName(int key_code) { + switch (key_code) { + case Qt::Key_Shift: + return QObject::tr("Shift"); + case Qt::Key_Control: + return QObject::tr("Ctrl"); + case Qt::Key_Alt: + return QObject::tr("Alt"); + case Qt::Key_Meta: + return {}; + default: + return QKeySequence(key_code).toString(); + } +} + +QString GetButtonName(Common::Input::ButtonNames button_name) { + switch (button_name) { + case Common::Input::ButtonNames::ButtonLeft: + return QObject::tr("Left"); + case Common::Input::ButtonNames::ButtonRight: + return QObject::tr("Right"); + case Common::Input::ButtonNames::ButtonDown: + return QObject::tr("Down"); + case Common::Input::ButtonNames::ButtonUp: + return QObject::tr("Up"); + case Common::Input::ButtonNames::TriggerZ: + return QObject::tr("Z"); + case Common::Input::ButtonNames::TriggerR: + return QObject::tr("R"); + case Common::Input::ButtonNames::TriggerL: + return QObject::tr("L"); + case Common::Input::ButtonNames::ButtonA: + return QObject::tr("A"); + case Common::Input::ButtonNames::ButtonB: + return QObject::tr("B"); + case Common::Input::ButtonNames::ButtonX: + return QObject::tr("X"); + case Common::Input::ButtonNames::ButtonY: + return QObject::tr("Y"); + case Common::Input::ButtonNames::ButtonStart: + return QObject::tr("Start"); + case Common::Input::ButtonNames::L1: + return QObject::tr("L1"); + case Common::Input::ButtonNames::L2: + return QObject::tr("L2"); + case Common::Input::ButtonNames::L3: + return QObject::tr("L3"); + case Common::Input::ButtonNames::R1: + return QObject::tr("R1"); + case Common::Input::ButtonNames::R2: + return QObject::tr("R2"); + case Common::Input::ButtonNames::R3: + return QObject::tr("R3"); + case Common::Input::ButtonNames::Circle: + return QObject::tr("Circle"); + case Common::Input::ButtonNames::Cross: + return QObject::tr("Cross"); + case Common::Input::ButtonNames::Square: + return QObject::tr("Square"); + case Common::Input::ButtonNames::Triangle: + return QObject::tr("Triangle"); + case Common::Input::ButtonNames::Share: + return QObject::tr("Share"); + case Common::Input::ButtonNames::Options: + return QObject::tr("Options"); + default: + return QObject::tr("[undefined]"); + } +} + +void SetAnalogParam(const Common::ParamPackage& input_param, Common::ParamPackage& analog_param, + const std::string& button_name) { + // The poller returned a complete axis, so set all the buttons + if (input_param.Has("axis_x") && input_param.Has("axis_y")) { + analog_param = input_param; + return; + } + // Check if the current configuration has either no engine or an axis binding. + // Clears out the old binding and adds one with analog_from_button. + if (!analog_param.Has("engine") || analog_param.Has("axis_x") || analog_param.Has("axis_y")) { + analog_param = { + {"engine", "analog_from_button"}, + }; + } + analog_param.Set(button_name, input_param.Serialize()); +} +} // namespace + +ConfigureRingController::ConfigureRingController(QWidget* parent, + InputCommon::InputSubsystem* input_subsystem_, + Core::HID::HIDCore& hid_core_) + : QDialog(parent), timeout_timer(std::make_unique()), + poll_timer(std::make_unique()), input_subsystem{input_subsystem_}, + + ui(std::make_unique()) { + ui->setupUi(this); + + analog_map_buttons = { + ui->buttonRingAnalogPull, + ui->buttonRingAnalogPush, + }; + + emulated_controller = hid_core_.GetEmulatedController(Core::HID::NpadIdType::Player1); + emulated_controller->SaveCurrentConfig(); + emulated_controller->EnableConfiguration(); + + Core::HID::ControllerUpdateCallback engine_callback{ + .on_change = [this](Core::HID::ControllerTriggerType type) { ControllerUpdate(type); }, + .is_npad_service = false, + }; + callback_key = emulated_controller->SetCallback(engine_callback); + is_controller_set = true; + + LoadConfiguration(); + + for (int sub_button_id = 0; sub_button_id < ANALOG_SUB_BUTTONS_NUM; ++sub_button_id) { + auto* const analog_button = analog_map_buttons[sub_button_id]; + + if (analog_button == nullptr) { + continue; + } + + connect(analog_button, &QPushButton::clicked, [=, this] { + HandleClick( + analog_map_buttons[sub_button_id], + [=, this](const Common::ParamPackage& params) { + Common::ParamPackage param = emulated_controller->GetRingParam(); + SetAnalogParam(params, param, analog_sub_buttons[sub_button_id]); + emulated_controller->SetRingParam(param); + }, + InputCommon::Polling::InputType::Stick); + }); + + analog_button->setContextMenuPolicy(Qt::CustomContextMenu); + + connect(analog_button, &QPushButton::customContextMenuRequested, + [=, this](const QPoint& menu_location) { + QMenu context_menu; + Common::ParamPackage param = emulated_controller->GetRingParam(); + context_menu.addAction(tr("Clear"), [&] { + emulated_controller->SetRingParam(param); + analog_map_buttons[sub_button_id]->setText(tr("[not set]")); + }); + context_menu.addAction(tr("Invert axis"), [&] { + const bool invert_value = param.Get("invert_x", "+") == "-"; + const std::string invert_str = invert_value ? "+" : "-"; + param.Set("invert_x", invert_str); + emulated_controller->SetRingParam(param); + for (int sub_button_id2 = 0; sub_button_id2 < ANALOG_SUB_BUTTONS_NUM; + ++sub_button_id2) { + analog_map_buttons[sub_button_id2]->setText( + AnalogToText(param, analog_sub_buttons[sub_button_id2])); + } + }); + context_menu.exec( + analog_map_buttons[sub_button_id]->mapToGlobal(menu_location)); + }); + } + + connect(ui->sliderRingAnalogDeadzone, &QSlider::valueChanged, [=, this] { + Common::ParamPackage param = emulated_controller->GetRingParam(); + const auto slider_value = ui->sliderRingAnalogDeadzone->value(); + ui->labelRingAnalogDeadzone->setText(tr("Deadzone: %1%").arg(slider_value)); + param.Set("deadzone", slider_value / 100.0f); + emulated_controller->SetRingParam(param); + }); + + connect(ui->restore_defaults_button, &QPushButton::clicked, this, + &ConfigureRingController::RestoreDefaults); + + connect(ui->enable_ring_controller_button, &QPushButton::clicked, this, + &ConfigureRingController::EnableRingController); + + timeout_timer->setSingleShot(true); + connect(timeout_timer.get(), &QTimer::timeout, [this] { SetPollingResult({}, true); }); + + connect(poll_timer.get(), &QTimer::timeout, [this] { + const auto& params = input_subsystem->GetNextInput(); + if (params.Has("engine") && IsInputAcceptable(params)) { + SetPollingResult(params, false); + return; + } + }); + + resize(0, 0); +} + +ConfigureRingController::~ConfigureRingController() { + emulated_controller->SetPollingMode(Core::HID::EmulatedDeviceIndex::RightIndex, + Common::Input::PollingMode::Active); + emulated_controller->DisableConfiguration(); + + if (is_controller_set) { + emulated_controller->DeleteCallback(callback_key); + is_controller_set = false; + } +}; + +void ConfigureRingController::changeEvent(QEvent* event) { + if (event->type() == QEvent::LanguageChange) { + RetranslateUI(); + } + + QDialog::changeEvent(event); +} + +void ConfigureRingController::RetranslateUI() { + ui->retranslateUi(this); +} + +void ConfigureRingController::UpdateUI() { + RetranslateUI(); + const Common::ParamPackage param = emulated_controller->GetRingParam(); + + for (int sub_button_id = 0; sub_button_id < ANALOG_SUB_BUTTONS_NUM; ++sub_button_id) { + auto* const analog_button = analog_map_buttons[sub_button_id]; + + if (analog_button == nullptr) { + continue; + } + + analog_button->setText(AnalogToText(param, analog_sub_buttons[sub_button_id])); + } + + const auto deadzone_label = ui->labelRingAnalogDeadzone; + const auto deadzone_slider = ui->sliderRingAnalogDeadzone; + + int slider_value = static_cast(param.Get("deadzone", 0.15f) * 100); + deadzone_label->setText(tr("Deadzone: %1%").arg(slider_value)); + deadzone_slider->setValue(slider_value); +} + +void ConfigureRingController::ApplyConfiguration() { + emulated_controller->DisableConfiguration(); + emulated_controller->SaveCurrentConfig(); + emulated_controller->EnableConfiguration(); +} + +void ConfigureRingController::LoadConfiguration() { + UpdateUI(); +} + +void ConfigureRingController::RestoreDefaults() { + const std::string default_ring_string = InputCommon::GenerateAnalogParamFromKeys( + 0, 0, QtConfig::default_ringcon_analogs[0], QtConfig::default_ringcon_analogs[1], 0, 0.05f); + emulated_controller->SetRingParam(Common::ParamPackage(default_ring_string)); + UpdateUI(); +} + +void ConfigureRingController::EnableRingController() { + const auto dialog_title = tr("Error enabling ring input"); + + is_ring_enabled = false; + ui->ring_controller_sensor_value->setText(tr("Not connected")); + + if (!Settings::values.enable_joycon_driver) { + QMessageBox::warning(this, dialog_title, tr("Direct Joycon driver is not enabled")); + return; + } + + ui->enable_ring_controller_button->setEnabled(false); + ui->enable_ring_controller_button->setText(tr("Configuring")); + // SetPollingMode is blocking. Allow to update the button status before calling the command + repaint(); + + const auto result = emulated_controller->SetPollingMode( + Core::HID::EmulatedDeviceIndex::RightIndex, Common::Input::PollingMode::Ring); + switch (result) { + case Common::Input::DriverResult::Success: + is_ring_enabled = true; + break; + case Common::Input::DriverResult::NotSupported: + QMessageBox::warning(this, dialog_title, + tr("The current mapped device doesn't support the ring controller")); + break; + case Common::Input::DriverResult::NoDeviceDetected: + QMessageBox::warning(this, dialog_title, + tr("The current mapped device doesn't have a ring attached")); + break; + case Common::Input::DriverResult::InvalidHandle: + QMessageBox::warning(this, dialog_title, tr("The current mapped device is not connected")); + break; + default: + QMessageBox::warning(this, dialog_title, + tr("Unexpected driver result %1").arg(static_cast(result))); + break; + } + ui->enable_ring_controller_button->setEnabled(true); + ui->enable_ring_controller_button->setText(tr("Enable")); +} + +void ConfigureRingController::ControllerUpdate(Core::HID::ControllerTriggerType type) { + if (!is_ring_enabled) { + return; + } + if (type != Core::HID::ControllerTriggerType::RingController) { + return; + } + + const auto value = emulated_controller->GetRingSensorValues(); + const auto tex_value = QString::fromStdString(fmt::format("{:.3f}", value.raw_value)); + ui->ring_controller_sensor_value->setText(tex_value); +} + +void ConfigureRingController::HandleClick( + QPushButton* button, std::function new_input_setter, + InputCommon::Polling::InputType type) { + button->setText(tr("[waiting]")); + button->setFocus(); + + input_setter = new_input_setter; + + input_subsystem->BeginMapping(type); + + QWidget::grabMouse(); + QWidget::grabKeyboard(); + + timeout_timer->start(2500); // Cancel after 2.5 seconds + poll_timer->start(25); // Check for new inputs every 25ms +} + +void ConfigureRingController::SetPollingResult(const Common::ParamPackage& params, bool abort) { + timeout_timer->stop(); + poll_timer->stop(); + input_subsystem->StopMapping(); + + QWidget::releaseMouse(); + QWidget::releaseKeyboard(); + + if (!abort) { + (*input_setter)(params); + } + + UpdateUI(); + + input_setter = std::nullopt; +} + +bool ConfigureRingController::IsInputAcceptable(const Common::ParamPackage& params) const { + return true; +} + +void ConfigureRingController::mousePressEvent(QMouseEvent* event) { + if (!input_setter || !event) { + return; + } + + const auto button = GRenderWindow::QtButtonToMouseButton(event->button()); + input_subsystem->GetMouse()->PressButton(0, 0, button); +} + +void ConfigureRingController::keyPressEvent(QKeyEvent* event) { + if (!input_setter || !event) { + return; + } + event->ignore(); + if (event->key() != Qt::Key_Escape) { + input_subsystem->GetKeyboard()->PressKey(event->key()); + } +} + +QString ConfigureRingController::ButtonToText(const Common::ParamPackage& param) { + if (!param.Has("engine")) { + return QObject::tr("[not set]"); + } + + const QString toggle = QString::fromStdString(param.Get("toggle", false) ? "~" : ""); + const QString inverted = QString::fromStdString(param.Get("inverted", false) ? "!" : ""); + const auto common_button_name = input_subsystem->GetButtonName(param); + + // Retrieve the names from Qt + if (param.Get("engine", "") == "keyboard") { + const QString button_str = GetKeyName(param.Get("code", 0)); + return QObject::tr("%1%2").arg(toggle, button_str); + } + + if (common_button_name == Common::Input::ButtonNames::Invalid) { + return QObject::tr("[invalid]"); + } + + if (common_button_name == Common::Input::ButtonNames::Engine) { + return QString::fromStdString(param.Get("engine", "")); + } + + if (common_button_name == Common::Input::ButtonNames::Value) { + if (param.Has("hat")) { + const QString hat = QString::fromStdString(param.Get("direction", "")); + return QObject::tr("%1%2Hat %3").arg(toggle, inverted, hat); + } + if (param.Has("axis")) { + const QString axis = QString::fromStdString(param.Get("axis", "")); + return QObject::tr("%1%2Axis %3").arg(toggle, inverted, axis); + } + if (param.Has("axis_x") && param.Has("axis_y") && param.Has("axis_z")) { + const QString axis_x = QString::fromStdString(param.Get("axis_x", "")); + const QString axis_y = QString::fromStdString(param.Get("axis_y", "")); + const QString axis_z = QString::fromStdString(param.Get("axis_z", "")); + return QObject::tr("%1%2Axis %3,%4,%5").arg(toggle, inverted, axis_x, axis_y, axis_z); + } + if (param.Has("motion")) { + const QString motion = QString::fromStdString(param.Get("motion", "")); + return QObject::tr("%1%2Motion %3").arg(toggle, inverted, motion); + } + if (param.Has("button")) { + const QString button = QString::fromStdString(param.Get("button", "")); + return QObject::tr("%1%2Button %3").arg(toggle, inverted, button); + } + } + + QString button_name = GetButtonName(common_button_name); + if (param.Has("hat")) { + return QObject::tr("%1%2Hat %3").arg(toggle, inverted, button_name); + } + if (param.Has("axis")) { + return QObject::tr("%1%2Axis %3").arg(toggle, inverted, button_name); + } + if (param.Has("motion")) { + return QObject::tr("%1%2Axis %3").arg(toggle, inverted, button_name); + } + if (param.Has("button")) { + return QObject::tr("%1%2Button %3").arg(toggle, inverted, button_name); + } + + return QObject::tr("[unknown]"); +} + +QString ConfigureRingController::AnalogToText(const Common::ParamPackage& param, + const std::string& dir) { + if (!param.Has("engine")) { + return QObject::tr("[not set]"); + } + + if (param.Get("engine", "") == "analog_from_button") { + return ButtonToText(Common::ParamPackage{param.Get(dir, "")}); + } + + if (!param.Has("axis_x") || !param.Has("axis_y")) { + return QObject::tr("[unknown]"); + } + + const auto engine_str = param.Get("engine", ""); + const QString axis_x_str = QString::fromStdString(param.Get("axis_x", "")); + const QString axis_y_str = QString::fromStdString(param.Get("axis_y", "")); + const bool invert_x = param.Get("invert_x", "+") == "-"; + const bool invert_y = param.Get("invert_y", "+") == "-"; + + if (dir == "modifier") { + return QObject::tr("[unused]"); + } + + if (dir == "left") { + const QString invert_x_str = QString::fromStdString(invert_x ? "+" : "-"); + return QObject::tr("Axis %1%2").arg(axis_x_str, invert_x_str); + } + if (dir == "right") { + const QString invert_x_str = QString::fromStdString(invert_x ? "-" : "+"); + return QObject::tr("Axis %1%2").arg(axis_x_str, invert_x_str); + } + if (dir == "up") { + const QString invert_y_str = QString::fromStdString(invert_y ? "-" : "+"); + return QObject::tr("Axis %1%2").arg(axis_y_str, invert_y_str); + } + if (dir == "down") { + const QString invert_y_str = QString::fromStdString(invert_y ? "+" : "-"); + return QObject::tr("Axis %1%2").arg(axis_y_str, invert_y_str); + } + + return QObject::tr("[unknown]"); +} diff --git a/src/sudachi/configuration/configure_ringcon.h b/src/sudachi/configuration/configure_ringcon.h new file mode 100644 index 0000000..c419430 --- /dev/null +++ b/src/sudachi/configuration/configure_ringcon.h @@ -0,0 +1,94 @@ +// SPDX-FileCopyrightText: Copyright 2022 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include +#include + +namespace InputCommon { +class InputSubsystem; +} // namespace InputCommon + +namespace Core::HID { +class HIDCore; +class EmulatedController; +} // namespace Core::HID + +namespace Ui { +class ConfigureRingController; +} // namespace Ui + +class ConfigureRingController : public QDialog { + Q_OBJECT + +public: + explicit ConfigureRingController(QWidget* parent, InputCommon::InputSubsystem* input_subsystem_, + Core::HID::HIDCore& hid_core_); + ~ConfigureRingController() override; + + void ApplyConfiguration(); + +private: + void changeEvent(QEvent* event) override; + void RetranslateUI(); + + void UpdateUI(); + + /// Load configuration settings. + void LoadConfiguration(); + + /// Restore all buttons to their default values. + void RestoreDefaults(); + + /// Sets current polling mode to ring input + void EnableRingController(); + + // Handles emulated controller events + void ControllerUpdate(Core::HID::ControllerTriggerType type); + + /// Called when the button was pressed. + void HandleClick(QPushButton* button, + std::function new_input_setter, + InputCommon::Polling::InputType type); + + /// Finish polling and configure input using the input_setter. + void SetPollingResult(const Common::ParamPackage& params, bool abort); + + /// Checks whether a given input can be accepted. + bool IsInputAcceptable(const Common::ParamPackage& params) const; + + /// Handle mouse button press events. + void mousePressEvent(QMouseEvent* event) override; + + /// Handle key press events. + void keyPressEvent(QKeyEvent* event) override; + + QString ButtonToText(const Common::ParamPackage& param); + + QString AnalogToText(const Common::ParamPackage& param, const std::string& dir); + + static constexpr int ANALOG_SUB_BUTTONS_NUM = 2; + + // A group of four QPushButtons represent one analog input. The buttons each represent left, + // right, respectively. + std::array analog_map_buttons; + + static const std::array analog_sub_buttons; + + std::unique_ptr timeout_timer; + std::unique_ptr poll_timer; + + /// This will be the the setting function when an input is awaiting configuration. + std::optional> input_setter; + + InputCommon::InputSubsystem* input_subsystem; + Core::HID::EmulatedController* emulated_controller; + + bool is_ring_enabled{}; + bool is_controller_set{}; + int callback_key; + + std::unique_ptr ui; +}; diff --git a/src/sudachi/configuration/configure_ringcon.ui b/src/sudachi/configuration/configure_ringcon.ui new file mode 100644 index 0000000..38ecccc --- /dev/null +++ b/src/sudachi/configuration/configure_ringcon.ui @@ -0,0 +1,374 @@ + + + ConfigureRingController + + + + 0 + 0 + 315 + 400 + + + + Configure Ring Controller + + + + + + + 280 + 0 + + + + To use Ring-Con, configure player 1 as right Joy-Con (both physical and emulated), and player 2 as left Joy-Con (left physical and dual emulated) before starting the game. + + + true + + + + + + + Qt::Vertical + + + QSizePolicy::Fixed + + + + 20 + 10 + + + + + + + + Virtual Ring Sensor Parameters + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop + + + + 0 + + + QLayout::SetDefaultConstraint + + + 3 + + + 6 + + + 3 + + + 0 + + + + + 3 + + + + + Pull + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 70 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + Pull + + + + + + + + + + Push + + + Qt::AlignCenter + + + + 3 + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 70 + 0 + + + + + 68 + 16777215 + + + + min-width: 68px; + + + Push + + + + + + + + + + + + 3 + + + QLayout::SetDefaultConstraint + + + 0 + + + 10 + + + 0 + + + 3 + + + + + + + Deadzone: 0% + + + Qt::AlignHCenter + + + + + + + + + 100 + + + Qt::Horizontal + + + + + + + + + + + + Direct Joycon Driver + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop + + + + 0 + + + QLayout::SetDefaultConstraint + + + 3 + + + 6 + + + 3 + + + 10 + + + + + 10 + + + 6 + + + 10 + + + 10 + + + 10 + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 76 + 20 + + + + + + + + Enable Ring Input + + + + + + + Enable + + + + + + + Ring Sensor Value + + + + + + + Not connected + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + + + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + + Restore Defaults + + + + + + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + + + + + + + + + + buttonBox + accepted() + ConfigureRingController + accept() + + + buttonBox + rejected() + ConfigureRingController + reject() + + + diff --git a/src/sudachi/configuration/configure_system.cpp b/src/sudachi/configuration/configure_system.cpp new file mode 100644 index 0000000..6de4460 --- /dev/null +++ b/src/sudachi/configuration/configure_system.cpp @@ -0,0 +1,206 @@ +// SPDX-FileCopyrightText: 2016 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "common/settings.h" +#include "core/core.h" +#include "ui_configure_system.h" +#include "sudachi/configuration/configuration_shared.h" +#include "sudachi/configuration/configure_system.h" +#include "sudachi/configuration/shared_widget.h" + +constexpr std::array LOCALE_BLOCKLIST{ + // pzzefezrpnkzeidfej + // thhsrnhutlohsternp + // BHH4CG U + // Raa1AB S + // nn9 + // ts + 0b0100011100001100000, // Japan + 0b0000001101001100100, // Americas + 0b0100110100001000010, // Europe + 0b0100110100001000010, // Australia + 0b0000000000000000000, // China + 0b0100111100001000000, // Korea + 0b0100111100001000000, // Taiwan +}; + +static bool IsValidLocale(u32 region_index, u32 language_index) { + if (region_index >= LOCALE_BLOCKLIST.size()) { + return false; + } + return ((LOCALE_BLOCKLIST.at(region_index) >> language_index) & 1) == 0; +} + +ConfigureSystem::ConfigureSystem(Core::System& system_, + std::shared_ptr> group_, + const ConfigurationShared::Builder& builder, QWidget* parent) + : Tab(group_, parent), ui{std::make_unique()}, system{system_} { + ui->setupUi(this); + + const auto posix_time = std::chrono::system_clock::now().time_since_epoch(); + const auto current_time_s = + std::chrono::duration_cast(posix_time).count(); + previous_time = current_time_s + Settings::values.custom_rtc_offset.GetValue(); + + Setup(builder); + + const auto locale_check = [this]() { + const auto region_index = combo_region->currentIndex(); + const auto language_index = combo_language->currentIndex(); + const bool valid_locale = IsValidLocale(region_index, language_index); + ui->label_warn_invalid_locale->setVisible(!valid_locale); + if (!valid_locale) { + ui->label_warn_invalid_locale->setText( + tr("Warning: \"%1\" is not a valid language for region \"%2\"") + .arg(combo_language->currentText()) + .arg(combo_region->currentText())); + } + }; + + const auto update_date_offset = [this]() { + if (!checkbox_rtc->isChecked()) { + return; + } + auto offset = date_rtc_offset->value(); + offset += date_rtc->dateTime().toSecsSinceEpoch() - previous_time; + previous_time = date_rtc->dateTime().toSecsSinceEpoch(); + date_rtc_offset->setValue(offset); + }; + const auto update_rtc_date = [this]() { UpdateRtcTime(); }; + + connect(combo_language, qOverload(&QComboBox::currentIndexChanged), this, locale_check); + connect(combo_region, qOverload(&QComboBox::currentIndexChanged), this, locale_check); + connect(checkbox_rtc, qOverload(&QCheckBox::stateChanged), this, update_rtc_date); + connect(date_rtc_offset, qOverload(&QSpinBox::valueChanged), this, update_rtc_date); + connect(date_rtc, &QDateTimeEdit::dateTimeChanged, this, update_date_offset); + + ui->label_warn_invalid_locale->setVisible(false); + locale_check(); + + SetConfiguration(); + UpdateRtcTime(); +} + +ConfigureSystem::~ConfigureSystem() = default; + +void ConfigureSystem::changeEvent(QEvent* event) { + if (event->type() == QEvent::LanguageChange) { + RetranslateUI(); + } + + QWidget::changeEvent(event); +} + +void ConfigureSystem::RetranslateUI() { + ui->retranslateUi(this); +} + +void ConfigureSystem::Setup(const ConfigurationShared::Builder& builder) { + auto& core_layout = *ui->core_widget->layout(); + auto& system_layout = *ui->system_widget->layout(); + + std::map core_hold{}; + std::map system_hold{}; + + std::vector settings; + auto push = [&settings](auto& list) { + for (auto setting : list) { + settings.push_back(setting); + } + }; + + push(Settings::values.linkage.by_category[Settings::Category::Core]); + push(Settings::values.linkage.by_category[Settings::Category::System]); + + for (auto setting : settings) { + if (setting->Id() == Settings::values.use_docked_mode.Id() && + Settings::IsConfiguringGlobal()) { + continue; + } + + ConfigurationShared::Widget* widget = builder.BuildWidget(setting, apply_funcs); + + if (widget == nullptr) { + continue; + } + if (!widget->Valid()) { + widget->deleteLater(); + continue; + } + + // Keep track of the region_index (and language_index) combobox to validate the selected + // settings + if (setting->Id() == Settings::values.region_index.Id()) { + combo_region = widget->combobox; + } + + if (setting->Id() == Settings::values.language_index.Id()) { + combo_language = widget->combobox; + } + + if (setting->Id() == Settings::values.custom_rtc.Id()) { + checkbox_rtc = widget->checkbox; + } + + if (setting->Id() == Settings::values.custom_rtc.Id()) { + date_rtc = widget->date_time_edit; + } + + if (setting->Id() == Settings::values.custom_rtc_offset.Id()) { + date_rtc_offset = widget->spinbox; + } + + switch (setting->GetCategory()) { + case Settings::Category::Core: + core_hold.emplace(setting->Id(), widget); + break; + case Settings::Category::System: + system_hold.emplace(setting->Id(), widget); + break; + default: + widget->deleteLater(); + } + } + for (const auto& [label, widget] : core_hold) { + core_layout.addWidget(widget); + } + for (const auto& [id, widget] : system_hold) { + system_layout.addWidget(widget); + } +} + +void ConfigureSystem::UpdateRtcTime() { + const auto posix_time = std::chrono::system_clock::now().time_since_epoch(); + previous_time = std::chrono::duration_cast(posix_time).count(); + date_rtc_offset->setEnabled(checkbox_rtc->isChecked()); + + if (checkbox_rtc->isChecked()) { + previous_time += date_rtc_offset->value(); + } + + const auto date = QDateTime::fromSecsSinceEpoch(previous_time); + date_rtc->setDateTime(date); +} + +void ConfigureSystem::SetConfiguration() {} + +void ConfigureSystem::ApplyConfiguration() { + const bool powered_on = system.IsPoweredOn(); + for (const auto& func : apply_funcs) { + func(powered_on); + } + UpdateRtcTime(); +} diff --git a/src/sudachi/configuration/configure_system.h b/src/sudachi/configuration/configure_system.h new file mode 100644 index 0000000..8d69ad2 --- /dev/null +++ b/src/sudachi/configuration/configure_system.h @@ -0,0 +1,63 @@ +// SPDX-FileCopyrightText: 2016 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include +#include + +#include +#include "sudachi/configuration/configuration_shared.h" + +class QCheckBox; +class QLineEdit; +class QComboBox; +class QDateTimeEdit; +namespace Core { +class System; +} + +namespace Ui { +class ConfigureSystem; +} + +namespace ConfigurationShared { +class Builder; +} + +class ConfigureSystem : public ConfigurationShared::Tab { + Q_OBJECT + +public: + explicit ConfigureSystem(Core::System& system_, + std::shared_ptr> group, + const ConfigurationShared::Builder& builder, + QWidget* parent = nullptr); + ~ConfigureSystem() override; + + void ApplyConfiguration() override; + void SetConfiguration() override; + +private: + void changeEvent(QEvent* event) override; + void RetranslateUI(); + + void Setup(const ConfigurationShared::Builder& builder); + + void UpdateRtcTime(); + + std::vector> apply_funcs{}; + + std::unique_ptr ui; + bool enabled = false; + + Core::System& system; + + QComboBox* combo_region; + QComboBox* combo_language; + QCheckBox* checkbox_rtc; + QDateTimeEdit* date_rtc; + QSpinBox* date_rtc_offset; + u64 previous_time; +}; diff --git a/src/sudachi/configuration/configure_system.ui b/src/sudachi/configuration/configure_system.ui new file mode 100644 index 0000000..04b7711 --- /dev/null +++ b/src/sudachi/configuration/configure_system.ui @@ -0,0 +1,105 @@ + + + ConfigureSystem + + + + 0 + 0 + 605 + 483 + + + + Form + + + System + + + + + + + + System + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + + + + + + true + + + + + + + + + + Core + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + + + diff --git a/src/sudachi/configuration/configure_tas.cpp b/src/sudachi/configuration/configure_tas.cpp new file mode 100644 index 0000000..36aec75 --- /dev/null +++ b/src/sudachi/configuration/configure_tas.cpp @@ -0,0 +1,81 @@ +// SPDX-FileCopyrightText: Copyright 2021 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include +#include "common/fs/fs.h" +#include "common/fs/path_util.h" +#include "common/settings.h" +#include "ui_configure_tas.h" +#include "sudachi/configuration/configure_tas.h" +#include "sudachi/uisettings.h" + +ConfigureTasDialog::ConfigureTasDialog(QWidget* parent) + : QDialog(parent), ui(std::make_unique()) { + + ui->setupUi(this); + + setFocusPolicy(Qt::ClickFocus); + setWindowTitle(tr("TAS Configuration")); + + connect(ui->tas_path_button, &QToolButton::pressed, this, + [this] { SetDirectory(DirectoryTarget::TAS, ui->tas_path_edit); }); + + LoadConfiguration(); +} + +ConfigureTasDialog::~ConfigureTasDialog() = default; + +void ConfigureTasDialog::LoadConfiguration() { + ui->tas_path_edit->setText( + QString::fromStdString(Common::FS::GetSudachiPathString(Common::FS::SudachiPath::TASDir))); + ui->tas_enable->setChecked(Settings::values.tas_enable.GetValue()); + ui->tas_loop_script->setChecked(Settings::values.tas_loop.GetValue()); + ui->tas_pause_on_load->setChecked(Settings::values.pause_tas_on_load.GetValue()); +} + +void ConfigureTasDialog::ApplyConfiguration() { + Common::FS::SetSudachiPath(Common::FS::SudachiPath::TASDir, ui->tas_path_edit->text().toStdString()); + Settings::values.tas_enable.SetValue(ui->tas_enable->isChecked()); + Settings::values.tas_loop.SetValue(ui->tas_loop_script->isChecked()); + Settings::values.pause_tas_on_load.SetValue(ui->tas_pause_on_load->isChecked()); +} + +void ConfigureTasDialog::SetDirectory(DirectoryTarget target, QLineEdit* edit) { + QString caption; + + switch (target) { + case DirectoryTarget::TAS: + caption = tr("Select TAS Load Directory..."); + break; + } + + QString str = QFileDialog::getExistingDirectory(this, caption, edit->text()); + + if (str.isEmpty()) { + return; + } + + if (str.back() != QChar::fromLatin1('/')) { + str.append(QChar::fromLatin1('/')); + } + + edit->setText(str); +} + +void ConfigureTasDialog::changeEvent(QEvent* event) { + if (event->type() == QEvent::LanguageChange) { + RetranslateUI(); + } + + QDialog::changeEvent(event); +} + +void ConfigureTasDialog::RetranslateUI() { + ui->retranslateUi(this); +} + +void ConfigureTasDialog::HandleApplyButtonClicked() { + UISettings::values.configuration_applied = true; + ApplyConfiguration(); +} diff --git a/src/sudachi/configuration/configure_tas.h b/src/sudachi/configuration/configure_tas.h new file mode 100644 index 0000000..eb3d36d --- /dev/null +++ b/src/sudachi/configuration/configure_tas.h @@ -0,0 +1,39 @@ +// SPDX-FileCopyrightText: Copyright 2021 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include + +class QLineEdit; + +namespace Ui { +class ConfigureTas; +} + +class ConfigureTasDialog : public QDialog { + Q_OBJECT + +public: + explicit ConfigureTasDialog(QWidget* parent); + ~ConfigureTasDialog() override; + + /// Save all button configurations to settings file + void ApplyConfiguration(); + +private: + enum class DirectoryTarget { + TAS, + }; + + void LoadConfiguration(); + + void SetDirectory(DirectoryTarget target, QLineEdit* edit); + + void changeEvent(QEvent* event) override; + void RetranslateUI(); + + void HandleApplyButtonClicked(); + + std::unique_ptr ui; +}; diff --git a/src/sudachi/configuration/configure_tas.ui b/src/sudachi/configuration/configure_tas.ui new file mode 100644 index 0000000..b045078 --- /dev/null +++ b/src/sudachi/configuration/configure_tas.ui @@ -0,0 +1,182 @@ + + + ConfigureTas + + + + + + + + TAS + + + + + + <html><head/><body><p>Reads controller input from scripts in the same format as TAS-nx scripts.<br/>For a more detailed explanation, please consult the <a href="https://sudachi-emu.org/help/feature/tas/"><span style=" text-decoration: underline; color:#039be5;">help page</span></a> on the sudachi website.</p></body></html> + + + true + + + + + + + To check which hotkeys control the playback/recording, please refer to the Hotkey settings (Configure -> General -> Hotkeys). + + + true + + + + + + + WARNING: This is an experimental feature.<br/>It will not play back scripts frame perfectly with the current, imperfect syncing method. + + + true + + + + + + + + + + + + + + Settings + + + + + + Enable TAS features + + + + + + + Loop script + + + + + + + false + + + Pause execution during loads + + + + + + + + + + + + + + Script Directory + + + + + + Path + + + + + + + ... + + + + + + + + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + 0 + 0 + + + + Qt::Horizontal + + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + + + + + + + + buttonBox + accepted() + ConfigureTas + accept() + + + 20 + 20 + + + 20 + 20 + + + + + buttonBox + rejected() + ConfigureTas + reject() + + + 20 + 20 + + + 20 + 20 + + + + + diff --git a/src/sudachi/configuration/configure_touch_from_button.cpp b/src/sudachi/configuration/configure_touch_from_button.cpp new file mode 100644 index 0000000..db3fa83 --- /dev/null +++ b/src/sudachi/configuration/configure_touch_from_button.cpp @@ -0,0 +1,617 @@ +// SPDX-FileCopyrightText: 2020 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include +#include +#include +#include +#include +#include "common/param_package.h" +#include "common/settings.h" +#include "core/frontend/framebuffer_layout.h" +#include "input_common/main.h" +#include "ui_configure_touch_from_button.h" +#include "sudachi/configuration/configure_touch_from_button.h" +#include "sudachi/configuration/configure_touch_widget.h" + +static QString GetKeyName(int key_code) { + switch (key_code) { + case Qt::Key_Shift: + return QObject::tr("Shift"); + case Qt::Key_Control: + return QObject::tr("Ctrl"); + case Qt::Key_Alt: + return QObject::tr("Alt"); + case Qt::Key_Meta: + return QString{}; + default: + return QKeySequence(key_code).toString(); + } +} + +static QString ButtonToText(const Common::ParamPackage& param) { + if (!param.Has("engine")) { + return QObject::tr("[not set]"); + } + + if (param.Get("engine", "") == "keyboard") { + return GetKeyName(param.Get("code", 0)); + } + + if (param.Get("engine", "") == "sdl") { + if (param.Has("hat")) { + const QString hat_str = QString::fromStdString(param.Get("hat", "")); + const QString direction_str = QString::fromStdString(param.Get("direction", "")); + + return QObject::tr("Hat %1 %2").arg(hat_str, direction_str); + } + + if (param.Has("axis")) { + const QString axis_str = QString::fromStdString(param.Get("axis", "")); + const QString direction_str = QString::fromStdString(param.Get("direction", "")); + + return QObject::tr("Axis %1%2").arg(axis_str, direction_str); + } + + if (param.Has("button")) { + const QString button_str = QString::fromStdString(param.Get("button", "")); + + return QObject::tr("Button %1").arg(button_str); + } + + return {}; + } + + return QObject::tr("[unknown]"); +} + +ConfigureTouchFromButton::ConfigureTouchFromButton( + QWidget* parent, const std::vector& touch_maps_, + InputCommon::InputSubsystem* input_subsystem_, const int default_index) + : QDialog(parent), ui(std::make_unique()), + touch_maps{touch_maps_}, input_subsystem{input_subsystem_}, selected_index{default_index}, + timeout_timer(std::make_unique()), poll_timer(std::make_unique()) { + ui->setupUi(this); + binding_list_model = new QStandardItemModel(0, 3, this); + binding_list_model->setHorizontalHeaderLabels( + {tr("Button"), tr("X", "X axis"), tr("Y", "Y axis")}); + ui->binding_list->setModel(binding_list_model); + ui->bottom_screen->SetCoordLabel(ui->coord_label); + + SetConfiguration(); + UpdateUiDisplay(); + ConnectEvents(); +} + +ConfigureTouchFromButton::~ConfigureTouchFromButton() = default; + +void ConfigureTouchFromButton::showEvent(QShowEvent* ev) { + QWidget::showEvent(ev); + + // width values are not valid in the constructor + const int w = + ui->binding_list->viewport()->contentsRect().width() / binding_list_model->columnCount(); + if (w <= 0) { + return; + } + ui->binding_list->setColumnWidth(0, w); + ui->binding_list->setColumnWidth(1, w); + ui->binding_list->setColumnWidth(2, w); +} + +void ConfigureTouchFromButton::SetConfiguration() { + for (const auto& touch_map : touch_maps) { + ui->mapping->addItem(QString::fromStdString(touch_map.name)); + } + + ui->mapping->setCurrentIndex(selected_index); +} + +void ConfigureTouchFromButton::UpdateUiDisplay() { + ui->button_delete->setEnabled(touch_maps.size() > 1); + ui->button_delete_bind->setEnabled(false); + + binding_list_model->removeRows(0, binding_list_model->rowCount()); + + for (const auto& button_str : touch_maps[selected_index].buttons) { + Common::ParamPackage package{button_str}; + QStandardItem* button = new QStandardItem(ButtonToText(package)); + button->setData(QString::fromStdString(button_str)); + button->setEditable(false); + QStandardItem* xcoord = new QStandardItem(QString::number(package.Get("x", 0))); + QStandardItem* ycoord = new QStandardItem(QString::number(package.Get("y", 0))); + binding_list_model->appendRow({button, xcoord, ycoord}); + + const int dot = ui->bottom_screen->AddDot(package.Get("x", 0), package.Get("y", 0)); + button->setData(dot, DataRoleDot); + } +} + +void ConfigureTouchFromButton::ConnectEvents() { + connect(ui->mapping, qOverload(&QComboBox::currentIndexChanged), this, [this](int index) { + SaveCurrentMapping(); + selected_index = index; + UpdateUiDisplay(); + }); + connect(ui->button_new, &QPushButton::clicked, this, &ConfigureTouchFromButton::NewMapping); + connect(ui->button_delete, &QPushButton::clicked, this, + &ConfigureTouchFromButton::DeleteMapping); + connect(ui->button_rename, &QPushButton::clicked, this, + &ConfigureTouchFromButton::RenameMapping); + connect(ui->button_delete_bind, &QPushButton::clicked, this, + &ConfigureTouchFromButton::DeleteBinding); + connect(ui->binding_list, &QTreeView::doubleClicked, this, + &ConfigureTouchFromButton::EditBinding); + connect(ui->binding_list->selectionModel(), &QItemSelectionModel::selectionChanged, this, + &ConfigureTouchFromButton::OnBindingSelection); + connect(binding_list_model, &QStandardItemModel::itemChanged, this, + &ConfigureTouchFromButton::OnBindingChanged); + connect(ui->binding_list->model(), &QStandardItemModel::rowsAboutToBeRemoved, this, + &ConfigureTouchFromButton::OnBindingDeleted); + connect(ui->bottom_screen, &TouchScreenPreview::DotAdded, this, + &ConfigureTouchFromButton::NewBinding); + connect(ui->bottom_screen, &TouchScreenPreview::DotSelected, this, + &ConfigureTouchFromButton::SetActiveBinding); + connect(ui->bottom_screen, &TouchScreenPreview::DotMoved, this, + &ConfigureTouchFromButton::SetCoordinates); + connect(ui->buttonBox, &QDialogButtonBox::accepted, this, + &ConfigureTouchFromButton::ApplyConfiguration); + + connect(timeout_timer.get(), &QTimer::timeout, [this]() { SetPollingResult({}, true); }); + + connect(poll_timer.get(), &QTimer::timeout, [this]() { + const auto& params = input_subsystem->GetNextInput(); + if (params.Has("engine")) { + SetPollingResult(params, false); + return; + } + }); +} + +void ConfigureTouchFromButton::SaveCurrentMapping() { + auto& map = touch_maps[selected_index]; + map.buttons.clear(); + for (int i = 0, rc = binding_list_model->rowCount(); i < rc; ++i) { + const auto bind_str = binding_list_model->index(i, 0) + .data(Qt::ItemDataRole::UserRole + 1) + .toString() + .toStdString(); + if (bind_str.empty()) { + continue; + } + Common::ParamPackage params{bind_str}; + if (!params.Has("engine")) { + continue; + } + params.Set("x", binding_list_model->index(i, 1).data().toInt()); + params.Set("y", binding_list_model->index(i, 2).data().toInt()); + map.buttons.emplace_back(params.Serialize()); + } +} + +void ConfigureTouchFromButton::NewMapping() { + const QString name = + QInputDialog::getText(this, tr("New Profile"), tr("Enter the name for the new profile.")); + if (name.isEmpty()) { + return; + } + touch_maps.emplace_back(Settings::TouchFromButtonMap{name.toStdString(), {}}); + ui->mapping->addItem(name); + ui->mapping->setCurrentIndex(ui->mapping->count() - 1); +} + +void ConfigureTouchFromButton::DeleteMapping() { + const auto answer = QMessageBox::question( + this, tr("Delete Profile"), tr("Delete profile %1?").arg(ui->mapping->currentText())); + if (answer != QMessageBox::Yes) { + return; + } + const bool blocked = ui->mapping->blockSignals(true); + ui->mapping->removeItem(selected_index); + ui->mapping->blockSignals(blocked); + touch_maps.erase(touch_maps.begin() + selected_index); + selected_index = ui->mapping->currentIndex(); + UpdateUiDisplay(); +} + +void ConfigureTouchFromButton::RenameMapping() { + const QString new_name = QInputDialog::getText(this, tr("Rename Profile"), tr("New name:")); + if (new_name.isEmpty()) { + return; + } + ui->mapping->setItemText(selected_index, new_name); + touch_maps[selected_index].name = new_name.toStdString(); +} + +void ConfigureTouchFromButton::GetButtonInput(const int row_index, const bool is_new) { + if (timeout_timer->isActive()) { + return; + } + binding_list_model->item(row_index, 0)->setText(tr("[press key]")); + + input_setter = [this, row_index, is_new](const Common::ParamPackage& params, + const bool cancel) { + auto* cell = binding_list_model->item(row_index, 0); + if (cancel) { + if (is_new) { + binding_list_model->removeRow(row_index); + } else { + cell->setText( + ButtonToText(Common::ParamPackage{cell->data().toString().toStdString()})); + } + } else { + cell->setText(ButtonToText(params)); + cell->setData(QString::fromStdString(params.Serialize())); + } + }; + + input_subsystem->BeginMapping(InputCommon::Polling::InputType::Button); + + grabKeyboard(); + grabMouse(); + qApp->setOverrideCursor(QCursor(Qt::CursorShape::ArrowCursor)); + timeout_timer->start(5000); // Cancel after 5 seconds + poll_timer->start(200); // Check for new inputs every 200ms +} + +void ConfigureTouchFromButton::NewBinding(const QPoint& pos) { + auto* button = new QStandardItem(); + button->setEditable(false); + auto* x_coord = new QStandardItem(QString::number(pos.x())); + auto* y_coord = new QStandardItem(QString::number(pos.y())); + + const int dot_id = ui->bottom_screen->AddDot(pos.x(), pos.y()); + button->setData(dot_id, DataRoleDot); + + binding_list_model->appendRow({button, x_coord, y_coord}); + ui->binding_list->setFocus(); + ui->binding_list->setCurrentIndex(button->index()); + + GetButtonInput(binding_list_model->rowCount() - 1, true); +} + +void ConfigureTouchFromButton::EditBinding(const QModelIndex& qi) { + if (qi.row() >= 0 && qi.column() == 0) { + GetButtonInput(qi.row(), false); + } +} + +void ConfigureTouchFromButton::DeleteBinding() { + const int row_index = ui->binding_list->currentIndex().row(); + if (row_index < 0) { + return; + } + ui->bottom_screen->RemoveDot(binding_list_model->index(row_index, 0).data(DataRoleDot).toInt()); + binding_list_model->removeRow(row_index); +} + +void ConfigureTouchFromButton::OnBindingSelection(const QItemSelection& selected, + const QItemSelection& deselected) { + ui->button_delete_bind->setEnabled(!selected.isEmpty()); + if (!selected.isEmpty()) { + const auto dot_data = selected.indexes().first().data(DataRoleDot); + if (dot_data.isValid()) { + ui->bottom_screen->HighlightDot(dot_data.toInt()); + } + } + if (!deselected.isEmpty()) { + const auto dot_data = deselected.indexes().first().data(DataRoleDot); + if (dot_data.isValid()) { + ui->bottom_screen->HighlightDot(dot_data.toInt(), false); + } + } +} + +void ConfigureTouchFromButton::OnBindingChanged(QStandardItem* item) { + if (item->column() == 0) { + return; + } + + const bool blocked = binding_list_model->blockSignals(true); + item->setText(QString::number( + std::clamp(item->text().toInt(), 0, + static_cast((item->column() == 1 ? Layout::ScreenUndocked::Width + : Layout::ScreenUndocked::Height) - + 1)))); + binding_list_model->blockSignals(blocked); + + const auto dot_data = binding_list_model->index(item->row(), 0).data(DataRoleDot); + if (dot_data.isValid()) { + ui->bottom_screen->MoveDot(dot_data.toInt(), + binding_list_model->item(item->row(), 1)->text().toInt(), + binding_list_model->item(item->row(), 2)->text().toInt()); + } +} + +void ConfigureTouchFromButton::OnBindingDeleted(const QModelIndex& parent, int first, int last) { + for (int i = first; i <= last; ++i) { + const auto ix = binding_list_model->index(i, 0); + if (!ix.isValid()) { + return; + } + const auto dot_data = ix.data(DataRoleDot); + if (dot_data.isValid()) { + ui->bottom_screen->RemoveDot(dot_data.toInt()); + } + } +} + +void ConfigureTouchFromButton::SetActiveBinding(const int dot_id) { + for (int i = 0; i < binding_list_model->rowCount(); ++i) { + if (binding_list_model->index(i, 0).data(DataRoleDot) == dot_id) { + ui->binding_list->setCurrentIndex(binding_list_model->index(i, 0)); + ui->binding_list->setFocus(); + return; + } + } +} + +void ConfigureTouchFromButton::SetCoordinates(const int dot_id, const QPoint& pos) { + for (int i = 0; i < binding_list_model->rowCount(); ++i) { + if (binding_list_model->item(i, 0)->data(DataRoleDot) == dot_id) { + binding_list_model->item(i, 1)->setText(QString::number(pos.x())); + binding_list_model->item(i, 2)->setText(QString::number(pos.y())); + return; + } + } +} + +void ConfigureTouchFromButton::SetPollingResult(const Common::ParamPackage& params, + const bool cancel) { + timeout_timer->stop(); + poll_timer->stop(); + input_subsystem->StopMapping(); + + releaseKeyboard(); + releaseMouse(); + qApp->restoreOverrideCursor(); + + if (input_setter) { + (*input_setter)(params, cancel); + input_setter.reset(); + } +} + +void ConfigureTouchFromButton::keyPressEvent(QKeyEvent* event) { + if (!input_setter && event->key() == Qt::Key_Delete) { + DeleteBinding(); + return; + } + + if (!input_setter) { + return QDialog::keyPressEvent(event); + } + + if (event->key() != Qt::Key_Escape) { + SetPollingResult(Common::ParamPackage{InputCommon::GenerateKeyboardParam(event->key())}, + false); + } else { + SetPollingResult({}, true); + } +} + +void ConfigureTouchFromButton::ApplyConfiguration() { + SaveCurrentMapping(); + accept(); +} + +int ConfigureTouchFromButton::GetSelectedIndex() const { + return selected_index; +} + +std::vector ConfigureTouchFromButton::GetMaps() const { + return touch_maps; +} + +TouchScreenPreview::TouchScreenPreview(QWidget* parent) : QFrame(parent) { + setBackgroundRole(QPalette::ColorRole::Base); +} + +TouchScreenPreview::~TouchScreenPreview() = default; + +void TouchScreenPreview::SetCoordLabel(QLabel* const label) { + coord_label = label; +} + +int TouchScreenPreview::AddDot(const int device_x, const int device_y) { + QFont dot_font{QStringLiteral("monospace")}; + dot_font.setStyleHint(QFont::Monospace); + dot_font.setPointSize(20); + + auto* dot = new QLabel(this); + dot->setAttribute(Qt::WA_TranslucentBackground); + dot->setFont(dot_font); + dot->setText(QChar(0xD7)); // U+00D7 Multiplication Sign + dot->setAlignment(Qt::AlignmentFlag::AlignCenter); + dot->setProperty(PropId, ++max_dot_id); + dot->setProperty(PropX, device_x); + dot->setProperty(PropY, device_y); + dot->setCursor(Qt::CursorShape::PointingHandCursor); + dot->setMouseTracking(true); + dot->installEventFilter(this); + dot->show(); + PositionDot(dot, device_x, device_y); + dots.emplace_back(max_dot_id, dot); + return max_dot_id; +} + +void TouchScreenPreview::RemoveDot(const int id) { + const auto iter = std::find_if(dots.begin(), dots.end(), + [id](const auto& entry) { return entry.first == id; }); + if (iter == dots.cend()) { + return; + } + + iter->second->deleteLater(); + dots.erase(iter); +} + +void TouchScreenPreview::HighlightDot(const int id, const bool active) const { + for (const auto& dot : dots) { + if (dot.first == id) { + // use color property from the stylesheet, or fall back to the default palette + if (dot_highlight_color.isValid()) { + dot.second->setStyleSheet( + active ? QStringLiteral("color: %1").arg(dot_highlight_color.name()) + : QString{}); + } else { + dot.second->setForegroundRole(active ? QPalette::ColorRole::LinkVisited + : QPalette::ColorRole::NoRole); + } + if (active) { + dot.second->raise(); + } + return; + } + } +} + +void TouchScreenPreview::MoveDot(const int id, const int device_x, const int device_y) const { + const auto iter = std::find_if(dots.begin(), dots.end(), + [id](const auto& entry) { return entry.first == id; }); + if (iter == dots.cend()) { + return; + } + + iter->second->setProperty(PropX, device_x); + iter->second->setProperty(PropY, device_y); + PositionDot(iter->second, device_x, device_y); +} + +void TouchScreenPreview::resizeEvent(QResizeEvent* event) { + if (ignore_resize) { + return; + } + + const int target_width = std::min(width(), height() * 4 / 3); + const int target_height = std::min(height(), width() * 3 / 4); + if (target_width == width() && target_height == height()) { + return; + } + ignore_resize = true; + setGeometry((parentWidget()->contentsRect().width() - target_width) / 2, y(), target_width, + target_height); + ignore_resize = false; + + if (event->oldSize().width() != target_width || event->oldSize().height() != target_height) { + for (const auto& dot : dots) { + PositionDot(dot.second); + } + } +} + +void TouchScreenPreview::mouseMoveEvent(QMouseEvent* event) { + if (!coord_label) { + return; + } + const auto pos = MapToDeviceCoords(event->x(), event->y()); + if (pos) { + coord_label->setText(QStringLiteral("X: %1, Y: %2").arg(pos->x()).arg(pos->y())); + } else { + coord_label->clear(); + } +} + +void TouchScreenPreview::leaveEvent(QEvent* event) { + if (coord_label) { + coord_label->clear(); + } +} + +void TouchScreenPreview::mousePressEvent(QMouseEvent* event) { + if (event->button() != Qt::MouseButton::LeftButton) { + return; + } + const auto pos = MapToDeviceCoords(event->x(), event->y()); + if (pos) { + emit DotAdded(*pos); + } +} + +bool TouchScreenPreview::eventFilter(QObject* obj, QEvent* event) { + switch (event->type()) { + case QEvent::Type::MouseButtonPress: { + const auto mouse_event = static_cast(event); + if (mouse_event->button() != Qt::MouseButton::LeftButton) { + break; + } + emit DotSelected(obj->property(PropId).toInt()); + + drag_state.dot = qobject_cast(obj); + drag_state.start_pos = mouse_event->globalPos(); + return true; + } + case QEvent::Type::MouseMove: { + if (!drag_state.dot) { + break; + } + const auto mouse_event = static_cast(event); + if (!drag_state.active) { + drag_state.active = + (mouse_event->globalPos() - drag_state.start_pos).manhattanLength() >= + QApplication::startDragDistance(); + if (!drag_state.active) { + break; + } + } + auto current_pos = mapFromGlobal(mouse_event->globalPos()); + current_pos.setX(std::clamp(current_pos.x(), contentsMargins().left(), + contentsMargins().left() + contentsRect().width() - 1)); + current_pos.setY(std::clamp(current_pos.y(), contentsMargins().top(), + contentsMargins().top() + contentsRect().height() - 1)); + const auto device_coord = MapToDeviceCoords(current_pos.x(), current_pos.y()); + if (device_coord) { + drag_state.dot->setProperty(PropX, device_coord->x()); + drag_state.dot->setProperty(PropY, device_coord->y()); + PositionDot(drag_state.dot, device_coord->x(), device_coord->y()); + emit DotMoved(drag_state.dot->property(PropId).toInt(), *device_coord); + if (coord_label) { + coord_label->setText( + QStringLiteral("X: %1, Y: %2").arg(device_coord->x()).arg(device_coord->y())); + } + } + return true; + } + case QEvent::Type::MouseButtonRelease: { + drag_state.dot.clear(); + drag_state.active = false; + return true; + } + default: + break; + } + return obj->eventFilter(obj, event); +} + +std::optional TouchScreenPreview::MapToDeviceCoords(const int screen_x, + const int screen_y) const { + const float t_x = 0.5f + static_cast(screen_x - contentsMargins().left()) * + (Layout::ScreenUndocked::Width - 1) / (contentsRect().width() - 1); + const float t_y = 0.5f + static_cast(screen_y - contentsMargins().top()) * + (Layout::ScreenUndocked::Height - 1) / + (contentsRect().height() - 1); + if (t_x >= 0.5f && t_x < Layout::ScreenUndocked::Width && t_y >= 0.5f && + t_y < Layout::ScreenUndocked::Height) { + + return QPoint{static_cast(t_x), static_cast(t_y)}; + } + return std::nullopt; +} + +void TouchScreenPreview::PositionDot(QLabel* const dot, const int device_x, + const int device_y) const { + const float device_coord_x = + static_cast(device_x >= 0 ? device_x : dot->property(PropX).toInt()); + int x_coord = static_cast( + device_coord_x * (contentsRect().width() - 1) / (Layout::ScreenUndocked::Width - 1) + + contentsMargins().left() - static_cast(dot->width()) / 2 + 0.5f); + + const float device_coord_y = + static_cast(device_y >= 0 ? device_y : dot->property(PropY).toInt()); + const int y_coord = static_cast( + device_coord_y * (contentsRect().height() - 1) / (Layout::ScreenUndocked::Height - 1) + + contentsMargins().top() - static_cast(dot->height()) / 2 + 0.5f); + + dot->move(x_coord, y_coord); +} diff --git a/src/sudachi/configuration/configure_touch_from_button.h b/src/sudachi/configuration/configure_touch_from_button.h new file mode 100644 index 0000000..5a1416d --- /dev/null +++ b/src/sudachi/configuration/configure_touch_from_button.h @@ -0,0 +1,86 @@ +// SPDX-FileCopyrightText: 2020 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include +#include +#include +#include + +class QItemSelection; +class QModelIndex; +class QStandardItemModel; +class QStandardItem; +class QTimer; + +namespace Common { +class ParamPackage; +} + +namespace InputCommon { +class InputSubsystem; +} + +namespace Settings { +struct TouchFromButtonMap; +} + +namespace Ui { +class ConfigureTouchFromButton; +} + +class ConfigureTouchFromButton : public QDialog { + Q_OBJECT + +public: + explicit ConfigureTouchFromButton(QWidget* parent, + const std::vector& touch_maps_, + InputCommon::InputSubsystem* input_subsystem_, + int default_index = 0); + ~ConfigureTouchFromButton() override; + + int GetSelectedIndex() const; + std::vector GetMaps() const; + +public slots: + void ApplyConfiguration(); + void NewBinding(const QPoint& pos); + void SetActiveBinding(int dot_id); + void SetCoordinates(int dot_id, const QPoint& pos); + +protected: + void showEvent(QShowEvent* ev) override; + void keyPressEvent(QKeyEvent* event) override; + +private slots: + void NewMapping(); + void DeleteMapping(); + void RenameMapping(); + void EditBinding(const QModelIndex& qi); + void DeleteBinding(); + void OnBindingSelection(const QItemSelection& selected, const QItemSelection& deselected); + void OnBindingChanged(QStandardItem* item); + void OnBindingDeleted(const QModelIndex& parent, int first, int last); + +private: + void SetConfiguration(); + void UpdateUiDisplay(); + void ConnectEvents(); + void GetButtonInput(int row_index, bool is_new); + void SetPollingResult(const Common::ParamPackage& params, bool cancel); + void SaveCurrentMapping(); + + std::unique_ptr ui; + std::vector touch_maps; + QStandardItemModel* binding_list_model; + InputCommon::InputSubsystem* input_subsystem; + int selected_index; + + std::unique_ptr timeout_timer; + std::unique_ptr poll_timer; + std::optional> input_setter; + + static constexpr int DataRoleDot = Qt::ItemDataRole::UserRole + 2; +}; diff --git a/src/sudachi/configuration/configure_touch_from_button.ui b/src/sudachi/configuration/configure_touch_from_button.ui new file mode 100644 index 0000000..2b2cdf4 --- /dev/null +++ b/src/sudachi/configuration/configure_touch_from_button.ui @@ -0,0 +1,221 @@ + + + ConfigureTouchFromButton + + + + 0 + 0 + 500 + 500 + + + + Configure Touchscreen Mappings + + + + + + + + Mapping: + + + Qt::PlainText + + + + + + + + 0 + 0 + + + + + + + + + 0 + 0 + + + + New + + + + + + + + 0 + 0 + + + + Delete + + + + + + + + 0 + 0 + + + + Rename + + + + + + + + + Qt::Horizontal + + + + + + + + + Click the bottom area to add a point, then press a button to bind. +Drag points to change position, or double-click table cells to edit values. + + + Qt::PlainText + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Delete Point + + + + + + + + + + 0 + 0 + + + + false + + + true + + + false + + + + + + + + 0 + 0 + + + + + 160 + 120 + + + + + 320 + 240 + + + + CrossCursor + + + true + + + true + + + QFrame::StyledPanel + + + QFrame::Sunken + + + + + + + + + + 0 + 0 + + + + Qt::PlainText + + + + + + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + + + + + + + + + TouchScreenPreview + QFrame +
sudachi/configuration/configure_touch_widget.h
+ 1 +
+
+ + + + buttonBox + rejected() + ConfigureTouchFromButton + reject() + + +
diff --git a/src/sudachi/configuration/configure_touch_widget.h b/src/sudachi/configuration/configure_touch_widget.h new file mode 100644 index 0000000..49f533a --- /dev/null +++ b/src/sudachi/configuration/configure_touch_widget.h @@ -0,0 +1,61 @@ +// SPDX-FileCopyrightText: 2020 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include +#include +#include +#include + +class QLabel; + +// Widget for representing touchscreen coordinates +class TouchScreenPreview : public QFrame { + Q_OBJECT + Q_PROPERTY(QColor dotHighlightColor MEMBER dot_highlight_color) + +public: + explicit TouchScreenPreview(QWidget* parent); + ~TouchScreenPreview() override; + + void SetCoordLabel(QLabel*); + int AddDot(int device_x, int device_y); + void RemoveDot(int id); + void HighlightDot(int id, bool active = true) const; + void MoveDot(int id, int device_x, int device_y) const; + +signals: + void DotAdded(const QPoint& pos); + void DotSelected(int dot_id); + void DotMoved(int dot_id, const QPoint& pos); + +protected: + void resizeEvent(QResizeEvent*) override; + void mouseMoveEvent(QMouseEvent*) override; + void leaveEvent(QEvent*) override; + void mousePressEvent(QMouseEvent*) override; + bool eventFilter(QObject*, QEvent*) override; + +private: + std::optional MapToDeviceCoords(int screen_x, int screen_y) const; + void PositionDot(QLabel* dot, int device_x = -1, int device_y = -1) const; + + bool ignore_resize = false; + QPointer coord_label; + + std::vector> dots; + int max_dot_id = 0; + QColor dot_highlight_color; + static constexpr char PropId[] = "dot_id"; + static constexpr char PropX[] = "device_x"; + static constexpr char PropY[] = "device_y"; + + struct DragState { + bool active = false; + QPointer dot; + QPoint start_pos; + }; + DragState drag_state; +}; diff --git a/src/sudachi/configuration/configure_touchscreen_advanced.cpp b/src/sudachi/configuration/configure_touchscreen_advanced.cpp new file mode 100644 index 0000000..12bfcac --- /dev/null +++ b/src/sudachi/configuration/configure_touchscreen_advanced.cpp @@ -0,0 +1,50 @@ +// SPDX-FileCopyrightText: 2016 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include "common/settings.h" +#include "ui_configure_touchscreen_advanced.h" +#include "sudachi/configuration/configure_touchscreen_advanced.h" + +ConfigureTouchscreenAdvanced::ConfigureTouchscreenAdvanced(QWidget* parent) + : QDialog(parent), ui(std::make_unique()) { + ui->setupUi(this); + + connect(ui->restore_defaults_button, &QPushButton::clicked, this, + &ConfigureTouchscreenAdvanced::RestoreDefaults); + + LoadConfiguration(); + resize(0, 0); +} + +ConfigureTouchscreenAdvanced::~ConfigureTouchscreenAdvanced() = default; + +void ConfigureTouchscreenAdvanced::changeEvent(QEvent* event) { + if (event->type() == QEvent::LanguageChange) { + RetranslateUI(); + } + + QDialog::changeEvent(event); +} + +void ConfigureTouchscreenAdvanced::RetranslateUI() { + ui->retranslateUi(this); +} + +void ConfigureTouchscreenAdvanced::ApplyConfiguration() { + Settings::values.touchscreen.diameter_x = ui->diameter_x_box->value(); + Settings::values.touchscreen.diameter_y = ui->diameter_y_box->value(); + Settings::values.touchscreen.rotation_angle = ui->angle_box->value(); +} + +void ConfigureTouchscreenAdvanced::LoadConfiguration() { + ui->diameter_x_box->setValue(Settings::values.touchscreen.diameter_x); + ui->diameter_y_box->setValue(Settings::values.touchscreen.diameter_y); + ui->angle_box->setValue(Settings::values.touchscreen.rotation_angle); +} + +void ConfigureTouchscreenAdvanced::RestoreDefaults() { + ui->diameter_x_box->setValue(15); + ui->diameter_y_box->setValue(15); + ui->angle_box->setValue(0); +} diff --git a/src/sudachi/configuration/configure_touchscreen_advanced.h b/src/sudachi/configuration/configure_touchscreen_advanced.h new file mode 100644 index 0000000..b6fdffd --- /dev/null +++ b/src/sudachi/configuration/configure_touchscreen_advanced.h @@ -0,0 +1,32 @@ +// SPDX-FileCopyrightText: 2016 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include + +namespace Ui { +class ConfigureTouchscreenAdvanced; +} + +class ConfigureTouchscreenAdvanced : public QDialog { + Q_OBJECT + +public: + explicit ConfigureTouchscreenAdvanced(QWidget* parent); + ~ConfigureTouchscreenAdvanced() override; + + void ApplyConfiguration(); + +private: + void changeEvent(QEvent* event) override; + void RetranslateUI(); + + /// Load configuration settings. + void LoadConfiguration(); + /// Restore all buttons to their default values. + void RestoreDefaults(); + + std::unique_ptr ui; +}; diff --git a/src/sudachi/configuration/configure_touchscreen_advanced.ui b/src/sudachi/configuration/configure_touchscreen_advanced.ui new file mode 100644 index 0000000..e1a8033 --- /dev/null +++ b/src/sudachi/configuration/configure_touchscreen_advanced.ui @@ -0,0 +1,162 @@ + + + ConfigureTouchscreenAdvanced + + + + 0 + 0 + 298 + 339 + + + + Configure Touchscreen + + + + + + + 280 + 0 + + + + Warning: The settings in this page affect the inner workings of sudachi's emulated touchscreen. Changing them may result in undesirable behavior, such as the touchscreen partially or not working. You should only use this page if you know what you are doing. + + + true + + + + + + + Qt::Vertical + + + QSizePolicy::Fixed + + + + 20 + 20 + + + + + + + + Touch Parameters + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Touch Diameter Y + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Touch Diameter X + + + + + + + Rotational Angle + + + + + + + + + + + + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + + Restore Defaults + + + + + + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + + + + + + + + + + buttonBox + accepted() + ConfigureTouchscreenAdvanced + accept() + + + buttonBox + rejected() + ConfigureTouchscreenAdvanced + reject() + + + diff --git a/src/sudachi/configuration/configure_ui.cpp b/src/sudachi/configuration/configure_ui.cpp new file mode 100644 index 0000000..f5beda5 --- /dev/null +++ b/src/sudachi/configuration/configure_ui.cpp @@ -0,0 +1,354 @@ +// SPDX-FileCopyrightText: 2016 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include "sudachi/configuration/configure_ui.h" + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "common/common_types.h" +#include "common/fs/path_util.h" +#include "common/logging/log.h" +#include "common/settings.h" +#include "common/settings_enums.h" +#include "core/core.h" +#include "core/frontend/framebuffer_layout.h" +#include "ui_configure_ui.h" +#include "sudachi/uisettings.h" + +namespace { +constexpr std::array default_game_icon_sizes{ + std::make_pair(0, QT_TRANSLATE_NOOP("ConfigureUI", "None")), + std::make_pair(32, QT_TRANSLATE_NOOP("ConfigureUI", "Small (32x32)")), + std::make_pair(64, QT_TRANSLATE_NOOP("ConfigureUI", "Standard (64x64)")), + std::make_pair(128, QT_TRANSLATE_NOOP("ConfigureUI", "Large (128x128)")), + std::make_pair(256, QT_TRANSLATE_NOOP("ConfigureUI", "Full Size (256x256)")), +}; + +constexpr std::array default_folder_icon_sizes{ + std::make_pair(0, QT_TRANSLATE_NOOP("ConfigureUI", "None")), + std::make_pair(24, QT_TRANSLATE_NOOP("ConfigureUI", "Small (24x24)")), + std::make_pair(48, QT_TRANSLATE_NOOP("ConfigureUI", "Standard (48x48)")), + std::make_pair(72, QT_TRANSLATE_NOOP("ConfigureUI", "Large (72x72)")), +}; + +// clang-format off +constexpr std::array row_text_names{ + QT_TRANSLATE_NOOP("ConfigureUI", "Filename"), + QT_TRANSLATE_NOOP("ConfigureUI", "Filetype"), + QT_TRANSLATE_NOOP("ConfigureUI", "Title ID"), + QT_TRANSLATE_NOOP("ConfigureUI", "Title Name"), + QT_TRANSLATE_NOOP("ConfigureUI", "None"), +}; +// clang-format on + +QString GetTranslatedGameIconSize(size_t index) { + return QCoreApplication::translate("ConfigureUI", default_game_icon_sizes[index].second); +} + +QString GetTranslatedFolderIconSize(size_t index) { + return QCoreApplication::translate("ConfigureUI", default_folder_icon_sizes[index].second); +} + +QString GetTranslatedRowTextName(size_t index) { + return QCoreApplication::translate("ConfigureUI", row_text_names[index]); +} +} // Anonymous namespace + +static float GetUpFactor(Settings::ResolutionSetup res_setup) { + Settings::ResolutionScalingInfo info{}; + Settings::TranslateResolutionInfo(res_setup, info); + return info.up_factor; +} + +static void PopulateResolutionComboBox(QComboBox* screenshot_height, QWidget* parent) { + screenshot_height->clear(); + + const auto& enumeration = + Settings::EnumMetadata::Canonicalizations(); + std::set resolutions{}; + for (const auto& [name, value] : enumeration) { + const float up_factor = GetUpFactor(value); + u32 height_undocked = Layout::ScreenUndocked::Height * up_factor; + u32 height_docked = Layout::ScreenDocked::Height * up_factor; + resolutions.emplace(height_undocked); + resolutions.emplace(height_docked); + } + + screenshot_height->addItem(parent->tr("Auto", "Screenshot height option")); + for (const auto res : resolutions) { + screenshot_height->addItem(QString::fromStdString(std::to_string(res))); + } +} + +static u32 ScreenshotDimensionToInt(const QString& height) { + return std::strtoul(height.toUtf8(), nullptr, 0); +} + +ConfigureUi::ConfigureUi(Core::System& system_, QWidget* parent) + : QWidget(parent), ui{std::make_unique()}, + ratio{Settings::values.aspect_ratio.GetValue()}, + resolution_setting{Settings::values.resolution_setup.GetValue()}, system{system_} { + ui->setupUi(this); + + InitializeLanguageComboBox(); + + for (const auto& theme : UISettings::themes) { + ui->theme_combobox->addItem(QString::fromUtf8(theme.first), + QString::fromUtf8(theme.second)); + } + + InitializeIconSizeComboBox(); + InitializeRowComboBoxes(); + + PopulateResolutionComboBox(ui->screenshot_height, this); + + SetConfiguration(); + + // Force game list reload if any of the relevant settings are changed. + connect(ui->show_add_ons, &QCheckBox::stateChanged, this, &ConfigureUi::RequestGameListUpdate); + connect(ui->show_compat, &QCheckBox::stateChanged, this, &ConfigureUi::RequestGameListUpdate); + connect(ui->show_size, &QCheckBox::stateChanged, this, &ConfigureUi::RequestGameListUpdate); + connect(ui->show_types, &QCheckBox::stateChanged, this, &ConfigureUi::RequestGameListUpdate); + connect(ui->show_play_time, &QCheckBox::stateChanged, this, + &ConfigureUi::RequestGameListUpdate); + connect(ui->game_icon_size_combobox, QOverload::of(&QComboBox::currentIndexChanged), this, + &ConfigureUi::RequestGameListUpdate); + connect(ui->folder_icon_size_combobox, QOverload::of(&QComboBox::currentIndexChanged), + this, &ConfigureUi::RequestGameListUpdate); + connect(ui->row_1_text_combobox, QOverload::of(&QComboBox::currentIndexChanged), this, + &ConfigureUi::RequestGameListUpdate); + connect(ui->row_2_text_combobox, QOverload::of(&QComboBox::currentIndexChanged), this, + &ConfigureUi::RequestGameListUpdate); + + // Update text ComboBoxes after user interaction. + connect(ui->row_1_text_combobox, QOverload::of(&QComboBox::activated), + [this] { ConfigureUi::UpdateSecondRowComboBox(); }); + connect(ui->row_2_text_combobox, QOverload::of(&QComboBox::activated), + [this] { ConfigureUi::UpdateFirstRowComboBox(); }); + + // Set screenshot path to user specification. + connect(ui->screenshot_path_button, &QToolButton::pressed, this, [this] { + auto dir = + QFileDialog::getExistingDirectory(this, tr("Select Screenshots Path..."), + QString::fromStdString(Common::FS::GetSudachiPathString( + Common::FS::SudachiPath::ScreenshotsDir))); + if (!dir.isEmpty()) { + if (dir.back() != QChar::fromLatin1('/')) { + dir.append(QChar::fromLatin1('/')); + } + + ui->screenshot_path_edit->setText(dir); + } + }); + + connect(ui->screenshot_height, &QComboBox::currentTextChanged, [this]() { UpdateWidthText(); }); + + UpdateWidthText(); +} + +ConfigureUi::~ConfigureUi() = default; + +void ConfigureUi::ApplyConfiguration() { + UISettings::values.theme = + ui->theme_combobox->itemData(ui->theme_combobox->currentIndex()).toString().toStdString(); + UISettings::values.show_add_ons = ui->show_add_ons->isChecked(); + UISettings::values.show_compat = ui->show_compat->isChecked(); + UISettings::values.show_size = ui->show_size->isChecked(); + UISettings::values.show_types = ui->show_types->isChecked(); + UISettings::values.show_play_time = ui->show_play_time->isChecked(); + UISettings::values.game_icon_size = ui->game_icon_size_combobox->currentData().toUInt(); + UISettings::values.folder_icon_size = ui->folder_icon_size_combobox->currentData().toUInt(); + UISettings::values.row_1_text_id = ui->row_1_text_combobox->currentData().toUInt(); + UISettings::values.row_2_text_id = ui->row_2_text_combobox->currentData().toUInt(); + + UISettings::values.enable_screenshot_save_as = ui->enable_screenshot_save_as->isChecked(); + Common::FS::SetSudachiPath(Common::FS::SudachiPath::ScreenshotsDir, + ui->screenshot_path_edit->text().toStdString()); + + const u32 height = ScreenshotDimensionToInt(ui->screenshot_height->currentText()); + UISettings::values.screenshot_height.SetValue(height); + + RequestGameListUpdate(); + system.ApplySettings(); +} + +void ConfigureUi::RequestGameListUpdate() { + UISettings::values.is_game_list_reload_pending.exchange(true); +} + +void ConfigureUi::SetConfiguration() { + ui->theme_combobox->setCurrentIndex( + ui->theme_combobox->findData(QString::fromStdString(UISettings::values.theme))); + ui->language_combobox->setCurrentIndex(ui->language_combobox->findData( + QString::fromStdString(UISettings::values.language.GetValue()))); + ui->show_add_ons->setChecked(UISettings::values.show_add_ons.GetValue()); + ui->show_compat->setChecked(UISettings::values.show_compat.GetValue()); + ui->show_size->setChecked(UISettings::values.show_size.GetValue()); + ui->show_types->setChecked(UISettings::values.show_types.GetValue()); + ui->show_play_time->setChecked(UISettings::values.show_play_time.GetValue()); + ui->game_icon_size_combobox->setCurrentIndex( + ui->game_icon_size_combobox->findData(UISettings::values.game_icon_size.GetValue())); + ui->folder_icon_size_combobox->setCurrentIndex( + ui->folder_icon_size_combobox->findData(UISettings::values.folder_icon_size.GetValue())); + + ui->enable_screenshot_save_as->setChecked( + UISettings::values.enable_screenshot_save_as.GetValue()); + ui->screenshot_path_edit->setText(QString::fromStdString( + Common::FS::GetSudachiPathString(Common::FS::SudachiPath::ScreenshotsDir))); + + const auto height = UISettings::values.screenshot_height.GetValue(); + if (height == 0) { + ui->screenshot_height->setCurrentIndex(0); + } else { + ui->screenshot_height->setCurrentText(QStringLiteral("%1").arg(height)); + } +} + +void ConfigureUi::changeEvent(QEvent* event) { + if (event->type() == QEvent::LanguageChange) { + RetranslateUI(); + } + + QWidget::changeEvent(event); +} + +void ConfigureUi::RetranslateUI() { + ui->retranslateUi(this); + + for (int i = 0; i < ui->game_icon_size_combobox->count(); i++) { + ui->game_icon_size_combobox->setItemText(i, + GetTranslatedGameIconSize(static_cast(i))); + } + + for (int i = 0; i < ui->folder_icon_size_combobox->count(); i++) { + ui->folder_icon_size_combobox->setItemText( + i, GetTranslatedFolderIconSize(static_cast(i))); + } + + for (int i = 0; i < ui->row_1_text_combobox->count(); i++) { + const QString name = GetTranslatedRowTextName(static_cast(i)); + + ui->row_1_text_combobox->setItemText(i, name); + ui->row_2_text_combobox->setItemText(i, name); + } +} + +void ConfigureUi::InitializeLanguageComboBox() { + ui->language_combobox->addItem(tr(""), QString{}); + ui->language_combobox->addItem(tr("English"), QStringLiteral("en")); + QDirIterator it(QStringLiteral(":/languages"), QDirIterator::NoIteratorFlags); + while (it.hasNext()) { + QString locale = it.next(); + locale.truncate(locale.lastIndexOf(QLatin1Char{'.'})); + locale.remove(0, locale.lastIndexOf(QLatin1Char{'/'}) + 1); + const QString lang = QLocale::languageToString(QLocale(locale).language()); + const QString country = QLocale::countryToString(QLocale(locale).country()); + ui->language_combobox->addItem(QStringLiteral("%1 (%2)").arg(lang, country), locale); + } + + // Unlike other configuration changes, interface language changes need to be reflected on the + // interface immediately. This is done by passing a signal to the main window, and then + // retranslating when passing back. + connect(ui->language_combobox, qOverload(&QComboBox::currentIndexChanged), this, + &ConfigureUi::OnLanguageChanged); +} + +void ConfigureUi::InitializeIconSizeComboBox() { + for (size_t i = 0; i < default_game_icon_sizes.size(); i++) { + const auto size = default_game_icon_sizes[i].first; + ui->game_icon_size_combobox->addItem(GetTranslatedGameIconSize(i), size); + } + for (size_t i = 0; i < default_folder_icon_sizes.size(); i++) { + const auto size = default_folder_icon_sizes[i].first; + ui->folder_icon_size_combobox->addItem(GetTranslatedFolderIconSize(i), size); + } +} + +void ConfigureUi::InitializeRowComboBoxes() { + UpdateFirstRowComboBox(true); + UpdateSecondRowComboBox(true); +} + +void ConfigureUi::UpdateFirstRowComboBox(bool init) { + const int currentIndex = + init ? UISettings::values.row_1_text_id.GetValue() + : ui->row_1_text_combobox->findData(ui->row_1_text_combobox->currentData()); + + ui->row_1_text_combobox->clear(); + + for (std::size_t i = 0; i < row_text_names.size(); i++) { + const QString row_text_name = GetTranslatedRowTextName(i); + ui->row_1_text_combobox->addItem(row_text_name, QVariant::fromValue(i)); + } + + ui->row_1_text_combobox->setCurrentIndex(ui->row_1_text_combobox->findData(currentIndex)); + + ui->row_1_text_combobox->removeItem(4); // None + ui->row_1_text_combobox->removeItem( + ui->row_1_text_combobox->findData(ui->row_2_text_combobox->currentData())); +} + +void ConfigureUi::UpdateSecondRowComboBox(bool init) { + const int currentIndex = + init ? UISettings::values.row_2_text_id.GetValue() + : ui->row_2_text_combobox->findData(ui->row_2_text_combobox->currentData()); + + ui->row_2_text_combobox->clear(); + + for (std::size_t i = 0; i < row_text_names.size(); ++i) { + const QString row_text_name = GetTranslatedRowTextName(i); + ui->row_2_text_combobox->addItem(row_text_name, QVariant::fromValue(i)); + } + + ui->row_2_text_combobox->setCurrentIndex(ui->row_2_text_combobox->findData(currentIndex)); + + ui->row_2_text_combobox->removeItem( + ui->row_2_text_combobox->findData(ui->row_1_text_combobox->currentData())); +} + +void ConfigureUi::OnLanguageChanged(int index) { + if (index == -1) + return; + + emit LanguageChanged(ui->language_combobox->itemData(index).toString()); +} + +void ConfigureUi::UpdateWidthText() { + const u32 height = ScreenshotDimensionToInt(ui->screenshot_height->currentText()); + const u32 width = UISettings::CalculateWidth(height, ratio); + if (height == 0) { + const auto up_factor = GetUpFactor(resolution_setting); + const u32 height_docked = Layout::ScreenDocked::Height * up_factor; + const u32 width_docked = UISettings::CalculateWidth(height_docked, ratio); + const u32 height_undocked = Layout::ScreenUndocked::Height * up_factor; + const u32 width_undocked = UISettings::CalculateWidth(height_undocked, ratio); + ui->screenshot_width->setText(tr("Auto (%1 x %2, %3 x %4)", "Screenshot width value") + .arg(width_undocked) + .arg(height_undocked) + .arg(width_docked) + .arg(height_docked)); + } else { + ui->screenshot_width->setText(QStringLiteral("%1 x").arg(width)); + } +} + +void ConfigureUi::UpdateScreenshotInfo(Settings::AspectRatio ratio_, + Settings::ResolutionSetup resolution_setting_) { + ratio = ratio_; + resolution_setting = resolution_setting_; + UpdateWidthText(); +} diff --git a/src/sudachi/configuration/configure_ui.h b/src/sudachi/configuration/configure_ui.h new file mode 100644 index 0000000..2a2563a --- /dev/null +++ b/src/sudachi/configuration/configure_ui.h @@ -0,0 +1,58 @@ +// SPDX-FileCopyrightText: 2016 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include +#include "common/settings_enums.h" + +namespace Core { +class System; +} + +namespace Ui { +class ConfigureUi; +} + +class ConfigureUi : public QWidget { + Q_OBJECT + +public: + explicit ConfigureUi(Core::System& system_, QWidget* parent = nullptr); + ~ConfigureUi() override; + + void ApplyConfiguration(); + + void UpdateScreenshotInfo(Settings::AspectRatio ratio, + Settings::ResolutionSetup resolution_info); + +private slots: + void OnLanguageChanged(int index); + +signals: + void LanguageChanged(const QString& locale); + +private: + void RequestGameListUpdate(); + + void SetConfiguration(); + + void changeEvent(QEvent*) override; + void RetranslateUI(); + + void InitializeLanguageComboBox(); + void InitializeIconSizeComboBox(); + void InitializeRowComboBoxes(); + + void UpdateFirstRowComboBox(bool init = false); + void UpdateSecondRowComboBox(bool init = false); + + void UpdateWidthText(); + + std::unique_ptr ui; + + Settings::AspectRatio ratio; + Settings::ResolutionSetup resolution_setting; + Core::System& system; +}; diff --git a/src/sudachi/configuration/configure_ui.ui b/src/sudachi/configuration/configure_ui.ui new file mode 100644 index 0000000..b8e6483 --- /dev/null +++ b/src/sudachi/configuration/configure_ui.ui @@ -0,0 +1,268 @@ + + + ConfigureUi + + + + 0 + 0 + 363 + 603 + + + + Form + + + UI + + + + + + General + + + + + + + + Note: Changing language will apply your configuration. + + + true + + + + + + + + + Interface language: + + + + + + + + + + + + + + Theme: + + + + + + + + + + + + + + + + + Game List + + + + + + + + Show Compatibility List + + + + + + + Show Add-Ons Column + + + + + + + Show Size Column + + + + + + + Show File Types Column + + + + + + + Show Play Time Column + + + + + + + + + Game Icon Size: + + + + + + + + + + + + + + Folder Icon Size: + + + + + + + + + + + + + + Row 1 Text: + + + + + + + + + + + + + + Row 2 Text: + + + + + + + + + + + + + + + + + Screenshots + + + + + + + + Ask Where To Save Screenshots (Windows Only) + + + + + + + + + Screenshots Path: + + + + + + + + + + ... + + + + + + + + + 6 + + + + + + + TextLabel + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + + + + + true + + + + + + + + + Resolution: + + + + + + + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + diff --git a/src/sudachi/configuration/configure_vibration.cpp b/src/sudachi/configuration/configure_vibration.cpp new file mode 100644 index 0000000..e440f50 --- /dev/null +++ b/src/sudachi/configuration/configure_vibration.cpp @@ -0,0 +1,133 @@ +// SPDX-FileCopyrightText: Copyright 2020 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include "common/settings.h" +#include "hid_core/frontend/emulated_controller.h" +#include "hid_core/hid_core.h" +#include "hid_core/hid_types.h" +#include "ui_configure_vibration.h" +#include "sudachi/configuration/configure_vibration.h" + +ConfigureVibration::ConfigureVibration(QWidget* parent, Core::HID::HIDCore& hid_core_) + : QDialog(parent), ui(std::make_unique()), hid_core{hid_core_} { + ui->setupUi(this); + + vibration_groupboxes = { + ui->vibrationGroupPlayer1, ui->vibrationGroupPlayer2, ui->vibrationGroupPlayer3, + ui->vibrationGroupPlayer4, ui->vibrationGroupPlayer5, ui->vibrationGroupPlayer6, + ui->vibrationGroupPlayer7, ui->vibrationGroupPlayer8, + }; + + vibration_spinboxes = { + ui->vibrationSpinPlayer1, ui->vibrationSpinPlayer2, ui->vibrationSpinPlayer3, + ui->vibrationSpinPlayer4, ui->vibrationSpinPlayer5, ui->vibrationSpinPlayer6, + ui->vibrationSpinPlayer7, ui->vibrationSpinPlayer8, + }; + + const auto& players = Settings::values.players.GetValue(); + + for (std::size_t i = 0; i < NUM_PLAYERS; ++i) { + auto controller = hid_core.GetEmulatedControllerByIndex(i); + Core::HID::ControllerUpdateCallback engine_callback{ + .on_change = [this, + i](Core::HID::ControllerTriggerType type) { VibrateController(type, i); }, + .is_npad_service = false, + }; + controller_callback_key[i] = controller->SetCallback(engine_callback); + vibration_groupboxes[i]->setChecked(players[i].vibration_enabled); + vibration_spinboxes[i]->setValue(players[i].vibration_strength); + } + + ui->checkBoxAccurateVibration->setChecked( + Settings::values.enable_accurate_vibrations.GetValue()); + + if (!Settings::IsConfiguringGlobal()) { + ui->checkBoxAccurateVibration->setDisabled(true); + } + + RetranslateUI(); +} + +ConfigureVibration::~ConfigureVibration() { + StopVibrations(); + + for (std::size_t i = 0; i < NUM_PLAYERS; ++i) { + auto controller = hid_core.GetEmulatedControllerByIndex(i); + controller->DeleteCallback(controller_callback_key[i]); + } +}; + +void ConfigureVibration::ApplyConfiguration() { + auto& players = Settings::values.players.GetValue(); + + for (std::size_t i = 0; i < NUM_PLAYERS; ++i) { + players[i].vibration_enabled = vibration_groupboxes[i]->isChecked(); + players[i].vibration_strength = vibration_spinboxes[i]->value(); + } + + Settings::values.enable_accurate_vibrations.SetValue( + ui->checkBoxAccurateVibration->isChecked()); +} + +void ConfigureVibration::changeEvent(QEvent* event) { + if (event->type() == QEvent::LanguageChange) { + RetranslateUI(); + } + + QDialog::changeEvent(event); +} + +void ConfigureVibration::RetranslateUI() { + ui->retranslateUi(this); +} + +void ConfigureVibration::VibrateController(Core::HID::ControllerTriggerType type, + std::size_t player_index) { + if (type != Core::HID::ControllerTriggerType::Button) { + return; + } + + auto& player = Settings::values.players.GetValue()[player_index]; + auto controller = hid_core.GetEmulatedControllerByIndex(player_index); + const int vibration_strength = vibration_spinboxes[player_index]->value(); + const auto& buttons = controller->GetButtonsValues(); + + bool button_is_pressed = false; + for (std::size_t i = 0; i < buttons.size(); ++i) { + if (buttons[i].value) { + button_is_pressed = true; + break; + } + } + + if (!button_is_pressed) { + StopVibrations(); + return; + } + + const bool old_vibration_enabled = player.vibration_enabled; + const int old_vibration_strength = player.vibration_strength; + player.vibration_enabled = true; + player.vibration_strength = vibration_strength; + + const Core::HID::VibrationValue vibration{ + .low_amplitude = 1.0f, + .low_frequency = 160.0f, + .high_amplitude = 1.0f, + .high_frequency = 320.0f, + }; + controller->SetVibration(Core::HID::DeviceIndex::Left, vibration); + controller->SetVibration(Core::HID::DeviceIndex::Right, vibration); + + // Restore previous values + player.vibration_enabled = old_vibration_enabled; + player.vibration_strength = old_vibration_strength; +} + +void ConfigureVibration::StopVibrations() { + for (std::size_t i = 0; i < NUM_PLAYERS; ++i) { + auto controller = hid_core.GetEmulatedControllerByIndex(i); + controller->SetVibration(Core::HID::DeviceIndex::Left, Core::HID::DEFAULT_VIBRATION_VALUE); + controller->SetVibration(Core::HID::DeviceIndex::Right, Core::HID::DEFAULT_VIBRATION_VALUE); + } +} diff --git a/src/sudachi/configuration/configure_vibration.h b/src/sudachi/configuration/configure_vibration.h new file mode 100644 index 0000000..831fedf --- /dev/null +++ b/src/sudachi/configuration/configure_vibration.h @@ -0,0 +1,51 @@ +// SPDX-FileCopyrightText: Copyright 2020 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include +#include + +class QGroupBox; +class QSpinBox; + +namespace Ui { +class ConfigureVibration; +} + +namespace Core::HID { +enum class ControllerTriggerType; +class HIDCore; +} // namespace Core::HID + +class ConfigureVibration : public QDialog { + Q_OBJECT + +public: + explicit ConfigureVibration(QWidget* parent, Core::HID::HIDCore& hid_core_); + ~ConfigureVibration() override; + + void ApplyConfiguration(); + +private: + void changeEvent(QEvent* event) override; + void RetranslateUI(); + void VibrateController(Core::HID::ControllerTriggerType type, std::size_t player_index); + void StopVibrations(); + + std::unique_ptr ui; + + static constexpr std::size_t NUM_PLAYERS = 8; + + /// Groupboxes encapsulating the vibration strength spinbox. + std::array vibration_groupboxes; + + /// Spinboxes representing the vibration strength percentage. + std::array vibration_spinboxes; + + /// Callback index to stop the controllers events + std::array controller_callback_key; + + Core::HID::HIDCore& hid_core; +}; diff --git a/src/sudachi/configuration/configure_vibration.ui b/src/sudachi/configuration/configure_vibration.ui new file mode 100644 index 0000000..447a18e --- /dev/null +++ b/src/sudachi/configuration/configure_vibration.ui @@ -0,0 +1,553 @@ + + + ConfigureVibration + + + + 0 + 0 + 364 + 242 + + + + Configure Vibration + + + + + + + + + Press any controller button to vibrate the controller. + + + + + + + Vibration + + + + 9 + + + 9 + + + 9 + + + 9 + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Player 1 + + + true + + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 68 + 21 + + + + + 68 + 16777215 + + + + % + + + 1 + + + 150 + + + 100 + + + + + + + + + + Player 2 + + + true + + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 68 + 21 + + + + + 68 + 16777215 + + + + % + + + 1 + + + 150 + + + 100 + + + + + + + + + + Player 3 + + + true + + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 68 + 21 + + + + + 68 + 16777215 + + + + % + + + 1 + + + 150 + + + 100 + + + + + + + + + + Player 4 + + + true + + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 68 + 21 + + + + + 68 + 16777215 + + + + % + + + 1 + + + 150 + + + 100 + + + + + + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Player 5 + + + true + + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 68 + 21 + + + + + 68 + 16777215 + + + + % + + + 1 + + + 150 + + + 100 + + + + + + + + + + Player 6 + + + true + + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 68 + 21 + + + + + 68 + 16777215 + + + + % + + + 1 + + + 150 + + + 100 + + + + + + + + + + Player 7 + + + true + + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 68 + 21 + + + + + 68 + 16777215 + + + + % + + + 1 + + + 150 + + + 100 + + + + + + + + + + Player 8 + + + true + + + + 3 + + + 3 + + + 3 + + + 3 + + + + + + 68 + 21 + + + + + 68 + 16777215 + + + + % + + + 1 + + + 150 + + + 100 + + + + + + + + + + + + + + + + Settings + + + + + + Enable Accurate Vibration + + + + + + + + + + Qt::Vertical + + + + 167 + 55 + + + + + + + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + + + + + + + + buttonBoxVibration + accepted() + ConfigureVibration + accept() + + + buttonBoxVibration + rejected() + ConfigureVibration + reject() + + + diff --git a/src/sudachi/configuration/configure_web.cpp b/src/sudachi/configuration/configure_web.cpp new file mode 100644 index 0000000..328888b --- /dev/null +++ b/src/sudachi/configuration/configure_web.cpp @@ -0,0 +1,180 @@ +// SPDX-FileCopyrightText: 2017 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include +#include +#include "common/settings.h" +#include "core/telemetry_session.h" +#include "ui_configure_web.h" +#include "sudachi/configuration/configure_web.h" +#include "sudachi/uisettings.h" + +static constexpr char token_delimiter{':'}; + +static std::string GenerateDisplayToken(const std::string& username, const std::string& token) { + if (username.empty() || token.empty()) { + return {}; + } + + const std::string unencoded_display_token{username + token_delimiter + token}; + QByteArray b{unencoded_display_token.c_str()}; + QByteArray b64 = b.toBase64(); + return b64.toStdString(); +} + +static std::string UsernameFromDisplayToken(const std::string& display_token) { + const std::string unencoded_display_token{ + QByteArray::fromBase64(display_token.c_str()).toStdString()}; + return unencoded_display_token.substr(0, unencoded_display_token.find(token_delimiter)); +} + +static std::string TokenFromDisplayToken(const std::string& display_token) { + const std::string unencoded_display_token{ + QByteArray::fromBase64(display_token.c_str()).toStdString()}; + return unencoded_display_token.substr(unencoded_display_token.find(token_delimiter) + 1); +} + +ConfigureWeb::ConfigureWeb(QWidget* parent) + : QWidget(parent), ui(std::make_unique()) { + ui->setupUi(this); + connect(ui->button_regenerate_telemetry_id, &QPushButton::clicked, this, + &ConfigureWeb::RefreshTelemetryID); + connect(ui->button_verify_login, &QPushButton::clicked, this, &ConfigureWeb::VerifyLogin); + connect(&verify_watcher, &QFutureWatcher::finished, this, &ConfigureWeb::OnLoginVerified); + +#ifndef USE_DISCORD_PRESENCE + ui->discord_group->setVisible(false); +#endif + + SetConfiguration(); + RetranslateUI(); +} + +ConfigureWeb::~ConfigureWeb() = default; + +void ConfigureWeb::changeEvent(QEvent* event) { + if (event->type() == QEvent::LanguageChange) { + RetranslateUI(); + } + + QWidget::changeEvent(event); +} + +void ConfigureWeb::RetranslateUI() { + ui->retranslateUi(this); + + ui->telemetry_learn_more->setText( + tr("Learn more")); + + ui->web_signup_link->setText( + tr("Sign up")); + + ui->web_token_info_link->setText( + tr("What is my token?")); + + ui->label_telemetry_id->setText( + tr("Telemetry ID: 0x%1").arg(QString::number(Core::GetTelemetryId(), 16).toUpper())); +} + +void ConfigureWeb::SetConfiguration() { + ui->web_credentials_disclaimer->setWordWrap(true); + + ui->telemetry_learn_more->setOpenExternalLinks(true); + ui->web_signup_link->setOpenExternalLinks(true); + ui->web_token_info_link->setOpenExternalLinks(true); + + if (Settings::values.sudachi_username.GetValue().empty()) { + ui->username->setText(tr("Unspecified")); + } else { + ui->username->setText(QString::fromStdString(Settings::values.sudachi_username.GetValue())); + } + + ui->toggle_telemetry->setChecked(Settings::values.enable_telemetry.GetValue()); + ui->edit_token->setText(QString::fromStdString(GenerateDisplayToken( + Settings::values.sudachi_username.GetValue(), Settings::values.sudachi_token.GetValue()))); + + // Connect after setting the values, to avoid calling OnLoginChanged now + connect(ui->edit_token, &QLineEdit::textChanged, this, &ConfigureWeb::OnLoginChanged); + + user_verified = true; + + ui->toggle_discordrpc->setChecked(UISettings::values.enable_discord_presence.GetValue()); +} + +void ConfigureWeb::ApplyConfiguration() { + Settings::values.enable_telemetry = ui->toggle_telemetry->isChecked(); + UISettings::values.enable_discord_presence = ui->toggle_discordrpc->isChecked(); + if (user_verified) { + Settings::values.sudachi_username = + UsernameFromDisplayToken(ui->edit_token->text().toStdString()); + Settings::values.sudachi_token = TokenFromDisplayToken(ui->edit_token->text().toStdString()); + } else { + QMessageBox::warning( + this, tr("Token not verified"), + tr("Token was not verified. The change to your token has not been saved.")); + } +} + +void ConfigureWeb::RefreshTelemetryID() { + const u64 new_telemetry_id{Core::RegenerateTelemetryId()}; + ui->label_telemetry_id->setText( + tr("Telemetry ID: 0x%1").arg(QString::number(new_telemetry_id, 16).toUpper())); +} + +void ConfigureWeb::OnLoginChanged() { + if (ui->edit_token->text().isEmpty()) { + user_verified = true; + // Empty = no icon + ui->label_token_verified->setPixmap(QPixmap()); + ui->label_token_verified->setToolTip(QString()); + } else { + user_verified = false; + + // Show an info icon if it's been changed, clearer than showing failure + const QPixmap pixmap = QIcon::fromTheme(QStringLiteral("info")).pixmap(16); + ui->label_token_verified->setPixmap(pixmap); + ui->label_token_verified->setToolTip( + tr("Unverified, please click Verify before saving configuration", "Tooltip")); + } +} + +void ConfigureWeb::VerifyLogin() { + ui->button_verify_login->setDisabled(true); + ui->button_verify_login->setText(tr("Verifying...")); + ui->label_token_verified->setPixmap(QIcon::fromTheme(QStringLiteral("sync")).pixmap(16)); + ui->label_token_verified->setToolTip(tr("Verifying...")); + verify_watcher.setFuture(QtConcurrent::run( + [username = UsernameFromDisplayToken(ui->edit_token->text().toStdString()), + token = TokenFromDisplayToken(ui->edit_token->text().toStdString())] { + return Core::VerifyLogin(username, token); + })); +} + +void ConfigureWeb::OnLoginVerified() { + ui->button_verify_login->setEnabled(true); + ui->button_verify_login->setText(tr("Verify")); + if (verify_watcher.result()) { + user_verified = true; + + ui->label_token_verified->setPixmap(QIcon::fromTheme(QStringLiteral("checked")).pixmap(16)); + ui->label_token_verified->setToolTip(tr("Verified", "Tooltip")); + ui->username->setText( + QString::fromStdString(UsernameFromDisplayToken(ui->edit_token->text().toStdString()))); + } else { + ui->label_token_verified->setPixmap(QIcon::fromTheme(QStringLiteral("failed")).pixmap(16)); + ui->label_token_verified->setToolTip(tr("Verification failed", "Tooltip")); + ui->username->setText(tr("Unspecified")); + QMessageBox::critical(this, tr("Verification failed"), + tr("Verification failed. Check that you have entered your token " + "correctly, and that your internet connection is working.")); + } +} + +void ConfigureWeb::SetWebServiceConfigEnabled(bool enabled) { + ui->label_disable_info->setVisible(!enabled); + ui->groupBoxWebConfig->setEnabled(enabled); +} diff --git a/src/sudachi/configuration/configure_web.h b/src/sudachi/configuration/configure_web.h new file mode 100644 index 0000000..03feb55 --- /dev/null +++ b/src/sudachi/configuration/configure_web.h @@ -0,0 +1,39 @@ +// SPDX-FileCopyrightText: 2017 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include +#include + +namespace Ui { +class ConfigureWeb; +} + +class ConfigureWeb : public QWidget { + Q_OBJECT + +public: + explicit ConfigureWeb(QWidget* parent = nullptr); + ~ConfigureWeb() override; + + void ApplyConfiguration(); + void SetWebServiceConfigEnabled(bool enabled); + +private: + void changeEvent(QEvent* event) override; + void RetranslateUI(); + + void RefreshTelemetryID(); + void OnLoginChanged(); + void VerifyLogin(); + void OnLoginVerified(); + + void SetConfiguration(); + + bool user_verified = true; + QFutureWatcher verify_watcher; + + std::unique_ptr ui; +}; diff --git a/src/sudachi/configuration/configure_web.ui b/src/sudachi/configuration/configure_web.ui new file mode 100644 index 0000000..eb5e44a --- /dev/null +++ b/src/sudachi/configuration/configure_web.ui @@ -0,0 +1,210 @@ + + + ConfigureWeb + + + + 0 + 0 + 926 + 561 + + + + Form + + + Web + + + + + + + + sudachi Web Service + + + + + + By providing your username and token, you agree to allow sudachi to collect additional usage data, which may include user identifying information. + + + + + + + + + + 0 + 0 + + + + Qt::RightToLeft + + + Verify + + + + + + + Sign up + + + + + + + + + + Token: + + + + + + + + + + Username: + + + + + + + 80 + + + QLineEdit::Password + + + + + + + What is my token? + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + + + Web Service configuration can only be changed when a public room isn't being hosted. + + + true + + + + + + + Telemetry + + + + + + Share anonymous usage data with the sudachi team + + + + + + + Learn more + + + + + + + + + Telemetry ID: + + + + + + + + 0 + 0 + + + + Qt::RightToLeft + + + Regenerate + + + + + + + + + + + + + + Discord Presence + + + + + + Show Current Game in your Discord Status + + + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + diff --git a/src/sudachi/configuration/input_profiles.cpp b/src/sudachi/configuration/input_profiles.cpp new file mode 100644 index 0000000..56b3638 --- /dev/null +++ b/src/sudachi/configuration/input_profiles.cpp @@ -0,0 +1,134 @@ +// SPDX-FileCopyrightText: Copyright 2020 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include + +#include "common/fs/fs.h" +#include "common/fs/path_util.h" +#include "common/logging/log.h" +#include "frontend_common/config.h" +#include "sudachi/configuration/input_profiles.h" + +namespace FS = Common::FS; + +namespace { + +bool ProfileExistsInFilesystem(std::string_view profile_name) { + return FS::Exists(FS::GetSudachiPath(FS::SudachiPath::ConfigDir) / "input" / + fmt::format("{}.ini", profile_name)); +} + +bool IsINI(const std::filesystem::path& filename) { + return filename.extension() == ".ini"; +} + +std::filesystem::path GetNameWithoutExtension(std::filesystem::path filename) { + return filename.replace_extension(); +} + +} // namespace + +InputProfiles::InputProfiles() { + const auto input_profile_loc = FS::GetSudachiPath(FS::SudachiPath::ConfigDir) / "input"; + + if (!FS::IsDir(input_profile_loc)) { + return; + } + + FS::IterateDirEntries( + input_profile_loc, + [this](const std::filesystem::path& full_path) { + const auto filename = full_path.filename(); + const auto name_without_ext = + Common::FS::PathToUTF8String(GetNameWithoutExtension(filename)); + + if (IsINI(filename) && IsProfileNameValid(name_without_ext)) { + map_profiles.insert_or_assign( + name_without_ext, + std::make_unique(name_without_ext, Config::ConfigType::InputProfile)); + } + + return true; + }, + FS::DirEntryFilter::File); +} + +InputProfiles::~InputProfiles() = default; + +std::vector InputProfiles::GetInputProfileNames() { + std::vector profile_names; + profile_names.reserve(map_profiles.size()); + + auto it = map_profiles.cbegin(); + while (it != map_profiles.cend()) { + const auto& [profile_name, config] = *it; + if (!ProfileExistsInFilesystem(profile_name)) { + it = map_profiles.erase(it); + continue; + } + + profile_names.push_back(profile_name); + ++it; + } + + std::stable_sort(profile_names.begin(), profile_names.end()); + + return profile_names; +} + +bool InputProfiles::IsProfileNameValid(std::string_view profile_name) { + return profile_name.find_first_of("<>:;\"/\\|,.!?*") == std::string::npos; +} + +bool InputProfiles::CreateProfile(const std::string& profile_name, std::size_t player_index) { + if (ProfileExistsInMap(profile_name)) { + return false; + } + + map_profiles.insert_or_assign( + profile_name, std::make_unique(profile_name, Config::ConfigType::InputProfile)); + + return SaveProfile(profile_name, player_index); +} + +bool InputProfiles::DeleteProfile(const std::string& profile_name) { + if (!ProfileExistsInMap(profile_name)) { + return false; + } + + if (!ProfileExistsInFilesystem(profile_name) || + FS::RemoveFile(map_profiles[profile_name]->GetConfigFilePath())) { + map_profiles.erase(profile_name); + } + + return !ProfileExistsInMap(profile_name) && !ProfileExistsInFilesystem(profile_name); +} + +bool InputProfiles::LoadProfile(const std::string& profile_name, std::size_t player_index) { + if (!ProfileExistsInMap(profile_name)) { + return false; + } + + if (!ProfileExistsInFilesystem(profile_name)) { + map_profiles.erase(profile_name); + return false; + } + + LOG_INFO(Config, "Loading input profile `{}`", profile_name); + + map_profiles[profile_name]->ReadQtControlPlayerValues(player_index); + return true; +} + +bool InputProfiles::SaveProfile(const std::string& profile_name, std::size_t player_index) { + if (!ProfileExistsInMap(profile_name)) { + return false; + } + + map_profiles[profile_name]->SaveQtControlPlayerValues(player_index); + return true; +} + +bool InputProfiles::ProfileExistsInMap(const std::string& profile_name) const { + return map_profiles.find(profile_name) != map_profiles.end(); +} diff --git a/src/sudachi/configuration/input_profiles.h b/src/sudachi/configuration/input_profiles.h new file mode 100644 index 0000000..0b1bd7e --- /dev/null +++ b/src/sudachi/configuration/input_profiles.h @@ -0,0 +1,36 @@ +// SPDX-FileCopyrightText: Copyright 2020 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include + +#include "configuration/qt_config.h" + +namespace Core { +class System; +} + +class Config; + +class InputProfiles { + +public: + explicit InputProfiles(); + virtual ~InputProfiles(); + + std::vector GetInputProfileNames(); + + static bool IsProfileNameValid(std::string_view profile_name); + + bool CreateProfile(const std::string& profile_name, std::size_t player_index); + bool DeleteProfile(const std::string& profile_name); + bool LoadProfile(const std::string& profile_name, std::size_t player_index); + bool SaveProfile(const std::string& profile_name, std::size_t player_index); + +private: + bool ProfileExistsInMap(const std::string& profile_name) const; + + std::unordered_map> map_profiles; +}; diff --git a/src/sudachi/configuration/qt_config.cpp b/src/sudachi/configuration/qt_config.cpp new file mode 100644 index 0000000..4f5d535 --- /dev/null +++ b/src/sudachi/configuration/qt_config.cpp @@ -0,0 +1,560 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include "common/logging/log.h" +#include "input_common/main.h" +#include "qt_config.h" +#include "uisettings.h" + +const std::array QtConfig::default_buttons = { + Qt::Key_C, Qt::Key_X, Qt::Key_V, Qt::Key_Z, Qt::Key_F, + Qt::Key_G, Qt::Key_Q, Qt::Key_E, Qt::Key_R, Qt::Key_T, + Qt::Key_M, Qt::Key_N, Qt::Key_Left, Qt::Key_Up, Qt::Key_Right, + Qt::Key_Down, Qt::Key_Q, Qt::Key_E, 0, 0, + Qt::Key_Q, Qt::Key_E, +}; + +const std::array QtConfig::default_motions = { + Qt::Key_7, + Qt::Key_8, +}; + +const std::array, Settings::NativeAnalog::NumAnalogs> QtConfig::default_analogs{{ + { + Qt::Key_W, + Qt::Key_S, + Qt::Key_A, + Qt::Key_D, + }, + { + Qt::Key_I, + Qt::Key_K, + Qt::Key_J, + Qt::Key_L, + }, +}}; + +const std::array QtConfig::default_stick_mod = { + Qt::Key_Shift, + 0, +}; + +const std::array QtConfig::default_ringcon_analogs{{ + Qt::Key_A, + Qt::Key_D, +}}; + +QtConfig::QtConfig(const std::string& config_name, const ConfigType config_type) + : Config(config_type) { + Initialize(config_name); + if (config_type != ConfigType::InputProfile) { + ReadQtValues(); + SaveQtValues(); + } +} + +QtConfig::~QtConfig() { + if (global) { + QtConfig::SaveAllValues(); + } +} + +void QtConfig::ReloadAllValues() { + Reload(); + ReadQtValues(); + SaveQtValues(); +} + +void QtConfig::SaveAllValues() { + SaveValues(); + SaveQtValues(); +} + +void QtConfig::ReadQtValues() { + if (global) { + ReadUIValues(); + } + ReadQtControlValues(); +} + +void QtConfig::ReadQtPlayerValues(const std::size_t player_index) { + std::string player_prefix; + if (type != ConfigType::InputProfile) { + player_prefix.append("player_").append(ToString(player_index)).append("_"); + } + + auto& player = Settings::values.players.GetValue()[player_index]; + if (IsCustomConfig()) { + const auto profile_name = + ReadStringSetting(std::string(player_prefix).append("profile_name")); + if (profile_name.empty()) { + // Use the global input config + player = Settings::values.players.GetValue(true)[player_index]; + player.profile_name = ""; + return; + } + } + + for (int i = 0; i < Settings::NativeButton::NumButtons; ++i) { + const std::string default_param = InputCommon::GenerateKeyboardParam(default_buttons[i]); + auto& player_buttons = player.buttons[i]; + + player_buttons = ReadStringSetting( + std::string(player_prefix).append(Settings::NativeButton::mapping[i]), default_param); + if (player_buttons.empty()) { + player_buttons = default_param; + } + } + + for (int i = 0; i < Settings::NativeAnalog::NumAnalogs; ++i) { + const std::string default_param = InputCommon::GenerateAnalogParamFromKeys( + default_analogs[i][0], default_analogs[i][1], default_analogs[i][2], + default_analogs[i][3], default_stick_mod[i], 0.5f); + auto& player_analogs = player.analogs[i]; + + player_analogs = ReadStringSetting( + std::string(player_prefix).append(Settings::NativeAnalog::mapping[i]), default_param); + if (player_analogs.empty()) { + player_analogs = default_param; + } + } + + for (int i = 0; i < Settings::NativeMotion::NumMotions; ++i) { + const std::string default_param = InputCommon::GenerateKeyboardParam(default_motions[i]); + auto& player_motions = player.motions[i]; + + player_motions = ReadStringSetting( + std::string(player_prefix).append(Settings::NativeMotion::mapping[i]), default_param); + if (player_motions.empty()) { + player_motions = default_param; + } + } +} + +void QtConfig::ReadHidbusValues() { + const std::string default_param = InputCommon::GenerateAnalogParamFromKeys( + 0, 0, default_ringcon_analogs[0], default_ringcon_analogs[1], 0, 0.05f); + auto& ringcon_analogs = Settings::values.ringcon_analogs; + + ringcon_analogs = ReadStringSetting(std::string("ring_controller"), default_param); + if (ringcon_analogs.empty()) { + ringcon_analogs = default_param; + } +} + +void QtConfig::ReadDebugControlValues() { + for (int i = 0; i < Settings::NativeButton::NumButtons; ++i) { + const std::string default_param = InputCommon::GenerateKeyboardParam(default_buttons[i]); + auto& debug_pad_buttons = Settings::values.debug_pad_buttons[i]; + + debug_pad_buttons = ReadStringSetting( + std::string("debug_pad_").append(Settings::NativeButton::mapping[i]), default_param); + if (debug_pad_buttons.empty()) { + debug_pad_buttons = default_param; + } + } + + for (int i = 0; i < Settings::NativeAnalog::NumAnalogs; ++i) { + const std::string default_param = InputCommon::GenerateAnalogParamFromKeys( + default_analogs[i][0], default_analogs[i][1], default_analogs[i][2], + default_analogs[i][3], default_stick_mod[i], 0.5f); + auto& debug_pad_analogs = Settings::values.debug_pad_analogs[i]; + + debug_pad_analogs = ReadStringSetting( + std::string("debug_pad_").append(Settings::NativeAnalog::mapping[i]), default_param); + if (debug_pad_analogs.empty()) { + debug_pad_analogs = default_param; + } + } +} + +void QtConfig::ReadQtControlValues() { + BeginGroup(Settings::TranslateCategory(Settings::Category::Controls)); + + Settings::values.players.SetGlobal(!IsCustomConfig()); + for (std::size_t p = 0; p < Settings::values.players.GetValue().size(); ++p) { + ReadQtPlayerValues(p); + } + if (IsCustomConfig()) { + EndGroup(); + return; + } + ReadDebugControlValues(); + ReadHidbusValues(); + + EndGroup(); +} + +void QtConfig::ReadPathValues() { + BeginGroup(Settings::TranslateCategory(Settings::Category::Paths)); + + UISettings::values.roms_path = ReadStringSetting(std::string("romsPath")); + UISettings::values.game_dir_deprecated = + ReadStringSetting(std::string("gameListRootDir"), std::string(".")); + UISettings::values.game_dir_deprecated_deepscan = + ReadBooleanSetting(std::string("gameListDeepScan"), std::make_optional(false)); + + const int gamedirs_size = BeginArray(std::string("gamedirs")); + for (int i = 0; i < gamedirs_size; ++i) { + SetArrayIndex(i); + UISettings::GameDir game_dir; + game_dir.path = ReadStringSetting(std::string("path")); + game_dir.deep_scan = + ReadBooleanSetting(std::string("deep_scan"), std::make_optional(false)); + game_dir.expanded = ReadBooleanSetting(std::string("expanded"), std::make_optional(true)); + UISettings::values.game_dirs.append(game_dir); + } + EndArray(); + + // Create NAND and SD card directories if empty, these are not removable through the UI, + // also carries over old game list settings if present + if (UISettings::values.game_dirs.empty()) { + UISettings::GameDir game_dir; + game_dir.path = std::string("SDMC"); + game_dir.expanded = true; + UISettings::values.game_dirs.append(game_dir); + game_dir.path = std::string("UserNAND"); + UISettings::values.game_dirs.append(game_dir); + game_dir.path = std::string("SysNAND"); + UISettings::values.game_dirs.append(game_dir); + if (UISettings::values.game_dir_deprecated != std::string(".")) { + game_dir.path = UISettings::values.game_dir_deprecated; + game_dir.deep_scan = UISettings::values.game_dir_deprecated_deepscan; + UISettings::values.game_dirs.append(game_dir); + } + } + UISettings::values.recent_files = + QString::fromStdString(ReadStringSetting(std::string("recentFiles"))) + .split(QStringLiteral(", "), Qt::SkipEmptyParts, Qt::CaseSensitive); + + ReadCategory(Settings::Category::Paths); + + EndGroup(); +} + +void QtConfig::ReadShortcutValues() { + BeginGroup(Settings::TranslateCategory(Settings::Category::Shortcuts)); + + for (const auto& [name, group, shortcut] : UISettings::default_hotkeys) { + BeginGroup(group); + BeginGroup(name); + + // No longer using ReadSetting for shortcut.second as it inaccurately returns a value of 1 + // for WidgetWithChildrenShortcut which is a value of 3. Needed to fix shortcuts the open + // a file dialog in windowed mode + UISettings::values.shortcuts.push_back( + {name, + group, + {ReadStringSetting(std::string("KeySeq"), shortcut.keyseq), + ReadStringSetting(std::string("Controller_KeySeq"), shortcut.controller_keyseq), + shortcut.context, + ReadBooleanSetting(std::string("Repeat"), std::optional(shortcut.repeat))}}); + + EndGroup(); // name + EndGroup(); // group + } + + EndGroup(); +} + +void QtConfig::ReadUIValues() { + BeginGroup(Settings::TranslateCategory(Settings::Category::Ui)); + + UISettings::values.theme = ReadStringSetting( + std::string("theme"), + std::string(UISettings::themes[static_cast(UISettings::default_theme)].second)); + + ReadUIGamelistValues(); + ReadUILayoutValues(); + ReadPathValues(); + ReadScreenshotValues(); + ReadShortcutValues(); + ReadMultiplayerValues(); + + ReadCategory(Settings::Category::Ui); + ReadCategory(Settings::Category::UiGeneral); + + EndGroup(); +} + +void QtConfig::ReadUIGamelistValues() { + BeginGroup(Settings::TranslateCategory(Settings::Category::UiGameList)); + + ReadCategory(Settings::Category::UiGameList); + + const int favorites_size = BeginArray("favorites"); + for (int i = 0; i < favorites_size; i++) { + SetArrayIndex(i); + UISettings::values.favorited_ids.append( + ReadUnsignedIntegerSetting(std::string("program_id"))); + } + EndArray(); + + EndGroup(); +} + +void QtConfig::ReadUILayoutValues() { + BeginGroup(Settings::TranslateCategory(Settings::Category::UiGameList)); + + ReadCategory(Settings::Category::UiLayout); + + EndGroup(); +} + +void QtConfig::ReadMultiplayerValues() { + BeginGroup(Settings::TranslateCategory(Settings::Category::Multiplayer)); + + ReadCategory(Settings::Category::Multiplayer); + + // Read ban list back + int size = BeginArray(std::string("username_ban_list")); + UISettings::values.multiplayer_ban_list.first.resize(size); + for (int i = 0; i < size; ++i) { + SetArrayIndex(i); + UISettings::values.multiplayer_ban_list.first[i] = + ReadStringSetting(std::string("username"), std::string("")); + } + EndArray(); + + size = BeginArray(std::string("ip_ban_list")); + UISettings::values.multiplayer_ban_list.second.resize(size); + for (int i = 0; i < size; ++i) { + UISettings::values.multiplayer_ban_list.second[i] = + ReadStringSetting("username", std::string("")); + } + EndArray(); + + EndGroup(); +} + +void QtConfig::SaveQtValues() { + if (global) { + LOG_DEBUG(Config, "Saving global Qt configuration values"); + SaveUIValues(); + } else { + LOG_DEBUG(Config, "Saving Qt configuration values"); + } + SaveQtControlValues(); + + WriteToIni(); +} + +void QtConfig::SaveQtPlayerValues(const std::size_t player_index) { + std::string player_prefix; + if (type != ConfigType::InputProfile) { + player_prefix = std::string("player_").append(ToString(player_index)).append("_"); + } + + const auto& player = Settings::values.players.GetValue()[player_index]; + if (IsCustomConfig() && player.profile_name.empty()) { + // No custom profile selected + return; + } + + for (int i = 0; i < Settings::NativeButton::NumButtons; ++i) { + const std::string default_param = InputCommon::GenerateKeyboardParam(default_buttons[i]); + WriteStringSetting(std::string(player_prefix).append(Settings::NativeButton::mapping[i]), + player.buttons[i], std::make_optional(default_param)); + } + for (int i = 0; i < Settings::NativeAnalog::NumAnalogs; ++i) { + const std::string default_param = InputCommon::GenerateAnalogParamFromKeys( + default_analogs[i][0], default_analogs[i][1], default_analogs[i][2], + default_analogs[i][3], default_stick_mod[i], 0.5f); + WriteStringSetting(std::string(player_prefix).append(Settings::NativeAnalog::mapping[i]), + player.analogs[i], std::make_optional(default_param)); + } + for (int i = 0; i < Settings::NativeMotion::NumMotions; ++i) { + const std::string default_param = InputCommon::GenerateKeyboardParam(default_motions[i]); + WriteStringSetting(std::string(player_prefix).append(Settings::NativeMotion::mapping[i]), + player.motions[i], std::make_optional(default_param)); + } +} + +void QtConfig::SaveDebugControlValues() { + for (int i = 0; i < Settings::NativeButton::NumButtons; ++i) { + const std::string default_param = InputCommon::GenerateKeyboardParam(default_buttons[i]); + WriteStringSetting(std::string("debug_pad_").append(Settings::NativeButton::mapping[i]), + Settings::values.debug_pad_buttons[i], + std::make_optional(default_param)); + } + for (int i = 0; i < Settings::NativeAnalog::NumAnalogs; ++i) { + const std::string default_param = InputCommon::GenerateAnalogParamFromKeys( + default_analogs[i][0], default_analogs[i][1], default_analogs[i][2], + default_analogs[i][3], default_stick_mod[i], 0.5f); + WriteStringSetting(std::string("debug_pad_").append(Settings::NativeAnalog::mapping[i]), + Settings::values.debug_pad_analogs[i], + std::make_optional(default_param)); + } +} + +void QtConfig::SaveHidbusValues() { + const std::string default_param = InputCommon::GenerateAnalogParamFromKeys( + 0, 0, default_ringcon_analogs[0], default_ringcon_analogs[1], 0, 0.05f); + WriteStringSetting(std::string("ring_controller"), Settings::values.ringcon_analogs, + std::make_optional(default_param)); +} + +void QtConfig::SaveQtControlValues() { + BeginGroup(Settings::TranslateCategory(Settings::Category::Controls)); + + Settings::values.players.SetGlobal(!IsCustomConfig()); + for (std::size_t p = 0; p < Settings::values.players.GetValue().size(); ++p) { + SaveQtPlayerValues(p); + } + if (IsCustomConfig()) { + EndGroup(); + return; + } + SaveDebugControlValues(); + SaveHidbusValues(); + + EndGroup(); +} + +void QtConfig::SavePathValues() { + BeginGroup(Settings::TranslateCategory(Settings::Category::Paths)); + + WriteCategory(Settings::Category::Paths); + + WriteStringSetting(std::string("romsPath"), UISettings::values.roms_path); + BeginArray(std::string("gamedirs")); + for (int i = 0; i < UISettings::values.game_dirs.size(); ++i) { + SetArrayIndex(i); + const auto& game_dir = UISettings::values.game_dirs[i]; + WriteStringSetting(std::string("path"), game_dir.path); + WriteBooleanSetting(std::string("deep_scan"), game_dir.deep_scan, + std::make_optional(false)); + WriteBooleanSetting(std::string("expanded"), game_dir.expanded, std::make_optional(true)); + } + EndArray(); + + WriteStringSetting(std::string("recentFiles"), + UISettings::values.recent_files.join(QStringLiteral(", ")).toStdString()); + + EndGroup(); +} + +void QtConfig::SaveShortcutValues() { + BeginGroup(Settings::TranslateCategory(Settings::Category::Shortcuts)); + + // Lengths of UISettings::values.shortcuts & default_hotkeys are same. + // However, their ordering must also be the same. + for (std::size_t i = 0; i < UISettings::default_hotkeys.size(); i++) { + const auto& [name, group, shortcut] = UISettings::values.shortcuts[i]; + const auto& default_hotkey = UISettings::default_hotkeys[i].shortcut; + + BeginGroup(group); + BeginGroup(name); + + WriteStringSetting(std::string("KeySeq"), shortcut.keyseq, + std::make_optional(default_hotkey.keyseq)); + WriteStringSetting(std::string("Controller_KeySeq"), shortcut.controller_keyseq, + std::make_optional(default_hotkey.controller_keyseq)); + WriteIntegerSetting(std::string("Context"), shortcut.context, + std::make_optional(default_hotkey.context)); + WriteBooleanSetting(std::string("Repeat"), shortcut.repeat, + std::make_optional(default_hotkey.repeat)); + + EndGroup(); // name + EndGroup(); // group + } + + EndGroup(); +} + +void QtConfig::SaveUIValues() { + BeginGroup(Settings::TranslateCategory(Settings::Category::Ui)); + + WriteCategory(Settings::Category::Ui); + WriteCategory(Settings::Category::UiGeneral); + + WriteStringSetting( + std::string("theme"), UISettings::values.theme, + std::make_optional(std::string( + UISettings::themes[static_cast(UISettings::default_theme)].second))); + + SaveUIGamelistValues(); + SaveUILayoutValues(); + SavePathValues(); + SaveScreenshotValues(); + SaveShortcutValues(); + SaveMultiplayerValues(); + + EndGroup(); +} + +void QtConfig::SaveUIGamelistValues() { + BeginGroup(Settings::TranslateCategory(Settings::Category::UiGameList)); + + WriteCategory(Settings::Category::UiGameList); + + BeginArray(std::string("favorites")); + for (int i = 0; i < UISettings::values.favorited_ids.size(); i++) { + SetArrayIndex(i); + WriteIntegerSetting(std::string("program_id"), UISettings::values.favorited_ids[i]); + } + EndArray(); // favorites + + EndGroup(); +} + +void QtConfig::SaveUILayoutValues() { + BeginGroup(Settings::TranslateCategory(Settings::Category::UiLayout)); + + WriteCategory(Settings::Category::UiLayout); + + EndGroup(); +} + +void QtConfig::SaveMultiplayerValues() { + BeginGroup(std::string("Multiplayer")); + + WriteCategory(Settings::Category::Multiplayer); + + // Write ban list + BeginArray(std::string("username_ban_list")); + for (std::size_t i = 0; i < UISettings::values.multiplayer_ban_list.first.size(); ++i) { + SetArrayIndex(static_cast(i)); + WriteStringSetting(std::string("username"), + UISettings::values.multiplayer_ban_list.first[i]); + } + EndArray(); // username_ban_list + + BeginArray(std::string("ip_ban_list")); + for (std::size_t i = 0; i < UISettings::values.multiplayer_ban_list.second.size(); ++i) { + SetArrayIndex(static_cast(i)); + WriteStringSetting(std::string("ip"), UISettings::values.multiplayer_ban_list.second[i]); + } + EndArray(); // ip_ban_list + + EndGroup(); +} + +std::vector& QtConfig::FindRelevantList(Settings::Category category) { + auto& map = Settings::values.linkage.by_category; + if (map.contains(category)) { + return Settings::values.linkage.by_category[category]; + } + return UISettings::values.linkage.by_category[category]; +} + +void QtConfig::ReadQtControlPlayerValues(std::size_t player_index) { + BeginGroup(Settings::TranslateCategory(Settings::Category::Controls)); + + ReadPlayerValues(player_index); + ReadQtPlayerValues(player_index); + + EndGroup(); +} + +void QtConfig::SaveQtControlPlayerValues(std::size_t player_index) { + BeginGroup(Settings::TranslateCategory(Settings::Category::Controls)); + + LOG_DEBUG(Config, "Saving players control configuration values"); + SavePlayerValues(player_index); + SaveQtPlayerValues(player_index); + + EndGroup(); + + WriteToIni(); +} diff --git a/src/sudachi/configuration/qt_config.h b/src/sudachi/configuration/qt_config.h new file mode 100644 index 0000000..2276f90 --- /dev/null +++ b/src/sudachi/configuration/qt_config.h @@ -0,0 +1,55 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include + +#include "frontend_common/config.h" + +class QtConfig final : public Config { +public: + explicit QtConfig(const std::string& config_name = "qt-config", + ConfigType config_type = ConfigType::GlobalConfig); + ~QtConfig() override; + + void ReloadAllValues() override; + void SaveAllValues() override; + + void ReadQtControlPlayerValues(std::size_t player_index); + void SaveQtControlPlayerValues(std::size_t player_index); + +protected: + void ReadQtValues(); + void ReadQtPlayerValues(std::size_t player_index); + void ReadQtControlValues(); + void ReadHidbusValues() override; + void ReadDebugControlValues() override; + void ReadPathValues() override; + void ReadShortcutValues() override; + void ReadUIValues() override; + void ReadUIGamelistValues() override; + void ReadUILayoutValues() override; + void ReadMultiplayerValues() override; + + void SaveQtValues(); + void SaveQtPlayerValues(std::size_t player_index); + void SaveQtControlValues(); + void SaveHidbusValues() override; + void SaveDebugControlValues() override; + void SavePathValues() override; + void SaveShortcutValues() override; + void SaveUIValues() override; + void SaveUIGamelistValues() override; + void SaveUILayoutValues() override; + void SaveMultiplayerValues() override; + + std::vector& FindRelevantList(Settings::Category category) override; + +public: + static const std::array default_buttons; + static const std::array default_motions; + static const std::array, Settings::NativeAnalog::NumAnalogs> default_analogs; + static const std::array default_stick_mod; + static const std::array default_ringcon_analogs; +}; diff --git a/src/sudachi/configuration/shared_translation.cpp b/src/sudachi/configuration/shared_translation.cpp new file mode 100644 index 0000000..684f0ed --- /dev/null +++ b/src/sudachi/configuration/shared_translation.cpp @@ -0,0 +1,537 @@ +// SPDX-FileCopyrightText: Copyright 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include "sudachi/configuration/shared_translation.h" + +#include +#include +#include +#include +#include +#include +#include "common/settings.h" +#include "common/settings_enums.h" +#include "common/settings_setting.h" +#include "common/time_zone.h" +#include "sudachi/uisettings.h" + +namespace ConfigurationShared { + +std::unique_ptr InitializeTranslations(QWidget* parent) { + std::unique_ptr translations = std::make_unique(); + const auto& tr = [parent](const char* text) -> QString { return parent->tr(text); }; + +#define INSERT(SETTINGS, ID, NAME, TOOLTIP) \ + translations->insert(std::pair{SETTINGS::values.ID.Id(), std::pair{(NAME), (TOOLTIP)}}) + + // A setting can be ignored by giving it a blank name + + // Applets + INSERT(Settings, cabinet_applet_mode, tr("Amiibo editor"), QStringLiteral()); + INSERT(Settings, controller_applet_mode, tr("Controller configuration"), QStringLiteral()); + INSERT(Settings, data_erase_applet_mode, tr("Data erase"), QStringLiteral()); + INSERT(Settings, error_applet_mode, tr("Error"), QStringLiteral()); + INSERT(Settings, net_connect_applet_mode, tr("Net connect"), QStringLiteral()); + INSERT(Settings, player_select_applet_mode, tr("Player select"), QStringLiteral()); + INSERT(Settings, swkbd_applet_mode, tr("Software keyboard"), QStringLiteral()); + INSERT(Settings, mii_edit_applet_mode, tr("Mii Edit"), QStringLiteral()); + INSERT(Settings, web_applet_mode, tr("Online web"), QStringLiteral()); + INSERT(Settings, shop_applet_mode, tr("Shop"), QStringLiteral()); + INSERT(Settings, photo_viewer_applet_mode, tr("Photo viewer"), QStringLiteral()); + INSERT(Settings, offline_web_applet_mode, tr("Offline web"), QStringLiteral()); + INSERT(Settings, login_share_applet_mode, tr("Login share"), QStringLiteral()); + INSERT(Settings, wifi_web_auth_applet_mode, tr("Wifi web auth"), QStringLiteral()); + INSERT(Settings, my_page_applet_mode, tr("My page"), QStringLiteral()); + + // Audio + INSERT(Settings, sink_id, tr("Output Engine:"), QStringLiteral()); + INSERT(Settings, audio_output_device_id, tr("Output Device:"), QStringLiteral()); + INSERT(Settings, audio_input_device_id, tr("Input Device:"), QStringLiteral()); + INSERT(Settings, audio_muted, tr("Mute audio"), QStringLiteral()); + INSERT(Settings, volume, tr("Volume:"), QStringLiteral()); + INSERT(Settings, dump_audio_commands, QStringLiteral(), QStringLiteral()); + INSERT(UISettings, mute_when_in_background, tr("Mute audio when in background"), + QStringLiteral()); + + // Core + INSERT( + Settings, use_multi_core, tr("Multicore CPU Emulation"), + tr("This option increases CPU emulation thread use from 1 to the Switch’s maximum of 4.\n" + "This is mainly a debug option and shouldn’t be disabled.")); + INSERT( + Settings, memory_layout_mode, tr("Memory Layout"), + tr("Increases the amount of emulated RAM from the stock 4GB of the retail Switch to the " + "developer kit's 8/6GB.\nIt’s doesn’t improve stability or performance and is intended " + "to let big texture mods fit in emulated RAM.\nEnabling it will increase memory " + "use. It is not recommended to enable unless a specific game with a texture mod needs " + "it.")); + INSERT(Settings, use_speed_limit, QStringLiteral(), QStringLiteral()); + INSERT(Settings, speed_limit, tr("Limit Speed Percent"), + tr("Controls the game's maximum rendering speed, but it’s up to each game if it runs " + "faster or not.\n200% for a 30 FPS game is 60 FPS, and for a " + "60 FPS game it will be 120 FPS.\nDisabling it means unlocking the framerate to the " + "maximum your PC can reach.")); + + // Cpu + INSERT(Settings, cpu_accuracy, tr("Accuracy:"), + tr("This setting controls the accuracy of the emulated CPU.\nDon't change this unless " + "you know what you are doing.")); + INSERT(Settings, cpu_backend, tr("Backend:"), QStringLiteral()); + + // Cpu Debug + + // Cpu Unsafe + INSERT( + Settings, cpuopt_unsafe_unfuse_fma, + tr("Unfuse FMA (improve performance on CPUs without FMA)"), + tr("This option improves speed by reducing accuracy of fused-multiply-add instructions on " + "CPUs without native FMA support.")); + INSERT( + Settings, cpuopt_unsafe_reduce_fp_error, tr("Faster FRSQRTE and FRECPE"), + tr("This option improves the speed of some approximate floating-point functions by using " + "less accurate native approximations.")); + INSERT(Settings, cpuopt_unsafe_ignore_standard_fpcr, + tr("Faster ASIMD instructions (32 bits only)"), + tr("This option improves the speed of 32 bits ASIMD floating-point functions by running " + "with incorrect rounding modes.")); + INSERT(Settings, cpuopt_unsafe_inaccurate_nan, tr("Inaccurate NaN handling"), + tr("This option improves speed by removing NaN checking.\nPlease note this also reduces " + "accuracy of certain floating-point instructions.")); + INSERT(Settings, cpuopt_unsafe_fastmem_check, tr("Disable address space checks"), + tr("This option improves speed by eliminating a safety check before every memory " + "read/write in guest.\nDisabling it may allow a game to read/write the emulator's " + "memory.")); + INSERT( + Settings, cpuopt_unsafe_ignore_global_monitor, tr("Ignore global monitor"), + tr("This option improves speed by relying only on the semantics of cmpxchg to ensure " + "safety of exclusive access instructions.\nPlease note this may result in deadlocks and " + "other race conditions.")); + + // Renderer + INSERT( + Settings, renderer_backend, tr("API:"), + tr("Switches between the available graphics APIs.\nVulkan is recommended in most cases.")); + INSERT(Settings, vulkan_device, tr("Device:"), + tr("This setting selects the GPU to use with the Vulkan backend.")); + INSERT(Settings, shader_backend, tr("Shader Backend:"), + tr("The shader backend to use for the OpenGL renderer.\nGLSL is the fastest in " + "performance and the best in rendering accuracy.\n" + "GLASM is a deprecated NVIDIA-only backend that offers much better shader building " + "performance at the cost of FPS and rendering accuracy.\n" + "SPIR-V compiles the fastest, but yields poor results on most GPU drivers.")); + INSERT(Settings, resolution_setup, tr("Resolution:"), + tr("Forces the game to render at a different resolution.\nHigher resolutions require " + "much more VRAM and bandwidth.\n" + "Options lower than 1X can cause rendering issues.")); + INSERT(Settings, scaling_filter, tr("Window Adapting Filter:"), QStringLiteral()); + INSERT(Settings, fsr_sharpening_slider, tr("FSR Sharpness:"), + tr("Determines how sharpened the image will look while using FSR’s dynamic contrast.")); + INSERT(Settings, anti_aliasing, tr("Anti-Aliasing Method:"), + tr("The anti-aliasing method to use.\nSMAA offers the best quality.\nFXAA has a " + "lower performance impact and can produce a better and more stable picture under " + "very low resolutions.")); + INSERT(Settings, fullscreen_mode, tr("Fullscreen Mode:"), + tr("The method used to render the window in fullscreen.\nBorderless offers the best " + "compatibility with the on-screen keyboard that some games request for " + "input.\nExclusive " + "fullscreen may offer better performance and better Freesync/Gsync support.")); + INSERT(Settings, aspect_ratio, tr("Aspect Ratio:"), + tr("Stretches the game to fit the specified aspect ratio.\nSwitch games only support " + "16:9, so custom game mods are required to get other ratios.\nAlso controls the " + "aspect ratio of captured screenshots.")); + INSERT(Settings, use_disk_shader_cache, tr("Use disk pipeline cache"), + tr("Allows saving shaders to storage for faster loading on following game " + "boots.\nDisabling " + "it is only intended for debugging.")); + INSERT( + Settings, use_asynchronous_gpu_emulation, tr("Use asynchronous GPU emulation"), + tr("Uses an extra CPU thread for rendering.\nThis option should always remain enabled.")); + INSERT(Settings, nvdec_emulation, tr("NVDEC emulation:"), + tr("Specifies how videos should be decoded.\nIt can either use the CPU or the GPU for " + "decoding, or perform no decoding at all (black screen on videos).\n" + "In most cases, GPU decoding provides the best performance.")); + INSERT(Settings, accelerate_astc, tr("ASTC Decoding Method:"), + tr("This option controls how ASTC textures should be decoded.\n" + "CPU: Use the CPU for decoding, slowest but safest method.\n" + "GPU: Use the GPU's compute shaders to decode ASTC textures, recommended for most " + "games and users.\n" + "CPU Asynchronously: Use the CPU to decode ASTC textures as they arrive. Completely " + "eliminates ASTC decoding\nstuttering at the cost of rendering issues while the " + "texture is being decoded.")); + INSERT( + Settings, astc_recompression, tr("ASTC Recompression Method:"), + tr("Almost all desktop and laptop dedicated GPUs lack support for ASTC textures, forcing " + "the emulator to decompress to an intermediate format any card supports, RGBA8.\n" + "This option recompresses RGBA8 to either the BC1 or BC3 format, saving VRAM but " + "negatively affecting image quality.")); + INSERT(Settings, vram_usage_mode, tr("VRAM Usage Mode:"), + tr("Selects whether the emulator should prefer to conserve memory or make maximum usage " + "of available video memory for performance. Has no effect on integrated graphics. " + "Aggressive mode may severely impact the performance of other applications such as " + "recording software.")); + INSERT( + Settings, vsync_mode, tr("VSync Mode:"), + tr("FIFO (VSync) does not drop frames or exhibit tearing but is limited by the screen " + "refresh rate.\nFIFO Relaxed is similar to FIFO but allows tearing as it recovers from " + "a slow down.\nMailbox can have lower latency than FIFO and does not tear but may drop " + "frames.\nImmediate (no synchronization) just presents whatever is available and can " + "exhibit tearing.")); + INSERT(Settings, bg_red, QStringLiteral(), QStringLiteral()); + INSERT(Settings, bg_green, QStringLiteral(), QStringLiteral()); + INSERT(Settings, bg_blue, QStringLiteral(), QStringLiteral()); + + // Renderer (Advanced Graphics) + INSERT(Settings, async_presentation, tr("Enable asynchronous presentation (Vulkan only)"), + tr("Slightly improves performance by moving presentation to a separate CPU thread.")); + INSERT( + Settings, renderer_force_max_clock, tr("Force maximum clocks (Vulkan only)"), + tr("Runs work in the background while waiting for graphics commands to keep the GPU from " + "lowering its clock speed.")); + INSERT(Settings, max_anisotropy, tr("Anisotropic Filtering:"), + tr("Controls the quality of texture rendering at oblique angles.\nIt’s a light setting " + "and safe to set at 16x on most GPUs.")); + INSERT(Settings, gpu_accuracy, tr("Accuracy Level:"), + tr("GPU emulation accuracy.\nMost games render fine with Normal, but High is still " + "required for some.\nParticles tend to only render correctly with High " + "accuracy.\nExtreme should only be used for debugging.\nThis option can " + "be changed while playing.\nSome games may require booting on high to render " + "properly.")); + INSERT(Settings, use_asynchronous_shaders, tr("Use asynchronous shader building (Hack)"), + tr("Enables asynchronous shader compilation, which may reduce shader stutter.\nThis " + "feature " + "is experimental.")); + INSERT(Settings, use_fast_gpu_time, tr("Use Fast GPU Time (Hack)"), + tr("Enables Fast GPU Time. This option will force most games to run at their highest " + "native resolution.")); + INSERT(Settings, use_vulkan_driver_pipeline_cache, tr("Use Vulkan pipeline cache"), + tr("Enables GPU vendor-specific pipeline cache.\nThis option can improve shader loading " + "time significantly in cases where the Vulkan driver does not store pipeline cache " + "files internally.")); + INSERT( + Settings, enable_compute_pipelines, tr("Enable Compute Pipelines (Intel Vulkan Only)"), + tr("Enable compute pipelines, required by some games.\nThis setting only exists for Intel " + "proprietary drivers, and may crash if enabled.\nCompute pipelines are always enabled " + "on all other drivers.")); + INSERT( + Settings, use_reactive_flushing, tr("Enable Reactive Flushing"), + tr("Uses reactive flushing instead of predictive flushing, allowing more accurate memory " + "syncing.")); + INSERT(Settings, use_video_framerate, tr("Sync to framerate of video playback"), + tr("Run the game at normal speed during video playback, even when the framerate is " + "unlocked.")); + INSERT(Settings, barrier_feedback_loops, tr("Barrier feedback loops"), + tr("Improves rendering of transparency effects in specific games.")); + + // Renderer (Debug) + + // System + INSERT(Settings, rng_seed, tr("RNG Seed"), + tr("Controls the seed of the random number generator.\nMainly used for speedrunning " + "purposes.")); + INSERT(Settings, rng_seed_enabled, QStringLiteral(), QStringLiteral()); + INSERT(Settings, device_name, tr("Device Name"), tr("The name of the emulated Switch.")); + INSERT(Settings, custom_rtc, tr("Custom RTC Date:"), + tr("This option allows to change the emulated clock of the Switch.\n" + "Can be used to manipulate time in games.")); + INSERT(Settings, custom_rtc_enabled, QStringLiteral(), QStringLiteral()); + INSERT(Settings, custom_rtc_offset, QStringLiteral(" "), + QStringLiteral("The number of seconds from the current unix time")); + INSERT(Settings, language_index, tr("Language:"), + tr("Note: this can be overridden when region setting is auto-select")); + INSERT(Settings, region_index, tr("Region:"), tr("The region of the emulated Switch.")); + INSERT(Settings, time_zone_index, tr("Time Zone:"), + tr("The time zone of the emulated Switch.")); + INSERT(Settings, sound_index, tr("Sound Output Mode:"), QStringLiteral()); + INSERT(Settings, use_docked_mode, tr("Console Mode:"), + tr("Selects if the console is emulated in Docked or Handheld mode.\nGames will change " + "their resolution, details and supported controllers and depending on this setting.\n" + "Setting to Handheld can help improve performance for low end systems.")); + INSERT(Settings, current_user, QStringLiteral(), QStringLiteral()); + + // Controls + + // Data Storage + + // Debugging + + // Debugging Graphics + + // Network + + // Web Service + + // Ui + + // Ui General + INSERT(UISettings, select_user_on_boot, tr("Prompt for user on game boot"), + tr("Ask to select a user profile on each boot, useful if multiple people use sudachi on " + "the same PC.")); + INSERT(UISettings, pause_when_in_background, tr("Pause emulation when in background"), + tr("This setting pauses sudachi when focusing other windows.")); + INSERT(UISettings, confirm_before_stopping, tr("Confirm before stopping emulation"), + tr("This setting overrides game prompts asking to confirm stopping the game.\nEnabling " + "it bypasses such prompts and directly exits the emulation.")); + INSERT(UISettings, hide_mouse, tr("Hide mouse on inactivity"), + tr("This setting hides the mouse after 2.5s of inactivity.")); + INSERT(UISettings, controller_applet_disabled, tr("Disable controller applet"), + tr("Forcibly disables the use of the controller applet by guests.\nWhen a guest " + "attempts to open the controller applet, it is immediately closed.")); + + // Linux + INSERT(Settings, enable_gamemode, tr("Enable Gamemode"), QStringLiteral()); + + // Ui Debugging + + // Ui Multiplayer + + // Ui Games list + +#undef INSERT + + return translations; +} + +std::unique_ptr ComboboxEnumeration(QWidget* parent) { + std::unique_ptr translations = + std::make_unique(); + const auto& tr = [&](const char* text, const char* context = "") { + return parent->tr(text, context); + }; + +#define PAIR(ENUM, VALUE, TRANSLATION) {static_cast(Settings::ENUM::VALUE), (TRANSLATION)} + + // Intentionally skipping VSyncMode to let the UI fill that one out + translations->insert({Settings::EnumMetadata::Index(), + { + PAIR(AppletMode, HLE, tr("Custom frontend")), + PAIR(AppletMode, LLE, tr("Real applet")), + }}); + + translations->insert({Settings::EnumMetadata::Index(), + { + PAIR(AstcDecodeMode, Cpu, tr("CPU")), + PAIR(AstcDecodeMode, Gpu, tr("GPU")), + PAIR(AstcDecodeMode, CpuAsynchronous, tr("CPU Asynchronous")), + }}); + translations->insert( + {Settings::EnumMetadata::Index(), + { + PAIR(AstcRecompression, Uncompressed, tr("Uncompressed (Best quality)")), + PAIR(AstcRecompression, Bc1, tr("BC1 (Low quality)")), + PAIR(AstcRecompression, Bc3, tr("BC3 (Medium quality)")), + }}); + translations->insert({Settings::EnumMetadata::Index(), + { + PAIR(VramUsageMode, Conservative, tr("Conservative")), + PAIR(VramUsageMode, Aggressive, tr("Aggressive")), + }}); + translations->insert({Settings::EnumMetadata::Index(), + { +#ifdef HAS_OPENGL + PAIR(RendererBackend, OpenGL, tr("OpenGL")), +#endif + PAIR(RendererBackend, Vulkan, tr("Vulkan")), + PAIR(RendererBackend, Null, tr("Null")), + }}); + translations->insert( + {Settings::EnumMetadata::Index(), + { + PAIR(ShaderBackend, Glsl, tr("GLSL")), + PAIR(ShaderBackend, Glasm, tr("GLASM (Assembly Shaders, NVIDIA Only)")), + PAIR(ShaderBackend, SpirV, tr("SPIR-V (Experimental, AMD/Mesa Only)")), + }}); + translations->insert({Settings::EnumMetadata::Index(), + { + PAIR(GpuAccuracy, Normal, tr("Normal")), + PAIR(GpuAccuracy, High, tr("High")), + PAIR(GpuAccuracy, Extreme, tr("Extreme")), + }}); + translations->insert( + {Settings::EnumMetadata::Index(), + { + PAIR(CpuAccuracy, Auto, tr("Auto")), + PAIR(CpuAccuracy, Accurate, tr("Accurate")), + PAIR(CpuAccuracy, Unsafe, tr("Unsafe")), + PAIR(CpuAccuracy, Paranoid, tr("Paranoid (disables most optimizations)")), + }}); + translations->insert({Settings::EnumMetadata::Index(), + { + PAIR(CpuBackend, Dynarmic, tr("Dynarmic")), + PAIR(CpuBackend, Nce, tr("NCE")), + }}); + translations->insert({Settings::EnumMetadata::Index(), + { + PAIR(FullscreenMode, Borderless, tr("Borderless Windowed")), + PAIR(FullscreenMode, Exclusive, tr("Exclusive Fullscreen")), + }}); + translations->insert({Settings::EnumMetadata::Index(), + { + PAIR(NvdecEmulation, Off, tr("No Video Output")), + PAIR(NvdecEmulation, Cpu, tr("CPU Video Decoding")), + PAIR(NvdecEmulation, Gpu, tr("GPU Video Decoding (Default)")), + }}); + translations->insert( + {Settings::EnumMetadata::Index(), + { + PAIR(ResolutionSetup, Res1_2X, tr("0.5X (360p/540p) [EXPERIMENTAL]")), + PAIR(ResolutionSetup, Res3_4X, tr("0.75X (540p/810p) [EXPERIMENTAL]")), + PAIR(ResolutionSetup, Res1X, tr("1X (720p/1080p)")), + PAIR(ResolutionSetup, Res3_2X, tr("1.5X (1080p/1620p) [EXPERIMENTAL]")), + PAIR(ResolutionSetup, Res2X, tr("2X (1440p/2160p)")), + PAIR(ResolutionSetup, Res3X, tr("3X (2160p/3240p)")), + PAIR(ResolutionSetup, Res4X, tr("4X (2880p/4320p)")), + PAIR(ResolutionSetup, Res5X, tr("5X (3600p/5400p)")), + PAIR(ResolutionSetup, Res6X, tr("6X (4320p/6480p)")), + PAIR(ResolutionSetup, Res7X, tr("7X (5040p/7560p)")), + PAIR(ResolutionSetup, Res8X, tr("8X (5760p/8640p)")), + }}); + translations->insert({Settings::EnumMetadata::Index(), + { + PAIR(ScalingFilter, NearestNeighbor, tr("Nearest Neighbor")), + PAIR(ScalingFilter, Bilinear, tr("Bilinear")), + PAIR(ScalingFilter, Bicubic, tr("Bicubic")), + PAIR(ScalingFilter, Gaussian, tr("Gaussian")), + PAIR(ScalingFilter, ScaleForce, tr("ScaleForce")), + PAIR(ScalingFilter, Fsr, tr("AMD FidelityFX™️ Super Resolution")), + }}); + translations->insert({Settings::EnumMetadata::Index(), + { + PAIR(AntiAliasing, None, tr("None")), + PAIR(AntiAliasing, Fxaa, tr("FXAA")), + PAIR(AntiAliasing, Smaa, tr("SMAA")), + }}); + translations->insert({Settings::EnumMetadata::Index(), + { + PAIR(AspectRatio, R16_9, tr("Default (16:9)")), + PAIR(AspectRatio, R4_3, tr("Force 4:3")), + PAIR(AspectRatio, R21_9, tr("Force 21:9")), + PAIR(AspectRatio, R16_10, tr("Force 16:10")), + PAIR(AspectRatio, Stretch, tr("Stretch to Window")), + }}); + translations->insert({Settings::EnumMetadata::Index(), + { + PAIR(AnisotropyMode, Automatic, tr("Automatic")), + PAIR(AnisotropyMode, Default, tr("Default")), + PAIR(AnisotropyMode, X2, tr("2x")), + PAIR(AnisotropyMode, X4, tr("4x")), + PAIR(AnisotropyMode, X8, tr("8x")), + PAIR(AnisotropyMode, X16, tr("16x")), + }}); + translations->insert( + {Settings::EnumMetadata::Index(), + { + PAIR(Language, Japanese, tr("Japanese (日本語)")), + PAIR(Language, EnglishAmerican, tr("American English")), + PAIR(Language, French, tr("French (français)")), + PAIR(Language, German, tr("German (Deutsch)")), + PAIR(Language, Italian, tr("Italian (italiano)")), + PAIR(Language, Spanish, tr("Spanish (español)")), + PAIR(Language, Chinese, tr("Chinese")), + PAIR(Language, Korean, tr("Korean (한국어)")), + PAIR(Language, Dutch, tr("Dutch (Nederlands)")), + PAIR(Language, Portuguese, tr("Portuguese (português)")), + PAIR(Language, Russian, tr("Russian (Русский)")), + PAIR(Language, Taiwanese, tr("Taiwanese")), + PAIR(Language, EnglishBritish, tr("British English")), + PAIR(Language, FrenchCanadian, tr("Canadian French")), + PAIR(Language, SpanishLatin, tr("Latin American Spanish")), + PAIR(Language, ChineseSimplified, tr("Simplified Chinese")), + PAIR(Language, ChineseTraditional, tr("Traditional Chinese (正體中文)")), + PAIR(Language, PortugueseBrazilian, tr("Brazilian Portuguese (português do Brasil)")), + }}); + translations->insert({Settings::EnumMetadata::Index(), + { + PAIR(Region, Japan, tr("Japan")), + PAIR(Region, Usa, tr("USA")), + PAIR(Region, Europe, tr("Europe")), + PAIR(Region, Australia, tr("Australia")), + PAIR(Region, China, tr("China")), + PAIR(Region, Korea, tr("Korea")), + PAIR(Region, Taiwan, tr("Taiwan")), + }}); + translations->insert( + {Settings::EnumMetadata::Index(), + { + {static_cast(Settings::TimeZone::Auto), + tr("Auto (%1)", "Auto select time zone") + .arg(QString::fromStdString( + Settings::GetTimeZoneString(Settings::TimeZone::Auto)))}, + {static_cast(Settings::TimeZone::Default), + tr("Default (%1)", "Default time zone") + .arg(QString::fromStdString(Common::TimeZone::GetDefaultTimeZone()))}, + PAIR(TimeZone, Cet, tr("CET")), + PAIR(TimeZone, Cst6Cdt, tr("CST6CDT")), + PAIR(TimeZone, Cuba, tr("Cuba")), + PAIR(TimeZone, Eet, tr("EET")), + PAIR(TimeZone, Egypt, tr("Egypt")), + PAIR(TimeZone, Eire, tr("Eire")), + PAIR(TimeZone, Est, tr("EST")), + PAIR(TimeZone, Est5Edt, tr("EST5EDT")), + PAIR(TimeZone, Gb, tr("GB")), + PAIR(TimeZone, GbEire, tr("GB-Eire")), + PAIR(TimeZone, Gmt, tr("GMT")), + PAIR(TimeZone, GmtPlusZero, tr("GMT+0")), + PAIR(TimeZone, GmtMinusZero, tr("GMT-0")), + PAIR(TimeZone, GmtZero, tr("GMT0")), + PAIR(TimeZone, Greenwich, tr("Greenwich")), + PAIR(TimeZone, Hongkong, tr("Hongkong")), + PAIR(TimeZone, Hst, tr("HST")), + PAIR(TimeZone, Iceland, tr("Iceland")), + PAIR(TimeZone, Iran, tr("Iran")), + PAIR(TimeZone, Israel, tr("Israel")), + PAIR(TimeZone, Jamaica, tr("Jamaica")), + PAIR(TimeZone, Japan, tr("Japan")), + PAIR(TimeZone, Kwajalein, tr("Kwajalein")), + PAIR(TimeZone, Libya, tr("Libya")), + PAIR(TimeZone, Met, tr("MET")), + PAIR(TimeZone, Mst, tr("MST")), + PAIR(TimeZone, Mst7Mdt, tr("MST7MDT")), + PAIR(TimeZone, Navajo, tr("Navajo")), + PAIR(TimeZone, Nz, tr("NZ")), + PAIR(TimeZone, NzChat, tr("NZ-CHAT")), + PAIR(TimeZone, Poland, tr("Poland")), + PAIR(TimeZone, Portugal, tr("Portugal")), + PAIR(TimeZone, Prc, tr("PRC")), + PAIR(TimeZone, Pst8Pdt, tr("PST8PDT")), + PAIR(TimeZone, Roc, tr("ROC")), + PAIR(TimeZone, Rok, tr("ROK")), + PAIR(TimeZone, Singapore, tr("Singapore")), + PAIR(TimeZone, Turkey, tr("Turkey")), + PAIR(TimeZone, Uct, tr("UCT")), + PAIR(TimeZone, Universal, tr("Universal")), + PAIR(TimeZone, Utc, tr("UTC")), + PAIR(TimeZone, WSu, tr("W-SU")), + PAIR(TimeZone, Wet, tr("WET")), + PAIR(TimeZone, Zulu, tr("Zulu")), + }}); + translations->insert({Settings::EnumMetadata::Index(), + { + PAIR(AudioMode, Mono, tr("Mono")), + PAIR(AudioMode, Stereo, tr("Stereo")), + PAIR(AudioMode, Surround, tr("Surround")), + }}); + translations->insert({Settings::EnumMetadata::Index(), + { + PAIR(MemoryLayout, Memory_4Gb, tr("4GB DRAM (Default)")), + PAIR(MemoryLayout, Memory_6Gb, tr("6GB DRAM (Unsafe)")), + PAIR(MemoryLayout, Memory_8Gb, tr("8GB DRAM (Unsafe)")), + }}); + translations->insert({Settings::EnumMetadata::Index(), + { + PAIR(ConsoleMode, Docked, tr("Docked")), + PAIR(ConsoleMode, Handheld, tr("Handheld")), + }}); + translations->insert( + {Settings::EnumMetadata::Index(), + { + PAIR(ConfirmStop, Ask_Always, tr("Always ask (Default)")), + PAIR(ConfirmStop, Ask_Based_On_Game, tr("Only if game specifies not to stop")), + PAIR(ConfirmStop, Ask_Never, tr("Never ask")), + }}); + +#undef PAIR +#undef CTX_PAIR + + return translations; +} +} // namespace ConfigurationShared diff --git a/src/sudachi/configuration/shared_translation.h b/src/sudachi/configuration/shared_translation.h new file mode 100644 index 0000000..65c4c72 --- /dev/null +++ b/src/sudachi/configuration/shared_translation.h @@ -0,0 +1,68 @@ +// SPDX-FileCopyrightText: Copyright 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include +#include +#include +#include +#include +#include "common/common_types.h" +#include "common/settings.h" + +class QWidget; + +namespace ConfigurationShared { +using TranslationMap = std::map>; +using ComboboxTranslations = std::vector>; +using ComboboxTranslationMap = std::map; + +std::unique_ptr InitializeTranslations(QWidget* parent); + +std::unique_ptr ComboboxEnumeration(QWidget* parent); + +static const std::map anti_aliasing_texts_map = { + {Settings::AntiAliasing::None, QStringLiteral(QT_TRANSLATE_NOOP("GMainWindow", "None"))}, + {Settings::AntiAliasing::Fxaa, QStringLiteral(QT_TRANSLATE_NOOP("GMainWindow", "FXAA"))}, + {Settings::AntiAliasing::Smaa, QStringLiteral(QT_TRANSLATE_NOOP("GMainWindow", "SMAA"))}, +}; + +static const std::map scaling_filter_texts_map = { + {Settings::ScalingFilter::NearestNeighbor, + QStringLiteral(QT_TRANSLATE_NOOP("GMainWindow", "Nearest"))}, + {Settings::ScalingFilter::Bilinear, + QStringLiteral(QT_TRANSLATE_NOOP("GMainWindow", "Bilinear"))}, + {Settings::ScalingFilter::Bicubic, QStringLiteral(QT_TRANSLATE_NOOP("GMainWindow", "Bicubic"))}, + {Settings::ScalingFilter::Gaussian, + QStringLiteral(QT_TRANSLATE_NOOP("GMainWindow", "Gaussian"))}, + {Settings::ScalingFilter::ScaleForce, + QStringLiteral(QT_TRANSLATE_NOOP("GMainWindow", "ScaleForce"))}, + {Settings::ScalingFilter::Fsr, QStringLiteral(QT_TRANSLATE_NOOP("GMainWindow", "FSR"))}, +}; + +static const std::map use_docked_mode_texts_map = { + {Settings::ConsoleMode::Docked, QStringLiteral(QT_TRANSLATE_NOOP("GMainWindow", "Docked"))}, + {Settings::ConsoleMode::Handheld, QStringLiteral(QT_TRANSLATE_NOOP("GMainWindow", "Handheld"))}, +}; + +static const std::map gpu_accuracy_texts_map = { + {Settings::GpuAccuracy::Normal, QStringLiteral(QT_TRANSLATE_NOOP("GMainWindow", "Normal"))}, + {Settings::GpuAccuracy::High, QStringLiteral(QT_TRANSLATE_NOOP("GMainWindow", "High"))}, + {Settings::GpuAccuracy::Extreme, QStringLiteral(QT_TRANSLATE_NOOP("GMainWindow", "Extreme"))}, +}; + +static const std::map renderer_backend_texts_map = { + {Settings::RendererBackend::Vulkan, QStringLiteral(QT_TRANSLATE_NOOP("GMainWindow", "Vulkan"))}, + {Settings::RendererBackend::OpenGL, QStringLiteral(QT_TRANSLATE_NOOP("GMainWindow", "OpenGL"))}, + {Settings::RendererBackend::Null, QStringLiteral(QT_TRANSLATE_NOOP("GMainWindow", "Null"))}, +}; + +static const std::map shader_backend_texts_map = { + {Settings::ShaderBackend::Glsl, QStringLiteral(QT_TRANSLATE_NOOP("GMainWindow", "GLSL"))}, + {Settings::ShaderBackend::Glasm, QStringLiteral(QT_TRANSLATE_NOOP("GMainWindow", "GLASM"))}, + {Settings::ShaderBackend::SpirV, QStringLiteral(QT_TRANSLATE_NOOP("GMainWindow", "SPIRV"))}, +}; + +} // namespace ConfigurationShared diff --git a/src/sudachi/configuration/shared_widget.cpp b/src/sudachi/configuration/shared_widget.cpp new file mode 100644 index 0000000..6fd52f3 --- /dev/null +++ b/src/sudachi/configuration/shared_widget.cpp @@ -0,0 +1,802 @@ +// SPDX-FileCopyrightText: Copyright 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include "sudachi/configuration/shared_widget.h" + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "common/assert.h" +#include "common/common_types.h" +#include "common/logging/log.h" +#include "common/settings.h" +#include "common/settings_common.h" +#include "sudachi/configuration/shared_translation.h" + +namespace ConfigurationShared { + +static int restore_button_count = 0; + +static std::string RelevantDefault(const Settings::BasicSetting& setting) { + return Settings::IsConfiguringGlobal() ? setting.DefaultToString() : setting.ToStringGlobal(); +} + +static QString DefaultSuffix(QWidget* parent, Settings::BasicSetting& setting) { + const auto tr = [parent](const char* text, const char* context) { + return parent->tr(text, context); + }; + + if ((setting.Specialization() & Settings::SpecializationAttributeMask) == + Settings::Specialization::Percentage) { + std::string context{fmt::format("{} percentage (e.g. 50%)", setting.GetLabel())}; + return tr("%", context.c_str()); + } + + return default_suffix; +} + +QPushButton* Widget::CreateRestoreGlobalButton(bool using_global, QWidget* parent) { + restore_button_count++; + + QStyle* style = parent->style(); + QIcon* icon = new QIcon(style->standardIcon(QStyle::SP_LineEditClearButton)); + QPushButton* restore_button = new QPushButton(*icon, QStringLiteral(), parent); + restore_button->setObjectName(QStringLiteral("RestoreButton%1").arg(restore_button_count)); + restore_button->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); + + // Workaround for dark theme causing min-width to be much larger than 0 + restore_button->setStyleSheet( + QStringLiteral("QAbstractButton#%1 { min-width: 0px }").arg(restore_button->objectName())); + + QSizePolicy sp_retain = restore_button->sizePolicy(); + sp_retain.setRetainSizeWhenHidden(true); + restore_button->setSizePolicy(sp_retain); + + restore_button->setEnabled(!using_global); + restore_button->setVisible(!using_global); + + return restore_button; +} + +QLabel* Widget::CreateLabel(const QString& text) { + QLabel* qt_label = new QLabel(text, this->parent); + qt_label->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); + return qt_label; +} + +QWidget* Widget::CreateCheckBox(Settings::BasicSetting* bool_setting, const QString& label, + std::function& serializer, + std::function& restore_func, + const std::function& touch) { + checkbox = new QCheckBox(label, this); + checkbox->setCheckState(bool_setting->ToString() == "true" ? Qt::CheckState::Checked + : Qt::CheckState::Unchecked); + checkbox->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); + + if (!bool_setting->Save() && !Settings::IsConfiguringGlobal() && runtime_lock) { + checkbox->setEnabled(false); + } + + serializer = [this]() { + return checkbox->checkState() == Qt::CheckState::Checked ? "true" : "false"; + }; + + restore_func = [this, bool_setting]() { + checkbox->setCheckState(RelevantDefault(*bool_setting) == "true" ? Qt::Checked + : Qt::Unchecked); + }; + + if (!Settings::IsConfiguringGlobal()) { + QObject::connect(checkbox, &QCheckBox::clicked, [touch]() { touch(); }); + } + + return checkbox; +} + +QWidget* Widget::CreateCombobox(std::function& serializer, + std::function& restore_func, + const std::function& touch) { + const auto type = setting.EnumIndex(); + + combobox = new QComboBox(this); + combobox->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); + + const ComboboxTranslations* enumeration{nullptr}; + if (combobox_enumerations.contains(type)) { + enumeration = &combobox_enumerations.at(type); + for (const auto& [id, name] : *enumeration) { + combobox->addItem(name); + } + } else { + return combobox; + } + + const auto find_index = [=](u32 value) -> int { + for (u32 i = 0; i < enumeration->size(); i++) { + if (enumeration->at(i).first == value) { + return i; + } + } + return -1; + }; + + const u32 setting_value = std::strtoul(setting.ToString().c_str(), nullptr, 0); + combobox->setCurrentIndex(find_index(setting_value)); + + serializer = [this, enumeration]() { + int current = combobox->currentIndex(); + return std::to_string(enumeration->at(current).first); + }; + + restore_func = [this, find_index]() { + const u32 global_value = std::strtoul(RelevantDefault(setting).c_str(), nullptr, 0); + combobox->setCurrentIndex(find_index(global_value)); + }; + + if (!Settings::IsConfiguringGlobal()) { + QObject::connect(combobox, QOverload::of(&QComboBox::activated), + [touch]() { touch(); }); + } + + return combobox; +} + +QWidget* Widget::CreateRadioGroup(std::function& serializer, + std::function& restore_func, + const std::function& touch) { + const auto type = setting.EnumIndex(); + + QWidget* group = new QWidget(this); + QHBoxLayout* layout = new QHBoxLayout(group); + layout->setContentsMargins(0, 0, 0, 0); + group->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); + + const ComboboxTranslations* enumeration{nullptr}; + if (combobox_enumerations.contains(type)) { + enumeration = &combobox_enumerations.at(type); + for (const auto& [id, name] : *enumeration) { + QRadioButton* radio_button = new QRadioButton(name, group); + layout->addWidget(radio_button); + radio_buttons.push_back({id, radio_button}); + } + } else { + return group; + } + + const auto get_selected = [this]() -> int { + for (const auto& [id, button] : radio_buttons) { + if (button->isChecked()) { + return id; + } + } + return -1; + }; + + const auto set_index = [this](u32 value) { + for (const auto& [id, button] : radio_buttons) { + button->setChecked(id == value); + } + }; + + const u32 setting_value = std::strtoul(setting.ToString().c_str(), nullptr, 0); + set_index(setting_value); + + serializer = [get_selected]() { + int current = get_selected(); + return std::to_string(current); + }; + + restore_func = [this, set_index]() { + const u32 global_value = std::strtoul(RelevantDefault(setting).c_str(), nullptr, 0); + set_index(global_value); + }; + + if (!Settings::IsConfiguringGlobal()) { + for (const auto& [id, button] : radio_buttons) { + QObject::connect(button, &QAbstractButton::clicked, [touch]() { touch(); }); + } + } + + return group; +} + +QWidget* Widget::CreateLineEdit(std::function& serializer, + std::function& restore_func, + const std::function& touch, bool managed) { + const QString text = QString::fromStdString(setting.ToString()); + line_edit = new QLineEdit(this); + line_edit->setText(text); + + serializer = [this]() { return line_edit->text().toStdString(); }; + + if (!managed) { + return line_edit; + } + + restore_func = [this]() { + line_edit->setText(QString::fromStdString(RelevantDefault(setting))); + }; + + if (!Settings::IsConfiguringGlobal()) { + QObject::connect(line_edit, &QLineEdit::textChanged, [touch]() { touch(); }); + } + + return line_edit; +} + +static void CreateIntSlider(Settings::BasicSetting& setting, bool reversed, float multiplier, + QLabel* feedback, const QString& use_format, QSlider* slider, + std::function& serializer, + std::function& restore_func) { + const int max_val = std::strtol(setting.MaxVal().c_str(), nullptr, 0); + + const auto update_feedback = [=](int value) { + int present = (reversed ? max_val - value : value) * multiplier + 0.5f; + feedback->setText(use_format.arg(QVariant::fromValue(present).value())); + }; + + QObject::connect(slider, &QAbstractSlider::valueChanged, update_feedback); + update_feedback(std::strtol(setting.ToString().c_str(), nullptr, 0)); + + slider->setMinimum(std::strtol(setting.MinVal().c_str(), nullptr, 0)); + slider->setMaximum(max_val); + slider->setValue(std::strtol(setting.ToString().c_str(), nullptr, 0)); + + serializer = [slider]() { return std::to_string(slider->value()); }; + restore_func = [slider, &setting]() { + slider->setValue(std::strtol(RelevantDefault(setting).c_str(), nullptr, 0)); + }; +} + +static void CreateFloatSlider(Settings::BasicSetting& setting, bool reversed, float multiplier, + QLabel* feedback, const QString& use_format, QSlider* slider, + std::function& serializer, + std::function& restore_func) { + const float max_val = std::strtof(setting.MaxVal().c_str(), nullptr); + const float min_val = std::strtof(setting.MinVal().c_str(), nullptr); + const float use_multiplier = + multiplier == default_multiplier ? default_float_multiplier : multiplier; + + const auto update_feedback = [=](float value) { + int present = (reversed ? max_val - value : value) + 0.5f; + feedback->setText(use_format.arg(QVariant::fromValue(present).value())); + }; + + QObject::connect(slider, &QAbstractSlider::valueChanged, update_feedback); + update_feedback(std::strtof(setting.ToString().c_str(), nullptr)); + + slider->setMinimum(min_val * use_multiplier); + slider->setMaximum(max_val * use_multiplier); + slider->setValue(std::strtof(setting.ToString().c_str(), nullptr) * use_multiplier); + + serializer = [slider, use_multiplier]() { + return std::to_string(slider->value() / use_multiplier); + }; + restore_func = [slider, &setting, use_multiplier]() { + slider->setValue(std::strtof(RelevantDefault(setting).c_str(), nullptr) * use_multiplier); + }; +} + +QWidget* Widget::CreateSlider(bool reversed, float multiplier, const QString& given_suffix, + std::function& serializer, + std::function& restore_func, + const std::function& touch) { + if (!setting.Ranged()) { + LOG_ERROR(Frontend, "\"{}\" is not a ranged setting, but a slider was requested.", + setting.GetLabel()); + return nullptr; + } + + QWidget* container = new QWidget(this); + QHBoxLayout* layout = new QHBoxLayout(container); + + slider = new QSlider(Qt::Horizontal, this); + QLabel* feedback = new QLabel(this); + + layout->addWidget(slider); + layout->addWidget(feedback); + + container->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); + + layout->setContentsMargins(0, 0, 0, 0); + + QString suffix = given_suffix == default_suffix ? DefaultSuffix(this, setting) : given_suffix; + + const QString use_format = QStringLiteral("%1").append(suffix); + + if (setting.IsIntegral()) { + CreateIntSlider(setting, reversed, multiplier, feedback, use_format, slider, serializer, + restore_func); + } else { + CreateFloatSlider(setting, reversed, multiplier, feedback, use_format, slider, serializer, + restore_func); + } + + slider->setInvertedAppearance(reversed); + + if (!Settings::IsConfiguringGlobal()) { + QObject::connect(slider, &QAbstractSlider::actionTriggered, [touch]() { touch(); }); + } + + return container; +} + +QWidget* Widget::CreateSpinBox(const QString& given_suffix, + std::function& serializer, + std::function& restore_func, + const std::function& touch) { + const auto min_val = std::strtol(setting.MinVal().c_str(), nullptr, 0); + const auto max_val = std::strtol(setting.MaxVal().c_str(), nullptr, 0); + const auto default_val = std::strtol(setting.ToString().c_str(), nullptr, 0); + + QString suffix = given_suffix == default_suffix ? DefaultSuffix(this, setting) : given_suffix; + + spinbox = new QSpinBox(this); + spinbox->setRange(min_val, max_val); + spinbox->setValue(default_val); + spinbox->setSuffix(suffix); + spinbox->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); + + serializer = [this]() { return std::to_string(spinbox->value()); }; + + restore_func = [this]() { + auto value{std::strtol(RelevantDefault(setting).c_str(), nullptr, 0)}; + spinbox->setValue(value); + }; + + if (!Settings::IsConfiguringGlobal()) { + QObject::connect(spinbox, QOverload::of(&QSpinBox::valueChanged), [this, touch]() { + if (spinbox->value() != std::strtol(setting.ToStringGlobal().c_str(), nullptr, 0)) { + touch(); + } + }); + } + + return spinbox; +} + +QWidget* Widget::CreateDoubleSpinBox(const QString& given_suffix, + std::function& serializer, + std::function& restore_func, + const std::function& touch) { + const auto min_val = std::strtod(setting.MinVal().c_str(), nullptr); + const auto max_val = std::strtod(setting.MaxVal().c_str(), nullptr); + const auto default_val = std::strtod(setting.ToString().c_str(), nullptr); + + QString suffix = given_suffix == default_suffix ? DefaultSuffix(this, setting) : given_suffix; + + double_spinbox = new QDoubleSpinBox(this); + double_spinbox->setRange(min_val, max_val); + double_spinbox->setValue(default_val); + double_spinbox->setSuffix(suffix); + double_spinbox->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); + + serializer = [this]() { return fmt::format("{:f}", double_spinbox->value()); }; + + restore_func = [this]() { + auto value{std::strtod(RelevantDefault(setting).c_str(), nullptr)}; + double_spinbox->setValue(value); + }; + + if (!Settings::IsConfiguringGlobal()) { + QObject::connect(double_spinbox, QOverload::of(&QDoubleSpinBox::valueChanged), + [this, touch]() { + if (double_spinbox->value() != + std::strtod(setting.ToStringGlobal().c_str(), nullptr)) { + touch(); + } + }); + } + + return double_spinbox; +} + +QWidget* Widget::CreateHexEdit(std::function& serializer, + std::function& restore_func, + const std::function& touch) { + auto* data_component = CreateLineEdit(serializer, restore_func, touch, false); + if (data_component == nullptr) { + return nullptr; + } + + auto to_hex = [=](const std::string& input) { + return QString::fromStdString( + fmt::format("{:08x}", std::strtoul(input.c_str(), nullptr, 0))); + }; + + QRegularExpressionValidator* regex = new QRegularExpressionValidator( + QRegularExpression{QStringLiteral("^[0-9a-fA-F]{0,8}$")}, line_edit); + + const QString default_val = to_hex(setting.ToString()); + + line_edit->setText(default_val); + line_edit->setMaxLength(8); + line_edit->setValidator(regex); + + auto hex_to_dec = [this]() -> std::string { + return std::to_string(std::strtoul(line_edit->text().toStdString().c_str(), nullptr, 16)); + }; + + serializer = [hex_to_dec]() { return hex_to_dec(); }; + + restore_func = [this, to_hex]() { line_edit->setText(to_hex(RelevantDefault(setting))); }; + + if (!Settings::IsConfiguringGlobal()) { + + QObject::connect(line_edit, &QLineEdit::textChanged, [touch]() { touch(); }); + } + + return line_edit; +} + +QWidget* Widget::CreateDateTimeEdit(bool disabled, bool restrict, + std::function& serializer, + std::function& restore_func, + const std::function& touch) { + const long long current_time = QDateTime::currentSecsSinceEpoch(); + const s64 the_time = + disabled ? current_time : std::strtoll(setting.ToString().c_str(), nullptr, 0); + const auto default_val = QDateTime::fromSecsSinceEpoch(the_time); + + date_time_edit = new QDateTimeEdit(this); + date_time_edit->setDateTime(default_val); + date_time_edit->setMinimumDateTime(QDateTime::fromSecsSinceEpoch(0)); + date_time_edit->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); + + serializer = [this]() { return std::to_string(date_time_edit->dateTime().toSecsSinceEpoch()); }; + + auto get_clear_val = [this, restrict, current_time]() { + return QDateTime::fromSecsSinceEpoch([this, restrict, current_time]() { + if (restrict && checkbox->checkState() == Qt::Checked) { + return std::strtoll(RelevantDefault(setting).c_str(), nullptr, 0); + } + return current_time; + }()); + }; + + restore_func = [this, get_clear_val]() { date_time_edit->setDateTime(get_clear_val()); }; + + if (!Settings::IsConfiguringGlobal()) { + QObject::connect(date_time_edit, &QDateTimeEdit::editingFinished, + [this, get_clear_val, touch]() { + if (date_time_edit->dateTime() != get_clear_val()) { + touch(); + } + }); + } + + return date_time_edit; +} + +void Widget::SetupComponent(const QString& label, std::function& load_func, bool managed, + RequestType request, float multiplier, + Settings::BasicSetting* other_setting, const QString& suffix) { + created = true; + const auto type = setting.TypeId(); + + QLayout* layout = new QHBoxLayout(this); + layout->setContentsMargins(0, 0, 0, 0); + + if (other_setting == nullptr) { + other_setting = setting.PairedSetting(); + } + + const bool require_checkbox = + other_setting != nullptr && other_setting->TypeId() == typeid(bool); + + if (other_setting != nullptr && other_setting->TypeId() != typeid(bool)) { + LOG_WARNING( + Frontend, + "Extra setting \"{}\" specified but is not bool, refusing to create checkbox for it.", + other_setting->GetLabel()); + } + + std::function checkbox_serializer = []() -> std::string { return {}; }; + std::function checkbox_restore_func = []() {}; + + std::function touch = []() {}; + std::function serializer = []() -> std::string { return {}; }; + std::function restore_func = []() {}; + + QWidget* data_component{nullptr}; + + request = [&]() { + if (request != RequestType::Default) { + return request; + } + switch (setting.Specialization() & Settings::SpecializationTypeMask) { + case Settings::Specialization::Default: + return RequestType::Default; + case Settings::Specialization::Time: + return RequestType::DateTimeEdit; + case Settings::Specialization::Hex: + return RequestType::HexEdit; + case Settings::Specialization::RuntimeList: + managed = false; + [[fallthrough]]; + case Settings::Specialization::List: + return RequestType::ComboBox; + case Settings::Specialization::Scalar: + return RequestType::Slider; + case Settings::Specialization::Countable: + return RequestType::SpinBox; + case Settings::Specialization::Radio: + return RequestType::RadioGroup; + default: + break; + } + return request; + }(); + + if (!Settings::IsConfiguringGlobal() && managed) { + restore_button = CreateRestoreGlobalButton(setting.UsingGlobal(), this); + + touch = [this]() { + LOG_DEBUG(Frontend, "Enabling custom setting for \"{}\"", setting.GetLabel()); + restore_button->setEnabled(true); + restore_button->setVisible(true); + }; + } + + if (require_checkbox) { + QWidget* lhs = + CreateCheckBox(other_setting, label, checkbox_serializer, checkbox_restore_func, touch); + layout->addWidget(lhs); + } else if (setting.TypeId() != typeid(bool)) { + QLabel* qt_label = CreateLabel(label); + layout->addWidget(qt_label); + } + + if (setting.TypeId() == typeid(bool)) { + data_component = CreateCheckBox(&setting, label, serializer, restore_func, touch); + } else if (setting.IsEnum()) { + if (request == RequestType::RadioGroup) { + data_component = CreateRadioGroup(serializer, restore_func, touch); + } else { + data_component = CreateCombobox(serializer, restore_func, touch); + } + } else if (setting.IsIntegral()) { + switch (request) { + case RequestType::Slider: + case RequestType::ReverseSlider: + data_component = CreateSlider(request == RequestType::ReverseSlider, multiplier, suffix, + serializer, restore_func, touch); + break; + case RequestType::Default: + case RequestType::LineEdit: + data_component = CreateLineEdit(serializer, restore_func, touch); + break; + case RequestType::DateTimeEdit: + data_component = CreateDateTimeEdit(other_setting->ToString() != "true", true, + serializer, restore_func, touch); + break; + case RequestType::SpinBox: + data_component = CreateSpinBox(suffix, serializer, restore_func, touch); + break; + case RequestType::HexEdit: + data_component = CreateHexEdit(serializer, restore_func, touch); + break; + case RequestType::ComboBox: + data_component = CreateCombobox(serializer, restore_func, touch); + break; + default: + UNIMPLEMENTED(); + } + } else if (setting.IsFloatingPoint()) { + switch (request) { + case RequestType::Default: + case RequestType::SpinBox: + data_component = CreateDoubleSpinBox(suffix, serializer, restore_func, touch); + break; + case RequestType::Slider: + case RequestType::ReverseSlider: + data_component = CreateSlider(request == RequestType::ReverseSlider, multiplier, suffix, + serializer, restore_func, touch); + break; + default: + UNIMPLEMENTED(); + } + } else if (type == typeid(std::string)) { + switch (request) { + case RequestType::Default: + case RequestType::LineEdit: + data_component = CreateLineEdit(serializer, restore_func, touch); + break; + case RequestType::ComboBox: + data_component = CreateCombobox(serializer, restore_func, touch); + break; + default: + UNIMPLEMENTED(); + } + } + + if (data_component == nullptr) { + LOG_ERROR(Frontend, "Failed to create widget for \"{}\"", setting.GetLabel()); + created = false; + return; + } + + layout->addWidget(data_component); + + if (!managed) { + return; + } + + if (Settings::IsConfiguringGlobal()) { + load_func = [this, serializer, checkbox_serializer, require_checkbox, other_setting]() { + if (require_checkbox && other_setting->UsingGlobal()) { + other_setting->LoadString(checkbox_serializer()); + } + if (setting.UsingGlobal()) { + setting.LoadString(serializer()); + } + }; + } else { + layout->addWidget(restore_button); + + QObject::connect(restore_button, &QAbstractButton::clicked, + [this, restore_func, checkbox_restore_func](bool) { + LOG_DEBUG(Frontend, "Restore global state for \"{}\"", + setting.GetLabel()); + + restore_button->setEnabled(false); + restore_button->setVisible(false); + + checkbox_restore_func(); + restore_func(); + }); + + load_func = [this, serializer, require_checkbox, checkbox_serializer, other_setting]() { + bool using_global = !restore_button->isEnabled(); + setting.SetGlobal(using_global); + if (!using_global) { + setting.LoadString(serializer()); + } + if (require_checkbox) { + other_setting->SetGlobal(using_global); + if (!using_global) { + other_setting->LoadString(checkbox_serializer()); + } + } + }; + } + + if (other_setting != nullptr) { + const auto reset = [restore_func, data_component](int state) { + data_component->setEnabled(state == Qt::Checked); + if (state != Qt::Checked) { + restore_func(); + } + }; + connect(checkbox, &QCheckBox::stateChanged, reset); + reset(checkbox->checkState()); + } +} + +bool Widget::Valid() const { + return created; +} + +Widget::~Widget() = default; + +Widget::Widget(Settings::BasicSetting* setting_, const TranslationMap& translations_, + const ComboboxTranslationMap& combobox_translations_, QWidget* parent_, + bool runtime_lock_, std::vector>& apply_funcs_, + RequestType request, bool managed, float multiplier, + Settings::BasicSetting* other_setting, const QString& suffix) + : QWidget(parent_), parent{parent_}, translations{translations_}, + combobox_enumerations{combobox_translations_}, setting{*setting_}, apply_funcs{apply_funcs_}, + runtime_lock{runtime_lock_} { + if (!Settings::IsConfiguringGlobal() && !setting.Switchable()) { + LOG_DEBUG(Frontend, "\"{}\" is not switchable, skipping...", setting.GetLabel()); + return; + } + + const int id = setting.Id(); + + const auto [label, tooltip] = [&]() { + const auto& setting_label = setting.GetLabel(); + if (translations.contains(id)) { + return std::pair{translations.at(id).first, translations.at(id).second}; + } + LOG_WARNING(Frontend, "Translation table lacks entry for \"{}\"", setting_label); + return std::pair{QString::fromStdString(setting_label), QStringLiteral()}; + }(); + + if (label == QStringLiteral()) { + LOG_DEBUG(Frontend, "Translation table has empty entry for \"{}\", skipping...", + setting.GetLabel()); + return; + } + + std::function load_func = []() {}; + + SetupComponent(label, load_func, managed, request, multiplier, other_setting, suffix); + + if (!created) { + LOG_WARNING(Frontend, "No widget was created for \"{}\"", setting.GetLabel()); + return; + } + + apply_funcs.push_back([load_func, setting_](bool powered_on) { + if (setting_->RuntimeModifiable() || !powered_on) { + load_func(); + } + }); + + bool enable = runtime_lock || setting.RuntimeModifiable(); + if (setting.Switchable() && Settings::IsConfiguringGlobal() && !runtime_lock) { + enable &= setting.UsingGlobal(); + } + this->setEnabled(enable); + + this->setToolTip(tooltip); +} + +Builder::Builder(QWidget* parent_, bool runtime_lock_) + : translations{InitializeTranslations(parent_)}, + combobox_translations{ComboboxEnumeration(parent_)}, parent{parent_}, runtime_lock{ + runtime_lock_} {} + +Builder::~Builder() = default; + +Widget* Builder::BuildWidget(Settings::BasicSetting* setting, + std::vector>& apply_funcs, + RequestType request, bool managed, float multiplier, + Settings::BasicSetting* other_setting, const QString& suffix) const { + if (!Settings::IsConfiguringGlobal() && !setting->Switchable()) { + return nullptr; + } + + if (setting->Specialization() == Settings::Specialization::Paired) { + LOG_DEBUG(Frontend, "\"{}\" has specialization Paired: ignoring", setting->GetLabel()); + return nullptr; + } + + return new Widget(setting, *translations, *combobox_translations, parent, runtime_lock, + apply_funcs, request, managed, multiplier, other_setting, suffix); +} + +Widget* Builder::BuildWidget(Settings::BasicSetting* setting, + std::vector>& apply_funcs, + Settings::BasicSetting* other_setting, RequestType request, + const QString& suffix) const { + return BuildWidget(setting, apply_funcs, request, true, 1.0f, other_setting, suffix); +} + +const ComboboxTranslationMap& Builder::ComboboxTranslations() const { + return *combobox_translations; +} + +} // namespace ConfigurationShared diff --git a/src/sudachi/configuration/shared_widget.h b/src/sudachi/configuration/shared_widget.h new file mode 100644 index 0000000..bd9fe15 --- /dev/null +++ b/src/sudachi/configuration/shared_widget.h @@ -0,0 +1,178 @@ +// SPDX-FileCopyrightText: Copyright 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include "sudachi/configuration/shared_translation.h" + +class QCheckBox; +class QComboBox; +class QDateTimeEdit; +class QLabel; +class QLineEdit; +class QObject; +class QPushButton; +class QSlider; +class QSpinBox; +class QDoubleSpinBox; +class QRadioButton; + +namespace Settings { +class BasicSetting; +} // namespace Settings + +namespace ConfigurationShared { + +enum class RequestType { + Default, + ComboBox, + SpinBox, + Slider, + ReverseSlider, + LineEdit, + HexEdit, + DateTimeEdit, + RadioGroup, + MaxEnum, +}; + +constexpr float default_multiplier{1.f}; +constexpr float default_float_multiplier{100.f}; +static const QString default_suffix = QStringLiteral(); + +class Widget : public QWidget { + Q_OBJECT + +public: + /** + * @param setting The primary Setting to create the Widget for + * @param translations Map of translations to display on the left side label/checkbox + * @param combobox_translations Map of translations for enumerating combo boxes + * @param parent Qt parent + * @param runtime_lock Emulated guest powered on state, for use on settings that should be + * configured during guest execution + * @param apply_funcs_ List to append, functions to run to apply the widget state to the setting + * @param request What type of data representation component to create -- not always respected + * for the Setting data type + * @param managed Set true if the caller will set up component data and handling + * @param multiplier Value to multiply the slider feedback label + * @param other_setting Second setting to modify, to replace the label with a checkbox + * @param suffix Set to specify formats for Slider feedback labels or SpinBox + */ + explicit Widget(Settings::BasicSetting* setting, const TranslationMap& translations, + const ComboboxTranslationMap& combobox_translations, QWidget* parent, + bool runtime_lock, std::vector>& apply_funcs_, + RequestType request = RequestType::Default, bool managed = true, + float multiplier = default_multiplier, + Settings::BasicSetting* other_setting = nullptr, + const QString& suffix = default_suffix); + virtual ~Widget(); + + /** + * @returns True if the Widget successfully created the components for the setting + */ + bool Valid() const; + + /** + * Creates a button to appear when a setting has been modified. This exists for custom + * configurations and wasn't designed to work for the global configuration. It has public access + * for settings that need to be unmanaged but can be custom. + * + * @param using_global The global state of the setting this button is for + * @param parent QWidget parent + */ + [[nodiscard]] static QPushButton* CreateRestoreGlobalButton(bool using_global, QWidget* parent); + + // Direct handles to sub components created + QPushButton* restore_button{}; ///< Restore button for custom configurations + QLineEdit* line_edit{}; ///< QLineEdit, used for LineEdit and HexEdit + QSpinBox* spinbox{}; + QDoubleSpinBox* double_spinbox{}; + QCheckBox* checkbox{}; + QSlider* slider{}; + QComboBox* combobox{}; + QDateTimeEdit* date_time_edit{}; + std::vector> radio_buttons{}; + +private: + void SetupComponent(const QString& label, std::function& load_func, bool managed, + RequestType request, float multiplier, + Settings::BasicSetting* other_setting, const QString& suffix); + + QLabel* CreateLabel(const QString& text); + QWidget* CreateCheckBox(Settings::BasicSetting* bool_setting, const QString& label, + std::function& serializer, + std::function& restore_func, + const std::function& touch); + + QWidget* CreateCombobox(std::function& serializer, + std::function& restore_func, + const std::function& touch); + QWidget* CreateRadioGroup(std::function& serializer, + std::function& restore_func, + const std::function& touch); + QWidget* CreateLineEdit(std::function& serializer, + std::function& restore_func, const std::function& touch, + bool managed = true); + QWidget* CreateHexEdit(std::function& serializer, + std::function& restore_func, const std::function& touch); + QWidget* CreateSlider(bool reversed, float multiplier, const QString& suffix, + std::function& serializer, + std::function& restore_func, const std::function& touch); + QWidget* CreateDateTimeEdit(bool disabled, bool restrict, + std::function& serializer, + std::function& restore_func, + const std::function& touch); + QWidget* CreateSpinBox(const QString& suffix, std::function& serializer, + std::function& restore_func, const std::function& touch); + QWidget* CreateDoubleSpinBox(const QString& suffix, std::function& serializer, + std::function& restore_func, + const std::function& touch); + + QWidget* parent; + const TranslationMap& translations; + const ComboboxTranslationMap& combobox_enumerations; + Settings::BasicSetting& setting; + std::vector>& apply_funcs; + + bool created{false}; + bool runtime_lock{false}; +}; + +class Builder { +public: + explicit Builder(QWidget* parent, bool runtime_lock); + ~Builder(); + + Widget* BuildWidget(Settings::BasicSetting* setting, + std::vector>& apply_funcs, + RequestType request = RequestType::Default, bool managed = true, + float multiplier = default_multiplier, + Settings::BasicSetting* other_setting = nullptr, + const QString& suffix = default_suffix) const; + + Widget* BuildWidget(Settings::BasicSetting* setting, + std::vector>& apply_funcs, + Settings::BasicSetting* other_setting, + RequestType request = RequestType::Default, + const QString& suffix = default_suffix) const; + + const ComboboxTranslationMap& ComboboxTranslations() const; + +private: + std::unique_ptr translations; + std::unique_ptr combobox_translations; + + QWidget* parent; + const bool runtime_lock; +}; + +} // namespace ConfigurationShared diff --git a/src/sudachi/debugger/console.cpp b/src/sudachi/debugger/console.cpp new file mode 100644 index 0000000..7f0fdeb --- /dev/null +++ b/src/sudachi/debugger/console.cpp @@ -0,0 +1,49 @@ +// SPDX-FileCopyrightText: Copyright 2018 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#ifdef _WIN32 +#include + +#include +#endif + +#include "common/logging/backend.h" +#include "sudachi/debugger/console.h" +#include "sudachi/uisettings.h" + +namespace Debugger { +void ToggleConsole() { + static bool console_shown = false; + if (console_shown == UISettings::values.show_console.GetValue()) { + return; + } else { + console_shown = UISettings::values.show_console.GetValue(); + } + + using namespace Common::Log; +#if defined(_WIN32) && !defined(_DEBUG) + FILE* temp; + if (UISettings::values.show_console) { + if (AllocConsole()) { + // The first parameter for freopen_s is a out parameter, so we can just ignore it + freopen_s(&temp, "CONIN$", "r", stdin); + freopen_s(&temp, "CONOUT$", "w", stdout); + freopen_s(&temp, "CONOUT$", "w", stderr); + SetConsoleOutputCP(65001); + SetColorConsoleBackendEnabled(true); + } + } else { + if (FreeConsole()) { + // In order to close the console, we have to also detach the streams on it. + // Just redirect them to NUL if there is no console window + SetColorConsoleBackendEnabled(false); + freopen_s(&temp, "NUL", "r", stdin); + freopen_s(&temp, "NUL", "w", stdout); + freopen_s(&temp, "NUL", "w", stderr); + } + } +#else + SetColorConsoleBackendEnabled(UISettings::values.show_console.GetValue()); +#endif +} +} // namespace Debugger diff --git a/src/sudachi/debugger/console.h b/src/sudachi/debugger/console.h new file mode 100644 index 0000000..e8d6a91 --- /dev/null +++ b/src/sudachi/debugger/console.h @@ -0,0 +1,13 @@ +// SPDX-FileCopyrightText: Copyright 2018 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +namespace Debugger { + +/** + * Uses the WINAPI to hide or show the stderr console. This function is a placeholder until we can + * get a real qt logging window which would work for all platforms. + */ +void ToggleConsole(); +} // namespace Debugger diff --git a/src/sudachi/debugger/controller.cpp b/src/sudachi/debugger/controller.cpp new file mode 100644 index 0000000..cc31f61 --- /dev/null +++ b/src/sudachi/debugger/controller.cpp @@ -0,0 +1,116 @@ +// SPDX-FileCopyrightText: 2015 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include +#include +#include "common/settings.h" +#include "hid_core/frontend/emulated_controller.h" +#include "hid_core/hid_core.h" +#include "input_common/drivers/tas_input.h" +#include "input_common/main.h" +#include "sudachi/configuration/configure_input_player_widget.h" +#include "sudachi/debugger/controller.h" + +ControllerDialog::ControllerDialog(Core::HID::HIDCore& hid_core_, + std::shared_ptr input_subsystem_, + QWidget* parent) + : QWidget(parent, Qt::Dialog), hid_core{hid_core_}, input_subsystem{input_subsystem_} { + setObjectName(QStringLiteral("Controller")); + setWindowTitle(tr("Controller P1")); + resize(500, 350); + setMinimumSize(500, 350); + // Enable the maximize button + setWindowFlags(windowFlags() | Qt::WindowMaximizeButtonHint); + + widget = new PlayerControlPreview(this); + refreshConfiguration(); + QLayout* layout = new QVBoxLayout(this); + layout->setContentsMargins(0, 0, 0, 0); + layout->addWidget(widget); + setLayout(layout); + + // Configure focus so that widget is focusable and the dialog automatically forwards focus to + // it. + setFocusProxy(widget); + widget->setFocusPolicy(Qt::StrongFocus); + widget->setFocus(); +} + +void ControllerDialog::refreshConfiguration() { + UnloadController(); + auto* player_1 = hid_core.GetEmulatedController(Core::HID::NpadIdType::Player1); + auto* handheld = hid_core.GetEmulatedController(Core::HID::NpadIdType::Handheld); + // Display the correct controller + controller = handheld->IsConnected() ? handheld : player_1; + + Core::HID::ControllerUpdateCallback engine_callback{ + .on_change = [this](Core::HID::ControllerTriggerType type) { ControllerUpdate(type); }, + .is_npad_service = true, + }; + callback_key = controller->SetCallback(engine_callback); + widget->SetController(controller); + is_controller_set = true; +} + +QAction* ControllerDialog::toggleViewAction() { + if (toggle_view_action == nullptr) { + toggle_view_action = new QAction(tr("&Controller P1"), this); + toggle_view_action->setCheckable(true); + toggle_view_action->setChecked(isVisible()); + connect(toggle_view_action, &QAction::toggled, this, &ControllerDialog::setVisible); + } + + return toggle_view_action; +} + +void ControllerDialog::UnloadController() { + widget->UnloadController(); + if (is_controller_set) { + controller->DeleteCallback(callback_key); + is_controller_set = false; + } +} + +void ControllerDialog::showEvent(QShowEvent* ev) { + if (toggle_view_action) { + toggle_view_action->setChecked(isVisible()); + } + QWidget::showEvent(ev); +} + +void ControllerDialog::hideEvent(QHideEvent* ev) { + if (toggle_view_action) { + toggle_view_action->setChecked(isVisible()); + } + QWidget::hideEvent(ev); +} + +void ControllerDialog::ControllerUpdate(Core::HID::ControllerTriggerType type) { + // TODO(german77): Remove TAS from here + switch (type) { + case Core::HID::ControllerTriggerType::Button: + case Core::HID::ControllerTriggerType::Stick: { + const auto buttons_values = controller->GetButtonsValues(); + const auto stick_values = controller->GetSticks(); + u64 buttons = 0; + std::size_t index = 0; + for (const auto& button : buttons_values) { + buttons |= button.value ? 1LLU << index : 0; + index++; + } + const InputCommon::TasInput::TasAnalog left_axis = { + .x = stick_values.left.x / 32767.f, + .y = stick_values.left.y / 32767.f, + }; + const InputCommon::TasInput::TasAnalog right_axis = { + .x = stick_values.right.x / 32767.f, + .y = stick_values.right.y / 32767.f, + }; + input_subsystem->GetTas()->RecordInput(buttons, left_axis, right_axis); + break; + } + default: + break; + } +} diff --git a/src/sudachi/debugger/controller.h b/src/sudachi/debugger/controller.h new file mode 100644 index 0000000..9651dfa --- /dev/null +++ b/src/sudachi/debugger/controller.h @@ -0,0 +1,56 @@ +// SPDX-FileCopyrightText: 2015 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include + +class QAction; +class QHideEvent; +class QShowEvent; +class PlayerControlPreview; + +namespace InputCommon { +class InputSubsystem; +} + +namespace Core::HID { +class HIDCore; +class EmulatedController; +enum class ControllerTriggerType; +} // namespace Core::HID + +class ControllerDialog : public QWidget { + Q_OBJECT + +public: + explicit ControllerDialog(Core::HID::HIDCore& hid_core_, + std::shared_ptr input_subsystem_, + QWidget* parent = nullptr); + + /// Returns a QAction that can be used to toggle visibility of this dialog. + QAction* toggleViewAction(); + + /// Reloads the widget to apply any changes in the configuration + void refreshConfiguration(); + + /// Disables events from the emulated controller + void UnloadController(); + +protected: + void showEvent(QShowEvent* ev) override; + void hideEvent(QHideEvent* ev) override; + +private: + /// Redirects input from the widget to the TAS driver + void ControllerUpdate(Core::HID::ControllerTriggerType type); + + int callback_key; + bool is_controller_set{}; + Core::HID::EmulatedController* controller; + + QAction* toggle_view_action = nullptr; + PlayerControlPreview* widget; + Core::HID::HIDCore& hid_core; + std::shared_ptr input_subsystem; +}; diff --git a/src/sudachi/debugger/profiler.cpp b/src/sudachi/debugger/profiler.cpp new file mode 100644 index 0000000..8dc1643 --- /dev/null +++ b/src/sudachi/debugger/profiler.cpp @@ -0,0 +1,229 @@ +// SPDX-FileCopyrightText: 2015 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include +#include +#include +#include +#include +#include "common/common_types.h" +#include "common/microprofile.h" +#include "sudachi/debugger/profiler.h" +#include "sudachi/util/util.h" + +// Include the implementation of the UI in this file. This isn't in microprofile.cpp because the +// non-Qt frontends don't need it (and don't implement the UI drawing hooks either). +#if MICROPROFILE_ENABLED +#define MICROPROFILEUI_IMPL 1 +#include "common/microprofileui.h" + +class MicroProfileWidget : public QWidget { +public: + MicroProfileWidget(QWidget* parent = nullptr); + +protected: + void paintEvent(QPaintEvent* ev) override; + void showEvent(QShowEvent* ev) override; + void hideEvent(QHideEvent* ev) override; + + void mouseMoveEvent(QMouseEvent* ev) override; + void mousePressEvent(QMouseEvent* ev) override; + void mouseReleaseEvent(QMouseEvent* ev) override; + void wheelEvent(QWheelEvent* ev) override; + + void keyPressEvent(QKeyEvent* ev) override; + void keyReleaseEvent(QKeyEvent* ev) override; + +private: + /// This timer is used to redraw the widget's contents continuously. To save resources, it only + /// runs while the widget is visible. + QTimer update_timer; + /// Scale the coordinate system appropriately when dpi != 96. + qreal x_scale = 1.0, y_scale = 1.0; +}; + +#endif + +MicroProfileDialog::MicroProfileDialog(QWidget* parent) : QWidget(parent, Qt::Dialog) { + setObjectName(QStringLiteral("MicroProfile")); + setWindowTitle(tr("&MicroProfile")); + resize(1000, 600); + // Enable the maximize button + setWindowFlags(windowFlags() | Qt::WindowMaximizeButtonHint); + +#if MICROPROFILE_ENABLED + + MicroProfileWidget* widget = new MicroProfileWidget(this); + + QLayout* layout = new QVBoxLayout(this); + layout->setContentsMargins(0, 0, 0, 0); + layout->addWidget(widget); + setLayout(layout); + + // Configure focus so that widget is focusable and the dialog automatically forwards focus to + // it. + setFocusProxy(widget); + widget->setFocusPolicy(Qt::StrongFocus); + widget->setFocus(); +#endif +} + +QAction* MicroProfileDialog::toggleViewAction() { + if (toggle_view_action == nullptr) { + toggle_view_action = new QAction(windowTitle(), this); + toggle_view_action->setCheckable(true); + toggle_view_action->setChecked(isVisible()); + connect(toggle_view_action, &QAction::toggled, this, &MicroProfileDialog::setVisible); + } + + return toggle_view_action; +} + +void MicroProfileDialog::showEvent(QShowEvent* ev) { + if (toggle_view_action) { + toggle_view_action->setChecked(isVisible()); + } + QWidget::showEvent(ev); +} + +void MicroProfileDialog::hideEvent(QHideEvent* ev) { + if (toggle_view_action) { + toggle_view_action->setChecked(isVisible()); + } + QWidget::hideEvent(ev); +} + +#if MICROPROFILE_ENABLED + +/// There's no way to pass a user pointer to MicroProfile, so this variable is used to make the +/// QPainter available inside the drawing callbacks. +static QPainter* mp_painter = nullptr; + +MicroProfileWidget::MicroProfileWidget(QWidget* parent) : QWidget(parent) { + // Send mouse motion events even when not dragging. + setMouseTracking(true); + + MicroProfileSetDisplayMode(1); // Timers screen + MicroProfileInitUI(); + + connect(&update_timer, &QTimer::timeout, this, qOverload<>(&MicroProfileWidget::update)); +} + +void MicroProfileWidget::paintEvent(QPaintEvent* ev) { + QPainter painter(this); + + // The units used by Microprofile for drawing are based in pixels on a 96 dpi display. + x_scale = qreal(painter.device()->logicalDpiX()) / 96.0; + y_scale = qreal(painter.device()->logicalDpiY()) / 96.0; + painter.scale(x_scale, y_scale); + + painter.setBackground(Qt::black); + painter.eraseRect(rect()); + + QFont font = GetMonospaceFont(); + font.setPixelSize(MICROPROFILE_TEXT_HEIGHT); + painter.setFont(font); + + mp_painter = &painter; + MicroProfileDraw(rect().width() / x_scale, rect().height() / y_scale); + mp_painter = nullptr; +} + +void MicroProfileWidget::showEvent(QShowEvent* ev) { + update_timer.start(15); // ~60 Hz + QWidget::showEvent(ev); +} + +void MicroProfileWidget::hideEvent(QHideEvent* ev) { + update_timer.stop(); + QWidget::hideEvent(ev); +} + +void MicroProfileWidget::mouseMoveEvent(QMouseEvent* ev) { + const auto mouse_position = ev->pos(); + MicroProfileMousePosition(mouse_position.x() / x_scale, mouse_position.y() / y_scale, 0); + ev->accept(); +} + +void MicroProfileWidget::mousePressEvent(QMouseEvent* ev) { + const auto mouse_position = ev->pos(); + MicroProfileMousePosition(mouse_position.x() / x_scale, mouse_position.y() / y_scale, 0); + MicroProfileMouseButton(ev->buttons() & Qt::LeftButton, ev->buttons() & Qt::RightButton); + ev->accept(); +} + +void MicroProfileWidget::mouseReleaseEvent(QMouseEvent* ev) { + const auto mouse_position = ev->pos(); + MicroProfileMousePosition(mouse_position.x() / x_scale, mouse_position.y() / y_scale, 0); + MicroProfileMouseButton(ev->buttons() & Qt::LeftButton, ev->buttons() & Qt::RightButton); + ev->accept(); +} + +void MicroProfileWidget::wheelEvent(QWheelEvent* ev) { + const auto wheel_position = ev->position().toPoint(); + MicroProfileMousePosition(wheel_position.x() / x_scale, wheel_position.y() / y_scale, + ev->angleDelta().y() / 120); + ev->accept(); +} + +void MicroProfileWidget::keyPressEvent(QKeyEvent* ev) { + if (ev->key() == Qt::Key_Control) { + // Inform MicroProfile that the user is holding Ctrl. + MicroProfileModKey(1); + } + QWidget::keyPressEvent(ev); +} + +void MicroProfileWidget::keyReleaseEvent(QKeyEvent* ev) { + if (ev->key() == Qt::Key_Control) { + MicroProfileModKey(0); + } + QWidget::keyReleaseEvent(ev); +} + +// These functions are called by MicroProfileDraw to draw the interface elements on the screen. + +void MicroProfileDrawText(int x, int y, u32 hex_color, const char* text, u32 text_length) { + // hex_color does not include an alpha, so it must be assumed to be 255 + mp_painter->setPen(QColor::fromRgb(hex_color)); + + // It's impossible to draw a string using a monospaced font with a fixed width per cell in a + // way that's reliable across different platforms and fonts as far as I (yuriks) can tell, so + // draw each character individually in order to precisely control the text advance. + for (u32 i = 0; i < text_length; ++i) { + // Position the text baseline 1 pixel above the bottom of the text cell, this gives nice + // vertical alignment of text for a wide range of tested fonts. + mp_painter->drawText(x, y + MICROPROFILE_TEXT_HEIGHT - 2, QString{QLatin1Char{text[i]}}); + x += MICROPROFILE_TEXT_WIDTH + 1; + } +} + +void MicroProfileDrawBox(int left, int top, int right, int bottom, u32 hex_color, + MicroProfileBoxType type) { + QColor color = QColor::fromRgba(hex_color); + QBrush brush = color; + if (type == MicroProfileBoxTypeBar) { + QLinearGradient gradient(left, top, left, bottom); + gradient.setColorAt(0.f, color.lighter(125)); + gradient.setColorAt(1.f, color.darker(125)); + brush = gradient; + } + mp_painter->fillRect(left, top, right - left, bottom - top, brush); +} + +void MicroProfileDrawLine2D(u32 vertices_length, float* vertices, u32 hex_color) { + // Temporary vector used to convert between the float array and QPointF. Marked static to reuse + // the allocation across calls. + static std::vector point_buf; + + for (u32 i = 0; i < vertices_length; ++i) { + point_buf.emplace_back(vertices[i * 2 + 0], vertices[i * 2 + 1]); + } + + // hex_color does not include an alpha, so it must be assumed to be 255 + mp_painter->setPen(QColor::fromRgb(hex_color)); + mp_painter->drawPolyline(point_buf.data(), vertices_length); + point_buf.clear(); +} +#endif diff --git a/src/sudachi/debugger/profiler.h b/src/sudachi/debugger/profiler.h new file mode 100644 index 0000000..4c8ccd3 --- /dev/null +++ b/src/sudachi/debugger/profiler.h @@ -0,0 +1,27 @@ +// SPDX-FileCopyrightText: 2015 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include + +class QAction; +class QHideEvent; +class QShowEvent; + +class MicroProfileDialog : public QWidget { + Q_OBJECT + +public: + explicit MicroProfileDialog(QWidget* parent = nullptr); + + /// Returns a QAction that can be used to toggle visibility of this dialog. + QAction* toggleViewAction(); + +protected: + void showEvent(QShowEvent* ev) override; + void hideEvent(QHideEvent* ev) override; + +private: + QAction* toggle_view_action = nullptr; +}; diff --git a/src/sudachi/debugger/wait_tree.cpp b/src/sudachi/debugger/wait_tree.cpp new file mode 100644 index 0000000..fedb861 --- /dev/null +++ b/src/sudachi/debugger/wait_tree.cpp @@ -0,0 +1,431 @@ +// SPDX-FileCopyrightText: 2016 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include + +#include "sudachi/debugger/wait_tree.h" +#include "sudachi/uisettings.h" + +#include "core/arm/debug.h" +#include "core/core.h" +#include "core/hle/kernel/k_class_token.h" +#include "core/hle/kernel/k_handle_table.h" +#include "core/hle/kernel/k_process.h" +#include "core/hle/kernel/k_readable_event.h" +#include "core/hle/kernel/k_scheduler.h" +#include "core/hle/kernel/k_synchronization_object.h" +#include "core/hle/kernel/k_thread.h" +#include "core/hle/kernel/svc_common.h" +#include "core/hle/kernel/svc_types.h" +#include "core/memory.h" + +namespace { + +constexpr std::array, 10> WaitTreeColors{{ + {Qt::GlobalColor::darkGreen, Qt::GlobalColor::green}, + {Qt::GlobalColor::darkBlue, Qt::GlobalColor::cyan}, + {Qt::GlobalColor::lightGray, Qt::GlobalColor::lightGray}, + {Qt::GlobalColor::lightGray, Qt::GlobalColor::lightGray}, + {Qt::GlobalColor::darkRed, Qt::GlobalColor::red}, + {Qt::GlobalColor::darkYellow, Qt::GlobalColor::yellow}, + {Qt::GlobalColor::red, Qt::GlobalColor::red}, + {Qt::GlobalColor::darkCyan, Qt::GlobalColor::cyan}, + {Qt::GlobalColor::gray, Qt::GlobalColor::gray}, +}}; + +bool IsDarkTheme() { + const auto& theme = UISettings::values.theme; + return theme == std::string("qdarkstyle") || theme == std::string("qdarkstyle_midnight_blue") || + theme == std::string("colorful_dark") || theme == std::string("colorful_midnight_blue"); +} + +} // namespace + +WaitTreeItem::WaitTreeItem() = default; +WaitTreeItem::~WaitTreeItem() = default; + +QColor WaitTreeItem::GetColor() const { + if (IsDarkTheme()) { + return QColor(Qt::GlobalColor::white); + } else { + return QColor(Qt::GlobalColor::black); + } +} + +std::vector> WaitTreeItem::GetChildren() const { + return {}; +} + +void WaitTreeItem::Expand() { + if (IsExpandable() && !expanded) { + children = GetChildren(); + for (std::size_t i = 0; i < children.size(); ++i) { + children[i]->parent = this; + children[i]->row = i; + } + expanded = true; + } +} + +WaitTreeItem* WaitTreeItem::Parent() const { + return parent; +} + +const std::vector>& WaitTreeItem::Children() const { + return children; +} + +bool WaitTreeItem::IsExpandable() const { + return false; +} + +std::size_t WaitTreeItem::Row() const { + return row; +} + +std::vector> WaitTreeItem::MakeThreadItemList( + Core::System& system) { + std::vector> item_list; + std::size_t row = 0; + auto add_threads = [&](const std::vector& threads) { + for (std::size_t i = 0; i < threads.size(); ++i) { + if (threads[i]->GetThreadType() == Kernel::ThreadType::User) { + item_list.push_back(std::make_unique(*threads[i], system)); + item_list.back()->row = row; + } + ++row; + } + }; + + add_threads(system.GlobalSchedulerContext().GetThreadList()); + + return item_list; +} + +WaitTreeText::WaitTreeText(QString t) : text(std::move(t)) {} +WaitTreeText::~WaitTreeText() = default; + +QString WaitTreeText::GetText() const { + return text; +} + +WaitTreeCallstack::WaitTreeCallstack(const Kernel::KThread& thread_, Core::System& system_) + : thread{thread_}, system{system_} {} +WaitTreeCallstack::~WaitTreeCallstack() = default; + +QString WaitTreeCallstack::GetText() const { + return tr("Call stack"); +} + +std::vector> WaitTreeCallstack::GetChildren() const { + std::vector> list; + + if (thread.GetThreadType() != Kernel::ThreadType::User) { + return list; + } + + if (thread.GetOwnerProcess() == nullptr || !thread.GetOwnerProcess()->Is64Bit()) { + return list; + } + + auto backtrace = Core::GetBacktraceFromContext(thread.GetOwnerProcess(), thread.GetContext()); + + for (auto& entry : backtrace) { + std::string s = fmt::format("{:20}{:016X} {:016X} {:016X} {}", entry.module, entry.address, + entry.original_address, entry.offset, entry.name); + list.push_back(std::make_unique(QString::fromStdString(s))); + } + + return list; +} + +WaitTreeSynchronizationObject::WaitTreeSynchronizationObject( + const Kernel::KSynchronizationObject& object_, Core::System& system_) + : object{object_}, system{system_} {} +WaitTreeSynchronizationObject::~WaitTreeSynchronizationObject() = default; + +WaitTreeExpandableItem::WaitTreeExpandableItem() = default; +WaitTreeExpandableItem::~WaitTreeExpandableItem() = default; + +bool WaitTreeExpandableItem::IsExpandable() const { + return true; +} + +QString WaitTreeSynchronizationObject::GetText() const { + return tr("[%1] %2") + .arg(object.GetId()) + .arg(QString::fromStdString(object.GetTypeObj().GetName())); +} + +std::unique_ptr WaitTreeSynchronizationObject::make( + const Kernel::KSynchronizationObject& object, Core::System& system) { + const auto type = + static_cast(object.GetTypeObj().GetClassToken()); + switch (type) { + case Kernel::KClassTokenGenerator::ObjectType::KReadableEvent: + return std::make_unique(static_cast(object), + system); + case Kernel::KClassTokenGenerator::ObjectType::KThread: + return std::make_unique(static_cast(object), + system); + default: + return std::make_unique(object, system); + } +} + +std::vector> WaitTreeSynchronizationObject::GetChildren() const { + std::vector> list; + + auto threads = object.GetWaitingThreadsForDebugging(); + if (threads.empty()) { + list.push_back(std::make_unique(tr("waited by no thread"))); + } else { + list.push_back(std::make_unique(std::move(threads), system)); + } + + return list; +} + +WaitTreeThread::WaitTreeThread(const Kernel::KThread& thread, Core::System& system_) + : WaitTreeSynchronizationObject(thread, system_), system{system_} {} +WaitTreeThread::~WaitTreeThread() = default; + +QString WaitTreeThread::GetText() const { + const auto& thread = static_cast(object); + QString status; + switch (thread.GetState()) { + case Kernel::ThreadState::Runnable: + if (!thread.IsSuspended()) { + status = tr("runnable"); + } else { + status = tr("paused"); + } + break; + case Kernel::ThreadState::Waiting: + switch (thread.GetWaitReasonForDebugging()) { + case Kernel::ThreadWaitReasonForDebugging::Sleep: + status = tr("sleeping"); + break; + case Kernel::ThreadWaitReasonForDebugging::IPC: + status = tr("waiting for IPC reply"); + break; + case Kernel::ThreadWaitReasonForDebugging::Synchronization: + status = tr("waiting for objects"); + break; + case Kernel::ThreadWaitReasonForDebugging::ConditionVar: + status = tr("waiting for condition variable"); + break; + case Kernel::ThreadWaitReasonForDebugging::Arbitration: + status = tr("waiting for address arbiter"); + break; + case Kernel::ThreadWaitReasonForDebugging::Suspended: + status = tr("waiting for suspend resume"); + break; + default: + status = tr("waiting"); + break; + } + break; + case Kernel::ThreadState::Initialized: + status = tr("initialized"); + break; + case Kernel::ThreadState::Terminated: + status = tr("terminated"); + break; + default: + status = tr("unknown"); + break; + } + + const auto& context = thread.GetContext(); + const QString pc_info = tr(" PC = 0x%1 LR = 0x%2") + .arg(context.pc, 8, 16, QLatin1Char{'0'}) + .arg(context.lr, 8, 16, QLatin1Char{'0'}); + return QStringLiteral("%1%2 (%3) ") + .arg(WaitTreeSynchronizationObject::GetText(), pc_info, status); +} + +QColor WaitTreeThread::GetColor() const { + const std::size_t color_index = IsDarkTheme() ? 1 : 0; + + const auto& thread = static_cast(object); + switch (thread.GetState()) { + case Kernel::ThreadState::Runnable: + if (!thread.IsSuspended()) { + return QColor(WaitTreeColors[0][color_index]); + } else { + return QColor(WaitTreeColors[2][color_index]); + } + case Kernel::ThreadState::Waiting: + switch (thread.GetWaitReasonForDebugging()) { + case Kernel::ThreadWaitReasonForDebugging::IPC: + return QColor(WaitTreeColors[4][color_index]); + case Kernel::ThreadWaitReasonForDebugging::Sleep: + return QColor(WaitTreeColors[5][color_index]); + case Kernel::ThreadWaitReasonForDebugging::Synchronization: + case Kernel::ThreadWaitReasonForDebugging::ConditionVar: + case Kernel::ThreadWaitReasonForDebugging::Arbitration: + case Kernel::ThreadWaitReasonForDebugging::Suspended: + return QColor(WaitTreeColors[6][color_index]); + break; + default: + return QColor(WaitTreeColors[3][color_index]); + } + case Kernel::ThreadState::Initialized: + return QColor(WaitTreeColors[7][color_index]); + case Kernel::ThreadState::Terminated: + return QColor(WaitTreeColors[8][color_index]); + default: + return WaitTreeItem::GetColor(); + } +} + +std::vector> WaitTreeThread::GetChildren() const { + std::vector> list(WaitTreeSynchronizationObject::GetChildren()); + + const auto& thread = static_cast(object); + + QString processor; + switch (thread.GetActiveCore()) { + case Kernel::Svc::IdealCoreUseProcessValue: + processor = tr("ideal"); + break; + default: + processor = tr("core %1").arg(thread.GetActiveCore()); + break; + } + + list.push_back(std::make_unique(tr("processor = %1").arg(processor))); + list.push_back(std::make_unique( + tr("affinity mask = %1").arg(thread.GetAffinityMask().GetAffinityMask()))); + list.push_back(std::make_unique(tr("thread id = %1").arg(thread.GetThreadId()))); + list.push_back(std::make_unique(tr("priority = %1(current) / %2(normal)") + .arg(thread.GetPriority()) + .arg(thread.GetBasePriority()))); + list.push_back(std::make_unique( + tr("last running ticks = %1").arg(thread.GetLastScheduledTick()))); + + list.push_back(std::make_unique(thread, system)); + + return list; +} + +WaitTreeEvent::WaitTreeEvent(const Kernel::KReadableEvent& object_, Core::System& system_) + : WaitTreeSynchronizationObject(object_, system_) {} +WaitTreeEvent::~WaitTreeEvent() = default; + +WaitTreeThreadList::WaitTreeThreadList(std::vector&& list, Core::System& system_) + : thread_list(std::move(list)), system{system_} {} +WaitTreeThreadList::~WaitTreeThreadList() = default; + +QString WaitTreeThreadList::GetText() const { + return tr("waited by thread"); +} + +std::vector> WaitTreeThreadList::GetChildren() const { + std::vector> list(thread_list.size()); + std::transform(thread_list.begin(), thread_list.end(), list.begin(), + [this](const auto& t) { return std::make_unique(*t, system); }); + return list; +} + +WaitTreeModel::WaitTreeModel(Core::System& system_, QObject* parent) + : QAbstractItemModel(parent), system{system_} {} +WaitTreeModel::~WaitTreeModel() = default; + +QModelIndex WaitTreeModel::index(int row, int column, const QModelIndex& parent) const { + if (!hasIndex(row, column, parent)) + return {}; + + if (parent.isValid()) { + WaitTreeItem* parent_item = static_cast(parent.internalPointer()); + parent_item->Expand(); + return createIndex(row, column, parent_item->Children()[row].get()); + } + + return createIndex(row, column, thread_items[row].get()); +} + +QModelIndex WaitTreeModel::parent(const QModelIndex& index) const { + if (!index.isValid()) + return {}; + + WaitTreeItem* parent_item = static_cast(index.internalPointer())->Parent(); + if (!parent_item) { + return QModelIndex(); + } + return createIndex(static_cast(parent_item->Row()), 0, parent_item); +} + +int WaitTreeModel::rowCount(const QModelIndex& parent) const { + if (!parent.isValid()) + return static_cast(thread_items.size()); + + WaitTreeItem* parent_item = static_cast(parent.internalPointer()); + parent_item->Expand(); + return static_cast(parent_item->Children().size()); +} + +int WaitTreeModel::columnCount(const QModelIndex&) const { + return 1; +} + +QVariant WaitTreeModel::data(const QModelIndex& index, int role) const { + if (!index.isValid()) + return {}; + + switch (role) { + case Qt::DisplayRole: + return static_cast(index.internalPointer())->GetText(); + case Qt::ForegroundRole: + return static_cast(index.internalPointer())->GetColor(); + default: + return {}; + } +} + +void WaitTreeModel::ClearItems() { + thread_items.clear(); +} + +void WaitTreeModel::InitItems() { + thread_items = WaitTreeItem::MakeThreadItemList(system); +} + +WaitTreeWidget::WaitTreeWidget(Core::System& system_, QWidget* parent) + : QDockWidget(tr("&Wait Tree"), parent), system{system_} { + setObjectName(QStringLiteral("WaitTreeWidget")); + view = new QTreeView(this); + view->setHeaderHidden(true); + setWidget(view); + setEnabled(false); +} + +WaitTreeWidget::~WaitTreeWidget() = default; + +void WaitTreeWidget::OnDebugModeEntered() { + if (!system.IsPoweredOn()) + return; + model->InitItems(); + view->setModel(model); + setEnabled(true); +} + +void WaitTreeWidget::OnDebugModeLeft() { + setEnabled(false); + view->setModel(nullptr); + model->ClearItems(); +} + +void WaitTreeWidget::OnEmulationStarting(EmuThread* emu_thread) { + model = new WaitTreeModel(system, this); + view->setModel(model); + setEnabled(false); +} + +void WaitTreeWidget::OnEmulationStopping() { + view->setModel(nullptr); + delete model; + setEnabled(false); +} diff --git a/src/sudachi/debugger/wait_tree.h b/src/sudachi/debugger/wait_tree.h new file mode 100644 index 0000000..23c329f --- /dev/null +++ b/src/sudachi/debugger/wait_tree.h @@ -0,0 +1,188 @@ +// SPDX-FileCopyrightText: 2016 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include +#include + +#include +#include + +#include "common/common_types.h" +#include "core/hle/kernel/k_auto_object.h" +#include "core/hle/kernel/svc_common.h" + +class EmuThread; + +namespace Core { +class System; +} + +namespace Kernel { +class KHandleTable; +class KReadableEvent; +class KSynchronizationObject; +class KThread; +} // namespace Kernel + +class WaitTreeThread; + +class WaitTreeItem : public QObject { + Q_OBJECT +public: + WaitTreeItem(); + ~WaitTreeItem() override; + + virtual bool IsExpandable() const; + virtual std::vector> GetChildren() const; + virtual QString GetText() const = 0; + virtual QColor GetColor() const; + + void Expand(); + WaitTreeItem* Parent() const; + const std::vector>& Children() const; + std::size_t Row() const; + static std::vector> MakeThreadItemList(Core::System& system); + +private: + std::size_t row; + bool expanded = false; + WaitTreeItem* parent = nullptr; + std::vector> children; +}; + +class WaitTreeText : public WaitTreeItem { + Q_OBJECT +public: + explicit WaitTreeText(QString text); + ~WaitTreeText() override; + + QString GetText() const override; + +private: + QString text; +}; + +class WaitTreeExpandableItem : public WaitTreeItem { + Q_OBJECT +public: + WaitTreeExpandableItem(); + ~WaitTreeExpandableItem() override; + + bool IsExpandable() const override; +}; + +class WaitTreeCallstack : public WaitTreeExpandableItem { + Q_OBJECT +public: + explicit WaitTreeCallstack(const Kernel::KThread& thread_, Core::System& system_); + ~WaitTreeCallstack() override; + + QString GetText() const override; + std::vector> GetChildren() const override; + +private: + const Kernel::KThread& thread; + + Core::System& system; +}; + +class WaitTreeSynchronizationObject : public WaitTreeExpandableItem { + Q_OBJECT +public: + explicit WaitTreeSynchronizationObject(const Kernel::KSynchronizationObject& object_, + Core::System& system_); + ~WaitTreeSynchronizationObject() override; + + static std::unique_ptr make( + const Kernel::KSynchronizationObject& object, Core::System& system); + QString GetText() const override; + std::vector> GetChildren() const override; + +protected: + const Kernel::KSynchronizationObject& object; + +private: + Core::System& system; +}; + +class WaitTreeThread : public WaitTreeSynchronizationObject { + Q_OBJECT +public: + explicit WaitTreeThread(const Kernel::KThread& thread, Core::System& system_); + ~WaitTreeThread() override; + + QString GetText() const override; + QColor GetColor() const override; + std::vector> GetChildren() const override; + +private: + Core::System& system; +}; + +class WaitTreeEvent : public WaitTreeSynchronizationObject { + Q_OBJECT +public: + explicit WaitTreeEvent(const Kernel::KReadableEvent& object_, Core::System& system_); + ~WaitTreeEvent() override; +}; + +class WaitTreeThreadList : public WaitTreeExpandableItem { + Q_OBJECT +public: + explicit WaitTreeThreadList(std::vector&& list, Core::System& system_); + ~WaitTreeThreadList() override; + + QString GetText() const override; + std::vector> GetChildren() const override; + +private: + std::vector thread_list; + + Core::System& system; +}; + +class WaitTreeModel : public QAbstractItemModel { + Q_OBJECT + +public: + explicit WaitTreeModel(Core::System& system_, QObject* parent = nullptr); + ~WaitTreeModel() override; + + QVariant data(const QModelIndex& index, int role) const override; + QModelIndex index(int row, int column, const QModelIndex& parent) const override; + QModelIndex parent(const QModelIndex& index) const override; + int rowCount(const QModelIndex& parent) const override; + int columnCount(const QModelIndex& parent) const override; + + void ClearItems(); + void InitItems(); + +private: + std::vector> thread_items; + + Core::System& system; +}; + +class WaitTreeWidget : public QDockWidget { + Q_OBJECT + +public: + explicit WaitTreeWidget(Core::System& system_, QWidget* parent = nullptr); + ~WaitTreeWidget() override; + +public slots: + void OnDebugModeEntered(); + void OnDebugModeLeft(); + + void OnEmulationStarting(EmuThread* emu_thread); + void OnEmulationStopping(); + +private: + QTreeView* view; + WaitTreeModel* model; + + Core::System& system; +}; diff --git a/src/sudachi/discord.h b/src/sudachi/discord.h new file mode 100644 index 0000000..e087844 --- /dev/null +++ b/src/sudachi/discord.h @@ -0,0 +1,24 @@ +// SPDX-FileCopyrightText: 2018 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +namespace DiscordRPC { + +class DiscordInterface { +public: + virtual ~DiscordInterface() = default; + + virtual void Pause() = 0; + virtual void Update() = 0; +}; + +class NullImpl : public DiscordInterface { +public: + ~NullImpl() = default; + + void Pause() override {} + void Update() override {} +}; + +} // namespace DiscordRPC diff --git a/src/sudachi/discord_impl.cpp b/src/sudachi/discord_impl.cpp new file mode 100644 index 0000000..7aeb151 --- /dev/null +++ b/src/sudachi/discord_impl.cpp @@ -0,0 +1,117 @@ +// SPDX-FileCopyrightText: 2018 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include + +#include +#include +#include + +#include +#include + +#include "common/common_types.h" +#include "common/string_util.h" +#include "core/core.h" +#include "core/loader/loader.h" +#include "sudachi/discord_impl.h" +#include "sudachi/uisettings.h" + +namespace DiscordRPC { + +DiscordImpl::DiscordImpl(Core::System& system_) : system{system_} { + DiscordEventHandlers handlers{}; + // The number is the client ID for sudachi, it's used for images and the + // application name + Discord_Initialize("712465656758665259", &handlers, 1, nullptr); +} + +DiscordImpl::~DiscordImpl() { + Discord_ClearPresence(); + Discord_Shutdown(); +} + +void DiscordImpl::Pause() { + Discord_ClearPresence(); +} + +std::string DiscordImpl::GetGameString(const std::string& title) { + // Convert to lowercase + std::string icon_name = Common::ToLower(title); + + // Replace spaces with dashes + std::replace(icon_name.begin(), icon_name.end(), ' ', '-'); + + // Remove non-alphanumeric characters but keep dashes + std::erase_if(icon_name, [](char c) { return !std::isalnum(c) && c != '-'; }); + + // Remove dashes from the start and end of the string + icon_name.erase(icon_name.begin(), std::find_if(icon_name.begin(), icon_name.end(), + [](int ch) { return ch != '-'; })); + icon_name.erase( + std::find_if(icon_name.rbegin(), icon_name.rend(), [](int ch) { return ch != '-'; }).base(), + icon_name.end()); + + // Remove double dashes + icon_name.erase(std::unique(icon_name.begin(), icon_name.end(), + [](char a, char b) { return a == '-' && b == '-'; }), + icon_name.end()); + + return icon_name; +} + +void DiscordImpl::UpdateGameStatus(bool use_default) { + const std::string default_text = "sudachi is an emulator for the Nintendo Switch"; + const std::string default_image = "sudachi_logo_ea"; + const std::string url = use_default ? default_image : game_url; + s64 start_time = std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()) + .count(); + DiscordRichPresence presence{}; + + presence.largeImageKey = url.c_str(); + presence.largeImageText = game_title.c_str(); + presence.smallImageKey = default_image.c_str(); + presence.smallImageText = default_text.c_str(); + presence.state = game_title.c_str(); + presence.details = "Currently in game"; + presence.startTimestamp = start_time; + Discord_UpdatePresence(&presence); +} + +void DiscordImpl::Update() { + const std::string default_text = "sudachi is an emulator for the Nintendo Switch"; + const std::string default_image = "sudachi_logo_ea"; + + if (system.IsPoweredOn()) { + system.GetAppLoader().ReadTitle(game_title); + + // Used to format Icon URL for sudachi website game compatibility page + std::string icon_name = GetGameString(game_title); + game_url = fmt::format("https://sudachi-emu.org/images/game/boxart/{}.png", icon_name); + + QNetworkAccessManager manager; + QNetworkRequest request; + request.setUrl(QUrl(QString::fromStdString(game_url))); + request.setTransferTimeout(3000); + QNetworkReply* reply = manager.head(request); + QEventLoop request_event_loop; + QObject::connect(reply, &QNetworkReply::finished, &request_event_loop, &QEventLoop::quit); + request_event_loop.exec(); + UpdateGameStatus(reply->error()); + return; + } + + s64 start_time = std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()) + .count(); + + DiscordRichPresence presence{}; + presence.largeImageKey = default_image.c_str(); + presence.largeImageText = default_text.c_str(); + presence.details = "Currently not in game"; + presence.startTimestamp = start_time; + Discord_UpdatePresence(&presence); +} +} // namespace DiscordRPC diff --git a/src/sudachi/discord_impl.h b/src/sudachi/discord_impl.h new file mode 100644 index 0000000..865fe8f --- /dev/null +++ b/src/sudachi/discord_impl.h @@ -0,0 +1,32 @@ +// SPDX-FileCopyrightText: 2018 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include "sudachi/discord.h" + +namespace Core { +class System; +} + +namespace DiscordRPC { + +class DiscordImpl : public DiscordInterface { +public: + DiscordImpl(Core::System& system_); + ~DiscordImpl() override; + + void Pause() override; + void Update() override; + +private: + std::string GetGameString(const std::string& title); + void UpdateGameStatus(bool use_default); + + std::string game_url{}; + std::string game_title{}; + + Core::System& system; +}; + +} // namespace DiscordRPC diff --git a/src/sudachi/game_list.cpp b/src/sudachi/game_list.cpp new file mode 100644 index 0000000..363e557 --- /dev/null +++ b/src/sudachi/game_list.cpp @@ -0,0 +1,970 @@ +// SPDX-FileCopyrightText: 2015 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "common/common_types.h" +#include "common/logging/log.h" +#include "core/core.h" +#include "core/file_sys/patch_manager.h" +#include "core/file_sys/registered_cache.h" +#include "sudachi/compatibility_list.h" +#include "sudachi/game_list.h" +#include "sudachi/game_list_p.h" +#include "sudachi/game_list_worker.h" +#include "sudachi/main.h" +#include "sudachi/uisettings.h" +#include "sudachi/util/controller_navigation.h" + +GameListSearchField::KeyReleaseEater::KeyReleaseEater(GameList* gamelist_, QObject* parent) + : QObject(parent), gamelist{gamelist_} {} + +// EventFilter in order to process systemkeys while editing the searchfield +bool GameListSearchField::KeyReleaseEater::eventFilter(QObject* obj, QEvent* event) { + // If it isn't a KeyRelease event then continue with standard event processing + if (event->type() != QEvent::KeyRelease) + return QObject::eventFilter(obj, event); + + QKeyEvent* keyEvent = static_cast(event); + QString edit_filter_text = gamelist->search_field->edit_filter->text().toLower(); + + // If the searchfield's text hasn't changed special function keys get checked + // If no function key changes the searchfield's text the filter doesn't need to get reloaded + if (edit_filter_text == edit_filter_text_old) { + switch (keyEvent->key()) { + // Escape: Resets the searchfield + case Qt::Key_Escape: { + if (edit_filter_text_old.isEmpty()) { + return QObject::eventFilter(obj, event); + } else { + gamelist->search_field->edit_filter->clear(); + edit_filter_text.clear(); + } + break; + } + // Return and Enter + // If the enter key gets pressed first checks how many and which entry is visible + // If there is only one result launch this game + case Qt::Key_Return: + case Qt::Key_Enter: { + if (gamelist->search_field->visible == 1) { + const QString file_path = gamelist->GetLastFilterResultItem(); + + // To avoid loading error dialog loops while confirming them using enter + // Also users usually want to run a different game after closing one + gamelist->search_field->edit_filter->clear(); + edit_filter_text.clear(); + emit gamelist->GameChosen(file_path); + } else { + return QObject::eventFilter(obj, event); + } + break; + } + default: + return QObject::eventFilter(obj, event); + } + } + edit_filter_text_old = edit_filter_text; + return QObject::eventFilter(obj, event); +} + +void GameListSearchField::setFilterResult(int visible_, int total_) { + visible = visible_; + total = total_; + + label_filter_result->setText(tr("%1 of %n result(s)", "", total).arg(visible)); +} + +QString GameListSearchField::filterText() const { + return edit_filter->text(); +} + +QString GameList::GetLastFilterResultItem() const { + QString file_path; + + for (int i = 1; i < item_model->rowCount() - 1; ++i) { + const QStandardItem* folder = item_model->item(i, 0); + const QModelIndex folder_index = folder->index(); + const int children_count = folder->rowCount(); + + for (int j = 0; j < children_count; ++j) { + if (tree_view->isRowHidden(j, folder_index)) { + continue; + } + + const QStandardItem* child = folder->child(j, 0); + file_path = child->data(GameListItemPath::FullPathRole).toString(); + } + } + + return file_path; +} + +void GameListSearchField::clear() { + edit_filter->clear(); +} + +void GameListSearchField::setFocus() { + if (edit_filter->isVisible()) { + edit_filter->setFocus(); + } +} + +GameListSearchField::GameListSearchField(GameList* parent) : QWidget{parent} { + auto* const key_release_eater = new KeyReleaseEater(parent, this); + layout_filter = new QHBoxLayout; + layout_filter->setContentsMargins(8, 8, 8, 8); + label_filter = new QLabel; + edit_filter = new QLineEdit; + edit_filter->clear(); + edit_filter->installEventFilter(key_release_eater); + edit_filter->setClearButtonEnabled(true); + connect(edit_filter, &QLineEdit::textChanged, parent, &GameList::OnTextChanged); + label_filter_result = new QLabel; + button_filter_close = new QToolButton(this); + button_filter_close->setText(QStringLiteral("X")); + button_filter_close->setCursor(Qt::ArrowCursor); + button_filter_close->setStyleSheet( + QStringLiteral("QToolButton{ border: none; padding: 0px; color: " + "#000000; font-weight: bold; background: #F0F0F0; }" + "QToolButton:hover{ border: none; padding: 0px; color: " + "#EEEEEE; font-weight: bold; background: #E81123}")); + connect(button_filter_close, &QToolButton::clicked, parent, &GameList::OnFilterCloseClicked); + layout_filter->setSpacing(10); + layout_filter->addWidget(label_filter); + layout_filter->addWidget(edit_filter); + layout_filter->addWidget(label_filter_result); + layout_filter->addWidget(button_filter_close); + setLayout(layout_filter); + RetranslateUI(); +} + +/** + * Checks if all words separated by spaces are contained in another string + * This offers a word order insensitive search function + * + * @param haystack String that gets checked if it contains all words of the userinput string + * @param userinput String containing all words getting checked + * @return true if the haystack contains all words of userinput + */ +static bool ContainsAllWords(const QString& haystack, const QString& userinput) { + const QStringList userinput_split = userinput.split(QLatin1Char{' '}, Qt::SkipEmptyParts); + + return std::all_of(userinput_split.begin(), userinput_split.end(), + [&haystack](const QString& s) { return haystack.contains(s); }); +} + +// Syncs the expanded state of Game Directories with settings to persist across sessions +void GameList::OnItemExpanded(const QModelIndex& item) { + const auto type = item.data(GameListItem::TypeRole).value(); + const bool is_dir = type == GameListItemType::CustomDir || type == GameListItemType::SdmcDir || + type == GameListItemType::UserNandDir || + type == GameListItemType::SysNandDir; + const bool is_fave = type == GameListItemType::Favorites; + if (!is_dir && !is_fave) { + return; + } + const bool is_expanded = tree_view->isExpanded(item); + if (is_fave) { + UISettings::values.favorites_expanded = is_expanded; + return; + } + const int item_dir_index = item.data(GameListDir::GameDirRole).toInt(); + UISettings::values.game_dirs[item_dir_index].expanded = is_expanded; +} + +// Event in order to filter the gamelist after editing the searchfield +void GameList::OnTextChanged(const QString& new_text) { + QString edit_filter_text = new_text.toLower(); + QStandardItem* folder; + int children_total = 0; + + // If the searchfield is empty every item is visible + // Otherwise the filter gets applied + if (edit_filter_text.isEmpty()) { + tree_view->setRowHidden(0, item_model->invisibleRootItem()->index(), + UISettings::values.favorited_ids.size() == 0); + for (int i = 1; i < item_model->rowCount() - 1; ++i) { + folder = item_model->item(i, 0); + const QModelIndex folder_index = folder->index(); + const int children_count = folder->rowCount(); + for (int j = 0; j < children_count; ++j) { + ++children_total; + tree_view->setRowHidden(j, folder_index, false); + } + } + search_field->setFilterResult(children_total, children_total); + } else { + tree_view->setRowHidden(0, item_model->invisibleRootItem()->index(), true); + int result_count = 0; + for (int i = 1; i < item_model->rowCount() - 1; ++i) { + folder = item_model->item(i, 0); + const QModelIndex folder_index = folder->index(); + const int children_count = folder->rowCount(); + for (int j = 0; j < children_count; ++j) { + ++children_total; + + const QStandardItem* child = folder->child(j, 0); + + const auto program_id = child->data(GameListItemPath::ProgramIdRole).toULongLong(); + + const QString file_path = + child->data(GameListItemPath::FullPathRole).toString().toLower(); + const QString file_title = + child->data(GameListItemPath::TitleRole).toString().toLower(); + const QString file_program_id = + QStringLiteral("%1").arg(program_id, 16, 16, QLatin1Char{'0'}); + + // Only items which filename in combination with its title contains all words + // that are in the searchfield will be visible in the gamelist + // The search is case insensitive because of toLower() + // I decided not to use Qt::CaseInsensitive in containsAllWords to prevent + // multiple conversions of edit_filter_text for each game in the gamelist + const QString file_name = + file_path.mid(file_path.lastIndexOf(QLatin1Char{'/'}) + 1) + QLatin1Char{' '} + + file_title; + if (ContainsAllWords(file_name, edit_filter_text) || + (file_program_id.count() == 16 && file_program_id.contains(edit_filter_text))) { + tree_view->setRowHidden(j, folder_index, false); + ++result_count; + } else { + tree_view->setRowHidden(j, folder_index, true); + } + } + } + search_field->setFilterResult(result_count, children_total); + } +} + +void GameList::OnUpdateThemedIcons() { + for (int i = 0; i < item_model->invisibleRootItem()->rowCount(); i++) { + QStandardItem* child = item_model->invisibleRootItem()->child(i); + + const int icon_size = UISettings::values.folder_icon_size.GetValue(); + + switch (child->data(GameListItem::TypeRole).value()) { + case GameListItemType::SdmcDir: + child->setData( + QIcon::fromTheme(QStringLiteral("sd_card")) + .pixmap(icon_size) + .scaled(icon_size, icon_size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation), + Qt::DecorationRole); + break; + case GameListItemType::UserNandDir: + child->setData( + QIcon::fromTheme(QStringLiteral("chip")) + .pixmap(icon_size) + .scaled(icon_size, icon_size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation), + Qt::DecorationRole); + break; + case GameListItemType::SysNandDir: + child->setData( + QIcon::fromTheme(QStringLiteral("chip")) + .pixmap(icon_size) + .scaled(icon_size, icon_size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation), + Qt::DecorationRole); + break; + case GameListItemType::CustomDir: { + const UISettings::GameDir& game_dir = + UISettings::values.game_dirs[child->data(GameListDir::GameDirRole).toInt()]; + const QString icon_name = QFileInfo::exists(QString::fromStdString(game_dir.path)) + ? QStringLiteral("folder") + : QStringLiteral("bad_folder"); + child->setData( + QIcon::fromTheme(icon_name).pixmap(icon_size).scaled( + icon_size, icon_size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation), + Qt::DecorationRole); + break; + } + case GameListItemType::AddDir: + child->setData( + QIcon::fromTheme(QStringLiteral("list-add")) + .pixmap(icon_size) + .scaled(icon_size, icon_size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation), + Qt::DecorationRole); + break; + case GameListItemType::Favorites: + child->setData( + QIcon::fromTheme(QStringLiteral("star")) + .pixmap(icon_size) + .scaled(icon_size, icon_size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation), + Qt::DecorationRole); + break; + default: + break; + } + } +} + +void GameList::OnFilterCloseClicked() { + main_window->filterBarSetChecked(false); +} + +GameList::GameList(FileSys::VirtualFilesystem vfs_, FileSys::ManualContentProvider* provider_, + PlayTime::PlayTimeManager& play_time_manager_, Core::System& system_, + GMainWindow* parent) + : QWidget{parent}, vfs{std::move(vfs_)}, provider{provider_}, + play_time_manager{play_time_manager_}, system{system_} { + watcher = new QFileSystemWatcher(this); + connect(watcher, &QFileSystemWatcher::directoryChanged, this, &GameList::RefreshGameDirectory); + + this->main_window = parent; + layout = new QVBoxLayout; + tree_view = new QTreeView; + controller_navigation = new ControllerNavigation(system.HIDCore(), this); + search_field = new GameListSearchField(this); + item_model = new QStandardItemModel(tree_view); + tree_view->setModel(item_model); + + tree_view->setAlternatingRowColors(true); + tree_view->setSelectionMode(QHeaderView::SingleSelection); + tree_view->setSelectionBehavior(QHeaderView::SelectRows); + tree_view->setVerticalScrollMode(QHeaderView::ScrollPerPixel); + tree_view->setHorizontalScrollMode(QHeaderView::ScrollPerPixel); + tree_view->setSortingEnabled(true); + tree_view->setEditTriggers(QHeaderView::NoEditTriggers); + tree_view->setContextMenuPolicy(Qt::CustomContextMenu); + tree_view->setStyleSheet(QStringLiteral("QTreeView{ border: none; }")); + + item_model->insertColumns(0, COLUMN_COUNT); + RetranslateUI(); + + tree_view->setColumnHidden(COLUMN_ADD_ONS, !UISettings::values.show_add_ons); + tree_view->setColumnHidden(COLUMN_COMPATIBILITY, !UISettings::values.show_compat); + tree_view->setColumnHidden(COLUMN_PLAY_TIME, !UISettings::values.show_play_time); + item_model->setSortRole(GameListItemPath::SortRole); + + connect(main_window, &GMainWindow::UpdateThemedIcons, this, &GameList::OnUpdateThemedIcons); + connect(tree_view, &QTreeView::activated, this, &GameList::ValidateEntry); + connect(tree_view, &QTreeView::customContextMenuRequested, this, &GameList::PopupContextMenu); + connect(tree_view, &QTreeView::expanded, this, &GameList::OnItemExpanded); + connect(tree_view, &QTreeView::collapsed, this, &GameList::OnItemExpanded); + connect(controller_navigation, &ControllerNavigation::TriggerKeyboardEvent, + [this](Qt::Key key) { + // Avoid pressing buttons while playing + if (system.IsPoweredOn()) { + return; + } + if (!this->isActiveWindow()) { + return; + } + QKeyEvent* event = new QKeyEvent(QEvent::KeyPress, key, Qt::NoModifier); + QCoreApplication::postEvent(tree_view, event); + }); + + // We must register all custom types with the Qt Automoc system so that we are able to use + // it with signals/slots. In this case, QList falls under the umbrells of custom types. + qRegisterMetaType>("QList"); + + layout->setContentsMargins(0, 0, 0, 0); + layout->setSpacing(0); + layout->addWidget(tree_view); + layout->addWidget(search_field); + setLayout(layout); +} + +void GameList::UnloadController() { + controller_navigation->UnloadController(); +} + +GameList::~GameList() { + UnloadController(); +} + +void GameList::SetFilterFocus() { + if (tree_view->model()->rowCount() > 0) { + search_field->setFocus(); + } +} + +void GameList::SetFilterVisible(bool visibility) { + search_field->setVisible(visibility); +} + +void GameList::ClearFilter() { + search_field->clear(); +} + +void GameList::WorkerEvent() { + current_worker->ProcessEvents(this); +} + +void GameList::AddDirEntry(GameListDir* entry_items) { + item_model->invisibleRootItem()->appendRow(entry_items); + tree_view->setExpanded( + entry_items->index(), + UISettings::values.game_dirs[entry_items->data(GameListDir::GameDirRole).toInt()].expanded); +} + +void GameList::AddEntry(const QList& entry_items, GameListDir* parent) { + parent->appendRow(entry_items); +} + +void GameList::ValidateEntry(const QModelIndex& item) { + const auto selected = item.sibling(item.row(), 0); + + switch (selected.data(GameListItem::TypeRole).value()) { + case GameListItemType::Game: { + const QString file_path = selected.data(GameListItemPath::FullPathRole).toString(); + if (file_path.isEmpty()) + return; + const QFileInfo file_info(file_path); + if (!file_info.exists()) + return; + + if (file_info.isDir()) { + const QDir dir{file_path}; + const QStringList matching_main = dir.entryList({QStringLiteral("main")}, QDir::Files); + if (matching_main.size() == 1) { + emit GameChosen(dir.path() + QDir::separator() + matching_main[0]); + } + return; + } + + const auto title_id = selected.data(GameListItemPath::ProgramIdRole).toULongLong(); + + // Users usually want to run a different game after closing one + search_field->clear(); + emit GameChosen(file_path, title_id); + break; + } + case GameListItemType::AddDir: + emit AddDirectory(); + break; + default: + break; + } +} + +bool GameList::IsEmpty() const { + for (int i = 0; i < item_model->rowCount(); i++) { + const QStandardItem* child = item_model->invisibleRootItem()->child(i); + const auto type = static_cast(child->type()); + + if (!child->hasChildren() && + (type == GameListItemType::SdmcDir || type == GameListItemType::UserNandDir || + type == GameListItemType::SysNandDir)) { + item_model->invisibleRootItem()->removeRow(child->row()); + i--; + } + } + + return !item_model->invisibleRootItem()->hasChildren(); +} + +void GameList::DonePopulating(const QStringList& watch_list) { + emit ShowList(!IsEmpty()); + + item_model->invisibleRootItem()->appendRow(new GameListAddDir()); + + // Add favorites row + item_model->invisibleRootItem()->insertRow(0, new GameListFavorites()); + tree_view->setRowHidden(0, item_model->invisibleRootItem()->index(), + UISettings::values.favorited_ids.size() == 0); + tree_view->setExpanded(item_model->invisibleRootItem()->child(0)->index(), + UISettings::values.favorites_expanded.GetValue()); + for (const auto id : UISettings::values.favorited_ids) { + AddFavorite(id); + } + + // Clear out the old directories to watch for changes and add the new ones + auto watch_dirs = watcher->directories(); + if (!watch_dirs.isEmpty()) { + watcher->removePaths(watch_dirs); + } + // Workaround: Add the watch paths in chunks to allow the gui to refresh + // This prevents the UI from stalling when a large number of watch paths are added + // Also artificially caps the watcher to a certain number of directories + constexpr int LIMIT_WATCH_DIRECTORIES = 5000; + constexpr int SLICE_SIZE = 25; + int len = std::min(static_cast(watch_list.size()), LIMIT_WATCH_DIRECTORIES); + for (int i = 0; i < len; i += SLICE_SIZE) { + watcher->addPaths(watch_list.mid(i, i + SLICE_SIZE)); + QCoreApplication::processEvents(); + } + tree_view->setEnabled(true); + int children_total = 0; + for (int i = 1; i < item_model->rowCount() - 1; ++i) { + children_total += item_model->item(i, 0)->rowCount(); + } + search_field->setFilterResult(children_total, children_total); + if (children_total > 0) { + search_field->setFocus(); + } + item_model->sort(tree_view->header()->sortIndicatorSection(), + tree_view->header()->sortIndicatorOrder()); + + emit PopulatingCompleted(); +} + +void GameList::PopupContextMenu(const QPoint& menu_location) { + QModelIndex item = tree_view->indexAt(menu_location); + if (!item.isValid()) + return; + + const auto selected = item.sibling(item.row(), 0); + QMenu context_menu; + switch (selected.data(GameListItem::TypeRole).value()) { + case GameListItemType::Game: + AddGamePopup(context_menu, selected.data(GameListItemPath::ProgramIdRole).toULongLong(), + selected.data(GameListItemPath::FullPathRole).toString().toStdString()); + break; + case GameListItemType::CustomDir: + AddPermDirPopup(context_menu, selected); + AddCustomDirPopup(context_menu, selected); + break; + case GameListItemType::SdmcDir: + case GameListItemType::UserNandDir: + case GameListItemType::SysNandDir: + AddPermDirPopup(context_menu, selected); + break; + case GameListItemType::Favorites: + AddFavoritesPopup(context_menu); + break; + default: + break; + } + context_menu.exec(tree_view->viewport()->mapToGlobal(menu_location)); +} + +void GameList::AddGamePopup(QMenu& context_menu, u64 program_id, const std::string& path) { + QAction* favorite = context_menu.addAction(tr("Favorite")); + context_menu.addSeparator(); + QAction* start_game = context_menu.addAction(tr("Start Game")); + QAction* start_game_global = + context_menu.addAction(tr("Start Game without Custom Configuration")); + context_menu.addSeparator(); + QAction* open_save_location = context_menu.addAction(tr("Open Save Data Location")); + QAction* open_mod_location = context_menu.addAction(tr("Open Mod Data Location")); + QAction* open_transferable_shader_cache = + context_menu.addAction(tr("Open Transferable Pipeline Cache")); + context_menu.addSeparator(); + QMenu* remove_menu = context_menu.addMenu(tr("Remove")); + QAction* remove_update = remove_menu->addAction(tr("Remove Installed Update")); + QAction* remove_dlc = remove_menu->addAction(tr("Remove All Installed DLC")); + QAction* remove_custom_config = remove_menu->addAction(tr("Remove Custom Configuration")); + QAction* remove_play_time_data = remove_menu->addAction(tr("Remove Play Time Data")); + QAction* remove_cache_storage = remove_menu->addAction(tr("Remove Cache Storage")); + QAction* remove_gl_shader_cache = remove_menu->addAction(tr("Remove OpenGL Pipeline Cache")); + QAction* remove_vk_shader_cache = remove_menu->addAction(tr("Remove Vulkan Pipeline Cache")); + remove_menu->addSeparator(); + QAction* remove_shader_cache = remove_menu->addAction(tr("Remove All Pipeline Caches")); + QAction* remove_all_content = remove_menu->addAction(tr("Remove All Installed Contents")); + QMenu* dump_romfs_menu = context_menu.addMenu(tr("Dump RomFS")); + QAction* dump_romfs = dump_romfs_menu->addAction(tr("Dump RomFS")); + QAction* dump_romfs_sdmc = dump_romfs_menu->addAction(tr("Dump RomFS to SDMC")); + QAction* verify_integrity = context_menu.addAction(tr("Verify Integrity")); + QAction* copy_tid = context_menu.addAction(tr("Copy Title ID to Clipboard")); + QAction* navigate_to_gamedb_entry = context_menu.addAction(tr("Navigate to GameDB entry")); +// TODO: Implement shortcut creation for macOS +#if !defined(__APPLE__) + QMenu* shortcut_menu = context_menu.addMenu(tr("Create Shortcut")); + QAction* create_desktop_shortcut = shortcut_menu->addAction(tr("Add to Desktop")); + QAction* create_applications_menu_shortcut = + shortcut_menu->addAction(tr("Add to Applications Menu")); +#endif + context_menu.addSeparator(); + QAction* properties = context_menu.addAction(tr("Properties")); + + favorite->setVisible(program_id != 0); + favorite->setCheckable(true); + favorite->setChecked(UISettings::values.favorited_ids.contains(program_id)); + open_save_location->setVisible(program_id != 0); + open_mod_location->setVisible(program_id != 0); + open_transferable_shader_cache->setVisible(program_id != 0); + remove_update->setVisible(program_id != 0); + remove_dlc->setVisible(program_id != 0); + remove_gl_shader_cache->setVisible(program_id != 0); + remove_vk_shader_cache->setVisible(program_id != 0); + remove_shader_cache->setVisible(program_id != 0); + remove_all_content->setVisible(program_id != 0); + auto it = FindMatchingCompatibilityEntry(compatibility_list, program_id); + navigate_to_gamedb_entry->setVisible(it != compatibility_list.end() && program_id != 0); + + connect(favorite, &QAction::triggered, [this, program_id]() { ToggleFavorite(program_id); }); + connect(open_save_location, &QAction::triggered, [this, program_id, path]() { + emit OpenFolderRequested(program_id, GameListOpenTarget::SaveData, path); + }); + connect(start_game, &QAction::triggered, + [this, path]() { emit BootGame(QString::fromStdString(path), StartGameType::Normal); }); + connect(start_game_global, &QAction::triggered, + [this, path]() { emit BootGame(QString::fromStdString(path), StartGameType::Global); }); + connect(open_mod_location, &QAction::triggered, [this, program_id, path]() { + emit OpenFolderRequested(program_id, GameListOpenTarget::ModData, path); + }); + connect(open_transferable_shader_cache, &QAction::triggered, + [this, program_id]() { emit OpenTransferableShaderCacheRequested(program_id); }); + connect(remove_all_content, &QAction::triggered, [this, program_id]() { + emit RemoveInstalledEntryRequested(program_id, InstalledEntryType::Game); + }); + connect(remove_update, &QAction::triggered, [this, program_id]() { + emit RemoveInstalledEntryRequested(program_id, InstalledEntryType::Update); + }); + connect(remove_dlc, &QAction::triggered, [this, program_id]() { + emit RemoveInstalledEntryRequested(program_id, InstalledEntryType::AddOnContent); + }); + connect(remove_gl_shader_cache, &QAction::triggered, [this, program_id, path]() { + emit RemoveFileRequested(program_id, GameListRemoveTarget::GlShaderCache, path); + }); + connect(remove_vk_shader_cache, &QAction::triggered, [this, program_id, path]() { + emit RemoveFileRequested(program_id, GameListRemoveTarget::VkShaderCache, path); + }); + connect(remove_shader_cache, &QAction::triggered, [this, program_id, path]() { + emit RemoveFileRequested(program_id, GameListRemoveTarget::AllShaderCache, path); + }); + connect(remove_custom_config, &QAction::triggered, [this, program_id, path]() { + emit RemoveFileRequested(program_id, GameListRemoveTarget::CustomConfiguration, path); + }); + connect(remove_play_time_data, &QAction::triggered, + [this, program_id]() { emit RemovePlayTimeRequested(program_id); }); + connect(remove_cache_storage, &QAction::triggered, [this, program_id, path] { + emit RemoveFileRequested(program_id, GameListRemoveTarget::CacheStorage, path); + }); + connect(dump_romfs, &QAction::triggered, [this, program_id, path]() { + emit DumpRomFSRequested(program_id, path, DumpRomFSTarget::Normal); + }); + connect(dump_romfs_sdmc, &QAction::triggered, [this, program_id, path]() { + emit DumpRomFSRequested(program_id, path, DumpRomFSTarget::SDMC); + }); + connect(verify_integrity, &QAction::triggered, + [this, path]() { emit VerifyIntegrityRequested(path); }); + connect(copy_tid, &QAction::triggered, + [this, program_id]() { emit CopyTIDRequested(program_id); }); + connect(navigate_to_gamedb_entry, &QAction::triggered, [this, program_id]() { + emit NavigateToGamedbEntryRequested(program_id, compatibility_list); + }); +// TODO: Implement shortcut creation for macOS +#if !defined(__APPLE__) + connect(create_desktop_shortcut, &QAction::triggered, [this, program_id, path]() { + emit CreateShortcut(program_id, path, GameListShortcutTarget::Desktop); + }); + connect(create_applications_menu_shortcut, &QAction::triggered, [this, program_id, path]() { + emit CreateShortcut(program_id, path, GameListShortcutTarget::Applications); + }); +#endif + connect(properties, &QAction::triggered, + [this, path]() { emit OpenPerGameGeneralRequested(path); }); +}; + +void GameList::AddCustomDirPopup(QMenu& context_menu, QModelIndex selected) { + UISettings::GameDir& game_dir = + UISettings::values.game_dirs[selected.data(GameListDir::GameDirRole).toInt()]; + + QAction* deep_scan = context_menu.addAction(tr("Scan Subfolders")); + QAction* delete_dir = context_menu.addAction(tr("Remove Game Directory")); + + deep_scan->setCheckable(true); + deep_scan->setChecked(game_dir.deep_scan); + + connect(deep_scan, &QAction::triggered, [this, &game_dir] { + game_dir.deep_scan = !game_dir.deep_scan; + PopulateAsync(UISettings::values.game_dirs); + }); + connect(delete_dir, &QAction::triggered, [this, &game_dir, selected] { + UISettings::values.game_dirs.removeOne(game_dir); + item_model->invisibleRootItem()->removeRow(selected.row()); + OnTextChanged(search_field->filterText()); + }); +} + +void GameList::AddPermDirPopup(QMenu& context_menu, QModelIndex selected) { + const int game_dir_index = selected.data(GameListDir::GameDirRole).toInt(); + + QAction* move_up = context_menu.addAction(tr("\u25B2 Move Up")); + QAction* move_down = context_menu.addAction(tr("\u25bc Move Down")); + QAction* open_directory_location = context_menu.addAction(tr("Open Directory Location")); + + const int row = selected.row(); + + move_up->setEnabled(row > 1); + move_down->setEnabled(row < item_model->rowCount() - 2); + + connect(move_up, &QAction::triggered, [this, selected, row, game_dir_index] { + const int other_index = selected.sibling(row - 1, 0).data(GameListDir::GameDirRole).toInt(); + // swap the items in the settings + std::swap(UISettings::values.game_dirs[game_dir_index], + UISettings::values.game_dirs[other_index]); + // swap the indexes held by the QVariants + item_model->setData(selected, QVariant(other_index), GameListDir::GameDirRole); + item_model->setData(selected.sibling(row - 1, 0), QVariant(game_dir_index), + GameListDir::GameDirRole); + // move the treeview items + QList item = item_model->takeRow(row); + item_model->invisibleRootItem()->insertRow(row - 1, item); + tree_view->setExpanded(selected.sibling(row - 1, 0), + UISettings::values.game_dirs[other_index].expanded); + }); + + connect(move_down, &QAction::triggered, [this, selected, row, game_dir_index] { + const int other_index = selected.sibling(row + 1, 0).data(GameListDir::GameDirRole).toInt(); + // swap the items in the settings + std::swap(UISettings::values.game_dirs[game_dir_index], + UISettings::values.game_dirs[other_index]); + // swap the indexes held by the QVariants + item_model->setData(selected, QVariant(other_index), GameListDir::GameDirRole); + item_model->setData(selected.sibling(row + 1, 0), QVariant(game_dir_index), + GameListDir::GameDirRole); + // move the treeview items + const QList item = item_model->takeRow(row); + item_model->invisibleRootItem()->insertRow(row + 1, item); + tree_view->setExpanded(selected.sibling(row + 1, 0), + UISettings::values.game_dirs[other_index].expanded); + }); + + connect(open_directory_location, &QAction::triggered, [this, game_dir_index] { + emit OpenDirectory( + QString::fromStdString(UISettings::values.game_dirs[game_dir_index].path)); + }); +} + +void GameList::AddFavoritesPopup(QMenu& context_menu) { + QAction* clear = context_menu.addAction(tr("Clear")); + + connect(clear, &QAction::triggered, [this] { + for (const auto id : UISettings::values.favorited_ids) { + RemoveFavorite(id); + } + UISettings::values.favorited_ids.clear(); + tree_view->setRowHidden(0, item_model->invisibleRootItem()->index(), true); + }); +} + +void GameList::LoadCompatibilityList() { + QFile compat_list{QStringLiteral(":compatibility_list/compatibility_list.json")}; + + if (!compat_list.open(QFile::ReadOnly | QFile::Text)) { + LOG_ERROR(Frontend, "Unable to open game compatibility list"); + return; + } + + if (compat_list.size() == 0) { + LOG_WARNING(Frontend, "Game compatibility list is empty"); + return; + } + + const QByteArray content = compat_list.readAll(); + if (content.isEmpty()) { + LOG_ERROR(Frontend, "Unable to completely read game compatibility list"); + return; + } + + const QJsonDocument json = QJsonDocument::fromJson(content); + const QJsonArray arr = json.array(); + + for (const QJsonValue value : arr) { + const QJsonObject game = value.toObject(); + const QString compatibility_key = QStringLiteral("compatibility"); + + if (!game.contains(compatibility_key) || !game[compatibility_key].isDouble()) { + continue; + } + + const int compatibility = game[compatibility_key].toInt(); + const QString directory = game[QStringLiteral("directory")].toString(); + const QJsonArray ids = game[QStringLiteral("releases")].toArray(); + + for (const QJsonValue id_ref : ids) { + const QJsonObject id_object = id_ref.toObject(); + const QString id = id_object[QStringLiteral("id")].toString(); + + compatibility_list.emplace(id.toUpper().toStdString(), + std::make_pair(QString::number(compatibility), directory)); + } + } +} + +void GameList::changeEvent(QEvent* event) { + if (event->type() == QEvent::LanguageChange) { + RetranslateUI(); + } + + QWidget::changeEvent(event); +} + +void GameList::RetranslateUI() { + item_model->setHeaderData(COLUMN_NAME, Qt::Horizontal, tr("Name")); + item_model->setHeaderData(COLUMN_COMPATIBILITY, Qt::Horizontal, tr("Compatibility")); + item_model->setHeaderData(COLUMN_ADD_ONS, Qt::Horizontal, tr("Add-ons")); + item_model->setHeaderData(COLUMN_FILE_TYPE, Qt::Horizontal, tr("File type")); + item_model->setHeaderData(COLUMN_SIZE, Qt::Horizontal, tr("Size")); + item_model->setHeaderData(COLUMN_PLAY_TIME, Qt::Horizontal, tr("Play time")); +} + +void GameListSearchField::changeEvent(QEvent* event) { + if (event->type() == QEvent::LanguageChange) { + RetranslateUI(); + } + + QWidget::changeEvent(event); +} + +void GameListSearchField::RetranslateUI() { + label_filter->setText(tr("Filter:")); + edit_filter->setPlaceholderText(tr("Enter pattern to filter")); +} + +QStandardItemModel* GameList::GetModel() const { + return item_model; +} + +void GameList::PopulateAsync(QVector& game_dirs) { + tree_view->setEnabled(false); + + // Update the columns in case UISettings has changed + tree_view->setColumnHidden(COLUMN_ADD_ONS, !UISettings::values.show_add_ons); + tree_view->setColumnHidden(COLUMN_COMPATIBILITY, !UISettings::values.show_compat); + tree_view->setColumnHidden(COLUMN_FILE_TYPE, !UISettings::values.show_types); + tree_view->setColumnHidden(COLUMN_SIZE, !UISettings::values.show_size); + tree_view->setColumnHidden(COLUMN_PLAY_TIME, !UISettings::values.show_play_time); + + // Cancel any existing worker. + current_worker.reset(); + + // Delete any rows that might already exist if we're repopulating + item_model->removeRows(0, item_model->rowCount()); + search_field->clear(); + + current_worker = std::make_unique(vfs, provider, game_dirs, compatibility_list, + play_time_manager, system); + + // Get events from the worker as data becomes available + connect(current_worker.get(), &GameListWorker::DataAvailable, this, &GameList::WorkerEvent, + Qt::QueuedConnection); + + QThreadPool::globalInstance()->start(current_worker.get()); +} + +void GameList::SaveInterfaceLayout() { + UISettings::values.gamelist_header_state = tree_view->header()->saveState(); +} + +void GameList::LoadInterfaceLayout() { + auto* header = tree_view->header(); + + if (header->restoreState(UISettings::values.gamelist_header_state)) { + return; + } + + // We are using the name column to display icons and titles + // so make it as large as possible as default. + header->resizeSection(COLUMN_NAME, header->width()); +} + +const QStringList GameList::supported_file_extensions = { + QStringLiteral("nso"), QStringLiteral("nro"), QStringLiteral("nca"), + QStringLiteral("xci"), QStringLiteral("nsp"), QStringLiteral("kip")}; + +void GameList::RefreshGameDirectory() { + if (!UISettings::values.game_dirs.empty() && current_worker != nullptr) { + LOG_INFO(Frontend, "Change detected in the games directory. Reloading game list."); + PopulateAsync(UISettings::values.game_dirs); + } +} + +void GameList::ToggleFavorite(u64 program_id) { + if (!UISettings::values.favorited_ids.contains(program_id)) { + tree_view->setRowHidden(0, item_model->invisibleRootItem()->index(), + !search_field->filterText().isEmpty()); + UISettings::values.favorited_ids.append(program_id); + AddFavorite(program_id); + item_model->sort(tree_view->header()->sortIndicatorSection(), + tree_view->header()->sortIndicatorOrder()); + } else { + UISettings::values.favorited_ids.removeOne(program_id); + RemoveFavorite(program_id); + if (UISettings::values.favorited_ids.size() == 0) { + tree_view->setRowHidden(0, item_model->invisibleRootItem()->index(), true); + } + } + SaveConfig(); +} + +void GameList::AddFavorite(u64 program_id) { + auto* favorites_row = item_model->item(0); + + for (int i = 1; i < item_model->rowCount() - 1; i++) { + const auto* folder = item_model->item(i); + for (int j = 0; j < folder->rowCount(); j++) { + if (folder->child(j)->data(GameListItemPath::ProgramIdRole).toULongLong() == + program_id) { + QList list; + for (int k = 0; k < COLUMN_COUNT; k++) { + list.append(folder->child(j, k)->clone()); + } + list[0]->setData(folder->child(j)->data(GameListItem::SortRole), + GameListItem::SortRole); + list[0]->setText(folder->child(j)->data(Qt::DisplayRole).toString()); + + favorites_row->appendRow(list); + return; + } + } + } +} + +void GameList::RemoveFavorite(u64 program_id) { + auto* favorites_row = item_model->item(0); + + for (int i = 0; i < favorites_row->rowCount(); i++) { + const auto* game = favorites_row->child(i); + if (game->data(GameListItemPath::ProgramIdRole).toULongLong() == program_id) { + favorites_row->removeRow(i); + return; + } + } +} + +GameListPlaceholder::GameListPlaceholder(GMainWindow* parent) : QWidget{parent} { + connect(parent, &GMainWindow::UpdateThemedIcons, this, + &GameListPlaceholder::onUpdateThemedIcons); + + layout = new QVBoxLayout; + image = new QLabel; + text = new QLabel; + layout->setAlignment(Qt::AlignCenter); + image->setPixmap(QIcon::fromTheme(QStringLiteral("plus_folder")).pixmap(200)); + + RetranslateUI(); + QFont font = text->font(); + font.setPointSize(20); + text->setFont(font); + text->setAlignment(Qt::AlignHCenter); + image->setAlignment(Qt::AlignHCenter); + + layout->addWidget(image); + layout->addWidget(text); + setLayout(layout); +} + +GameListPlaceholder::~GameListPlaceholder() = default; + +void GameListPlaceholder::onUpdateThemedIcons() { + image->setPixmap(QIcon::fromTheme(QStringLiteral("plus_folder")).pixmap(200)); +} + +void GameListPlaceholder::mouseDoubleClickEvent(QMouseEvent* event) { + emit GameListPlaceholder::AddDirectory(); +} + +void GameListPlaceholder::changeEvent(QEvent* event) { + if (event->type() == QEvent::LanguageChange) { + RetranslateUI(); + } + + QWidget::changeEvent(event); +} + +void GameListPlaceholder::RetranslateUI() { + text->setText(tr("Double-click to add a new folder to the game list")); +} diff --git a/src/sudachi/game_list.h b/src/sudachi/game_list.h new file mode 100644 index 0000000..3135e91 --- /dev/null +++ b/src/sudachi/game_list.h @@ -0,0 +1,204 @@ +// SPDX-FileCopyrightText: 2015 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "common/common_types.h" +#include "core/core.h" +#include "uisettings.h" +#include "sudachi/compatibility_list.h" +#include "sudachi/play_time_manager.h" + +namespace Core { +class System; +} + +class ControllerNavigation; +class GameListWorker; +class GameListSearchField; +class GameListDir; +class GMainWindow; +enum class AmLaunchType; +enum class StartGameType; + +namespace FileSys { +class ManualContentProvider; +class VfsFilesystem; +} // namespace FileSys + +enum class GameListOpenTarget { + SaveData, + ModData, +}; + +enum class GameListRemoveTarget { + GlShaderCache, + VkShaderCache, + AllShaderCache, + CustomConfiguration, + CacheStorage, +}; + +enum class DumpRomFSTarget { + Normal, + SDMC, +}; + +enum class GameListShortcutTarget { + Desktop, + Applications, +}; + +enum class InstalledEntryType { + Game, + Update, + AddOnContent, +}; + +class GameList : public QWidget { + Q_OBJECT + +public: + enum { + COLUMN_NAME, + COLUMN_COMPATIBILITY, + COLUMN_ADD_ONS, + COLUMN_FILE_TYPE, + COLUMN_SIZE, + COLUMN_PLAY_TIME, + COLUMN_COUNT, // Number of columns + }; + + explicit GameList(std::shared_ptr vfs_, + FileSys::ManualContentProvider* provider_, + PlayTime::PlayTimeManager& play_time_manager_, Core::System& system_, + GMainWindow* parent = nullptr); + ~GameList() override; + + QString GetLastFilterResultItem() const; + void ClearFilter(); + void SetFilterFocus(); + void SetFilterVisible(bool visibility); + bool IsEmpty() const; + + void LoadCompatibilityList(); + void PopulateAsync(QVector& game_dirs); + + void SaveInterfaceLayout(); + void LoadInterfaceLayout(); + + QStandardItemModel* GetModel() const; + + /// Disables events from the emulated controller + void UnloadController(); + + static const QStringList supported_file_extensions; + +signals: + void BootGame(const QString& game_path, StartGameType type); + void GameChosen(const QString& game_path, const u64 title_id = 0); + void OpenFolderRequested(u64 program_id, GameListOpenTarget target, + const std::string& game_path); + void OpenTransferableShaderCacheRequested(u64 program_id); + void RemoveInstalledEntryRequested(u64 program_id, InstalledEntryType type); + void RemoveFileRequested(u64 program_id, GameListRemoveTarget target, + const std::string& game_path); + void RemovePlayTimeRequested(u64 program_id); + void DumpRomFSRequested(u64 program_id, const std::string& game_path, DumpRomFSTarget target); + void VerifyIntegrityRequested(const std::string& game_path); + void CopyTIDRequested(u64 program_id); + void CreateShortcut(u64 program_id, const std::string& game_path, + GameListShortcutTarget target); + void NavigateToGamedbEntryRequested(u64 program_id, + const CompatibilityList& compatibility_list); + void OpenPerGameGeneralRequested(const std::string& file); + void OpenDirectory(const QString& directory); + void AddDirectory(); + void ShowList(bool show); + void PopulatingCompleted(); + void SaveConfig(); + +private slots: + void OnItemExpanded(const QModelIndex& item); + void OnTextChanged(const QString& new_text); + void OnFilterCloseClicked(); + void OnUpdateThemedIcons(); + +private: + friend class GameListWorker; + void WorkerEvent(); + + void AddDirEntry(GameListDir* entry_items); + void AddEntry(const QList& entry_items, GameListDir* parent); + void DonePopulating(const QStringList& watch_list); + +private: + void ValidateEntry(const QModelIndex& item); + + void RefreshGameDirectory(); + + void ToggleFavorite(u64 program_id); + void AddFavorite(u64 program_id); + void RemoveFavorite(u64 program_id); + + void PopupContextMenu(const QPoint& menu_location); + void AddGamePopup(QMenu& context_menu, u64 program_id, const std::string& path); + void AddCustomDirPopup(QMenu& context_menu, QModelIndex selected); + void AddPermDirPopup(QMenu& context_menu, QModelIndex selected); + void AddFavoritesPopup(QMenu& context_menu); + + void changeEvent(QEvent*) override; + void RetranslateUI(); + + std::shared_ptr vfs; + FileSys::ManualContentProvider* provider; + GameListSearchField* search_field; + GMainWindow* main_window = nullptr; + QVBoxLayout* layout = nullptr; + QTreeView* tree_view = nullptr; + QStandardItemModel* item_model = nullptr; + std::unique_ptr current_worker; + QFileSystemWatcher* watcher = nullptr; + ControllerNavigation* controller_navigation = nullptr; + CompatibilityList compatibility_list; + + friend class GameListSearchField; + + const PlayTime::PlayTimeManager& play_time_manager; + Core::System& system; +}; + +class GameListPlaceholder : public QWidget { + Q_OBJECT +public: + explicit GameListPlaceholder(GMainWindow* parent = nullptr); + ~GameListPlaceholder(); + +signals: + void AddDirectory(); + +private slots: + void onUpdateThemedIcons(); + +protected: + void mouseDoubleClickEvent(QMouseEvent* event) override; + +private: + void changeEvent(QEvent* event) override; + void RetranslateUI(); + + QVBoxLayout* layout = nullptr; + QLabel* image = nullptr; + QLabel* text = nullptr; +}; diff --git a/src/sudachi/game_list_p.h b/src/sudachi/game_list_p.h new file mode 100644 index 0000000..e57539a --- /dev/null +++ b/src/sudachi/game_list_p.h @@ -0,0 +1,408 @@ +// SPDX-FileCopyrightText: 2015 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "common/common_types.h" +#include "common/logging/log.h" +#include "common/string_util.h" +#include "sudachi/play_time_manager.h" +#include "sudachi/uisettings.h" +#include "sudachi/util/util.h" + +enum class GameListItemType { + Game = QStandardItem::UserType + 1, + CustomDir = QStandardItem::UserType + 2, + SdmcDir = QStandardItem::UserType + 3, + UserNandDir = QStandardItem::UserType + 4, + SysNandDir = QStandardItem::UserType + 5, + AddDir = QStandardItem::UserType + 6, + Favorites = QStandardItem::UserType + 7, +}; + +Q_DECLARE_METATYPE(GameListItemType); + +/** + * Gets the default icon (for games without valid title metadata) + * @param size The desired width and height of the default icon. + * @return QPixmap default icon + */ +static QPixmap GetDefaultIcon(u32 size) { + QPixmap icon(size, size); + icon.fill(Qt::transparent); + return icon; +} + +class GameListItem : public QStandardItem { + +public: + // used to access type from item index + static constexpr int TypeRole = Qt::UserRole + 1; + static constexpr int SortRole = Qt::UserRole + 2; + GameListItem() = default; + explicit GameListItem(const QString& string) : QStandardItem(string) { + setData(string, SortRole); + } +}; + +/** + * A specialization of GameListItem for path values. + * This class ensures that for every full path value it holds, a correct string representation + * of just the filename (with no extension) will be displayed to the user. + * If this class receives valid title metadata, it will also display game icons and titles. + */ +class GameListItemPath : public GameListItem { +public: + static constexpr int TitleRole = SortRole + 1; + static constexpr int FullPathRole = SortRole + 2; + static constexpr int ProgramIdRole = SortRole + 3; + static constexpr int FileTypeRole = SortRole + 4; + + GameListItemPath() = default; + GameListItemPath(const QString& game_path, const std::vector& picture_data, + const QString& game_name, const QString& game_type, u64 program_id) { + setData(type(), TypeRole); + setData(game_path, FullPathRole); + setData(game_name, TitleRole); + setData(qulonglong(program_id), ProgramIdRole); + setData(game_type, FileTypeRole); + + const u32 size = UISettings::values.game_icon_size.GetValue(); + + QPixmap picture; + if (!picture.loadFromData(picture_data.data(), static_cast(picture_data.size()))) { + picture = GetDefaultIcon(size); + } + picture = picture.scaled(size, size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); + + setData(picture, Qt::DecorationRole); + } + + int type() const override { + return static_cast(GameListItemType::Game); + } + + QVariant data(int role) const override { + if (role == Qt::DisplayRole || role == SortRole) { + std::string filename; + Common::SplitPath(data(FullPathRole).toString().toStdString(), nullptr, &filename, + nullptr); + + const std::array row_data{{ + QString::fromStdString(filename), + data(FileTypeRole).toString(), + QString::fromStdString(fmt::format("0x{:016X}", data(ProgramIdRole).toULongLong())), + data(TitleRole).toString(), + }}; + + const auto& row1 = row_data.at(UISettings::values.row_1_text_id.GetValue()); + const int row2_id = UISettings::values.row_2_text_id.GetValue(); + + if (role == SortRole) { + return row1.toLower(); + } + + // None + if (row2_id == 4) { + return row1; + } + + const auto& row2 = row_data.at(row2_id); + + if (row1 == row2) { + return row1; + } + + return QStringLiteral("%1\n %2").arg(row1, row2); + } + + return GameListItem::data(role); + } +}; + +class GameListItemCompat : public GameListItem { + Q_DECLARE_TR_FUNCTIONS(GameListItemCompat) +public: + static constexpr int CompatNumberRole = SortRole; + GameListItemCompat() = default; + explicit GameListItemCompat(const QString& compatibility) { + setData(type(), TypeRole); + + struct CompatStatus { + QString color; + const char* text; + const char* tooltip; + }; + // clang-format off + const auto ingame_status = + CompatStatus{QStringLiteral("#f2d624"), QT_TR_NOOP("Ingame"), QT_TR_NOOP("Game starts, but crashes or major glitches prevent it from being completed.")}; + static const std::map status_data = { + {QStringLiteral("0"), {QStringLiteral("#5c93ed"), QT_TR_NOOP("Perfect"), QT_TR_NOOP("Game can be played without issues.")}}, + {QStringLiteral("1"), {QStringLiteral("#47d35c"), QT_TR_NOOP("Playable"), QT_TR_NOOP("Game functions with minor graphical or audio glitches and is playable from start to finish.")}}, + {QStringLiteral("2"), ingame_status}, + {QStringLiteral("3"), ingame_status}, // Fallback for the removed "Okay" category + {QStringLiteral("4"), {QStringLiteral("#FF0000"), QT_TR_NOOP("Intro/Menu"), QT_TR_NOOP("Game loads, but is unable to progress past the Start Screen.")}}, + {QStringLiteral("5"), {QStringLiteral("#828282"), QT_TR_NOOP("Won't Boot"), QT_TR_NOOP("The game crashes when attempting to startup.")}}, + {QStringLiteral("99"), {QStringLiteral("#000000"), QT_TR_NOOP("Not Tested"), QT_TR_NOOP("The game has not yet been tested.")}}, + }; + // clang-format on + + auto iterator = status_data.find(compatibility); + if (iterator == status_data.end()) { + LOG_WARNING(Frontend, "Invalid compatibility number {}", compatibility.toStdString()); + return; + } + const CompatStatus& status = iterator->second; + setData(compatibility, CompatNumberRole); + setText(tr(status.text)); + setToolTip(tr(status.tooltip)); + setData(CreateCirclePixmapFromColor(status.color), Qt::DecorationRole); + } + + int type() const override { + return static_cast(GameListItemType::Game); + } + + bool operator<(const QStandardItem& other) const override { + return data(CompatNumberRole).value() < + other.data(CompatNumberRole).value(); + } +}; + +/** + * A specialization of GameListItem for size values. + * This class ensures that for every numerical size value it holds (in bytes), a correct + * human-readable string representation will be displayed to the user. + */ +class GameListItemSize : public GameListItem { +public: + static constexpr int SizeRole = SortRole; + + GameListItemSize() = default; + explicit GameListItemSize(const qulonglong size_bytes) { + setData(type(), TypeRole); + setData(size_bytes, SizeRole); + } + + void setData(const QVariant& value, int role) override { + // By specializing setData for SizeRole, we can ensure that the numerical and string + // representations of the data are always accurate and in the correct format. + if (role == SizeRole) { + qulonglong size_bytes = value.toULongLong(); + GameListItem::setData(ReadableByteSize(size_bytes), Qt::DisplayRole); + GameListItem::setData(value, SizeRole); + } else { + GameListItem::setData(value, role); + } + } + + int type() const override { + return static_cast(GameListItemType::Game); + } + + /** + * This operator is, in practice, only used by the TreeView sorting systems. + * Override it so that it will correctly sort by numerical value instead of by string + * representation. + */ + bool operator<(const QStandardItem& other) const override { + return data(SizeRole).toULongLong() < other.data(SizeRole).toULongLong(); + } +}; + +/** + * GameListItem for Play Time values. + * This object stores the play time of a game in seconds, and its readable + * representation in minutes/hours + */ +class GameListItemPlayTime : public GameListItem { +public: + static constexpr int PlayTimeRole = SortRole; + + GameListItemPlayTime() = default; + explicit GameListItemPlayTime(const qulonglong time_seconds) { + setData(time_seconds, PlayTimeRole); + } + + void setData(const QVariant& value, int role) override { + qulonglong time_seconds = value.toULongLong(); + GameListItem::setData(PlayTime::ReadablePlayTime(time_seconds), Qt::DisplayRole); + GameListItem::setData(value, PlayTimeRole); + } + + bool operator<(const QStandardItem& other) const override { + return data(PlayTimeRole).toULongLong() < other.data(PlayTimeRole).toULongLong(); + } +}; + +class GameListDir : public GameListItem { +public: + static constexpr int GameDirRole = Qt::UserRole + 2; + + explicit GameListDir(UISettings::GameDir& directory, + GameListItemType dir_type_ = GameListItemType::CustomDir) + : dir_type{dir_type_} { + setData(type(), TypeRole); + + UISettings::GameDir* game_dir = &directory; + setData(QVariant(UISettings::values.game_dirs.indexOf(directory)), GameDirRole); + + const int icon_size = UISettings::values.folder_icon_size.GetValue(); + switch (dir_type) { + case GameListItemType::SdmcDir: + setData( + QIcon::fromTheme(QStringLiteral("sd_card")) + .pixmap(icon_size) + .scaled(icon_size, icon_size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation), + Qt::DecorationRole); + setData(QObject::tr("Installed SD Titles"), Qt::DisplayRole); + break; + case GameListItemType::UserNandDir: + setData( + QIcon::fromTheme(QStringLiteral("chip")) + .pixmap(icon_size) + .scaled(icon_size, icon_size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation), + Qt::DecorationRole); + setData(QObject::tr("Installed NAND Titles"), Qt::DisplayRole); + break; + case GameListItemType::SysNandDir: + setData( + QIcon::fromTheme(QStringLiteral("chip")) + .pixmap(icon_size) + .scaled(icon_size, icon_size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation), + Qt::DecorationRole); + setData(QObject::tr("System Titles"), Qt::DisplayRole); + break; + case GameListItemType::CustomDir: { + const QString path = QString::fromStdString(game_dir->path); + const QString icon_name = + QFileInfo::exists(path) ? QStringLiteral("folder") : QStringLiteral("bad_folder"); + setData(QIcon::fromTheme(icon_name).pixmap(icon_size).scaled( + icon_size, icon_size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation), + Qt::DecorationRole); + setData(path, Qt::DisplayRole); + break; + } + default: + break; + } + } + + int type() const override { + return static_cast(dir_type); + } + + /** + * Override to prevent automatic sorting between folders and the addDir button. + */ + bool operator<(const QStandardItem& other) const override { + return false; + } + +private: + GameListItemType dir_type; +}; + +class GameListAddDir : public GameListItem { +public: + explicit GameListAddDir() { + setData(type(), TypeRole); + + const int icon_size = UISettings::values.folder_icon_size.GetValue(); + + setData(QIcon::fromTheme(QStringLiteral("list-add")) + .pixmap(icon_size) + .scaled(icon_size, icon_size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation), + Qt::DecorationRole); + setData(QObject::tr("Add New Game Directory"), Qt::DisplayRole); + } + + int type() const override { + return static_cast(GameListItemType::AddDir); + } + + bool operator<(const QStandardItem& other) const override { + return false; + } +}; + +class GameListFavorites : public GameListItem { +public: + explicit GameListFavorites() { + setData(type(), TypeRole); + + const int icon_size = UISettings::values.folder_icon_size.GetValue(); + + setData(QIcon::fromTheme(QStringLiteral("star")) + .pixmap(icon_size) + .scaled(icon_size, icon_size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation), + Qt::DecorationRole); + setData(QObject::tr("Favorites"), Qt::DisplayRole); + } + + int type() const override { + return static_cast(GameListItemType::Favorites); + } + + bool operator<(const QStandardItem& other) const override { + return false; + } +}; + +class GameList; +class QHBoxLayout; +class QTreeView; +class QLabel; +class QLineEdit; +class QToolButton; + +class GameListSearchField : public QWidget { + Q_OBJECT + +public: + explicit GameListSearchField(GameList* parent = nullptr); + + QString filterText() const; + void setFilterResult(int visible_, int total_); + + void clear(); + void setFocus(); + +private: + void changeEvent(QEvent*) override; + void RetranslateUI(); + + class KeyReleaseEater : public QObject { + public: + explicit KeyReleaseEater(GameList* gamelist_, QObject* parent = nullptr); + + private: + GameList* gamelist = nullptr; + QString edit_filter_text_old; + + protected: + // EventFilter in order to process systemkeys while editing the searchfield + bool eventFilter(QObject* obj, QEvent* event) override; + }; + int visible; + int total; + + QHBoxLayout* layout_filter = nullptr; + QTreeView* tree_view = nullptr; + QLabel* label_filter = nullptr; + QLineEdit* edit_filter = nullptr; + QLabel* label_filter_result = nullptr; + QToolButton* button_filter_close = nullptr; +}; diff --git a/src/sudachi/game_list_worker.cpp b/src/sudachi/game_list_worker.cpp new file mode 100644 index 0000000..f127610 --- /dev/null +++ b/src/sudachi/game_list_worker.cpp @@ -0,0 +1,485 @@ +// SPDX-FileCopyrightText: Copyright 2018 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "common/fs/fs.h" +#include "common/fs/path_util.h" +#include "core/core.h" +#include "core/file_sys/card_image.h" +#include "core/file_sys/content_archive.h" +#include "core/file_sys/control_metadata.h" +#include "core/file_sys/fs_filesystem.h" +#include "core/file_sys/nca_metadata.h" +#include "core/file_sys/patch_manager.h" +#include "core/file_sys/registered_cache.h" +#include "core/file_sys/submission_package.h" +#include "core/loader/loader.h" +#include "sudachi/compatibility_list.h" +#include "sudachi/game_list.h" +#include "sudachi/game_list_p.h" +#include "sudachi/game_list_worker.h" +#include "sudachi/uisettings.h" + +namespace { + +QString GetGameListCachedObject(const std::string& filename, const std::string& ext, + const std::function& generator) { + if (!UISettings::values.cache_game_list || filename == "0000000000000000") { + return generator(); + } + + const auto path = + Common::FS::PathToUTF8String(Common::FS::GetSudachiPath(Common::FS::SudachiPath::CacheDir) / + "game_list" / fmt::format("{}.{}", filename, ext)); + + void(Common::FS::CreateParentDirs(path)); + + if (!Common::FS::Exists(path)) { + const auto str = generator(); + + QFile file{QString::fromStdString(path)}; + if (file.open(QFile::WriteOnly)) { + file.write(str.toUtf8()); + } + + return str; + } + + QFile file{QString::fromStdString(path)}; + if (file.open(QFile::ReadOnly)) { + return QString::fromUtf8(file.readAll()); + } + + return generator(); +} + +std::pair, std::string> GetGameListCachedObject( + const std::string& filename, const std::string& ext, + const std::function, std::string>()>& generator) { + if (!UISettings::values.cache_game_list || filename == "0000000000000000") { + return generator(); + } + + const auto game_list_dir = + Common::FS::GetSudachiPath(Common::FS::SudachiPath::CacheDir) / "game_list"; + const auto jpeg_name = fmt::format("{}.jpeg", filename); + const auto app_name = fmt::format("{}.appname.txt", filename); + + const auto path1 = Common::FS::PathToUTF8String(game_list_dir / jpeg_name); + const auto path2 = Common::FS::PathToUTF8String(game_list_dir / app_name); + + void(Common::FS::CreateParentDirs(path1)); + + if (!Common::FS::Exists(path1) || !Common::FS::Exists(path2)) { + const auto [icon, nacp] = generator(); + + QFile file1{QString::fromStdString(path1)}; + if (!file1.open(QFile::WriteOnly)) { + LOG_ERROR(Frontend, "Failed to open cache file."); + return generator(); + } + + if (!file1.resize(icon.size())) { + LOG_ERROR(Frontend, "Failed to resize cache file to necessary size."); + return generator(); + } + + if (file1.write(reinterpret_cast(icon.data()), icon.size()) != + s64(icon.size())) { + LOG_ERROR(Frontend, "Failed to write data to cache file."); + return generator(); + } + + QFile file2{QString::fromStdString(path2)}; + if (file2.open(QFile::WriteOnly)) { + file2.write(nacp.data(), nacp.size()); + } + + return std::make_pair(icon, nacp); + } + + QFile file1(QString::fromStdString(path1)); + QFile file2(QString::fromStdString(path2)); + + if (!file1.open(QFile::ReadOnly)) { + LOG_ERROR(Frontend, "Failed to open cache file for reading."); + return generator(); + } + + if (!file2.open(QFile::ReadOnly)) { + LOG_ERROR(Frontend, "Failed to open cache file for reading."); + return generator(); + } + + std::vector vec(file1.size()); + if (file1.read(reinterpret_cast(vec.data()), vec.size()) != + static_cast(vec.size())) { + return generator(); + } + + const auto data = file2.readAll(); + return std::make_pair(vec, data.toStdString()); +} + +void GetMetadataFromControlNCA(const FileSys::PatchManager& patch_manager, const FileSys::NCA& nca, + std::vector& icon, std::string& name) { + std::tie(icon, name) = GetGameListCachedObject( + fmt::format("{:016X}", patch_manager.GetTitleID()), {}, [&patch_manager, &nca] { + const auto [nacp, icon_f] = patch_manager.ParseControlNCA(nca); + return std::make_pair(icon_f->ReadAllBytes(), nacp->GetApplicationName()); + }); +} + +bool HasSupportedFileExtension(const std::string& file_name) { + const QFileInfo file = QFileInfo(QString::fromStdString(file_name)); + return GameList::supported_file_extensions.contains(file.suffix(), Qt::CaseInsensitive); +} + +bool IsExtractedNCAMain(const std::string& file_name) { + return QFileInfo(QString::fromStdString(file_name)).fileName() == QStringLiteral("main"); +} + +QString FormatGameName(const std::string& physical_name) { + const QString physical_name_as_qstring = QString::fromStdString(physical_name); + const QFileInfo file_info(physical_name_as_qstring); + + if (IsExtractedNCAMain(physical_name)) { + return file_info.dir().path(); + } + + return physical_name_as_qstring; +} + +QString FormatPatchNameVersions(const FileSys::PatchManager& patch_manager, + Loader::AppLoader& loader, bool updatable = true) { + QString out; + FileSys::VirtualFile update_raw; + loader.ReadUpdateRaw(update_raw); + for (const auto& patch : patch_manager.GetPatches(update_raw)) { + const bool is_update = patch.name == "Update"; + if (!updatable && is_update) { + continue; + } + + const QString type = + QString::fromStdString(patch.enabled ? patch.name : "[D] " + patch.name); + + if (patch.version.empty()) { + out.append(QStringLiteral("%1\n").arg(type)); + } else { + auto ver = patch.version; + + // Display container name for packed updates + if (is_update && ver == "PACKED") { + ver = Loader::GetFileTypeString(loader.GetFileType()); + } + + out.append(QStringLiteral("%1 (%2)\n").arg(type, QString::fromStdString(ver))); + } + } + + out.chop(1); + return out; +} + +QList MakeGameListEntry(const std::string& path, const std::string& name, + const std::size_t size, const std::vector& icon, + Loader::AppLoader& loader, u64 program_id, + const CompatibilityList& compatibility_list, + const PlayTime::PlayTimeManager& play_time_manager, + const FileSys::PatchManager& patch) { + const auto it = FindMatchingCompatibilityEntry(compatibility_list, program_id); + + // The game list uses this as compatibility number for untested games + QString compatibility{QStringLiteral("99")}; + if (it != compatibility_list.end()) { + compatibility = it->second.first; + } + + const auto file_type = loader.GetFileType(); + const auto file_type_string = QString::fromStdString(Loader::GetFileTypeString(file_type)); + + QList list{ + new GameListItemPath(FormatGameName(path), icon, QString::fromStdString(name), + file_type_string, program_id), + new GameListItemCompat(compatibility), + new GameListItem(file_type_string), + new GameListItemSize(size), + new GameListItemPlayTime(play_time_manager.GetPlayTime(program_id)), + }; + + const auto patch_versions = GetGameListCachedObject( + fmt::format("{:016X}", patch.GetTitleID()), "pv.txt", [&patch, &loader] { + return FormatPatchNameVersions(patch, loader, loader.IsRomFSUpdatable()); + }); + list.insert(2, new GameListItem(patch_versions)); + + return list; +} +} // Anonymous namespace + +GameListWorker::GameListWorker(FileSys::VirtualFilesystem vfs_, + FileSys::ManualContentProvider* provider_, + QVector& game_dirs_, + const CompatibilityList& compatibility_list_, + const PlayTime::PlayTimeManager& play_time_manager_, + Core::System& system_) + : vfs{std::move(vfs_)}, provider{provider_}, game_dirs{game_dirs_}, + compatibility_list{compatibility_list_}, play_time_manager{play_time_manager_}, system{ + system_} { + // We want the game list to manage our lifetime. + setAutoDelete(false); +} + +GameListWorker::~GameListWorker() { + this->disconnect(); + stop_requested.store(true); + processing_completed.Wait(); +} + +void GameListWorker::ProcessEvents(GameList* game_list) { + while (true) { + std::function func; + { + // Lock queue to protect concurrent modification. + std::scoped_lock lk(lock); + + // If we can't pop a function, return. + if (queued_events.empty()) { + return; + } + + // Pop a function. + func = std::move(queued_events.back()); + queued_events.pop_back(); + } + + // Run the function. + func(game_list); + } +} + +template +void GameListWorker::RecordEvent(F&& func) { + { + // Lock queue to protect concurrent modification. + std::scoped_lock lk(lock); + + // Add the function into the front of the queue. + queued_events.emplace_front(std::move(func)); + } + + // Data now available. + emit DataAvailable(); +} + +void GameListWorker::AddTitlesToGameList(GameListDir* parent_dir) { + using namespace FileSys; + + const auto& cache = system.GetContentProviderUnion(); + + auto installed_games = cache.ListEntriesFilterOrigin(std::nullopt, TitleType::Application, + ContentRecordType::Program); + + if (parent_dir->type() == static_cast(GameListItemType::SdmcDir)) { + installed_games = cache.ListEntriesFilterOrigin( + ContentProviderUnionSlot::SDMC, TitleType::Application, ContentRecordType::Program); + } else if (parent_dir->type() == static_cast(GameListItemType::UserNandDir)) { + installed_games = cache.ListEntriesFilterOrigin( + ContentProviderUnionSlot::UserNAND, TitleType::Application, ContentRecordType::Program); + } else if (parent_dir->type() == static_cast(GameListItemType::SysNandDir)) { + installed_games = cache.ListEntriesFilterOrigin( + ContentProviderUnionSlot::SysNAND, TitleType::Application, ContentRecordType::Program); + } + + for (const auto& [slot, game] : installed_games) { + if (slot == ContentProviderUnionSlot::FrontendManual) { + continue; + } + + const auto file = cache.GetEntryUnparsed(game.title_id, game.type); + std::unique_ptr loader = Loader::GetLoader(system, file); + if (!loader) { + continue; + } + + std::vector icon; + std::string name; + u64 program_id = 0; + const auto result = loader->ReadProgramId(program_id); + + if (result != Loader::ResultStatus::Success) { + continue; + } + + const PatchManager patch{program_id, system.GetFileSystemController(), + system.GetContentProvider()}; + const auto control = cache.GetEntry(game.title_id, ContentRecordType::Control); + if (control != nullptr) { + GetMetadataFromControlNCA(patch, *control, icon, name); + } + + auto entry = MakeGameListEntry(file->GetFullPath(), name, file->GetSize(), icon, *loader, + program_id, compatibility_list, play_time_manager, patch); + RecordEvent([=](GameList* game_list) { game_list->AddEntry(entry, parent_dir); }); + } +} + +void GameListWorker::ScanFileSystem(ScanTarget target, const std::string& dir_path, bool deep_scan, + GameListDir* parent_dir) { + const auto callback = [this, target, parent_dir](const std::filesystem::path& path) -> bool { + if (stop_requested) { + // Breaks the callback loop. + return false; + } + + const auto physical_name = Common::FS::PathToUTF8String(path); + const auto is_dir = Common::FS::IsDir(path); + + if (!is_dir && + (HasSupportedFileExtension(physical_name) || IsExtractedNCAMain(physical_name))) { + const auto file = vfs->OpenFile(physical_name, FileSys::OpenMode::Read); + if (!file) { + return true; + } + + auto loader = Loader::GetLoader(system, file); + if (!loader) { + return true; + } + + const auto file_type = loader->GetFileType(); + if (file_type == Loader::FileType::Unknown || file_type == Loader::FileType::Error) { + return true; + } + + u64 program_id = 0; + const auto res2 = loader->ReadProgramId(program_id); + + if (target == ScanTarget::FillManualContentProvider) { + if (res2 == Loader::ResultStatus::Success && file_type == Loader::FileType::NCA) { + provider->AddEntry(FileSys::TitleType::Application, + FileSys::GetCRTypeFromNCAType(FileSys::NCA{file}.GetType()), + program_id, file); + } else if (res2 == Loader::ResultStatus::Success && + (file_type == Loader::FileType::XCI || + file_type == Loader::FileType::NSP)) { + const auto nsp = file_type == Loader::FileType::NSP + ? std::make_shared(file) + : FileSys::XCI{file}.GetSecurePartitionNSP(); + for (const auto& title : nsp->GetNCAs()) { + for (const auto& entry : title.second) { + provider->AddEntry(entry.first.first, entry.first.second, title.first, + entry.second->GetBaseFile()); + } + } + } + } else { + std::vector program_ids; + loader->ReadProgramIds(program_ids); + + if (res2 == Loader::ResultStatus::Success && program_ids.size() > 1 && + (file_type == Loader::FileType::XCI || file_type == Loader::FileType::NSP)) { + for (const auto id : program_ids) { + loader = Loader::GetLoader(system, file, id); + if (!loader) { + continue; + } + + std::vector icon; + [[maybe_unused]] const auto res1 = loader->ReadIcon(icon); + + std::string name = " "; + [[maybe_unused]] const auto res3 = loader->ReadTitle(name); + + const FileSys::PatchManager patch{id, system.GetFileSystemController(), + system.GetContentProvider()}; + + auto entry = MakeGameListEntry( + physical_name, name, Common::FS::GetSize(physical_name), icon, *loader, + id, compatibility_list, play_time_manager, patch); + + RecordEvent( + [=](GameList* game_list) { game_list->AddEntry(entry, parent_dir); }); + } + } else { + std::vector icon; + [[maybe_unused]] const auto res1 = loader->ReadIcon(icon); + + std::string name = " "; + [[maybe_unused]] const auto res3 = loader->ReadTitle(name); + + const FileSys::PatchManager patch{program_id, system.GetFileSystemController(), + system.GetContentProvider()}; + + auto entry = MakeGameListEntry( + physical_name, name, Common::FS::GetSize(physical_name), icon, *loader, + program_id, compatibility_list, play_time_manager, patch); + + RecordEvent( + [=](GameList* game_list) { game_list->AddEntry(entry, parent_dir); }); + } + } + } else if (is_dir) { + watch_list.append(QString::fromStdString(physical_name)); + } + + return true; + }; + + if (deep_scan) { + Common::FS::IterateDirEntriesRecursively(dir_path, callback, + Common::FS::DirEntryFilter::All); + } else { + Common::FS::IterateDirEntries(dir_path, callback, Common::FS::DirEntryFilter::File); + } +} + +void GameListWorker::run() { + watch_list.clear(); + provider->ClearAllEntries(); + + const auto DirEntryReady = [&](GameListDir* game_list_dir) { + RecordEvent([=](GameList* game_list) { game_list->AddDirEntry(game_list_dir); }); + }; + + for (UISettings::GameDir& game_dir : game_dirs) { + if (stop_requested) { + break; + } + + if (game_dir.path == std::string("SDMC")) { + auto* const game_list_dir = new GameListDir(game_dir, GameListItemType::SdmcDir); + DirEntryReady(game_list_dir); + AddTitlesToGameList(game_list_dir); + } else if (game_dir.path == std::string("UserNAND")) { + auto* const game_list_dir = new GameListDir(game_dir, GameListItemType::UserNandDir); + DirEntryReady(game_list_dir); + AddTitlesToGameList(game_list_dir); + } else if (game_dir.path == std::string("SysNAND")) { + auto* const game_list_dir = new GameListDir(game_dir, GameListItemType::SysNandDir); + DirEntryReady(game_list_dir); + AddTitlesToGameList(game_list_dir); + } else { + watch_list.append(QString::fromStdString(game_dir.path)); + auto* const game_list_dir = new GameListDir(game_dir); + DirEntryReady(game_list_dir); + ScanFileSystem(ScanTarget::FillManualContentProvider, game_dir.path, game_dir.deep_scan, + game_list_dir); + ScanFileSystem(ScanTarget::PopulateGameList, game_dir.path, game_dir.deep_scan, + game_list_dir); + } + } + + RecordEvent([this](GameList* game_list) { game_list->DonePopulating(watch_list); }); + processing_completed.Set(); +} diff --git a/src/sudachi/game_list_worker.h b/src/sudachi/game_list_worker.h new file mode 100644 index 0000000..b8dc5fd --- /dev/null +++ b/src/sudachi/game_list_worker.h @@ -0,0 +1,94 @@ +// SPDX-FileCopyrightText: Copyright 2018 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "common/thread.h" +#include "sudachi/compatibility_list.h" +#include "sudachi/play_time_manager.h" + +namespace Core { +class System; +} + +class GameList; +class QStandardItem; + +namespace FileSys { +class NCA; +class VfsFilesystem; +} // namespace FileSys + +/** + * Asynchronous worker object for populating the game list. + * Communicates with other threads through Qt's signal/slot system. + */ +class GameListWorker : public QObject, public QRunnable { + Q_OBJECT + +public: + explicit GameListWorker(std::shared_ptr vfs_, + FileSys::ManualContentProvider* provider_, + QVector& game_dirs_, + const CompatibilityList& compatibility_list_, + const PlayTime::PlayTimeManager& play_time_manager_, + Core::System& system_); + ~GameListWorker() override; + + /// Starts the processing of directory tree information. + void run() override; + +public: + /** + * Synchronously processes any events queued by the worker. + * + * AddDirEntry is called on the game list for every discovered directory. + * AddEntry is called on the game list for every discovered program. + * DonePopulating is called on the game list when processing completes. + */ + void ProcessEvents(GameList* game_list); + +signals: + void DataAvailable(); + +private: + template + void RecordEvent(F&& func); + +private: + void AddTitlesToGameList(GameListDir* parent_dir); + + enum class ScanTarget { + FillManualContentProvider, + PopulateGameList, + }; + + void ScanFileSystem(ScanTarget target, const std::string& dir_path, bool deep_scan, + GameListDir* parent_dir); + + std::shared_ptr vfs; + FileSys::ManualContentProvider* provider; + QVector& game_dirs; + const CompatibilityList& compatibility_list; + const PlayTime::PlayTimeManager& play_time_manager; + + QStringList watch_list; + + std::mutex lock; + std::condition_variable cv; + std::deque> queued_events; + std::atomic_bool stop_requested = false; + Common::Event processing_completed; + + Core::System& system; +}; diff --git a/src/sudachi/hotkeys.cpp b/src/sudachi/hotkeys.cpp new file mode 100644 index 0000000..b117228 --- /dev/null +++ b/src/sudachi/hotkeys.cpp @@ -0,0 +1,214 @@ +// SPDX-FileCopyrightText: 2014 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include +#include +#include + +#include "hid_core/frontend/emulated_controller.h" +#include "sudachi/hotkeys.h" +#include "sudachi/uisettings.h" + +HotkeyRegistry::HotkeyRegistry() = default; +HotkeyRegistry::~HotkeyRegistry() = default; + +void HotkeyRegistry::SaveHotkeys() { + UISettings::values.shortcuts.clear(); + for (const auto& group : hotkey_groups) { + for (const auto& hotkey : group.second) { + UISettings::values.shortcuts.push_back( + {hotkey.first, group.first, + UISettings::ContextualShortcut({hotkey.second.keyseq.toString().toStdString(), + hotkey.second.controller_keyseq, + hotkey.second.context, hotkey.second.repeat})}); + } + } +} + +void HotkeyRegistry::LoadHotkeys() { + // Make sure NOT to use a reference here because it would become invalid once we call + // beginGroup() + for (auto shortcut : UISettings::values.shortcuts) { + Hotkey& hk = hotkey_groups[shortcut.group][shortcut.name]; + if (!shortcut.shortcut.keyseq.empty()) { + hk.keyseq = QKeySequence::fromString(QString::fromStdString(shortcut.shortcut.keyseq), + QKeySequence::NativeText); + hk.context = static_cast(shortcut.shortcut.context); + } + if (!shortcut.shortcut.controller_keyseq.empty()) { + hk.controller_keyseq = shortcut.shortcut.controller_keyseq; + } + if (hk.shortcut) { + hk.shortcut->disconnect(); + hk.shortcut->setKey(hk.keyseq); + } + if (hk.controller_shortcut) { + hk.controller_shortcut->disconnect(); + hk.controller_shortcut->SetKey(hk.controller_keyseq); + } + hk.repeat = shortcut.shortcut.repeat; + } +} + +QShortcut* HotkeyRegistry::GetHotkey(const std::string& group, const std::string& action, + QWidget* widget) { + Hotkey& hk = hotkey_groups[group][action]; + + if (!hk.shortcut) { + hk.shortcut = new QShortcut(hk.keyseq, widget, nullptr, nullptr, hk.context); + } + + hk.shortcut->setAutoRepeat(hk.repeat); + return hk.shortcut; +} + +ControllerShortcut* HotkeyRegistry::GetControllerHotkey(const std::string& group, + const std::string& action, + Core::HID::EmulatedController* controller) { + Hotkey& hk = hotkey_groups[group][action]; + + if (!hk.controller_shortcut) { + hk.controller_shortcut = new ControllerShortcut(controller); + hk.controller_shortcut->SetKey(hk.controller_keyseq); + } + + return hk.controller_shortcut; +} + +QKeySequence HotkeyRegistry::GetKeySequence(const std::string& group, const std::string& action) { + return hotkey_groups[group][action].keyseq; +} + +Qt::ShortcutContext HotkeyRegistry::GetShortcutContext(const std::string& group, + const std::string& action) { + return hotkey_groups[group][action].context; +} + +ControllerShortcut::ControllerShortcut(Core::HID::EmulatedController* controller) { + emulated_controller = controller; + Core::HID::ControllerUpdateCallback engine_callback{ + .on_change = [this](Core::HID::ControllerTriggerType type) { ControllerUpdateEvent(type); }, + .is_npad_service = false, + }; + callback_key = emulated_controller->SetCallback(engine_callback); + is_enabled = true; +} + +ControllerShortcut::~ControllerShortcut() { + emulated_controller->DeleteCallback(callback_key); +} + +void ControllerShortcut::SetKey(const ControllerButtonSequence& buttons) { + button_sequence = buttons; +} + +void ControllerShortcut::SetKey(const std::string& buttons_shortcut) { + ControllerButtonSequence sequence{}; + name = buttons_shortcut; + std::istringstream command_line(buttons_shortcut); + std::string line; + while (std::getline(command_line, line, '+')) { + if (line.empty()) { + continue; + } + if (line == "A") { + sequence.npad.a.Assign(1); + } + if (line == "B") { + sequence.npad.b.Assign(1); + } + if (line == "X") { + sequence.npad.x.Assign(1); + } + if (line == "Y") { + sequence.npad.y.Assign(1); + } + if (line == "L") { + sequence.npad.l.Assign(1); + } + if (line == "R") { + sequence.npad.r.Assign(1); + } + if (line == "ZL") { + sequence.npad.zl.Assign(1); + } + if (line == "ZR") { + sequence.npad.zr.Assign(1); + } + if (line == "Dpad_Left") { + sequence.npad.left.Assign(1); + } + if (line == "Dpad_Right") { + sequence.npad.right.Assign(1); + } + if (line == "Dpad_Up") { + sequence.npad.up.Assign(1); + } + if (line == "Dpad_Down") { + sequence.npad.down.Assign(1); + } + if (line == "Left_Stick") { + sequence.npad.stick_l.Assign(1); + } + if (line == "Right_Stick") { + sequence.npad.stick_r.Assign(1); + } + if (line == "Minus") { + sequence.npad.minus.Assign(1); + } + if (line == "Plus") { + sequence.npad.plus.Assign(1); + } + if (line == "Home") { + sequence.home.home.Assign(1); + } + if (line == "Screenshot") { + sequence.capture.capture.Assign(1); + } + } + + button_sequence = sequence; +} + +ControllerButtonSequence ControllerShortcut::ButtonSequence() const { + return button_sequence; +} + +void ControllerShortcut::SetEnabled(bool enable) { + is_enabled = enable; +} + +bool ControllerShortcut::IsEnabled() const { + return is_enabled; +} + +void ControllerShortcut::ControllerUpdateEvent(Core::HID::ControllerTriggerType type) { + if (!is_enabled) { + return; + } + if (type != Core::HID::ControllerTriggerType::Button) { + return; + } + if (button_sequence.npad.raw == Core::HID::NpadButton::None && + button_sequence.capture.raw == 0 && button_sequence.home.raw == 0) { + return; + } + + const auto player_npad_buttons = + emulated_controller->GetNpadButtons().raw & button_sequence.npad.raw; + const u64 player_capture_buttons = + emulated_controller->GetCaptureButtons().raw & button_sequence.capture.raw; + const u64 player_home_buttons = + emulated_controller->GetHomeButtons().raw & button_sequence.home.raw; + + if (player_npad_buttons == button_sequence.npad.raw && + player_capture_buttons == button_sequence.capture.raw && + player_home_buttons == button_sequence.home.raw && !active) { + // Force user to press the home or capture button again + active = true; + emit Activated(); + return; + } + active = false; +} diff --git a/src/sudachi/hotkeys.h b/src/sudachi/hotkeys.h new file mode 100644 index 0000000..bdc0816 --- /dev/null +++ b/src/sudachi/hotkeys.h @@ -0,0 +1,127 @@ +// SPDX-FileCopyrightText: 2014 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include +#include +#include +#include "hid_core/hid_types.h" + +class QDialog; +class QSettings; +class QShortcut; +class ControllerShortcut; + +namespace Core::HID { +enum class ControllerTriggerType; +class EmulatedController; +} // namespace Core::HID + +struct ControllerButtonSequence { + Core::HID::CaptureButtonState capture{}; + Core::HID::HomeButtonState home{}; + Core::HID::NpadButtonState npad{}; +}; + +class ControllerShortcut : public QObject { + Q_OBJECT + +public: + explicit ControllerShortcut(Core::HID::EmulatedController* controller); + ~ControllerShortcut(); + + void SetKey(const ControllerButtonSequence& buttons); + void SetKey(const std::string& buttons_shortcut); + + ControllerButtonSequence ButtonSequence() const; + + void SetEnabled(bool enable); + bool IsEnabled() const; + +Q_SIGNALS: + void Activated(); + +private: + void ControllerUpdateEvent(Core::HID::ControllerTriggerType type); + + bool is_enabled{}; + bool active{}; + int callback_key{}; + ControllerButtonSequence button_sequence{}; + std::string name{}; + Core::HID::EmulatedController* emulated_controller = nullptr; +}; + +class HotkeyRegistry final { +public: + friend class ConfigureHotkeys; + + explicit HotkeyRegistry(); + ~HotkeyRegistry(); + + /** + * Loads hotkeys from the settings file. + * + * @note Yet unregistered hotkeys which are present in the settings will automatically be + * registered. + */ + void LoadHotkeys(); + + /** + * Saves all registered hotkeys to the settings file. + * + * @note Each hotkey group will be stored a settings group; For each hotkey inside that group, a + * settings group will be created to store the key sequence and the hotkey context. + */ + void SaveHotkeys(); + + /** + * Returns a QShortcut object whose activated() signal can be connected to other QObjects' + * slots. + * + * @param group General group this hotkey belongs to (e.g. "Main Window", "Debugger"). + * @param action Name of the action (e.g. "Start Emulation", "Load Image"). + * @param widget Parent widget of the returned QShortcut. + * @warning If multiple QWidgets' call this function for the same action, the returned QShortcut + * will be the same. Thus, you shouldn't rely on the caller really being the + * QShortcut's parent. + */ + QShortcut* GetHotkey(const std::string& group, const std::string& action, QWidget* widget); + ControllerShortcut* GetControllerHotkey(const std::string& group, const std::string& action, + Core::HID::EmulatedController* controller); + + /** + * Returns a QKeySequence object whose signal can be connected to QAction::setShortcut. + * + * @param group General group this hotkey belongs to (e.g. "Main Window", "Debugger"). + * @param action Name of the action (e.g. "Start Emulation", "Load Image"). + */ + QKeySequence GetKeySequence(const std::string& group, const std::string& action); + + /** + * Returns a Qt::ShortcutContext object who can be connected to other + * QAction::setShortcutContext. + * + * @param group General group this shortcut context belongs to (e.g. "Main Window", + * "Debugger"). + * @param action Name of the action (e.g. "Start Emulation", "Load Image"). + */ + Qt::ShortcutContext GetShortcutContext(const std::string& group, const std::string& action); + +private: + struct Hotkey { + QKeySequence keyseq; + std::string controller_keyseq; + QShortcut* shortcut = nullptr; + ControllerShortcut* controller_shortcut = nullptr; + Qt::ShortcutContext context = Qt::WindowShortcut; + bool repeat; + }; + + using HotkeyMap = std::map; + using HotkeyGroupMap = std::map; + + HotkeyGroupMap hotkey_groups; +}; diff --git a/src/sudachi/install_dialog.cpp b/src/sudachi/install_dialog.cpp new file mode 100644 index 0000000..bf39e7e --- /dev/null +++ b/src/sudachi/install_dialog.cpp @@ -0,0 +1,69 @@ +// SPDX-FileCopyrightText: Copyright 2020 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include +#include +#include +#include +#include +#include "sudachi/install_dialog.h" +#include "sudachi/uisettings.h" + +InstallDialog::InstallDialog(QWidget* parent, const QStringList& files) : QDialog(parent) { + file_list = new QListWidget(this); + + for (const QString& file : files) { + QListWidgetItem* item = new QListWidgetItem(QFileInfo(file).fileName(), file_list); + item->setData(Qt::UserRole, file); + item->setFlags(item->flags() | Qt::ItemIsUserCheckable); + item->setCheckState(Qt::Checked); + } + + file_list->setMinimumWidth((file_list->sizeHintForColumn(0) * 11) / 10); + + vbox_layout = new QVBoxLayout; + + hbox_layout = new QHBoxLayout; + + description = new QLabel(tr("Please confirm these are the files you wish to install.")); + + update_description = + new QLabel(tr("Installing an Update or DLC will overwrite the previously installed one.")); + + buttons = new QDialogButtonBox; + buttons->addButton(QDialogButtonBox::Cancel); + buttons->addButton(tr("Install"), QDialogButtonBox::AcceptRole); + + connect(buttons, &QDialogButtonBox::accepted, this, &InstallDialog::accept); + connect(buttons, &QDialogButtonBox::rejected, this, &InstallDialog::reject); + + hbox_layout->addWidget(buttons); + + vbox_layout->addWidget(description); + vbox_layout->addWidget(update_description); + vbox_layout->addWidget(file_list); + vbox_layout->addLayout(hbox_layout); + + setLayout(vbox_layout); + setWindowTitle(tr("Install Files to NAND")); +} + +InstallDialog::~InstallDialog() = default; + +QStringList InstallDialog::GetFiles() const { + QStringList files; + + for (int i = 0; i < file_list->count(); ++i) { + const QListWidgetItem* item = file_list->item(i); + if (item->checkState() == Qt::Checked) { + files.append(item->data(Qt::UserRole).toString()); + } + } + + return files; +} + +int InstallDialog::GetMinimumWidth() const { + return file_list->width(); +} diff --git a/src/sudachi/install_dialog.h b/src/sudachi/install_dialog.h new file mode 100644 index 0000000..474f2e4 --- /dev/null +++ b/src/sudachi/install_dialog.h @@ -0,0 +1,34 @@ +// SPDX-FileCopyrightText: Copyright 2020 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include + +class QCheckBox; +class QDialogButtonBox; +class QHBoxLayout; +class QLabel; +class QListWidget; +class QVBoxLayout; + +class InstallDialog : public QDialog { + Q_OBJECT + +public: + explicit InstallDialog(QWidget* parent, const QStringList& files); + ~InstallDialog() override; + + [[nodiscard]] QStringList GetFiles() const; + [[nodiscard]] int GetMinimumWidth() const; + +private: + QListWidget* file_list; + + QVBoxLayout* vbox_layout; + QHBoxLayout* hbox_layout; + + QLabel* description; + QLabel* update_description; + QDialogButtonBox* buttons; +}; diff --git a/src/sudachi/loading_screen.cpp b/src/sudachi/loading_screen.cpp new file mode 100644 index 0000000..9d061d5 --- /dev/null +++ b/src/sudachi/loading_screen.cpp @@ -0,0 +1,202 @@ +// SPDX-FileCopyrightText: Copyright 2019 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "core/frontend/framebuffer_layout.h" +#include "core/loader/loader.h" +#include "ui_loading_screen.h" +#include "video_core/rasterizer_interface.h" +#include "sudachi/loading_screen.h" + +// Mingw seems to not have QMovie at all. If QMovie is missing then use a single frame instead of an +// showing the full animation +#if !SUDACHI_QT_MOVIE_MISSING +#include +#endif + +constexpr char PROGRESSBAR_STYLE_PREPARE[] = R"( +QProgressBar {} +QProgressBar::chunk {})"; + +constexpr char PROGRESSBAR_STYLE_BUILD[] = R"( +QProgressBar { + background-color: black; + border: 2px solid white; + border-radius: 4px; + padding: 2px; +} +QProgressBar::chunk { + background-color: #ff3c28; + width: 1px; +})"; + +constexpr char PROGRESSBAR_STYLE_COMPLETE[] = R"( +QProgressBar { + background-color: #0ab9e6; + border: 2px solid white; + border-radius: 4px; + padding: 2px; +} +QProgressBar::chunk { + background-color: #ff3c28; +})"; + +LoadingScreen::LoadingScreen(QWidget* parent) + : QWidget(parent), ui(std::make_unique()), + previous_stage(VideoCore::LoadCallbackStage::Complete) { + ui->setupUi(this); + setMinimumSize(Layout::MinimumSize::Width, Layout::MinimumSize::Height); + + // Create a fade out effect to hide this loading screen widget. + // When fading opacity, it will fade to the parent widgets background color, which is why we + // create an internal widget named fade_widget that we use the effect on, while keeping the + // loading screen widget's background color black. This way we can create a fade to black effect + opacity_effect = new QGraphicsOpacityEffect(this); + opacity_effect->setOpacity(1); + ui->fade_parent->setGraphicsEffect(opacity_effect); + fadeout_animation = std::make_unique(opacity_effect, "opacity"); + fadeout_animation->setDuration(500); + fadeout_animation->setStartValue(1); + fadeout_animation->setEndValue(0); + fadeout_animation->setEasingCurve(QEasingCurve::OutBack); + + // After the fade completes, hide the widget and reset the opacity + connect(fadeout_animation.get(), &QPropertyAnimation::finished, [this] { + hide(); + opacity_effect->setOpacity(1); + emit Hidden(); + }); + connect(this, &LoadingScreen::LoadProgress, this, &LoadingScreen::OnLoadProgress, + Qt::QueuedConnection); + qRegisterMetaType(); + + stage_translations = { + {VideoCore::LoadCallbackStage::Prepare, tr("Loading...")}, + {VideoCore::LoadCallbackStage::Build, tr("Loading Shaders %1 / %2")}, + {VideoCore::LoadCallbackStage::Complete, tr("Launching...")}, + }; + progressbar_style = { + {VideoCore::LoadCallbackStage::Prepare, PROGRESSBAR_STYLE_PREPARE}, + {VideoCore::LoadCallbackStage::Build, PROGRESSBAR_STYLE_BUILD}, + {VideoCore::LoadCallbackStage::Complete, PROGRESSBAR_STYLE_COMPLETE}, + }; +} + +LoadingScreen::~LoadingScreen() = default; + +void LoadingScreen::Prepare(Loader::AppLoader& loader) { + std::vector buffer; + if (loader.ReadBanner(buffer) == Loader::ResultStatus::Success) { +#ifdef SUDACHI_QT_MOVIE_MISSING + QPixmap map; + map.loadFromData(buffer.data(), buffer.size()); + ui->banner->setPixmap(map); +#else + backing_mem = std::make_unique(reinterpret_cast(buffer.data()), + static_cast(buffer.size())); + backing_buf = std::make_unique(backing_mem.get()); + backing_buf->open(QIODevice::ReadOnly); + animation = std::make_unique(backing_buf.get(), QByteArray()); + animation->start(); + ui->banner->setMovie(animation.get()); +#endif + buffer.clear(); + } + if (loader.ReadLogo(buffer) == Loader::ResultStatus::Success) { + QPixmap map; + map.loadFromData(buffer.data(), static_cast(buffer.size())); + ui->logo->setPixmap(map); + } + + slow_shader_compile_start = false; + OnLoadProgress(VideoCore::LoadCallbackStage::Prepare, 0, 0); +} + +void LoadingScreen::OnLoadComplete() { + fadeout_animation->start(QPropertyAnimation::KeepWhenStopped); +} + +void LoadingScreen::OnLoadProgress(VideoCore::LoadCallbackStage stage, std::size_t value, + std::size_t total) { + using namespace std::chrono; + const auto now = steady_clock::now(); + // reset the timer if the stage changes + if (stage != previous_stage) { + ui->progress_bar->setStyleSheet(QString::fromUtf8(progressbar_style[stage])); + // Hide the progress bar during the prepare stage + if (stage == VideoCore::LoadCallbackStage::Prepare) { + ui->progress_bar->hide(); + } else { + ui->progress_bar->show(); + } + previous_stage = stage; + // reset back to fast shader compiling since the stage changed + slow_shader_compile_start = false; + } + // update the max of the progress bar if the number of shaders change + if (total != previous_total) { + ui->progress_bar->setMaximum(static_cast(total)); + previous_total = total; + } + // Reset the progress bar ranges if compilation is done + if (stage == VideoCore::LoadCallbackStage::Complete) { + ui->progress_bar->setRange(0, 0); + } + + QString estimate; + // If there's a drastic slowdown in the rate, then display an estimate + if (now - previous_time > milliseconds{50} || slow_shader_compile_start) { + if (!slow_shader_compile_start) { + slow_shader_start = steady_clock::now(); + slow_shader_compile_start = true; + slow_shader_first_value = value; + } + // only calculate an estimate time after a second has passed since stage change + const auto diff = duration_cast(now - slow_shader_start); + if (diff > seconds{1}) { + const auto eta_mseconds = + static_cast(static_cast(total - slow_shader_first_value) / + (value - slow_shader_first_value) * diff.count()); + estimate = + tr("Estimated Time %1") + .arg(QTime(0, 0, 0, 0) + .addMSecs(std::max(eta_mseconds - diff.count() + 1000, 1000)) + .toString(QStringLiteral("mm:ss"))); + } + } + + // update labels and progress bar + if (stage == VideoCore::LoadCallbackStage::Build) { + ui->stage->setText(stage_translations[stage].arg(value).arg(total)); + } else { + ui->stage->setText(stage_translations[stage]); + } + ui->value->setText(estimate); + ui->progress_bar->setValue(static_cast(value)); + previous_time = now; +} + +void LoadingScreen::paintEvent(QPaintEvent* event) { + QStyleOption opt; + opt.initFrom(this); + QPainter p(this); + style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this); + QWidget::paintEvent(event); +} + +void LoadingScreen::Clear() { +#ifndef SUDACHI_QT_MOVIE_MISSING + animation.reset(); + backing_buf.reset(); + backing_mem.reset(); +#endif +} diff --git a/src/sudachi/loading_screen.h b/src/sudachi/loading_screen.h new file mode 100644 index 0000000..fa06185 --- /dev/null +++ b/src/sudachi/loading_screen.h @@ -0,0 +1,94 @@ +// SPDX-FileCopyrightText: Copyright 2019 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include +#include +#include +#include + +#if !QT_CONFIG(movie) +#define SUDACHI_QT_MOVIE_MISSING 1 +#endif + +namespace Loader { +class AppLoader; +} + +namespace Ui { +class LoadingScreen; +} + +namespace VideoCore { +enum class LoadCallbackStage; +} + +class QBuffer; +class QByteArray; +class QGraphicsOpacityEffect; +class QMovie; +class QPropertyAnimation; + +class LoadingScreen : public QWidget { + Q_OBJECT + +public: + explicit LoadingScreen(QWidget* parent = nullptr); + + ~LoadingScreen(); + + /// Call before showing the loading screen to load the widgets with the logo and banner for the + /// currently loaded application. + void Prepare(Loader::AppLoader& loader); + + /// After the loading screen is hidden, the owner of this class can call this to clean up any + /// used resources such as the logo and banner. + void Clear(); + + /// Slot used to update the status of the progress bar + void OnLoadProgress(VideoCore::LoadCallbackStage stage, std::size_t value, std::size_t total); + + /// Hides the LoadingScreen with a fade out effect + void OnLoadComplete(); + + // In order to use a custom widget with a stylesheet, you need to override the paintEvent + // See https://wiki.qt.io/How_to_Change_the_Background_Color_of_QWidget + void paintEvent(QPaintEvent* event) override; + +signals: + void LoadProgress(VideoCore::LoadCallbackStage stage, std::size_t value, std::size_t total); + /// Signals that this widget is completely hidden now and should be replaced with the other + /// widget + void Hidden(); + +private: +#ifndef SUDACHI_QT_MOVIE_MISSING + std::unique_ptr animation; + std::unique_ptr backing_buf; + std::unique_ptr backing_mem; +#endif + std::unique_ptr ui; + std::size_t previous_total = 0; + VideoCore::LoadCallbackStage previous_stage; + + QGraphicsOpacityEffect* opacity_effect = nullptr; + std::unique_ptr fadeout_animation; + + // Definitions for the differences in text and styling for each stage + std::unordered_map progressbar_style; + std::unordered_map stage_translations; + + // newly generated shaders are added to the end of the file, so when loading and compiling + // shaders, it will start quickly but end slow if new shaders were added since previous launch. + // These variables are used to detect the change in speed so we can generate an ETA + bool slow_shader_compile_start = false; + std::chrono::steady_clock::time_point slow_shader_start; + std::chrono::steady_clock::time_point previous_time; + std::size_t slow_shader_first_value = 0; +}; + +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) +Q_DECLARE_METATYPE(VideoCore::LoadCallbackStage); +#endif diff --git a/src/sudachi/loading_screen.ui b/src/sudachi/loading_screen.ui new file mode 100644 index 0000000..820b475 --- /dev/null +++ b/src/sudachi/loading_screen.ui @@ -0,0 +1,164 @@ + + + LoadingScreen + + + + 0 + 0 + 746 + 495 + + + + background-color: rgb(0, 0, 0); + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop + + + 30 + + + + + + + 15 + + + QLayout::SetNoConstraint + + + + + + 0 + 0 + + + + background-color: black; color: white; +font: 75 20pt "Arial"; + + + Loading Shaders 387 / 1628 + + + + + + + + 0 + 0 + + + + + 500 + 40 + + + + QProgressBar { +color: white; +border: 2px solid white; +outline-color: black; +border-radius: 20px; +} +QProgressBar::chunk { +background-color: white; +border-radius: 15px; +} + + + 50 + + + false + + + Loading Shaders %v out of %m + + + + + + + + + + background-color: black; color: white; +font: 75 15pt "Arial"; + + + Estimated Time 5m 4s + + + + + + + + + background-color: black; + + + + + + Qt::AlignCenter + + + 30 + + + + + + + + + + + diff --git a/src/sudachi/main.cpp b/src/sudachi/main.cpp new file mode 100644 index 0000000..8e31a84 --- /dev/null +++ b/src/sudachi/main.cpp @@ -0,0 +1,5343 @@ +// SPDX-FileCopyrightText: 2014 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include +#include +#include +#include +#include +#include +#include "core/hle/service/am/applet_manager.h" +#include "core/loader/nca.h" +#include "core/tools/renderdoc.h" + +#ifdef __APPLE__ +#include // for chdir +#endif +#ifdef __unix__ +#include +#include +#include "common/linux/gamemode.h" +#endif + +#include + +// VFS includes must be before glad as they will conflict with Windows file api, which uses defines. +#include "applets/qt_amiibo_settings.h" +#include "applets/qt_controller.h" +#include "applets/qt_error.h" +#include "applets/qt_profile_select.h" +#include "applets/qt_software_keyboard.h" +#include "applets/qt_web_browser.h" +#include "common/nvidia_flags.h" +#include "common/settings_enums.h" +#include "configuration/configure_input.h" +#include "configuration/configure_per_game.h" +#include "configuration/configure_tas.h" +#include "core/file_sys/romfs_factory.h" +#include "core/file_sys/vfs/vfs.h" +#include "core/file_sys/vfs/vfs_real.h" +#include "core/frontend/applets/cabinet.h" +#include "core/frontend/applets/controller.h" +#include "core/frontend/applets/general.h" +#include "core/frontend/applets/mii_edit.h" +#include "core/frontend/applets/software_keyboard.h" +#include "core/hle/service/acc/profile_manager.h" +#include "core/hle/service/am/frontend/applets.h" +#include "core/hle/service/set/system_settings_server.h" +#include "frontend_common/content_manager.h" +#include "hid_core/frontend/emulated_controller.h" +#include "hid_core/hid_core.h" +#include "sudachi/multiplayer/state.h" +#include "sudachi/util/controller_navigation.h" + +// These are wrappers to avoid the calls to CreateDirectory and CreateFile because of the Windows +// defines. +static FileSys::VirtualDir VfsFilesystemCreateDirectoryWrapper( + const FileSys::VirtualFilesystem& vfs, const std::string& path, FileSys::OpenMode mode) { + return vfs->CreateDirectory(path, mode); +} + +static FileSys::VirtualFile VfsDirectoryCreateFileWrapper(const FileSys::VirtualDir& dir, + const std::string& path) { + return dir->CreateFile(path); +} + +#include +#include + +#define QT_NO_OPENGL +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef HAVE_SDL2 +#include // For SDL ScreenSaver functions +#endif + +#include +#include "common/detached_tasks.h" +#include "common/fs/fs.h" +#include "common/fs/path_util.h" +#include "common/literals.h" +#include "common/logging/backend.h" +#include "common/logging/log.h" +#include "common/memory_detect.h" +#include "common/microprofile.h" +#include "common/scm_rev.h" +#include "common/scope_exit.h" +#ifdef _WIN32 +#include +#include "common/windows/timer_resolution.h" +#endif +#ifdef ARCHITECTURE_x86_64 +#include "common/x64/cpu_detect.h" +#endif +#include "common/settings.h" +#include "common/telemetry.h" +#include "core/core.h" +#include "core/core_timing.h" +#include "core/crypto/key_manager.h" +#include "core/file_sys/card_image.h" +#include "core/file_sys/common_funcs.h" +#include "core/file_sys/content_archive.h" +#include "core/file_sys/control_metadata.h" +#include "core/file_sys/patch_manager.h" +#include "core/file_sys/registered_cache.h" +#include "core/file_sys/romfs.h" +#include "core/file_sys/savedata_factory.h" +#include "core/file_sys/submission_package.h" +#include "core/hle/kernel/k_process.h" +#include "core/hle/service/am/am.h" +#include "core/hle/service/filesystem/filesystem.h" +#include "core/hle/service/sm/sm.h" +#include "core/loader/loader.h" +#include "core/perf_stats.h" +#include "core/telemetry_session.h" +#include "frontend_common/config.h" +#include "input_common/drivers/tas_input.h" +#include "input_common/drivers/virtual_amiibo.h" +#include "input_common/main.h" +#include "ui_main.h" +#include "util/overlay_dialog.h" +#include "video_core/gpu.h" +#include "video_core/renderer_base.h" +#include "video_core/shader_notify.h" +#include "sudachi/about_dialog.h" +#include "sudachi/bootmanager.h" +#include "sudachi/compatdb.h" +#include "sudachi/compatibility_list.h" +#include "sudachi/configuration/configure_dialog.h" +#include "sudachi/configuration/configure_input_per_game.h" +#include "sudachi/configuration/qt_config.h" +#include "sudachi/debugger/console.h" +#include "sudachi/debugger/controller.h" +#include "sudachi/debugger/profiler.h" +#include "sudachi/debugger/wait_tree.h" +#include "sudachi/discord.h" +#include "sudachi/game_list.h" +#include "sudachi/game_list_p.h" +#include "sudachi/hotkeys.h" +#include "sudachi/install_dialog.h" +#include "sudachi/loading_screen.h" +#include "sudachi/main.h" +#include "sudachi/play_time_manager.h" +#include "sudachi/startup_checks.h" +#include "sudachi/uisettings.h" +#include "sudachi/util/clickable_label.h" +#include "sudachi/vk_device_info.h" + +#ifdef SUDACHI_CRASH_DUMPS +#include "sudachi/breakpad.h" +#endif + +using namespace Common::Literals; + +#ifdef USE_DISCORD_PRESENCE +#include "sudachi/discord_impl.h" +#endif + +#ifdef QT_STATICPLUGIN +Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin); +#endif + +#ifdef _WIN32 +#include +extern "C" { +// tells Nvidia and AMD drivers to use the dedicated GPU by default on laptops with switchable +// graphics +__declspec(dllexport) unsigned long NvOptimusEnablement = 0x00000001; +__declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1; +} +#endif + +constexpr int default_mouse_hide_timeout = 2500; +constexpr int default_input_update_timeout = 1; + +constexpr size_t CopyBufferSize = 1_MiB; + +/** + * "Callouts" are one-time instructional messages shown to the user. In the config settings, there + * is a bitfield "callout_flags" options, used to track if a message has already been shown to the + * user. This is 32-bits - if we have more than 32 callouts, we should retire and recycle old ones. + */ +enum class CalloutFlag : uint32_t { + Telemetry = 0x1, + DRDDeprecation = 0x2, +}; + +void GMainWindow::ShowTelemetryCallout() { + if (UISettings::values.callout_flags.GetValue() & + static_cast(CalloutFlag::Telemetry)) { + return; + } + + UISettings::values.callout_flags = + UISettings::values.callout_flags.GetValue() | static_cast(CalloutFlag::Telemetry); + const QString telemetry_message = + tr("Anonymous " + "data is collected to help improve sudachi. " + "

Would you like to share your usage data with us?"); + if (!question(this, tr("Telemetry"), telemetry_message)) { + Settings::values.enable_telemetry = false; + system->ApplySettings(); + } +} + +const int GMainWindow::max_recent_files_item; + +static void RemoveCachedContents() { + const auto cache_dir = Common::FS::GetSudachiPath(Common::FS::SudachiPath::CacheDir); + const auto offline_fonts = cache_dir / "fonts"; + const auto offline_manual = cache_dir / "offline_web_applet_manual"; + const auto offline_legal_information = cache_dir / "offline_web_applet_legal_information"; + const auto offline_system_data = cache_dir / "offline_web_applet_system_data"; + + Common::FS::RemoveDirRecursively(offline_fonts); + Common::FS::RemoveDirRecursively(offline_manual); + Common::FS::RemoveDirRecursively(offline_legal_information); + Common::FS::RemoveDirRecursively(offline_system_data); +} + +static void LogRuntimes() { +#ifdef _MSC_VER + // It is possible that the name of the dll will change. + // vcruntime140.dll is for 2015 and onwards + static constexpr char runtime_dll_name[] = "vcruntime140.dll"; + UINT sz = GetFileVersionInfoSizeA(runtime_dll_name, nullptr); + bool runtime_version_inspection_worked = false; + if (sz > 0) { + std::vector buf(sz); + if (GetFileVersionInfoA(runtime_dll_name, 0, sz, buf.data())) { + VS_FIXEDFILEINFO* pvi; + sz = sizeof(VS_FIXEDFILEINFO); + if (VerQueryValueA(buf.data(), "\\", reinterpret_cast(&pvi), &sz)) { + if (pvi->dwSignature == VS_FFI_SIGNATURE) { + runtime_version_inspection_worked = true; + LOG_INFO(Frontend, "MSVC Compiler: {} Runtime: {}.{}.{}.{}", _MSC_VER, + pvi->dwProductVersionMS >> 16, pvi->dwProductVersionMS & 0xFFFF, + pvi->dwProductVersionLS >> 16, pvi->dwProductVersionLS & 0xFFFF); + } + } + } + } + if (!runtime_version_inspection_worked) { + LOG_INFO(Frontend, "Unable to inspect {}", runtime_dll_name); + } +#endif + LOG_INFO(Frontend, "Qt Compile: {} Runtime: {}", QT_VERSION_STR, qVersion()); +} + +static QString PrettyProductName() { +#ifdef _WIN32 + // After Windows 10 Version 2004, Microsoft decided to switch to a different notation: 20H2 + // With that notation change they changed the registry key used to denote the current version + QSettings windows_registry( + QStringLiteral("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion"), + QSettings::NativeFormat); + const QString release_id = windows_registry.value(QStringLiteral("ReleaseId")).toString(); + if (release_id == QStringLiteral("2009")) { + const u32 current_build = windows_registry.value(QStringLiteral("CurrentBuild")).toUInt(); + const QString display_version = + windows_registry.value(QStringLiteral("DisplayVersion")).toString(); + const u32 ubr = windows_registry.value(QStringLiteral("UBR")).toUInt(); + u32 version = 10; + if (current_build >= 22000) { + version = 11; + } + return QStringLiteral("Windows %1 Version %2 (Build %3.%4)") + .arg(QString::number(version), display_version, QString::number(current_build), + QString::number(ubr)); + } +#endif + return QSysInfo::prettyProductName(); +} + +#ifdef _WIN32 +static void OverrideWindowsFont() { + // Qt5 chooses these fonts on Windows and they have fairly ugly alphanumeric/cyrillic characters + // Asking to use "MS Shell Dlg 2" gives better other chars while leaving the Chinese Characters. + const QString startup_font = QApplication::font().family(); + const QStringList ugly_fonts = {QStringLiteral("SimSun"), QStringLiteral("PMingLiU")}; + if (ugly_fonts.contains(startup_font)) { + QApplication::setFont(QFont(QStringLiteral("MS Shell Dlg 2"), 9, QFont::Normal)); + } +} +#endif + +bool GMainWindow::CheckDarkMode() { +#ifdef __unix__ + const QPalette test_palette(qApp->palette()); + const QColor text_color = test_palette.color(QPalette::Active, QPalette::Text); + const QColor window_color = test_palette.color(QPalette::Active, QPalette::Window); + return (text_color.value() > window_color.value()); +#else + // TODO: Windows + return false; +#endif // __unix__ +} + +GMainWindow::GMainWindow(std::unique_ptr config_, bool has_broken_vulkan) + : ui{std::make_unique()}, system{std::make_unique()}, + input_subsystem{std::make_shared()}, config{std::move(config_)}, + vfs{std::make_shared()}, + provider{std::make_unique()} { +#ifdef __unix__ + SetupSigInterrupts(); + SetGamemodeEnabled(Settings::values.enable_gamemode.GetValue()); +#endif + system->Initialize(); + + Common::Log::Initialize(); + Common::Log::Start(); + + LoadTranslation(); + + setAcceptDrops(true); + ui->setupUi(this); + statusBar()->hide(); + + // Check dark mode before a theme is loaded + os_dark_mode = CheckDarkMode(); + startup_icon_theme = QIcon::themeName(); + // fallback can only be set once, colorful theme icons are okay on both light/dark + QIcon::setFallbackThemeName(QStringLiteral("colorful")); + QIcon::setFallbackSearchPaths(QStringList(QStringLiteral(":/icons"))); + + default_theme_paths = QIcon::themeSearchPaths(); + UpdateUITheme(); + + SetDiscordEnabled(UISettings::values.enable_discord_presence.GetValue()); + discord_rpc->Update(); + + play_time_manager = std::make_unique(system->GetProfileManager()); + + system->GetRoomNetwork().Init(); + + RegisterMetaTypes(); + + InitializeWidgets(); + InitializeDebugWidgets(); + InitializeRecentFileMenuActions(); + InitializeHotkeys(); + + SetDefaultUIGeometry(); + RestoreUIState(); + + ConnectMenuEvents(); + ConnectWidgetEvents(); + + system->HIDCore().ReloadInputDevices(); + controller_dialog->refreshConfiguration(); + + const auto branch_name = std::string(Common::g_scm_branch); + const auto description = std::string(Common::g_scm_desc); + const auto build_id = std::string(Common::g_build_id); + + const auto sudachi_build = fmt::format("sudachi Development Build | {}-{}", branch_name, description); + const auto override_build = + fmt::format(fmt::runtime(std::string(Common::g_title_bar_format_idle)), build_id); + const auto sudachi_build_version = override_build.empty() ? sudachi_build : override_build; + const auto processor_count = std::thread::hardware_concurrency(); + + LOG_INFO(Frontend, "sudachi Version: {}", sudachi_build_version); + LogRuntimes(); +#ifdef ARCHITECTURE_x86_64 + const auto& caps = Common::GetCPUCaps(); + std::string cpu_string = caps.cpu_string; + if (caps.avx || caps.avx2 || caps.avx512f) { + cpu_string += " | AVX"; + if (caps.avx512f) { + cpu_string += "512"; + } else if (caps.avx2) { + cpu_string += '2'; + } + if (caps.fma || caps.fma4) { + cpu_string += " | FMA"; + } + } + LOG_INFO(Frontend, "Host CPU: {}", cpu_string); + if (std::optional processor_core = Common::GetProcessorCount()) { + LOG_INFO(Frontend, "Host CPU Cores: {}", *processor_core); + } +#endif + LOG_INFO(Frontend, "Host CPU Threads: {}", processor_count); + LOG_INFO(Frontend, "Host OS: {}", PrettyProductName().toStdString()); + LOG_INFO(Frontend, "Host RAM: {:.2f} GiB", + Common::GetMemInfo().TotalPhysicalMemory / f64{1_GiB}); + LOG_INFO(Frontend, "Host Swap: {:.2f} GiB", Common::GetMemInfo().TotalSwapMemory / f64{1_GiB}); +#ifdef _WIN32 + LOG_INFO(Frontend, "Host Timer Resolution: {:.4f} ms", + std::chrono::duration_cast>( + Common::Windows::SetCurrentTimerResolutionToMaximum()) + .count()); + system->CoreTiming().SetTimerResolutionNs(Common::Windows::GetCurrentTimerResolution()); +#endif + UpdateWindowTitle(); + + show(); + + system->SetContentProvider(std::make_unique()); + system->RegisterContentProvider(FileSys::ContentProviderUnionSlot::FrontendManual, + provider.get()); + system->GetFileSystemController().CreateFactories(*vfs); + + // Remove cached contents generated during the previous session + RemoveCachedContents(); + + // Gen keys if necessary + OnCheckFirmwareDecryption(); + + game_list->LoadCompatibilityList(); + game_list->PopulateAsync(UISettings::values.game_dirs); + + // Show one-time "callout" messages to the user + ShowTelemetryCallout(); + + // make sure menubar has the arrow cursor instead of inheriting from this + ui->menubar->setCursor(QCursor()); + statusBar()->setCursor(QCursor()); + + mouse_hide_timer.setInterval(default_mouse_hide_timeout); + connect(&mouse_hide_timer, &QTimer::timeout, this, &GMainWindow::HideMouseCursor); + connect(ui->menubar, &QMenuBar::hovered, this, &GMainWindow::ShowMouseCursor); + + update_input_timer.setInterval(default_input_update_timeout); + connect(&update_input_timer, &QTimer::timeout, this, &GMainWindow::UpdateInputDrivers); + update_input_timer.start(); + + MigrateConfigFiles(); + + if (has_broken_vulkan) { + UISettings::values.has_broken_vulkan = true; + + QMessageBox::warning(this, tr("Broken Vulkan Installation Detected"), + tr("Vulkan initialization failed during boot.

Click " + "here for instructions to fix the issue.")); + +#ifdef HAS_OPENGL + Settings::values.renderer_backend = Settings::RendererBackend::OpenGL; +#else + Settings::values.renderer_backend = Settings::RendererBackend::Null; +#endif + + UpdateAPIText(); + renderer_status_button->setDisabled(true); + renderer_status_button->setChecked(false); + } else { + VkDeviceInfo::PopulateRecords(vk_device_records, this->window()->windowHandle()); + } + +#if defined(HAVE_SDL2) && !defined(_WIN32) + SDL_InitSubSystem(SDL_INIT_VIDEO); + + // Set a screensaver inhibition reason string. Currently passed to DBus by SDL and visible to + // the user through their desktop environment. + //: TRANSLATORS: This string is shown to the user to explain why sudachi needs to prevent the + //: computer from sleeping + QByteArray wakelock_reason = tr("Running a game").toUtf8(); + SDL_SetHint(SDL_HINT_SCREENSAVER_INHIBIT_ACTIVITY_NAME, wakelock_reason.data()); + + // SDL disables the screen saver by default, and setting the hint + // SDL_HINT_VIDEO_ALLOW_SCREENSAVER doesn't seem to work, so we just enable the screen saver + // for now. + SDL_EnableScreenSaver(); +#endif + + SetupPrepareForSleep(); + + QStringList args = QApplication::arguments(); + + if (args.size() < 2) { + return; + } + + QString game_path; + bool has_gamepath = false; + bool is_fullscreen = false; + + for (int i = 1; i < args.size(); ++i) { + // Preserves drag/drop functionality + if (args.size() == 2 && !args[1].startsWith(QChar::fromLatin1('-'))) { + game_path = args[1]; + has_gamepath = true; + break; + } + + // Launch game in fullscreen mode + if (args[i] == QStringLiteral("-f")) { + is_fullscreen = true; + continue; + } + + // Launch game with a specific user + if (args[i] == QStringLiteral("-u")) { + if (i >= args.size() - 1) { + continue; + } + + if (args[i + 1].startsWith(QChar::fromLatin1('-'))) { + continue; + } + + int user_arg_idx = ++i; + bool argument_ok; + std::size_t selected_user = args[user_arg_idx].toUInt(&argument_ok); + + if (!argument_ok) { + // try to look it up by username, only finds the first username that matches. + const std::string user_arg_str = args[user_arg_idx].toStdString(); + const auto user_idx = system->GetProfileManager().GetUserIndex(user_arg_str); + + if (user_idx == std::nullopt) { + LOG_ERROR(Frontend, "Invalid user argument"); + continue; + } + + selected_user = user_idx.value(); + } + + if (!system->GetProfileManager().UserExistsIndex(selected_user)) { + LOG_ERROR(Frontend, "Selected user doesn't exist"); + continue; + } + + Settings::values.current_user = static_cast(selected_user); + + user_flag_cmd_line = true; + continue; + } + + // Launch game at path + if (args[i] == QStringLiteral("-g")) { + if (i >= args.size() - 1) { + continue; + } + + if (args[i + 1].startsWith(QChar::fromLatin1('-'))) { + continue; + } + + game_path = args[++i]; + has_gamepath = true; + } + } + + // Override fullscreen setting if gamepath or argument is provided + if (has_gamepath || is_fullscreen) { + ui->action_Fullscreen->setChecked(is_fullscreen); + } + + if (!game_path.isEmpty()) { + BootGame(game_path, ApplicationAppletParameters()); + } +} + +GMainWindow::~GMainWindow() { + // will get automatically deleted otherwise + if (render_window->parent() == nullptr) { + delete render_window; + } + +#ifdef __unix__ + ::close(sig_interrupt_fds[0]); + ::close(sig_interrupt_fds[1]); +#endif +} + +void GMainWindow::RegisterMetaTypes() { + // Register integral and floating point types + qRegisterMetaType("u8"); + qRegisterMetaType("u16"); + qRegisterMetaType("u32"); + qRegisterMetaType("u64"); + qRegisterMetaType("u128"); + qRegisterMetaType("s8"); + qRegisterMetaType("s16"); + qRegisterMetaType("s32"); + qRegisterMetaType("s64"); + qRegisterMetaType("f32"); + qRegisterMetaType("f64"); + + // Register string types + qRegisterMetaType("std::string"); + qRegisterMetaType("std::wstring"); + qRegisterMetaType("std::u8string"); + qRegisterMetaType("std::u16string"); + qRegisterMetaType("std::u32string"); + qRegisterMetaType("std::string_view"); + qRegisterMetaType("std::wstring_view"); + qRegisterMetaType("std::u8string_view"); + qRegisterMetaType("std::u16string_view"); + qRegisterMetaType("std::u32string_view"); + + // Register applet types + + // Cabinet Applet + qRegisterMetaType("Core::Frontend::CabinetParameters"); + qRegisterMetaType>( + "std::shared_ptr"); + + // Controller Applet + qRegisterMetaType("Core::Frontend::ControllerParameters"); + + // Profile Select Applet + qRegisterMetaType( + "Core::Frontend::ProfileSelectParameters"); + + // Software Keyboard Applet + qRegisterMetaType( + "Core::Frontend::KeyboardInitializeParameters"); + qRegisterMetaType( + "Core::Frontend::InlineAppearParameters"); + qRegisterMetaType("Core::Frontend::InlineTextParameters"); + qRegisterMetaType("Service::AM::Frontend::SwkbdResult"); + qRegisterMetaType( + "Service::AM::Frontend::SwkbdTextCheckResult"); + qRegisterMetaType( + "Service::AM::Frontend::SwkbdReplyType"); + + // Web Browser Applet + qRegisterMetaType("Service::AM::Frontend::WebExitReason"); + + // Register loader types + qRegisterMetaType("Core::SystemResultStatus"); +} + +void GMainWindow::AmiiboSettingsShowDialog(const Core::Frontend::CabinetParameters& parameters, + std::shared_ptr nfp_device) { + cabinet_applet = + new QtAmiiboSettingsDialog(this, parameters, input_subsystem.get(), nfp_device); + SCOPE_EXIT { + cabinet_applet->deleteLater(); + cabinet_applet = nullptr; + }; + + cabinet_applet->setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowStaysOnTopHint | + Qt::WindowTitleHint | Qt::WindowSystemMenuHint); + cabinet_applet->setWindowModality(Qt::WindowModal); + + if (cabinet_applet->exec() == QDialog::Rejected) { + emit AmiiboSettingsFinished(false, {}); + return; + } + + emit AmiiboSettingsFinished(true, cabinet_applet->GetName()); +} + +void GMainWindow::AmiiboSettingsRequestExit() { + if (cabinet_applet) { + cabinet_applet->reject(); + } +} + +void GMainWindow::ControllerSelectorReconfigureControllers( + const Core::Frontend::ControllerParameters& parameters) { + controller_applet = + new QtControllerSelectorDialog(this, parameters, input_subsystem.get(), *system); + SCOPE_EXIT { + controller_applet->deleteLater(); + controller_applet = nullptr; + }; + + controller_applet->setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | + Qt::WindowStaysOnTopHint | Qt::WindowTitleHint | + Qt::WindowSystemMenuHint); + controller_applet->setWindowModality(Qt::WindowModal); + bool is_success = controller_applet->exec() != QDialog::Rejected; + + // Don't forget to apply settings. + system->HIDCore().DisableAllControllerConfiguration(); + system->ApplySettings(); + config->SaveAllValues(); + + UpdateStatusButtons(); + + emit ControllerSelectorReconfigureFinished(is_success); +} + +void GMainWindow::ControllerSelectorRequestExit() { + if (controller_applet) { + controller_applet->reject(); + } +} + +void GMainWindow::ProfileSelectorSelectProfile( + const Core::Frontend::ProfileSelectParameters& parameters) { + profile_select_applet = new QtProfileSelectionDialog(*system, this, parameters); + SCOPE_EXIT { + profile_select_applet->deleteLater(); + profile_select_applet = nullptr; + }; + + profile_select_applet->setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | + Qt::WindowStaysOnTopHint | Qt::WindowTitleHint | + Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint); + profile_select_applet->setWindowModality(Qt::WindowModal); + if (profile_select_applet->exec() == QDialog::Rejected) { + emit ProfileSelectorFinishedSelection(std::nullopt); + return; + } + + const auto uuid = system->GetProfileManager().GetUser( + static_cast(profile_select_applet->GetIndex())); + if (!uuid.has_value()) { + emit ProfileSelectorFinishedSelection(std::nullopt); + return; + } + + emit ProfileSelectorFinishedSelection(uuid); +} + +void GMainWindow::ProfileSelectorRequestExit() { + if (profile_select_applet) { + profile_select_applet->reject(); + } +} + +void GMainWindow::SoftwareKeyboardInitialize( + bool is_inline, Core::Frontend::KeyboardInitializeParameters initialize_parameters) { + if (software_keyboard) { + LOG_ERROR(Frontend, "The software keyboard is already initialized!"); + return; + } + + software_keyboard = new QtSoftwareKeyboardDialog(render_window, *system, is_inline, + std::move(initialize_parameters)); + + if (is_inline) { + connect( + software_keyboard, &QtSoftwareKeyboardDialog::SubmitInlineText, this, + [this](Service::AM::Frontend::SwkbdReplyType reply_type, std::u16string submitted_text, + s32 cursor_position) { + emit SoftwareKeyboardSubmitInlineText(reply_type, submitted_text, cursor_position); + }, + Qt::QueuedConnection); + } else { + connect( + software_keyboard, &QtSoftwareKeyboardDialog::SubmitNormalText, this, + [this](Service::AM::Frontend::SwkbdResult result, std::u16string submitted_text, + bool confirmed) { + emit SoftwareKeyboardSubmitNormalText(result, submitted_text, confirmed); + }, + Qt::QueuedConnection); + } +} + +void GMainWindow::SoftwareKeyboardShowNormal() { + if (!software_keyboard) { + LOG_ERROR(Frontend, "The software keyboard is not initialized!"); + return; + } + + const auto& layout = render_window->GetFramebufferLayout(); + + const auto x = layout.screen.left; + const auto y = layout.screen.top; + const auto w = layout.screen.GetWidth(); + const auto h = layout.screen.GetHeight(); + const auto scale_ratio = devicePixelRatioF(); + + software_keyboard->ShowNormalKeyboard(render_window->mapToGlobal(QPoint(x, y) / scale_ratio), + QSize(w, h) / scale_ratio); +} + +void GMainWindow::SoftwareKeyboardShowTextCheck( + Service::AM::Frontend::SwkbdTextCheckResult text_check_result, + std::u16string text_check_message) { + if (!software_keyboard) { + LOG_ERROR(Frontend, "The software keyboard is not initialized!"); + return; + } + + software_keyboard->ShowTextCheckDialog(text_check_result, text_check_message); +} + +void GMainWindow::SoftwareKeyboardShowInline( + Core::Frontend::InlineAppearParameters appear_parameters) { + if (!software_keyboard) { + LOG_ERROR(Frontend, "The software keyboard is not initialized!"); + return; + } + + const auto& layout = render_window->GetFramebufferLayout(); + + const auto x = + static_cast(layout.screen.left + (0.5f * layout.screen.GetWidth() * + ((2.0f * appear_parameters.key_top_translate_x) + + (1.0f - appear_parameters.key_top_scale_x)))); + const auto y = + static_cast(layout.screen.top + (layout.screen.GetHeight() * + ((2.0f * appear_parameters.key_top_translate_y) + + (1.0f - appear_parameters.key_top_scale_y)))); + const auto w = static_cast(layout.screen.GetWidth() * appear_parameters.key_top_scale_x); + const auto h = static_cast(layout.screen.GetHeight() * appear_parameters.key_top_scale_y); + const auto scale_ratio = devicePixelRatioF(); + + software_keyboard->ShowInlineKeyboard(std::move(appear_parameters), + render_window->mapToGlobal(QPoint(x, y) / scale_ratio), + QSize(w, h) / scale_ratio); +} + +void GMainWindow::SoftwareKeyboardHideInline() { + if (!software_keyboard) { + LOG_ERROR(Frontend, "The software keyboard is not initialized!"); + return; + } + + software_keyboard->HideInlineKeyboard(); +} + +void GMainWindow::SoftwareKeyboardInlineTextChanged( + Core::Frontend::InlineTextParameters text_parameters) { + if (!software_keyboard) { + LOG_ERROR(Frontend, "The software keyboard is not initialized!"); + return; + } + + software_keyboard->InlineTextChanged(std::move(text_parameters)); +} + +void GMainWindow::SoftwareKeyboardExit() { + if (!software_keyboard) { + return; + } + + software_keyboard->ExitKeyboard(); + + software_keyboard = nullptr; +} + +void GMainWindow::WebBrowserOpenWebPage(const std::string& main_url, + const std::string& additional_args, bool is_local) { +#ifdef SUDACHI_USE_QT_WEB_ENGINE + + // Raw input breaks with the web applet, Disable web applets if enabled + if (UISettings::values.disable_web_applet || Settings::values.enable_raw_input) { + emit WebBrowserClosed(Service::AM::Frontend::WebExitReason::WindowClosed, + "http://localhost/"); + return; + } + + web_applet = new QtNXWebEngineView(this, *system, input_subsystem.get()); + + ui->action_Pause->setEnabled(false); + ui->action_Restart->setEnabled(false); + ui->action_Stop->setEnabled(false); + + { + QProgressDialog loading_progress(this); + loading_progress.setLabelText(tr("Loading Web Applet...")); + loading_progress.setRange(0, 3); + loading_progress.setValue(0); + + if (is_local && !Common::FS::Exists(main_url)) { + loading_progress.show(); + + auto future = QtConcurrent::run([this] { emit WebBrowserExtractOfflineRomFS(); }); + + while (!future.isFinished()) { + QCoreApplication::processEvents(); + + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + } + + loading_progress.setValue(1); + + if (is_local) { + web_applet->LoadLocalWebPage(main_url, additional_args); + } else { + web_applet->LoadExternalWebPage(main_url, additional_args); + } + + if (render_window->IsLoadingComplete()) { + render_window->hide(); + } + + const auto& layout = render_window->GetFramebufferLayout(); + const auto scale_ratio = devicePixelRatioF(); + web_applet->resize(layout.screen.GetWidth() / scale_ratio, + layout.screen.GetHeight() / scale_ratio); + web_applet->move(layout.screen.left / scale_ratio, + (layout.screen.top / scale_ratio) + menuBar()->height()); + web_applet->setZoomFactor(static_cast(layout.screen.GetWidth() / scale_ratio) / + static_cast(Layout::ScreenUndocked::Width)); + + web_applet->setFocus(); + web_applet->show(); + + loading_progress.setValue(2); + + QCoreApplication::processEvents(); + + loading_progress.setValue(3); + } + + bool exit_check = false; + + // TODO (Morph): Remove this + QAction* exit_action = new QAction(tr("Disable Web Applet"), this); + connect(exit_action, &QAction::triggered, this, [this] { + const auto result = QMessageBox::warning( + this, tr("Disable Web Applet"), + tr("Disabling the web applet can lead to undefined behavior and should only be used " + "with Super Mario 3D All-Stars. Are you sure you want to disable the web " + "applet?\n(This can be re-enabled in the Debug settings.)"), + QMessageBox::Yes | QMessageBox::No); + if (result == QMessageBox::Yes) { + UISettings::values.disable_web_applet = true; + web_applet->SetFinished(true); + } + }); + ui->menubar->addAction(exit_action); + + while (!web_applet->IsFinished()) { + QCoreApplication::processEvents(); + + if (!exit_check) { + web_applet->page()->runJavaScript( + QStringLiteral("end_applet;"), [&](const QVariant& variant) { + exit_check = false; + if (variant.toBool()) { + web_applet->SetFinished(true); + web_applet->SetExitReason( + Service::AM::Frontend::WebExitReason::EndButtonPressed); + } + }); + + exit_check = true; + } + + if (web_applet->GetCurrentURL().contains(QStringLiteral("localhost"))) { + if (!web_applet->IsFinished()) { + web_applet->SetFinished(true); + web_applet->SetExitReason(Service::AM::Frontend::WebExitReason::CallbackURL); + } + + web_applet->SetLastURL(web_applet->GetCurrentURL().toStdString()); + } + + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + + const auto exit_reason = web_applet->GetExitReason(); + const auto last_url = web_applet->GetLastURL(); + + web_applet->hide(); + + render_window->setFocus(); + + if (render_window->IsLoadingComplete()) { + render_window->show(); + } + + ui->action_Pause->setEnabled(true); + ui->action_Restart->setEnabled(true); + ui->action_Stop->setEnabled(true); + + ui->menubar->removeAction(exit_action); + + QCoreApplication::processEvents(); + + emit WebBrowserClosed(exit_reason, last_url); + +#else + + // Utilize the same fallback as the default web browser applet. + emit WebBrowserClosed(Service::AM::Frontend::WebExitReason::WindowClosed, "http://localhost/"); + +#endif +} + +void GMainWindow::WebBrowserRequestExit() { +#ifdef SUDACHI_USE_QT_WEB_ENGINE + if (web_applet) { + web_applet->SetExitReason(Service::AM::Frontend::WebExitReason::ExitRequested); + web_applet->SetFinished(true); + } +#endif +} + +void GMainWindow::InitializeWidgets() { +#ifdef SUDACHI_ENABLE_COMPATIBILITY_REPORTING + ui->action_Report_Compatibility->setVisible(true); +#endif + render_window = new GRenderWindow(this, emu_thread.get(), input_subsystem, *system); + render_window->hide(); + + game_list = new GameList(vfs, provider.get(), *play_time_manager, *system, this); + ui->horizontalLayout->addWidget(game_list); + + game_list_placeholder = new GameListPlaceholder(this); + ui->horizontalLayout->addWidget(game_list_placeholder); + game_list_placeholder->setVisible(false); + + loading_screen = new LoadingScreen(this); + loading_screen->hide(); + ui->horizontalLayout->addWidget(loading_screen); + connect(loading_screen, &LoadingScreen::Hidden, [&] { + loading_screen->Clear(); + if (emulation_running) { + render_window->show(); + render_window->setFocus(); + } + }); + + multiplayer_state = new MultiplayerState(this, game_list->GetModel(), ui->action_Leave_Room, + ui->action_Show_Room, *system); + multiplayer_state->setVisible(false); + + // Create status bar + message_label = new QLabel(); + // Configured separately for left alignment + message_label->setFrameStyle(QFrame::NoFrame); + message_label->setContentsMargins(4, 0, 4, 0); + message_label->setAlignment(Qt::AlignLeft); + statusBar()->addPermanentWidget(message_label, 1); + + shader_building_label = new QLabel(); + shader_building_label->setToolTip(tr("The amount of shaders currently being built")); + res_scale_label = new QLabel(); + res_scale_label->setToolTip(tr("The current selected resolution scaling multiplier.")); + emu_speed_label = new QLabel(); + emu_speed_label->setToolTip( + tr("Current emulation speed. Values higher or lower than 100% " + "indicate emulation is running faster or slower than a Switch.")); + game_fps_label = new QLabel(); + game_fps_label->setToolTip(tr("How many frames per second the game is currently displaying. " + "This will vary from game to game and scene to scene.")); + emu_frametime_label = new QLabel(); + emu_frametime_label->setToolTip( + tr("Time taken to emulate a Switch frame, not counting framelimiting or v-sync. For " + "full-speed emulation this should be at most 16.67 ms.")); + + for (auto& label : {shader_building_label, res_scale_label, emu_speed_label, game_fps_label, + emu_frametime_label}) { + label->setVisible(false); + label->setFrameStyle(QFrame::NoFrame); + label->setContentsMargins(4, 0, 4, 0); + statusBar()->addPermanentWidget(label); + } + + firmware_label = new QLabel(); + firmware_label->setObjectName(QStringLiteral("FirmwareLabel")); + firmware_label->setVisible(false); + firmware_label->setFocusPolicy(Qt::NoFocus); + statusBar()->addPermanentWidget(firmware_label); + + statusBar()->addPermanentWidget(multiplayer_state->GetStatusText(), 0); + statusBar()->addPermanentWidget(multiplayer_state->GetStatusIcon(), 0); + + tas_label = new QLabel(); + tas_label->setObjectName(QStringLiteral("TASlabel")); + tas_label->setFocusPolicy(Qt::NoFocus); + statusBar()->insertPermanentWidget(0, tas_label); + + volume_popup = new QWidget(this); + volume_popup->setWindowFlags(Qt::FramelessWindowHint | Qt::NoDropShadowWindowHint | Qt::Popup); + volume_popup->setLayout(new QVBoxLayout()); + volume_popup->setMinimumWidth(200); + + volume_slider = new QSlider(Qt::Horizontal); + volume_slider->setObjectName(QStringLiteral("volume_slider")); + volume_slider->setMaximum(200); + volume_slider->setPageStep(5); + volume_popup->layout()->addWidget(volume_slider); + + volume_button = new VolumeButton(); + volume_button->setObjectName(QStringLiteral("TogglableStatusBarButton")); + volume_button->setFocusPolicy(Qt::NoFocus); + volume_button->setCheckable(true); + UpdateVolumeUI(); + connect(volume_slider, &QSlider::valueChanged, this, [this](int percentage) { + Settings::values.audio_muted = false; + const auto volume = static_cast(percentage); + Settings::values.volume.SetValue(volume); + UpdateVolumeUI(); + }); + connect(volume_button, &QPushButton::clicked, this, [&] { + UpdateVolumeUI(); + volume_popup->setVisible(!volume_popup->isVisible()); + QRect rect = volume_button->geometry(); + QPoint bottomLeft = statusBar()->mapToGlobal(rect.topLeft()); + bottomLeft.setY(bottomLeft.y() - volume_popup->geometry().height()); + volume_popup->setGeometry(QRect(bottomLeft, QSize(rect.width(), rect.height()))); + }); + volume_button->setContextMenuPolicy(Qt::CustomContextMenu); + connect(volume_button, &QPushButton::customContextMenuRequested, + [this](const QPoint& menu_location) { + QMenu context_menu; + context_menu.addAction( + Settings::values.audio_muted ? tr("Unmute") : tr("Mute"), [this] { + Settings::values.audio_muted = !Settings::values.audio_muted; + UpdateVolumeUI(); + }); + + context_menu.addAction(tr("Reset Volume"), [this] { + Settings::values.volume.SetValue(100); + UpdateVolumeUI(); + }); + + context_menu.exec(volume_button->mapToGlobal(menu_location)); + volume_button->repaint(); + }); + connect(volume_button, &VolumeButton::VolumeChanged, this, &GMainWindow::UpdateVolumeUI); + + statusBar()->insertPermanentWidget(0, volume_button); + + // setup AA button + aa_status_button = new QPushButton(); + aa_status_button->setObjectName(QStringLiteral("TogglableStatusBarButton")); + aa_status_button->setFocusPolicy(Qt::NoFocus); + connect(aa_status_button, &QPushButton::clicked, [&] { + auto aa_mode = Settings::values.anti_aliasing.GetValue(); + aa_mode = static_cast(static_cast(aa_mode) + 1); + if (aa_mode == Settings::AntiAliasing::MaxEnum) { + aa_mode = Settings::AntiAliasing::None; + } + Settings::values.anti_aliasing.SetValue(aa_mode); + aa_status_button->setChecked(true); + UpdateAAText(); + }); + UpdateAAText(); + aa_status_button->setCheckable(true); + aa_status_button->setChecked(true); + aa_status_button->setContextMenuPolicy(Qt::CustomContextMenu); + connect(aa_status_button, &QPushButton::customContextMenuRequested, + [this](const QPoint& menu_location) { + QMenu context_menu; + for (auto const& aa_text_pair : ConfigurationShared::anti_aliasing_texts_map) { + context_menu.addAction(aa_text_pair.second, [this, aa_text_pair] { + Settings::values.anti_aliasing.SetValue(aa_text_pair.first); + UpdateAAText(); + }); + } + context_menu.exec(aa_status_button->mapToGlobal(menu_location)); + aa_status_button->repaint(); + }); + statusBar()->insertPermanentWidget(0, aa_status_button); + + // Setup Filter button + filter_status_button = new QPushButton(); + filter_status_button->setObjectName(QStringLiteral("TogglableStatusBarButton")); + filter_status_button->setFocusPolicy(Qt::NoFocus); + connect(filter_status_button, &QPushButton::clicked, this, + &GMainWindow::OnToggleAdaptingFilter); + UpdateFilterText(); + filter_status_button->setCheckable(true); + filter_status_button->setChecked(true); + filter_status_button->setContextMenuPolicy(Qt::CustomContextMenu); + connect(filter_status_button, &QPushButton::customContextMenuRequested, + [this](const QPoint& menu_location) { + QMenu context_menu; + for (auto const& filter_text_pair : ConfigurationShared::scaling_filter_texts_map) { + context_menu.addAction(filter_text_pair.second, [this, filter_text_pair] { + Settings::values.scaling_filter.SetValue(filter_text_pair.first); + UpdateFilterText(); + }); + } + context_menu.exec(filter_status_button->mapToGlobal(menu_location)); + filter_status_button->repaint(); + }); + statusBar()->insertPermanentWidget(0, filter_status_button); + + // Setup Dock button + dock_status_button = new QPushButton(); + dock_status_button->setObjectName(QStringLiteral("DockingStatusBarButton")); + dock_status_button->setFocusPolicy(Qt::NoFocus); + connect(dock_status_button, &QPushButton::clicked, this, &GMainWindow::OnToggleDockedMode); + dock_status_button->setCheckable(true); + UpdateDockedButton(); + dock_status_button->setContextMenuPolicy(Qt::CustomContextMenu); + connect(dock_status_button, &QPushButton::customContextMenuRequested, + [this](const QPoint& menu_location) { + QMenu context_menu; + + for (auto const& pair : ConfigurationShared::use_docked_mode_texts_map) { + context_menu.addAction(pair.second, [this, &pair] { + if (pair.first != Settings::values.use_docked_mode.GetValue()) { + OnToggleDockedMode(); + } + }); + } + context_menu.exec(dock_status_button->mapToGlobal(menu_location)); + dock_status_button->repaint(); + }); + statusBar()->insertPermanentWidget(0, dock_status_button); + + // Setup GPU Accuracy button + gpu_accuracy_button = new QPushButton(); + gpu_accuracy_button->setObjectName(QStringLiteral("GPUStatusBarButton")); + gpu_accuracy_button->setCheckable(true); + gpu_accuracy_button->setFocusPolicy(Qt::NoFocus); + connect(gpu_accuracy_button, &QPushButton::clicked, this, &GMainWindow::OnToggleGpuAccuracy); + UpdateGPUAccuracyButton(); + gpu_accuracy_button->setContextMenuPolicy(Qt::CustomContextMenu); + connect(gpu_accuracy_button, &QPushButton::customContextMenuRequested, + [this](const QPoint& menu_location) { + QMenu context_menu; + + for (auto const& gpu_accuracy_pair : ConfigurationShared::gpu_accuracy_texts_map) { + if (gpu_accuracy_pair.first == Settings::GpuAccuracy::Extreme) { + continue; + } + context_menu.addAction(gpu_accuracy_pair.second, [this, gpu_accuracy_pair] { + Settings::values.gpu_accuracy.SetValue(gpu_accuracy_pair.first); + UpdateGPUAccuracyButton(); + }); + } + context_menu.exec(gpu_accuracy_button->mapToGlobal(menu_location)); + gpu_accuracy_button->repaint(); + }); + statusBar()->insertPermanentWidget(0, gpu_accuracy_button); + + // Setup Renderer API button + renderer_status_button = new QPushButton(); + renderer_status_button->setObjectName(QStringLiteral("RendererStatusBarButton")); + renderer_status_button->setCheckable(true); + renderer_status_button->setFocusPolicy(Qt::NoFocus); + connect(renderer_status_button, &QPushButton::clicked, this, &GMainWindow::OnToggleGraphicsAPI); + UpdateAPIText(); + renderer_status_button->setCheckable(true); + renderer_status_button->setChecked(Settings::values.renderer_backend.GetValue() == + Settings::RendererBackend::Vulkan); + renderer_status_button->setContextMenuPolicy(Qt::CustomContextMenu); + connect(renderer_status_button, &QPushButton::customContextMenuRequested, + [this](const QPoint& menu_location) { + QMenu context_menu; + + for (auto const& renderer_backend_pair : + ConfigurationShared::renderer_backend_texts_map) { + if (renderer_backend_pair.first == Settings::RendererBackend::Null) { + continue; + } + context_menu.addAction( + renderer_backend_pair.second, [this, renderer_backend_pair] { + Settings::values.renderer_backend.SetValue(renderer_backend_pair.first); + UpdateAPIText(); + }); + } + context_menu.exec(renderer_status_button->mapToGlobal(menu_location)); + renderer_status_button->repaint(); + }); + statusBar()->insertPermanentWidget(0, renderer_status_button); + + statusBar()->setVisible(true); + setStyleSheet(QStringLiteral("QStatusBar::item{border: none;}")); +} + +void GMainWindow::InitializeDebugWidgets() { + QMenu* debug_menu = ui->menu_View_Debugging; + +#if MICROPROFILE_ENABLED + microProfileDialog = new MicroProfileDialog(this); + microProfileDialog->hide(); + debug_menu->addAction(microProfileDialog->toggleViewAction()); +#endif + + waitTreeWidget = new WaitTreeWidget(*system, this); + addDockWidget(Qt::LeftDockWidgetArea, waitTreeWidget); + waitTreeWidget->hide(); + debug_menu->addAction(waitTreeWidget->toggleViewAction()); + + controller_dialog = new ControllerDialog(system->HIDCore(), input_subsystem, this); + controller_dialog->hide(); + debug_menu->addAction(controller_dialog->toggleViewAction()); + + connect(this, &GMainWindow::EmulationStarting, waitTreeWidget, + &WaitTreeWidget::OnEmulationStarting); + connect(this, &GMainWindow::EmulationStopping, waitTreeWidget, + &WaitTreeWidget::OnEmulationStopping); +} + +void GMainWindow::InitializeRecentFileMenuActions() { + for (int i = 0; i < max_recent_files_item; ++i) { + actions_recent_files[i] = new QAction(this); + actions_recent_files[i]->setVisible(false); + connect(actions_recent_files[i], &QAction::triggered, this, &GMainWindow::OnMenuRecentFile); + + ui->menu_recent_files->addAction(actions_recent_files[i]); + } + ui->menu_recent_files->addSeparator(); + QAction* action_clear_recent_files = new QAction(this); + action_clear_recent_files->setText(tr("&Clear Recent Files")); + connect(action_clear_recent_files, &QAction::triggered, this, [this] { + UISettings::values.recent_files.clear(); + UpdateRecentFiles(); + }); + ui->menu_recent_files->addAction(action_clear_recent_files); + + UpdateRecentFiles(); +} + +void GMainWindow::LinkActionShortcut(QAction* action, const QString& action_name, + const bool tas_allowed) { + static const auto main_window = std::string("Main Window"); + action->setShortcut(hotkey_registry.GetKeySequence(main_window, action_name.toStdString())); + action->setShortcutContext( + hotkey_registry.GetShortcutContext(main_window, action_name.toStdString())); + action->setAutoRepeat(false); + + this->addAction(action); + + auto* controller = system->HIDCore().GetEmulatedController(Core::HID::NpadIdType::Player1); + const auto* controller_hotkey = + hotkey_registry.GetControllerHotkey(main_window, action_name.toStdString(), controller); + connect( + controller_hotkey, &ControllerShortcut::Activated, this, + [action, tas_allowed, this] { + auto [tas_status, current_tas_frame, total_tas_frames] = + input_subsystem->GetTas()->GetStatus(); + if (tas_allowed || tas_status == InputCommon::TasInput::TasState::Stopped) { + action->trigger(); + } + }, + Qt::QueuedConnection); +} + +void GMainWindow::InitializeHotkeys() { + hotkey_registry.LoadHotkeys(); + + LinkActionShortcut(ui->action_Load_File, QStringLiteral("Load File")); + LinkActionShortcut(ui->action_Load_Amiibo, QStringLiteral("Load/Remove Amiibo")); + LinkActionShortcut(ui->action_Exit, QStringLiteral("Exit sudachi")); + LinkActionShortcut(ui->action_Restart, QStringLiteral("Restart Emulation")); + LinkActionShortcut(ui->action_Pause, QStringLiteral("Continue/Pause Emulation")); + LinkActionShortcut(ui->action_Stop, QStringLiteral("Stop Emulation")); + LinkActionShortcut(ui->action_Show_Filter_Bar, QStringLiteral("Toggle Filter Bar")); + LinkActionShortcut(ui->action_Show_Status_Bar, QStringLiteral("Toggle Status Bar")); + LinkActionShortcut(ui->action_Fullscreen, QStringLiteral("Fullscreen")); + LinkActionShortcut(ui->action_Capture_Screenshot, QStringLiteral("Capture Screenshot")); + LinkActionShortcut(ui->action_TAS_Start, QStringLiteral("TAS Start/Stop"), true); + LinkActionShortcut(ui->action_TAS_Record, QStringLiteral("TAS Record"), true); + LinkActionShortcut(ui->action_TAS_Reset, QStringLiteral("TAS Reset"), true); + LinkActionShortcut(ui->action_View_Lobby, + QStringLiteral("Multiplayer Browse Public Game Lobby")); + LinkActionShortcut(ui->action_Start_Room, QStringLiteral("Multiplayer Create Room")); + LinkActionShortcut(ui->action_Connect_To_Room, + QStringLiteral("Multiplayer Direct Connect to Room")); + LinkActionShortcut(ui->action_Show_Room, QStringLiteral("Multiplayer Show Current Room")); + LinkActionShortcut(ui->action_Leave_Room, QStringLiteral("Multiplayer Leave Room")); + + static const QString main_window = QStringLiteral("Main Window"); + const auto connect_shortcut = [&](const QString& action_name, const Fn& function) { + const auto* hotkey = + hotkey_registry.GetHotkey(main_window.toStdString(), action_name.toStdString(), this); + auto* controller = system->HIDCore().GetEmulatedController(Core::HID::NpadIdType::Player1); + const auto* controller_hotkey = hotkey_registry.GetControllerHotkey( + main_window.toStdString(), action_name.toStdString(), controller); + connect(hotkey, &QShortcut::activated, this, function); + connect(controller_hotkey, &ControllerShortcut::Activated, this, function, + Qt::QueuedConnection); + }; + + connect_shortcut(QStringLiteral("Exit Fullscreen"), [&] { + if (emulation_running && ui->action_Fullscreen->isChecked()) { + ui->action_Fullscreen->setChecked(false); + ToggleFullscreen(); + } + }); + connect_shortcut(QStringLiteral("Change Adapting Filter"), + &GMainWindow::OnToggleAdaptingFilter); + connect_shortcut(QStringLiteral("Change Docked Mode"), &GMainWindow::OnToggleDockedMode); + connect_shortcut(QStringLiteral("Change GPU Accuracy"), &GMainWindow::OnToggleGpuAccuracy); + connect_shortcut(QStringLiteral("Audio Mute/Unmute"), &GMainWindow::OnMute); + connect_shortcut(QStringLiteral("Audio Volume Down"), &GMainWindow::OnDecreaseVolume); + connect_shortcut(QStringLiteral("Audio Volume Up"), &GMainWindow::OnIncreaseVolume); + connect_shortcut(QStringLiteral("Toggle Framerate Limit"), [] { + Settings::values.use_speed_limit.SetValue(!Settings::values.use_speed_limit.GetValue()); + }); + connect_shortcut(QStringLiteral("Toggle Renderdoc Capture"), [this] { + if (Settings::values.enable_renderdoc_hotkey) { + system->GetRenderdocAPI().ToggleCapture(); + } + }); + connect_shortcut(QStringLiteral("Toggle Mouse Panning"), [&] { + Settings::values.mouse_panning = !Settings::values.mouse_panning; + if (Settings::values.mouse_panning) { + render_window->installEventFilter(render_window); + render_window->setAttribute(Qt::WA_Hover, true); + } + }); +} + +void GMainWindow::SetDefaultUIGeometry() { + // geometry: 53% of the window contents are in the upper screen half, 47% in the lower half + const QRect screenRect = QGuiApplication::primaryScreen()->geometry(); + + const int w = screenRect.width() * 2 / 3; + const int h = screenRect.height() * 2 / 3; + const int x = (screenRect.x() + screenRect.width()) / 2 - w / 2; + const int y = (screenRect.y() + screenRect.height()) / 2 - h * 53 / 100; + + setGeometry(x, y, w, h); +} + +void GMainWindow::RestoreUIState() { + setWindowFlags(windowFlags() & ~Qt::FramelessWindowHint); + restoreGeometry(UISettings::values.geometry); + // Work-around because the games list isn't supposed to be full screen + if (isFullScreen()) { + showNormal(); + } + restoreState(UISettings::values.state); + render_window->setWindowFlags(render_window->windowFlags() & ~Qt::FramelessWindowHint); + render_window->restoreGeometry(UISettings::values.renderwindow_geometry); +#if MICROPROFILE_ENABLED + microProfileDialog->restoreGeometry(UISettings::values.microprofile_geometry); + microProfileDialog->setVisible(UISettings::values.microprofile_visible.GetValue()); +#endif + + game_list->LoadInterfaceLayout(); + + ui->action_Single_Window_Mode->setChecked(UISettings::values.single_window_mode.GetValue()); + ToggleWindowMode(); + + ui->action_Fullscreen->setChecked(UISettings::values.fullscreen.GetValue()); + + ui->action_Display_Dock_Widget_Headers->setChecked( + UISettings::values.display_titlebar.GetValue()); + OnDisplayTitleBars(ui->action_Display_Dock_Widget_Headers->isChecked()); + + ui->action_Show_Filter_Bar->setChecked(UISettings::values.show_filter_bar.GetValue()); + game_list->SetFilterVisible(ui->action_Show_Filter_Bar->isChecked()); + + ui->action_Show_Status_Bar->setChecked(UISettings::values.show_status_bar.GetValue()); + statusBar()->setVisible(ui->action_Show_Status_Bar->isChecked()); + Debugger::ToggleConsole(); +} + +void GMainWindow::OnAppFocusStateChanged(Qt::ApplicationState state) { + if (state != Qt::ApplicationHidden && state != Qt::ApplicationInactive && + state != Qt::ApplicationActive) { + LOG_DEBUG(Frontend, "ApplicationState unusual flag: {} ", state); + } + if (!emulation_running) { + return; + } + if (UISettings::values.pause_when_in_background) { + if (emu_thread->IsRunning() && + (state & (Qt::ApplicationHidden | Qt::ApplicationInactive))) { + auto_paused = true; + OnPauseGame(); + } else if (!emu_thread->IsRunning() && auto_paused && state == Qt::ApplicationActive) { + auto_paused = false; + OnStartGame(); + } + } + if (UISettings::values.mute_when_in_background) { + if (!Settings::values.audio_muted && + (state & (Qt::ApplicationHidden | Qt::ApplicationInactive))) { + Settings::values.audio_muted = true; + auto_muted = true; + } else if (auto_muted && state == Qt::ApplicationActive) { + Settings::values.audio_muted = false; + auto_muted = false; + } + UpdateVolumeUI(); + } +} + +void GMainWindow::ConnectWidgetEvents() { + connect(game_list, &GameList::BootGame, this, &GMainWindow::BootGameFromList); + connect(game_list, &GameList::GameChosen, this, &GMainWindow::OnGameListLoadFile); + connect(game_list, &GameList::OpenDirectory, this, &GMainWindow::OnGameListOpenDirectory); + connect(game_list, &GameList::OpenFolderRequested, this, &GMainWindow::OnGameListOpenFolder); + connect(game_list, &GameList::OpenTransferableShaderCacheRequested, this, + &GMainWindow::OnTransferableShaderCacheOpenFile); + connect(game_list, &GameList::RemoveInstalledEntryRequested, this, + &GMainWindow::OnGameListRemoveInstalledEntry); + connect(game_list, &GameList::RemoveFileRequested, this, &GMainWindow::OnGameListRemoveFile); + connect(game_list, &GameList::RemovePlayTimeRequested, this, + &GMainWindow::OnGameListRemovePlayTimeData); + connect(game_list, &GameList::DumpRomFSRequested, this, &GMainWindow::OnGameListDumpRomFS); + connect(game_list, &GameList::VerifyIntegrityRequested, this, + &GMainWindow::OnGameListVerifyIntegrity); + connect(game_list, &GameList::CopyTIDRequested, this, &GMainWindow::OnGameListCopyTID); + connect(game_list, &GameList::NavigateToGamedbEntryRequested, this, + &GMainWindow::OnGameListNavigateToGamedbEntry); + connect(game_list, &GameList::CreateShortcut, this, &GMainWindow::OnGameListCreateShortcut); + connect(game_list, &GameList::AddDirectory, this, &GMainWindow::OnGameListAddDirectory); + connect(game_list_placeholder, &GameListPlaceholder::AddDirectory, this, + &GMainWindow::OnGameListAddDirectory); + connect(game_list, &GameList::ShowList, this, &GMainWindow::OnGameListShowList); + connect(game_list, &GameList::PopulatingCompleted, + [this] { multiplayer_state->UpdateGameList(game_list->GetModel()); }); + connect(game_list, &GameList::SaveConfig, this, &GMainWindow::OnSaveConfig); + + connect(game_list, &GameList::OpenPerGameGeneralRequested, this, + &GMainWindow::OnGameListOpenPerGameProperties); + + connect(this, &GMainWindow::UpdateInstallProgress, this, + &GMainWindow::IncrementInstallProgress); + + connect(this, &GMainWindow::EmulationStarting, render_window, + &GRenderWindow::OnEmulationStarting); + connect(this, &GMainWindow::EmulationStopping, render_window, + &GRenderWindow::OnEmulationStopping); + + // Software Keyboard Applet + connect(this, &GMainWindow::EmulationStarting, this, &GMainWindow::SoftwareKeyboardExit); + connect(this, &GMainWindow::EmulationStopping, this, &GMainWindow::SoftwareKeyboardExit); + + connect(&status_bar_update_timer, &QTimer::timeout, this, &GMainWindow::UpdateStatusBar); + + connect(this, &GMainWindow::UpdateThemedIcons, multiplayer_state, + &MultiplayerState::UpdateThemedIcons); +} + +void GMainWindow::ConnectMenuEvents() { + const auto connect_menu = [&](QAction* action, const Fn& event_fn) { + connect(action, &QAction::triggered, this, event_fn); + // Add actions to this window so that hiding menus in fullscreen won't disable them + addAction(action); + // Add actions to the render window so that they work outside of single window mode + render_window->addAction(action); + }; + + // File + connect_menu(ui->action_Load_File, &GMainWindow::OnMenuLoadFile); + connect_menu(ui->action_Load_Folder, &GMainWindow::OnMenuLoadFolder); + connect_menu(ui->action_Install_File_NAND, &GMainWindow::OnMenuInstallToNAND); + connect_menu(ui->action_Exit, &QMainWindow::close); + connect_menu(ui->action_Load_Amiibo, &GMainWindow::OnLoadAmiibo); + + // Emulation + connect_menu(ui->action_Pause, &GMainWindow::OnPauseContinueGame); + connect_menu(ui->action_Stop, &GMainWindow::OnStopGame); + connect_menu(ui->action_Report_Compatibility, &GMainWindow::OnMenuReportCompatibility); + connect_menu(ui->action_Open_Mods_Page, &GMainWindow::OnOpenModsPage); + connect_menu(ui->action_Open_Quickstart_Guide, &GMainWindow::OnOpenQuickstartGuide); + connect_menu(ui->action_Open_FAQ, &GMainWindow::OnOpenFAQ); + connect_menu(ui->action_Restart, &GMainWindow::OnRestartGame); + connect_menu(ui->action_Configure, &GMainWindow::OnConfigure); + connect_menu(ui->action_Configure_Current_Game, &GMainWindow::OnConfigurePerGame); + + // View + connect_menu(ui->action_Fullscreen, &GMainWindow::ToggleFullscreen); + connect_menu(ui->action_Single_Window_Mode, &GMainWindow::ToggleWindowMode); + connect_menu(ui->action_Display_Dock_Widget_Headers, &GMainWindow::OnDisplayTitleBars); + connect_menu(ui->action_Show_Filter_Bar, &GMainWindow::OnToggleFilterBar); + connect_menu(ui->action_Show_Status_Bar, &GMainWindow::OnToggleStatusBar); + + connect_menu(ui->action_Reset_Window_Size_720, &GMainWindow::ResetWindowSize720); + connect_menu(ui->action_Reset_Window_Size_900, &GMainWindow::ResetWindowSize900); + connect_menu(ui->action_Reset_Window_Size_1080, &GMainWindow::ResetWindowSize1080); + ui->menu_Reset_Window_Size->addActions({ui->action_Reset_Window_Size_720, + ui->action_Reset_Window_Size_900, + ui->action_Reset_Window_Size_1080}); + + // Multiplayer + connect(ui->action_View_Lobby, &QAction::triggered, multiplayer_state, + &MultiplayerState::OnViewLobby); + connect(ui->action_Start_Room, &QAction::triggered, multiplayer_state, + &MultiplayerState::OnCreateRoom); + connect(ui->action_Leave_Room, &QAction::triggered, multiplayer_state, + &MultiplayerState::OnCloseRoom); + connect(ui->action_Connect_To_Room, &QAction::triggered, multiplayer_state, + &MultiplayerState::OnDirectConnectToRoom); + connect(ui->action_Show_Room, &QAction::triggered, multiplayer_state, + &MultiplayerState::OnOpenNetworkRoom); + connect(multiplayer_state, &MultiplayerState::SaveConfig, this, &GMainWindow::OnSaveConfig); + + // Tools + connect_menu(ui->action_Load_Album, &GMainWindow::OnAlbum); + connect_menu(ui->action_Load_Cabinet_Nickname_Owner, + [this]() { OnCabinet(Service::NFP::CabinetMode::StartNicknameAndOwnerSettings); }); + connect_menu(ui->action_Load_Cabinet_Eraser, + [this]() { OnCabinet(Service::NFP::CabinetMode::StartGameDataEraser); }); + connect_menu(ui->action_Load_Cabinet_Restorer, + [this]() { OnCabinet(Service::NFP::CabinetMode::StartRestorer); }); + connect_menu(ui->action_Load_Cabinet_Formatter, + [this]() { OnCabinet(Service::NFP::CabinetMode::StartFormatter); }); + connect_menu(ui->action_Load_Mii_Edit, &GMainWindow::OnMiiEdit); + connect_menu(ui->action_Open_Controller_Menu, &GMainWindow::OnOpenControllerMenu); + connect_menu(ui->action_Capture_Screenshot, &GMainWindow::OnCaptureScreenshot); + + // TAS + connect_menu(ui->action_TAS_Start, &GMainWindow::OnTasStartStop); + connect_menu(ui->action_TAS_Record, &GMainWindow::OnTasRecord); + connect_menu(ui->action_TAS_Reset, &GMainWindow::OnTasReset); + connect_menu(ui->action_Configure_Tas, &GMainWindow::OnConfigureTas); + + // Help + connect_menu(ui->action_Open_sudachi_Folder, &GMainWindow::OnOpenSudachiFolder); + connect_menu(ui->action_Verify_installed_contents, &GMainWindow::OnVerifyInstalledContents); + connect_menu(ui->action_Install_Firmware, &GMainWindow::OnInstallFirmware); + connect_menu(ui->action_Install_Keys, &GMainWindow::OnInstallDecryptionKeys); + connect_menu(ui->action_About, &GMainWindow::OnAbout); +} + +void GMainWindow::UpdateMenuState() { + const bool is_paused = emu_thread == nullptr || !emu_thread->IsRunning(); + const bool is_firmware_available = CheckFirmwarePresence(); + + const std::array running_actions{ + ui->action_Stop, + ui->action_Restart, + ui->action_Configure_Current_Game, + ui->action_Report_Compatibility, + ui->action_Load_Amiibo, + ui->action_Pause, + }; + + const std::array applet_actions{ui->action_Load_Album, + ui->action_Load_Cabinet_Nickname_Owner, + ui->action_Load_Cabinet_Eraser, + ui->action_Load_Cabinet_Restorer, + ui->action_Load_Cabinet_Formatter, + ui->action_Load_Mii_Edit, + ui->action_Open_Controller_Menu}; + + for (QAction* action : running_actions) { + action->setEnabled(emulation_running); + } + + ui->action_Install_Firmware->setEnabled(!emulation_running); + ui->action_Install_Keys->setEnabled(!emulation_running); + + for (QAction* action : applet_actions) { + action->setEnabled(is_firmware_available && !emulation_running); + } + + ui->action_Capture_Screenshot->setEnabled(emulation_running && !is_paused); + + if (emulation_running && is_paused) { + ui->action_Pause->setText(tr("&Continue")); + } else { + ui->action_Pause->setText(tr("&Pause")); + } + + multiplayer_state->UpdateNotificationStatus(); +} + +void GMainWindow::OnDisplayTitleBars(bool show) { + QList widgets = findChildren(); + + if (show) { + for (QDockWidget* widget : widgets) { + QWidget* old = widget->titleBarWidget(); + widget->setTitleBarWidget(nullptr); + if (old != nullptr) + delete old; + } + } else { + for (QDockWidget* widget : widgets) { + QWidget* old = widget->titleBarWidget(); + widget->setTitleBarWidget(new QWidget()); + if (old != nullptr) + delete old; + } + } +} + +void GMainWindow::SetupPrepareForSleep() { +#ifdef __unix__ + auto bus = QDBusConnection::systemBus(); + if (bus.isConnected()) { + const bool success = bus.connect( + QStringLiteral("org.freedesktop.login1"), QStringLiteral("/org/freedesktop/login1"), + QStringLiteral("org.freedesktop.login1.Manager"), QStringLiteral("PrepareForSleep"), + QStringLiteral("b"), this, SLOT(OnPrepareForSleep(bool))); + + if (!success) { + LOG_WARNING(Frontend, "Couldn't register PrepareForSleep signal"); + } + } else { + LOG_WARNING(Frontend, "QDBusConnection system bus is not connected"); + } +#endif // __unix__ +} + +void GMainWindow::OnPrepareForSleep(bool prepare_sleep) { + if (emu_thread == nullptr) { + return; + } + + if (prepare_sleep) { + if (emu_thread->IsRunning()) { + auto_paused = true; + OnPauseGame(); + } + } else { + if (!emu_thread->IsRunning() && auto_paused) { + auto_paused = false; + OnStartGame(); + } + } +} + +#ifdef __unix__ +std::array GMainWindow::sig_interrupt_fds{0, 0, 0}; + +void GMainWindow::SetupSigInterrupts() { + if (sig_interrupt_fds[2] == 1) { + return; + } + socketpair(AF_UNIX, SOCK_STREAM, 0, sig_interrupt_fds.data()); + sig_interrupt_fds[2] = 1; + + struct sigaction sa; + sa.sa_handler = &GMainWindow::HandleSigInterrupt; + sigemptyset(&sa.sa_mask); + sa.sa_flags = SA_RESETHAND; + sigaction(SIGINT, &sa, nullptr); + sigaction(SIGTERM, &sa, nullptr); + + sig_interrupt_notifier = new QSocketNotifier(sig_interrupt_fds[1], QSocketNotifier::Read, this); + connect(sig_interrupt_notifier, &QSocketNotifier::activated, this, + &GMainWindow::OnSigInterruptNotifierActivated); + connect(this, &GMainWindow::SigInterrupt, this, &GMainWindow::close); +} + +void GMainWindow::HandleSigInterrupt(int sig) { + if (sig == SIGINT) { + _exit(1); + } + + // Calling into Qt directly from a signal handler is not safe, + // so wake up a QSocketNotifier with this hacky write call instead. + char a = 1; + int ret = write(sig_interrupt_fds[0], &a, sizeof(a)); + (void)ret; +} + +void GMainWindow::OnSigInterruptNotifierActivated() { + sig_interrupt_notifier->setEnabled(false); + + char a; + int ret = read(sig_interrupt_fds[1], &a, sizeof(a)); + (void)ret; + + sig_interrupt_notifier->setEnabled(true); + + emit SigInterrupt(); +} +#endif // __unix__ + +void GMainWindow::PreventOSSleep() { +#ifdef _WIN32 + SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED | ES_DISPLAY_REQUIRED); +#elif defined(HAVE_SDL2) + SDL_DisableScreenSaver(); +#endif +} + +void GMainWindow::AllowOSSleep() { +#ifdef _WIN32 + SetThreadExecutionState(ES_CONTINUOUS); +#elif defined(HAVE_SDL2) + SDL_EnableScreenSaver(); +#endif +} + +bool GMainWindow::LoadROM(const QString& filename, Service::AM::FrontendAppletParameters params) { + // Shutdown previous session if the emu thread is still active... + if (emu_thread != nullptr) { + ShutdownGame(); + } + + if (!render_window->InitRenderTarget()) { + return false; + } + + system->SetFilesystem(vfs); + + if (params.launch_type == Service::AM::LaunchType::FrontendInitiated) { + system->GetUserChannel().clear(); + } + + system->SetFrontendAppletSet({ + std::make_unique(*this), // Amiibo Settings + (UISettings::values.controller_applet_disabled.GetValue() == true) + ? nullptr + : std::make_unique(*this), // Controller Selector + std::make_unique(*this), // Error Display + nullptr, // Mii Editor + nullptr, // Parental Controls + nullptr, // Photo Viewer + std::make_unique(*this), // Profile Selector + std::make_unique(*this), // Software Keyboard + std::make_unique(*this), // Web Browser + }); + + const Core::SystemResultStatus result{ + system->Load(*render_window, filename.toStdString(), params)}; + + const auto drd_callout = (UISettings::values.callout_flags.GetValue() & + static_cast(CalloutFlag::DRDDeprecation)) == 0; + + if (result == Core::SystemResultStatus::Success && + system->GetAppLoader().GetFileType() == Loader::FileType::DeconstructedRomDirectory && + drd_callout) { + UISettings::values.callout_flags = UISettings::values.callout_flags.GetValue() | + static_cast(CalloutFlag::DRDDeprecation); + QMessageBox::warning( + this, tr("Warning Outdated Game Format"), + tr("You are using the deconstructed ROM directory format for this game, which is an " + "outdated format that has been superseded by others such as NCA, NAX, XCI, or " + "NSP. Deconstructed ROM directories lack icons, metadata, and update " + "support.

For an explanation of the various Switch formats sudachi supports, check out our " + "wiki. This message will not be shown again.")); + } + + if (result != Core::SystemResultStatus::Success) { + switch (result) { + case Core::SystemResultStatus::ErrorGetLoader: + LOG_CRITICAL(Frontend, "Failed to obtain loader for {}!", filename.toStdString()); + QMessageBox::critical(this, tr("Error while loading ROM!"), + tr("The ROM format is not supported.")); + break; + case Core::SystemResultStatus::ErrorVideoCore: + QMessageBox::critical( + this, tr("An error occurred initializing the video core."), + tr("sudachi has encountered an error while running the video core. " + "This is usually caused by outdated GPU drivers, including integrated ones. " + "Please see the log for more details. " + "For more information on accessing the log, please see the following page: " + "" + "How to Upload the Log File. ")); + break; + default: + if (result > Core::SystemResultStatus::ErrorLoader) { + const u16 loader_id = static_cast(Core::SystemResultStatus::ErrorLoader); + const u16 error_id = static_cast(result) - loader_id; + const std::string error_code = fmt::format("({:04X}-{:04X})", loader_id, error_id); + LOG_CRITICAL(Frontend, "Failed to load ROM! {}", error_code); + + const auto title = + tr("Error while loading ROM! %1", "%1 signifies a numeric error code.") + .arg(QString::fromStdString(error_code)); + const auto description = + tr("%1
Please follow the " + "sudachi quickstart guide to redump your files.
You can refer " + "to the sudachi wiki or the sudachi Discord for help.", + "%1 signifies an error string.") + .arg(QString::fromStdString( + GetResultStatusString(static_cast(error_id)))); + + QMessageBox::critical(this, title, description); + } else { + QMessageBox::critical( + this, tr("Error while loading ROM!"), + tr("An unknown error occurred. Please see the log for more details.")); + } + break; + } + return false; + } + current_game_path = filename; + + system->TelemetrySession().AddField(Common::Telemetry::FieldType::App, "Frontend", "Qt"); + return true; +} + +bool GMainWindow::SelectAndSetCurrentUser( + const Core::Frontend::ProfileSelectParameters& parameters) { + QtProfileSelectionDialog dialog(*system, this, parameters); + dialog.setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint | + Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint); + dialog.setWindowModality(Qt::WindowModal); + + if (dialog.exec() == QDialog::Rejected) { + return false; + } + + Settings::values.current_user = dialog.GetIndex(); + return true; +} + +void GMainWindow::ConfigureFilesystemProvider(const std::string& filepath) { + // Ensure all NCAs are registered before launching the game + const auto file = vfs->OpenFile(filepath, FileSys::OpenMode::Read); + if (!file) { + return; + } + + auto loader = Loader::GetLoader(*system, file); + if (!loader) { + return; + } + + const auto file_type = loader->GetFileType(); + if (file_type == Loader::FileType::Unknown || file_type == Loader::FileType::Error) { + return; + } + + u64 program_id = 0; + const auto res2 = loader->ReadProgramId(program_id); + if (res2 == Loader::ResultStatus::Success && file_type == Loader::FileType::NCA) { + provider->AddEntry(FileSys::TitleType::Application, + FileSys::GetCRTypeFromNCAType(FileSys::NCA{file}.GetType()), program_id, + file); + } else if (res2 == Loader::ResultStatus::Success && + (file_type == Loader::FileType::XCI || file_type == Loader::FileType::NSP)) { + const auto nsp = file_type == Loader::FileType::NSP + ? std::make_shared(file) + : FileSys::XCI{file}.GetSecurePartitionNSP(); + for (const auto& title : nsp->GetNCAs()) { + for (const auto& entry : title.second) { + provider->AddEntry(entry.first.first, entry.first.second, title.first, + entry.second->GetBaseFile()); + } + } + } +} + +void GMainWindow::BootGame(const QString& filename, Service::AM::FrontendAppletParameters params, + StartGameType type) { + LOG_INFO(Frontend, "sudachi starting..."); + + if (params.program_id == 0 || + params.program_id > static_cast(Service::AM::AppletProgramId::MaxProgramId)) { + StoreRecentFile(filename); // Put the filename on top of the list + } + + // Save configurations + UpdateUISettings(); + game_list->SaveInterfaceLayout(); + config->SaveAllValues(); + + u64 title_id{0}; + + last_filename_booted = filename; + + ConfigureFilesystemProvider(filename.toStdString()); + const auto v_file = Core::GetGameFileFromPath(vfs, filename.toUtf8().constData()); + const auto loader = Loader::GetLoader(*system, v_file, params.program_id, params.program_index); + + if (loader != nullptr && loader->ReadProgramId(title_id) == Loader::ResultStatus::Success && + type == StartGameType::Normal) { + // Load per game settings + const auto file_path = + std::filesystem::path{Common::U16StringFromBuffer(filename.utf16(), filename.size())}; + const auto config_file_name = title_id == 0 + ? Common::FS::PathToUTF8String(file_path.filename()) + : fmt::format("{:016X}", title_id); + QtConfig per_game_config(config_file_name, Config::ConfigType::PerGameConfig); + system->HIDCore().ReloadInputDevices(); + system->ApplySettings(); + } + + Settings::LogSettings(); + + if (UISettings::values.select_user_on_boot && !user_flag_cmd_line) { + const Core::Frontend::ProfileSelectParameters parameters{ + .mode = Service::AM::Frontend::UiMode::UserSelector, + .invalid_uid_list = {}, + .display_options = {}, + .purpose = Service::AM::Frontend::UserSelectionPurpose::General, + }; + if (SelectAndSetCurrentUser(parameters) == false) { + return; + } + } + + // If the user specifies -u (successfully) on the cmd line, don't prompt for a user on first + // game startup only. If the user stops emulation and starts a new one, go back to the expected + // behavior of asking. + user_flag_cmd_line = false; + + if (!LoadROM(filename, params)) { + return; + } + + system->SetShuttingDown(false); + game_list->setDisabled(true); + + // Create and start the emulation thread + emu_thread = std::make_unique(*system); + emit EmulationStarting(emu_thread.get()); + emu_thread->start(); + + // Register an ExecuteProgram callback such that Core can execute a sub-program + system->RegisterExecuteProgramCallback( + [this](std::size_t program_index_) { render_window->ExecuteProgram(program_index_); }); + + system->RegisterExitCallback([this] { + emu_thread->ForceStop(); + render_window->Exit(); + }); + + connect(render_window, &GRenderWindow::Closed, this, &GMainWindow::OnStopGame); + connect(render_window, &GRenderWindow::MouseActivity, this, &GMainWindow::OnMouseActivity); + // BlockingQueuedConnection is important here, it makes sure we've finished refreshing our views + // before the CPU continues + connect(emu_thread.get(), &EmuThread::DebugModeEntered, waitTreeWidget, + &WaitTreeWidget::OnDebugModeEntered, Qt::BlockingQueuedConnection); + connect(emu_thread.get(), &EmuThread::DebugModeLeft, waitTreeWidget, + &WaitTreeWidget::OnDebugModeLeft, Qt::BlockingQueuedConnection); + + connect(emu_thread.get(), &EmuThread::LoadProgress, loading_screen, + &LoadingScreen::OnLoadProgress, Qt::QueuedConnection); + + // Update the GUI + UpdateStatusButtons(); + if (ui->action_Single_Window_Mode->isChecked()) { + game_list->hide(); + game_list_placeholder->hide(); + } + status_bar_update_timer.start(500); + renderer_status_button->setDisabled(true); + + if (UISettings::values.hide_mouse || Settings::values.mouse_panning) { + render_window->installEventFilter(render_window); + render_window->setAttribute(Qt::WA_Hover, true); + } + + if (UISettings::values.hide_mouse) { + mouse_hide_timer.start(); + } + + render_window->InitializeCamera(); + + std::string title_name; + std::string title_version; + const auto res = system->GetGameName(title_name); + + const auto metadata = [this, title_id] { + const FileSys::PatchManager pm(title_id, system->GetFileSystemController(), + system->GetContentProvider()); + return pm.GetControlMetadata(); + }(); + if (metadata.first != nullptr) { + title_version = metadata.first->GetVersionString(); + title_name = metadata.first->GetApplicationName(); + } + if (res != Loader::ResultStatus::Success || title_name.empty()) { + title_name = Common::FS::PathToUTF8String( + std::filesystem::path{Common::U16StringFromBuffer(filename.utf16(), filename.size())} + .filename()); + } + const bool is_64bit = system->Kernel().ApplicationProcess()->Is64Bit(); + const auto instruction_set_suffix = is_64bit ? tr("(64-bit)") : tr("(32-bit)"); + title_name = tr("%1 %2", "%1 is the title name. %2 indicates if the title is 64-bit or 32-bit") + .arg(QString::fromStdString(title_name), instruction_set_suffix) + .toStdString(); + LOG_INFO(Frontend, "Booting game: {:016X} | {} | {}", title_id, title_name, title_version); + const auto gpu_vendor = system->GPU().Renderer().GetDeviceVendor(); + UpdateWindowTitle(title_name, title_version, gpu_vendor); + + loading_screen->Prepare(system->GetAppLoader()); + loading_screen->show(); + + emulation_running = true; + if (ui->action_Fullscreen->isChecked()) { + ShowFullscreen(); + } + OnStartGame(); +} + +void GMainWindow::BootGameFromList(const QString& filename, StartGameType with_config) { + BootGame(filename, ApplicationAppletParameters(), with_config); +} + +bool GMainWindow::OnShutdownBegin() { + if (!emulation_running) { + return false; + } + + if (ui->action_Fullscreen->isChecked()) { + HideFullscreen(); + } + + AllowOSSleep(); + + // Disable unlimited frame rate + Settings::values.use_speed_limit.SetValue(true); + + if (system->IsShuttingDown()) { + return false; + } + + system->SetShuttingDown(true); + discord_rpc->Pause(); + + RequestGameExit(); + emu_thread->disconnect(); + emu_thread->SetRunning(true); + + emit EmulationStopping(); + + int shutdown_time = 1000; + + if (system->DebuggerEnabled()) { + shutdown_time = 0; + } else if (system->GetExitLocked()) { + shutdown_time = 5000; + } + + shutdown_timer.setSingleShot(true); + shutdown_timer.start(shutdown_time); + connect(&shutdown_timer, &QTimer::timeout, this, &GMainWindow::OnEmulationStopTimeExpired); + connect(emu_thread.get(), &QThread::finished, this, &GMainWindow::OnEmulationStopped); + + // Disable everything to prevent anything from being triggered here + ui->action_Pause->setEnabled(false); + ui->action_Restart->setEnabled(false); + ui->action_Stop->setEnabled(false); + + return true; +} + +void GMainWindow::OnShutdownBeginDialog() { + shutdown_dialog = new OverlayDialog(this, *system, QString{}, tr("Closing software..."), + QString{}, QString{}, Qt::AlignHCenter | Qt::AlignVCenter); + shutdown_dialog->open(); +} + +void GMainWindow::OnEmulationStopTimeExpired() { + if (emu_thread) { + emu_thread->ForceStop(); + } +} + +void GMainWindow::OnEmulationStopped() { + shutdown_timer.stop(); + if (emu_thread) { + emu_thread->disconnect(); + emu_thread->wait(); + emu_thread.reset(); + } + + if (shutdown_dialog) { + shutdown_dialog->deleteLater(); + shutdown_dialog = nullptr; + } + + emulation_running = false; + + discord_rpc->Update(); + +#ifdef __unix__ + Common::Linux::StopGamemode(); +#endif + + // The emulation is stopped, so closing the window or not does not matter anymore + disconnect(render_window, &GRenderWindow::Closed, this, &GMainWindow::OnStopGame); + + // Update the GUI + UpdateMenuState(); + + render_window->hide(); + loading_screen->hide(); + loading_screen->Clear(); + if (game_list->IsEmpty()) { + game_list_placeholder->show(); + } else { + game_list->show(); + } + game_list->SetFilterFocus(); + tas_label->clear(); + input_subsystem->GetTas()->Stop(); + OnTasStateChanged(); + render_window->FinalizeCamera(); + + system->GetFrontendAppletHolder().SetCurrentAppletId(Service::AM::AppletId::None); + + // Enable all controllers + system->HIDCore().SetSupportedStyleTag({Core::HID::NpadStyleSet::All}); + + render_window->removeEventFilter(render_window); + render_window->setAttribute(Qt::WA_Hover, false); + + UpdateWindowTitle(); + + // Disable status bar updates + status_bar_update_timer.stop(); + shader_building_label->setVisible(false); + res_scale_label->setVisible(false); + emu_speed_label->setVisible(false); + game_fps_label->setVisible(false); + emu_frametime_label->setVisible(false); + renderer_status_button->setEnabled(!UISettings::values.has_broken_vulkan); + + if (!firmware_label->text().isEmpty()) { + firmware_label->setVisible(true); + } + + current_game_path.clear(); + + // When closing the game, destroy the GLWindow to clear the context after the game is closed + render_window->ReleaseRenderTarget(); + + // Enable game list + game_list->setEnabled(true); + + Settings::RestoreGlobalState(system->IsPoweredOn()); + system->HIDCore().ReloadInputDevices(); + UpdateStatusButtons(); +} + +void GMainWindow::ShutdownGame() { + if (!emulation_running) { + return; + } + + play_time_manager->Stop(); + OnShutdownBegin(); + OnEmulationStopTimeExpired(); + OnEmulationStopped(); +} + +void GMainWindow::StoreRecentFile(const QString& filename) { + UISettings::values.recent_files.prepend(filename); + UISettings::values.recent_files.removeDuplicates(); + while (UISettings::values.recent_files.size() > max_recent_files_item) { + UISettings::values.recent_files.removeLast(); + } + + UpdateRecentFiles(); +} + +void GMainWindow::UpdateRecentFiles() { + const int num_recent_files = + std::min(static_cast(UISettings::values.recent_files.size()), max_recent_files_item); + + for (int i = 0; i < num_recent_files; i++) { + const QString text = QStringLiteral("&%1. %2").arg(i + 1).arg( + QFileInfo(UISettings::values.recent_files[i]).fileName()); + actions_recent_files[i]->setText(text); + actions_recent_files[i]->setData(UISettings::values.recent_files[i]); + actions_recent_files[i]->setToolTip(UISettings::values.recent_files[i]); + actions_recent_files[i]->setVisible(true); + } + + for (int j = num_recent_files; j < max_recent_files_item; ++j) { + actions_recent_files[j]->setVisible(false); + } + + // Enable the recent files menu if the list isn't empty + ui->menu_recent_files->setEnabled(num_recent_files != 0); +} + +void GMainWindow::OnGameListLoadFile(QString game_path, u64 program_id) { + auto params = ApplicationAppletParameters(); + params.program_id = program_id; + + BootGame(game_path, params); +} + +void GMainWindow::OnGameListOpenFolder(u64 program_id, GameListOpenTarget target, + const std::string& game_path) { + std::filesystem::path path; + QString open_target; + + const auto [user_save_size, device_save_size] = [this, &game_path, &program_id] { + const FileSys::PatchManager pm{program_id, system->GetFileSystemController(), + system->GetContentProvider()}; + const auto control = pm.GetControlMetadata().first; + if (control != nullptr) { + return std::make_pair(control->GetDefaultNormalSaveSize(), + control->GetDeviceSaveDataSize()); + } else { + const auto file = Core::GetGameFileFromPath(vfs, game_path); + const auto loader = Loader::GetLoader(*system, file); + + FileSys::NACP nacp{}; + loader->ReadControlData(nacp); + return std::make_pair(nacp.GetDefaultNormalSaveSize(), nacp.GetDeviceSaveDataSize()); + } + }(); + + const bool has_user_save{user_save_size > 0}; + const bool has_device_save{device_save_size > 0}; + + ASSERT_MSG(has_user_save != has_device_save, "Game uses both user and device savedata?"); + + switch (target) { + case GameListOpenTarget::SaveData: { + open_target = tr("Save Data"); + const auto nand_dir = Common::FS::GetSudachiPath(Common::FS::SudachiPath::NANDDir); + auto vfs_nand_dir = + vfs->OpenDirectory(Common::FS::PathToUTF8String(nand_dir), FileSys::OpenMode::Read); + + if (has_user_save) { + // User save data + const auto select_profile = [this] { + const Core::Frontend::ProfileSelectParameters parameters{ + .mode = Service::AM::Frontend::UiMode::UserSelector, + .invalid_uid_list = {}, + .display_options = {}, + .purpose = Service::AM::Frontend::UserSelectionPurpose::General, + }; + QtProfileSelectionDialog dialog(*system, this, parameters); + dialog.setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint | + Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint); + dialog.setWindowModality(Qt::WindowModal); + + if (dialog.exec() == QDialog::Rejected) { + return -1; + } + + return dialog.GetIndex(); + }; + + const auto index = select_profile(); + if (index == -1) { + return; + } + + const auto user_id = + system->GetProfileManager().GetUser(static_cast(index)); + ASSERT(user_id); + + const auto user_save_data_path = FileSys::SaveDataFactory::GetFullPath( + {}, vfs_nand_dir, FileSys::SaveDataSpaceId::User, FileSys::SaveDataType::Account, + program_id, user_id->AsU128(), 0); + + path = Common::FS::ConcatPathSafe(nand_dir, user_save_data_path); + } else { + // Device save data + const auto device_save_data_path = FileSys::SaveDataFactory::GetFullPath( + {}, vfs_nand_dir, FileSys::SaveDataSpaceId::User, FileSys::SaveDataType::Account, + program_id, {}, 0); + + path = Common::FS::ConcatPathSafe(nand_dir, device_save_data_path); + } + + if (!Common::FS::CreateDirs(path)) { + LOG_ERROR(Frontend, "Unable to create the directories for save data"); + } + + break; + } + case GameListOpenTarget::ModData: { + open_target = tr("Mod Data"); + path = Common::FS::GetSudachiPath(Common::FS::SudachiPath::LoadDir) / + fmt::format("{:016X}", program_id); + break; + } + default: + UNIMPLEMENTED(); + break; + } + + const QString qpath = QString::fromStdString(Common::FS::PathToUTF8String(path)); + const QDir dir(qpath); + if (!dir.exists()) { + QMessageBox::warning(this, tr("Error Opening %1 Folder").arg(open_target), + tr("Folder does not exist!")); + return; + } + LOG_INFO(Frontend, "Opening {} path for program_id={:016x}", open_target.toStdString(), + program_id); + QDesktopServices::openUrl(QUrl::fromLocalFile(qpath)); +} + +void GMainWindow::OnTransferableShaderCacheOpenFile(u64 program_id) { + const auto shader_cache_dir = Common::FS::GetSudachiPath(Common::FS::SudachiPath::ShaderDir); + const auto shader_cache_folder_path{shader_cache_dir / fmt::format("{:016x}", program_id)}; + if (!Common::FS::CreateDirs(shader_cache_folder_path)) { + QMessageBox::warning(this, tr("Error Opening Transferable Shader Cache"), + tr("Failed to create the shader cache directory for this title.")); + return; + } + const auto shader_path_string{Common::FS::PathToUTF8String(shader_cache_folder_path)}; + const auto qt_shader_cache_path = QString::fromStdString(shader_path_string); + QDesktopServices::openUrl(QUrl::fromLocalFile(qt_shader_cache_path)); +} + +static bool RomFSRawCopy(size_t total_size, size_t& read_size, QProgressDialog& dialog, + const FileSys::VirtualDir& src, const FileSys::VirtualDir& dest, + bool full) { + if (src == nullptr || dest == nullptr || !src->IsReadable() || !dest->IsWritable()) + return false; + if (dialog.wasCanceled()) + return false; + + std::vector buffer(CopyBufferSize); + auto last_timestamp = std::chrono::steady_clock::now(); + + const auto QtRawCopy = [&](const FileSys::VirtualFile& src_file, + const FileSys::VirtualFile& dest_file) { + if (src_file == nullptr || dest_file == nullptr) { + return false; + } + if (!dest_file->Resize(src_file->GetSize())) { + return false; + } + + for (std::size_t i = 0; i < src_file->GetSize(); i += buffer.size()) { + if (dialog.wasCanceled()) { + dest_file->Resize(0); + return false; + } + + using namespace std::literals::chrono_literals; + const auto new_timestamp = std::chrono::steady_clock::now(); + + if ((new_timestamp - last_timestamp) > 33ms) { + last_timestamp = new_timestamp; + dialog.setValue( + static_cast(std::min(read_size, total_size) * 100 / total_size)); + QCoreApplication::processEvents(); + } + + const auto read = src_file->Read(buffer.data(), buffer.size(), i); + dest_file->Write(buffer.data(), read, i); + + read_size += read; + } + + return true; + }; + + if (full) { + for (const auto& file : src->GetFiles()) { + const auto out = VfsDirectoryCreateFileWrapper(dest, file->GetName()); + if (!QtRawCopy(file, out)) + return false; + } + } + + for (const auto& dir : src->GetSubdirectories()) { + const auto out = dest->CreateSubdirectory(dir->GetName()); + if (!RomFSRawCopy(total_size, read_size, dialog, dir, out, full)) + return false; + } + + return true; +} + +QString GMainWindow::GetGameListErrorRemoving(InstalledEntryType type) const { + switch (type) { + case InstalledEntryType::Game: + return tr("Error Removing Contents"); + case InstalledEntryType::Update: + return tr("Error Removing Update"); + case InstalledEntryType::AddOnContent: + return tr("Error Removing DLC"); + default: + return QStringLiteral("Error Removing "); + } +} +void GMainWindow::OnGameListRemoveInstalledEntry(u64 program_id, InstalledEntryType type) { + const QString entry_question = [type] { + switch (type) { + case InstalledEntryType::Game: + return tr("Remove Installed Game Contents?"); + case InstalledEntryType::Update: + return tr("Remove Installed Game Update?"); + case InstalledEntryType::AddOnContent: + return tr("Remove Installed Game DLC?"); + default: + return QStringLiteral("Remove Installed Game ?"); + } + }(); + + if (!question(this, tr("Remove Entry"), entry_question, QMessageBox::Yes | QMessageBox::No, + QMessageBox::No)) { + return; + } + + switch (type) { + case InstalledEntryType::Game: + RemoveBaseContent(program_id, type); + [[fallthrough]]; + case InstalledEntryType::Update: + RemoveUpdateContent(program_id, type); + if (type != InstalledEntryType::Game) { + break; + } + [[fallthrough]]; + case InstalledEntryType::AddOnContent: + RemoveAddOnContent(program_id, type); + break; + } + Common::FS::RemoveDirRecursively(Common::FS::GetSudachiPath(Common::FS::SudachiPath::CacheDir) / + "game_list"); + game_list->PopulateAsync(UISettings::values.game_dirs); +} + +void GMainWindow::RemoveBaseContent(u64 program_id, InstalledEntryType type) { + const auto res = + ContentManager::RemoveBaseContent(system->GetFileSystemController(), program_id); + if (res) { + QMessageBox::information(this, tr("Successfully Removed"), + tr("Successfully removed the installed base game.")); + } else { + QMessageBox::warning( + this, GetGameListErrorRemoving(type), + tr("The base game is not installed in the NAND and cannot be removed.")); + } +} + +void GMainWindow::RemoveUpdateContent(u64 program_id, InstalledEntryType type) { + const auto res = ContentManager::RemoveUpdate(system->GetFileSystemController(), program_id); + if (res) { + QMessageBox::information(this, tr("Successfully Removed"), + tr("Successfully removed the installed update.")); + } else { + QMessageBox::warning(this, GetGameListErrorRemoving(type), + tr("There is no update installed for this title.")); + } +} + +void GMainWindow::RemoveAddOnContent(u64 program_id, InstalledEntryType type) { + const size_t count = ContentManager::RemoveAllDLC(*system, program_id); + if (count == 0) { + QMessageBox::warning(this, GetGameListErrorRemoving(type), + tr("There are no DLC installed for this title.")); + return; + } + + QMessageBox::information(this, tr("Successfully Removed"), + tr("Successfully removed %1 installed DLC.").arg(count)); +} + +void GMainWindow::OnGameListRemoveFile(u64 program_id, GameListRemoveTarget target, + const std::string& game_path) { + const QString question = [target] { + switch (target) { + case GameListRemoveTarget::GlShaderCache: + return tr("Delete OpenGL Transferable Shader Cache?"); + case GameListRemoveTarget::VkShaderCache: + return tr("Delete Vulkan Transferable Shader Cache?"); + case GameListRemoveTarget::AllShaderCache: + return tr("Delete All Transferable Shader Caches?"); + case GameListRemoveTarget::CustomConfiguration: + return tr("Remove Custom Game Configuration?"); + case GameListRemoveTarget::CacheStorage: + return tr("Remove Cache Storage?"); + default: + return QString{}; + } + }(); + + if (!GMainWindow::question(this, tr("Remove File"), question, + QMessageBox::Yes | QMessageBox::No, QMessageBox::No)) { + return; + } + + switch (target) { + case GameListRemoveTarget::VkShaderCache: + RemoveVulkanDriverPipelineCache(program_id); + [[fallthrough]]; + case GameListRemoveTarget::GlShaderCache: + RemoveTransferableShaderCache(program_id, target); + break; + case GameListRemoveTarget::AllShaderCache: + RemoveAllTransferableShaderCaches(program_id); + break; + case GameListRemoveTarget::CustomConfiguration: + RemoveCustomConfiguration(program_id, game_path); + break; + case GameListRemoveTarget::CacheStorage: + RemoveCacheStorage(program_id); + break; + } +} + +void GMainWindow::OnGameListRemovePlayTimeData(u64 program_id) { + if (QMessageBox::question(this, tr("Remove Play Time Data"), tr("Reset play time?"), + QMessageBox::Yes | QMessageBox::No, + QMessageBox::No) != QMessageBox::Yes) { + return; + } + + play_time_manager->ResetProgramPlayTime(program_id); + game_list->PopulateAsync(UISettings::values.game_dirs); +} + +void GMainWindow::RemoveTransferableShaderCache(u64 program_id, GameListRemoveTarget target) { + const auto target_file_name = [target] { + switch (target) { + case GameListRemoveTarget::GlShaderCache: + return "opengl.bin"; + case GameListRemoveTarget::VkShaderCache: + return "vulkan.bin"; + default: + return ""; + } + }(); + const auto shader_cache_dir = Common::FS::GetSudachiPath(Common::FS::SudachiPath::ShaderDir); + const auto shader_cache_folder_path = shader_cache_dir / fmt::format("{:016x}", program_id); + const auto target_file = shader_cache_folder_path / target_file_name; + + if (!Common::FS::Exists(target_file)) { + QMessageBox::warning(this, tr("Error Removing Transferable Shader Cache"), + tr("A shader cache for this title does not exist.")); + return; + } + if (Common::FS::RemoveFile(target_file)) { + QMessageBox::information(this, tr("Successfully Removed"), + tr("Successfully removed the transferable shader cache.")); + } else { + QMessageBox::warning(this, tr("Error Removing Transferable Shader Cache"), + tr("Failed to remove the transferable shader cache.")); + } +} + +void GMainWindow::RemoveVulkanDriverPipelineCache(u64 program_id) { + static constexpr std::string_view target_file_name = "vulkan_pipelines.bin"; + + const auto shader_cache_dir = Common::FS::GetSudachiPath(Common::FS::SudachiPath::ShaderDir); + const auto shader_cache_folder_path = shader_cache_dir / fmt::format("{:016x}", program_id); + const auto target_file = shader_cache_folder_path / target_file_name; + + if (!Common::FS::Exists(target_file)) { + return; + } + if (!Common::FS::RemoveFile(target_file)) { + QMessageBox::warning(this, tr("Error Removing Vulkan Driver Pipeline Cache"), + tr("Failed to remove the driver pipeline cache.")); + } +} + +void GMainWindow::RemoveAllTransferableShaderCaches(u64 program_id) { + const auto shader_cache_dir = Common::FS::GetSudachiPath(Common::FS::SudachiPath::ShaderDir); + const auto program_shader_cache_dir = shader_cache_dir / fmt::format("{:016x}", program_id); + + if (!Common::FS::Exists(program_shader_cache_dir)) { + QMessageBox::warning(this, tr("Error Removing Transferable Shader Caches"), + tr("A shader cache for this title does not exist.")); + return; + } + if (Common::FS::RemoveDirRecursively(program_shader_cache_dir)) { + QMessageBox::information(this, tr("Successfully Removed"), + tr("Successfully removed the transferable shader caches.")); + } else { + QMessageBox::warning(this, tr("Error Removing Transferable Shader Caches"), + tr("Failed to remove the transferable shader cache directory.")); + } +} + +void GMainWindow::RemoveCustomConfiguration(u64 program_id, const std::string& game_path) { + const auto file_path = std::filesystem::path(Common::FS::ToU8String(game_path)); + const auto config_file_name = + program_id == 0 ? Common::FS::PathToUTF8String(file_path.filename()).append(".ini") + : fmt::format("{:016X}.ini", program_id); + const auto custom_config_file_path = + Common::FS::GetSudachiPath(Common::FS::SudachiPath::ConfigDir) / "custom" / config_file_name; + + if (!Common::FS::Exists(custom_config_file_path)) { + QMessageBox::warning(this, tr("Error Removing Custom Configuration"), + tr("A custom configuration for this title does not exist.")); + return; + } + + if (Common::FS::RemoveFile(custom_config_file_path)) { + QMessageBox::information(this, tr("Successfully Removed"), + tr("Successfully removed the custom game configuration.")); + } else { + QMessageBox::warning(this, tr("Error Removing Custom Configuration"), + tr("Failed to remove the custom game configuration.")); + } +} + +void GMainWindow::RemoveCacheStorage(u64 program_id) { + const auto nand_dir = Common::FS::GetSudachiPath(Common::FS::SudachiPath::NANDDir); + auto vfs_nand_dir = + vfs->OpenDirectory(Common::FS::PathToUTF8String(nand_dir), FileSys::OpenMode::Read); + + const auto cache_storage_path = FileSys::SaveDataFactory::GetFullPath( + {}, vfs_nand_dir, FileSys::SaveDataSpaceId::User, FileSys::SaveDataType::Cache, + 0 /* program_id */, {}, 0); + + const auto path = Common::FS::ConcatPathSafe(nand_dir, cache_storage_path); + + // Not an error if it wasn't cleared. + Common::FS::RemoveDirRecursively(path); +} + +void GMainWindow::OnGameListDumpRomFS(u64 program_id, const std::string& game_path, + DumpRomFSTarget target) { + const auto failed = [this] { + QMessageBox::warning(this, tr("RomFS Extraction Failed!"), + tr("There was an error copying the RomFS files or the user " + "cancelled the operation.")); + }; + + const auto loader = + Loader::GetLoader(*system, vfs->OpenFile(game_path, FileSys::OpenMode::Read)); + if (loader == nullptr) { + failed(); + return; + } + + FileSys::VirtualFile packed_update_raw{}; + loader->ReadUpdateRaw(packed_update_raw); + + const auto& installed = system->GetContentProvider(); + + u64 title_id{}; + u8 raw_type{}; + if (!SelectRomFSDumpTarget(installed, program_id, &title_id, &raw_type)) { + failed(); + return; + } + + const auto type = static_cast(raw_type); + const auto base_nca = installed.GetEntry(title_id, type); + if (!base_nca) { + failed(); + return; + } + + const FileSys::NCA update_nca{packed_update_raw, nullptr}; + if (type != FileSys::ContentRecordType::Program || + update_nca.GetStatus() != Loader::ResultStatus::ErrorMissingBKTRBaseRomFS || + update_nca.GetTitleId() != FileSys::GetUpdateTitleID(title_id)) { + packed_update_raw = {}; + } + + const auto base_romfs = base_nca->GetRomFS(); + const auto dump_dir = + target == DumpRomFSTarget::Normal + ? Common::FS::GetSudachiPath(Common::FS::SudachiPath::DumpDir) + : Common::FS::GetSudachiPath(Common::FS::SudachiPath::SDMCDir) / "atmosphere" / "contents"; + const auto romfs_dir = fmt::format("{:016X}/romfs", title_id); + + const auto path = Common::FS::PathToUTF8String(dump_dir / romfs_dir); + + const FileSys::PatchManager pm{title_id, system->GetFileSystemController(), installed}; + auto romfs = pm.PatchRomFS(base_nca.get(), base_romfs, type, packed_update_raw, false); + + const auto out = VfsFilesystemCreateDirectoryWrapper(vfs, path, FileSys::OpenMode::ReadWrite); + + if (out == nullptr) { + failed(); + vfs->DeleteDirectory(path); + return; + } + + bool ok = false; + const QStringList selections{tr("Full"), tr("Skeleton")}; + const auto res = QInputDialog::getItem( + this, tr("Select RomFS Dump Mode"), + tr("Please select the how you would like the RomFS dumped.
Full will copy all of the " + "files into the new directory while
skeleton will only create the directory " + "structure."), + selections, 0, false, &ok); + if (!ok) { + failed(); + vfs->DeleteDirectory(path); + return; + } + + const auto extracted = FileSys::ExtractRomFS(romfs); + if (extracted == nullptr) { + failed(); + return; + } + + const auto full = res == selections.constFirst(); + + // The expected required space is the size of the RomFS + 1 GiB + const auto minimum_free_space = romfs->GetSize() + 0x40000000; + + if (full && Common::FS::GetFreeSpaceSize(path) < minimum_free_space) { + QMessageBox::warning(this, tr("RomFS Extraction Failed!"), + tr("There is not enough free space at %1 to extract the RomFS. Please " + "free up space or select a different dump directory at " + "Emulation > Configure > System > Filesystem > Dump Root") + .arg(QString::fromStdString(path))); + return; + } + + QProgressDialog progress(tr("Extracting RomFS..."), tr("Cancel"), 0, 100, this); + progress.setWindowModality(Qt::WindowModal); + progress.setMinimumDuration(100); + progress.setAutoClose(false); + progress.setAutoReset(false); + + size_t read_size = 0; + + if (RomFSRawCopy(romfs->GetSize(), read_size, progress, extracted, out, full)) { + progress.close(); + QMessageBox::information(this, tr("RomFS Extraction Succeeded!"), + tr("The operation completed successfully.")); + QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(path))); + } else { + progress.close(); + failed(); + vfs->DeleteDirectory(path); + } +} + +void GMainWindow::OnGameListVerifyIntegrity(const std::string& game_path) { + const auto NotImplemented = [this] { + QMessageBox::warning(this, tr("Integrity verification couldn't be performed!"), + tr("File contents were not checked for validity.")); + }; + + QProgressDialog progress(tr("Verifying integrity..."), tr("Cancel"), 0, 100, this); + progress.setWindowModality(Qt::WindowModal); + progress.setMinimumDuration(100); + progress.setAutoClose(false); + progress.setAutoReset(false); + + const auto QtProgressCallback = [&](size_t total_size, size_t processed_size) { + progress.setValue(static_cast((processed_size * 100) / total_size)); + return progress.wasCanceled(); + }; + + const auto result = ContentManager::VerifyGameContents(*system, game_path, QtProgressCallback); + progress.close(); + switch (result) { + case ContentManager::GameVerificationResult::Success: + QMessageBox::information(this, tr("Integrity verification succeeded!"), + tr("The operation completed successfully.")); + break; + case ContentManager::GameVerificationResult::Failed: + QMessageBox::critical(this, tr("Integrity verification failed!"), + tr("File contents may be corrupt.")); + break; + case ContentManager::GameVerificationResult::NotImplemented: + NotImplemented(); + } +} + +void GMainWindow::OnGameListCopyTID(u64 program_id) { + QClipboard* clipboard = QGuiApplication::clipboard(); + clipboard->setText(QString::fromStdString(fmt::format("{:016X}", program_id))); +} + +void GMainWindow::OnGameListNavigateToGamedbEntry(u64 program_id, + const CompatibilityList& compatibility_list) { + const auto it = FindMatchingCompatibilityEntry(compatibility_list, program_id); + + QString directory; + if (it != compatibility_list.end()) { + directory = it->second.second; + } + + QDesktopServices::openUrl(QUrl(QStringLiteral("https://sudachi-emu.org/game/") + directory)); +} + +bool GMainWindow::CreateShortcutLink(const std::filesystem::path& shortcut_path, + const std::string& comment, + const std::filesystem::path& icon_path, + const std::filesystem::path& command, + const std::string& arguments, const std::string& categories, + const std::string& keywords, const std::string& name) try { +#if defined(__linux__) || defined(__FreeBSD__) // Linux and FreeBSD + std::filesystem::path shortcut_path_full = shortcut_path / (name + ".desktop"); + std::ofstream shortcut_stream(shortcut_path_full, std::ios::binary | std::ios::trunc); + if (!shortcut_stream.is_open()) { + LOG_ERROR(Frontend, "Failed to create shortcut"); + return false; + } + // TODO: Migrate fmt::print to std::print in futures STD C++ 23. + fmt::print(shortcut_stream, "[Desktop Entry]\n"); + fmt::print(shortcut_stream, "Type=Application\n"); + fmt::print(shortcut_stream, "Version=1.0\n"); + fmt::print(shortcut_stream, "Name={}\n", name); + if (!comment.empty()) { + fmt::print(shortcut_stream, "Comment={}\n", comment); + } + if (std::filesystem::is_regular_file(icon_path)) { + fmt::print(shortcut_stream, "Icon={}\n", icon_path.string()); + } + fmt::print(shortcut_stream, "TryExec={}\n", command.string()); + fmt::print(shortcut_stream, "Exec={} {}\n", command.string(), arguments); + if (!categories.empty()) { + fmt::print(shortcut_stream, "Categories={}\n", categories); + } + if (!keywords.empty()) { + fmt::print(shortcut_stream, "Keywords={}\n", keywords); + } + return true; +#elif defined(_WIN32) // Windows + HRESULT hr = CoInitialize(nullptr); + if (FAILED(hr)) { + LOG_ERROR(Frontend, "CoInitialize failed"); + return false; + } + SCOPE_EXIT { + CoUninitialize(); + }; + IShellLinkW* ps1 = nullptr; + IPersistFile* persist_file = nullptr; + SCOPE_EXIT { + if (persist_file != nullptr) { + persist_file->Release(); + } + if (ps1 != nullptr) { + ps1->Release(); + } + }; + HRESULT hres = CoCreateInstance(CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER, IID_IShellLinkW, + reinterpret_cast(&ps1)); + if (FAILED(hres)) { + LOG_ERROR(Frontend, "Failed to create IShellLinkW instance"); + return false; + } + hres = ps1->SetPath(command.c_str()); + if (FAILED(hres)) { + LOG_ERROR(Frontend, "Failed to set path"); + return false; + } + if (!arguments.empty()) { + hres = ps1->SetArguments(Common::UTF8ToUTF16W(arguments).data()); + if (FAILED(hres)) { + LOG_ERROR(Frontend, "Failed to set arguments"); + return false; + } + } + if (!comment.empty()) { + hres = ps1->SetDescription(Common::UTF8ToUTF16W(comment).data()); + if (FAILED(hres)) { + LOG_ERROR(Frontend, "Failed to set description"); + return false; + } + } + if (std::filesystem::is_regular_file(icon_path)) { + hres = ps1->SetIconLocation(icon_path.c_str(), 0); + if (FAILED(hres)) { + LOG_ERROR(Frontend, "Failed to set icon location"); + return false; + } + } + hres = ps1->QueryInterface(IID_IPersistFile, reinterpret_cast(&persist_file)); + if (FAILED(hres)) { + LOG_ERROR(Frontend, "Failed to get IPersistFile interface"); + return false; + } + hres = persist_file->Save(std::filesystem::path{shortcut_path / (name + ".lnk")}.c_str(), TRUE); + if (FAILED(hres)) { + LOG_ERROR(Frontend, "Failed to save shortcut"); + return false; + } + return true; +#else // Unsupported platform + return false; +#endif +} catch (const std::exception& e) { + LOG_ERROR(Frontend, "Failed to create shortcut: {}", e.what()); + return false; +} +// Messages in pre-defined message boxes for less code spaghetti +bool GMainWindow::CreateShortcutMessagesGUI(QWidget* parent, int imsg, const QString& game_title) { + int result = 0; + QMessageBox::StandardButtons buttons; + switch (imsg) { + case GMainWindow::CREATE_SHORTCUT_MSGBOX_FULLSCREEN_YES: + buttons = QMessageBox::Yes | QMessageBox::No; + result = + QMessageBox::information(parent, tr("Create Shortcut"), + tr("Do you want to launch the game in fullscreen?"), buttons); + return result == QMessageBox::Yes; + case GMainWindow::CREATE_SHORTCUT_MSGBOX_SUCCESS: + QMessageBox::information(parent, tr("Create Shortcut"), + tr("Successfully created a shortcut to %1").arg(game_title)); + return false; + case GMainWindow::CREATE_SHORTCUT_MSGBOX_APPVOLATILE_WARNING: + buttons = QMessageBox::StandardButton::Ok | QMessageBox::StandardButton::Cancel; + result = + QMessageBox::warning(this, tr("Create Shortcut"), + tr("This will create a shortcut to the current AppImage. This may " + "not work well if you update. Continue?"), + buttons); + return result == QMessageBox::Ok; + default: + buttons = QMessageBox::Ok; + QMessageBox::critical(parent, tr("Create Shortcut"), + tr("Failed to create a shortcut to %1").arg(game_title), buttons); + return false; + } +} + +bool GMainWindow::MakeShortcutIcoPath(const u64 program_id, const std::string_view game_file_name, + std::filesystem::path& out_icon_path) { + // Get path to Sudachi icons directory & icon extension + std::string ico_extension = "png"; +#if defined(_WIN32) + out_icon_path = Common::FS::GetSudachiPath(Common::FS::SudachiPath::IconsDir); + ico_extension = "ico"; +#elif defined(__linux__) || defined(__FreeBSD__) + out_icon_path = Common::FS::GetDataDirectory("XDG_DATA_HOME") / "icons/hicolor/256x256"; +#endif + // Create icons directory if it doesn't exist + if (!Common::FS::CreateDirs(out_icon_path)) { + QMessageBox::critical( + this, tr("Create Icon"), + tr("Cannot create icon file. Path \"%1\" does not exist and cannot be created.") + .arg(QString::fromStdString(out_icon_path.string())), + QMessageBox::StandardButton::Ok); + out_icon_path.clear(); + return false; + } + + // Create icon file path + out_icon_path /= (program_id == 0 ? fmt::format("sudachi-{}.{}", game_file_name, ico_extension) + : fmt::format("sudachi-{:016X}.{}", program_id, ico_extension)); + return true; +} + +void GMainWindow::OnGameListCreateShortcut(u64 program_id, const std::string& game_path, + GameListShortcutTarget target) { + // Get path to sudachi executable + const QStringList args = QApplication::arguments(); + std::filesystem::path sudachi_command = args[0].toStdString(); + // If relative path, make it an absolute path + if (sudachi_command.c_str()[0] == '.') { + sudachi_command = Common::FS::GetCurrentDir() / sudachi_command; + } + // Shortcut path + std::filesystem::path shortcut_path{}; + if (target == GameListShortcutTarget::Desktop) { + shortcut_path = + QStandardPaths::writableLocation(QStandardPaths::DesktopLocation).toStdString(); + } else if (target == GameListShortcutTarget::Applications) { + shortcut_path = + QStandardPaths::writableLocation(QStandardPaths::ApplicationsLocation).toStdString(); + } + + if (!std::filesystem::exists(shortcut_path)) { + GMainWindow::CreateShortcutMessagesGUI( + this, GMainWindow::CREATE_SHORTCUT_MSGBOX_ERROR, + QString::fromStdString(shortcut_path.generic_string())); + LOG_ERROR(Frontend, "Invalid shortcut target {}", shortcut_path.generic_string()); + return; + } + + // Get title from game file + const FileSys::PatchManager pm{program_id, system->GetFileSystemController(), + system->GetContentProvider()}; + const auto control = pm.GetControlMetadata(); + const auto loader = + Loader::GetLoader(*system, vfs->OpenFile(game_path, FileSys::OpenMode::Read)); + std::string game_title = fmt::format("{:016X}", program_id); + if (control.first != nullptr) { + game_title = control.first->GetApplicationName(); + } else { + loader->ReadTitle(game_title); + } + // Delete illegal characters from title + const std::string illegal_chars = "<>:\"/\\|?*."; + for (auto it = game_title.rbegin(); it != game_title.rend(); ++it) { + if (illegal_chars.find(*it) != std::string::npos) { + game_title.erase(it.base() - 1); + } + } + const QString qt_game_title = QString::fromStdString(game_title); + // Get icon from game file + std::vector icon_image_file{}; + if (control.second != nullptr) { + icon_image_file = control.second->ReadAllBytes(); + } else if (loader->ReadIcon(icon_image_file) != Loader::ResultStatus::Success) { + LOG_WARNING(Frontend, "Could not read icon from {:s}", game_path); + } + QImage icon_data = + QImage::fromData(icon_image_file.data(), static_cast(icon_image_file.size())); + std::filesystem::path out_icon_path; + if (GMainWindow::MakeShortcutIcoPath(program_id, game_title, out_icon_path)) { + if (!SaveIconToFile(out_icon_path, icon_data)) { + LOG_ERROR(Frontend, "Could not write icon to file"); + } + } + +#if defined(__linux__) + // Special case for AppImages + // Warn once if we are making a shortcut to a volatile AppImage + const std::string appimage_ending = + std::string(Common::g_scm_rev).substr(0, 9).append(".AppImage"); + if (sudachi_command.string().ends_with(appimage_ending) && + !UISettings::values.shortcut_already_warned) { + if (GMainWindow::CreateShortcutMessagesGUI( + this, GMainWindow::CREATE_SHORTCUT_MSGBOX_APPVOLATILE_WARNING, qt_game_title)) { + return; + } + UISettings::values.shortcut_already_warned = true; + } +#endif // __linux__ + // Create shortcut + std::string arguments = fmt::format("-g \"{:s}\"", game_path); + if (GMainWindow::CreateShortcutMessagesGUI( + this, GMainWindow::CREATE_SHORTCUT_MSGBOX_FULLSCREEN_YES, qt_game_title)) { + arguments = "-f " + arguments; + } + const std::string comment = fmt::format("Start {:s} with the sudachi Emulator", game_title); + const std::string categories = "Game;Emulator;Qt;"; + const std::string keywords = "Switch;Nintendo;"; + + if (GMainWindow::CreateShortcutLink(shortcut_path, comment, out_icon_path, sudachi_command, + arguments, categories, keywords, game_title)) { + GMainWindow::CreateShortcutMessagesGUI(this, GMainWindow::CREATE_SHORTCUT_MSGBOX_SUCCESS, + qt_game_title); + return; + } + GMainWindow::CreateShortcutMessagesGUI(this, GMainWindow::CREATE_SHORTCUT_MSGBOX_ERROR, + qt_game_title); +} + +void GMainWindow::OnGameListOpenDirectory(const QString& directory) { + std::filesystem::path fs_path; + if (directory == QStringLiteral("SDMC")) { + fs_path = + Common::FS::GetSudachiPath(Common::FS::SudachiPath::SDMCDir) / "Nintendo/Contents/registered"; + } else if (directory == QStringLiteral("UserNAND")) { + fs_path = + Common::FS::GetSudachiPath(Common::FS::SudachiPath::NANDDir) / "user/Contents/registered"; + } else if (directory == QStringLiteral("SysNAND")) { + fs_path = + Common::FS::GetSudachiPath(Common::FS::SudachiPath::NANDDir) / "system/Contents/registered"; + } else { + fs_path = directory.toStdString(); + } + + const auto qt_path = QString::fromStdString(Common::FS::PathToUTF8String(fs_path)); + + if (!Common::FS::IsDir(fs_path)) { + QMessageBox::critical(this, tr("Error Opening %1").arg(qt_path), + tr("Folder does not exist!")); + return; + } + + QDesktopServices::openUrl(QUrl::fromLocalFile(qt_path)); +} + +void GMainWindow::OnGameListAddDirectory() { + const QString dir_path = QFileDialog::getExistingDirectory(this, tr("Select Directory")); + if (dir_path.isEmpty()) { + return; + } + + UISettings::GameDir game_dir{dir_path.toStdString(), false, true}; + if (!UISettings::values.game_dirs.contains(game_dir)) { + UISettings::values.game_dirs.append(game_dir); + game_list->PopulateAsync(UISettings::values.game_dirs); + } else { + LOG_WARNING(Frontend, "Selected directory is already in the game list"); + } + + OnSaveConfig(); +} + +void GMainWindow::OnGameListShowList(bool show) { + if (emulation_running && ui->action_Single_Window_Mode->isChecked()) + return; + game_list->setVisible(show); + game_list_placeholder->setVisible(!show); +}; + +void GMainWindow::OnGameListOpenPerGameProperties(const std::string& file) { + u64 title_id{}; + const auto v_file = Core::GetGameFileFromPath(vfs, file); + const auto loader = Loader::GetLoader(*system, v_file); + + if (loader == nullptr || loader->ReadProgramId(title_id) != Loader::ResultStatus::Success) { + QMessageBox::information(this, tr("Properties"), + tr("The game properties could not be loaded.")); + return; + } + + OpenPerGameConfiguration(title_id, file); +} + +void GMainWindow::OnMenuLoadFile() { + if (is_load_file_select_active) { + return; + } + + is_load_file_select_active = true; + const QString extensions = + QStringLiteral("*.") + .append(GameList::supported_file_extensions.join(QStringLiteral(" *."))) + .append(QStringLiteral(" main")); + const QString file_filter = tr("Switch Executable (%1);;All Files (*.*)", + "%1 is an identifier for the Switch executable file extensions.") + .arg(extensions); + const QString filename = QFileDialog::getOpenFileName( + this, tr("Load File"), QString::fromStdString(UISettings::values.roms_path), file_filter); + is_load_file_select_active = false; + + if (filename.isEmpty()) { + return; + } + + UISettings::values.roms_path = QFileInfo(filename).path().toStdString(); + BootGame(filename, ApplicationAppletParameters()); +} + +void GMainWindow::OnMenuLoadFolder() { + const QString dir_path = + QFileDialog::getExistingDirectory(this, tr("Open Extracted ROM Directory")); + + if (dir_path.isNull()) { + return; + } + + const QDir dir{dir_path}; + const QStringList matching_main = dir.entryList({QStringLiteral("main")}, QDir::Files); + if (matching_main.size() == 1) { + BootGame(dir.path() + QDir::separator() + matching_main[0], ApplicationAppletParameters()); + } else { + QMessageBox::warning(this, tr("Invalid Directory Selected"), + tr("The directory you have selected does not contain a 'main' file.")); + } +} + +void GMainWindow::IncrementInstallProgress() { + install_progress->setValue(install_progress->value() + 1); +} + +void GMainWindow::OnMenuInstallToNAND() { + const QString file_filter = + tr("Installable Switch File (*.nca *.nsp *.xci);;Nintendo Content Archive " + "(*.nca);;Nintendo Submission Package (*.nsp);;NX Cartridge " + "Image (*.xci)"); + + QStringList filenames = QFileDialog::getOpenFileNames( + this, tr("Install Files"), QString::fromStdString(UISettings::values.roms_path), + file_filter); + + if (filenames.isEmpty()) { + return; + } + + InstallDialog installDialog(this, filenames); + if (installDialog.exec() == QDialog::Rejected) { + return; + } + + const QStringList files = installDialog.GetFiles(); + + if (files.isEmpty()) { + return; + } + + // Save folder location of the first selected file + UISettings::values.roms_path = QFileInfo(filenames[0]).path().toStdString(); + + int remaining = filenames.size(); + + // This would only overflow above 2^51 bytes (2.252 PB) + int total_size = 0; + for (const QString& file : files) { + total_size += static_cast(QFile(file).size() / CopyBufferSize); + } + if (total_size < 0) { + LOG_CRITICAL(Frontend, "Attempting to install too many files, aborting."); + return; + } + + QStringList new_files{}; // Newly installed files that do not yet exist in the NAND + QStringList overwritten_files{}; // Files that overwrote those existing in the NAND + QStringList failed_files{}; // Files that failed to install due to errors + bool detected_base_install{}; // Whether a base game was attempted to be installed + + ui->action_Install_File_NAND->setEnabled(false); + + install_progress = new QProgressDialog(QString{}, tr("Cancel"), 0, total_size, this); + install_progress->setWindowFlags(windowFlags() & ~Qt::WindowMaximizeButtonHint); + install_progress->setAttribute(Qt::WA_DeleteOnClose, true); + install_progress->setFixedWidth(installDialog.GetMinimumWidth() + 40); + install_progress->show(); + + for (const QString& file : files) { + install_progress->setWindowTitle(tr("%n file(s) remaining", "", remaining)); + install_progress->setLabelText( + tr("Installing file \"%1\"...").arg(QFileInfo(file).fileName())); + + QFuture future; + ContentManager::InstallResult result; + + if (file.endsWith(QStringLiteral("nsp"), Qt::CaseInsensitive)) { + const auto progress_callback = [this](size_t size, size_t progress) { + emit UpdateInstallProgress(); + if (install_progress->wasCanceled()) { + return true; + } + return false; + }; + future = QtConcurrent::run([this, &file, progress_callback] { + return ContentManager::InstallNSP(*system, *vfs, file.toStdString(), + progress_callback); + }); + + while (!future.isFinished()) { + QCoreApplication::processEvents(); + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + + result = future.result(); + + } else { + result = InstallNCA(file); + } + + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + + switch (result) { + case ContentManager::InstallResult::Success: + new_files.append(QFileInfo(file).fileName()); + break; + case ContentManager::InstallResult::Overwrite: + overwritten_files.append(QFileInfo(file).fileName()); + break; + case ContentManager::InstallResult::Failure: + failed_files.append(QFileInfo(file).fileName()); + break; + case ContentManager::InstallResult::BaseInstallAttempted: + failed_files.append(QFileInfo(file).fileName()); + detected_base_install = true; + break; + } + + --remaining; + } + + install_progress->close(); + + if (detected_base_install) { + QMessageBox::warning( + this, tr("Install Results"), + tr("To avoid possible conflicts, we discourage users from installing base games to the " + "NAND.\nPlease, only use this feature to install updates and DLC.")); + } + + const QString install_results = + (new_files.isEmpty() ? QString{} + : tr("%n file(s) were newly installed\n", "", new_files.size())) + + (overwritten_files.isEmpty() + ? QString{} + : tr("%n file(s) were overwritten\n", "", overwritten_files.size())) + + (failed_files.isEmpty() ? QString{} + : tr("%n file(s) failed to install\n", "", failed_files.size())); + + QMessageBox::information(this, tr("Install Results"), install_results); + Common::FS::RemoveDirRecursively(Common::FS::GetSudachiPath(Common::FS::SudachiPath::CacheDir) / + "game_list"); + game_list->PopulateAsync(UISettings::values.game_dirs); + ui->action_Install_File_NAND->setEnabled(true); +} + +ContentManager::InstallResult GMainWindow::InstallNCA(const QString& filename) { + const QStringList tt_options{tr("System Application"), + tr("System Archive"), + tr("System Application Update"), + tr("Firmware Package (Type A)"), + tr("Firmware Package (Type B)"), + tr("Game"), + tr("Game Update"), + tr("Game DLC"), + tr("Delta Title")}; + bool ok; + const auto item = QInputDialog::getItem( + this, tr("Select NCA Install Type..."), + tr("Please select the type of title you would like to install this NCA as:\n(In " + "most instances, the default 'Game' is fine.)"), + tt_options, 5, false, &ok); + + auto index = tt_options.indexOf(item); + if (!ok || index == -1) { + QMessageBox::warning(this, tr("Failed to Install"), + tr("The title type you selected for the NCA is invalid.")); + return ContentManager::InstallResult::Failure; + } + + // If index is equal to or past Game, add the jump in TitleType. + if (index >= 5) { + index += static_cast(FileSys::TitleType::Application) - + static_cast(FileSys::TitleType::FirmwarePackageB); + } + + const bool is_application = index >= static_cast(FileSys::TitleType::Application); + const auto& fs_controller = system->GetFileSystemController(); + auto* registered_cache = is_application ? fs_controller.GetUserNANDContents() + : fs_controller.GetSystemNANDContents(); + + const auto progress_callback = [this](size_t size, size_t progress) { + emit UpdateInstallProgress(); + if (install_progress->wasCanceled()) { + return true; + } + return false; + }; + return ContentManager::InstallNCA(*vfs, filename.toStdString(), *registered_cache, + static_cast(index), progress_callback); +} + +void GMainWindow::OnMenuRecentFile() { + QAction* action = qobject_cast(sender()); + assert(action); + + const QString filename = action->data().toString(); + if (QFileInfo::exists(filename)) { + BootGame(filename, ApplicationAppletParameters()); + } else { + // Display an error message and remove the file from the list. + QMessageBox::information(this, tr("File not found"), + tr("File \"%1\" not found").arg(filename)); + + UISettings::values.recent_files.removeOne(filename); + UpdateRecentFiles(); + } +} + +void GMainWindow::OnStartGame() { + PreventOSSleep(); + + emu_thread->SetRunning(true); + + UpdateMenuState(); + OnTasStateChanged(); + + play_time_manager->SetProgramId(system->GetApplicationProcessProgramID()); + play_time_manager->Start(); + + discord_rpc->Update(); + +#ifdef __unix__ + Common::Linux::StartGamemode(); +#endif +} + +void GMainWindow::OnRestartGame() { + if (!system->IsPoweredOn()) { + return; + } + + if (ConfirmShutdownGame()) { + // Make a copy since ShutdownGame edits game_path + const auto current_game = QString(current_game_path); + ShutdownGame(); + BootGame(current_game, ApplicationAppletParameters()); + } +} + +void GMainWindow::OnPauseGame() { + emu_thread->SetRunning(false); + play_time_manager->Stop(); + UpdateMenuState(); + AllowOSSleep(); + +#ifdef __unix__ + Common::Linux::StopGamemode(); +#endif +} + +void GMainWindow::OnPauseContinueGame() { + if (emulation_running) { + if (emu_thread->IsRunning()) { + OnPauseGame(); + } else { + OnStartGame(); + } + } +} + +void GMainWindow::OnStopGame() { + if (ConfirmShutdownGame()) { + play_time_manager->Stop(); + // Update game list to show new play time + game_list->PopulateAsync(UISettings::values.game_dirs); + if (OnShutdownBegin()) { + OnShutdownBeginDialog(); + } else { + OnEmulationStopped(); + } + } +} + +bool GMainWindow::ConfirmShutdownGame() { + if (UISettings::values.confirm_before_stopping.GetValue() == ConfirmStop::Ask_Always) { + if (system->GetExitLocked()) { + if (!ConfirmForceLockedExit()) { + return false; + } + } else { + if (!ConfirmChangeGame()) { + return false; + } + } + } else { + if (UISettings::values.confirm_before_stopping.GetValue() == + ConfirmStop::Ask_Based_On_Game && + system->GetExitLocked()) { + if (!ConfirmForceLockedExit()) { + return false; + } + } + } + return true; +} + +void GMainWindow::OnLoadComplete() { + loading_screen->OnLoadComplete(); +} + +void GMainWindow::OnExecuteProgram(std::size_t program_index) { + ShutdownGame(); + + auto params = ApplicationAppletParameters(); + params.program_index = static_cast(program_index); + params.launch_type = Service::AM::LaunchType::ApplicationInitiated; + BootGame(last_filename_booted, params); +} + +void GMainWindow::OnExit() { + ShutdownGame(); +} + +void GMainWindow::OnSaveConfig() { + system->ApplySettings(); + config->SaveAllValues(); +} + +void GMainWindow::ErrorDisplayDisplayError(QString error_code, QString error_text) { + error_applet = new OverlayDialog(render_window, *system, error_code, error_text, QString{}, + tr("OK"), Qt::AlignLeft | Qt::AlignVCenter); + SCOPE_EXIT { + error_applet->deleteLater(); + error_applet = nullptr; + }; + error_applet->exec(); + + emit ErrorDisplayFinished(); +} + +void GMainWindow::ErrorDisplayRequestExit() { + if (error_applet) { + error_applet->reject(); + } +} + +void GMainWindow::OnMenuReportCompatibility() { +#if defined(ARCHITECTURE_x86_64) && !defined(__APPLE__) + const auto& caps = Common::GetCPUCaps(); + const bool has_fma = caps.fma || caps.fma4; + const auto processor_count = std::thread::hardware_concurrency(); + const bool has_4threads = processor_count == 0 || processor_count >= 4; + const bool has_8gb_ram = Common::GetMemInfo().TotalPhysicalMemory >= 8_GiB; + const bool has_broken_vulkan = UISettings::values.has_broken_vulkan; + + if (!has_fma || !has_4threads || !has_8gb_ram || has_broken_vulkan) { + QMessageBox::critical(this, tr("Hardware requirements not met"), + tr("Your system does not meet the recommended hardware requirements. " + "Compatibility reporting has been disabled.")); + return; + } + + if (!Settings::values.sudachi_token.GetValue().empty() && + !Settings::values.sudachi_username.GetValue().empty()) { + CompatDB compatdb{system->TelemetrySession(), this}; + compatdb.exec(); + } else { + QMessageBox::critical( + this, tr("Missing sudachi Account"), + tr("In order to submit a game compatibility test case, you must link your sudachi " + "account.

To link your sudachi account, go to Emulation > Configuration " + "> " + "Web.")); + } +#else + QMessageBox::critical(this, tr("Hardware requirements not met"), + tr("Your system does not meet the recommended hardware requirements. " + "Compatibility reporting has been disabled.")); +#endif +} + +void GMainWindow::OpenURL(const QUrl& url) { + const bool open = QDesktopServices::openUrl(url); + if (!open) { + QMessageBox::warning(this, tr("Error opening URL"), + tr("Unable to open the URL \"%1\".").arg(url.toString())); + } +} + +void GMainWindow::OnOpenModsPage() { + OpenURL(QUrl(QStringLiteral("https://github.com/sudachi-emu/sudachi/wiki/Switch-Mods"))); +} + +void GMainWindow::OnOpenQuickstartGuide() { + OpenURL(QUrl(QStringLiteral("https://sudachi-emu.org/help/quickstart/"))); +} + +void GMainWindow::OnOpenFAQ() { + OpenURL(QUrl(QStringLiteral("https://sudachi-emu.org/wiki/faq/"))); +} + +void GMainWindow::ToggleFullscreen() { + if (!emulation_running) { + return; + } + if (ui->action_Fullscreen->isChecked()) { + ShowFullscreen(); + } else { + HideFullscreen(); + } +} + +// We're going to return the screen that the given window has the most pixels on +static QScreen* GuessCurrentScreen(QWidget* window) { + const QList screens = QGuiApplication::screens(); + return *std::max_element( + screens.cbegin(), screens.cend(), [window](const QScreen* left, const QScreen* right) { + const QSize left_size = left->geometry().intersected(window->geometry()).size(); + const QSize right_size = right->geometry().intersected(window->geometry()).size(); + return (left_size.height() * left_size.width()) < + (right_size.height() * right_size.width()); + }); +} + +bool GMainWindow::UsingExclusiveFullscreen() { + return Settings::values.fullscreen_mode.GetValue() == Settings::FullscreenMode::Exclusive || + QGuiApplication::platformName() == QStringLiteral("wayland") || + QGuiApplication::platformName() == QStringLiteral("wayland-egl"); +} + +void GMainWindow::ShowFullscreen() { + const auto show_fullscreen = [this](QWidget* window) { + if (UsingExclusiveFullscreen()) { + window->showFullScreen(); + return; + } + window->hide(); + window->setWindowFlags(window->windowFlags() | Qt::FramelessWindowHint); + const auto screen_geometry = GuessCurrentScreen(window)->geometry(); + window->setGeometry(screen_geometry.x(), screen_geometry.y(), screen_geometry.width(), + screen_geometry.height() + 1); + window->raise(); + window->showNormal(); + }; + + if (ui->action_Single_Window_Mode->isChecked()) { + UISettings::values.geometry = saveGeometry(); + + ui->menubar->hide(); + statusBar()->hide(); + + show_fullscreen(this); + } else { + UISettings::values.renderwindow_geometry = render_window->saveGeometry(); + show_fullscreen(render_window); + } +} + +void GMainWindow::HideFullscreen() { + if (ui->action_Single_Window_Mode->isChecked()) { + if (UsingExclusiveFullscreen()) { + showNormal(); + restoreGeometry(UISettings::values.geometry); + } else { + hide(); + setWindowFlags(windowFlags() & ~Qt::FramelessWindowHint); + restoreGeometry(UISettings::values.geometry); + raise(); + show(); + } + + statusBar()->setVisible(ui->action_Show_Status_Bar->isChecked()); + ui->menubar->show(); + } else { + if (UsingExclusiveFullscreen()) { + render_window->showNormal(); + render_window->restoreGeometry(UISettings::values.renderwindow_geometry); + } else { + render_window->hide(); + render_window->setWindowFlags(windowFlags() & ~Qt::FramelessWindowHint); + render_window->restoreGeometry(UISettings::values.renderwindow_geometry); + render_window->raise(); + render_window->show(); + } + } +} + +void GMainWindow::ToggleWindowMode() { + if (ui->action_Single_Window_Mode->isChecked()) { + // Render in the main window... + render_window->BackupGeometry(); + ui->horizontalLayout->addWidget(render_window); + render_window->setFocusPolicy(Qt::StrongFocus); + if (emulation_running) { + render_window->setVisible(true); + render_window->setFocus(); + game_list->hide(); + } + + } else { + // Render in a separate window... + ui->horizontalLayout->removeWidget(render_window); + render_window->setParent(nullptr); + render_window->setFocusPolicy(Qt::NoFocus); + if (emulation_running) { + render_window->setVisible(true); + render_window->RestoreGeometry(); + game_list->show(); + } + } +} + +void GMainWindow::ResetWindowSize(u32 width, u32 height) { + const auto aspect_ratio = Layout::EmulationAspectRatio( + static_cast(Settings::values.aspect_ratio.GetValue()), + static_cast(height) / width); + if (!ui->action_Single_Window_Mode->isChecked()) { + render_window->resize(height / aspect_ratio, height); + } else { + const bool show_status_bar = ui->action_Show_Status_Bar->isChecked(); + const auto status_bar_height = show_status_bar ? statusBar()->height() : 0; + resize(height / aspect_ratio, height + menuBar()->height() + status_bar_height); + } +} + +void GMainWindow::ResetWindowSize720() { + ResetWindowSize(Layout::ScreenUndocked::Width, Layout::ScreenUndocked::Height); +} + +void GMainWindow::ResetWindowSize900() { + ResetWindowSize(1600U, 900U); +} + +void GMainWindow::ResetWindowSize1080() { + ResetWindowSize(Layout::ScreenDocked::Width, Layout::ScreenDocked::Height); +} + +void GMainWindow::OnConfigure() { + const auto old_theme = UISettings::values.theme; + const bool old_discord_presence = UISettings::values.enable_discord_presence.GetValue(); + const auto old_language_index = Settings::values.language_index.GetValue(); +#ifdef __unix__ + const bool old_gamemode = Settings::values.enable_gamemode.GetValue(); +#endif + + Settings::SetConfiguringGlobal(true); + ConfigureDialog configure_dialog(this, hotkey_registry, input_subsystem.get(), + vk_device_records, *system, + !multiplayer_state->IsHostingPublicRoom()); + connect(&configure_dialog, &ConfigureDialog::LanguageChanged, this, + &GMainWindow::OnLanguageChanged); + + const auto result = configure_dialog.exec(); + if (result != QDialog::Accepted && !UISettings::values.configuration_applied && + !UISettings::values.reset_to_defaults) { + // Runs if the user hit Cancel or closed the window, and did not ever press the Apply button + // or `Reset to Defaults` button + return; + } else if (result == QDialog::Accepted) { + // Only apply new changes if user hit Okay + // This is here to avoid applying changes if the user hit Apply, made some changes, then hit + // Cancel + configure_dialog.ApplyConfiguration(); + } else if (UISettings::values.reset_to_defaults) { + LOG_INFO(Frontend, "Resetting all settings to defaults"); + if (!Common::FS::RemoveFile(config->GetConfigFilePath())) { + LOG_WARNING(Frontend, "Failed to remove configuration file"); + } + if (!Common::FS::RemoveDirContentsRecursively( + Common::FS::GetSudachiPath(Common::FS::SudachiPath::ConfigDir) / "custom")) { + LOG_WARNING(Frontend, "Failed to remove custom configuration files"); + } + if (!Common::FS::RemoveDirRecursively( + Common::FS::GetSudachiPath(Common::FS::SudachiPath::CacheDir) / "game_list")) { + LOG_WARNING(Frontend, "Failed to remove game metadata cache files"); + } + + // Explicitly save the game directories, since reinitializing config does not explicitly do + // so. + QVector old_game_dirs = std::move(UISettings::values.game_dirs); + QVector old_favorited_ids = std::move(UISettings::values.favorited_ids); + + Settings::values.disabled_addons.clear(); + + config = std::make_unique(); + UISettings::values.reset_to_defaults = false; + + UISettings::values.game_dirs = std::move(old_game_dirs); + UISettings::values.favorited_ids = std::move(old_favorited_ids); + + InitializeRecentFileMenuActions(); + + SetDefaultUIGeometry(); + RestoreUIState(); + + ShowTelemetryCallout(); + } + InitializeHotkeys(); + + if (UISettings::values.theme != old_theme) { + UpdateUITheme(); + } + if (UISettings::values.enable_discord_presence.GetValue() != old_discord_presence) { + SetDiscordEnabled(UISettings::values.enable_discord_presence.GetValue()); + } +#ifdef __unix__ + if (Settings::values.enable_gamemode.GetValue() != old_gamemode) { + SetGamemodeEnabled(Settings::values.enable_gamemode.GetValue()); + } +#endif + + if (!multiplayer_state->IsHostingPublicRoom()) { + multiplayer_state->UpdateCredentials(); + } + + emit UpdateThemedIcons(); + + const auto reload = UISettings::values.is_game_list_reload_pending.exchange(false); + if (reload || Settings::values.language_index.GetValue() != old_language_index) { + game_list->PopulateAsync(UISettings::values.game_dirs); + } + + UISettings::values.configuration_applied = false; + + config->SaveAllValues(); + + if ((UISettings::values.hide_mouse || Settings::values.mouse_panning) && emulation_running) { + render_window->installEventFilter(render_window); + render_window->setAttribute(Qt::WA_Hover, true); + } else { + render_window->removeEventFilter(render_window); + render_window->setAttribute(Qt::WA_Hover, false); + } + + if (UISettings::values.hide_mouse) { + mouse_hide_timer.start(); + } + + // Restart camera config + if (emulation_running) { + render_window->FinalizeCamera(); + render_window->InitializeCamera(); + } + + if (!UISettings::values.has_broken_vulkan) { + renderer_status_button->setEnabled(!emulation_running); + } + + UpdateStatusButtons(); + controller_dialog->refreshConfiguration(); + system->ApplySettings(); +} + +void GMainWindow::OnConfigureTas() { + ConfigureTasDialog dialog(this); + const auto result = dialog.exec(); + + if (result != QDialog::Accepted && !UISettings::values.configuration_applied) { + Settings::RestoreGlobalState(system->IsPoweredOn()); + return; + } else if (result == QDialog::Accepted) { + dialog.ApplyConfiguration(); + OnSaveConfig(); + } +} + +void GMainWindow::OnTasStartStop() { + if (!emulation_running) { + return; + } + + // Disable system buttons to prevent TAS from executing a hotkey + auto* controller = system->HIDCore().GetEmulatedController(Core::HID::NpadIdType::Player1); + controller->ResetSystemButtons(); + + input_subsystem->GetTas()->StartStop(); + OnTasStateChanged(); +} + +void GMainWindow::OnTasRecord() { + if (!emulation_running) { + return; + } + if (is_tas_recording_dialog_active) { + return; + } + + // Disable system buttons to prevent TAS from recording a hotkey + auto* controller = system->HIDCore().GetEmulatedController(Core::HID::NpadIdType::Player1); + controller->ResetSystemButtons(); + + const bool is_recording = input_subsystem->GetTas()->Record(); + if (!is_recording) { + is_tas_recording_dialog_active = true; + + bool answer = question(this, tr("TAS Recording"), tr("Overwrite file of player 1?"), + QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes); + + input_subsystem->GetTas()->SaveRecording(answer); + is_tas_recording_dialog_active = false; + } + OnTasStateChanged(); +} + +void GMainWindow::OnTasReset() { + input_subsystem->GetTas()->Reset(); +} + +void GMainWindow::OnToggleDockedMode() { + const bool is_docked = Settings::IsDockedMode(); + auto* player_1 = system->HIDCore().GetEmulatedController(Core::HID::NpadIdType::Player1); + auto* handheld = system->HIDCore().GetEmulatedController(Core::HID::NpadIdType::Handheld); + + if (!is_docked && handheld->IsConnected()) { + QMessageBox::warning(this, tr("Invalid config detected"), + tr("Handheld controller can't be used on docked mode. Pro " + "controller will be selected.")); + handheld->Disconnect(); + player_1->SetNpadStyleIndex(Core::HID::NpadStyleIndex::Fullkey); + player_1->Connect(); + controller_dialog->refreshConfiguration(); + } + + Settings::values.use_docked_mode.SetValue(is_docked ? Settings::ConsoleMode::Handheld + : Settings::ConsoleMode::Docked); + UpdateDockedButton(); + OnDockedModeChanged(is_docked, !is_docked, *system); +} + +void GMainWindow::OnToggleGpuAccuracy() { + switch (Settings::values.gpu_accuracy.GetValue()) { + case Settings::GpuAccuracy::High: { + Settings::values.gpu_accuracy.SetValue(Settings::GpuAccuracy::Normal); + break; + } + case Settings::GpuAccuracy::Normal: + case Settings::GpuAccuracy::Extreme: + default: { + Settings::values.gpu_accuracy.SetValue(Settings::GpuAccuracy::High); + break; + } + } + + system->ApplySettings(); + UpdateGPUAccuracyButton(); +} + +void GMainWindow::OnMute() { + Settings::values.audio_muted = !Settings::values.audio_muted; + UpdateVolumeUI(); +} + +void GMainWindow::OnDecreaseVolume() { + Settings::values.audio_muted = false; + const auto current_volume = static_cast(Settings::values.volume.GetValue()); + int step = 5; + if (current_volume <= 30) { + step = 2; + } + if (current_volume <= 6) { + step = 1; + } + Settings::values.volume.SetValue(std::max(current_volume - step, 0)); + UpdateVolumeUI(); +} + +void GMainWindow::OnIncreaseVolume() { + Settings::values.audio_muted = false; + const auto current_volume = static_cast(Settings::values.volume.GetValue()); + int step = 5; + if (current_volume < 30) { + step = 2; + } + if (current_volume < 6) { + step = 1; + } + Settings::values.volume.SetValue(current_volume + step); + UpdateVolumeUI(); +} + +void GMainWindow::OnToggleAdaptingFilter() { + auto filter = Settings::values.scaling_filter.GetValue(); + filter = static_cast(static_cast(filter) + 1); + if (filter == Settings::ScalingFilter::MaxEnum) { + filter = Settings::ScalingFilter::NearestNeighbor; + } + Settings::values.scaling_filter.SetValue(filter); + filter_status_button->setChecked(true); + UpdateFilterText(); +} + +void GMainWindow::OnToggleGraphicsAPI() { + auto api = Settings::values.renderer_backend.GetValue(); + if (api != Settings::RendererBackend::Vulkan) { + api = Settings::RendererBackend::Vulkan; + } else { +#ifdef HAS_OPENGL + api = Settings::RendererBackend::OpenGL; +#else + api = Settings::RendererBackend::Null; +#endif + } + Settings::values.renderer_backend.SetValue(api); + renderer_status_button->setChecked(api == Settings::RendererBackend::Vulkan); + UpdateAPIText(); +} + +void GMainWindow::OnConfigurePerGame() { + const u64 title_id = system->GetApplicationProcessProgramID(); + OpenPerGameConfiguration(title_id, current_game_path.toStdString()); +} + +void GMainWindow::OpenPerGameConfiguration(u64 title_id, const std::string& file_name) { + const auto v_file = Core::GetGameFileFromPath(vfs, file_name); + + Settings::SetConfiguringGlobal(false); + ConfigurePerGame dialog(this, title_id, file_name, vk_device_records, *system); + dialog.LoadFromFile(v_file); + const auto result = dialog.exec(); + + if (result != QDialog::Accepted && !UISettings::values.configuration_applied) { + Settings::RestoreGlobalState(system->IsPoweredOn()); + return; + } else if (result == QDialog::Accepted) { + dialog.ApplyConfiguration(); + } + + const auto reload = UISettings::values.is_game_list_reload_pending.exchange(false); + if (reload) { + game_list->PopulateAsync(UISettings::values.game_dirs); + } + + // Do not cause the global config to write local settings into the config file + const bool is_powered_on = system->IsPoweredOn(); + Settings::RestoreGlobalState(is_powered_on); + system->HIDCore().ReloadInputDevices(); + + UISettings::values.configuration_applied = false; + + if (!is_powered_on) { + config->SaveAllValues(); + } +} + +void GMainWindow::OnLoadAmiibo() { + if (emu_thread == nullptr || !emu_thread->IsRunning()) { + return; + } + if (is_amiibo_file_select_active) { + return; + } + + auto* virtual_amiibo = input_subsystem->GetVirtualAmiibo(); + + // Remove amiibo if one is connected + if (virtual_amiibo->GetCurrentState() == InputCommon::VirtualAmiibo::State::TagNearby) { + virtual_amiibo->CloseAmiibo(); + QMessageBox::warning(this, tr("Amiibo"), tr("The current amiibo has been removed")); + return; + } + + if (virtual_amiibo->GetCurrentState() != InputCommon::VirtualAmiibo::State::WaitingForAmiibo) { + QMessageBox::warning(this, tr("Error"), tr("The current game is not looking for amiibos")); + return; + } + + is_amiibo_file_select_active = true; + const QString extensions{QStringLiteral("*.bin")}; + const QString file_filter = tr("Amiibo File (%1);; All Files (*.*)").arg(extensions); + const QString filename = QFileDialog::getOpenFileName(this, tr("Load Amiibo"), {}, file_filter); + is_amiibo_file_select_active = false; + + if (filename.isEmpty()) { + return; + } + + LoadAmiibo(filename); +} + +bool GMainWindow::question(QWidget* parent, const QString& title, const QString& text, + QMessageBox::StandardButtons buttons, + QMessageBox::StandardButton defaultButton) { + QMessageBox* box_dialog = new QMessageBox(parent); + box_dialog->setWindowTitle(title); + box_dialog->setText(text); + box_dialog->setStandardButtons(buttons); + box_dialog->setDefaultButton(defaultButton); + + ControllerNavigation* controller_navigation = + new ControllerNavigation(system->HIDCore(), box_dialog); + connect(controller_navigation, &ControllerNavigation::TriggerKeyboardEvent, + [box_dialog](Qt::Key key) { + QKeyEvent* event = new QKeyEvent(QEvent::KeyPress, key, Qt::NoModifier); + QCoreApplication::postEvent(box_dialog, event); + }); + int res = box_dialog->exec(); + + controller_navigation->UnloadController(); + return res == QMessageBox::Yes; +} + +void GMainWindow::LoadAmiibo(const QString& filename) { + auto* virtual_amiibo = input_subsystem->GetVirtualAmiibo(); + const QString title = tr("Error loading Amiibo data"); + // Remove amiibo if one is connected + if (virtual_amiibo->GetCurrentState() == InputCommon::VirtualAmiibo::State::TagNearby) { + virtual_amiibo->CloseAmiibo(); + QMessageBox::warning(this, tr("Amiibo"), tr("The current amiibo has been removed")); + return; + } + + switch (virtual_amiibo->LoadAmiibo(filename.toStdString())) { + case InputCommon::VirtualAmiibo::Info::NotAnAmiibo: + QMessageBox::warning(this, title, tr("The selected file is not a valid amiibo")); + break; + case InputCommon::VirtualAmiibo::Info::UnableToLoad: + QMessageBox::warning(this, title, tr("The selected file is already on use")); + break; + case InputCommon::VirtualAmiibo::Info::WrongDeviceState: + QMessageBox::warning(this, title, tr("The current game is not looking for amiibos")); + break; + case InputCommon::VirtualAmiibo::Info::Unknown: + QMessageBox::warning(this, title, tr("An unknown error occurred")); + break; + default: + break; + } +} + +void GMainWindow::OnOpenSudachiFolder() { + QDesktopServices::openUrl(QUrl::fromLocalFile( + QString::fromStdString(Common::FS::GetSudachiPathString(Common::FS::SudachiPath::SudachiDir)))); +} + +void GMainWindow::OnVerifyInstalledContents() { + // Initialize a progress dialog. + QProgressDialog progress(tr("Verifying integrity..."), tr("Cancel"), 0, 100, this); + progress.setWindowModality(Qt::WindowModal); + progress.setMinimumDuration(100); + progress.setAutoClose(false); + progress.setAutoReset(false); + + // Declare progress callback. + auto QtProgressCallback = [&](size_t total_size, size_t processed_size) { + progress.setValue(static_cast((processed_size * 100) / total_size)); + return progress.wasCanceled(); + }; + + const std::vector result = + ContentManager::VerifyInstalledContents(*system, *provider, QtProgressCallback); + progress.close(); + + if (result.empty()) { + QMessageBox::information(this, tr("Integrity verification succeeded!"), + tr("The operation completed successfully.")); + } else { + const auto failed_names = + QString::fromStdString(fmt::format("{}", fmt::join(result, "\n"))); + QMessageBox::critical( + this, tr("Integrity verification failed!"), + tr("Verification failed for the following files:\n\n%1").arg(failed_names)); + } +} + +void GMainWindow::OnInstallFirmware() { + // Don't do this while emulation is running, that'd probably be a bad idea. + if (emu_thread != nullptr && emu_thread->IsRunning()) { + return; + } + + // Check for installed keys, error out, suggest restart? + if (!ContentManager::AreKeysPresent()) { + QMessageBox::information( + this, tr("Keys not installed"), + tr("Install decryption keys and restart sudachi before attempting to install firmware.")); + return; + } + + const QString firmware_source_location = QFileDialog::getExistingDirectory( + this, tr("Select Dumped Firmware Source Location"), {}, QFileDialog::ShowDirsOnly); + if (firmware_source_location.isEmpty()) { + return; + } + + QProgressDialog progress(tr("Installing Firmware..."), tr("Cancel"), 0, 100, this); + progress.setWindowModality(Qt::WindowModal); + progress.setMinimumDuration(100); + progress.setAutoClose(false); + progress.setAutoReset(false); + progress.show(); + + // Declare progress callback. + auto QtProgressCallback = [&](size_t total_size, size_t processed_size) { + progress.setValue(static_cast((processed_size * 100) / total_size)); + return progress.wasCanceled(); + }; + + LOG_INFO(Frontend, "Installing firmware from {}", firmware_source_location.toStdString()); + + // Check for a reasonable number of .nca files (don't hardcode them, just see if there's some in + // there.) + std::filesystem::path firmware_source_path = firmware_source_location.toStdString(); + if (!Common::FS::IsDir(firmware_source_path)) { + progress.close(); + return; + } + + std::vector out; + const Common::FS::DirEntryCallable callback = + [&out](const std::filesystem::directory_entry& entry) { + if (entry.path().has_extension() && entry.path().extension() == ".nca") { + out.emplace_back(entry.path()); + } + + return true; + }; + + QtProgressCallback(100, 10); + + Common::FS::IterateDirEntries(firmware_source_path, callback, Common::FS::DirEntryFilter::File); + if (out.size() <= 0) { + progress.close(); + QMessageBox::warning(this, tr("Firmware install failed"), + tr("Unable to locate potential firmware NCA files")); + return; + } + + // Locate and erase the content of nand/system/Content/registered/*.nca, if any. + auto sysnand_content_vdir = system->GetFileSystemController().GetSystemNANDContentDirectory(); + if (!sysnand_content_vdir->CleanSubdirectoryRecursive("registered")) { + progress.close(); + QMessageBox::critical(this, tr("Firmware install failed"), + tr("Failed to delete one or more firmware file.")); + return; + } + + LOG_INFO(Frontend, + "Cleaned nand/system/Content/registered folder in preparation for new firmware."); + + QtProgressCallback(100, 20); + + auto firmware_vdir = sysnand_content_vdir->GetDirectoryRelative("registered"); + + bool success = true; + int i = 0; + for (const auto& firmware_src_path : out) { + i++; + auto firmware_src_vfile = + vfs->OpenFile(firmware_src_path.generic_string(), FileSys::OpenMode::Read); + auto firmware_dst_vfile = + firmware_vdir->CreateFileRelative(firmware_src_path.filename().string()); + + if (!VfsRawCopy(firmware_src_vfile, firmware_dst_vfile)) { + LOG_ERROR(Frontend, "Failed to copy firmware file {} to {} in registered folder!", + firmware_src_path.generic_string(), firmware_src_path.filename().string()); + success = false; + } + + if (QtProgressCallback( + 100, 20 + static_cast(((i) / static_cast(out.size())) * 70.0))) { + progress.close(); + QMessageBox::warning( + this, tr("Firmware install failed"), + tr("Firmware installation cancelled, firmware may be in bad state, " + "restart sudachi or re-install firmware.")); + return; + } + } + + if (!success) { + progress.close(); + QMessageBox::critical(this, tr("Firmware install failed"), + tr("One or more firmware files failed to copy into NAND.")); + return; + } + + // Re-scan VFS for the newly placed firmware files. + system->GetFileSystemController().CreateFactories(*vfs); + + auto VerifyFirmwareCallback = [&](size_t total_size, size_t processed_size) { + progress.setValue(90 + static_cast((processed_size * 10) / total_size)); + return progress.wasCanceled(); + }; + + auto result = + ContentManager::VerifyInstalledContents(*system, *provider, VerifyFirmwareCallback, true); + + if (result.size() > 0) { + const auto failed_names = + QString::fromStdString(fmt::format("{}", fmt::join(result, "\n"))); + progress.close(); + QMessageBox::critical( + this, tr("Firmware integrity verification failed!"), + tr("Verification failed for the following files:\n\n%1").arg(failed_names)); + return; + } + + progress.close(); + OnCheckFirmwareDecryption(); +} + +void GMainWindow::OnInstallDecryptionKeys() { + // Don't do this while emulation is running. + if (emu_thread != nullptr && emu_thread->IsRunning()) { + return; + } + + const QString key_source_location = QFileDialog::getOpenFileName( + this, tr("Select Dumped Keys Location"), {}, QStringLiteral("prod.keys (prod.keys)"), {}, + QFileDialog::ReadOnly); + if (key_source_location.isEmpty()) { + return; + } + + // Verify that it contains prod.keys, title.keys and optionally, key_retail.bin + LOG_INFO(Frontend, "Installing key files from {}", key_source_location.toStdString()); + + const std::filesystem::path prod_key_path = key_source_location.toStdString(); + const std::filesystem::path key_source_path = prod_key_path.parent_path(); + if (!Common::FS::IsDir(key_source_path)) { + return; + } + + bool prod_keys_found = false; + std::vector source_key_files; + + if (Common::FS::Exists(prod_key_path)) { + prod_keys_found = true; + source_key_files.emplace_back(prod_key_path); + } + + if (Common::FS::Exists(key_source_path / "title.keys")) { + source_key_files.emplace_back(key_source_path / "title.keys"); + } + + if (Common::FS::Exists(key_source_path / "key_retail.bin")) { + source_key_files.emplace_back(key_source_path / "key_retail.bin"); + } + + // There should be at least prod.keys. + if (source_key_files.empty() || !prod_keys_found) { + QMessageBox::warning(this, tr("Decryption Keys install failed"), + tr("prod.keys is a required decryption key file.")); + return; + } + + const auto sudachi_keys_dir = Common::FS::GetSudachiPath(Common::FS::SudachiPath::KeysDir); + for (auto key_file : source_key_files) { + std::filesystem::path destination_key_file = sudachi_keys_dir / key_file.filename(); + if (!std::filesystem::copy_file(key_file, destination_key_file, + std::filesystem::copy_options::overwrite_existing)) { + LOG_ERROR(Frontend, "Failed to copy file {} to {}", key_file.string(), + destination_key_file.string()); + QMessageBox::critical(this, tr("Decryption Keys install failed"), + tr("One or more keys failed to copy.")); + return; + } + } + + // Reinitialize the key manager, re-read the vfs (for update/dlc files), + // and re-populate the game list in the UI if the user has already added + // game folders. + Core::Crypto::KeyManager::Instance().ReloadKeys(); + system->GetFileSystemController().CreateFactories(*vfs); + game_list->PopulateAsync(UISettings::values.game_dirs); + + if (ContentManager::AreKeysPresent()) { + QMessageBox::information(this, tr("Decryption Keys install succeeded"), + tr("Decryption Keys were successfully installed")); + } else { + QMessageBox::critical( + this, tr("Decryption Keys install failed"), + tr("Decryption Keys failed to initialize. Check that your dumping tools are " + "up to date and re-dump keys.")); + } + + OnCheckFirmwareDecryption(); +} + +void GMainWindow::OnAbout() { + AboutDialog aboutDialog(this); + aboutDialog.exec(); +} + +void GMainWindow::OnToggleFilterBar() { + game_list->SetFilterVisible(ui->action_Show_Filter_Bar->isChecked()); + if (ui->action_Show_Filter_Bar->isChecked()) { + game_list->SetFilterFocus(); + } else { + game_list->ClearFilter(); + } +} + +void GMainWindow::OnToggleStatusBar() { + statusBar()->setVisible(ui->action_Show_Status_Bar->isChecked()); +} + +void GMainWindow::OnAlbum() { + constexpr u64 AlbumId = static_cast(Service::AM::AppletProgramId::PhotoViewer); + auto bis_system = system->GetFileSystemController().GetSystemNANDContents(); + if (!bis_system) { + QMessageBox::warning(this, tr("No firmware available"), + tr("Please install the firmware to use the Album applet.")); + return; + } + + auto album_nca = bis_system->GetEntry(AlbumId, FileSys::ContentRecordType::Program); + if (!album_nca) { + QMessageBox::warning(this, tr("Album Applet"), + tr("Album applet is not available. Please reinstall firmware.")); + return; + } + + system->GetFrontendAppletHolder().SetCurrentAppletId(Service::AM::AppletId::PhotoViewer); + + const auto filename = QString::fromStdString(album_nca->GetFullPath()); + UISettings::values.roms_path = QFileInfo(filename).path().toStdString(); + BootGame(filename, LibraryAppletParameters(AlbumId, Service::AM::AppletId::PhotoViewer)); +} + +void GMainWindow::OnCabinet(Service::NFP::CabinetMode mode) { + constexpr u64 CabinetId = static_cast(Service::AM::AppletProgramId::Cabinet); + auto bis_system = system->GetFileSystemController().GetSystemNANDContents(); + if (!bis_system) { + QMessageBox::warning(this, tr("No firmware available"), + tr("Please install the firmware to use the Cabinet applet.")); + return; + } + + auto cabinet_nca = bis_system->GetEntry(CabinetId, FileSys::ContentRecordType::Program); + if (!cabinet_nca) { + QMessageBox::warning(this, tr("Cabinet Applet"), + tr("Cabinet applet is not available. Please reinstall firmware.")); + return; + } + + system->GetFrontendAppletHolder().SetCurrentAppletId(Service::AM::AppletId::Cabinet); + system->GetFrontendAppletHolder().SetCabinetMode(mode); + + const auto filename = QString::fromStdString(cabinet_nca->GetFullPath()); + UISettings::values.roms_path = QFileInfo(filename).path().toStdString(); + BootGame(filename, LibraryAppletParameters(CabinetId, Service::AM::AppletId::Cabinet)); +} + +void GMainWindow::OnMiiEdit() { + constexpr u64 MiiEditId = static_cast(Service::AM::AppletProgramId::MiiEdit); + auto bis_system = system->GetFileSystemController().GetSystemNANDContents(); + if (!bis_system) { + QMessageBox::warning(this, tr("No firmware available"), + tr("Please install the firmware to use the Mii editor.")); + return; + } + + auto mii_applet_nca = bis_system->GetEntry(MiiEditId, FileSys::ContentRecordType::Program); + if (!mii_applet_nca) { + QMessageBox::warning(this, tr("Mii Edit Applet"), + tr("Mii editor is not available. Please reinstall firmware.")); + return; + } + + system->GetFrontendAppletHolder().SetCurrentAppletId(Service::AM::AppletId::MiiEdit); + + const auto filename = QString::fromStdString((mii_applet_nca->GetFullPath())); + UISettings::values.roms_path = QFileInfo(filename).path().toStdString(); + BootGame(filename, LibraryAppletParameters(MiiEditId, Service::AM::AppletId::MiiEdit)); +} + +void GMainWindow::OnOpenControllerMenu() { + constexpr u64 ControllerAppletId = static_cast(Service::AM::AppletProgramId::Controller); + auto bis_system = system->GetFileSystemController().GetSystemNANDContents(); + if (!bis_system) { + QMessageBox::warning(this, tr("No firmware available"), + tr("Please install the firmware to use the Controller Menu.")); + return; + } + + auto controller_applet_nca = + bis_system->GetEntry(ControllerAppletId, FileSys::ContentRecordType::Program); + if (!controller_applet_nca) { + QMessageBox::warning(this, tr("Controller Applet"), + tr("Controller Menu is not available. Please reinstall firmware.")); + return; + } + + system->GetFrontendAppletHolder().SetCurrentAppletId(Service::AM::AppletId::Controller); + + const auto filename = QString::fromStdString((controller_applet_nca->GetFullPath())); + UISettings::values.roms_path = QFileInfo(filename).path().toStdString(); + BootGame(filename, + LibraryAppletParameters(ControllerAppletId, Service::AM::AppletId::Controller)); +} + +void GMainWindow::OnCaptureScreenshot() { + if (emu_thread == nullptr || !emu_thread->IsRunning()) { + return; + } + + const u64 title_id = system->GetApplicationProcessProgramID(); + const auto screenshot_path = + QString::fromStdString(Common::FS::GetSudachiPathString(Common::FS::SudachiPath::ScreenshotsDir)); + const auto date = + QDateTime::currentDateTime().toString(QStringLiteral("yyyy-MM-dd_hh-mm-ss-zzz")); + QString filename = QStringLiteral("%1/%2_%3.png") + .arg(screenshot_path) + .arg(title_id, 16, 16, QLatin1Char{'0'}) + .arg(date); + + if (!Common::FS::CreateDir(screenshot_path.toStdString())) { + return; + } + +#ifdef _WIN32 + if (UISettings::values.enable_screenshot_save_as) { + OnPauseGame(); + filename = QFileDialog::getSaveFileName(this, tr("Capture Screenshot"), filename, + tr("PNG Image (*.png)")); + OnStartGame(); + if (filename.isEmpty()) { + return; + } + } +#endif + render_window->CaptureScreenshot(filename); +} + +// TODO: Written 2020-10-01: Remove per-game config migration code when it is irrelevant +void GMainWindow::MigrateConfigFiles() { + const auto config_dir_fs_path = Common::FS::GetSudachiPath(Common::FS::SudachiPath::ConfigDir); + const QDir config_dir = + QDir(QString::fromStdString(Common::FS::PathToUTF8String(config_dir_fs_path))); + const QStringList config_dir_list = config_dir.entryList(QStringList(QStringLiteral("*.ini"))); + + if (!Common::FS::CreateDirs(config_dir_fs_path / "custom")) { + LOG_ERROR(Frontend, "Failed to create new config file directory"); + } + + for (auto it = config_dir_list.constBegin(); it != config_dir_list.constEnd(); ++it) { + const auto filename = it->toStdString(); + if (filename.find_first_not_of("0123456789abcdefACBDEF", 0) < 16) { + continue; + } + const auto origin = config_dir_fs_path / filename; + const auto destination = config_dir_fs_path / "custom" / filename; + LOG_INFO(Frontend, "Migrating config file from {} to {}", origin.string(), + destination.string()); + if (!Common::FS::RenameFile(origin, destination)) { + // Delete the old config file if one already exists in the new location. + Common::FS::RemoveFile(origin); + } + } +} + +void GMainWindow::UpdateWindowTitle(std::string_view title_name, std::string_view title_version, + std::string_view gpu_vendor) { + const auto branch_name = std::string(Common::g_scm_branch); + const auto description = std::string(Common::g_scm_desc); + const auto build_id = std::string(Common::g_build_id); + + const auto sudachi_title = fmt::format("sudachi | {}-{}", branch_name, description); + const auto override_title = + fmt::format(fmt::runtime(std::string(Common::g_title_bar_format_idle)), build_id); + const auto window_title = override_title.empty() ? sudachi_title : override_title; + + if (title_name.empty()) { + setWindowTitle(QString::fromStdString(window_title)); + } else { + const auto run_title = [window_title, title_name, title_version, gpu_vendor]() { + if (title_version.empty()) { + return fmt::format("{} | {} | {}", window_title, title_name, gpu_vendor); + } + return fmt::format("{} | {} | {} | {}", window_title, title_name, title_version, + gpu_vendor); + }(); + setWindowTitle(QString::fromStdString(run_title)); + } +} + +std::string GMainWindow::CreateTASFramesString( + std::array frames) const { + std::string string = ""; + size_t maxPlayerIndex = 0; + for (size_t i = 0; i < frames.size(); i++) { + if (frames[i] != 0) { + if (maxPlayerIndex != 0) + string += ", "; + while (maxPlayerIndex++ != i) + string += "0, "; + string += std::to_string(frames[i]); + } + } + return string; +} + +QString GMainWindow::GetTasStateDescription() const { + auto [tas_status, current_tas_frame, total_tas_frames] = input_subsystem->GetTas()->GetStatus(); + std::string tas_frames_string = CreateTASFramesString(total_tas_frames); + switch (tas_status) { + case InputCommon::TasInput::TasState::Running: + return tr("TAS state: Running %1/%2") + .arg(current_tas_frame) + .arg(QString::fromStdString(tas_frames_string)); + case InputCommon::TasInput::TasState::Recording: + return tr("TAS state: Recording %1").arg(total_tas_frames[0]); + case InputCommon::TasInput::TasState::Stopped: + return tr("TAS state: Idle %1/%2") + .arg(current_tas_frame) + .arg(QString::fromStdString(tas_frames_string)); + default: + return tr("TAS State: Invalid"); + } +} + +void GMainWindow::OnTasStateChanged() { + bool is_running = false; + bool is_recording = false; + if (emulation_running) { + const InputCommon::TasInput::TasState tas_status = + std::get<0>(input_subsystem->GetTas()->GetStatus()); + is_running = tas_status == InputCommon::TasInput::TasState::Running; + is_recording = tas_status == InputCommon::TasInput::TasState::Recording; + } + + ui->action_TAS_Start->setText(is_running ? tr("&Stop Running") : tr("&Start")); + ui->action_TAS_Record->setText(is_recording ? tr("Stop R&ecording") : tr("R&ecord")); + + ui->action_TAS_Start->setEnabled(emulation_running); + ui->action_TAS_Record->setEnabled(emulation_running); + ui->action_TAS_Reset->setEnabled(emulation_running); +} + +void GMainWindow::UpdateStatusBar() { + if (emu_thread == nullptr || !system->IsPoweredOn()) { + status_bar_update_timer.stop(); + return; + } + + if (Settings::values.tas_enable) { + tas_label->setText(GetTasStateDescription()); + } else { + tas_label->clear(); + } + + auto results = system->GetAndResetPerfStats(); + auto& shader_notify = system->GPU().ShaderNotify(); + const int shaders_building = shader_notify.ShadersBuilding(); + + if (shaders_building > 0) { + shader_building_label->setText(tr("Building: %n shader(s)", "", shaders_building)); + shader_building_label->setVisible(true); + } else { + shader_building_label->setVisible(false); + } + + const auto res_info = Settings::values.resolution_info; + const auto res_scale = res_info.up_factor; + res_scale_label->setText( + tr("Scale: %1x", "%1 is the resolution scaling factor").arg(res_scale)); + + if (Settings::values.use_speed_limit.GetValue()) { + emu_speed_label->setText(tr("Speed: %1% / %2%") + .arg(results.emulation_speed * 100.0, 0, 'f', 0) + .arg(Settings::values.speed_limit.GetValue())); + } else { + emu_speed_label->setText(tr("Speed: %1%").arg(results.emulation_speed * 100.0, 0, 'f', 0)); + } + if (!Settings::values.use_speed_limit) { + game_fps_label->setText( + tr("Game: %1 FPS (Unlocked)").arg(std::round(results.average_game_fps), 0, 'f', 0)); + } else { + game_fps_label->setText( + tr("Game: %1 FPS").arg(std::round(results.average_game_fps), 0, 'f', 0)); + } + emu_frametime_label->setText(tr("Frame: %1 ms").arg(results.frametime * 1000.0, 0, 'f', 2)); + + res_scale_label->setVisible(true); + emu_speed_label->setVisible(!Settings::values.use_multi_core.GetValue()); + game_fps_label->setVisible(true); + emu_frametime_label->setVisible(true); + firmware_label->setVisible(false); +} + +void GMainWindow::UpdateGPUAccuracyButton() { + const auto gpu_accuracy = Settings::values.gpu_accuracy.GetValue(); + const auto gpu_accuracy_text = + ConfigurationShared::gpu_accuracy_texts_map.find(gpu_accuracy)->second; + gpu_accuracy_button->setText(gpu_accuracy_text.toUpper()); + gpu_accuracy_button->setChecked(gpu_accuracy != Settings::GpuAccuracy::Normal); +} + +void GMainWindow::UpdateDockedButton() { + const auto console_mode = Settings::values.use_docked_mode.GetValue(); + dock_status_button->setChecked(Settings::IsDockedMode()); + dock_status_button->setText( + ConfigurationShared::use_docked_mode_texts_map.find(console_mode)->second.toUpper()); +} + +void GMainWindow::UpdateAPIText() { + const auto api = Settings::values.renderer_backend.GetValue(); + const auto renderer_status_text = + ConfigurationShared::renderer_backend_texts_map.find(api)->second; + renderer_status_button->setText( + api == Settings::RendererBackend::OpenGL + ? tr("%1 %2").arg(renderer_status_text.toUpper(), + ConfigurationShared::shader_backend_texts_map + .find(Settings::values.shader_backend.GetValue()) + ->second) + : renderer_status_text.toUpper()); +} + +void GMainWindow::UpdateFilterText() { + const auto filter = Settings::values.scaling_filter.GetValue(); + const auto filter_text = ConfigurationShared::scaling_filter_texts_map.find(filter)->second; + filter_status_button->setText(filter == Settings::ScalingFilter::Fsr ? tr("FSR") + : filter_text.toUpper()); +} + +void GMainWindow::UpdateAAText() { + const auto aa_mode = Settings::values.anti_aliasing.GetValue(); + const auto aa_text = ConfigurationShared::anti_aliasing_texts_map.find(aa_mode)->second; + aa_status_button->setText(aa_mode == Settings::AntiAliasing::None + ? QStringLiteral(QT_TRANSLATE_NOOP("GMainWindow", "NO AA")) + : aa_text.toUpper()); +} + +void GMainWindow::UpdateVolumeUI() { + const auto volume_value = static_cast(Settings::values.volume.GetValue()); + volume_slider->setValue(volume_value); + if (Settings::values.audio_muted) { + volume_button->setChecked(false); + volume_button->setText(tr("VOLUME: MUTE")); + } else { + volume_button->setChecked(true); + volume_button->setText(tr("VOLUME: %1%", "Volume percentage (e.g. 50%)").arg(volume_value)); + } +} + +void GMainWindow::UpdateStatusButtons() { + renderer_status_button->setChecked(Settings::values.renderer_backend.GetValue() == + Settings::RendererBackend::Vulkan); + UpdateAPIText(); + UpdateGPUAccuracyButton(); + UpdateDockedButton(); + UpdateFilterText(); + UpdateAAText(); + UpdateVolumeUI(); +} + +void GMainWindow::UpdateUISettings() { + if (!ui->action_Fullscreen->isChecked()) { + UISettings::values.geometry = saveGeometry(); + UISettings::values.renderwindow_geometry = render_window->saveGeometry(); + } + UISettings::values.state = saveState(); +#if MICROPROFILE_ENABLED + UISettings::values.microprofile_geometry = microProfileDialog->saveGeometry(); + UISettings::values.microprofile_visible = microProfileDialog->isVisible(); +#endif + UISettings::values.single_window_mode = ui->action_Single_Window_Mode->isChecked(); + UISettings::values.fullscreen = ui->action_Fullscreen->isChecked(); + UISettings::values.display_titlebar = ui->action_Display_Dock_Widget_Headers->isChecked(); + UISettings::values.show_filter_bar = ui->action_Show_Filter_Bar->isChecked(); + UISettings::values.show_status_bar = ui->action_Show_Status_Bar->isChecked(); + UISettings::values.first_start = false; +} + +void GMainWindow::UpdateInputDrivers() { + if (!input_subsystem) { + return; + } + input_subsystem->PumpEvents(); +} + +void GMainWindow::HideMouseCursor() { + if (emu_thread == nullptr && UISettings::values.hide_mouse) { + mouse_hide_timer.stop(); + ShowMouseCursor(); + return; + } + render_window->setCursor(QCursor(Qt::BlankCursor)); +} + +void GMainWindow::ShowMouseCursor() { + render_window->unsetCursor(); + if (emu_thread != nullptr && UISettings::values.hide_mouse) { + mouse_hide_timer.start(); + } +} + +void GMainWindow::OnMouseActivity() { + if (!Settings::values.mouse_panning) { + ShowMouseCursor(); + } +} + +void GMainWindow::OnCheckFirmwareDecryption() { + system->GetFileSystemController().CreateFactories(*vfs); + if (!ContentManager::AreKeysPresent()) { + QMessageBox::warning( + this, tr("Derivation Components Missing"), + tr("Encryption keys are missing. " + "
Please follow the sudachi " + "quickstart guide to get all your keys, firmware and " + "games.")); + } + SetFirmwareVersion(); + UpdateMenuState(); +} + +bool GMainWindow::CheckFirmwarePresence() { + constexpr u64 MiiEditId = static_cast(Service::AM::AppletProgramId::MiiEdit); + + auto bis_system = system->GetFileSystemController().GetSystemNANDContents(); + if (!bis_system) { + return false; + } + + auto mii_applet_nca = bis_system->GetEntry(MiiEditId, FileSys::ContentRecordType::Program); + if (!mii_applet_nca) { + return false; + } + + return true; +} + +void GMainWindow::SetFirmwareVersion() { + Service::Set::FirmwareVersionFormat firmware_data{}; + const auto result = Service::Set::GetFirmwareVersionImpl( + firmware_data, *system, Service::Set::GetFirmwareVersionType::Version2); + + if (result.IsError() || !CheckFirmwarePresence()) { + LOG_INFO(Frontend, "Installed firmware: No firmware available"); + firmware_label->setVisible(false); + return; + } + + firmware_label->setVisible(true); + + const std::string display_version(firmware_data.display_version.data()); + const std::string display_title(firmware_data.display_title.data()); + + LOG_INFO(Frontend, "Installed firmware: {}", display_title); + + firmware_label->setText(QString::fromStdString(display_version)); + firmware_label->setToolTip(QString::fromStdString(display_title)); +} + +bool GMainWindow::SelectRomFSDumpTarget(const FileSys::ContentProvider& installed, u64 program_id, + u64* selected_title_id, u8* selected_content_record_type) { + using ContentInfo = std::tuple; + boost::container::flat_set available_title_ids; + + const auto RetrieveEntries = [&](FileSys::TitleType title_type, + FileSys::ContentRecordType record_type) { + const auto entries = installed.ListEntriesFilter(title_type, record_type); + for (const auto& entry : entries) { + if (FileSys::GetBaseTitleID(entry.title_id) == program_id && + installed.GetEntry(entry)->GetStatus() == Loader::ResultStatus::Success) { + available_title_ids.insert({entry.title_id, title_type, record_type}); + } + } + }; + + RetrieveEntries(FileSys::TitleType::Application, FileSys::ContentRecordType::Program); + RetrieveEntries(FileSys::TitleType::Application, FileSys::ContentRecordType::HtmlDocument); + RetrieveEntries(FileSys::TitleType::Application, FileSys::ContentRecordType::LegalInformation); + RetrieveEntries(FileSys::TitleType::AOC, FileSys::ContentRecordType::Data); + + if (available_title_ids.empty()) { + return false; + } + + size_t title_index = 0; + + if (available_title_ids.size() > 1) { + QStringList list; + for (auto& [title_id, title_type, record_type] : available_title_ids) { + const auto hex_title_id = QString::fromStdString(fmt::format("{:X}", title_id)); + if (record_type == FileSys::ContentRecordType::Program) { + list.push_back(QStringLiteral("Program [%1]").arg(hex_title_id)); + } else if (record_type == FileSys::ContentRecordType::HtmlDocument) { + list.push_back(QStringLiteral("HTML document [%1]").arg(hex_title_id)); + } else if (record_type == FileSys::ContentRecordType::LegalInformation) { + list.push_back(QStringLiteral("Legal information [%1]").arg(hex_title_id)); + } else { + list.push_back( + QStringLiteral("DLC %1 [%2]").arg(title_id & 0x7FF).arg(hex_title_id)); + } + } + + bool ok; + const auto res = QInputDialog::getItem( + this, tr("Select RomFS Dump Target"), + tr("Please select which RomFS you would like to dump."), list, 0, false, &ok); + if (!ok) { + return false; + } + + title_index = list.indexOf(res); + } + + const auto& [title_id, title_type, record_type] = *available_title_ids.nth(title_index); + *selected_title_id = title_id; + *selected_content_record_type = static_cast(record_type); + return true; +} + +bool GMainWindow::ConfirmClose() { + if (emu_thread == nullptr || + UISettings::values.confirm_before_stopping.GetValue() == ConfirmStop::Ask_Never) { + return true; + } + if (!system->GetExitLocked() && + UISettings::values.confirm_before_stopping.GetValue() == ConfirmStop::Ask_Based_On_Game) { + return true; + } + const auto text = tr("Are you sure you want to close sudachi?"); + return question(this, tr("sudachi"), text); +} + +void GMainWindow::closeEvent(QCloseEvent* event) { + if (!ConfirmClose()) { + event->ignore(); + return; + } + + UpdateUISettings(); + game_list->SaveInterfaceLayout(); + UISettings::SaveWindowState(); + hotkey_registry.SaveHotkeys(); + + // Unload controllers early + controller_dialog->UnloadController(); + game_list->UnloadController(); + + // Shutdown session if the emu thread is active... + if (emu_thread != nullptr) { + ShutdownGame(); + } + + render_window->close(); + multiplayer_state->Close(); + system->HIDCore().UnloadInputDevices(); + system->GetRoomNetwork().Shutdown(); + + QWidget::closeEvent(event); +} + +static bool IsSingleFileDropEvent(const QMimeData* mime) { + return mime->hasUrls() && mime->urls().length() == 1; +} + +void GMainWindow::AcceptDropEvent(QDropEvent* event) { + if (IsSingleFileDropEvent(event->mimeData())) { + event->setDropAction(Qt::DropAction::LinkAction); + event->accept(); + } +} + +bool GMainWindow::DropAction(QDropEvent* event) { + if (!IsSingleFileDropEvent(event->mimeData())) { + return false; + } + + const QMimeData* mime_data = event->mimeData(); + const QString& filename = mime_data->urls().at(0).toLocalFile(); + + if (emulation_running && QFileInfo(filename).suffix() == QStringLiteral("bin")) { + // Amiibo + LoadAmiibo(filename); + } else { + // Game + if (ConfirmChangeGame()) { + BootGame(filename, ApplicationAppletParameters()); + } + } + return true; +} + +void GMainWindow::dropEvent(QDropEvent* event) { + DropAction(event); +} + +void GMainWindow::dragEnterEvent(QDragEnterEvent* event) { + AcceptDropEvent(event); +} + +void GMainWindow::dragMoveEvent(QDragMoveEvent* event) { + AcceptDropEvent(event); +} + +bool GMainWindow::ConfirmChangeGame() { + if (emu_thread == nullptr) + return true; + + // Use custom question to link controller navigation + return question( + this, tr("sudachi"), + tr("Are you sure you want to stop the emulation? Any unsaved progress will be lost."), + QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes); +} + +bool GMainWindow::ConfirmForceLockedExit() { + if (emu_thread == nullptr) { + return true; + } + const auto text = tr("The currently running application has requested sudachi to not exit.\n\n" + "Would you like to bypass this and exit anyway?"); + + return question(this, tr("sudachi"), text); +} + +void GMainWindow::RequestGameExit() { + if (!system->IsPoweredOn()) { + return; + } + + system->SetExitRequested(true); + system->GetAppletManager().RequestExit(); +} + +void GMainWindow::filterBarSetChecked(bool state) { + ui->action_Show_Filter_Bar->setChecked(state); + emit(OnToggleFilterBar()); +} + +static void AdjustLinkColor() { + QPalette new_pal(qApp->palette()); + if (UISettings::IsDarkTheme()) { + new_pal.setColor(QPalette::Link, QColor(0, 190, 255, 255)); + } else { + new_pal.setColor(QPalette::Link, QColor(0, 140, 200, 255)); + } + if (qApp->palette().color(QPalette::Link) != new_pal.color(QPalette::Link)) { + qApp->setPalette(new_pal); + } +} + +void GMainWindow::UpdateUITheme() { + const QString default_theme = QString::fromUtf8( + UISettings::themes[static_cast(UISettings::default_theme)].second); + QString current_theme = QString::fromStdString(UISettings::values.theme); + + if (current_theme.isEmpty()) { + current_theme = default_theme; + } + +#ifdef _WIN32 + QIcon::setThemeName(current_theme); + AdjustLinkColor(); +#else + if (current_theme == QStringLiteral("default") || current_theme == QStringLiteral("colorful")) { + QIcon::setThemeName(current_theme == QStringLiteral("colorful") ? current_theme + : startup_icon_theme); + QIcon::setThemeSearchPaths(QStringList(default_theme_paths)); + if (CheckDarkMode()) { + current_theme = QStringLiteral("default_dark"); + } + } else { + QIcon::setThemeName(current_theme); + QIcon::setThemeSearchPaths(QStringList(QStringLiteral(":/icons"))); + AdjustLinkColor(); + } +#endif + if (current_theme != default_theme) { + QString theme_uri{QStringLiteral(":%1/style.qss").arg(current_theme)}; + QFile f(theme_uri); + if (!f.open(QFile::ReadOnly | QFile::Text)) { + LOG_ERROR(Frontend, "Unable to open style \"{}\", fallback to the default theme", + UISettings::values.theme); + current_theme = default_theme; + } + } + + QString theme_uri{QStringLiteral(":%1/style.qss").arg(current_theme)}; + QFile f(theme_uri); + if (f.open(QFile::ReadOnly | QFile::Text)) { + QTextStream ts(&f); + qApp->setStyleSheet(ts.readAll()); + setStyleSheet(ts.readAll()); + } else { + LOG_ERROR(Frontend, "Unable to set style \"{}\", stylesheet file not found", + UISettings::values.theme); + qApp->setStyleSheet({}); + setStyleSheet({}); + } +} + +void GMainWindow::LoadTranslation() { + bool loaded; + + if (UISettings::values.language.GetValue().empty()) { + // If the selected language is empty, use system locale + loaded = translator.load(QLocale(), {}, {}, QStringLiteral(":/languages/")); + } else { + // Otherwise load from the specified file + loaded = translator.load(QString::fromStdString(UISettings::values.language.GetValue()), + QStringLiteral(":/languages/")); + } + + if (loaded) { + qApp->installTranslator(&translator); + } else { + UISettings::values.language = std::string("en"); + } +} + +void GMainWindow::OnLanguageChanged(const QString& locale) { + if (UISettings::values.language.GetValue() != std::string("en")) { + qApp->removeTranslator(&translator); + } + + UISettings::values.language = locale.toStdString(); + LoadTranslation(); + ui->retranslateUi(this); + multiplayer_state->retranslateUi(); + UpdateWindowTitle(); +} + +void GMainWindow::SetDiscordEnabled([[maybe_unused]] bool state) { +#ifdef USE_DISCORD_PRESENCE + if (state) { + discord_rpc = std::make_unique(*system); + } else { + discord_rpc = std::make_unique(); + } +#else + discord_rpc = std::make_unique(); +#endif + discord_rpc->Update(); +} + +#ifdef __unix__ +void GMainWindow::SetGamemodeEnabled(bool state) { + if (emulation_running) { + Common::Linux::SetGamemodeState(state); + } +} +#endif + +void GMainWindow::changeEvent(QEvent* event) { +#ifdef __unix__ + // PaletteChange event appears to only reach so far into the GUI, explicitly asking to + // UpdateUITheme is a decent work around + if (event->type() == QEvent::PaletteChange) { + const QPalette test_palette(qApp->palette()); + const QString current_theme = QString::fromStdString(UISettings::values.theme); + // Keeping eye on QPalette::Window to avoid looping. QPalette::Text might be useful too + static QColor last_window_color; + const QColor window_color = test_palette.color(QPalette::Active, QPalette::Window); + if (last_window_color != window_color && (current_theme == QStringLiteral("default") || + current_theme == QStringLiteral("colorful"))) { + UpdateUITheme(); + } + last_window_color = window_color; + } +#endif // __unix__ + QWidget::changeEvent(event); +} + +Service::AM::FrontendAppletParameters GMainWindow::ApplicationAppletParameters() { + return Service::AM::FrontendAppletParameters{ + .applet_id = Service::AM::AppletId::Application, + .applet_type = Service::AM::AppletType::Application, + }; +} + +Service::AM::FrontendAppletParameters GMainWindow::LibraryAppletParameters( + u64 program_id, Service::AM::AppletId applet_id) { + return Service::AM::FrontendAppletParameters{ + .program_id = program_id, + .applet_id = applet_id, + .applet_type = Service::AM::AppletType::LibraryApplet, + }; +} + +void VolumeButton::wheelEvent(QWheelEvent* event) { + + int num_degrees = event->angleDelta().y() / 8; + int num_steps = (num_degrees / 15) * scroll_multiplier; + // Stated in QT docs: Most mouse types work in steps of 15 degrees, in which case the delta + // value is a multiple of 120; i.e., 120 units * 1/8 = 15 degrees. + + if (num_steps > 0) { + Settings::values.volume.SetValue( + std::min(200, Settings::values.volume.GetValue() + num_steps)); + } else { + Settings::values.volume.SetValue( + std::max(0, Settings::values.volume.GetValue() + num_steps)); + } + + scroll_multiplier = std::min(MaxMultiplier, scroll_multiplier * 2); + scroll_timer.start(100); // reset the multiplier if no scroll event occurs within 100 ms + + emit VolumeChanged(); + event->accept(); +} + +void VolumeButton::ResetMultiplier() { + scroll_multiplier = 1; +} + +#ifdef main +#undef main +#endif + +static void SetHighDPIAttributes() { +#ifdef _WIN32 + // For Windows, we want to avoid scaling artifacts on fractional scaling ratios. + // This is done by setting the optimal scaling policy for the primary screen. + + // Create a temporary QApplication. + int temp_argc = 0; + char** temp_argv = nullptr; + QApplication temp{temp_argc, temp_argv}; + + // Get the current screen geometry. + const QScreen* primary_screen = QGuiApplication::primaryScreen(); + if (primary_screen == nullptr) { + return; + } + + const QRect screen_rect = primary_screen->geometry(); + const int real_width = screen_rect.width(); + const int real_height = screen_rect.height(); + const float real_ratio = primary_screen->logicalDotsPerInch() / 96.0f; + + // Recommended minimum width and height for proper window fit. + // Any screen with a lower resolution than this will still have a scale of 1. + constexpr float minimum_width = 1350.0f; + constexpr float minimum_height = 900.0f; + + const float width_ratio = std::max(1.0f, real_width / minimum_width); + const float height_ratio = std::max(1.0f, real_height / minimum_height); + + // Get the lower of the 2 ratios and truncate, this is the maximum integer scale. + const float max_ratio = std::trunc(std::min(width_ratio, height_ratio)); + + if (max_ratio > real_ratio) { + QApplication::setHighDpiScaleFactorRoundingPolicy( + Qt::HighDpiScaleFactorRoundingPolicy::Round); + } else { + QApplication::setHighDpiScaleFactorRoundingPolicy( + Qt::HighDpiScaleFactorRoundingPolicy::Floor); + } +#else + // Other OSes should be better than Windows at fractional scaling. + QApplication::setHighDpiScaleFactorRoundingPolicy( + Qt::HighDpiScaleFactorRoundingPolicy::PassThrough); +#endif + + QApplication::setAttribute(Qt::AA_EnableHighDpiScaling); + QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); +} + +int main(int argc, char* argv[]) { + std::unique_ptr config = std::make_unique(); + UISettings::RestoreWindowState(config); + bool has_broken_vulkan = false; + bool is_child = false; + if (CheckEnvVars(&is_child)) { + return 0; + } + + if (StartupChecks(argv[0], &has_broken_vulkan, + Settings::values.perform_vulkan_check.GetValue())) { + return 0; + } + +#ifdef SUDACHI_CRASH_DUMPS + Breakpad::InstallCrashHandler(); +#endif + + Common::DetachedTasks detached_tasks; + MicroProfileOnThreadCreate("Frontend"); + SCOPE_EXIT { + MicroProfileShutdown(); + }; + + Common::ConfigureNvidiaEnvironmentFlags(); + + // Init settings params + QCoreApplication::setOrganizationName(QStringLiteral("sudachi team")); + QCoreApplication::setApplicationName(QStringLiteral("sudachi")); + +#ifdef _WIN32 + // Increases the maximum open file limit to 8192 + _setmaxstdio(8192); +#endif + +#ifdef __APPLE__ + // If you start a bundle (binary) on OSX without the Terminal, the working directory is "/". + // But since we require the working directory to be the executable path for the location of + // the user folder in the Qt Frontend, we need to cd into that working directory + const auto bin_path = Common::FS::GetBundleDirectory() / ".."; + chdir(Common::FS::PathToUTF8String(bin_path).c_str()); +#endif + +#ifdef __linux__ + // Set the DISPLAY variable in order to open web browsers + // TODO (lat9nq): Find a better solution for AppImages to start external applications + if (QString::fromLocal8Bit(qgetenv("DISPLAY")).isEmpty()) { + qputenv("DISPLAY", ":0"); + } + + // Fix the Wayland appId. This needs to match the name of the .desktop file without the .desktop + // suffix. + QGuiApplication::setDesktopFileName(QStringLiteral("org.sudachi_emu.sudachi")); +#endif + + SetHighDPIAttributes(); + +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) + // Disables the "?" button on all dialogs. Disabled by default on Qt6. + QCoreApplication::setAttribute(Qt::AA_DisableWindowContextHelpButton); +#endif + + // Enables the core to make the qt created contexts current on std::threads + QCoreApplication::setAttribute(Qt::AA_DontCheckOpenGLContextThreadAffinity); + + QApplication app(argc, argv); + +#ifdef _WIN32 + OverrideWindowsFont(); +#endif + + // Workaround for QTBUG-85409, for Suzhou numerals the number 1 is actually \u3021 + // so we can see if we get \u3008 instead + // TL;DR all other number formats are consecutive in unicode code points + // This bug is fixed in Qt6, specifically 6.0.0-alpha1 +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) + const QLocale locale = QLocale::system(); + if (QStringLiteral("\u3008") == locale.toString(1)) { + QLocale::setDefault(QLocale::system().name()); + } +#endif + + // Qt changes the locale and causes issues in float conversion using std::to_string() when + // generating shaders + setlocale(LC_ALL, "C"); + + GMainWindow main_window{std::move(config), has_broken_vulkan}; + // After settings have been loaded by GMainWindow, apply the filter + main_window.show(); + + QObject::connect(&app, &QGuiApplication::applicationStateChanged, &main_window, + &GMainWindow::OnAppFocusStateChanged); + + int result = app.exec(); + detached_tasks.WaitForAllTasks(); + return result; +} \ No newline at end of file diff --git a/src/sudachi/main.h b/src/sudachi/main.h new file mode 100644 index 0000000..be14ae8 --- /dev/null +++ b/src/sudachi/main.h @@ -0,0 +1,580 @@ +// SPDX-FileCopyrightText: 2014 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "common/announce_multiplayer_room.h" +#include "common/common_types.h" +#include "configuration/qt_config.h" +#include "frontend_common/content_manager.h" +#include "input_common/drivers/tas_input.h" +#include "sudachi/compatibility_list.h" +#include "sudachi/hotkeys.h" +#include "sudachi/util/controller_navigation.h" + +#ifdef __unix__ +#include +#include +#include +#endif + +class QtConfig; +class ClickableLabel; +class EmuThread; +class GameList; +class GImageInfo; +class GRenderWindow; +class LoadingScreen; +class MicroProfileDialog; +class OverlayDialog; +class ProfilerWidget; +class ControllerDialog; +class QLabel; +class MultiplayerState; +class QPushButton; +class QProgressDialog; +class QSlider; +class QHBoxLayout; +class WaitTreeWidget; +enum class GameListOpenTarget; +enum class GameListRemoveTarget; +enum class GameListShortcutTarget; +enum class DumpRomFSTarget; +enum class InstalledEntryType; +class GameListPlaceholder; + +class QtAmiiboSettingsDialog; +class QtControllerSelectorDialog; +class QtProfileSelectionDialog; +class QtSoftwareKeyboardDialog; +class QtNXWebEngineView; + +enum class StartGameType { + Normal, // Can use custom configuration + Global, // Only uses global configuration +}; + +namespace Core { +enum class SystemResultStatus : u32; +class System; +} // namespace Core + +namespace Core::Frontend { +struct CabinetParameters; +struct ControllerParameters; +struct InlineAppearParameters; +struct InlineTextParameters; +struct KeyboardInitializeParameters; +struct ProfileSelectParameters; +} // namespace Core::Frontend + +namespace DiscordRPC { +class DiscordInterface; +} + +namespace PlayTime { +class PlayTimeManager; +} + +namespace FileSys { +class ContentProvider; +class ManualContentProvider; +class VfsFilesystem; +} // namespace FileSys + +namespace InputCommon { +class InputSubsystem; +} + +namespace Service::AM { +struct FrontendAppletParameters; +enum class AppletId : u32; +} // namespace Service::AM + +namespace Service::AM::Frontend { +enum class SwkbdResult : u32; +enum class SwkbdTextCheckResult : u32; +enum class SwkbdReplyType : u32; +enum class WebExitReason : u32; +} // namespace Service::AM::Frontend + +namespace Service::NFC { +class NfcDevice; +} // namespace Service::NFC + +namespace Service::NFP { +enum class CabinetMode : u8; +} // namespace Service::NFP + +namespace Ui { +class MainWindow; +} + +enum class EmulatedDirectoryTarget { + NAND, + SDMC, +}; + +namespace VkDeviceInfo { +class Record; +} + +class VolumeButton : public QPushButton { + Q_OBJECT +public: + explicit VolumeButton(QWidget* parent = nullptr) : QPushButton(parent), scroll_multiplier(1) { + connect(&scroll_timer, &QTimer::timeout, this, &VolumeButton::ResetMultiplier); + } + +signals: + void VolumeChanged(); + +protected: + void wheelEvent(QWheelEvent* event) override; + +private slots: + void ResetMultiplier(); + +private: + int scroll_multiplier; + QTimer scroll_timer; + constexpr static int MaxMultiplier = 8; +}; + +class GMainWindow : public QMainWindow { + Q_OBJECT + + /// Max number of recently loaded items to keep track of + static const int max_recent_files_item = 10; + + enum { + CREATE_SHORTCUT_MSGBOX_FULLSCREEN_YES, + CREATE_SHORTCUT_MSGBOX_SUCCESS, + CREATE_SHORTCUT_MSGBOX_ERROR, + CREATE_SHORTCUT_MSGBOX_APPVOLATILE_WARNING, + }; + +public: + void filterBarSetChecked(bool state); + void UpdateUITheme(); + explicit GMainWindow(std::unique_ptr config_, bool has_broken_vulkan); + ~GMainWindow() override; + + bool DropAction(QDropEvent* event); + void AcceptDropEvent(QDropEvent* event); + +signals: + + /** + * Signal that is emitted when a new EmuThread has been created and an emulation session is + * about to start. At this time, the core system emulation has been initialized, and all + * emulation handles and memory should be valid. + * + * @param emu_thread Pointer to the newly created EmuThread (to be used by widgets that need to + * access/change emulation state). + */ + void EmulationStarting(EmuThread* emu_thread); + + /** + * Signal that is emitted when emulation is about to stop. At this time, the EmuThread and core + * system emulation handles and memory are still valid, but are about become invalid. + */ + void EmulationStopping(); + + // Signal that tells widgets to update icons to use the current theme + void UpdateThemedIcons(); + + void UpdateInstallProgress(); + + void AmiiboSettingsFinished(bool is_success, const std::string& name); + + void ControllerSelectorReconfigureFinished(bool is_success); + + void ErrorDisplayFinished(); + + void ProfileSelectorFinishedSelection(std::optional uuid); + + void SoftwareKeyboardSubmitNormalText(Service::AM::Frontend::SwkbdResult result, + std::u16string submitted_text, bool confirmed); + void SoftwareKeyboardSubmitInlineText(Service::AM::Frontend::SwkbdReplyType reply_type, + std::u16string submitted_text, s32 cursor_position); + + void WebBrowserExtractOfflineRomFS(); + void WebBrowserClosed(Service::AM::Frontend::WebExitReason exit_reason, std::string last_url); + + void SigInterrupt(); + +public slots: + void OnLoadComplete(); + void OnExecuteProgram(std::size_t program_index); + void OnExit(); + void OnSaveConfig(); + void AmiiboSettingsShowDialog(const Core::Frontend::CabinetParameters& parameters, + std::shared_ptr nfp_device); + void AmiiboSettingsRequestExit(); + void ControllerSelectorReconfigureControllers( + const Core::Frontend::ControllerParameters& parameters); + void ControllerSelectorRequestExit(); + void SoftwareKeyboardInitialize( + bool is_inline, Core::Frontend::KeyboardInitializeParameters initialize_parameters); + void SoftwareKeyboardShowNormal(); + void SoftwareKeyboardShowTextCheck( + Service::AM::Frontend::SwkbdTextCheckResult text_check_result, + std::u16string text_check_message); + void SoftwareKeyboardShowInline(Core::Frontend::InlineAppearParameters appear_parameters); + void SoftwareKeyboardHideInline(); + void SoftwareKeyboardInlineTextChanged(Core::Frontend::InlineTextParameters text_parameters); + void SoftwareKeyboardExit(); + void ErrorDisplayDisplayError(QString error_code, QString error_text); + void ErrorDisplayRequestExit(); + void ProfileSelectorSelectProfile(const Core::Frontend::ProfileSelectParameters& parameters); + void ProfileSelectorRequestExit(); + void WebBrowserOpenWebPage(const std::string& main_url, const std::string& additional_args, + bool is_local); + void WebBrowserRequestExit(); + void OnAppFocusStateChanged(Qt::ApplicationState state); + void OnTasStateChanged(); + +private: + /// Updates an action's shortcut and text to reflect an updated hotkey from the hotkey registry. + void LinkActionShortcut(QAction* action, const QString& action_name, + const bool tas_allowed = false); + + void RegisterMetaTypes(); + + void InitializeWidgets(); + void InitializeDebugWidgets(); + void InitializeRecentFileMenuActions(); + + void SetDefaultUIGeometry(); + void RestoreUIState(); + + void ConnectWidgetEvents(); + void ConnectMenuEvents(); + void UpdateMenuState(); + + void SetupPrepareForSleep(); + + void PreventOSSleep(); + void AllowOSSleep(); + + bool LoadROM(const QString& filename, Service::AM::FrontendAppletParameters params); + void BootGame(const QString& filename, Service::AM::FrontendAppletParameters params, + StartGameType with_config = StartGameType::Normal); + void BootGameFromList(const QString& filename, StartGameType with_config); + void ShutdownGame(); + + void ShowTelemetryCallout(); + void SetDiscordEnabled(bool state); + void LoadAmiibo(const QString& filename); + + bool SelectAndSetCurrentUser(const Core::Frontend::ProfileSelectParameters& parameters); + + /** + * Stores the filename in the recently loaded files list. + * The new filename is stored at the beginning of the recently loaded files list. + * After inserting the new entry, duplicates are removed meaning that if + * this was inserted from \a OnMenuRecentFile(), the entry will be put on top + * and remove from its previous position. + * + * Finally, this function calls \a UpdateRecentFiles() to update the UI. + * + * @param filename the filename to store + */ + void StoreRecentFile(const QString& filename); + + /** + * Updates the recent files menu. + * Menu entries are rebuilt from the configuration file. + * If there is no entry in the menu, the menu is greyed out. + */ + void UpdateRecentFiles(); + + /** + * If the emulation is running, + * asks the user if he really want to close the emulator + * + * @return true if the user confirmed + */ + bool ConfirmClose(); + bool ConfirmChangeGame(); + bool ConfirmForceLockedExit(); + void RequestGameExit(); + void changeEvent(QEvent* event) override; + void closeEvent(QCloseEvent* event) override; + + std::string CreateTASFramesString( + std::array frames) const; + +#ifdef __unix__ + void SetupSigInterrupts(); + static void HandleSigInterrupt(int); + void OnSigInterruptNotifierActivated(); + void SetGamemodeEnabled(bool state); +#endif + + Service::AM::FrontendAppletParameters ApplicationAppletParameters(); + Service::AM::FrontendAppletParameters LibraryAppletParameters(u64 program_id, + Service::AM::AppletId applet_id); + +private slots: + void OnStartGame(); + void OnRestartGame(); + void OnPauseGame(); + void OnPauseContinueGame(); + void OnStopGame(); + void OnPrepareForSleep(bool prepare_sleep); + void OnMenuReportCompatibility(); + void OnOpenModsPage(); + void OnOpenQuickstartGuide(); + void OnOpenFAQ(); + /// Called whenever a user selects a game in the game list widget. + void OnGameListLoadFile(QString game_path, u64 program_id); + void OnGameListOpenFolder(u64 program_id, GameListOpenTarget target, + const std::string& game_path); + void OnTransferableShaderCacheOpenFile(u64 program_id); + void OnGameListRemoveInstalledEntry(u64 program_id, InstalledEntryType type); + void OnGameListRemoveFile(u64 program_id, GameListRemoveTarget target, + const std::string& game_path); + void OnGameListRemovePlayTimeData(u64 program_id); + void OnGameListDumpRomFS(u64 program_id, const std::string& game_path, DumpRomFSTarget target); + void OnGameListVerifyIntegrity(const std::string& game_path); + void OnGameListCopyTID(u64 program_id); + void OnGameListNavigateToGamedbEntry(u64 program_id, + const CompatibilityList& compatibility_list); + void OnGameListCreateShortcut(u64 program_id, const std::string& game_path, + GameListShortcutTarget target); + void OnGameListOpenDirectory(const QString& directory); + void OnGameListAddDirectory(); + void OnGameListShowList(bool show); + void OnGameListOpenPerGameProperties(const std::string& file); + void OnMenuLoadFile(); + void OnMenuLoadFolder(); + void IncrementInstallProgress(); + void OnMenuInstallToNAND(); + void OnMenuRecentFile(); + void OnConfigure(); + void OnConfigureTas(); + void OnDecreaseVolume(); + void OnIncreaseVolume(); + void OnMute(); + void OnTasStartStop(); + void OnTasRecord(); + void OnTasReset(); + void OnToggleGraphicsAPI(); + void OnToggleDockedMode(); + void OnToggleGpuAccuracy(); + void OnToggleAdaptingFilter(); + void OnConfigurePerGame(); + void OnLoadAmiibo(); + void OnOpenSudachiFolder(); + void OnVerifyInstalledContents(); + void OnInstallFirmware(); + void OnInstallDecryptionKeys(); + void OnAbout(); + void OnToggleFilterBar(); + void OnToggleStatusBar(); + void OnDisplayTitleBars(bool); + void InitializeHotkeys(); + void ToggleFullscreen(); + bool UsingExclusiveFullscreen(); + void ShowFullscreen(); + void HideFullscreen(); + void ToggleWindowMode(); + void ResetWindowSize(u32 width, u32 height); + void ResetWindowSize720(); + void ResetWindowSize900(); + void ResetWindowSize1080(); + void OnAlbum(); + void OnCabinet(Service::NFP::CabinetMode mode); + void OnMiiEdit(); + void OnOpenControllerMenu(); + void OnCaptureScreenshot(); + void OnCheckFirmwareDecryption(); + void OnLanguageChanged(const QString& locale); + void OnMouseActivity(); + bool OnShutdownBegin(); + void OnShutdownBeginDialog(); + void OnEmulationStopped(); + void OnEmulationStopTimeExpired(); + +private: + QString GetGameListErrorRemoving(InstalledEntryType type) const; + void RemoveBaseContent(u64 program_id, InstalledEntryType type); + void RemoveUpdateContent(u64 program_id, InstalledEntryType type); + void RemoveAddOnContent(u64 program_id, InstalledEntryType type); + void RemoveTransferableShaderCache(u64 program_id, GameListRemoveTarget target); + void RemoveVulkanDriverPipelineCache(u64 program_id); + void RemoveAllTransferableShaderCaches(u64 program_id); + void RemoveCustomConfiguration(u64 program_id, const std::string& game_path); + void RemovePlayTimeData(u64 program_id); + void RemoveCacheStorage(u64 program_id); + bool SelectRomFSDumpTarget(const FileSys::ContentProvider&, u64 program_id, + u64* selected_title_id, u8* selected_content_record_type); + ContentManager::InstallResult InstallNCA(const QString& filename); + void MigrateConfigFiles(); + void UpdateWindowTitle(std::string_view title_name = {}, std::string_view title_version = {}, + std::string_view gpu_vendor = {}); + void UpdateDockedButton(); + void UpdateAPIText(); + void UpdateFilterText(); + void UpdateAAText(); + void UpdateVolumeUI(); + void UpdateStatusBar(); + void UpdateGPUAccuracyButton(); + void UpdateStatusButtons(); + void UpdateUISettings(); + void UpdateInputDrivers(); + void HideMouseCursor(); + void ShowMouseCursor(); + void OpenURL(const QUrl& url); + void LoadTranslation(); + void OpenPerGameConfiguration(u64 title_id, const std::string& file_name); + bool CheckDarkMode(); + bool CheckFirmwarePresence(); + void SetFirmwareVersion(); + void ConfigureFilesystemProvider(const std::string& filepath); + /** + * Open (or not) the right confirm dialog based on current setting and game exit lock + * @returns true if the player confirmed or the settings do no require it + */ + bool ConfirmShutdownGame(); + + QString GetTasStateDescription() const; + bool CreateShortcutMessagesGUI(QWidget* parent, int imsg, const QString& game_title); + bool MakeShortcutIcoPath(const u64 program_id, const std::string_view game_file_name, + std::filesystem::path& out_icon_path); + bool CreateShortcutLink(const std::filesystem::path& shortcut_path, const std::string& comment, + const std::filesystem::path& icon_path, + const std::filesystem::path& command, const std::string& arguments, + const std::string& categories, const std::string& keywords, + const std::string& name); + /** + * Mimic the behavior of QMessageBox::question but link controller navigation to the dialog + * The only difference is that it returns a boolean. + * + * @returns true if buttons contains QMessageBox::Yes and the user clicks on the "Yes" button. + */ + bool question(QWidget* parent, const QString& title, const QString& text, + QMessageBox::StandardButtons buttons = + QMessageBox::StandardButtons(QMessageBox::Yes | QMessageBox::No), + QMessageBox::StandardButton defaultButton = QMessageBox::NoButton); + + std::unique_ptr ui; + + std::unique_ptr system; + std::unique_ptr discord_rpc; + std::unique_ptr play_time_manager; + std::shared_ptr input_subsystem; + + MultiplayerState* multiplayer_state = nullptr; + + GRenderWindow* render_window; + GameList* game_list; + LoadingScreen* loading_screen; + QTimer shutdown_timer; + OverlayDialog* shutdown_dialog{}; + + GameListPlaceholder* game_list_placeholder; + + std::vector vk_device_records; + + // Status bar elements + QLabel* message_label = nullptr; + QLabel* shader_building_label = nullptr; + QLabel* res_scale_label = nullptr; + QLabel* emu_speed_label = nullptr; + QLabel* game_fps_label = nullptr; + QLabel* emu_frametime_label = nullptr; + QLabel* tas_label = nullptr; + QLabel* firmware_label = nullptr; + QPushButton* gpu_accuracy_button = nullptr; + QPushButton* renderer_status_button = nullptr; + QPushButton* dock_status_button = nullptr; + QPushButton* filter_status_button = nullptr; + QPushButton* aa_status_button = nullptr; + VolumeButton* volume_button = nullptr; + QWidget* volume_popup = nullptr; + QSlider* volume_slider = nullptr; + QTimer status_bar_update_timer; + + std::unique_ptr config; + + // Whether emulation is currently running in sudachi. + bool emulation_running = false; + std::unique_ptr emu_thread; + // The path to the game currently running + QString current_game_path; + // Whether a user was set on the command line (skips UserSelector if it's forced to show up) + bool user_flag_cmd_line = false; + + bool auto_paused = false; + bool auto_muted = false; + QTimer mouse_hide_timer; + QTimer update_input_timer; + + QString startup_icon_theme; + bool os_dark_mode = false; + + // FS + std::shared_ptr vfs; + std::unique_ptr provider; + + // Debugger panes + ProfilerWidget* profilerWidget; + MicroProfileDialog* microProfileDialog; + WaitTreeWidget* waitTreeWidget; + ControllerDialog* controller_dialog; + + QAction* actions_recent_files[max_recent_files_item]; + + // stores default icon theme search paths for the platform + QStringList default_theme_paths; + + HotkeyRegistry hotkey_registry; + + QTranslator translator; + + // Install progress dialog + QProgressDialog* install_progress; + + // Last game booted, used for multi-process apps + QString last_filename_booted; + + // Applets + QtAmiiboSettingsDialog* cabinet_applet = nullptr; + QtControllerSelectorDialog* controller_applet = nullptr; + QtProfileSelectionDialog* profile_select_applet = nullptr; + QDialog* error_applet = nullptr; + QtSoftwareKeyboardDialog* software_keyboard = nullptr; + QtNXWebEngineView* web_applet = nullptr; + + // True if amiibo file select is visible + bool is_amiibo_file_select_active{}; + + // True if load file select is visible + bool is_load_file_select_active{}; + + // True if TAS recording dialog is visible + bool is_tas_recording_dialog_active{}; + +#ifdef __unix__ + QSocketNotifier* sig_interrupt_notifier; + static std::array sig_interrupt_fds; +#endif + +protected: + void dropEvent(QDropEvent* event) override; + void dragEnterEvent(QDragEnterEvent* event) override; + void dragMoveEvent(QDragMoveEvent* event) override; +}; diff --git a/src/sudachi/main.ui b/src/sudachi/main.ui new file mode 100644 index 0000000..820ef8f --- /dev/null +++ b/src/sudachi/main.ui @@ -0,0 +1,483 @@ + + + MainWindow + + + + 0 + 0 + 1280 + 720 + + + + sudachi + + + + :/img/sudachi.ico:/img/sudachi.ico + + + QTabWidget::Rounded + + + true + + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + + 0 + 0 + 1280 + 21 + + + + + &File + + + + &Recent Files + + + + + + + + + + + + + + + + + + &Emulation + + + + + + + + + + + &View + + + + &Reset Window Size + + + + + &Debugging + + + + + Reset Window Size to &720p + + + Reset Window Size to 720p + + + + + Reset Window Size to &900p + + + Reset Window Size to 900p + + + + + Reset Window Size to &1080p + + + Reset Window Size to 1080p + + + + + + + + + + + + + + true + + + &Multiplayer + + + + + + + + + + + &Tools + + + + &Amiibo + + + + + + + + + &TAS + + + + + + + + + + + + + + + + + + + + + + &Help + + + + + + + + + + + + + + + + + + true + + + &Install Files to NAND... + + + + + L&oad File... + + + + + Load &Folder... + + + + + E&xit + + + + + false + + + &Pause + + + + + false + + + &Stop + + + + + &Verify Installed Contents + + + + + &About sudachi + + + + + true + + + Single &Window Mode + + + + + Con&figure... + + + QAction::PreferencesRole + + + + + true + + + Display D&ock Widget Headers + + + + + true + + + Show &Filter Bar + + + + + true + + + Show &Status Bar + + + Show Status Bar + + + + + true + + + &Browse Public Game Lobby + + + + + true + + + &Create Room + + + + + false + + + &Leave Room + + + + + &Direct Connect to Room + + + + + false + + + &Show Current Room + + + + + true + + + F&ullscreen + + + + + false + + + &Restart + + + + + false + + + Load/Remove &Amiibo... + + + + + false + + + &Report Compatibility + + + false + + + + + Open &Mods Page + + + + + Open &Quickstart Guide + + + + + &FAQ + + + + + Open &sudachi Folder + + + + + false + + + &Capture Screenshot + + + + + Open &Album + + + + + &Set Nickname and Owner + + + + + &Delete Game Data + + + + + &Restore Amiibo + + + + + &Format Amiibo + + + + + Open &Mii Editor + + + + + &Configure TAS... + + + QAction::NoRole + + + + + false + + + Configure C&urrent Game... + + + QAction::NoRole + + + + + false + + + &Start + + + + + false + + + &Reset + + + + + false + + + R&ecord + + + + + Open &Controller Menu + + + + + Install Firmware + + + + + Install Decryption Keys + + + + + + + + diff --git a/src/sudachi/mini_dump.cpp b/src/sudachi/mini_dump.cpp new file mode 100644 index 0000000..d06712e --- /dev/null +++ b/src/sudachi/mini_dump.cpp @@ -0,0 +1,202 @@ +// SPDX-FileCopyrightText: 2022 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include +#include +#include +#include +#include +#include "sudachi/mini_dump.h" +#include "sudachi/startup_checks.h" + +// dbghelp.h must be included after windows.h +#include + +namespace MiniDump { + +void CreateMiniDump(HANDLE process_handle, DWORD process_id, MINIDUMP_EXCEPTION_INFORMATION* info, + EXCEPTION_POINTERS* pep) { + char file_name[255]; + const std::time_t the_time = std::time(nullptr); + std::strftime(file_name, 255, "sudachi-crash-%Y%m%d%H%M%S.dmp", std::localtime(&the_time)); + + // Open the file + HANDLE file_handle = CreateFileA(file_name, GENERIC_READ | GENERIC_WRITE, 0, nullptr, + CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + + if (file_handle == nullptr || file_handle == INVALID_HANDLE_VALUE) { + fmt::print(stderr, "CreateFileA failed. Error: {}", GetLastError()); + return; + } + + // Create the minidump + const MINIDUMP_TYPE dump_type = MiniDumpNormal; + + const bool write_dump_status = MiniDumpWriteDump(process_handle, process_id, file_handle, + dump_type, (pep != 0) ? info : 0, 0, 0); + + if (write_dump_status) { + fmt::print(stderr, "MiniDump created: {}", file_name); + } else { + fmt::print(stderr, "MiniDumpWriteDump failed. Error: {}", GetLastError()); + } + + // Close the file + CloseHandle(file_handle); +} + +void DumpFromDebugEvent(DEBUG_EVENT& deb_ev, PROCESS_INFORMATION& pi) { + EXCEPTION_RECORD& record = deb_ev.u.Exception.ExceptionRecord; + + HANDLE thread_handle = OpenThread(THREAD_GET_CONTEXT, false, deb_ev.dwThreadId); + if (thread_handle == nullptr) { + fmt::print(stderr, "OpenThread failed ({})", GetLastError()); + return; + } + + // Get child process context + CONTEXT context = {}; + context.ContextFlags = CONTEXT_ALL; + if (!GetThreadContext(thread_handle, &context)) { + fmt::print(stderr, "GetThreadContext failed ({})", GetLastError()); + return; + } + + // Create exception pointers for minidump + EXCEPTION_POINTERS ep; + ep.ExceptionRecord = &record; + ep.ContextRecord = &context; + + MINIDUMP_EXCEPTION_INFORMATION info; + info.ThreadId = deb_ev.dwThreadId; + info.ExceptionPointers = &ep; + info.ClientPointers = false; + + CreateMiniDump(pi.hProcess, pi.dwProcessId, &info, &ep); + + if (CloseHandle(thread_handle) == 0) { + fmt::print(stderr, "error: CloseHandle(thread_handle) failed ({})", GetLastError()); + } +} + +bool SpawnDebuggee(const char* arg0, PROCESS_INFORMATION& pi) { + std::memset(&pi, 0, sizeof(pi)); + + // Don't debug if we are already being debugged + if (IsDebuggerPresent()) { + return false; + } + + if (!SpawnChild(arg0, &pi, 0)) { + fmt::print(stderr, "warning: continuing without crash dumps"); + return false; + } + + const bool can_debug = DebugActiveProcess(pi.dwProcessId); + if (!can_debug) { + fmt::print(stderr, + "warning: DebugActiveProcess failed ({}), continuing without crash dumps", + GetLastError()); + return false; + } + + return true; +} + +static const char* ExceptionName(DWORD exception) { + switch (exception) { + case EXCEPTION_ACCESS_VIOLATION: + return "EXCEPTION_ACCESS_VIOLATION"; + case EXCEPTION_DATATYPE_MISALIGNMENT: + return "EXCEPTION_DATATYPE_MISALIGNMENT"; + case EXCEPTION_BREAKPOINT: + return "EXCEPTION_BREAKPOINT"; + case EXCEPTION_SINGLE_STEP: + return "EXCEPTION_SINGLE_STEP"; + case EXCEPTION_ARRAY_BOUNDS_EXCEEDED: + return "EXCEPTION_ARRAY_BOUNDS_EXCEEDED"; + case EXCEPTION_FLT_DENORMAL_OPERAND: + return "EXCEPTION_FLT_DENORMAL_OPERAND"; + case EXCEPTION_FLT_DIVIDE_BY_ZERO: + return "EXCEPTION_FLT_DIVIDE_BY_ZERO"; + case EXCEPTION_FLT_INEXACT_RESULT: + return "EXCEPTION_FLT_INEXACT_RESULT"; + case EXCEPTION_FLT_INVALID_OPERATION: + return "EXCEPTION_FLT_INVALID_OPERATION"; + case EXCEPTION_FLT_OVERFLOW: + return "EXCEPTION_FLT_OVERFLOW"; + case EXCEPTION_FLT_STACK_CHECK: + return "EXCEPTION_FLT_STACK_CHECK"; + case EXCEPTION_FLT_UNDERFLOW: + return "EXCEPTION_FLT_UNDERFLOW"; + case EXCEPTION_INT_DIVIDE_BY_ZERO: + return "EXCEPTION_INT_DIVIDE_BY_ZERO"; + case EXCEPTION_INT_OVERFLOW: + return "EXCEPTION_INT_OVERFLOW"; + case EXCEPTION_PRIV_INSTRUCTION: + return "EXCEPTION_PRIV_INSTRUCTION"; + case EXCEPTION_IN_PAGE_ERROR: + return "EXCEPTION_IN_PAGE_ERROR"; + case EXCEPTION_ILLEGAL_INSTRUCTION: + return "EXCEPTION_ILLEGAL_INSTRUCTION"; + case EXCEPTION_NONCONTINUABLE_EXCEPTION: + return "EXCEPTION_NONCONTINUABLE_EXCEPTION"; + case EXCEPTION_STACK_OVERFLOW: + return "EXCEPTION_STACK_OVERFLOW"; + case EXCEPTION_INVALID_DISPOSITION: + return "EXCEPTION_INVALID_DISPOSITION"; + case EXCEPTION_GUARD_PAGE: + return "EXCEPTION_GUARD_PAGE"; + case EXCEPTION_INVALID_HANDLE: + return "EXCEPTION_INVALID_HANDLE"; + default: + return "unknown exception type"; + } +} + +void DebugDebuggee(PROCESS_INFORMATION& pi) { + DEBUG_EVENT deb_ev = {}; + + while (deb_ev.dwDebugEventCode != EXIT_PROCESS_DEBUG_EVENT) { + const bool wait_success = WaitForDebugEvent(&deb_ev, INFINITE); + if (!wait_success) { + fmt::print(stderr, "error: WaitForDebugEvent failed ({})", GetLastError()); + return; + } + + switch (deb_ev.dwDebugEventCode) { + case OUTPUT_DEBUG_STRING_EVENT: + case CREATE_PROCESS_DEBUG_EVENT: + case CREATE_THREAD_DEBUG_EVENT: + case EXIT_PROCESS_DEBUG_EVENT: + case EXIT_THREAD_DEBUG_EVENT: + case LOAD_DLL_DEBUG_EVENT: + case RIP_EVENT: + case UNLOAD_DLL_DEBUG_EVENT: + // Continue on all other debug events + ContinueDebugEvent(deb_ev.dwProcessId, deb_ev.dwThreadId, DBG_CONTINUE); + break; + case EXCEPTION_DEBUG_EVENT: + EXCEPTION_RECORD& record = deb_ev.u.Exception.ExceptionRecord; + + // We want to generate a crash dump if we are seeing the same exception again. + if (!deb_ev.u.Exception.dwFirstChance) { + fmt::print(stderr, "Creating MiniDump on ExceptionCode: 0x{:08x} {}\n", + record.ExceptionCode, ExceptionName(record.ExceptionCode)); + DumpFromDebugEvent(deb_ev, pi); + } + + // Continue without handling the exception. + // Lets the debuggee use its own exception handler. + // - If one does not exist, we will see the exception once more where we make a minidump + // for. Then when it reaches here again, sudachi will probably crash. + // - DBG_CONTINUE on an exception that the debuggee does not handle can set us up for an + // infinite loop of exceptions. + ContinueDebugEvent(deb_ev.dwProcessId, deb_ev.dwThreadId, DBG_EXCEPTION_NOT_HANDLED); + break; + } + } +} + +} // namespace MiniDump diff --git a/src/sudachi/mini_dump.h b/src/sudachi/mini_dump.h new file mode 100644 index 0000000..48f2b29 --- /dev/null +++ b/src/sudachi/mini_dump.h @@ -0,0 +1,19 @@ +// SPDX-FileCopyrightText: 2022 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include + +#include + +namespace MiniDump { + +void CreateMiniDump(HANDLE process_handle, DWORD process_id, MINIDUMP_EXCEPTION_INFORMATION* info, + EXCEPTION_POINTERS* pep); + +void DumpFromDebugEvent(DEBUG_EVENT& deb_ev, PROCESS_INFORMATION& pi); +bool SpawnDebuggee(const char* arg0, PROCESS_INFORMATION& pi); +void DebugDebuggee(PROCESS_INFORMATION& pi); + +} // namespace MiniDump diff --git a/src/sudachi/multiplayer/chat_room.cpp b/src/sudachi/multiplayer/chat_room.cpp new file mode 100644 index 0000000..852b3fe --- /dev/null +++ b/src/sudachi/multiplayer/chat_room.cpp @@ -0,0 +1,508 @@ +// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "common/logging/log.h" +#include "network/announce_multiplayer_session.h" +#include "ui_chat_room.h" +#include "sudachi/game_list_p.h" +#include "sudachi/multiplayer/chat_room.h" +#include "sudachi/multiplayer/message.h" +#ifdef ENABLE_WEB_SERVICE +#include "web_service/web_backend.h" +#endif + +class ChatMessage { +public: + explicit ChatMessage(const Network::ChatEntry& chat, Network::RoomNetwork& room_network, + QTime ts = {}) { + /// Convert the time to their default locale defined format + QLocale locale; + timestamp = locale.toString(ts.isValid() ? ts : QTime::currentTime(), QLocale::ShortFormat); + nickname = QString::fromStdString(chat.nickname); + username = QString::fromStdString(chat.username); + message = QString::fromStdString(chat.message); + + // Check for user pings + QString cur_nickname, cur_username; + if (auto room = room_network.GetRoomMember().lock()) { + cur_nickname = QString::fromStdString(room->GetNickname()); + cur_username = QString::fromStdString(room->GetUsername()); + } + + // Handle pings at the beginning and end of message + QString fixed_message = QStringLiteral(" %1 ").arg(message); + if (fixed_message.contains(QStringLiteral(" @%1 ").arg(cur_nickname)) || + (!cur_username.isEmpty() && + fixed_message.contains(QStringLiteral(" @%1 ").arg(cur_username)))) { + + contains_ping = true; + } else { + contains_ping = false; + } + } + + bool ContainsPing() const { + return contains_ping; + } + + /// Format the message using the players color + QString GetPlayerChatMessage(u16 player) const { + const bool is_dark_theme = QIcon::themeName().contains(QStringLiteral("dark")) || + QIcon::themeName().contains(QStringLiteral("midnight")); + auto color = + is_dark_theme ? player_color_dark[player % 16] : player_color_default[player % 16]; + QString name; + if (username.isEmpty() || username == nickname) { + name = nickname; + } else { + name = QStringLiteral("%1 (%2)").arg(nickname, username); + } + + QString style, text_color; + if (ContainsPing()) { + // Add a background color to these messages + style = QStringLiteral("background-color: %1").arg(QString::fromStdString(ping_color)); + // Add a font color + text_color = QStringLiteral("color='#000000'"); + } + + return QStringLiteral("[%1] <%3> %6") + .arg(timestamp, QString::fromStdString(color), name.toHtmlEscaped(), style, text_color, + message.toHtmlEscaped()); + } + +private: + static constexpr std::array player_color_default = { + {"#0000FF", "#FF0000", "#8A2BE2", "#FF69B4", "#1E90FF", "#008000", "#00FF7F", "#B22222", + "#DAA520", "#FF4500", "#2E8B57", "#5F9EA0", "#D2691E", "#9ACD32", "#FF7F50", "#FFFF00"}}; + static constexpr std::array player_color_dark = { + {"#559AD1", "#4EC9A8", "#D69D85", "#C6C923", "#B975B5", "#D81F1F", "#7EAE39", "#4F8733", + "#F7CD8A", "#6FCACF", "#CE4897", "#8A2BE2", "#D2691E", "#9ACD32", "#FF7F50", "#152ccd"}}; + static constexpr char ping_color[] = "#FFFF00"; + + QString timestamp; + QString nickname; + QString username; + QString message; + bool contains_ping; +}; + +class StatusMessage { +public: + explicit StatusMessage(const QString& msg, QTime ts = {}) { + /// Convert the time to their default locale defined format + QLocale locale; + timestamp = locale.toString(ts.isValid() ? ts : QTime::currentTime(), QLocale::ShortFormat); + message = msg; + } + + QString GetSystemChatMessage() const { + return QStringLiteral("[%1] * %3") + .arg(timestamp, QString::fromStdString(system_color), message); + } + +private: + static constexpr const char system_color[] = "#FF8C00"; + QString timestamp; + QString message; +}; + +class PlayerListItem : public QStandardItem { +public: + static const int NicknameRole = Qt::UserRole + 1; + static const int UsernameRole = Qt::UserRole + 2; + static const int AvatarUrlRole = Qt::UserRole + 3; + static const int GameNameRole = Qt::UserRole + 4; + static const int GameVersionRole = Qt::UserRole + 5; + + PlayerListItem() = default; + explicit PlayerListItem(const std::string& nickname, const std::string& username, + const std::string& avatar_url, + const AnnounceMultiplayerRoom::GameInfo& game_info) { + setEditable(false); + setData(QString::fromStdString(nickname), NicknameRole); + setData(QString::fromStdString(username), UsernameRole); + setData(QString::fromStdString(avatar_url), AvatarUrlRole); + if (game_info.name.empty()) { + setData(QObject::tr("Not playing a game"), GameNameRole); + } else { + setData(QString::fromStdString(game_info.name), GameNameRole); + } + setData(QString::fromStdString(game_info.version), GameVersionRole); + } + + QVariant data(int role) const override { + if (role != Qt::DisplayRole) { + return QStandardItem::data(role); + } + QString name; + const QString nickname = data(NicknameRole).toString(); + const QString username = data(UsernameRole).toString(); + if (username.isEmpty() || username == nickname) { + name = nickname; + } else { + name = QStringLiteral("%1 (%2)").arg(nickname, username); + } + const QString version = data(GameVersionRole).toString(); + QString version_string; + if (!version.isEmpty()) { + version_string = QStringLiteral("(%1)").arg(version); + } + return QStringLiteral("%1\n %2 %3") + .arg(name, data(GameNameRole).toString(), version_string); + } +}; + +ChatRoom::ChatRoom(QWidget* parent) : QWidget(parent), ui(std::make_unique()) { + ui->setupUi(this); + + // set the item_model for player_view + + player_list = new QStandardItemModel(ui->player_view); + ui->player_view->setModel(player_list); + ui->player_view->setContextMenuPolicy(Qt::CustomContextMenu); + // set a header to make it look better though there is only one column + player_list->insertColumns(0, 1); + player_list->setHeaderData(0, Qt::Horizontal, tr("Members")); + + ui->chat_history->document()->setMaximumBlockCount(max_chat_lines); + + auto font = ui->chat_history->font(); + font.setPointSizeF(10); + ui->chat_history->setFont(font); + + // register the network structs to use in slots and signals + qRegisterMetaType(); + qRegisterMetaType(); + qRegisterMetaType(); + qRegisterMetaType(); + + // Connect all the widgets to the appropriate events + connect(ui->player_view, &QTreeView::customContextMenuRequested, this, + &ChatRoom::PopupContextMenu); + connect(ui->chat_message, &QLineEdit::returnPressed, this, &ChatRoom::OnSendChat); + connect(ui->chat_message, &QLineEdit::textChanged, this, &ChatRoom::OnChatTextChanged); + connect(ui->send_message, &QPushButton::clicked, this, &ChatRoom::OnSendChat); +} + +ChatRoom::~ChatRoom() = default; + +void ChatRoom::Initialize(Network::RoomNetwork* room_network_) { + room_network = room_network_; + // setup the callbacks for network updates + if (auto member = room_network->GetRoomMember().lock()) { + member->BindOnChatMessageReceived( + [this](const Network::ChatEntry& chat) { emit ChatReceived(chat); }); + member->BindOnStatusMessageReceived( + [this](const Network::StatusMessageEntry& status_message) { + emit StatusMessageReceived(status_message); + }); + connect(this, &ChatRoom::ChatReceived, this, &ChatRoom::OnChatReceive); + connect(this, &ChatRoom::StatusMessageReceived, this, &ChatRoom::OnStatusMessageReceive); + } +} + +void ChatRoom::SetModPerms(bool is_mod) { + has_mod_perms = is_mod; +} + +void ChatRoom::RetranslateUi() { + ui->retranslateUi(this); +} + +void ChatRoom::Clear() { + ui->chat_history->clear(); + block_list.clear(); +} + +void ChatRoom::AppendStatusMessage(const QString& msg) { + ui->chat_history->append(StatusMessage(msg).GetSystemChatMessage()); +} + +void ChatRoom::AppendChatMessage(const QString& msg) { + ui->chat_history->append(msg); +} + +void ChatRoom::SendModerationRequest(Network::RoomMessageTypes type, const std::string& nickname) { + if (auto room = room_network->GetRoomMember().lock()) { + auto members = room->GetMemberInformation(); + auto it = std::find_if(members.begin(), members.end(), + [&nickname](const Network::RoomMember::MemberInformation& member) { + return member.nickname == nickname; + }); + if (it == members.end()) { + NetworkMessage::ErrorManager::ShowError(NetworkMessage::ErrorManager::NO_SUCH_USER); + return; + } + room->SendModerationRequest(type, nickname); + } +} + +bool ChatRoom::ValidateMessage(const std::string& msg) { + return !msg.empty(); +} + +void ChatRoom::OnRoomUpdate(const Network::RoomInformation& info) { + // TODO(B3N30): change title + if (auto room_member = room_network->GetRoomMember().lock()) { + SetPlayerList(room_member->GetMemberInformation()); + } +} + +void ChatRoom::Disable() { + ui->send_message->setDisabled(true); + ui->chat_message->setDisabled(true); +} + +void ChatRoom::Enable() { + ui->send_message->setEnabled(true); + ui->chat_message->setEnabled(true); +} + +void ChatRoom::OnChatReceive(const Network::ChatEntry& chat) { + if (!ValidateMessage(chat.message)) { + return; + } + if (auto room = room_network->GetRoomMember().lock()) { + // get the id of the player + auto members = room->GetMemberInformation(); + auto it = std::find_if(members.begin(), members.end(), + [&chat](const Network::RoomMember::MemberInformation& member) { + return member.nickname == chat.nickname && + member.username == chat.username; + }); + if (it == members.end()) { + LOG_INFO(Network, "Chat message received from unknown player. Ignoring it."); + return; + } + if (block_list.count(chat.nickname)) { + LOG_INFO(Network, "Chat message received from blocked player {}. Ignoring it.", + chat.nickname); + return; + } + auto player = std::distance(members.begin(), it); + ChatMessage m(chat, *room_network); + if (m.ContainsPing()) { + emit UserPinged(); + } + AppendChatMessage(m.GetPlayerChatMessage(player)); + } +} + +void ChatRoom::OnStatusMessageReceive(const Network::StatusMessageEntry& status_message) { + QString name; + if (status_message.username.empty() || status_message.username == status_message.nickname) { + name = QString::fromStdString(status_message.nickname); + } else { + name = QStringLiteral("%1 (%2)").arg(QString::fromStdString(status_message.nickname), + QString::fromStdString(status_message.username)); + } + QString message; + switch (status_message.type) { + case Network::IdMemberJoin: + message = tr("%1 has joined").arg(name); + break; + case Network::IdMemberLeave: + message = tr("%1 has left").arg(name); + break; + case Network::IdMemberKicked: + message = tr("%1 has been kicked").arg(name); + break; + case Network::IdMemberBanned: + message = tr("%1 has been banned").arg(name); + break; + case Network::IdAddressUnbanned: + message = tr("%1 has been unbanned").arg(name); + break; + } + if (!message.isEmpty()) + AppendStatusMessage(message); +} + +void ChatRoom::OnSendChat() { + if (auto room_member = room_network->GetRoomMember().lock()) { + if (!room_member->IsConnected()) { + return; + } + auto message = ui->chat_message->text().toStdString(); + if (!ValidateMessage(message)) { + return; + } + auto nick = room_member->GetNickname(); + auto username = room_member->GetUsername(); + Network::ChatEntry chat{nick, username, message}; + + auto members = room_member->GetMemberInformation(); + auto it = std::find_if(members.begin(), members.end(), + [&chat](const Network::RoomMember::MemberInformation& member) { + return member.nickname == chat.nickname && + member.username == chat.username; + }); + if (it == members.end()) { + LOG_INFO(Network, "Cannot find self in the player list when sending a message."); + } + auto player = std::distance(members.begin(), it); + ChatMessage m(chat, *room_network); + room_member->SendChatMessage(message); + AppendChatMessage(m.GetPlayerChatMessage(player)); + ui->chat_message->clear(); + } +} + +void ChatRoom::UpdateIconDisplay() { + for (int row = 0; row < player_list->invisibleRootItem()->rowCount(); ++row) { + QStandardItem* item = player_list->invisibleRootItem()->child(row); + const std::string avatar_url = + item->data(PlayerListItem::AvatarUrlRole).toString().toStdString(); + if (icon_cache.count(avatar_url)) { + item->setData(icon_cache.at(avatar_url), Qt::DecorationRole); + } else { + item->setData(QIcon::fromTheme(QStringLiteral("no_avatar")).pixmap(48), + Qt::DecorationRole); + } + } +} + +void ChatRoom::SetPlayerList(const Network::RoomMember::MemberList& member_list) { + // TODO(B3N30): Remember which row is selected + player_list->removeRows(0, player_list->rowCount()); + for (const auto& member : member_list) { + if (member.nickname.empty()) + continue; + QStandardItem* name_item = new PlayerListItem(member.nickname, member.username, + member.avatar_url, member.game_info); + +#ifdef ENABLE_WEB_SERVICE + if (!icon_cache.count(member.avatar_url) && !member.avatar_url.empty()) { + // Start a request to get the member's avatar + const QUrl url(QString::fromStdString(member.avatar_url)); + QFuture future = QtConcurrent::run([url] { + WebService::Client client( + QStringLiteral("%1://%2").arg(url.scheme(), url.host()).toStdString(), "", ""); + auto result = client.GetImage(url.path().toStdString(), true); + if (result.returned_data.empty()) { + LOG_ERROR(WebService, "Failed to get avatar"); + } + return result.returned_data; + }); + auto* future_watcher = new QFutureWatcher(this); + connect(future_watcher, &QFutureWatcher::finished, this, + [this, future_watcher, avatar_url = member.avatar_url] { + const std::string result = future_watcher->result(); + if (result.empty()) + return; + QPixmap pixmap; + if (!pixmap.loadFromData(reinterpret_cast(result.data()), + static_cast(result.size()))) + return; + icon_cache[avatar_url] = + pixmap.scaled(48, 48, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); + // Update all the displayed icons with the new icon_cache + UpdateIconDisplay(); + }); + future_watcher->setFuture(future); + } +#endif + + player_list->invisibleRootItem()->appendRow(name_item); + } + UpdateIconDisplay(); + // TODO(B3N30): Restore row selection +} + +void ChatRoom::OnChatTextChanged() { + if (ui->chat_message->text().length() > static_cast(Network::MaxMessageSize)) + ui->chat_message->setText( + ui->chat_message->text().left(static_cast(Network::MaxMessageSize))); +} + +void ChatRoom::PopupContextMenu(const QPoint& menu_location) { + QModelIndex item = ui->player_view->indexAt(menu_location); + if (!item.isValid()) + return; + + std::string nickname = + player_list->item(item.row())->data(PlayerListItem::NicknameRole).toString().toStdString(); + + QMenu context_menu; + + QString username = player_list->item(item.row())->data(PlayerListItem::UsernameRole).toString(); + if (!username.isEmpty()) { + QAction* view_profile_action = context_menu.addAction(tr("View Profile")); + connect(view_profile_action, &QAction::triggered, [username] { + QDesktopServices::openUrl( + QUrl(QStringLiteral("https://community.citra-emu.org/u/%1").arg(username))); + }); + } + + std::string cur_nickname; + if (auto room = room_network->GetRoomMember().lock()) { + cur_nickname = room->GetNickname(); + } + + if (nickname != cur_nickname) { // You can't block yourself + QAction* block_action = context_menu.addAction(tr("Block Player")); + + block_action->setCheckable(true); + block_action->setChecked(block_list.count(nickname) > 0); + + connect(block_action, &QAction::triggered, [this, nickname] { + if (block_list.count(nickname)) { + block_list.erase(nickname); + } else { + QMessageBox::StandardButton result = QMessageBox::question( + this, tr("Block Player"), + tr("When you block a player, you will no longer receive chat messages from " + "them.

Are you sure you would like to block %1?") + .arg(QString::fromStdString(nickname)), + QMessageBox::Yes | QMessageBox::No); + if (result == QMessageBox::Yes) + block_list.emplace(nickname); + } + }); + } + + if (has_mod_perms && nickname != cur_nickname) { // You can't kick or ban yourself + context_menu.addSeparator(); + + QAction* kick_action = context_menu.addAction(tr("Kick")); + QAction* ban_action = context_menu.addAction(tr("Ban")); + + connect(kick_action, &QAction::triggered, [this, nickname] { + QMessageBox::StandardButton result = + QMessageBox::question(this, tr("Kick Player"), + tr("Are you sure you would like to kick %1?") + .arg(QString::fromStdString(nickname)), + QMessageBox::Yes | QMessageBox::No); + if (result == QMessageBox::Yes) + SendModerationRequest(Network::IdModKick, nickname); + }); + connect(ban_action, &QAction::triggered, [this, nickname] { + QMessageBox::StandardButton result = QMessageBox::question( + this, tr("Ban Player"), + tr("Are you sure you would like to kick and ban %1?\n\nThis would " + "ban both their forum username and their IP address.") + .arg(QString::fromStdString(nickname)), + QMessageBox::Yes | QMessageBox::No); + if (result == QMessageBox::Yes) + SendModerationRequest(Network::IdModBan, nickname); + }); + } + + context_menu.exec(ui->player_view->viewport()->mapToGlobal(menu_location)); +} diff --git a/src/sudachi/multiplayer/chat_room.h b/src/sudachi/multiplayer/chat_room.h new file mode 100644 index 0000000..dd71ea4 --- /dev/null +++ b/src/sudachi/multiplayer/chat_room.h @@ -0,0 +1,76 @@ +// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include "network/network.h" + +namespace Ui { +class ChatRoom; +} + +namespace Core { +class AnnounceMultiplayerSession; +} + +class ConnectionError; +class ComboBoxProxyModel; + +class ChatMessage; + +class ChatRoom : public QWidget { + Q_OBJECT + +public: + explicit ChatRoom(QWidget* parent); + void Initialize(Network::RoomNetwork* room_network); + void RetranslateUi(); + void SetPlayerList(const Network::RoomMember::MemberList& member_list); + void Clear(); + void AppendStatusMessage(const QString& msg); + ~ChatRoom(); + + void SetModPerms(bool is_mod); + void UpdateIconDisplay(); + +public slots: + void OnRoomUpdate(const Network::RoomInformation& info); + void OnChatReceive(const Network::ChatEntry&); + void OnStatusMessageReceive(const Network::StatusMessageEntry&); + void OnSendChat(); + void OnChatTextChanged(); + void PopupContextMenu(const QPoint& menu_location); + void Disable(); + void Enable(); + +signals: + void ChatReceived(const Network::ChatEntry&); + void StatusMessageReceived(const Network::StatusMessageEntry&); + void UserPinged(); + +private: + static constexpr u32 max_chat_lines = 1000; + void AppendChatMessage(const QString&); + bool ValidateMessage(const std::string&); + void SendModerationRequest(Network::RoomMessageTypes type, const std::string& nickname); + + bool has_mod_perms = false; + QStandardItemModel* player_list; + std::unique_ptr ui; + std::unordered_set block_list; + std::unordered_map icon_cache; + Network::RoomNetwork* room_network; +}; + +Q_DECLARE_METATYPE(Network::ChatEntry); +Q_DECLARE_METATYPE(Network::StatusMessageEntry); +Q_DECLARE_METATYPE(Network::RoomInformation); +Q_DECLARE_METATYPE(Network::RoomMember::State); +Q_DECLARE_METATYPE(Network::RoomMember::Error); diff --git a/src/sudachi/multiplayer/chat_room.ui b/src/sudachi/multiplayer/chat_room.ui new file mode 100644 index 0000000..f2b31b5 --- /dev/null +++ b/src/sudachi/multiplayer/chat_room.ui @@ -0,0 +1,59 @@ + + + ChatRoom + + + + 0 + 0 + 807 + 432 + + + + Room Window + + + + + + + + + + + false + + + true + + + Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse + + + + + + + + + Send Chat Message + + + + + + + Send Message + + + + + + + + + + + + diff --git a/src/sudachi/multiplayer/client_room.cpp b/src/sudachi/multiplayer/client_room.cpp new file mode 100644 index 0000000..fbb715a --- /dev/null +++ b/src/sudachi/multiplayer/client_room.cpp @@ -0,0 +1,115 @@ +// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include +#include +#include +#include +#include +#include +#include +#include "common/logging/log.h" +#include "network/announce_multiplayer_session.h" +#include "ui_client_room.h" +#include "sudachi/game_list_p.h" +#include "sudachi/multiplayer/client_room.h" +#include "sudachi/multiplayer/message.h" +#include "sudachi/multiplayer/moderation_dialog.h" +#include "sudachi/multiplayer/state.h" + +ClientRoomWindow::ClientRoomWindow(QWidget* parent, Network::RoomNetwork& room_network_) + : QDialog(parent, Qt::WindowTitleHint | Qt::WindowCloseButtonHint | Qt::WindowSystemMenuHint), + ui(std::make_unique()), room_network{room_network_} { + ui->setupUi(this); + ui->chat->Initialize(&room_network); + + // setup the callbacks for network updates + if (auto member = room_network.GetRoomMember().lock()) { + member->BindOnRoomInformationChanged( + [this](const Network::RoomInformation& info) { emit RoomInformationChanged(info); }); + member->BindOnStateChanged( + [this](const Network::RoomMember::State& state) { emit StateChanged(state); }); + + connect(this, &ClientRoomWindow::RoomInformationChanged, this, + &ClientRoomWindow::OnRoomUpdate); + connect(this, &ClientRoomWindow::StateChanged, this, &::ClientRoomWindow::OnStateChange); + // Update the state + OnStateChange(member->GetState()); + } else { + // TODO (jroweboy) network was not initialized? + } + + connect(ui->disconnect, &QPushButton::clicked, this, &ClientRoomWindow::Disconnect); + ui->disconnect->setDefault(false); + ui->disconnect->setAutoDefault(false); + connect(ui->moderation, &QPushButton::clicked, [this] { + ModerationDialog dialog(room_network, this); + dialog.exec(); + }); + ui->moderation->setDefault(false); + ui->moderation->setAutoDefault(false); + connect(ui->chat, &ChatRoom::UserPinged, this, &ClientRoomWindow::ShowNotification); + UpdateView(); +} + +ClientRoomWindow::~ClientRoomWindow() = default; + +void ClientRoomWindow::SetModPerms(bool is_mod) { + ui->chat->SetModPerms(is_mod); + ui->moderation->setVisible(is_mod); + ui->moderation->setDefault(false); + ui->moderation->setAutoDefault(false); +} + +void ClientRoomWindow::RetranslateUi() { + ui->retranslateUi(this); + ui->chat->RetranslateUi(); +} + +void ClientRoomWindow::OnRoomUpdate(const Network::RoomInformation& info) { + UpdateView(); +} + +void ClientRoomWindow::OnStateChange(const Network::RoomMember::State& state) { + if (state == Network::RoomMember::State::Joined || + state == Network::RoomMember::State::Moderator) { + ui->chat->Clear(); + ui->chat->AppendStatusMessage(tr("Connected")); + SetModPerms(state == Network::RoomMember::State::Moderator); + } + UpdateView(); +} + +void ClientRoomWindow::Disconnect() { + auto parent = static_cast(parentWidget()); + if (parent->OnCloseRoom()) { + ui->chat->AppendStatusMessage(tr("Disconnected")); + close(); + } +} + +void ClientRoomWindow::UpdateView() { + if (auto member = room_network.GetRoomMember().lock()) { + if (member->IsConnected()) { + ui->chat->Enable(); + ui->disconnect->setEnabled(true); + auto memberlist = member->GetMemberInformation(); + ui->chat->SetPlayerList(memberlist); + const auto information = member->GetRoomInformation(); + setWindowTitle(QString(tr("%1 - %2 (%3/%4 members) - connected")) + .arg(QString::fromStdString(information.name)) + .arg(QString::fromStdString(information.preferred_game.name)) + .arg(memberlist.size()) + .arg(information.member_slots)); + ui->description->setText(QString::fromStdString(information.description)); + return; + } + } + // TODO(B3N30): can't get RoomMember*, show error and close window + close(); +} + +void ClientRoomWindow::UpdateIconDisplay() { + ui->chat->UpdateIconDisplay(); +} diff --git a/src/sudachi/multiplayer/client_room.h b/src/sudachi/multiplayer/client_room.h new file mode 100644 index 0000000..6f1bb6d --- /dev/null +++ b/src/sudachi/multiplayer/client_room.h @@ -0,0 +1,39 @@ +// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include "sudachi/multiplayer/chat_room.h" + +namespace Ui { +class ClientRoom; +} + +class ClientRoomWindow : public QDialog { + Q_OBJECT + +public: + explicit ClientRoomWindow(QWidget* parent, Network::RoomNetwork& room_network_); + ~ClientRoomWindow(); + + void RetranslateUi(); + void UpdateIconDisplay(); + +public slots: + void OnRoomUpdate(const Network::RoomInformation&); + void OnStateChange(const Network::RoomMember::State&); + +signals: + void RoomInformationChanged(const Network::RoomInformation&); + void StateChanged(const Network::RoomMember::State&); + void ShowNotification(); + +private: + void Disconnect(); + void UpdateView(); + void SetModPerms(bool is_mod); + + QStandardItemModel* player_list; + std::unique_ptr ui; + Network::RoomNetwork& room_network; +}; diff --git a/src/sudachi/multiplayer/client_room.ui b/src/sudachi/multiplayer/client_room.ui new file mode 100644 index 0000000..97e88b5 --- /dev/null +++ b/src/sudachi/multiplayer/client_room.ui @@ -0,0 +1,80 @@ + + + ClientRoom + + + + 0 + 0 + 807 + 432 + + + + Room Window + + + + + + + + 0 + + + + + Room Description + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Moderation... + + + false + + + + + + + Leave Room + + + + + + + + + + + + + + + ChatRoom + QWidget +
multiplayer/chat_room.h
+ 1 +
+
+ + +
diff --git a/src/sudachi/multiplayer/direct_connect.cpp b/src/sudachi/multiplayer/direct_connect.cpp new file mode 100644 index 0000000..a76df86 --- /dev/null +++ b/src/sudachi/multiplayer/direct_connect.cpp @@ -0,0 +1,137 @@ +// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include +#include +#include +#include +#include +#include "common/settings.h" +#include "core/core.h" +#include "core/internal_network/network_interface.h" +#include "network/network.h" +#include "ui_direct_connect.h" +#include "sudachi/main.h" +#include "sudachi/multiplayer/client_room.h" +#include "sudachi/multiplayer/direct_connect.h" +#include "sudachi/multiplayer/message.h" +#include "sudachi/multiplayer/state.h" +#include "sudachi/multiplayer/validation.h" +#include "sudachi/uisettings.h" + +enum class ConnectionType : u8 { TraversalServer, IP }; + +DirectConnectWindow::DirectConnectWindow(Core::System& system_, QWidget* parent) + : QDialog(parent, Qt::WindowTitleHint | Qt::WindowCloseButtonHint | Qt::WindowSystemMenuHint), + ui(std::make_unique()), system{system_}, room_network{ + system.GetRoomNetwork()} { + + ui->setupUi(this); + + // setup the watcher for background connections + watcher = new QFutureWatcher; + connect(watcher, &QFutureWatcher::finished, this, &DirectConnectWindow::OnConnection); + + ui->nickname->setValidator(validation.GetNickname()); + ui->nickname->setText( + QString::fromStdString(UISettings::values.multiplayer_nickname.GetValue())); + if (ui->nickname->text().isEmpty() && !Settings::values.sudachi_username.GetValue().empty()) { + // Use sudachi Web Service user name as nickname by default + ui->nickname->setText(QString::fromStdString(Settings::values.sudachi_username.GetValue())); + } + ui->ip->setValidator(validation.GetIP()); + ui->ip->setText(QString::fromStdString(UISettings::values.multiplayer_ip.GetValue())); + ui->port->setValidator(validation.GetPort()); + ui->port->setText(QString::number(UISettings::values.multiplayer_port.GetValue())); + + // TODO(jroweboy): Show or hide the connection options based on the current value of the combo + // box. Add this back in when the traversal server support is added. + connect(ui->connect, &QPushButton::clicked, this, &DirectConnectWindow::Connect); +} + +DirectConnectWindow::~DirectConnectWindow() = default; + +void DirectConnectWindow::RetranslateUi() { + ui->retranslateUi(this); +} + +void DirectConnectWindow::Connect() { + if (!Network::GetSelectedNetworkInterface()) { + NetworkMessage::ErrorManager::ShowError( + NetworkMessage::ErrorManager::NO_INTERFACE_SELECTED); + return; + } + if (!ui->nickname->hasAcceptableInput()) { + NetworkMessage::ErrorManager::ShowError(NetworkMessage::ErrorManager::USERNAME_NOT_VALID); + return; + } + if (system.IsPoweredOn()) { + if (!NetworkMessage::WarnGameRunning()) { + return; + } + } + if (const auto member = room_network.GetRoomMember().lock()) { + // Prevent the user from trying to join a room while they are already joining. + if (member->GetState() == Network::RoomMember::State::Joining) { + return; + } else if (member->IsConnected()) { + // And ask if they want to leave the room if they are already in one. + if (!NetworkMessage::WarnDisconnect()) { + return; + } + } + } + if (!ui->ip->hasAcceptableInput()) { + NetworkMessage::ErrorManager::ShowError(NetworkMessage::ErrorManager::IP_ADDRESS_NOT_VALID); + return; + } + if (!ui->port->hasAcceptableInput()) { + NetworkMessage::ErrorManager::ShowError(NetworkMessage::ErrorManager::PORT_NOT_VALID); + return; + } + + // Store settings + UISettings::values.multiplayer_nickname = ui->nickname->text().toStdString(); + UISettings::values.multiplayer_ip = ui->ip->text().toStdString(); + if (!ui->port->text().isEmpty()) { + UISettings::values.multiplayer_port = ui->port->text().toInt(); + } else { + UISettings::values.multiplayer_port = UISettings::values.multiplayer_port.GetDefault(); + } + + emit SaveConfig(); + + // attempt to connect in a different thread + QFuture f = QtConcurrent::run([&] { + if (auto room_member = room_network.GetRoomMember().lock()) { + auto port = UISettings::values.multiplayer_port.GetValue(); + room_member->Join(ui->nickname->text().toStdString(), + ui->ip->text().toStdString().c_str(), port, 0, Network::NoPreferredIP, + ui->password->text().toStdString().c_str()); + } + }); + watcher->setFuture(f); + // and disable widgets and display a connecting while we wait + BeginConnecting(); +} + +void DirectConnectWindow::BeginConnecting() { + ui->connect->setEnabled(false); + ui->connect->setText(tr("Connecting")); +} + +void DirectConnectWindow::EndConnecting() { + ui->connect->setEnabled(true); + ui->connect->setText(tr("Connect")); +} + +void DirectConnectWindow::OnConnection() { + EndConnecting(); + + if (auto room_member = room_network.GetRoomMember().lock()) { + if (room_member->IsConnected()) { + close(); + } + } +} diff --git a/src/sudachi/multiplayer/direct_connect.h b/src/sudachi/multiplayer/direct_connect.h new file mode 100644 index 0000000..58fe59b --- /dev/null +++ b/src/sudachi/multiplayer/direct_connect.h @@ -0,0 +1,49 @@ +// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include +#include +#include "sudachi/multiplayer/validation.h" + +namespace Ui { +class DirectConnect; +} + +namespace Core { +class System; +} + +class DirectConnectWindow : public QDialog { + Q_OBJECT + +public: + explicit DirectConnectWindow(Core::System& system_, QWidget* parent = nullptr); + ~DirectConnectWindow(); + + void RetranslateUi(); + +signals: + /** + * Signalled by this widget when it is closing itself and destroying any state such as + * connections that it might have. + */ + void Closed(); + void SaveConfig(); + +private slots: + void OnConnection(); + +private: + void Connect(); + void BeginConnecting(); + void EndConnecting(); + + QFutureWatcher* watcher; + std::unique_ptr ui; + Validation validation; + Core::System& system; + Network::RoomNetwork& room_network; +}; diff --git a/src/sudachi/multiplayer/direct_connect.ui b/src/sudachi/multiplayer/direct_connect.ui new file mode 100644 index 0000000..0dd4e68 --- /dev/null +++ b/src/sudachi/multiplayer/direct_connect.ui @@ -0,0 +1,165 @@ + + + DirectConnect + + + + 0 + 0 + 455 + 161 + + + + Direct Connect + + + + + + + + + + 0 + + + 0 + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Server Address + + + + + + + <html><head/><body><p>Server address of the host</p></body></html> + + + 253 + + + + + + + Port + + + + + + + <html><head/><body><p>Port number the host is listening on</p></body></html> + + + 5 + + + 24872 + + + + 65 + 50 + + + + + + + + + + + + + + + Nickname + + + + + + + 20 + + + + + + + Password + + + + + + + + + + + + + + Qt::Vertical + + + + 20 + 20 + + + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Connect + + + + + + + + + + + + diff --git a/src/sudachi/multiplayer/host_room.cpp b/src/sudachi/multiplayer/host_room.cpp new file mode 100644 index 0000000..b33193b --- /dev/null +++ b/src/sudachi/multiplayer/host_room.cpp @@ -0,0 +1,264 @@ +// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "common/logging/log.h" +#include "common/settings.h" +#include "core/core.h" +#include "core/internal_network/network_interface.h" +#include "network/announce_multiplayer_session.h" +#include "ui_host_room.h" +#include "sudachi/game_list_p.h" +#include "sudachi/main.h" +#include "sudachi/multiplayer/host_room.h" +#include "sudachi/multiplayer/message.h" +#include "sudachi/multiplayer/state.h" +#include "sudachi/multiplayer/validation.h" +#include "sudachi/uisettings.h" +#ifdef ENABLE_WEB_SERVICE +#include "web_service/verify_user_jwt.h" +#endif + +HostRoomWindow::HostRoomWindow(QWidget* parent, QStandardItemModel* list, + std::shared_ptr session, + Core::System& system_) + : QDialog(parent, Qt::WindowTitleHint | Qt::WindowCloseButtonHint | Qt::WindowSystemMenuHint), + ui(std::make_unique()), + announce_multiplayer_session(session), system{system_}, room_network{ + system.GetRoomNetwork()} { + ui->setupUi(this); + + // set up validation for all of the fields + ui->room_name->setValidator(validation.GetRoomName()); + ui->username->setValidator(validation.GetNickname()); + ui->port->setValidator(validation.GetPort()); + ui->port->setPlaceholderText(QString::number(Network::DefaultRoomPort)); + + // Create a proxy to the game list to display the list of preferred games + game_list = new QStandardItemModel; + UpdateGameList(list); + + proxy = new ComboBoxProxyModel; + proxy->setSourceModel(game_list); + proxy->sort(0, Qt::AscendingOrder); + ui->game_list->setModel(proxy); + + // Connect all the widgets to the appropriate events + connect(ui->host, &QPushButton::clicked, this, &HostRoomWindow::Host); + + // Restore the settings: + ui->username->setText( + QString::fromStdString(UISettings::values.multiplayer_room_nickname.GetValue())); + if (ui->username->text().isEmpty() && !Settings::values.sudachi_username.GetValue().empty()) { + // Use sudachi Web Service user name as nickname by default + ui->username->setText(QString::fromStdString(Settings::values.sudachi_username.GetValue())); + } + ui->room_name->setText( + QString::fromStdString(UISettings::values.multiplayer_room_name.GetValue())); + ui->port->setText(QString::number(UISettings::values.multiplayer_room_port.GetValue())); + ui->max_player->setValue(UISettings::values.multiplayer_max_player.GetValue()); + int index = UISettings::values.multiplayer_host_type.GetValue(); + if (index < ui->host_type->count()) { + ui->host_type->setCurrentIndex(index); + } + index = ui->game_list->findData(UISettings::values.multiplayer_game_id.GetValue(), + GameListItemPath::ProgramIdRole); + if (index != -1) { + ui->game_list->setCurrentIndex(index); + } + ui->room_description->setText( + QString::fromStdString(UISettings::values.multiplayer_room_description.GetValue())); +} + +HostRoomWindow::~HostRoomWindow() = default; + +void HostRoomWindow::UpdateGameList(QStandardItemModel* list) { + game_list->clear(); + for (int i = 0; i < list->rowCount(); i++) { + auto parent = list->item(i, 0); + for (int j = 0; j < parent->rowCount(); j++) { + game_list->appendRow(parent->child(j)->clone()); + } + } +} + +void HostRoomWindow::RetranslateUi() { + ui->retranslateUi(this); +} + +std::unique_ptr HostRoomWindow::CreateVerifyBackend( + bool use_validation) const { + std::unique_ptr verify_backend; + if (use_validation) { +#ifdef ENABLE_WEB_SERVICE + verify_backend = + std::make_unique(Settings::values.web_api_url.GetValue()); +#else + verify_backend = std::make_unique(); +#endif + } else { + verify_backend = std::make_unique(); + } + return verify_backend; +} + +void HostRoomWindow::Host() { + if (!Network::GetSelectedNetworkInterface()) { + NetworkMessage::ErrorManager::ShowError( + NetworkMessage::ErrorManager::NO_INTERFACE_SELECTED); + return; + } + if (!ui->username->hasAcceptableInput()) { + NetworkMessage::ErrorManager::ShowError(NetworkMessage::ErrorManager::USERNAME_NOT_VALID); + return; + } + if (!ui->room_name->hasAcceptableInput()) { + NetworkMessage::ErrorManager::ShowError(NetworkMessage::ErrorManager::ROOMNAME_NOT_VALID); + return; + } + if (!ui->port->hasAcceptableInput()) { + NetworkMessage::ErrorManager::ShowError(NetworkMessage::ErrorManager::PORT_NOT_VALID); + return; + } + if (ui->game_list->currentIndex() == -1) { + NetworkMessage::ErrorManager::ShowError(NetworkMessage::ErrorManager::GAME_NOT_SELECTED); + return; + } + if (system.IsPoweredOn()) { + if (!NetworkMessage::WarnGameRunning()) { + return; + } + } + if (auto member = room_network.GetRoomMember().lock()) { + if (member->GetState() == Network::RoomMember::State::Joining) { + return; + } else if (member->IsConnected()) { + auto parent = static_cast(parentWidget()); + if (!parent->OnCloseRoom()) { + close(); + return; + } + } + ui->host->setDisabled(true); + + const AnnounceMultiplayerRoom::GameInfo game{ + .name = ui->game_list->currentData(Qt::DisplayRole).toString().toStdString(), + .id = ui->game_list->currentData(GameListItemPath::ProgramIdRole).toULongLong(), + }; + const auto port = + ui->port->isModified() ? ui->port->text().toInt() : Network::DefaultRoomPort; + const auto password = ui->password->text().toStdString(); + const bool is_public = ui->host_type->currentIndex() == 0; + Network::Room::BanList ban_list{}; + if (ui->load_ban_list->isChecked()) { + ban_list = UISettings::values.multiplayer_ban_list; + } + if (auto room = room_network.GetRoom().lock()) { + const bool created = + room->Create(ui->room_name->text().toStdString(), + ui->room_description->toPlainText().toStdString(), "", port, password, + ui->max_player->value(), Settings::values.sudachi_username.GetValue(), + game, CreateVerifyBackend(is_public), ban_list); + if (!created) { + NetworkMessage::ErrorManager::ShowError( + NetworkMessage::ErrorManager::COULD_NOT_CREATE_ROOM); + LOG_ERROR(Network, "Could not create room!"); + ui->host->setEnabled(true); + return; + } + } + // Start the announce session if they chose Public + if (is_public) { + if (auto session = announce_multiplayer_session.lock()) { + // Register the room first to ensure verify_uid is present when we connect + WebService::WebResult result = session->Register(); + if (result.result_code != WebService::WebResult::Code::Success) { + QMessageBox::warning( + this, tr("Error"), + tr("Failed to announce the room to the public lobby. In order to host a " + "room publicly, you must have a valid sudachi account configured in " + "Emulation -> Configure -> Web. If you do not want to publish a room in " + "the public lobby, then select Unlisted instead.\nDebug Message: ") + + QString::fromStdString(result.result_string), + QMessageBox::Ok); + ui->host->setEnabled(true); + if (auto room = room_network.GetRoom().lock()) { + room->Destroy(); + } + return; + } + session->Start(); + } else { + LOG_ERROR(Network, "Starting announce session failed"); + } + } + std::string token; +#ifdef ENABLE_WEB_SERVICE + if (is_public) { + WebService::Client client(Settings::values.web_api_url.GetValue(), + Settings::values.sudachi_username.GetValue(), + Settings::values.sudachi_token.GetValue()); + if (auto room = room_network.GetRoom().lock()) { + token = client.GetExternalJWT(room->GetVerifyUID()).returned_data; + } + if (token.empty()) { + LOG_ERROR(WebService, "Could not get external JWT, verification may fail"); + } else { + LOG_INFO(WebService, "Successfully requested external JWT: size={}", token.size()); + } + } +#endif + // TODO: Check what to do with this + member->Join(ui->username->text().toStdString(), "127.0.0.1", port, 0, + Network::NoPreferredIP, password, token); + + // Store settings + UISettings::values.multiplayer_room_nickname = ui->username->text().toStdString(); + UISettings::values.multiplayer_room_name = ui->room_name->text().toStdString(); + UISettings::values.multiplayer_game_id = + ui->game_list->currentData(GameListItemPath::ProgramIdRole).toLongLong(); + UISettings::values.multiplayer_max_player = ui->max_player->value(); + + UISettings::values.multiplayer_host_type = ui->host_type->currentIndex(); + if (ui->port->isModified() && !ui->port->text().isEmpty()) { + UISettings::values.multiplayer_room_port = ui->port->text().toInt(); + } else { + UISettings::values.multiplayer_room_port = Network::DefaultRoomPort; + } + UISettings::values.multiplayer_room_description = + ui->room_description->toPlainText().toStdString(); + ui->host->setEnabled(true); + emit SaveConfig(); + close(); + } +} + +QVariant ComboBoxProxyModel::data(const QModelIndex& idx, int role) const { + if (role != Qt::DisplayRole) { + auto val = QSortFilterProxyModel::data(idx, role); + // If its the icon, shrink it to 16x16 + if (role == Qt::DecorationRole) + val = val.value().scaled(16, 16, Qt::KeepAspectRatio); + return val; + } + std::string filename; + Common::SplitPath( + QSortFilterProxyModel::data(idx, GameListItemPath::FullPathRole).toString().toStdString(), + nullptr, &filename, nullptr); + QString title = QSortFilterProxyModel::data(idx, GameListItemPath::TitleRole).toString(); + return title.isEmpty() ? QString::fromStdString(filename) : title; +} + +bool ComboBoxProxyModel::lessThan(const QModelIndex& left, const QModelIndex& right) const { + auto leftData = left.data(GameListItemPath::TitleRole).toString(); + auto rightData = right.data(GameListItemPath::TitleRole).toString(); + return leftData.compare(rightData) < 0; +} diff --git a/src/sudachi/multiplayer/host_room.h b/src/sudachi/multiplayer/host_room.h new file mode 100644 index 0000000..b0ae13e --- /dev/null +++ b/src/sudachi/multiplayer/host_room.h @@ -0,0 +1,80 @@ +// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include +#include +#include +#include +#include "network/network.h" +#include "sudachi/multiplayer/chat_room.h" +#include "sudachi/multiplayer/validation.h" + +namespace Ui { +class HostRoom; +} + +namespace Core { +class System; +class AnnounceMultiplayerSession; +} // namespace Core + +class ConnectionError; +class ComboBoxProxyModel; + +class ChatMessage; + +namespace Network::VerifyUser { +class Backend; +}; + +class HostRoomWindow : public QDialog { + Q_OBJECT + +public: + explicit HostRoomWindow(QWidget* parent, QStandardItemModel* list, + std::shared_ptr session, + Core::System& system_); + ~HostRoomWindow(); + + /** + * Updates the dialog with a new game list model. + * This model should be the original model of the game list. + */ + void UpdateGameList(QStandardItemModel* list); + void RetranslateUi(); + +signals: + void SaveConfig(); + +private: + void Host(); + std::unique_ptr CreateVerifyBackend(bool use_validation) const; + + std::unique_ptr ui; + std::weak_ptr announce_multiplayer_session; + QStandardItemModel* game_list; + ComboBoxProxyModel* proxy; + Validation validation; + Core::System& system; + Network::RoomNetwork& room_network; +}; + +/** + * Proxy Model for the game list combo box so we can reuse the game list model while still + * displaying the fields slightly differently + */ +class ComboBoxProxyModel : public QSortFilterProxyModel { + Q_OBJECT + +public: + int columnCount(const QModelIndex& idx) const override { + return 1; + } + + QVariant data(const QModelIndex& idx, int role) const override; + + bool lessThan(const QModelIndex& left, const QModelIndex& right) const override; +}; diff --git a/src/sudachi/multiplayer/host_room.ui b/src/sudachi/multiplayer/host_room.ui new file mode 100644 index 0000000..d54cf49 --- /dev/null +++ b/src/sudachi/multiplayer/host_room.ui @@ -0,0 +1,207 @@ + + + HostRoom + + + + 0 + 0 + 607 + 211 + + + + Create Room + + + + + + + 0 + + + 0 + + + 0 + + + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + + + Room Name + + + + + + + 50 + + + + + + + Preferred Game + + + + + + + + + + Max Players + + + + + + + 2 + + + 16 + + + 8 + + + + + + + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + + + + + + Username + + + + + + + QLineEdit::PasswordEchoOnEdit + + + (Leave blank for open game) + + + + + + + Qt::ImhDigitsOnly + + + 5 + + + + + + + Password + + + + + + + Port + + + + + + + + + + + + + + Room Description + + + + + + + + + + + + + + Load Previous Ban List + + + true + + + + + + + + + 0 + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + Public + + + + + Unlisted + + + + + + + + Host Room + + + + + + + + + + diff --git a/src/sudachi/multiplayer/lobby.cpp b/src/sudachi/multiplayer/lobby.cpp new file mode 100644 index 0000000..c479a3a --- /dev/null +++ b/src/sudachi/multiplayer/lobby.cpp @@ -0,0 +1,439 @@ +// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include +#include +#include "common/logging/log.h" +#include "common/settings.h" +#include "core/core.h" +#include "core/hle/service/acc/profile_manager.h" +#include "core/internal_network/network_interface.h" +#include "network/network.h" +#include "ui_lobby.h" +#include "sudachi/game_list_p.h" +#include "sudachi/main.h" +#include "sudachi/multiplayer/client_room.h" +#include "sudachi/multiplayer/lobby.h" +#include "sudachi/multiplayer/lobby_p.h" +#include "sudachi/multiplayer/message.h" +#include "sudachi/multiplayer/state.h" +#include "sudachi/multiplayer/validation.h" +#include "sudachi/uisettings.h" +#ifdef ENABLE_WEB_SERVICE +#include "web_service/web_backend.h" +#endif + +Lobby::Lobby(QWidget* parent, QStandardItemModel* list, + std::shared_ptr session, Core::System& system_) + : QDialog(parent, Qt::WindowTitleHint | Qt::WindowCloseButtonHint | Qt::WindowSystemMenuHint), + ui(std::make_unique()), + announce_multiplayer_session(session), system{system_}, room_network{ + system.GetRoomNetwork()} { + ui->setupUi(this); + + // setup the watcher for background connections + watcher = new QFutureWatcher; + + model = new QStandardItemModel(ui->room_list); + + // Create a proxy to the game list to get the list of games owned + game_list = new QStandardItemModel; + UpdateGameList(list); + + proxy = new LobbyFilterProxyModel(this, game_list); + proxy->setSourceModel(model); + proxy->setDynamicSortFilter(true); + proxy->setFilterCaseSensitivity(Qt::CaseInsensitive); + proxy->setSortLocaleAware(true); + ui->room_list->setModel(proxy); + ui->room_list->header()->setSectionResizeMode(QHeaderView::Interactive); + ui->room_list->header()->stretchLastSection(); + ui->room_list->setAlternatingRowColors(true); + ui->room_list->setSelectionMode(QHeaderView::SingleSelection); + ui->room_list->setSelectionBehavior(QHeaderView::SelectRows); + ui->room_list->setVerticalScrollMode(QHeaderView::ScrollPerPixel); + ui->room_list->setHorizontalScrollMode(QHeaderView::ScrollPerPixel); + ui->room_list->setSortingEnabled(true); + ui->room_list->setEditTriggers(QHeaderView::NoEditTriggers); + ui->room_list->setExpandsOnDoubleClick(false); + ui->room_list->setContextMenuPolicy(Qt::CustomContextMenu); + + ui->nickname->setValidator(validation.GetNickname()); + ui->nickname->setText( + QString::fromStdString(UISettings::values.multiplayer_nickname.GetValue())); + + // Try find the best nickname by default + if (ui->nickname->text().isEmpty() || ui->nickname->text() == QStringLiteral("sudachi")) { + if (!Settings::values.sudachi_username.GetValue().empty()) { + ui->nickname->setText( + QString::fromStdString(Settings::values.sudachi_username.GetValue())); + } else if (!GetProfileUsername().empty()) { + ui->nickname->setText(QString::fromStdString(GetProfileUsername())); + } else { + ui->nickname->setText(QStringLiteral("sudachi")); + } + } + + // UI Buttons + connect(ui->refresh_list, &QPushButton::clicked, this, &Lobby::RefreshLobby); + connect(ui->search, &QLineEdit::textChanged, proxy, &LobbyFilterProxyModel::SetFilterSearch); + connect(ui->games_owned, &QCheckBox::toggled, proxy, &LobbyFilterProxyModel::SetFilterOwned); + connect(ui->hide_empty, &QCheckBox::toggled, proxy, &LobbyFilterProxyModel::SetFilterEmpty); + connect(ui->hide_full, &QCheckBox::toggled, proxy, &LobbyFilterProxyModel::SetFilterFull); + connect(ui->room_list, &QTreeView::doubleClicked, this, &Lobby::OnJoinRoom); + connect(ui->room_list, &QTreeView::clicked, this, &Lobby::OnExpandRoom); + + // Actions + connect(&room_list_watcher, &QFutureWatcher::finished, this, + &Lobby::OnRefreshLobby); + + // Load persistent filters after events are connected to make sure they apply + ui->search->setText( + QString::fromStdString(UISettings::values.multiplayer_filter_text.GetValue())); + ui->games_owned->setChecked(UISettings::values.multiplayer_filter_games_owned.GetValue()); + ui->hide_empty->setChecked(UISettings::values.multiplayer_filter_hide_empty.GetValue()); + ui->hide_full->setChecked(UISettings::values.multiplayer_filter_hide_full.GetValue()); +} + +Lobby::~Lobby() = default; + +void Lobby::UpdateGameList(QStandardItemModel* list) { + game_list->clear(); + for (int i = 0; i < list->rowCount(); i++) { + auto parent = list->item(i, 0); + for (int j = 0; j < parent->rowCount(); j++) { + game_list->appendRow(parent->child(j)->clone()); + } + } + if (proxy) + proxy->UpdateGameList(game_list); + ui->room_list->sortByColumn(Column::GAME_NAME, Qt::AscendingOrder); +} + +void Lobby::RetranslateUi() { + ui->retranslateUi(this); +} + +QString Lobby::PasswordPrompt() { + bool ok; + const QString text = + QInputDialog::getText(this, tr("Password Required to Join"), tr("Password:"), + QLineEdit::Password, QString(), &ok); + return ok ? text : QString(); +} + +void Lobby::OnExpandRoom(const QModelIndex& index) { + QModelIndex member_index = proxy->index(index.row(), Column::MEMBER); + auto member_list = proxy->data(member_index, LobbyItemMemberList::MemberListRole).toList(); +} + +void Lobby::OnJoinRoom(const QModelIndex& source) { + if (!Network::GetSelectedNetworkInterface()) { + LOG_INFO(WebService, "Automatically selected network interface for room network."); + Network::SelectFirstNetworkInterface(); + } + + if (!Network::GetSelectedNetworkInterface()) { + NetworkMessage::ErrorManager::ShowError( + NetworkMessage::ErrorManager::NO_INTERFACE_SELECTED); + return; + } + + if (system.IsPoweredOn()) { + if (!NetworkMessage::WarnGameRunning()) { + return; + } + } + + if (const auto member = room_network.GetRoomMember().lock()) { + // Prevent the user from trying to join a room while they are already joining. + if (member->GetState() == Network::RoomMember::State::Joining) { + return; + } else if (member->IsConnected()) { + // And ask if they want to leave the room if they are already in one. + if (!NetworkMessage::WarnDisconnect()) { + return; + } + } + } + QModelIndex index = source; + // If the user double clicks on a child row (aka the player list) then use the parent instead + if (source.parent() != QModelIndex()) { + index = source.parent(); + } + if (!ui->nickname->hasAcceptableInput()) { + NetworkMessage::ErrorManager::ShowError(NetworkMessage::ErrorManager::USERNAME_NOT_VALID); + return; + } + + // Get a password to pass if the room is password protected + QModelIndex password_index = proxy->index(index.row(), Column::ROOM_NAME); + bool has_password = proxy->data(password_index, LobbyItemName::PasswordRole).toBool(); + const std::string password = has_password ? PasswordPrompt().toStdString() : ""; + if (has_password && password.empty()) { + return; + } + + QModelIndex connection_index = proxy->index(index.row(), Column::HOST); + const std::string nickname = ui->nickname->text().toStdString(); + const std::string ip = + proxy->data(connection_index, LobbyItemHost::HostIPRole).toString().toStdString(); + int port = proxy->data(connection_index, LobbyItemHost::HostPortRole).toInt(); + const std::string verify_uid = + proxy->data(connection_index, LobbyItemHost::HostVerifyUIDRole).toString().toStdString(); + + // attempt to connect in a different thread + QFuture f = QtConcurrent::run([nickname, ip, port, password, verify_uid, this] { + std::string token; +#ifdef ENABLE_WEB_SERVICE + if (!Settings::values.sudachi_username.GetValue().empty() && + !Settings::values.sudachi_token.GetValue().empty()) { + WebService::Client client(Settings::values.web_api_url.GetValue(), + Settings::values.sudachi_username.GetValue(), + Settings::values.sudachi_token.GetValue()); + token = client.GetExternalJWT(verify_uid).returned_data; + if (token.empty()) { + LOG_ERROR(WebService, "Could not get external JWT, verification may fail"); + } else { + LOG_INFO(WebService, "Successfully requested external JWT: size={}", token.size()); + } + } +#endif + if (auto room_member = room_network.GetRoomMember().lock()) { + room_member->Join(nickname, ip.c_str(), port, 0, Network::NoPreferredIP, password, + token); + } + }); + watcher->setFuture(f); + + // TODO(jroweboy): disable widgets and display a connecting while we wait + + // Save settings + UISettings::values.multiplayer_nickname = ui->nickname->text().toStdString(); + UISettings::values.multiplayer_filter_text = ui->search->text().toStdString(); + UISettings::values.multiplayer_filter_games_owned = ui->games_owned->isChecked(); + UISettings::values.multiplayer_filter_hide_empty = ui->hide_empty->isChecked(); + UISettings::values.multiplayer_filter_hide_full = ui->hide_full->isChecked(); + UISettings::values.multiplayer_ip = + proxy->data(connection_index, LobbyItemHost::HostIPRole).value().toStdString(); + UISettings::values.multiplayer_port = + proxy->data(connection_index, LobbyItemHost::HostPortRole).toInt(); + emit SaveConfig(); +} + +void Lobby::ResetModel() { + model->clear(); + model->insertColumns(0, Column::TOTAL); + model->setHeaderData(Column::MEMBER, Qt::Horizontal, tr("Players"), Qt::DisplayRole); + model->setHeaderData(Column::ROOM_NAME, Qt::Horizontal, tr("Room Name"), Qt::DisplayRole); + model->setHeaderData(Column::GAME_NAME, Qt::Horizontal, tr("Preferred Game"), Qt::DisplayRole); + model->setHeaderData(Column::HOST, Qt::Horizontal, tr("Host"), Qt::DisplayRole); +} + +void Lobby::RefreshLobby() { + if (auto session = announce_multiplayer_session.lock()) { + ResetModel(); + ui->refresh_list->setEnabled(false); + ui->refresh_list->setText(tr("Refreshing")); + room_list_watcher.setFuture( + QtConcurrent::run([session]() { return session->GetRoomList(); })); + } else { + // TODO(jroweboy): Display an error box about announce couldn't be started + } +} + +void Lobby::OnRefreshLobby() { + AnnounceMultiplayerRoom::RoomList new_room_list = room_list_watcher.result(); + for (auto room : new_room_list) { + // find the icon for the game if this person owns that game. + QPixmap smdh_icon; + for (int r = 0; r < game_list->rowCount(); ++r) { + auto index = game_list->index(r, 0); + auto game_id = game_list->data(index, GameListItemPath::ProgramIdRole).toULongLong(); + + if (game_id != 0 && room.information.preferred_game.id == game_id) { + smdh_icon = game_list->data(index, Qt::DecorationRole).value(); + } + } + + QList members; + for (auto member : room.members) { + QVariant var; + var.setValue(LobbyMember{QString::fromStdString(member.username), + QString::fromStdString(member.nickname), member.game.id, + QString::fromStdString(member.game.name)}); + members.append(var); + } + + auto first_item = new LobbyItemGame( + room.information.preferred_game.id, + QString::fromStdString(room.information.preferred_game.name), smdh_icon); + auto row = QList({ + first_item, + new LobbyItemName(room.has_password, QString::fromStdString(room.information.name)), + new LobbyItemMemberList(members, room.information.member_slots), + new LobbyItemHost(QString::fromStdString(room.information.host_username), + QString::fromStdString(room.ip), room.information.port, + QString::fromStdString(room.verify_uid)), + }); + model->appendRow(row); + // To make the rows expandable, add the member data as a child of the first column of the + // rows with people in them and have qt set them to colspan after the model is finished + // resetting + if (!room.information.description.empty()) { + first_item->appendRow( + new LobbyItemDescription(QString::fromStdString(room.information.description))); + } + if (!room.members.empty()) { + first_item->appendRow(new LobbyItemExpandedMemberList(members)); + } + } + + // Re-enable the refresh button and resize the columns + ui->refresh_list->setEnabled(true); + ui->refresh_list->setText(tr("Refresh List")); + ui->room_list->header()->stretchLastSection(); + for (int i = 0; i < Column::TOTAL - 1; ++i) { + ui->room_list->resizeColumnToContents(i); + } + + // Set the member list child items to span all columns + for (int i = 0; i < proxy->rowCount(); i++) { + auto parent = model->item(i, 0); + for (int j = 0; j < parent->rowCount(); j++) { + ui->room_list->setFirstColumnSpanned(j, proxy->index(i, 0), true); + } + } + + ui->room_list->sortByColumn(Column::GAME_NAME, Qt::AscendingOrder); +} + +std::string Lobby::GetProfileUsername() { + const auto& current_user = + system.GetProfileManager().GetUser(Settings::values.current_user.GetValue()); + Service::Account::ProfileBase profile{}; + + if (!current_user.has_value()) { + return ""; + } + + if (!system.GetProfileManager().GetProfileBase(*current_user, profile)) { + return ""; + } + + const auto text = Common::StringFromFixedZeroTerminatedBuffer( + reinterpret_cast(profile.username.data()), profile.username.size()); + + return text; +} + +LobbyFilterProxyModel::LobbyFilterProxyModel(QWidget* parent, QStandardItemModel* list) + : QSortFilterProxyModel(parent), game_list(list) {} + +void LobbyFilterProxyModel::UpdateGameList(QStandardItemModel* list) { + game_list = list; +} + +bool LobbyFilterProxyModel::filterAcceptsRow(int sourceRow, const QModelIndex& sourceParent) const { + // Prioritize filters by fastest to compute + + // pass over any child rows (aka row that shows the players in the room) + if (sourceParent != QModelIndex()) { + return true; + } + + // filter by empty rooms + if (filter_empty) { + QModelIndex member_list = sourceModel()->index(sourceRow, Column::MEMBER, sourceParent); + int player_count = + sourceModel()->data(member_list, LobbyItemMemberList::MemberListRole).toList().size(); + if (player_count == 0) { + return false; + } + } + + // filter by filled rooms + if (filter_full) { + QModelIndex member_list = sourceModel()->index(sourceRow, Column::MEMBER, sourceParent); + int player_count = + sourceModel()->data(member_list, LobbyItemMemberList::MemberListRole).toList().size(); + int max_players = + sourceModel()->data(member_list, LobbyItemMemberList::MaxPlayerRole).toInt(); + if (player_count >= max_players) { + return false; + } + } + + // filter by search parameters + if (!filter_search.isEmpty()) { + QModelIndex game_name = sourceModel()->index(sourceRow, Column::GAME_NAME, sourceParent); + QModelIndex room_name = sourceModel()->index(sourceRow, Column::ROOM_NAME, sourceParent); + QModelIndex host_name = sourceModel()->index(sourceRow, Column::HOST, sourceParent); + bool preferred_game_match = sourceModel() + ->data(game_name, LobbyItemGame::GameNameRole) + .toString() + .contains(filter_search, filterCaseSensitivity()); + bool room_name_match = sourceModel() + ->data(room_name, LobbyItemName::NameRole) + .toString() + .contains(filter_search, filterCaseSensitivity()); + bool username_match = sourceModel() + ->data(host_name, LobbyItemHost::HostUsernameRole) + .toString() + .contains(filter_search, filterCaseSensitivity()); + if (!preferred_game_match && !room_name_match && !username_match) { + return false; + } + } + + // filter by game owned + if (filter_owned) { + QModelIndex game_name = sourceModel()->index(sourceRow, Column::GAME_NAME, sourceParent); + QList owned_games; + for (int r = 0; r < game_list->rowCount(); ++r) { + owned_games.append(QModelIndex(game_list->index(r, 0))); + } + auto current_id = sourceModel()->data(game_name, LobbyItemGame::TitleIDRole).toLongLong(); + if (current_id == 0) { + // TODO(jroweboy): homebrew often doesn't have a game id and this hides them + return false; + } + bool owned = false; + for (const auto& game : owned_games) { + auto game_id = game_list->data(game, GameListItemPath::ProgramIdRole).toLongLong(); + if (current_id == game_id) { + owned = true; + } + } + if (!owned) { + return false; + } + } + + return true; +} + +void LobbyFilterProxyModel::sort(int column, Qt::SortOrder order) { + sourceModel()->sort(column, order); +} + +void LobbyFilterProxyModel::SetFilterOwned(bool filter) { + filter_owned = filter; + invalidate(); +} + +void LobbyFilterProxyModel::SetFilterEmpty(bool filter) { + filter_empty = filter; + invalidate(); +} + +void LobbyFilterProxyModel::SetFilterFull(bool filter) { + filter_full = filter; + invalidate(); +} + +void LobbyFilterProxyModel::SetFilterSearch(const QString& filter) { + filter_search = filter; + invalidate(); +} diff --git a/src/sudachi/multiplayer/lobby.h b/src/sudachi/multiplayer/lobby.h new file mode 100644 index 0000000..bbfc977 --- /dev/null +++ b/src/sudachi/multiplayer/lobby.h @@ -0,0 +1,138 @@ +// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include +#include +#include +#include +#include "common/announce_multiplayer_room.h" +#include "network/announce_multiplayer_session.h" +#include "network/network.h" +#include "sudachi/multiplayer/validation.h" + +namespace Ui { +class Lobby; +} + +class LobbyModel; +class LobbyFilterProxyModel; + +namespace Core { +class System; +} + +/** + * Listing of all public games pulled from services. The lobby should be simple enough for users to + * find the game they want to play, and join it. + */ +class Lobby : public QDialog { + Q_OBJECT + +public: + explicit Lobby(QWidget* parent, QStandardItemModel* list, + std::shared_ptr session, + Core::System& system_); + ~Lobby() override; + + /** + * Updates the lobby with a new game list model. + * This model should be the original model of the game list. + */ + void UpdateGameList(QStandardItemModel* list); + void RetranslateUi(); + +public slots: + /** + * Begin the process to pull the latest room list from web services. After the listing is + * returned from web services, `LobbyRefreshed` will be signalled + */ + void RefreshLobby(); + +private slots: + /** + * Pulls the list of rooms from network and fills out the lobby model with the results + */ + void OnRefreshLobby(); + + /** + * Handler for single clicking on a room in the list. Expands the treeitem to show player + * information for the people in the room + * + * index - The row of the proxy model that the user wants to join. + */ + void OnExpandRoom(const QModelIndex&); + + /** + * Handler for double clicking on a room in the list. Gathers the host ip and port and attempts + * to connect. Will also prompt for a password in case one is required. + * + * index - The row of the proxy model that the user wants to join. + */ + void OnJoinRoom(const QModelIndex&); + +signals: + void StateChanged(const Network::RoomMember::State&); + void SaveConfig(); + +private: + std::string GetProfileUsername(); + + /** + * Removes all entries in the Lobby before refreshing. + */ + void ResetModel(); + + /** + * Prompts for a password. Returns an empty QString if the user either did not provide a + * password or if the user closed the window. + */ + QString PasswordPrompt(); + + std::unique_ptr ui; + + QStandardItemModel* model{}; + QStandardItemModel* game_list{}; + LobbyFilterProxyModel* proxy{}; + + QFutureWatcher room_list_watcher; + std::weak_ptr announce_multiplayer_session; + QFutureWatcher* watcher; + Validation validation; + Core::System& system; + Network::RoomNetwork& room_network; +}; + +/** + * Proxy Model for filtering the lobby + */ +class LobbyFilterProxyModel : public QSortFilterProxyModel { + Q_OBJECT; + +public: + explicit LobbyFilterProxyModel(QWidget* parent, QStandardItemModel* list); + + /** + * Updates the filter with a new game list model. + * This model should be the processed one created by the Lobby. + */ + void UpdateGameList(QStandardItemModel* list); + + bool filterAcceptsRow(int sourceRow, const QModelIndex& sourceParent) const override; + void sort(int column, Qt::SortOrder order) override; + +public slots: + void SetFilterOwned(bool); + void SetFilterEmpty(bool); + void SetFilterFull(bool); + void SetFilterSearch(const QString&); + +private: + QStandardItemModel* game_list; + bool filter_owned = false; + bool filter_empty = false; + bool filter_full = false; + QString filter_search; +}; diff --git a/src/sudachi/multiplayer/lobby.ui b/src/sudachi/multiplayer/lobby.ui new file mode 100644 index 0000000..0ef0ef7 --- /dev/null +++ b/src/sudachi/multiplayer/lobby.ui @@ -0,0 +1,130 @@ + + + Lobby + + + + 0 + 0 + 903 + 487 + + + + Public Room Browser + + + + + + 3 + + + + + 6 + + + + + + + Nickname + + + + + + + Nickname + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Filters + + + + + + + Search + + + true + + + + + + + Games I Own + + + + + + + Hide Empty Rooms + + + + + + + Hide Full Rooms + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Refresh Lobby + + + + + + + + + + + + + + + + + + + + diff --git a/src/sudachi/multiplayer/lobby_p.h b/src/sudachi/multiplayer/lobby_p.h new file mode 100644 index 0000000..77ec1fc --- /dev/null +++ b/src/sudachi/multiplayer/lobby_p.h @@ -0,0 +1,268 @@ +// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include +#include +#include +#include "common/common_types.h" + +namespace Column { +enum List { + GAME_NAME, + ROOM_NAME, + MEMBER, + HOST, + TOTAL, +}; +} + +class LobbyItem : public QStandardItem { +public: + LobbyItem() = default; + explicit LobbyItem(const QString& string) : QStandardItem(string) {} + virtual ~LobbyItem() override = default; +}; + +class LobbyItemName : public LobbyItem { +public: + static const int NameRole = Qt::UserRole + 1; + static const int PasswordRole = Qt::UserRole + 2; + + LobbyItemName() = default; + explicit LobbyItemName(bool has_password, QString name) : LobbyItem() { + setData(name, NameRole); + setData(has_password, PasswordRole); + } + + QVariant data(int role) const override { + if (role == Qt::DecorationRole) { + bool has_password = data(PasswordRole).toBool(); + return has_password ? QIcon::fromTheme(QStringLiteral("lock")).pixmap(16) : QIcon(); + } + if (role != Qt::DisplayRole) { + return LobbyItem::data(role); + } + return data(NameRole).toString(); + } + + bool operator<(const QStandardItem& other) const override { + return data(NameRole).toString().localeAwareCompare(other.data(NameRole).toString()) < 0; + } +}; + +class LobbyItemDescription : public LobbyItem { +public: + static const int DescriptionRole = Qt::UserRole + 1; + + LobbyItemDescription() = default; + explicit LobbyItemDescription(QString description) { + setData(description, DescriptionRole); + } + + QVariant data(int role) const override { + if (role != Qt::DisplayRole) { + return LobbyItem::data(role); + } + auto description = data(DescriptionRole).toString(); + description.prepend(QStringLiteral("Description: ")); + return description; + } + + bool operator<(const QStandardItem& other) const override { + return data(DescriptionRole) + .toString() + .localeAwareCompare(other.data(DescriptionRole).toString()) < 0; + } +}; + +class LobbyItemGame : public LobbyItem { +public: + static const int TitleIDRole = Qt::UserRole + 1; + static const int GameNameRole = Qt::UserRole + 2; + static const int GameIconRole = Qt::UserRole + 3; + + LobbyItemGame() = default; + explicit LobbyItemGame(u64 title_id, QString game_name, QPixmap smdh_icon) { + setData(static_cast(title_id), TitleIDRole); + setData(game_name, GameNameRole); + if (!smdh_icon.isNull()) { + setData(smdh_icon, GameIconRole); + } else { + setData(QIcon::fromTheme(QStringLiteral("chip")).pixmap(32), GameIconRole); + } + } + + QVariant data(int role) const override { + if (role == Qt::DecorationRole) { + auto val = data(GameIconRole); + if (val.isValid()) { + val = val.value().scaled(32, 32, Qt::KeepAspectRatio, + Qt::TransformationMode::SmoothTransformation); + } else { + auto blank_image = QPixmap(32, 32); + blank_image.fill(Qt::black); + val = blank_image; + } + return val; + } else if (role != Qt::DisplayRole) { + return LobbyItem::data(role); + } + return data(GameNameRole).toString(); + } + + bool operator<(const QStandardItem& other) const override { + return data(GameNameRole) + .toString() + .localeAwareCompare(other.data(GameNameRole).toString()) < 0; + } +}; + +class LobbyItemHost : public LobbyItem { +public: + static const int HostUsernameRole = Qt::UserRole + 1; + static const int HostIPRole = Qt::UserRole + 2; + static const int HostPortRole = Qt::UserRole + 3; + static const int HostVerifyUIDRole = Qt::UserRole + 4; + + LobbyItemHost() = default; + explicit LobbyItemHost(QString username, QString ip, u16 port, QString verify_uid) { + setData(username, HostUsernameRole); + setData(ip, HostIPRole); + setData(port, HostPortRole); + setData(verify_uid, HostVerifyUIDRole); + } + + QVariant data(int role) const override { + if (role != Qt::DisplayRole) { + return LobbyItem::data(role); + } + return data(HostUsernameRole).toString(); + } + + bool operator<(const QStandardItem& other) const override { + return data(HostUsernameRole) + .toString() + .localeAwareCompare(other.data(HostUsernameRole).toString()) < 0; + } +}; + +class LobbyMember { +public: + LobbyMember() = default; + LobbyMember(const LobbyMember& other) = default; + explicit LobbyMember(QString username_, QString nickname_, u64 title_id_, QString game_name_) + : username(std::move(username_)), nickname(std::move(nickname_)), title_id(title_id_), + game_name(std::move(game_name_)) {} + ~LobbyMember() = default; + + QString GetName() const { + if (username.isEmpty() || username == nickname) { + return nickname; + } else { + return QStringLiteral("%1 (%2)").arg(nickname, username); + } + } + u64 GetTitleId() const { + return title_id; + } + QString GetGameName() const { + return game_name; + } + +private: + QString username; + QString nickname; + u64 title_id; + QString game_name; +}; + +Q_DECLARE_METATYPE(LobbyMember); + +class LobbyItemMemberList : public LobbyItem { +public: + static const int MemberListRole = Qt::UserRole + 1; + static const int MaxPlayerRole = Qt::UserRole + 2; + + LobbyItemMemberList() = default; + explicit LobbyItemMemberList(QList members, u32 max_players) { + setData(members, MemberListRole); + setData(max_players, MaxPlayerRole); + } + + QVariant data(int role) const override { + switch (role) { + case Qt::DisplayRole: { + auto members = data(MemberListRole).toList(); + return QStringLiteral("%1 / %2 ") + .arg(QString::number(members.size()), data(MaxPlayerRole).toString()); + } + case Qt::ForegroundRole: { + auto members = data(MemberListRole).toList(); + auto max_players = data(MaxPlayerRole).toInt(); + const QColor room_full_color(255, 48, 32); + const QColor room_almost_full_color(255, 140, 32); + const QColor room_has_players_color(32, 160, 32); + const QColor room_empty_color(128, 128, 128); + + if (members.size() >= max_players) { + return QBrush(room_full_color); + } else if (members.size() == (max_players - 1)) { + return QBrush(room_almost_full_color); + } else if (members.size() == 0) { + return QBrush(room_empty_color); + } else if (members.size() > 0 && members.size() < (max_players - 1)) { + return QBrush(room_has_players_color); + } + // FIXME: How to return a value that tells Qt not to modify the + // text color from the default (as if Qt::ForegroundRole wasn't overridden)? + return QBrush(nullptr); + } + default: + return LobbyItem::data(role); + } + } + + bool operator<(const QStandardItem& other) const override { + // sort by rooms that have the most players + int left_members = data(MemberListRole).toList().size(); + int right_members = other.data(MemberListRole).toList().size(); + return left_members < right_members; + } +}; + +/** + * Member information for when a lobby is expanded in the UI + */ +class LobbyItemExpandedMemberList : public LobbyItem { +public: + static const int MemberListRole = Qt::UserRole + 1; + + LobbyItemExpandedMemberList() = default; + explicit LobbyItemExpandedMemberList(QList members) { + setData(members, MemberListRole); + } + + QVariant data(int role) const override { + if (role != Qt::DisplayRole) { + return LobbyItem::data(role); + } + auto members = data(MemberListRole).toList(); + QString out; + bool first = true; + for (const auto& member : members) { + if (!first) + out.append(QStringLiteral("\n")); + const auto& m = member.value(); + if (m.GetGameName().isEmpty()) { + out += QString(QObject::tr("%1 is not playing a game")).arg(m.GetName()); + } else { + out += QString(QObject::tr("%1 is playing %2")).arg(m.GetName(), m.GetGameName()); + } + first = false; + } + return out; + } +}; diff --git a/src/sudachi/multiplayer/message.cpp b/src/sudachi/multiplayer/message.cpp new file mode 100644 index 0000000..b20e50a --- /dev/null +++ b/src/sudachi/multiplayer/message.cpp @@ -0,0 +1,85 @@ +// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include + +#include "sudachi/multiplayer/message.h" + +namespace NetworkMessage { +const ConnectionError ErrorManager::USERNAME_NOT_VALID( + QT_TR_NOOP("Username is not valid. Must be 4 to 20 alphanumeric characters.")); +const ConnectionError ErrorManager::ROOMNAME_NOT_VALID( + QT_TR_NOOP("Room name is not valid. Must be 4 to 20 alphanumeric characters.")); +const ConnectionError ErrorManager::USERNAME_NOT_VALID_SERVER( + QT_TR_NOOP("Username is already in use or not valid. Please choose another.")); +const ConnectionError ErrorManager::IP_ADDRESS_NOT_VALID( + QT_TR_NOOP("IP is not a valid IPv4 address.")); +const ConnectionError ErrorManager::PORT_NOT_VALID( + QT_TR_NOOP("Port must be a number between 0 to 65535.")); +const ConnectionError ErrorManager::GAME_NOT_SELECTED(QT_TR_NOOP( + "You must choose a Preferred Game to host a room. If you do not have any games in your game " + "list yet, add a game folder by clicking on the plus icon in the game list.")); +const ConnectionError ErrorManager::NO_INTERNET( + QT_TR_NOOP("Unable to find an internet connection. Check your internet settings.")); +const ConnectionError ErrorManager::UNABLE_TO_CONNECT( + QT_TR_NOOP("Unable to connect to the host. Verify that the connection settings are correct. If " + "you still cannot connect, contact the room host and verify that the host is " + "properly configured with the external port forwarded.")); +const ConnectionError ErrorManager::ROOM_IS_FULL( + QT_TR_NOOP("Unable to connect to the room because it is already full.")); +const ConnectionError ErrorManager::COULD_NOT_CREATE_ROOM( + QT_TR_NOOP("Creating a room failed. Please retry. Restarting sudachi might be necessary.")); +const ConnectionError ErrorManager::HOST_BANNED( + QT_TR_NOOP("The host of the room has banned you. Speak with the host to unban you " + "or try a different room.")); +const ConnectionError ErrorManager::WRONG_VERSION( + QT_TR_NOOP("Version mismatch! Please update to the latest version of sudachi. If the problem " + "persists, contact the room host and ask them to update the server.")); +const ConnectionError ErrorManager::WRONG_PASSWORD(QT_TR_NOOP("Incorrect password.")); +const ConnectionError ErrorManager::GENERIC_ERROR(QT_TR_NOOP( + "An unknown error occurred. If this error continues to occur, please open an issue")); +const ConnectionError ErrorManager::LOST_CONNECTION( + QT_TR_NOOP("Connection to room lost. Try to reconnect.")); +const ConnectionError ErrorManager::HOST_KICKED( + QT_TR_NOOP("You have been kicked by the room host.")); +const ConnectionError ErrorManager::IP_COLLISION( + QT_TR_NOOP("IP address is already in use. Please choose another.")); +const ConnectionError ErrorManager::PERMISSION_DENIED( + QT_TR_NOOP("You do not have enough permission to perform this action.")); +const ConnectionError ErrorManager::NO_SUCH_USER(QT_TR_NOOP( + "The user you are trying to kick/ban could not be found.\nThey may have left the room.")); +const ConnectionError ErrorManager::NO_INTERFACE_SELECTED(QT_TR_NOOP( + "No valid network interface is selected.\nPlease go to Configure -> System -> Network and " + "make a selection.")); + +static bool WarnMessage(const std::string& title, const std::string& text) { + return QMessageBox::Ok == QMessageBox::warning(nullptr, QObject::tr(title.c_str()), + QObject::tr(text.c_str()), + QMessageBox::Ok | QMessageBox::Cancel); +} + +void ErrorManager::ShowError(const ConnectionError& e) { + QMessageBox::critical(nullptr, tr("Error"), tr(e.GetString().c_str())); +} + +bool WarnGameRunning() { + return WarnMessage( + QT_TR_NOOP("Game already running"), + QT_TR_NOOP("Joining a room when the game is already running is discouraged " + "and can cause the room feature not to work correctly.\nProceed anyway?")); +} + +bool WarnCloseRoom() { + return WarnMessage( + QT_TR_NOOP("Leave Room"), + QT_TR_NOOP("You are about to close the room. Any network connections will be closed.")); +} + +bool WarnDisconnect() { + return WarnMessage( + QT_TR_NOOP("Disconnect"), + QT_TR_NOOP("You are about to leave the room. Any network connections will be closed.")); +} + +} // namespace NetworkMessage diff --git a/src/sudachi/multiplayer/message.h b/src/sudachi/multiplayer/message.h new file mode 100644 index 0000000..f038b9a --- /dev/null +++ b/src/sudachi/multiplayer/message.h @@ -0,0 +1,72 @@ +// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include + +namespace NetworkMessage { + +class ConnectionError { + +public: + explicit ConnectionError(std::string str) : err(std::move(str)) {} + const std::string& GetString() const { + return err; + } + +private: + std::string err; +}; + +class ErrorManager : QObject { + Q_OBJECT +public: + /// When the nickname is considered invalid by the client + static const ConnectionError USERNAME_NOT_VALID; + static const ConnectionError ROOMNAME_NOT_VALID; + /// When the nickname is considered invalid by the room server + static const ConnectionError USERNAME_NOT_VALID_SERVER; + static const ConnectionError IP_ADDRESS_NOT_VALID; + static const ConnectionError PORT_NOT_VALID; + static const ConnectionError GAME_NOT_SELECTED; + static const ConnectionError NO_INTERNET; + static const ConnectionError UNABLE_TO_CONNECT; + static const ConnectionError ROOM_IS_FULL; + static const ConnectionError COULD_NOT_CREATE_ROOM; + static const ConnectionError HOST_BANNED; + static const ConnectionError WRONG_VERSION; + static const ConnectionError WRONG_PASSWORD; + static const ConnectionError GENERIC_ERROR; + static const ConnectionError LOST_CONNECTION; + static const ConnectionError HOST_KICKED; + static const ConnectionError IP_COLLISION; + static const ConnectionError PERMISSION_DENIED; + static const ConnectionError NO_SUCH_USER; + static const ConnectionError NO_INTERFACE_SELECTED; + /** + * Shows a standard QMessageBox with a error message + */ + static void ShowError(const ConnectionError& e); +}; + +/** + * Show a standard QMessageBox with a warning message about joining a room when + * the game is already running + * return true if the user wants to close the network connection + */ +bool WarnGameRunning(); + +/** + * Show a standard QMessageBox with a warning message about leaving the room + * return true if the user wants to close the network connection + */ +bool WarnCloseRoom(); + +/** + * Show a standard QMessageBox with a warning message about disconnecting from the room + * return true if the user wants to disconnect + */ +bool WarnDisconnect(); + +} // namespace NetworkMessage diff --git a/src/sudachi/multiplayer/moderation_dialog.cpp b/src/sudachi/multiplayer/moderation_dialog.cpp new file mode 100644 index 0000000..02b7c1e --- /dev/null +++ b/src/sudachi/multiplayer/moderation_dialog.cpp @@ -0,0 +1,112 @@ +// SPDX-FileCopyrightText: Copyright 2018 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include +#include "network/network.h" +#include "network/room_member.h" +#include "ui_moderation_dialog.h" +#include "sudachi/multiplayer/moderation_dialog.h" + +namespace Column { +enum { + SUBJECT, + TYPE, + COUNT, +}; +} + +ModerationDialog::ModerationDialog(Network::RoomNetwork& room_network_, QWidget* parent) + : QDialog(parent), ui(std::make_unique()), room_network{room_network_} { + ui->setupUi(this); + + qRegisterMetaType(); + + if (auto member = room_network.GetRoomMember().lock()) { + callback_handle_status_message = member->BindOnStatusMessageReceived( + [this](const Network::StatusMessageEntry& status_message) { + emit StatusMessageReceived(status_message); + }); + connect(this, &ModerationDialog::StatusMessageReceived, this, + &ModerationDialog::OnStatusMessageReceived); + callback_handle_ban_list = member->BindOnBanListReceived( + [this](const Network::Room::BanList& ban_list) { emit BanListReceived(ban_list); }); + connect(this, &ModerationDialog::BanListReceived, this, &ModerationDialog::PopulateBanList); + } + + // Initialize the UI + model = new QStandardItemModel(ui->ban_list_view); + model->insertColumns(0, Column::COUNT); + model->setHeaderData(Column::SUBJECT, Qt::Horizontal, tr("Subject")); + model->setHeaderData(Column::TYPE, Qt::Horizontal, tr("Type")); + + ui->ban_list_view->setModel(model); + + // Load the ban list in background + LoadBanList(); + + connect(ui->refresh, &QPushButton::clicked, this, [this] { LoadBanList(); }); + connect(ui->unban, &QPushButton::clicked, this, [this] { + auto index = ui->ban_list_view->currentIndex(); + SendUnbanRequest(model->item(index.row(), 0)->text()); + }); + connect(ui->ban_list_view, &QTreeView::clicked, [this] { ui->unban->setEnabled(true); }); +} + +ModerationDialog::~ModerationDialog() { + if (callback_handle_status_message) { + if (auto room = room_network.GetRoomMember().lock()) { + room->Unbind(callback_handle_status_message); + } + } + + if (callback_handle_ban_list) { + if (auto room = room_network.GetRoomMember().lock()) { + room->Unbind(callback_handle_ban_list); + } + } +} + +void ModerationDialog::LoadBanList() { + if (auto room = room_network.GetRoomMember().lock()) { + ui->refresh->setEnabled(false); + ui->refresh->setText(tr("Refreshing")); + ui->unban->setEnabled(false); + room->RequestBanList(); + } +} + +void ModerationDialog::PopulateBanList(const Network::Room::BanList& ban_list) { + model->removeRows(0, model->rowCount()); + for (const auto& username : ban_list.first) { + QStandardItem* subject_item = new QStandardItem(QString::fromStdString(username)); + QStandardItem* type_item = new QStandardItem(tr("Forum Username")); + model->invisibleRootItem()->appendRow({subject_item, type_item}); + } + for (const auto& ip : ban_list.second) { + QStandardItem* subject_item = new QStandardItem(QString::fromStdString(ip)); + QStandardItem* type_item = new QStandardItem(tr("IP Address")); + model->invisibleRootItem()->appendRow({subject_item, type_item}); + } + for (int i = 0; i < Column::COUNT - 1; ++i) { + ui->ban_list_view->resizeColumnToContents(i); + } + ui->refresh->setEnabled(true); + ui->refresh->setText(tr("Refresh")); + ui->unban->setEnabled(false); +} + +void ModerationDialog::SendUnbanRequest(const QString& subject) { + if (auto room = room_network.GetRoomMember().lock()) { + room->SendModerationRequest(Network::IdModUnban, subject.toStdString()); + } +} + +void ModerationDialog::OnStatusMessageReceived(const Network::StatusMessageEntry& status_message) { + if (status_message.type != Network::IdMemberBanned && + status_message.type != Network::IdAddressUnbanned) + return; + + // Update the ban list for ban/unban + LoadBanList(); +} diff --git a/src/sudachi/multiplayer/moderation_dialog.h b/src/sudachi/multiplayer/moderation_dialog.h new file mode 100644 index 0000000..e9e5daf --- /dev/null +++ b/src/sudachi/multiplayer/moderation_dialog.h @@ -0,0 +1,43 @@ +// SPDX-FileCopyrightText: Copyright 2018 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include +#include +#include "network/room.h" +#include "network/room_member.h" + +namespace Ui { +class ModerationDialog; +} + +class QStandardItemModel; + +class ModerationDialog : public QDialog { + Q_OBJECT + +public: + explicit ModerationDialog(Network::RoomNetwork& room_network_, QWidget* parent = nullptr); + ~ModerationDialog(); + +signals: + void StatusMessageReceived(const Network::StatusMessageEntry&); + void BanListReceived(const Network::Room::BanList&); + +private: + void LoadBanList(); + void PopulateBanList(const Network::Room::BanList& ban_list); + void SendUnbanRequest(const QString& subject); + void OnStatusMessageReceived(const Network::StatusMessageEntry& status_message); + + std::unique_ptr ui; + QStandardItemModel* model; + Network::RoomMember::CallbackHandle callback_handle_status_message; + Network::RoomMember::CallbackHandle callback_handle_ban_list; + + Network::RoomNetwork& room_network; +}; + +Q_DECLARE_METATYPE(Network::Room::BanList); diff --git a/src/sudachi/multiplayer/moderation_dialog.ui b/src/sudachi/multiplayer/moderation_dialog.ui new file mode 100644 index 0000000..808d994 --- /dev/null +++ b/src/sudachi/multiplayer/moderation_dialog.ui @@ -0,0 +1,84 @@ + + + ModerationDialog + + + Moderation + + + + 0 + 0 + 500 + 300 + + + + + + + Ban List + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Refreshing + + + false + + + + + + + Unban + + + false + + + + + + + + + + + + + + + QDialogButtonBox::Ok + + + + + + + + buttonBox + accepted() + ModerationDialog + accept() + + + + diff --git a/src/sudachi/multiplayer/state.cpp b/src/sudachi/multiplayer/state.cpp new file mode 100644 index 0000000..ba64a62 --- /dev/null +++ b/src/sudachi/multiplayer/state.cpp @@ -0,0 +1,336 @@ +// SPDX-FileCopyrightText: Copyright 2018 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include +#include +#include +#include +#include "common/announce_multiplayer_room.h" +#include "common/logging/log.h" +#include "core/core.h" +#include "sudachi/game_list.h" +#include "sudachi/multiplayer/client_room.h" +#include "sudachi/multiplayer/direct_connect.h" +#include "sudachi/multiplayer/host_room.h" +#include "sudachi/multiplayer/lobby.h" +#include "sudachi/multiplayer/message.h" +#include "sudachi/multiplayer/state.h" +#include "sudachi/uisettings.h" +#include "sudachi/util/clickable_label.h" + +MultiplayerState::MultiplayerState(QWidget* parent, QStandardItemModel* game_list_model_, + QAction* leave_room_, QAction* show_room_, Core::System& system_) + : QWidget(parent), game_list_model(game_list_model_), leave_room(leave_room_), + show_room(show_room_), system{system_}, room_network{system.GetRoomNetwork()} { + if (auto member = room_network.GetRoomMember().lock()) { + // register the network structs to use in slots and signals + state_callback_handle = member->BindOnStateChanged( + [this](const Network::RoomMember::State& state) { emit NetworkStateChanged(state); }); + connect(this, &MultiplayerState::NetworkStateChanged, this, + &MultiplayerState::OnNetworkStateChanged); + error_callback_handle = member->BindOnError( + [this](const Network::RoomMember::Error& error) { emit NetworkError(error); }); + connect(this, &MultiplayerState::NetworkError, this, &MultiplayerState::OnNetworkError); + } + + qRegisterMetaType(); + qRegisterMetaType(); + qRegisterMetaType(); + announce_multiplayer_session = std::make_shared(room_network); + announce_multiplayer_session->BindErrorCallback( + [this](const WebService::WebResult& result) { emit AnnounceFailed(result); }); + connect(this, &MultiplayerState::AnnounceFailed, this, &MultiplayerState::OnAnnounceFailed); + + status_text = new ClickableLabel(this); + status_icon = new ClickableLabel(this); + + connect(status_text, &ClickableLabel::clicked, this, &MultiplayerState::OnOpenNetworkRoom); + connect(status_icon, &ClickableLabel::clicked, this, &MultiplayerState::OnOpenNetworkRoom); + + connect(static_cast(QApplication::instance()), &QApplication::focusChanged, this, + [this](QWidget* /*old*/, QWidget* now) { + if (client_room && client_room->isAncestorOf(now)) { + HideNotification(); + } + }); + + retranslateUi(); +} + +MultiplayerState::~MultiplayerState() = default; + +void MultiplayerState::Close() { + if (state_callback_handle) { + if (auto member = room_network.GetRoomMember().lock()) { + member->Unbind(state_callback_handle); + } + } + + if (error_callback_handle) { + if (auto member = room_network.GetRoomMember().lock()) { + member->Unbind(error_callback_handle); + } + } + if (host_room) { + host_room->close(); + } + if (direct_connect) { + direct_connect->close(); + } + if (client_room) { + client_room->close(); + } + if (lobby) { + lobby->close(); + } +} + +void MultiplayerState::retranslateUi() { + status_text->setToolTip(tr("Current connection status")); + + UpdateNotificationStatus(); + + if (lobby) { + lobby->RetranslateUi(); + } + if (host_room) { + host_room->RetranslateUi(); + } + if (client_room) { + client_room->RetranslateUi(); + } + if (direct_connect) { + direct_connect->RetranslateUi(); + } +} + +void MultiplayerState::SetNotificationStatus(NotificationStatus status) { + notification_status = status; + UpdateNotificationStatus(); +} + +void MultiplayerState::UpdateNotificationStatus() { + switch (notification_status) { + case NotificationStatus::Uninitialized: + status_icon->setPixmap(QIcon::fromTheme(QStringLiteral("disconnected")).pixmap(16)); + status_text->setText(tr("Not Connected. Click here to find a room!")); + leave_room->setEnabled(false); + show_room->setEnabled(false); + break; + case NotificationStatus::Disconnected: + status_icon->setPixmap(QIcon::fromTheme(QStringLiteral("disconnected")).pixmap(16)); + status_text->setText(tr("Not Connected")); + leave_room->setEnabled(false); + show_room->setEnabled(false); + break; + case NotificationStatus::Connected: + status_icon->setPixmap(QIcon::fromTheme(QStringLiteral("connected")).pixmap(16)); + status_text->setText(tr("Connected")); + leave_room->setEnabled(true); + show_room->setEnabled(true); + break; + case NotificationStatus::Notification: + status_icon->setPixmap( + QIcon::fromTheme(QStringLiteral("connected_notification")).pixmap(16)); + status_text->setText(tr("New Messages Received")); + leave_room->setEnabled(true); + show_room->setEnabled(true); + break; + } + + // Clean up status bar if game is running + if (system.IsPoweredOn()) { + status_text->clear(); + } +} + +void MultiplayerState::OnNetworkStateChanged(const Network::RoomMember::State& state) { + LOG_DEBUG(Frontend, "Network State: {}", Network::GetStateStr(state)); + if (state == Network::RoomMember::State::Joined || + state == Network::RoomMember::State::Moderator) { + + OnOpenNetworkRoom(); + SetNotificationStatus(NotificationStatus::Connected); + } else { + SetNotificationStatus(NotificationStatus::Disconnected); + } + + current_state = state; +} + +void MultiplayerState::OnNetworkError(const Network::RoomMember::Error& error) { + LOG_DEBUG(Frontend, "Network Error: {}", Network::GetErrorStr(error)); + switch (error) { + case Network::RoomMember::Error::LostConnection: + NetworkMessage::ErrorManager::ShowError(NetworkMessage::ErrorManager::LOST_CONNECTION); + break; + case Network::RoomMember::Error::HostKicked: + NetworkMessage::ErrorManager::ShowError(NetworkMessage::ErrorManager::HOST_KICKED); + break; + case Network::RoomMember::Error::CouldNotConnect: + NetworkMessage::ErrorManager::ShowError(NetworkMessage::ErrorManager::UNABLE_TO_CONNECT); + break; + case Network::RoomMember::Error::NameCollision: + NetworkMessage::ErrorManager::ShowError( + NetworkMessage::ErrorManager::USERNAME_NOT_VALID_SERVER); + break; + case Network::RoomMember::Error::IpCollision: + NetworkMessage::ErrorManager::ShowError(NetworkMessage::ErrorManager::IP_COLLISION); + break; + case Network::RoomMember::Error::RoomIsFull: + NetworkMessage::ErrorManager::ShowError(NetworkMessage::ErrorManager::ROOM_IS_FULL); + break; + case Network::RoomMember::Error::WrongPassword: + NetworkMessage::ErrorManager::ShowError(NetworkMessage::ErrorManager::WRONG_PASSWORD); + break; + case Network::RoomMember::Error::WrongVersion: + NetworkMessage::ErrorManager::ShowError(NetworkMessage::ErrorManager::WRONG_VERSION); + break; + case Network::RoomMember::Error::HostBanned: + NetworkMessage::ErrorManager::ShowError(NetworkMessage::ErrorManager::HOST_BANNED); + break; + case Network::RoomMember::Error::UnknownError: + NetworkMessage::ErrorManager::ShowError(NetworkMessage::ErrorManager::UNABLE_TO_CONNECT); + break; + case Network::RoomMember::Error::PermissionDenied: + NetworkMessage::ErrorManager::ShowError(NetworkMessage::ErrorManager::PERMISSION_DENIED); + break; + case Network::RoomMember::Error::NoSuchUser: + NetworkMessage::ErrorManager::ShowError(NetworkMessage::ErrorManager::NO_SUCH_USER); + break; + } +} + +void MultiplayerState::OnAnnounceFailed(const WebService::WebResult& result) { + announce_multiplayer_session->Stop(); + QMessageBox::warning(this, tr("Error"), + tr("Failed to update the room information. Please check your Internet " + "connection and try hosting the room again.\nDebug Message: ") + + QString::fromStdString(result.result_string), + QMessageBox::Ok); +} + +void MultiplayerState::OnSaveConfig() { + emit SaveConfig(); +} + +void MultiplayerState::UpdateThemedIcons() { + if (show_notification) { + status_icon->setPixmap( + QIcon::fromTheme(QStringLiteral("connected_notification")).pixmap(16)); + } else if (current_state == Network::RoomMember::State::Joined || + current_state == Network::RoomMember::State::Moderator) { + + status_icon->setPixmap(QIcon::fromTheme(QStringLiteral("connected")).pixmap(16)); + } else { + status_icon->setPixmap(QIcon::fromTheme(QStringLiteral("disconnected")).pixmap(16)); + } + if (client_room) + client_room->UpdateIconDisplay(); +} + +static void BringWidgetToFront(QWidget* widget) { + widget->show(); + widget->activateWindow(); + widget->raise(); +} + +void MultiplayerState::OnViewLobby() { + if (lobby == nullptr) { + lobby = new Lobby(this, game_list_model, announce_multiplayer_session, system); + connect(lobby, &Lobby::SaveConfig, this, &MultiplayerState::OnSaveConfig); + } + lobby->RefreshLobby(); + BringWidgetToFront(lobby); +} + +void MultiplayerState::OnCreateRoom() { + if (host_room == nullptr) { + host_room = new HostRoomWindow(this, game_list_model, announce_multiplayer_session, system); + connect(host_room, &HostRoomWindow::SaveConfig, this, &MultiplayerState::OnSaveConfig); + } + BringWidgetToFront(host_room); +} + +bool MultiplayerState::OnCloseRoom() { + if (!NetworkMessage::WarnCloseRoom()) + return false; + if (auto room = room_network.GetRoom().lock()) { + // if you are in a room, leave it + if (auto member = room_network.GetRoomMember().lock()) { + member->Leave(); + LOG_DEBUG(Frontend, "Left the room (as a client)"); + } + + // if you are hosting a room, also stop hosting + if (room->GetState() != Network::Room::State::Open) { + return true; + } + // Save ban list + UISettings::values.multiplayer_ban_list = room->GetBanList(); + + room->Destroy(); + announce_multiplayer_session->Stop(); + LOG_DEBUG(Frontend, "Closed the room (as a server)"); + } + return true; +} + +void MultiplayerState::ShowNotification() { + if (client_room && client_room->isAncestorOf(QApplication::focusWidget())) + return; // Do not show notification if the chat window currently has focus + show_notification = true; + QApplication::alert(nullptr); + QApplication::beep(); + SetNotificationStatus(NotificationStatus::Notification); +} + +void MultiplayerState::HideNotification() { + show_notification = false; + SetNotificationStatus(NotificationStatus::Connected); +} + +void MultiplayerState::OnOpenNetworkRoom() { + if (auto member = room_network.GetRoomMember().lock()) { + if (member->IsConnected()) { + if (client_room == nullptr) { + client_room = new ClientRoomWindow(this, room_network); + connect(client_room, &ClientRoomWindow::ShowNotification, this, + &MultiplayerState::ShowNotification); + } + BringWidgetToFront(client_room); + return; + } + } + // If the user is not a member of a room, show the lobby instead. + // This is currently only used on the clickable label in the status bar + OnViewLobby(); +} + +void MultiplayerState::OnDirectConnectToRoom() { + if (direct_connect == nullptr) { + direct_connect = new DirectConnectWindow(system, this); + connect(direct_connect, &DirectConnectWindow::SaveConfig, this, + &MultiplayerState::OnSaveConfig); + } + BringWidgetToFront(direct_connect); +} + +bool MultiplayerState::IsHostingPublicRoom() const { + return announce_multiplayer_session->IsRunning(); +} + +void MultiplayerState::UpdateCredentials() { + announce_multiplayer_session->UpdateCredentials(); +} + +void MultiplayerState::UpdateGameList(QStandardItemModel* game_list) { + game_list_model = game_list; + if (lobby) { + lobby->UpdateGameList(game_list); + } + if (host_room) { + host_room->UpdateGameList(game_list); + } +} diff --git a/src/sudachi/multiplayer/state.h b/src/sudachi/multiplayer/state.h new file mode 100644 index 0000000..d614983 --- /dev/null +++ b/src/sudachi/multiplayer/state.h @@ -0,0 +1,111 @@ +// SPDX-FileCopyrightText: Copyright 2018 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include "network/announce_multiplayer_session.h" +#include "network/network.h" + +class QStandardItemModel; +class Lobby; +class HostRoomWindow; +class ClientRoomWindow; +class DirectConnectWindow; +class ClickableLabel; + +namespace Core { +class System; +} + +class MultiplayerState : public QWidget { + Q_OBJECT; + +public: + enum class NotificationStatus { + Uninitialized, + Disconnected, + Connected, + Notification, + }; + + explicit MultiplayerState(QWidget* parent, QStandardItemModel* game_list, QAction* leave_room, + QAction* show_room, Core::System& system_); + ~MultiplayerState(); + + /** + * Close all open multiplayer related dialogs + */ + void Close(); + + void SetNotificationStatus(NotificationStatus state); + + void UpdateNotificationStatus(); + + ClickableLabel* GetStatusText() const { + return status_text; + } + + ClickableLabel* GetStatusIcon() const { + return status_icon; + } + + void retranslateUi(); + + /** + * Whether a public room is being hosted or not. + * When this is true, Web Services configuration should be disabled. + */ + bool IsHostingPublicRoom() const; + + void UpdateCredentials(); + + /** + * Updates the multiplayer dialogs with a new game list model. + * This model should be the original model of the game list. + */ + void UpdateGameList(QStandardItemModel* game_list); + +public slots: + void OnNetworkStateChanged(const Network::RoomMember::State& state); + void OnNetworkError(const Network::RoomMember::Error& error); + void OnViewLobby(); + void OnCreateRoom(); + bool OnCloseRoom(); + void OnOpenNetworkRoom(); + void OnDirectConnectToRoom(); + void OnAnnounceFailed(const WebService::WebResult&); + void OnSaveConfig(); + void UpdateThemedIcons(); + void ShowNotification(); + void HideNotification(); + +signals: + void NetworkStateChanged(const Network::RoomMember::State&); + void NetworkError(const Network::RoomMember::Error&); + void AnnounceFailed(const WebService::WebResult&); + void SaveConfig(); + +private: + Lobby* lobby = nullptr; + HostRoomWindow* host_room = nullptr; + ClientRoomWindow* client_room = nullptr; + DirectConnectWindow* direct_connect = nullptr; + ClickableLabel* status_icon = nullptr; + ClickableLabel* status_text = nullptr; + QStandardItemModel* game_list_model = nullptr; + QAction* leave_room; + QAction* show_room; + std::shared_ptr announce_multiplayer_session; + Network::RoomMember::State current_state = Network::RoomMember::State::Uninitialized; + NotificationStatus notification_status = NotificationStatus::Uninitialized; + bool has_mod_perms = false; + Network::RoomMember::CallbackHandle state_callback_handle; + Network::RoomMember::CallbackHandle error_callback_handle; + + bool show_notification = false; + Core::System& system; + Network::RoomNetwork& room_network; +}; + +Q_DECLARE_METATYPE(WebService::WebResult); diff --git a/src/sudachi/multiplayer/validation.h b/src/sudachi/multiplayer/validation.h new file mode 100644 index 0000000..cbbe675 --- /dev/null +++ b/src/sudachi/multiplayer/validation.h @@ -0,0 +1,67 @@ +// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include +#include + +class Validation { +public: + Validation() + : room_name(room_name_regex), nickname(nickname_regex), ip(ip_regex), port(0, UINT16_MAX) {} + + ~Validation() = default; + + const QValidator* GetRoomName() const { + return &room_name; + } + const QValidator* GetNickname() const { + return &nickname; + } + const QValidator* GetIP() const { + return &ip; + } + const QValidator* GetPort() const { + return &port; + } + +private: + /// room name can be alphanumeric and " " "_" "." and "-" and must have a size of 4-20 + QRegularExpression room_name_regex = + QRegularExpression(QStringLiteral("^[a-zA-Z0-9._ -]{4,20}")); + QRegularExpressionValidator room_name; + + /// nickname can be alphanumeric and " " "_" "." and "-" and must have a size of 4-20 + const QRegularExpression nickname_regex = + QRegularExpression(QStringLiteral("^[a-zA-Z0-9._ -]{4,20}")); + QRegularExpressionValidator nickname; + + /// ipv4 / ipv6 / hostnames + QRegularExpression ip_regex = QRegularExpression(QStringLiteral( + // IPv4 regex + "^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$|" + // IPv6 regex + "^((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|" + "(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-" + "5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|" + "(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)" + "(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|" + "(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]" + "\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|" + "(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[" + "0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|" + "(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[" + "0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|" + "(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[" + "0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|" + "(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?" + "\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:)))(%.+)?$|" + // Hostname regex + "^([a-zA-Z0-9]+(-[a-zA-Z0-9]+)*\\.)+[a-zA-Z]{2,}$")); + QRegularExpressionValidator ip; + + /// port must be between 0 and 65535 + QIntValidator port; +}; diff --git a/src/sudachi/play_time.cpp b/src/sudachi/play_time.cpp new file mode 100644 index 0000000..1af5cb7 --- /dev/null +++ b/src/sudachi/play_time.cpp @@ -0,0 +1,177 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include "common/fs/file.h" +#include "common/fs/path_util.h" +#include "common/logging/log.h" +#include "common/settings.h" +#include "common/thread.h" +#include "core/hle/service/acc/profile_manager.h" + +#include "sudachi/play_time.h" + +namespace PlayTime { + +void PlayTimeManager::SetProgramId(u64 program_id) { + this->running_program_id = program_id; +} + +inline void PlayTimeManager::UpdateTimestamp() { + this->last_timestamp = std::chrono::steady_clock::now(); +} + +void PlayTimeManager::Start() { + UpdateTimestamp(); + play_time_thread = + std::jthread([&](std::stop_token stop_token) { this->AutoTimestamp(stop_token); }); +} + +void PlayTimeManager::Stop() { + play_time_thread.request_stop(); +} + +void PlayTimeManager::AutoTimestamp(std::stop_token stop_token) { + Common::SetCurrentThreadName("PlayTimeReport"); + + using namespace std::literals::chrono_literals; + + const auto duration = 30s; + while (Common::StoppableTimedWait(stop_token, duration)) { + Save(); + } + + Save(); +} + +void PlayTimeManager::Save() { + const auto now = std::chrono::steady_clock::now(); + const auto duration = + static_cast(std::chrono::duration_cast( + std::chrono::steady_clock::duration(now - this->last_timestamp)) + .count()); + UpdateTimestamp(); + if (!UpdatePlayTime(running_program_id, duration)) { + LOG_ERROR(Common, "Failed to update play time"); + } +} + +bool UpdatePlayTime(u64 program_id, u64 add_play_time) { + std::vector play_time_elements; + if (!ReadPlayTimeFile(play_time_elements)) { + return false; + } + const auto it = std::find(play_time_elements.begin(), play_time_elements.end(), program_id); + + if (it == play_time_elements.end()) { + play_time_elements.push_back({.program_id = program_id, .play_time = add_play_time}); + } else { + play_time_elements.at(it - play_time_elements.begin()).play_time += add_play_time; + } + if (!WritePlayTimeFile(play_time_elements)) { + return false; + } + return true; +} + +u64 GetPlayTime(u64 program_id) { + std::vector play_time_elements; + + if (!ReadPlayTimeFile(play_time_elements)) { + return 0; + } + const auto it = std::find(play_time_elements.begin(), play_time_elements.end(), program_id); + if (it == play_time_elements.end()) { + return 0; + } + return play_time_elements.at(it - play_time_elements.begin()).play_time; +} + +bool PlayTimeManager::ResetProgramPlayTime(u64 program_id) { + std::vector play_time_elements; + + if (!ReadPlayTimeFile(play_time_elements)) { + return false; + } + const auto it = std::find(play_time_elements.begin(), play_time_elements.end(), program_id); + if (it == play_time_elements.end()) { + return false; + } + play_time_elements.erase(it); + if (!WritePlayTimeFile(play_time_elements)) { + return false; + } + return true; +} + +std::optional GetCurrentUserPlayTimePath() { + const Service::Account::ProfileManager manager; + const auto uuid = manager.GetUser(static_cast(Settings::values.current_user)); + if (!uuid.has_value()) { + return std::nullopt; + } + return Common::FS::GetSudachiPath(Common::FS::SudachiPath::PlayTimeDir) / + uuid->RawString().append(".bin"); +} + +[[nodiscard]] bool ReadPlayTimeFile(std::vector& out_play_time_elements) { + const auto filename = GetCurrentUserPlayTimePath(); + if (!filename.has_value()) { + LOG_ERROR(Common, "Failed to get current user path"); + return false; + } + + if (Common::FS::Exists(filename.value())) { + Common::FS::IOFile file{filename.value(), Common::FS::FileAccessMode::Read, + Common::FS::FileType::BinaryFile}; + if (!file.IsOpen()) { + LOG_ERROR(Common, "Failed to open play time file: {}", + Common::FS::PathToUTF8String(filename.value())); + return false; + } + const size_t elem_num = file.GetSize() / sizeof(PlayTimeElement); + out_play_time_elements.resize(elem_num); + const bool success = file.ReadSpan(out_play_time_elements) == elem_num; + file.Close(); + return success; + } else { + out_play_time_elements.clear(); + return true; + } +} + +[[nodiscard]] bool WritePlayTimeFile(const std::vector& play_time_elements) { + const auto filename = GetCurrentUserPlayTimePath(); + if (!filename.has_value()) { + LOG_ERROR(Common, "Failed to get current user path"); + return false; + } + Common::FS::IOFile file{filename.value(), Common::FS::FileAccessMode::Write, + Common::FS::FileType::BinaryFile}; + + if (!file.IsOpen()) { + LOG_ERROR(Common, "Failed to open play time file: {}", + Common::FS::PathToUTF8String(filename.value())); + return false; + } + const bool success = + file.WriteSpan(play_time_elements) == play_time_elements.size(); + file.Close(); + return success; +} + +QString ReadablePlayTime(qulonglong time_seconds) { + static constexpr std::array units{"m", "h"}; + if (time_seconds == 0) { + return QLatin1String(""); + } + const auto time_minutes = std::max(static_cast(time_seconds) / 60, 1.0); + const auto time_hours = static_cast(time_seconds) / 3600; + const int unit = time_minutes < 60 ? 0 : 1; + const auto value = unit == 0 ? time_minutes : time_hours; + + return QStringLiteral("%L1 %2") + .arg(value, 0, 'f', unit && time_seconds % 60 != 0) + .arg(QString::fromUtf8(units[unit])); +} + +} // namespace PlayTime diff --git a/src/sudachi/play_time.h b/src/sudachi/play_time.h new file mode 100644 index 0000000..c6bfaf5 --- /dev/null +++ b/src/sudachi/play_time.h @@ -0,0 +1,68 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include + +#include +#include +#include +#include +#include + +#include "common/common_types.h" +#include "common/fs/fs.h" +#include "common/polyfill_thread.h" +#include "core/core.h" + +namespace PlayTime { +struct PlayTimeElement { + u64 program_id; + u64 play_time; + + inline bool operator==(const PlayTimeElement& other) const { + return program_id == other.program_id; + } + + inline bool operator==(const u64 _program_id) const { + return program_id == _program_id; + } +}; + +class PlayTimeManager { +public: + explicit PlayTimeManager() = default; + ~PlayTimeManager() = default; + +public: + SUDACHI_NON_COPYABLE(PlayTimeManager); + SUDACHI_NON_MOVEABLE(PlayTimeManager); + +public: + bool ResetProgramPlayTime(u64 program_id); + void SetProgramId(u64 program_id); + inline void UpdateTimestamp(); + void Start(); + void Stop(); + +private: + u64 running_program_id; + std::chrono::steady_clock::time_point last_timestamp; + std::jthread play_time_thread; + void AutoTimestamp(std::stop_token stop_token); + void Save(); +}; + +std::optional GetCurrentUserPlayTimePath(); + +bool UpdatePlayTime(u64 program_id, u64 add_play_time); + +[[nodiscard]] bool ReadPlayTimeFile(std::vector& out_play_time_elements); +[[nodiscard]] bool WritePlayTimeFile(const std::vector& play_time_elements); + +u64 GetPlayTime(u64 program_id); + +QString ReadablePlayTime(qulonglong time_seconds); + +} // namespace PlayTime diff --git a/src/sudachi/play_time_manager.cpp b/src/sudachi/play_time_manager.cpp new file mode 100644 index 0000000..691e26d --- /dev/null +++ b/src/sudachi/play_time_manager.cpp @@ -0,0 +1,182 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include "common/alignment.h" +#include "common/fs/file.h" +#include "common/fs/fs.h" +#include "common/fs/path_util.h" +#include "common/logging/log.h" +#include "common/settings.h" +#include "common/thread.h" +#include "core/hle/service/acc/profile_manager.h" +#include "sudachi/play_time_manager.h" + +namespace PlayTime { + +namespace { + +struct PlayTimeElement { + ProgramId program_id; + PlayTime play_time; +}; + +std::optional GetCurrentUserPlayTimePath( + const Service::Account::ProfileManager& manager) { + const auto uuid = manager.GetUser(static_cast(Settings::values.current_user)); + if (!uuid.has_value()) { + return std::nullopt; + } + return Common::FS::GetSudachiPath(Common::FS::SudachiPath::PlayTimeDir) / + uuid->RawString().append(".bin"); +} + +[[nodiscard]] bool ReadPlayTimeFile(PlayTimeDatabase& out_play_time_db, + const Service::Account::ProfileManager& manager) { + const auto filename = GetCurrentUserPlayTimePath(manager); + + if (!filename.has_value()) { + LOG_ERROR(Frontend, "Failed to get current user path"); + return false; + } + + out_play_time_db.clear(); + + if (Common::FS::Exists(filename.value())) { + Common::FS::IOFile file{filename.value(), Common::FS::FileAccessMode::Read, + Common::FS::FileType::BinaryFile}; + if (!file.IsOpen()) { + LOG_ERROR(Frontend, "Failed to open play time file: {}", + Common::FS::PathToUTF8String(filename.value())); + return false; + } + + const size_t num_elements = file.GetSize() / sizeof(PlayTimeElement); + std::vector elements(num_elements); + + if (file.ReadSpan(elements) != num_elements) { + return false; + } + + for (const auto& [program_id, play_time] : elements) { + if (program_id != 0) { + out_play_time_db[program_id] = play_time; + } + } + } + + return true; +} + +[[nodiscard]] bool WritePlayTimeFile(const PlayTimeDatabase& play_time_db, + const Service::Account::ProfileManager& manager) { + const auto filename = GetCurrentUserPlayTimePath(manager); + + if (!filename.has_value()) { + LOG_ERROR(Frontend, "Failed to get current user path"); + return false; + } + + Common::FS::IOFile file{filename.value(), Common::FS::FileAccessMode::Write, + Common::FS::FileType::BinaryFile}; + if (!file.IsOpen()) { + LOG_ERROR(Frontend, "Failed to open play time file: {}", + Common::FS::PathToUTF8String(filename.value())); + return false; + } + + std::vector elements; + elements.reserve(play_time_db.size()); + + for (auto& [program_id, play_time] : play_time_db) { + if (program_id != 0) { + elements.push_back(PlayTimeElement{program_id, play_time}); + } + } + + return file.WriteSpan(elements) == elements.size(); +} + +} // namespace + +PlayTimeManager::PlayTimeManager(Service::Account::ProfileManager& profile_manager) + : manager{profile_manager} { + if (!ReadPlayTimeFile(database, manager)) { + LOG_ERROR(Frontend, "Failed to read play time database! Resetting to default."); + } +} + +PlayTimeManager::~PlayTimeManager() { + Save(); +} + +void PlayTimeManager::SetProgramId(u64 program_id) { + running_program_id = program_id; +} + +void PlayTimeManager::Start() { + play_time_thread = std::jthread([&](std::stop_token stop_token) { AutoTimestamp(stop_token); }); +} + +void PlayTimeManager::Stop() { + play_time_thread = {}; +} + +void PlayTimeManager::AutoTimestamp(std::stop_token stop_token) { + Common::SetCurrentThreadName("PlayTimeReport"); + + using namespace std::literals::chrono_literals; + using std::chrono::seconds; + using std::chrono::steady_clock; + + auto timestamp = steady_clock::now(); + + const auto GetDuration = [&]() -> u64 { + const auto last_timestamp = std::exchange(timestamp, steady_clock::now()); + const auto duration = std::chrono::duration_cast(timestamp - last_timestamp); + return static_cast(duration.count()); + }; + + while (!stop_token.stop_requested()) { + Common::StoppableTimedWait(stop_token, 30s); + + database[running_program_id] += GetDuration(); + Save(); + } +} + +void PlayTimeManager::Save() { + if (!WritePlayTimeFile(database, manager)) { + LOG_ERROR(Frontend, "Failed to update play time database!"); + } +} + +u64 PlayTimeManager::GetPlayTime(u64 program_id) const { + auto it = database.find(program_id); + if (it != database.end()) { + return it->second; + } else { + return 0; + } +} + +void PlayTimeManager::ResetProgramPlayTime(u64 program_id) { + database.erase(program_id); + Save(); +} + +QString ReadablePlayTime(qulonglong time_seconds) { + if (time_seconds == 0) { + return {}; + } + const auto time_minutes = std::max(static_cast(time_seconds) / 60, 1.0); + const auto time_hours = static_cast(time_seconds) / 3600; + const bool is_minutes = time_minutes < 60; + const char* unit = is_minutes ? "m" : "h"; + const auto value = is_minutes ? time_minutes : time_hours; + + return QStringLiteral("%L1 %2") + .arg(value, 0, 'f', !is_minutes && time_seconds % 60 != 0) + .arg(QString::fromUtf8(unit)); +} + +} // namespace PlayTime diff --git a/src/sudachi/play_time_manager.h b/src/sudachi/play_time_manager.h new file mode 100644 index 0000000..f5aaa82 --- /dev/null +++ b/src/sudachi/play_time_manager.h @@ -0,0 +1,50 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include + +#include + +#include "common/common_funcs.h" +#include "common/common_types.h" +#include "common/polyfill_thread.h" + +namespace Service::Account { +class ProfileManager; +} + +namespace PlayTime { + +using ProgramId = u64; +using PlayTime = u64; +using PlayTimeDatabase = std::map; + +class PlayTimeManager { +public: + explicit PlayTimeManager(Service::Account::ProfileManager& profile_manager); + ~PlayTimeManager(); + + SUDACHI_NON_COPYABLE(PlayTimeManager); + SUDACHI_NON_MOVEABLE(PlayTimeManager); + + u64 GetPlayTime(u64 program_id) const; + void ResetProgramPlayTime(u64 program_id); + void SetProgramId(u64 program_id); + void Start(); + void Stop(); + +private: + void AutoTimestamp(std::stop_token stop_token); + void Save(); + + PlayTimeDatabase database; + u64 running_program_id; + std::jthread play_time_thread; + Service::Account::ProfileManager& manager; +}; + +QString ReadablePlayTime(qulonglong time_seconds); + +} // namespace PlayTime diff --git a/src/sudachi/precompiled_headers.h b/src/sudachi/precompiled_headers.h new file mode 100644 index 0000000..0303960 --- /dev/null +++ b/src/sudachi/precompiled_headers.h @@ -0,0 +1,6 @@ +// SPDX-FileCopyrightText: 2022 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include "common/common_precompiled_headers.h" diff --git a/src/sudachi/qt_common.cpp b/src/sudachi/qt_common.cpp new file mode 100644 index 0000000..b8cc21c --- /dev/null +++ b/src/sudachi/qt_common.cpp @@ -0,0 +1,60 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include +#include +#include "common/logging/log.h" +#include "core/frontend/emu_window.h" +#include "sudachi/qt_common.h" + +#if !defined(WIN32) && !defined(__APPLE__) +#include +#elif defined(__APPLE__) +#include +#endif + +namespace QtCommon { +Core::Frontend::WindowSystemType GetWindowSystemType() { + // Determine WSI type based on Qt platform. + QString platform_name = QGuiApplication::platformName(); + if (platform_name == QStringLiteral("windows")) + return Core::Frontend::WindowSystemType::Windows; + else if (platform_name == QStringLiteral("xcb")) + return Core::Frontend::WindowSystemType::X11; + else if (platform_name == QStringLiteral("wayland")) + return Core::Frontend::WindowSystemType::Wayland; + else if (platform_name == QStringLiteral("wayland-egl")) + return Core::Frontend::WindowSystemType::Wayland; + else if (platform_name == QStringLiteral("cocoa")) + return Core::Frontend::WindowSystemType::Cocoa; + else if (platform_name == QStringLiteral("android")) + return Core::Frontend::WindowSystemType::Android; + + LOG_CRITICAL(Frontend, "Unknown Qt platform {}!", platform_name.toStdString()); + return Core::Frontend::WindowSystemType::Windows; +} // namespace Core::Frontend::WindowSystemType + +Core::Frontend::EmuWindow::WindowSystemInfo GetWindowSystemInfo(QWindow* window) { + Core::Frontend::EmuWindow::WindowSystemInfo wsi; + wsi.type = GetWindowSystemType(); + +#if defined(WIN32) + // Our Win32 Qt external doesn't have the private API. + wsi.render_surface = reinterpret_cast(window->winId()); +#elif defined(__APPLE__) + wsi.render_surface = reinterpret_cast(objc_msgSend)( + reinterpret_cast(window->winId()), sel_registerName("layer")); +#else + QPlatformNativeInterface* pni = QGuiApplication::platformNativeInterface(); + wsi.display_connection = pni->nativeResourceForWindow("display", window); + if (wsi.type == Core::Frontend::WindowSystemType::Wayland) + wsi.render_surface = window ? pni->nativeResourceForWindow("surface", window) : nullptr; + else + wsi.render_surface = window ? reinterpret_cast(window->winId()) : nullptr; +#endif + wsi.render_surface_scale = window ? static_cast(window->devicePixelRatio()) : 1.0f; + + return wsi; +} +} // namespace QtCommon diff --git a/src/sudachi/qt_common.h b/src/sudachi/qt_common.h new file mode 100644 index 0000000..b874228 --- /dev/null +++ b/src/sudachi/qt_common.h @@ -0,0 +1,15 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include "core/frontend/emu_window.h" + +namespace QtCommon { + +Core::Frontend::WindowSystemType GetWindowSystemType(); + +Core::Frontend::EmuWindow::WindowSystemInfo GetWindowSystemInfo(QWindow* window); + +} // namespace QtCommon diff --git a/src/sudachi/startup_checks.cpp b/src/sudachi/startup_checks.cpp new file mode 100644 index 0000000..9f1bad0 --- /dev/null +++ b/src/sudachi/startup_checks.cpp @@ -0,0 +1,197 @@ +// SPDX-FileCopyrightText: Copyright 2022 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include "video_core/vulkan_common/vulkan_wrapper.h" + +#ifdef _WIN32 +#include +#include +#include +#elif defined(SUDACHI_UNIX) +#include +#include +#include +#include +#include +#include +#endif + +#include +#include "video_core/vulkan_common/vulkan_instance.h" +#include "video_core/vulkan_common/vulkan_library.h" +#include "sudachi/startup_checks.h" + +void CheckVulkan() { + // Just start the Vulkan loader, this will crash if something is wrong + try { + Vulkan::vk::InstanceDispatch dld; + const auto library = Vulkan::OpenLibrary(); + const Vulkan::vk::Instance instance = + Vulkan::CreateInstance(*library, dld, VK_API_VERSION_1_1); + + } catch (const Vulkan::vk::Exception& exception) { + fmt::print(stderr, "Failed to initialize Vulkan: {}\n", exception.what()); + } +} + +bool CheckEnvVars(bool* is_child) { +#ifdef _WIN32 + // Check environment variable to see if we are the child + char variable_contents[8]; + const DWORD startup_check_var = + GetEnvironmentVariableA(STARTUP_CHECK_ENV_VAR, variable_contents, 8); + if (startup_check_var > 0 && std::strncmp(variable_contents, ENV_VAR_ENABLED_TEXT, 8) == 0) { + CheckVulkan(); + return true; + } + + // Don't perform startup checks if we are a child process + char is_child_s[8]; + const DWORD is_child_len = GetEnvironmentVariableA(IS_CHILD_ENV_VAR, is_child_s, 8); + if (is_child_len > 0 && std::strncmp(is_child_s, ENV_VAR_ENABLED_TEXT, 8) == 0) { + *is_child = true; + return false; + } else if (!SetEnvironmentVariableA(IS_CHILD_ENV_VAR, ENV_VAR_ENABLED_TEXT)) { + fmt::print(stderr, "SetEnvironmentVariableA failed to set {} with error {}\n", + IS_CHILD_ENV_VAR, GetLastError()); + return true; + } +#elif defined(SUDACHI_UNIX) + const char* startup_check_var = getenv(STARTUP_CHECK_ENV_VAR); + if (startup_check_var != nullptr && + std::strncmp(startup_check_var, ENV_VAR_ENABLED_TEXT, 8) == 0) { + CheckVulkan(); + return true; + } +#endif + return false; +} + +bool StartupChecks(const char* arg0, bool* has_broken_vulkan, bool perform_vulkan_check) { +#ifdef _WIN32 + // Set the startup variable for child processes + const bool env_var_set = SetEnvironmentVariableA(STARTUP_CHECK_ENV_VAR, ENV_VAR_ENABLED_TEXT); + if (!env_var_set) { + fmt::print(stderr, "SetEnvironmentVariableA failed to set {} with error {}\n", + STARTUP_CHECK_ENV_VAR, GetLastError()); + return false; + } + + if (perform_vulkan_check) { + // Spawn child process that performs Vulkan check + PROCESS_INFORMATION process_info; + std::memset(&process_info, '\0', sizeof(process_info)); + + if (!SpawnChild(arg0, &process_info, 0)) { + return false; + } + + // Wait until the process exits and get exit code from it + WaitForSingleObject(process_info.hProcess, INFINITE); + DWORD exit_code = STILL_ACTIVE; + const int err = GetExitCodeProcess(process_info.hProcess, &exit_code); + if (err == 0) { + fmt::print(stderr, "GetExitCodeProcess failed with error {}\n", GetLastError()); + } + + // Vulkan is broken if the child crashed (return value is not zero) + *has_broken_vulkan = (exit_code != 0); + + if (CloseHandle(process_info.hProcess) == 0) { + fmt::print(stderr, "CloseHandle failed with error {}\n", GetLastError()); + } + if (CloseHandle(process_info.hThread) == 0) { + fmt::print(stderr, "CloseHandle failed with error {}\n", GetLastError()); + } + } + + if (!SetEnvironmentVariableA(STARTUP_CHECK_ENV_VAR, nullptr)) { + fmt::print(stderr, "SetEnvironmentVariableA failed to clear {} with error {}\n", + STARTUP_CHECK_ENV_VAR, GetLastError()); + } + +#elif defined(SUDACHI_UNIX) + const int env_var_set = setenv(STARTUP_CHECK_ENV_VAR, ENV_VAR_ENABLED_TEXT, 1); + if (env_var_set == -1) { + const int err = errno; + fmt::print(stderr, "setenv failed to set {} with error {}\n", STARTUP_CHECK_ENV_VAR, err); + return false; + } + + if (perform_vulkan_check) { + const pid_t pid = SpawnChild(arg0); + if (pid == -1) { + return false; + } + + // Get exit code from child process + int status; + const int r_val = waitpid(pid, &status, 0); + if (r_val == -1) { + const int err = errno; + fmt::print(stderr, "wait failed with error {}\n", err); + return false; + } + // Vulkan is broken if the child crashed (return value is not zero) + *has_broken_vulkan = (status != 0); + } + + const int env_var_cleared = unsetenv(STARTUP_CHECK_ENV_VAR); + if (env_var_cleared == -1) { + const int err = errno; + fmt::print(stderr, "unsetenv failed to clear {} with error {}\n", STARTUP_CHECK_ENV_VAR, + err); + } +#endif + return false; +} + +#ifdef _WIN32 +bool SpawnChild(const char* arg0, PROCESS_INFORMATION* pi, int flags) { + STARTUPINFOA startup_info; + + std::memset(&startup_info, '\0', sizeof(startup_info)); + startup_info.cb = sizeof(startup_info); + + char p_name[255]; + std::strncpy(p_name, arg0, 254); + p_name[254] = '\0'; + + const bool process_created = CreateProcessA(nullptr, // lpApplicationName + p_name, // lpCommandLine + nullptr, // lpProcessAttributes + nullptr, // lpThreadAttributes + false, // bInheritHandles + flags, // dwCreationFlags + nullptr, // lpEnvironment + nullptr, // lpCurrentDirectory + &startup_info, // lpStartupInfo + pi // lpProcessInformation + ); + if (!process_created) { + fmt::print(stderr, "CreateProcessA failed with error {}\n", GetLastError()); + return false; + } + + return true; +} +#elif defined(SUDACHI_UNIX) +pid_t SpawnChild(const char* arg0) { + const pid_t pid = fork(); + + if (pid == -1) { + // error + const int err = errno; + fmt::print(stderr, "fork failed with error {}\n", err); + return pid; + } else if (pid == 0) { + // child + execlp(arg0, arg0, nullptr); + const int err = errno; + fmt::print(stderr, "execl failed with error {}\n", err); + _exit(0); + } + + return pid; +} +#endif diff --git a/src/sudachi/startup_checks.h b/src/sudachi/startup_checks.h new file mode 100644 index 0000000..a2e46b8 --- /dev/null +++ b/src/sudachi/startup_checks.h @@ -0,0 +1,24 @@ +// SPDX-FileCopyrightText: Copyright 2022 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#ifdef _WIN32 +#include +#elif defined(SUDACHI_UNIX) +#include +#endif + +constexpr char IS_CHILD_ENV_VAR[] = "SUDACHI_IS_CHILD"; +constexpr char STARTUP_CHECK_ENV_VAR[] = "SUDACHI_DO_STARTUP_CHECKS"; +constexpr char ENV_VAR_ENABLED_TEXT[] = "ON"; + +void CheckVulkan(); +bool CheckEnvVars(bool* is_child); +bool StartupChecks(const char* arg0, bool* has_broken_vulkan, bool perform_vulkan_check); + +#ifdef _WIN32 +bool SpawnChild(const char* arg0, PROCESS_INFORMATION* pi, int flags); +#elif defined(SUDACHI_UNIX) +pid_t SpawnChild(const char* arg0); +#endif diff --git a/src/sudachi/sudachi.qrc b/src/sudachi/sudachi.qrc new file mode 100644 index 0000000..6564df8 --- /dev/null +++ b/src/sudachi/sudachi.qrc @@ -0,0 +1,10 @@ + + + + + ../../dist/sudachi.ico + + diff --git a/src/sudachi/sudachi.rc b/src/sudachi/sudachi.rc new file mode 100644 index 0000000..905e658 --- /dev/null +++ b/src/sudachi/sudachi.rc @@ -0,0 +1,22 @@ +// SPDX-FileCopyrightText: 2018 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include "winresrc.h" +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +// QT requires that the default application icon is named IDI_ICON1 + +IDI_ICON1 ICON "../../dist/sudachi.ico" + + +///////////////////////////////////////////////////////////////////////////// +// +// RT_MANIFEST +// + +0 RT_MANIFEST "../../dist/sudachi.manifest" diff --git a/src/sudachi/uisettings.cpp b/src/sudachi/uisettings.cpp new file mode 100644 index 0000000..241e875 --- /dev/null +++ b/src/sudachi/uisettings.cpp @@ -0,0 +1,112 @@ +// SPDX-FileCopyrightText: 2016 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include "common/fs/fs.h" +#include "common/fs/path_util.h" +#include "sudachi/uisettings.h" + +#ifndef CANNOT_EXPLICITLY_INSTANTIATE +namespace Settings { +template class Setting; +template class Setting; +template class Setting; +template class Setting; +template class Setting; +template class Setting; +template class Setting; +} // namespace Settings +#endif + +namespace FS = Common::FS; + +namespace UISettings { + +const Themes themes{{ + {"Default", "default"}, + {"Default Colorful", "colorful"}, + {"Dark", "qdarkstyle"}, + {"Dark Colorful", "colorful_dark"}, + {"Midnight Blue", "qdarkstyle_midnight_blue"}, + {"Midnight Blue Colorful", "colorful_midnight_blue"}, +}}; + +bool IsDarkTheme() { + const auto& theme = UISettings::values.theme; + return theme == std::string("qdarkstyle") || theme == std::string("qdarkstyle_midnight_blue") || + theme == std::string("colorful_dark") || theme == std::string("colorful_midnight_blue"); +} + +Values values = {}; + +u32 CalculateWidth(u32 height, Settings::AspectRatio ratio) { + switch (ratio) { + case Settings::AspectRatio::R4_3: + return height * 4 / 3; + case Settings::AspectRatio::R21_9: + return height * 21 / 9; + case Settings::AspectRatio::R16_10: + return height * 16 / 10; + case Settings::AspectRatio::R16_9: + case Settings::AspectRatio::Stretch: + // TODO: Move this function wherever appropriate to implement Stretched aspect + break; + } + return height * 16 / 9; +} + +void SaveWindowState() { + const auto window_state_config_loc = + FS::PathToUTF8String(FS::GetSudachiPath(FS::SudachiPath::ConfigDir) / "window_state.ini"); + + void(FS::CreateParentDir(window_state_config_loc)); + QSettings config(QString::fromStdString(window_state_config_loc), QSettings::IniFormat); + + config.setValue(QStringLiteral("geometry"), values.geometry); + config.setValue(QStringLiteral("state"), values.state); + config.setValue(QStringLiteral("geometryRenderWindow"), values.renderwindow_geometry); + config.setValue(QStringLiteral("gameListHeaderState"), values.gamelist_header_state); + config.setValue(QStringLiteral("microProfileDialogGeometry"), values.microprofile_geometry); + + config.sync(); +} + +void RestoreWindowState(std::unique_ptr& qtConfig) { + const auto window_state_config_loc = + FS::PathToUTF8String(FS::GetSudachiPath(FS::SudachiPath::ConfigDir) / "window_state.ini"); + + // Migrate window state from old location + if (!FS::Exists(window_state_config_loc) && qtConfig->Exists("UI", "UILayout\\geometry")) { + const auto config_loc = + FS::PathToUTF8String(FS::GetSudachiPath(FS::SudachiPath::ConfigDir) / "qt-config.ini"); + QSettings config(QString::fromStdString(config_loc), QSettings::IniFormat); + + config.beginGroup(QStringLiteral("UI")); + config.beginGroup(QStringLiteral("UILayout")); + values.geometry = config.value(QStringLiteral("geometry")).toByteArray(); + values.state = config.value(QStringLiteral("state")).toByteArray(); + values.renderwindow_geometry = + config.value(QStringLiteral("geometryRenderWindow")).toByteArray(); + values.gamelist_header_state = + config.value(QStringLiteral("gameListHeaderState")).toByteArray(); + values.microprofile_geometry = + config.value(QStringLiteral("microProfileDialogGeometry")).toByteArray(); + config.endGroup(); + config.endGroup(); + return; + } + + void(FS::CreateParentDir(window_state_config_loc)); + const QSettings config(QString::fromStdString(window_state_config_loc), QSettings::IniFormat); + + values.geometry = config.value(QStringLiteral("geometry")).toByteArray(); + values.state = config.value(QStringLiteral("state")).toByteArray(); + values.renderwindow_geometry = + config.value(QStringLiteral("geometryRenderWindow")).toByteArray(); + values.gamelist_header_state = + config.value(QStringLiteral("gameListHeaderState")).toByteArray(); + values.microprofile_geometry = + config.value(QStringLiteral("microProfileDialogGeometry")).toByteArray(); +} + +} // namespace UISettings diff --git a/src/sudachi/uisettings.h b/src/sudachi/uisettings.h new file mode 100644 index 0000000..fe87064 --- /dev/null +++ b/src/sudachi/uisettings.h @@ -0,0 +1,279 @@ +// SPDX-FileCopyrightText: 2016 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include "common/common_types.h" +#include "common/settings.h" +#include "common/settings_enums.h" +#include "configuration/qt_config.h" + +using Settings::Category; +using Settings::ConfirmStop; +using Settings::Setting; +using Settings::SwitchableSetting; + +#ifndef CANNOT_EXPLICITLY_INSTANTIATE +namespace Settings { +extern template class Setting; +extern template class Setting; +extern template class Setting; +extern template class Setting; +extern template class Setting; +extern template class Setting; +extern template class Setting; +} // namespace Settings +#endif + +namespace UISettings { + +bool IsDarkTheme(); + +struct ContextualShortcut { + std::string keyseq; + std::string controller_keyseq; + int context; + bool repeat; +}; + +struct Shortcut { + std::string name; + std::string group; + ContextualShortcut shortcut; +}; + +enum class Theme { + Default, + DefaultColorful, + Dark, + DarkColorful, + MidnightBlue, + MidnightBlueColorful, +}; + +static constexpr Theme default_theme{ +#ifdef _WIN32 + Theme::DarkColorful +#else + Theme::DefaultColorful +#endif +}; + +using Themes = std::array, 6>; +extern const Themes themes; + +struct GameDir { + std::string path; + bool deep_scan = false; + bool expanded = false; + bool operator==(const GameDir& rhs) const { + return path == rhs.path; + } + bool operator!=(const GameDir& rhs) const { + return !operator==(rhs); + } +}; + +struct Values { + Settings::Linkage linkage{1000}; + + QByteArray geometry; + QByteArray state; + + QByteArray renderwindow_geometry; + + QByteArray gamelist_header_state; + + QByteArray microprofile_geometry; + Setting microprofile_visible{linkage, false, "microProfileDialogVisible", + Category::UiLayout}; + + Setting single_window_mode{linkage, true, "singleWindowMode", Category::Ui}; + Setting fullscreen{linkage, false, "fullscreen", Category::Ui}; + Setting display_titlebar{linkage, true, "displayTitleBars", Category::Ui}; + Setting show_filter_bar{linkage, true, "showFilterBar", Category::Ui}; + Setting show_status_bar{linkage, true, "showStatusBar", Category::Ui}; + + SwitchableSetting confirm_before_stopping{linkage, + ConfirmStop::Ask_Always, + "confirmStop", + Category::UiGeneral, + Settings::Specialization::Default, + true, + true}; + + Setting first_start{linkage, true, "firstStart", Category::Ui}; + Setting pause_when_in_background{linkage, + false, + "pauseWhenInBackground", + Category::UiGeneral, + Settings::Specialization::Default, + true, + true}; + Setting mute_when_in_background{linkage, + false, + "muteWhenInBackground", + Category::UiAudio, + Settings::Specialization::Default, + true, + true}; + Setting hide_mouse{ + linkage, true, "hideInactiveMouse", Category::UiGeneral, Settings::Specialization::Default, + true, true}; + Setting controller_applet_disabled{linkage, false, "disableControllerApplet", + Category::UiGeneral}; + // Set when Vulkan is known to crash the application + bool has_broken_vulkan = false; + + Setting select_user_on_boot{linkage, + false, + "select_user_on_boot", + Category::UiGeneral, + Settings::Specialization::Default, + true, + true}; + Setting disable_web_applet{linkage, true, "disable_web_applet", Category::Ui}; + + // Discord RPC + Setting enable_discord_presence{linkage, true, "enable_discord_presence", Category::Ui}; + + // logging + Setting show_console{linkage, false, "showConsole", Category::Ui}; + + // Screenshots + Setting enable_screenshot_save_as{linkage, true, "enable_screenshot_save_as", + Category::Screenshots}; + Setting screenshot_height{linkage, 0, "screenshot_height", Category::Screenshots}; + + std::string roms_path; + std::string game_dir_deprecated; + bool game_dir_deprecated_deepscan; + QVector game_dirs; + QStringList recent_files; + Setting language{linkage, {}, "language", Category::Paths}; + + std::string theme; + + // Shortcut name + std::vector shortcuts; + + Setting callout_flags{linkage, 0, "calloutFlags", Category::Ui}; + + // multiplayer settings + Setting multiplayer_nickname{linkage, {}, "nickname", Category::Multiplayer}; + Setting multiplayer_filter_text{linkage, {}, "filter_text", Category::Multiplayer}; + Setting multiplayer_filter_games_owned{linkage, false, "filter_games_owned", + Category::Multiplayer}; + Setting multiplayer_filter_hide_empty{linkage, false, "filter_games_hide_empty", + Category::Multiplayer}; + Setting multiplayer_filter_hide_full{linkage, false, "filter_games_hide_full", + Category::Multiplayer}; + Setting multiplayer_ip{linkage, {}, "ip", Category::Multiplayer}; + Setting multiplayer_port{linkage, 24872, 0, + UINT16_MAX, "port", Category::Multiplayer}; + Setting multiplayer_room_nickname{ + linkage, {}, "room_nickname", Category::Multiplayer}; + Setting multiplayer_room_name{linkage, {}, "room_name", Category::Multiplayer}; + Setting multiplayer_max_player{linkage, 8, 0, 8, "max_player", Category::Multiplayer}; + Setting multiplayer_room_port{linkage, 24872, 0, + UINT16_MAX, "room_port", Category::Multiplayer}; + Setting multiplayer_host_type{linkage, 0, 0, 1, "host_type", Category::Multiplayer}; + Setting multiplayer_game_id{linkage, {}, "game_id", Category::Multiplayer}; + Setting multiplayer_room_description{ + linkage, {}, "room_description", Category::Multiplayer}; + std::pair, std::vector> multiplayer_ban_list; + + // Game List + Setting show_add_ons{linkage, true, "show_add_ons", Category::UiGameList}; + Setting game_icon_size{linkage, 64, "game_icon_size", Category::UiGameList}; + Setting folder_icon_size{linkage, 48, "folder_icon_size", Category::UiGameList}; + Setting row_1_text_id{linkage, 3, "row_1_text_id", Category::UiGameList}; + Setting row_2_text_id{linkage, 2, "row_2_text_id", Category::UiGameList}; + std::atomic_bool is_game_list_reload_pending{false}; + Setting cache_game_list{linkage, true, "cache_game_list", Category::UiGameList}; + Setting favorites_expanded{linkage, true, "favorites_expanded", Category::UiGameList}; + QVector favorited_ids; + + // Compatibility List + Setting show_compat{linkage, false, "show_compat", Category::UiGameList}; + + // Size & File Types Column + Setting show_size{linkage, true, "show_size", Category::UiGameList}; + Setting show_types{linkage, true, "show_types", Category::UiGameList}; + + // Play time + Setting show_play_time{linkage, true, "show_play_time", Category::UiGameList}; + + bool configuration_applied; + bool reset_to_defaults; + bool shortcut_already_warned{false}; +}; + +extern Values values; + +u32 CalculateWidth(u32 height, Settings::AspectRatio ratio); + +void SaveWindowState(); +void RestoreWindowState(std::unique_ptr& qtConfig); + +// This shouldn't have anything except static initializers (no functions). So +// QKeySequence(...).toString() is NOT ALLOWED HERE. +// This must be in alphabetical order according to action name as it must have the same order as +// UISetting::values.shortcuts, which is alphabetically ordered. +// clang-format off +const std::array default_hotkeys{{ + {QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Audio Mute/Unmute")).toStdString(), QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Main Window")).toStdString(), {std::string("Ctrl+M"), std::string("Home+Dpad_Right"), Qt::WindowShortcut, false}}, + {QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Audio Volume Down")).toStdString(), QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Main Window")).toStdString(), {std::string("-"), std::string("Home+Dpad_Down"), Qt::ApplicationShortcut, true}}, + {QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Audio Volume Up")).toStdString(), QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Main Window")).toStdString(), {std::string("="), std::string("Home+Dpad_Up"), Qt::ApplicationShortcut, true}}, + {QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Capture Screenshot")).toStdString(), QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Main Window")).toStdString(), {std::string("Ctrl+P"), std::string("Screenshot"), Qt::WidgetWithChildrenShortcut, false}}, + {QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Change Adapting Filter")).toStdString(), QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Main Window")).toStdString(), {std::string("F8"), std::string("Home+L"), Qt::ApplicationShortcut, false}}, + {QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Change Docked Mode")).toStdString(), QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Main Window")).toStdString(), {std::string("F10"), std::string("Home+X"), Qt::ApplicationShortcut, false}}, + {QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Change GPU Accuracy")).toStdString(), QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Main Window")).toStdString(), {std::string("F9"), std::string("Home+R"), Qt::ApplicationShortcut, false}}, + {QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Continue/Pause Emulation")).toStdString(), QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Main Window")).toStdString(), {std::string("F4"), std::string("Home+Plus"), Qt::WindowShortcut, false}}, + {QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Exit Fullscreen")).toStdString(), QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Main Window")).toStdString(), {std::string("Esc"), std::string(""), Qt::WindowShortcut, false}}, + {QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Exit sudachi")).toStdString(), QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Main Window")).toStdString(), {std::string("Ctrl+Q"), std::string("Home+Minus"), Qt::WindowShortcut, false}}, + {QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Fullscreen")).toStdString(), QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Main Window")).toStdString(), {std::string("F11"), std::string("Home+B"), Qt::WindowShortcut, false}}, + {QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Load File")).toStdString(), QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Main Window")).toStdString(), {std::string("Ctrl+O"), std::string(""), Qt::WidgetWithChildrenShortcut, false}}, + {QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Load/Remove Amiibo")).toStdString(), QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Main Window")).toStdString(), {std::string("F2"), std::string("Home+A"), Qt::WidgetWithChildrenShortcut, false}}, + {QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Multiplayer Browse Public Game Lobby")).toStdString(), QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Main Window")).toStdString(), {std::string("Ctrl+B"), std::string(""), Qt::ApplicationShortcut, false}}, + {QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Multiplayer Create Room")).toStdString(), QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Main Window")).toStdString(), {std::string("Ctrl+N"), std::string(""), Qt::ApplicationShortcut, false}}, + {QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Multiplayer Direct Connect to Room")).toStdString(), QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Main Window")).toStdString(), {std::string("Ctrl+C"), std::string(""), Qt::ApplicationShortcut, false}}, + {QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Multiplayer Leave Room")).toStdString(), QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Main Window")).toStdString(), {std::string("Ctrl+L"), std::string(""), Qt::ApplicationShortcut, false}}, + {QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Multiplayer Show Current Room")).toStdString(), QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Main Window")).toStdString(), {std::string("Ctrl+R"), std::string(""), Qt::ApplicationShortcut, false}}, + {QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Restart Emulation")).toStdString(), QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Main Window")).toStdString(), {std::string("F6"), std::string("R+Plus+Minus"), Qt::WindowShortcut, false}}, + {QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Stop Emulation")).toStdString(), QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Main Window")).toStdString(), {std::string("F5"), std::string("L+Plus+Minus"), Qt::WindowShortcut, false}}, + {QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "TAS Record")).toStdString(), QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Main Window")).toStdString(), {std::string("Ctrl+F7"), std::string(""), Qt::ApplicationShortcut, false}}, + {QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "TAS Reset")).toStdString(), QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Main Window")).toStdString(), {std::string("Ctrl+F6"), std::string(""), Qt::ApplicationShortcut, false}}, + {QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "TAS Start/Stop")).toStdString(), QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Main Window")).toStdString(), {std::string("Ctrl+F5"), std::string(""), Qt::ApplicationShortcut, false}}, + {QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Toggle Filter Bar")).toStdString(), QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Main Window")).toStdString(), {std::string("Ctrl+F"), std::string(""), Qt::WindowShortcut, false}}, + {QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Toggle Framerate Limit")).toStdString(), QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Main Window")).toStdString(), {std::string("Ctrl+U"), std::string("Home+Y"), Qt::ApplicationShortcut, false}}, + {QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Toggle Mouse Panning")).toStdString(), QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Main Window")).toStdString(), {std::string("Ctrl+F9"), std::string(""), Qt::ApplicationShortcut, false}}, + {QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Toggle Renderdoc Capture")).toStdString(), QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Main Window")).toStdString(), {std::string(""), std::string(""), Qt::ApplicationShortcut, false}}, + {QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Toggle Status Bar")).toStdString(), QStringLiteral(QT_TRANSLATE_NOOP("Hotkeys", "Main Window")).toStdString(), {std::string("Ctrl+S"), std::string(""), Qt::WindowShortcut, false}}, +}}; +// clang-format on + +} // namespace UISettings + +Q_DECLARE_METATYPE(UISettings::GameDir*); + +// These metatype declarations cannot be in common/settings.h because core is devoid of QT +Q_DECLARE_METATYPE(Settings::CpuAccuracy); +Q_DECLARE_METATYPE(Settings::GpuAccuracy); +Q_DECLARE_METATYPE(Settings::FullscreenMode); +Q_DECLARE_METATYPE(Settings::NvdecEmulation); +Q_DECLARE_METATYPE(Settings::ResolutionSetup); +Q_DECLARE_METATYPE(Settings::ScalingFilter); +Q_DECLARE_METATYPE(Settings::AntiAliasing); +Q_DECLARE_METATYPE(Settings::RendererBackend); +Q_DECLARE_METATYPE(Settings::ShaderBackend); +Q_DECLARE_METATYPE(Settings::AstcRecompression); +Q_DECLARE_METATYPE(Settings::AstcDecodeMode); diff --git a/src/sudachi/util/clickable_label.cpp b/src/sudachi/util/clickable_label.cpp new file mode 100644 index 0000000..fbfe49e --- /dev/null +++ b/src/sudachi/util/clickable_label.cpp @@ -0,0 +1,11 @@ +// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include "sudachi/util/clickable_label.h" + +ClickableLabel::ClickableLabel(QWidget* parent, [[maybe_unused]] Qt::WindowFlags f) + : QLabel(parent) {} + +void ClickableLabel::mouseReleaseEvent([[maybe_unused]] QMouseEvent* event) { + emit clicked(); +} diff --git a/src/sudachi/util/clickable_label.h b/src/sudachi/util/clickable_label.h new file mode 100644 index 0000000..4fe7441 --- /dev/null +++ b/src/sudachi/util/clickable_label.h @@ -0,0 +1,21 @@ +// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include + +class ClickableLabel : public QLabel { + Q_OBJECT + +public: + explicit ClickableLabel(QWidget* parent = nullptr, Qt::WindowFlags f = Qt::WindowFlags()); + ~ClickableLabel() = default; + +signals: + void clicked(); + +protected: + void mouseReleaseEvent(QMouseEvent* event); +}; diff --git a/src/sudachi/util/controller_navigation.cpp b/src/sudachi/util/controller_navigation.cpp new file mode 100644 index 0000000..3d5e181 --- /dev/null +++ b/src/sudachi/util/controller_navigation.cpp @@ -0,0 +1,179 @@ +// SPDX-FileCopyrightText: Copyright 2021 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include "common/settings_input.h" +#include "hid_core/frontend/emulated_controller.h" +#include "hid_core/hid_core.h" +#include "sudachi/util/controller_navigation.h" + +ControllerNavigation::ControllerNavigation(Core::HID::HIDCore& hid_core, QWidget* parent) { + player1_controller = hid_core.GetEmulatedController(Core::HID::NpadIdType::Player1); + handheld_controller = hid_core.GetEmulatedController(Core::HID::NpadIdType::Handheld); + Core::HID::ControllerUpdateCallback engine_callback{ + .on_change = [this](Core::HID::ControllerTriggerType type) { ControllerUpdateEvent(type); }, + .is_npad_service = false, + }; + player1_callback_key = player1_controller->SetCallback(engine_callback); + handheld_callback_key = handheld_controller->SetCallback(engine_callback); + is_controller_set = true; +} + +ControllerNavigation::~ControllerNavigation() { + UnloadController(); +} + +void ControllerNavigation::UnloadController() { + if (is_controller_set) { + player1_controller->DeleteCallback(player1_callback_key); + handheld_controller->DeleteCallback(handheld_callback_key); + is_controller_set = false; + } +} + +void ControllerNavigation::TriggerButton(Settings::NativeButton::Values native_button, + Qt::Key key) { + if (button_values[native_button].value && !button_values[native_button].locked) { + emit TriggerKeyboardEvent(key); + } +} + +void ControllerNavigation::ControllerUpdateEvent(Core::HID::ControllerTriggerType type) { + std::scoped_lock lock{mutex}; + if (!Settings::values.controller_navigation) { + return; + } + if (type == Core::HID::ControllerTriggerType::Button) { + ControllerUpdateButton(); + return; + } + + if (type == Core::HID::ControllerTriggerType::Stick) { + ControllerUpdateStick(); + return; + } +} + +void ControllerNavigation::ControllerUpdateButton() { + const auto controller_type = player1_controller->GetNpadStyleIndex(); + const auto& player1_buttons = player1_controller->GetButtonsValues(); + const auto& handheld_buttons = handheld_controller->GetButtonsValues(); + + for (std::size_t i = 0; i < player1_buttons.size(); ++i) { + const bool button = player1_buttons[i].value || handheld_buttons[i].value; + // Trigger only once + button_values[i].locked = button == button_values[i].value; + button_values[i].value = button; + } + + switch (controller_type) { + case Core::HID::NpadStyleIndex::Fullkey: + case Core::HID::NpadStyleIndex::JoyconDual: + case Core::HID::NpadStyleIndex::Handheld: + case Core::HID::NpadStyleIndex::GameCube: + TriggerButton(Settings::NativeButton::A, Qt::Key_Enter); + TriggerButton(Settings::NativeButton::B, Qt::Key_Escape); + TriggerButton(Settings::NativeButton::DDown, Qt::Key_Down); + TriggerButton(Settings::NativeButton::DLeft, Qt::Key_Left); + TriggerButton(Settings::NativeButton::DRight, Qt::Key_Right); + TriggerButton(Settings::NativeButton::DUp, Qt::Key_Up); + break; + case Core::HID::NpadStyleIndex::JoyconLeft: + TriggerButton(Settings::NativeButton::DDown, Qt::Key_Enter); + TriggerButton(Settings::NativeButton::DLeft, Qt::Key_Escape); + break; + case Core::HID::NpadStyleIndex::JoyconRight: + TriggerButton(Settings::NativeButton::X, Qt::Key_Enter); + TriggerButton(Settings::NativeButton::A, Qt::Key_Escape); + break; + default: + break; + } +} + +void ControllerNavigation::ControllerUpdateStick() { + const auto controller_type = player1_controller->GetNpadStyleIndex(); + const auto& player1_sticks = player1_controller->GetSticksValues(); + const auto& handheld_sticks = player1_controller->GetSticksValues(); + bool update = false; + + for (std::size_t i = 0; i < player1_sticks.size(); ++i) { + const Common::Input::StickStatus stick{ + .left = player1_sticks[i].left || handheld_sticks[i].left, + .right = player1_sticks[i].right || handheld_sticks[i].right, + .up = player1_sticks[i].up || handheld_sticks[i].up, + .down = player1_sticks[i].down || handheld_sticks[i].down, + }; + // Trigger only once + if (stick.down != stick_values[i].down || stick.left != stick_values[i].left || + stick.right != stick_values[i].right || stick.up != stick_values[i].up) { + update = true; + } + stick_values[i] = stick; + } + + if (!update) { + return; + } + + switch (controller_type) { + case Core::HID::NpadStyleIndex::Fullkey: + case Core::HID::NpadStyleIndex::JoyconDual: + case Core::HID::NpadStyleIndex::Handheld: + case Core::HID::NpadStyleIndex::GameCube: + if (stick_values[Settings::NativeAnalog::LStick].down) { + emit TriggerKeyboardEvent(Qt::Key_Down); + return; + } + if (stick_values[Settings::NativeAnalog::LStick].left) { + emit TriggerKeyboardEvent(Qt::Key_Left); + return; + } + if (stick_values[Settings::NativeAnalog::LStick].right) { + emit TriggerKeyboardEvent(Qt::Key_Right); + return; + } + if (stick_values[Settings::NativeAnalog::LStick].up) { + emit TriggerKeyboardEvent(Qt::Key_Up); + return; + } + break; + case Core::HID::NpadStyleIndex::JoyconLeft: + if (stick_values[Settings::NativeAnalog::LStick].left) { + emit TriggerKeyboardEvent(Qt::Key_Down); + return; + } + if (stick_values[Settings::NativeAnalog::LStick].up) { + emit TriggerKeyboardEvent(Qt::Key_Left); + return; + } + if (stick_values[Settings::NativeAnalog::LStick].down) { + emit TriggerKeyboardEvent(Qt::Key_Right); + return; + } + if (stick_values[Settings::NativeAnalog::LStick].right) { + emit TriggerKeyboardEvent(Qt::Key_Up); + return; + } + break; + case Core::HID::NpadStyleIndex::JoyconRight: + if (stick_values[Settings::NativeAnalog::RStick].right) { + emit TriggerKeyboardEvent(Qt::Key_Down); + return; + } + if (stick_values[Settings::NativeAnalog::RStick].down) { + emit TriggerKeyboardEvent(Qt::Key_Left); + return; + } + if (stick_values[Settings::NativeAnalog::RStick].up) { + emit TriggerKeyboardEvent(Qt::Key_Right); + return; + } + if (stick_values[Settings::NativeAnalog::RStick].left) { + emit TriggerKeyboardEvent(Qt::Key_Up); + return; + } + break; + default: + break; + } +} diff --git a/src/sudachi/util/controller_navigation.h b/src/sudachi/util/controller_navigation.h new file mode 100644 index 0000000..023e958 --- /dev/null +++ b/src/sudachi/util/controller_navigation.h @@ -0,0 +1,50 @@ +// SPDX-FileCopyrightText: Copyright 2021 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include + +#include "common/input.h" +#include "common/settings_input.h" + +namespace Core::HID { +using ButtonValues = std::array; +using SticksValues = std::array; +enum class ControllerTriggerType; +class EmulatedController; +class HIDCore; +} // namespace Core::HID + +class ControllerNavigation : public QObject { + Q_OBJECT + +public: + explicit ControllerNavigation(Core::HID::HIDCore& hid_core, QWidget* parent = nullptr); + ~ControllerNavigation(); + + /// Disables events from the emulated controller + void UnloadController(); + +signals: + void TriggerKeyboardEvent(Qt::Key key); + +private: + void TriggerButton(Settings::NativeButton::Values native_button, Qt::Key key); + void ControllerUpdateEvent(Core::HID::ControllerTriggerType type); + + void ControllerUpdateButton(); + + void ControllerUpdateStick(); + + Core::HID::ButtonValues button_values{}; + Core::HID::SticksValues stick_values{}; + + int player1_callback_key{}; + int handheld_callback_key{}; + bool is_controller_set{}; + mutable std::mutex mutex; + Core::HID::EmulatedController* player1_controller; + Core::HID::EmulatedController* handheld_controller; +}; diff --git a/src/sudachi/util/limitable_input_dialog.cpp b/src/sudachi/util/limitable_input_dialog.cpp new file mode 100644 index 0000000..4f6e523 --- /dev/null +++ b/src/sudachi/util/limitable_input_dialog.cpp @@ -0,0 +1,88 @@ +// SPDX-FileCopyrightText: Copyright 2018 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include +#include +#include +#include +#include "sudachi/util/limitable_input_dialog.h" + +LimitableInputDialog::LimitableInputDialog(QWidget* parent) : QDialog{parent} { + CreateUI(); + ConnectEvents(); +} + +LimitableInputDialog::~LimitableInputDialog() = default; + +void LimitableInputDialog::CreateUI() { + text_label = new QLabel(this); + text_entry = new QLineEdit(this); + text_label_invalid = new QLabel(this); + buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, this); + + auto* const layout = new QVBoxLayout; + layout->addWidget(text_label); + layout->addWidget(text_entry); + layout->addWidget(text_label_invalid); + layout->addWidget(buttons); + + setLayout(layout); +} + +void LimitableInputDialog::ConnectEvents() { + connect(buttons, &QDialogButtonBox::accepted, this, &QDialog::accept); + connect(buttons, &QDialogButtonBox::rejected, this, &QDialog::reject); +} + +QString LimitableInputDialog::GetText(QWidget* parent, const QString& title, const QString& text, + int min_character_limit, int max_character_limit, + InputLimiter limit_type) { + Q_ASSERT(min_character_limit <= max_character_limit); + + LimitableInputDialog dialog{parent}; + dialog.setWindowTitle(title); + dialog.text_label->setText(text); + dialog.text_entry->setMaxLength(max_character_limit); + dialog.text_label_invalid->show(); + + switch (limit_type) { + case InputLimiter::Filesystem: + dialog.invalid_characters = QStringLiteral("<>:;\"/\\|,.!?*"); + break; + default: + dialog.invalid_characters.clear(); + dialog.text_label_invalid->hide(); + break; + } + dialog.text_label_invalid->setText( + tr("The text can't contain any of the following characters:\n%1") + .arg(dialog.invalid_characters)); + + auto* const ok_button = dialog.buttons->button(QDialogButtonBox::Ok); + ok_button->setEnabled(false); + connect(dialog.text_entry, &QLineEdit::textEdited, [&] { + if (!dialog.invalid_characters.isEmpty()) { + dialog.RemoveInvalidCharacters(); + } + ok_button->setEnabled(dialog.text_entry->text().length() >= min_character_limit); + }); + + if (dialog.exec() != QDialog::Accepted) { + return {}; + } + + return dialog.text_entry->text(); +} + +void LimitableInputDialog::RemoveInvalidCharacters() { + auto cpos = text_entry->cursorPosition(); + for (int i = 0; i < text_entry->text().length(); i++) { + if (invalid_characters.contains(text_entry->text().at(i))) { + text_entry->setText(text_entry->text().remove(i, 1)); + i--; + cpos--; + } + } + text_entry->setCursorPosition(cpos); +} diff --git a/src/sudachi/util/limitable_input_dialog.h b/src/sudachi/util/limitable_input_dialog.h new file mode 100644 index 0000000..ab8a7f4 --- /dev/null +++ b/src/sudachi/util/limitable_input_dialog.h @@ -0,0 +1,40 @@ +// SPDX-FileCopyrightText: Copyright 2018 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include + +class QDialogButtonBox; +class QLabel; +class QLineEdit; + +/// A QDialog that functions similarly to QInputDialog, however, it allows +/// restricting the minimum and total number of characters that can be entered. +class LimitableInputDialog final : public QDialog { + Q_OBJECT +public: + explicit LimitableInputDialog(QWidget* parent = nullptr); + ~LimitableInputDialog() override; + + enum class InputLimiter { + None, + Filesystem, + }; + + static QString GetText(QWidget* parent, const QString& title, const QString& text, + int min_character_limit, int max_character_limit, + InputLimiter limit_type = InputLimiter::None); + +private: + void CreateUI(); + void ConnectEvents(); + + void RemoveInvalidCharacters(); + QString invalid_characters; + + QLabel* text_label; + QLineEdit* text_entry; + QLabel* text_label_invalid; + QDialogButtonBox* buttons; +}; diff --git a/src/sudachi/util/overlay_dialog.cpp b/src/sudachi/util/overlay_dialog.cpp new file mode 100644 index 0000000..f99ecb3 --- /dev/null +++ b/src/sudachi/util/overlay_dialog.cpp @@ -0,0 +1,268 @@ +// SPDX-FileCopyrightText: Copyright 2021 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include +#include + +#include "core/core.h" +#include "hid_core/frontend/input_interpreter.h" +#include "hid_core/hid_types.h" +#include "ui_overlay_dialog.h" +#include "sudachi/util/overlay_dialog.h" + +namespace { + +constexpr float BASE_TITLE_FONT_SIZE = 14.0f; +constexpr float BASE_FONT_SIZE = 18.0f; +constexpr float BASE_WIDTH = 1280.0f; +constexpr float BASE_HEIGHT = 720.0f; + +} // Anonymous namespace + +OverlayDialog::OverlayDialog(QWidget* parent, Core::System& system, const QString& title_text, + const QString& body_text, const QString& left_button_text, + const QString& right_button_text, Qt::Alignment alignment, + bool use_rich_text_) + : QDialog(parent), ui{std::make_unique()}, use_rich_text{use_rich_text_} { + ui->setupUi(this); + + setWindowFlags(Qt::Dialog | Qt::FramelessWindowHint | Qt::WindowTitleHint | + Qt::WindowSystemMenuHint | Qt::CustomizeWindowHint); + setWindowModality(Qt::WindowModal); + setAttribute(Qt::WA_TranslucentBackground); + + if (use_rich_text) { + InitializeRichTextDialog(title_text, body_text, left_button_text, right_button_text, + alignment); + } else { + InitializeRegularTextDialog(title_text, body_text, left_button_text, right_button_text, + alignment); + } + + MoveAndResizeWindow(); + + // TODO (Morph): Remove this when InputInterpreter no longer relies on the HID backend + if (system.IsPoweredOn() && !ui->buttonsDialog->isHidden()) { + input_interpreter = std::make_unique(system); + + StartInputThread(); + } +} + +OverlayDialog::~OverlayDialog() { + StopInputThread(); +} + +void OverlayDialog::InitializeRegularTextDialog(const QString& title_text, const QString& body_text, + const QString& left_button_text, + const QString& right_button_text, + Qt::Alignment alignment) { + ui->stackedDialog->setCurrentIndex(0); + + ui->label_title->setText(title_text); + ui->label_dialog->setText(body_text); + ui->button_cancel->setText(left_button_text); + ui->button_ok_label->setText(right_button_text); + + ui->label_dialog->setAlignment(alignment); + + if (title_text.isEmpty()) { + ui->label_title->hide(); + ui->verticalLayout_2->setStretch(0, 0); + ui->verticalLayout_2->setStretch(1, 219); + ui->verticalLayout_2->setStretch(2, 82); + } + + if (left_button_text.isEmpty()) { + ui->button_cancel->hide(); + ui->button_cancel->setEnabled(false); + } + + if (right_button_text.isEmpty()) { + ui->button_ok_label->hide(); + ui->button_ok_label->setEnabled(false); + } + + if (ui->button_cancel->isHidden() && ui->button_ok_label->isHidden()) { + ui->buttonsDialog->hide(); + return; + } + + connect( + ui->button_cancel, &QPushButton::clicked, this, + [this](bool) { + StopInputThread(); + QDialog::reject(); + }, + Qt::QueuedConnection); + connect( + ui->button_ok_label, &QPushButton::clicked, this, + [this](bool) { + StopInputThread(); + QDialog::accept(); + }, + Qt::QueuedConnection); +} + +void OverlayDialog::InitializeRichTextDialog(const QString& title_text, const QString& body_text, + const QString& left_button_text, + const QString& right_button_text, + Qt::Alignment alignment) { + ui->stackedDialog->setCurrentIndex(1); + + ui->label_title_rich->setText(title_text); + ui->text_browser_dialog->setText(body_text); + ui->button_cancel_rich->setText(left_button_text); + ui->button_ok_rich->setText(right_button_text); + + // TODO (Morph/Rei): Replace this with something that works better + ui->text_browser_dialog->setAlignment(alignment); + + if (title_text.isEmpty()) { + ui->label_title_rich->hide(); + ui->verticalLayout_3->setStretch(0, 0); + ui->verticalLayout_3->setStretch(1, 438); + ui->verticalLayout_3->setStretch(2, 82); + } + + if (left_button_text.isEmpty()) { + ui->button_cancel_rich->hide(); + ui->button_cancel_rich->setEnabled(false); + } + + if (right_button_text.isEmpty()) { + ui->button_ok_rich->hide(); + ui->button_ok_rich->setEnabled(false); + } + + if (ui->button_cancel_rich->isHidden() && ui->button_ok_rich->isHidden()) { + ui->buttonsRichDialog->hide(); + return; + } + + connect( + ui->button_cancel_rich, &QPushButton::clicked, this, + [this](bool) { + StopInputThread(); + QDialog::reject(); + }, + Qt::QueuedConnection); + connect( + ui->button_ok_rich, &QPushButton::clicked, this, + [this](bool) { + StopInputThread(); + QDialog::accept(); + }, + Qt::QueuedConnection); +} + +void OverlayDialog::MoveAndResizeWindow() { + const auto pos = parentWidget()->mapToGlobal(parentWidget()->rect().topLeft()); + const auto width = static_cast(parentWidget()->width()); + const auto height = static_cast(parentWidget()->height()); + + // High DPI + const float dpi_scale = screen()->logicalDotsPerInch() / 96.0f; + + const auto title_text_font_size = BASE_TITLE_FONT_SIZE * (height / BASE_HEIGHT) / dpi_scale; + const auto body_text_font_size = + BASE_FONT_SIZE * (((width / BASE_WIDTH) + (height / BASE_HEIGHT)) / 2.0f) / dpi_scale; + const auto button_text_font_size = BASE_FONT_SIZE * (height / BASE_HEIGHT) / dpi_scale; + + QFont title_text_font(QStringLiteral("MS Shell Dlg 2"), title_text_font_size, QFont::Normal); + QFont body_text_font(QStringLiteral("MS Shell Dlg 2"), body_text_font_size, QFont::Normal); + QFont button_text_font(QStringLiteral("MS Shell Dlg 2"), button_text_font_size, QFont::Normal); + + if (use_rich_text) { + ui->label_title_rich->setFont(title_text_font); + ui->text_browser_dialog->setFont(body_text_font); + ui->button_cancel_rich->setFont(button_text_font); + ui->button_ok_rich->setFont(button_text_font); + } else { + ui->label_title->setFont(title_text_font); + ui->label_dialog->setFont(body_text_font); + ui->button_cancel->setFont(button_text_font); + ui->button_ok_label->setFont(button_text_font); + } + + QDialog::move(pos); + QDialog::resize(width, height); +} + +template +void OverlayDialog::HandleButtonPressedOnce() { + const auto f = [this](Core::HID::NpadButton button) { + if (input_interpreter->IsButtonPressedOnce(button)) { + TranslateButtonPress(button); + } + }; + + (f(T), ...); +} + +void OverlayDialog::TranslateButtonPress(Core::HID::NpadButton button) { + QPushButton* left_button = use_rich_text ? ui->button_cancel_rich : ui->button_cancel; + QPushButton* right_button = use_rich_text ? ui->button_ok_rich : ui->button_ok_label; + + // TODO (Morph): Handle QTextBrowser text scrolling + // TODO (Morph): focusPrevious/NextChild() doesn't work well with the rich text dialog, fix it + + switch (button) { + case Core::HID::NpadButton::A: + case Core::HID::NpadButton::B: + if (left_button->hasFocus()) { + left_button->click(); + } else if (right_button->hasFocus()) { + right_button->click(); + } + break; + case Core::HID::NpadButton::Left: + case Core::HID::NpadButton::StickLLeft: + focusPreviousChild(); + break; + case Core::HID::NpadButton::Right: + case Core::HID::NpadButton::StickLRight: + focusNextChild(); + break; + default: + break; + } +} + +void OverlayDialog::StartInputThread() { + if (input_thread_running) { + return; + } + + input_thread_running = true; + + input_thread = std::thread(&OverlayDialog::InputThread, this); +} + +void OverlayDialog::StopInputThread() { + input_thread_running = false; + + if (input_thread.joinable()) { + input_thread.join(); + } +} + +void OverlayDialog::InputThread() { + while (input_thread_running) { + input_interpreter->PollInput(); + + HandleButtonPressedOnce(); + + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + } +} + +void OverlayDialog::keyPressEvent(QKeyEvent* e) { + if (!ui->buttonsDialog->isHidden() || e->key() != Qt::Key_Escape) { + QDialog::keyPressEvent(e); + } +} diff --git a/src/sudachi/util/overlay_dialog.h b/src/sudachi/util/overlay_dialog.h new file mode 100644 index 0000000..586a2b5 --- /dev/null +++ b/src/sudachi/util/overlay_dialog.h @@ -0,0 +1,108 @@ +// SPDX-FileCopyrightText: Copyright 2021 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include +#include + +#include + +#include "common/common_types.h" + +class InputInterpreter; + +namespace Core { +class System; +} + +namespace Core::HID { +enum class NpadButton : u64; +} + +namespace Ui { +class OverlayDialog; +} + +/** + * An OverlayDialog is an interactive dialog that accepts controller input (while a game is running) + * This dialog attempts to replicate the look and feel of the Nintendo Switch's overlay dialogs and + * provide some extra features such as embedding HTML/Rich Text content in a QTextBrowser. + * The OverlayDialog provides 2 modes: one to embed regular text into a QLabel and another to embed + * HTML/Rich Text content into a QTextBrowser. + */ +class OverlayDialog final : public QDialog { + Q_OBJECT + +public: + explicit OverlayDialog(QWidget* parent, Core::System& system, const QString& title_text, + const QString& body_text, const QString& left_button_text, + const QString& right_button_text, + Qt::Alignment alignment = Qt::AlignCenter, bool use_rich_text_ = false); + ~OverlayDialog() override; + +private: + /** + * Initializes a text dialog with a QLabel storing text. + * Only use this for short text as the dialog buttons would be squashed with longer text. + * + * @param title_text Title text to be displayed + * @param body_text Main text to be displayed + * @param left_button_text Left button text. If empty, the button is hidden and disabled + * @param right_button_text Right button text. If empty, the button is hidden and disabled + * @param alignment Main text alignment + */ + void InitializeRegularTextDialog(const QString& title_text, const QString& body_text, + const QString& left_button_text, + const QString& right_button_text, Qt::Alignment alignment); + + /** + * Initializes a text dialog with a QTextBrowser storing text. + * This is ideal for longer text or rich text content. A scrollbar is shown for longer text. + * + * @param title_text Title text to be displayed + * @param body_text Main text to be displayed + * @param left_button_text Left button text. If empty, the button is hidden and disabled + * @param right_button_text Right button text. If empty, the button is hidden and disabled + * @param alignment Main text alignment + */ + void InitializeRichTextDialog(const QString& title_text, const QString& body_text, + const QString& left_button_text, const QString& right_button_text, + Qt::Alignment alignment); + + /// Moves and resizes the dialog to be fully overlaid on top of the parent window. + void MoveAndResizeWindow(); + + /** + * Handles button presses and converts them into keyboard input. + * + * @tparam HIDButton The list of buttons that can be converted into keyboard input. + */ + template + void HandleButtonPressedOnce(); + + /** + * Translates a button press to focus or click either the left or right buttons. + * + * @param button The button press to process. + */ + void TranslateButtonPress(Core::HID::NpadButton button); + + void StartInputThread(); + void StopInputThread(); + + /// The thread where input is being polled and processed. + void InputThread(); + void keyPressEvent(QKeyEvent* e) override; + + std::unique_ptr ui; + + bool use_rich_text; + + std::unique_ptr input_interpreter; + + std::thread input_thread; + + std::atomic input_thread_running{}; +}; diff --git a/src/sudachi/util/overlay_dialog.ui b/src/sudachi/util/overlay_dialog.ui new file mode 100644 index 0000000..278e2f2 --- /dev/null +++ b/src/sudachi/util/overlay_dialog.ui @@ -0,0 +1,404 @@ + + + OverlayDialog + + + + 0 + 0 + 1280 + 720 + + + + Dialog + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + 0 + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 14 + + + + Qt::AlignBottom|Qt::AlignLeading|Qt::AlignLeft + + + + + + + + 18 + + + + Qt::AlignCenter + + + true + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 0 + 0 + + + + + 18 + + + + Cancel + + + + + + + + 0 + 0 + + + + + 18 + + + + OK + + + + + + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 14 + + + + + + + Qt::AlignBottom|Qt::AlignLeading|Qt::AlignLeft + + + + + + + + 18 + + + + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:18pt; font-weight:400; font-style:normal;"> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p></body></html> + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 0 + 0 + + + + + 18 + + + + Cancel + + + + + + + + 0 + 0 + + + + + 18 + + + + OK + + + + + + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + + + + + diff --git a/src/sudachi/util/sequence_dialog/sequence_dialog.cpp b/src/sudachi/util/sequence_dialog/sequence_dialog.cpp new file mode 100644 index 0000000..c432439 --- /dev/null +++ b/src/sudachi/util/sequence_dialog/sequence_dialog.cpp @@ -0,0 +1,38 @@ +// SPDX-FileCopyrightText: 2018 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include +#include +#include "sudachi/util/sequence_dialog/sequence_dialog.h" + +SequenceDialog::SequenceDialog(QWidget* parent) : QDialog(parent) { + setWindowTitle(tr("Enter a hotkey")); + + key_sequence = new QKeySequenceEdit; + + auto* const buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); + buttons->setCenterButtons(true); + + auto* const layout = new QVBoxLayout(this); + layout->addWidget(key_sequence); + layout->addWidget(buttons); + + connect(buttons, &QDialogButtonBox::accepted, this, &QDialog::accept); + connect(buttons, &QDialogButtonBox::rejected, this, &QDialog::reject); +} + +SequenceDialog::~SequenceDialog() = default; + +QKeySequence SequenceDialog::GetSequence() const { + // Only the first key is returned. The other 3, if present, are ignored. + return QKeySequence(key_sequence->keySequence()[0]); +} + +bool SequenceDialog::focusNextPrevChild(bool next) { + return false; +} + +void SequenceDialog::closeEvent(QCloseEvent*) { + reject(); +} diff --git a/src/sudachi/util/sequence_dialog/sequence_dialog.h b/src/sudachi/util/sequence_dialog/sequence_dialog.h new file mode 100644 index 0000000..85e146d --- /dev/null +++ b/src/sudachi/util/sequence_dialog/sequence_dialog.h @@ -0,0 +1,23 @@ +// SPDX-FileCopyrightText: 2018 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include + +class QKeySequenceEdit; + +class SequenceDialog : public QDialog { + Q_OBJECT + +public: + explicit SequenceDialog(QWidget* parent = nullptr); + ~SequenceDialog() override; + + QKeySequence GetSequence() const; + void closeEvent(QCloseEvent*) override; + +private: + QKeySequenceEdit* key_sequence; + bool focusNextPrevChild(bool next) override; +}; diff --git a/src/sudachi/util/url_request_interceptor.cpp b/src/sudachi/util/url_request_interceptor.cpp new file mode 100644 index 0000000..d11c986 --- /dev/null +++ b/src/sudachi/util/url_request_interceptor.cpp @@ -0,0 +1,33 @@ +// SPDX-FileCopyrightText: Copyright 2020 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#ifdef SUDACHI_USE_QT_WEB_ENGINE + +#include "sudachi/util/url_request_interceptor.h" + +UrlRequestInterceptor::UrlRequestInterceptor(QObject* p) : QWebEngineUrlRequestInterceptor(p) {} + +UrlRequestInterceptor::~UrlRequestInterceptor() = default; + +void UrlRequestInterceptor::interceptRequest(QWebEngineUrlRequestInfo& info) { + const auto resource_type = info.resourceType(); + + switch (resource_type) { + case QWebEngineUrlRequestInfo::ResourceTypeMainFrame: + requested_url = info.requestUrl(); + emit FrameChanged(); + break; + case QWebEngineUrlRequestInfo::ResourceTypeSubFrame: + case QWebEngineUrlRequestInfo::ResourceTypeXhr: + emit FrameChanged(); + break; + default: + break; + } +} + +QUrl UrlRequestInterceptor::GetRequestedURL() const { + return requested_url; +} + +#endif diff --git a/src/sudachi/util/url_request_interceptor.h b/src/sudachi/util/url_request_interceptor.h new file mode 100644 index 0000000..e81be76 --- /dev/null +++ b/src/sudachi/util/url_request_interceptor.h @@ -0,0 +1,29 @@ +// SPDX-FileCopyrightText: Copyright 2020 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#ifdef SUDACHI_USE_QT_WEB_ENGINE + +#include +#include + +class UrlRequestInterceptor : public QWebEngineUrlRequestInterceptor { + Q_OBJECT + +public: + explicit UrlRequestInterceptor(QObject* p = nullptr); + ~UrlRequestInterceptor() override; + + void interceptRequest(QWebEngineUrlRequestInfo& info) override; + + QUrl GetRequestedURL() const; + +signals: + void FrameChanged(); + +private: + QUrl requested_url; +}; + +#endif diff --git a/src/sudachi/util/util.cpp b/src/sudachi/util/util.cpp new file mode 100644 index 0000000..e0ca49f --- /dev/null +++ b/src/sudachi/util/util.cpp @@ -0,0 +1,152 @@ +// SPDX-FileCopyrightText: 2015 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include +#include + +#include "common/logging/log.h" +#include "sudachi/util/util.h" + +#ifdef _WIN32 +#include +#include "common/fs/file.h" +#endif + +QFont GetMonospaceFont() { + QFont font(QStringLiteral("monospace")); + // Automatic fallback to a monospace font on on platforms without a font called "monospace" + font.setStyleHint(QFont::Monospace); + font.setFixedPitch(true); + return font; +} + +QString ReadableByteSize(qulonglong size) { + static constexpr std::array units{"B", "KiB", "MiB", "GiB", "TiB", "PiB"}; + if (size == 0) { + return QStringLiteral("0"); + } + + const int digit_groups = std::min(static_cast(std::log10(size) / std::log10(1024)), + static_cast(units.size())); + return QStringLiteral("%L1 %2") + .arg(size / std::pow(1024, digit_groups), 0, 'f', 1) + .arg(QString::fromUtf8(units[digit_groups])); +} + +QPixmap CreateCirclePixmapFromColor(const QColor& color) { + QPixmap circle_pixmap(16, 16); + circle_pixmap.fill(Qt::transparent); + QPainter painter(&circle_pixmap); + painter.setRenderHint(QPainter::Antialiasing); + painter.setPen(color); + painter.setBrush(color); + painter.drawEllipse({circle_pixmap.width() / 2.0, circle_pixmap.height() / 2.0}, 7.0, 7.0); + return circle_pixmap; +} + +bool SaveIconToFile(const std::filesystem::path& icon_path, const QImage& image) { +#if defined(WIN32) +#pragma pack(push, 2) + struct IconDir { + WORD id_reserved; + WORD id_type; + WORD id_count; + }; + + struct IconDirEntry { + BYTE width; + BYTE height; + BYTE color_count; + BYTE reserved; + WORD planes; + WORD bit_count; + DWORD bytes_in_res; + DWORD image_offset; + }; +#pragma pack(pop) + + const QImage source_image = image.convertToFormat(QImage::Format_RGB32); + constexpr std::array scale_sizes{256, 128, 64, 48, 32, 24, 16}; + constexpr int bytes_per_pixel = 4; + + const IconDir icon_dir{ + .id_reserved = 0, + .id_type = 1, + .id_count = static_cast(scale_sizes.size()), + }; + + Common::FS::IOFile icon_file(icon_path.string(), Common::FS::FileAccessMode::Write, + Common::FS::FileType::BinaryFile); + if (!icon_file.IsOpen()) { + return false; + } + + if (!icon_file.Write(icon_dir)) { + return false; + } + + std::size_t image_offset = sizeof(IconDir) + (sizeof(IconDirEntry) * scale_sizes.size()); + for (std::size_t i = 0; i < scale_sizes.size(); i++) { + const int image_size = scale_sizes[i] * scale_sizes[i] * bytes_per_pixel; + const IconDirEntry icon_entry{ + .width = static_cast(scale_sizes[i]), + .height = static_cast(scale_sizes[i]), + .color_count = 0, + .reserved = 0, + .planes = 1, + .bit_count = bytes_per_pixel * 8, + .bytes_in_res = static_cast(sizeof(BITMAPINFOHEADER) + image_size), + .image_offset = static_cast(image_offset), + }; + image_offset += icon_entry.bytes_in_res; + if (!icon_file.Write(icon_entry)) { + return false; + } + } + + for (std::size_t i = 0; i < scale_sizes.size(); i++) { + const QImage scaled_image = source_image.scaled( + scale_sizes[i], scale_sizes[i], Qt::IgnoreAspectRatio, Qt::SmoothTransformation); + const BITMAPINFOHEADER info_header{ + .biSize = sizeof(BITMAPINFOHEADER), + .biWidth = scaled_image.width(), + .biHeight = scaled_image.height() * 2, + .biPlanes = 1, + .biBitCount = bytes_per_pixel * 8, + .biCompression = BI_RGB, + .biSizeImage{}, + .biXPelsPerMeter{}, + .biYPelsPerMeter{}, + .biClrUsed{}, + .biClrImportant{}, + }; + + if (!icon_file.Write(info_header)) { + return false; + } + + for (int y = 0; y < scaled_image.height(); y++) { + const auto* line = scaled_image.scanLine(scaled_image.height() - 1 - y); + std::vector line_data(scaled_image.width() * bytes_per_pixel); + std::memcpy(line_data.data(), line, line_data.size()); + if (!icon_file.Write(line_data)) { + return false; + } + } + } + icon_file.Close(); + + return true; +#elif defined(__linux__) || defined(__FreeBSD__) + // Convert and write the icon as a PNG + if (!image.save(QString::fromStdString(icon_path.string()))) { + LOG_ERROR(Frontend, "Could not write icon as PNG to file"); + } else { + LOG_INFO(Frontend, "Wrote an icon to {}", icon_path.string()); + } + return true; +#else + return false; +#endif +} diff --git a/src/sudachi/util/util.h b/src/sudachi/util/util.h new file mode 100644 index 0000000..4094cf6 --- /dev/null +++ b/src/sudachi/util/util.h @@ -0,0 +1,29 @@ +// SPDX-FileCopyrightText: 2015 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include +#include + +/// Returns a QFont object appropriate to use as a monospace font for debugging widgets, etc. +[[nodiscard]] QFont GetMonospaceFont(); + +/// Convert a size in bytes into a readable format (KiB, MiB, etc.) +[[nodiscard]] QString ReadableByteSize(qulonglong size); + +/** + * Creates a circle pixmap from a specified color + * @param color The color the pixmap shall have + * @return QPixmap circle pixmap + */ +[[nodiscard]] QPixmap CreateCirclePixmapFromColor(const QColor& color); + +/** + * Saves a windows icon to a file + * @param path The icons path + * @param image The image to save + * @return bool If the operation succeeded + */ +[[nodiscard]] bool SaveIconToFile(const std::filesystem::path& icon_path, const QImage& image); diff --git a/src/sudachi/vk_device_info.cpp b/src/sudachi/vk_device_info.cpp new file mode 100644 index 0000000..e586516 --- /dev/null +++ b/src/sudachi/vk_device_info.cpp @@ -0,0 +1,67 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include + +#include "sudachi/qt_common.h" + +#include "common/dynamic_library.h" +#include "common/logging/log.h" +#include "video_core/vulkan_common/vulkan_device.h" +#include "video_core/vulkan_common/vulkan_instance.h" +#include "video_core/vulkan_common/vulkan_library.h" +#include "video_core/vulkan_common/vulkan_surface.h" +#include "video_core/vulkan_common/vulkan_wrapper.h" +#include "vulkan/vulkan_core.h" +#include "sudachi/vk_device_info.h" + +class QWindow; + +namespace VkDeviceInfo { +Record::Record(std::string_view name_, const std::vector& vsync_modes_, + bool has_broken_compute_) + : name{name_}, vsync_support{vsync_modes_}, has_broken_compute{has_broken_compute_} {} + +Record::~Record() = default; + +void PopulateRecords(std::vector& records, QWindow* window) try { + using namespace Vulkan; + + // Create a test window with a Vulkan surface type for checking present modes. + QWindow test_window(window); + test_window.setSurfaceType(QWindow::VulkanSurface); + test_window.create(); + auto wsi = QtCommon::GetWindowSystemInfo(&test_window); + + vk::InstanceDispatch dld; + const auto library = OpenLibrary(); + const vk::Instance instance = CreateInstance(*library, dld, VK_API_VERSION_1_1, wsi.type); + const std::vector physical_devices = instance.EnumeratePhysicalDevices(); + vk::SurfaceKHR surface = CreateSurface(instance, wsi); + + records.clear(); + records.reserve(physical_devices.size()); + for (const VkPhysicalDevice device : physical_devices) { + const auto physical_device = vk::PhysicalDevice(device, dld); + const std::string name = physical_device.GetProperties().deviceName; + const std::vector present_modes = + physical_device.GetSurfacePresentModesKHR(*surface); + + VkPhysicalDeviceDriverProperties driver_properties{}; + driver_properties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES; + driver_properties.pNext = nullptr; + VkPhysicalDeviceProperties2 properties{}; + properties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2_KHR; + properties.pNext = &driver_properties; + dld.vkGetPhysicalDeviceProperties2(physical_device, &properties); + + bool has_broken_compute{Vulkan::Device::CheckBrokenCompute( + driver_properties.driverID, properties.properties.driverVersion)}; + + records.push_back(VkDeviceInfo::Record(name, present_modes, has_broken_compute)); + } +} catch (const Vulkan::vk::Exception& exception) { + LOG_ERROR(Frontend, "Failed to enumerate devices with error: {}", exception.what()); +} +} // namespace VkDeviceInfo diff --git a/src/sudachi/vk_device_info.h b/src/sudachi/vk_device_info.h new file mode 100644 index 0000000..1818865 --- /dev/null +++ b/src/sudachi/vk_device_info.h @@ -0,0 +1,36 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include +#include +#include +#include +#include +#include "common/common_types.h" +#include "vulkan/vulkan_core.h" + +class QWindow; + +namespace Settings { +enum class VSyncMode : u32; +} +// #include "common/settings.h" + +namespace VkDeviceInfo { +// Short class to record Vulkan driver information for configuration purposes +class Record { +public: + explicit Record(std::string_view name, const std::vector& vsync_modes, + bool has_broken_compute); + ~Record(); + + const std::string name; + const std::vector vsync_support; + const bool has_broken_compute; +}; + +void PopulateRecords(std::vector& records, QWindow* window); +} // namespace VkDeviceInfo diff --git a/src/sudachi_cmd/CMakeLists.txt b/src/sudachi_cmd/CMakeLists.txt new file mode 100644 index 0000000..9be012c --- /dev/null +++ b/src/sudachi_cmd/CMakeLists.txt @@ -0,0 +1,65 @@ +# SPDX-FileCopyrightText: 2018 sudachi Emulator Project +# SPDX-License-Identifier: GPL-2.0-or-later + +# Credits to Samantas5855 and others for this function. +function(create_resource file output filename) + # Read hex data from file + file(READ ${file} filedata HEX) + # Convert hex data for C compatibility + string(REGEX REPLACE "([0-9a-f][0-9a-f])" "0x\\1," filedata ${filedata}) + # Write data to output file + set(RESOURCES_DIR "${PROJECT_BINARY_DIR}/dist" PARENT_SCOPE) + file(WRITE "${PROJECT_BINARY_DIR}/dist/${output}" "const unsigned char ${filename}[] = {${filedata}};\nconst unsigned ${filename}_size = sizeof(${filename});\n") +endfunction() + +add_executable(sudachi-cmd + emu_window/emu_window_sdl2.cpp + emu_window/emu_window_sdl2.h + emu_window/emu_window_sdl2_gl.cpp + emu_window/emu_window_sdl2_gl.h + emu_window/emu_window_sdl2_null.cpp + emu_window/emu_window_sdl2_null.h + emu_window/emu_window_sdl2_vk.cpp + emu_window/emu_window_sdl2_vk.h + precompiled_headers.h + sdl_config.cpp + sdl_config.h + sudachi.cpp + sudachi.rc +) + +target_link_libraries(sudachi-cmd PRIVATE common core input_common frontend_common) +target_link_libraries(sudachi-cmd PRIVATE glad) +if (MSVC) + target_link_libraries(sudachi-cmd PRIVATE getopt) +endif() +target_link_libraries(sudachi-cmd PRIVATE ${PLATFORM_LIBRARIES} Threads::Threads) + +create_resource("../../dist/sudachi.bmp" "sudachi_cmd/sudachi_icon.h" "sudachi_icon") +target_include_directories(sudachi-cmd PRIVATE ${RESOURCES_DIR}) + +target_link_libraries(sudachi-cmd PRIVATE SDL2::SDL2 Vulkan::Headers) + +if(UNIX AND NOT APPLE) + install(TARGETS sudachi-cmd) +endif() + +if(WIN32) + # compile as a win32 gui application instead of a console application + if(MSVC) + set_target_properties(sudachi-cmd PROPERTIES LINK_FLAGS_RELEASE "/SUBSYSTEM:WINDOWS /ENTRY:mainCRTStartup") + elseif(MINGW) + set_target_properties(sudachi-cmd PROPERTIES LINK_FLAGS_RELEASE "-Wl,--subsystem,windows") + endif() +endif() + +if (MSVC) + include(CopySudachiSDLDeps) + copy_sudachi_SDL_deps(sudachi-cmd) +endif() + +if (SUDACHI_USE_PRECOMPILED_HEADERS) + target_precompile_headers(sudachi-cmd PRIVATE precompiled_headers.h) +endif() + +create_target_directory_groups(sudachi-cmd) diff --git a/src/sudachi_cmd/config.cpp b/src/sudachi_cmd/config.cpp new file mode 100644 index 0000000..f8fc0f3 --- /dev/null +++ b/src/sudachi_cmd/config.cpp @@ -0,0 +1,279 @@ +// SPDX-FileCopyrightText: 2014 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include +#include +#include +#include +#include "common/fs/file.h" +#include "common/fs/fs.h" +#include "common/fs/path_util.h" +#include "common/logging/log.h" +#include "common/settings.h" +#include "core/hle/service/acc/profile_manager.h" +#include "input_common/main.h" +#include "sudachi_cmd/config.h" +#include "sudachi_cmd/default_ini.h" + +namespace FS = Common::FS; + +const std::filesystem::path default_config_path = + FS::GetSudachiPath(FS::SudachiPath::ConfigDir) / "sdl2-config.ini"; + +Config::Config(std::optional config_path) + : sdl2_config_loc{config_path.value_or(default_config_path)}, + sdl2_config{std::make_unique(FS::PathToUTF8String(sdl2_config_loc))} { + Reload(); +} + +Config::~Config() = default; + +bool Config::LoadINI(const std::string& default_contents, bool retry) { + const auto config_loc_str = FS::PathToUTF8String(sdl2_config_loc); + if (sdl2_config->ParseError() < 0) { + if (retry) { + LOG_WARNING(Config, "Failed to load {}. Creating file from defaults...", + config_loc_str); + + void(FS::CreateParentDir(sdl2_config_loc)); + void(FS::WriteStringToFile(sdl2_config_loc, FS::FileType::TextFile, default_contents)); + + sdl2_config = std::make_unique(config_loc_str); + + return LoadINI(default_contents, false); + } + LOG_ERROR(Config, "Failed."); + return false; + } + LOG_INFO(Config, "Successfully loaded {}", config_loc_str); + return true; +} + +static const std::array default_buttons = { + SDL_SCANCODE_A, SDL_SCANCODE_S, SDL_SCANCODE_Z, SDL_SCANCODE_X, SDL_SCANCODE_T, + SDL_SCANCODE_G, SDL_SCANCODE_F, SDL_SCANCODE_H, SDL_SCANCODE_Q, SDL_SCANCODE_W, + SDL_SCANCODE_M, SDL_SCANCODE_N, SDL_SCANCODE_1, SDL_SCANCODE_2, SDL_SCANCODE_B, +}; + +static const std::array default_motions = { + SDL_SCANCODE_7, + SDL_SCANCODE_8, +}; + +static const std::array, Settings::NativeAnalog::NumAnalogs> default_analogs{{ + { + SDL_SCANCODE_UP, + SDL_SCANCODE_DOWN, + SDL_SCANCODE_LEFT, + SDL_SCANCODE_RIGHT, + SDL_SCANCODE_D, + }, + { + SDL_SCANCODE_I, + SDL_SCANCODE_K, + SDL_SCANCODE_J, + SDL_SCANCODE_L, + SDL_SCANCODE_D, + }, +}}; + +template <> +void Config::ReadSetting(const std::string& group, Settings::Setting& setting) { + std::string setting_value = sdl2_config->Get(group, setting.GetLabel(), setting.GetDefault()); + if (setting_value.empty()) { + setting_value = setting.GetDefault(); + } + setting = std::move(setting_value); +} + +template <> +void Config::ReadSetting(const std::string& group, Settings::Setting& setting) { + setting = sdl2_config->GetBoolean(group, setting.GetLabel(), setting.GetDefault()); +} + +template +void Config::ReadSetting(const std::string& group, Settings::Setting& setting) { + setting = static_cast(sdl2_config->GetInteger(group, setting.GetLabel(), + static_cast(setting.GetDefault()))); +} + +void Config::ReadCategory(Settings::Category category) { + for (const auto setting : Settings::values.linkage.by_category[category]) { + const char* category_name = [&]() { + if (category == Settings::Category::Controls) { + // For compatibility with older configs + return "ControlsGeneral"; + } else { + return Settings::TranslateCategory(category); + } + }(); + std::string setting_value = + sdl2_config->Get(category_name, setting->GetLabel(), setting->DefaultToString()); + setting->LoadString(setting_value); + } +} + +void Config::ReadValues() { + // Controls + ReadCategory(Settings::Category::Controls); + + for (std::size_t p = 0; p < Settings::values.players.GetValue().size(); ++p) { + auto& player = Settings::values.players.GetValue()[p]; + + const auto group = fmt::format("ControlsP{}", p); + for (int i = 0; i < Settings::NativeButton::NumButtons; ++i) { + std::string default_param = InputCommon::GenerateKeyboardParam(default_buttons[i]); + player.buttons[i] = + sdl2_config->Get(group, Settings::NativeButton::mapping[i], default_param); + if (player.buttons[i].empty()) { + player.buttons[i] = default_param; + } + } + + for (int i = 0; i < Settings::NativeAnalog::NumAnalogs; ++i) { + std::string default_param = InputCommon::GenerateAnalogParamFromKeys( + default_analogs[i][0], default_analogs[i][1], default_analogs[i][2], + default_analogs[i][3], default_analogs[i][4], 0.5f); + player.analogs[i] = + sdl2_config->Get(group, Settings::NativeAnalog::mapping[i], default_param); + if (player.analogs[i].empty()) { + player.analogs[i] = default_param; + } + } + + for (int i = 0; i < Settings::NativeMotion::NumMotions; ++i) { + const std::string default_param = + InputCommon::GenerateKeyboardParam(default_motions[i]); + auto& player_motions = player.motions[i]; + + player_motions = + sdl2_config->Get(group, Settings::NativeMotion::mapping[i], default_param); + if (player_motions.empty()) { + player_motions = default_param; + } + } + + player.connected = sdl2_config->GetBoolean(group, "connected", false); + } + + for (int i = 0; i < Settings::NativeButton::NumButtons; ++i) { + std::string default_param = InputCommon::GenerateKeyboardParam(default_buttons[i]); + Settings::values.debug_pad_buttons[i] = sdl2_config->Get( + "ControlsGeneral", std::string("debug_pad_") + Settings::NativeButton::mapping[i], + default_param); + if (Settings::values.debug_pad_buttons[i].empty()) + Settings::values.debug_pad_buttons[i] = default_param; + } + + for (int i = 0; i < Settings::NativeAnalog::NumAnalogs; ++i) { + std::string default_param = InputCommon::GenerateAnalogParamFromKeys( + default_analogs[i][0], default_analogs[i][1], default_analogs[i][2], + default_analogs[i][3], default_analogs[i][4], 0.5f); + Settings::values.debug_pad_analogs[i] = sdl2_config->Get( + "ControlsGeneral", std::string("debug_pad_") + Settings::NativeAnalog::mapping[i], + default_param); + if (Settings::values.debug_pad_analogs[i].empty()) + Settings::values.debug_pad_analogs[i] = default_param; + } + + Settings::values.touchscreen.enabled = + sdl2_config->GetBoolean("ControlsGeneral", "touch_enabled", true); + Settings::values.touchscreen.rotation_angle = + sdl2_config->GetInteger("ControlsGeneral", "touch_angle", 0); + Settings::values.touchscreen.diameter_x = + sdl2_config->GetInteger("ControlsGeneral", "touch_diameter_x", 15); + Settings::values.touchscreen.diameter_y = + sdl2_config->GetInteger("ControlsGeneral", "touch_diameter_y", 15); + + int num_touch_from_button_maps = + sdl2_config->GetInteger("ControlsGeneral", "touch_from_button_map", 0); + if (num_touch_from_button_maps > 0) { + for (int i = 0; i < num_touch_from_button_maps; ++i) { + Settings::TouchFromButtonMap map; + map.name = sdl2_config->Get("ControlsGeneral", + std::string("touch_from_button_maps_") + std::to_string(i) + + std::string("_name"), + "default"); + const int num_touch_maps = sdl2_config->GetInteger( + "ControlsGeneral", + std::string("touch_from_button_maps_") + std::to_string(i) + std::string("_count"), + 0); + map.buttons.reserve(num_touch_maps); + + for (int j = 0; j < num_touch_maps; ++j) { + std::string touch_mapping = + sdl2_config->Get("ControlsGeneral", + std::string("touch_from_button_maps_") + std::to_string(i) + + std::string("_bind_") + std::to_string(j), + ""); + map.buttons.emplace_back(std::move(touch_mapping)); + } + + Settings::values.touch_from_button_maps.emplace_back(std::move(map)); + } + } else { + Settings::values.touch_from_button_maps.emplace_back( + Settings::TouchFromButtonMap{"default", {}}); + num_touch_from_button_maps = 1; + } + Settings::values.touch_from_button_map_index = std::clamp( + Settings::values.touch_from_button_map_index.GetValue(), 0, num_touch_from_button_maps - 1); + + ReadCategory(Settings::Category::Audio); + ReadCategory(Settings::Category::Core); + ReadCategory(Settings::Category::Cpu); + ReadCategory(Settings::Category::CpuDebug); + ReadCategory(Settings::Category::CpuUnsafe); + ReadCategory(Settings::Category::Renderer); + ReadCategory(Settings::Category::RendererAdvanced); + ReadCategory(Settings::Category::RendererDebug); + ReadCategory(Settings::Category::System); + ReadCategory(Settings::Category::SystemAudio); + ReadCategory(Settings::Category::DataStorage); + ReadCategory(Settings::Category::Debugging); + ReadCategory(Settings::Category::DebuggingGraphics); + ReadCategory(Settings::Category::Miscellaneous); + ReadCategory(Settings::Category::Network); + ReadCategory(Settings::Category::WebService); + + // Data Storage + FS::SetSudachiPath(FS::SudachiPath::NANDDir, + sdl2_config->Get("Data Storage", "nand_directory", + FS::GetSudachiPathString(FS::SudachiPath::NANDDir))); + FS::SetSudachiPath(FS::SudachiPath::SDMCDir, + sdl2_config->Get("Data Storage", "sdmc_directory", + FS::GetSudachiPathString(FS::SudachiPath::SDMCDir))); + FS::SetSudachiPath(FS::SudachiPath::LoadDir, + sdl2_config->Get("Data Storage", "load_directory", + FS::GetSudachiPathString(FS::SudachiPath::LoadDir))); + FS::SetSudachiPath(FS::SudachiPath::DumpDir, + sdl2_config->Get("Data Storage", "dump_directory", + FS::GetSudachiPathString(FS::SudachiPath::DumpDir))); + + // Debugging + Settings::values.record_frame_times = + sdl2_config->GetBoolean("Debugging", "record_frame_times", false); + + const auto title_list = sdl2_config->Get("AddOns", "title_ids", ""); + std::stringstream ss(title_list); + std::string line; + while (std::getline(ss, line, '|')) { + const auto title_id = std::strtoul(line.c_str(), nullptr, 16); + const auto disabled_list = sdl2_config->Get("AddOns", "disabled_" + line, ""); + + std::stringstream inner_ss(disabled_list); + std::string inner_line; + std::vector out; + while (std::getline(inner_ss, inner_line, '|')) { + out.push_back(inner_line); + } + + Settings::values.disabled_addons.insert_or_assign(title_id, out); + } +} + +void Config::Reload() { + LoadINI(DefaultINI::sdl2_config_file); + ReadValues(); +} diff --git a/src/sudachi_cmd/config.h b/src/sudachi_cmd/config.h new file mode 100644 index 0000000..cbcfb55 --- /dev/null +++ b/src/sudachi_cmd/config.h @@ -0,0 +1,38 @@ +// SPDX-FileCopyrightText: 2014 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include +#include +#include + +#include "common/settings.h" + +class INIReader; + +class Config { + std::filesystem::path sdl2_config_loc; + std::unique_ptr sdl2_config; + + bool LoadINI(const std::string& default_contents = "", bool retry = true); + void ReadValues(); + +public: + explicit Config(std::optional config_path); + ~Config(); + + void Reload(); + +private: + /** + * Applies a value read from the sdl2_config to a Setting. + * + * @param group The name of the INI group + * @param setting The sudachi setting to modify + */ + template + void ReadSetting(const std::string& group, Settings::Setting& setting); + void ReadCategory(Settings::Category category); +}; diff --git a/src/sudachi_cmd/default_ini.h b/src/sudachi_cmd/default_ini.h new file mode 100644 index 0000000..6c412c0 --- /dev/null +++ b/src/sudachi_cmd/default_ini.h @@ -0,0 +1,553 @@ +// SPDX-FileCopyrightText: 2014 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +namespace DefaultINI { + +const char* sdl2_config_file = + R"( +[ControlsP0] +# The input devices and parameters for each Switch native input +# The config section determines the player number where the config will be applied on. For example "ControlsP0", "ControlsP1", ... +# It should be in the format of "engine:[engine_name],[param1]:[value1],[param2]:[value2]..." +# Escape characters $0 (for ':'), $1 (for ',') and $2 (for '$') can be used in values + +# Indicates if this player should be connected at boot +# 0 (default): Disabled, 1: Enabled +connected= + +# for button input, the following devices are available: +# - "keyboard" (default) for keyboard input. Required parameters: +# - "code": the code of the key to bind +# - "sdl" for joystick input using SDL. Required parameters: +# - "guid": SDL identification GUID of the joystick +# - "port": the index of the joystick to bind +# - "button"(optional): the index of the button to bind +# - "hat"(optional): the index of the hat to bind as direction buttons +# - "axis"(optional): the index of the axis to bind +# - "direction"(only used for hat): the direction name of the hat to bind. Can be "up", "down", "left" or "right" +# - "threshold"(only used for axis): a float value in (-1.0, 1.0) which the button is +# triggered if the axis value crosses +# - "direction"(only used for axis): "+" means the button is triggered when the axis value +# is greater than the threshold; "-" means the button is triggered when the axis value +# is smaller than the threshold +button_a= +button_b= +button_x= +button_y= +button_lstick= +button_rstick= +button_l= +button_r= +button_zl= +button_zr= +button_plus= +button_minus= +button_dleft= +button_dup= +button_dright= +button_ddown= +button_lstick_left= +button_lstick_up= +button_lstick_right= +button_lstick_down= +button_sl= +button_sr= +button_home= +button_screenshot= + +# for analog input, the following devices are available: +# - "analog_from_button" (default) for emulating analog input from direction buttons. Required parameters: +# - "up", "down", "left", "right": sub-devices for each direction. +# Should be in the format as a button input devices using escape characters, for example, "engine$0keyboard$1code$00" +# - "modifier": sub-devices as a modifier. +# - "modifier_scale": a float number representing the applied modifier scale to the analog input. +# Must be in range of 0.0-1.0. Defaults to 0.5 +# - "sdl" for joystick input using SDL. Required parameters: +# - "guid": SDL identification GUID of the joystick +# - "port": the index of the joystick to bind +# - "axis_x": the index of the axis to bind as x-axis (default to 0) +# - "axis_y": the index of the axis to bind as y-axis (default to 1) +lstick= +rstick= + +# for motion input, the following devices are available: +# - "keyboard" (default) for emulating random motion input from buttons. Required parameters: +# - "code": the code of the key to bind +# - "sdl" for motion input using SDL. Required parameters: +# - "guid": SDL identification GUID of the joystick +# - "port": the index of the joystick to bind +# - "motion": the index of the motion sensor to bind +# - "cemuhookudp" for motion input using Cemu Hook protocol. Required parameters: +# - "guid": the IP address of the cemu hook server encoded to a hex string. for example 192.168.0.1 = "c0a80001" +# - "port": the port of the cemu hook server +# - "pad": the index of the joystick +# - "motion": the index of the motion sensor of the joystick to bind +motionleft= +motionright= + +[ControlsGeneral] +# To use the debug_pad, prepend `debug_pad_` before each button setting above. +# i.e. debug_pad_button_a= + +# Enable debug pad inputs to the guest +# 0 (default): Disabled, 1: Enabled +debug_pad_enabled = + +# Enable sdl raw input. Allows to configure up to 8 xinput controllers. +# 0 (default): Disabled, 1: Enabled +enable_raw_input = + +# Enable sudachi joycon driver instead of SDL drive. +# 0: Disabled, 1 (default): Enabled +enable_joycon_driver = + +# Emulates an analog input from buttons. Allowing to dial any angle. +# 0 (default): Disabled, 1: Enabled +emulate_analog_keyboard = + +# Whether to enable or disable vibration +# 0: Disabled, 1 (default): Enabled +vibration_enabled= + +# Whether to enable or disable accurate vibrations +# 0 (default): Disabled, 1: Enabled +enable_accurate_vibrations= + +# Enables controller motion inputs +# 0: Disabled, 1 (default): Enabled +motion_enabled = + +# Defines the udp device's touch screen coordinate system for cemuhookudp devices +# - "min_x", "min_y", "max_x", "max_y" +touch_device= + +# for mapping buttons to touch inputs. +#touch_from_button_map=1 +#touch_from_button_maps_0_name=default +#touch_from_button_maps_0_count=2 +#touch_from_button_maps_0_bind_0=foo +#touch_from_button_maps_0_bind_1=bar +# etc. + +# List of Cemuhook UDP servers, delimited by ','. +# Default: 127.0.0.1:26760 +# Example: 127.0.0.1:26760,123.4.5.67:26761 +udp_input_servers = + +# Enable controlling an axis via a mouse input. +# 0 (default): Off, 1: On +mouse_panning = + +# Set mouse panning horizontal sensitivity. +# Default: 50.0 +mouse_panning_x_sensitivity = + +# Set mouse panning vertical sensitivity. +# Default: 50.0 +mouse_panning_y_sensitivity = + +# Set mouse panning deadzone horizontal counterweight. +# Default: 0.0 +mouse_panning_deadzone_x_counterweight = + +# Set mouse panning deadzone vertical counterweight. +# Default: 0.0 +mouse_panning_deadzone_y_counterweight = + +# Set mouse panning stick decay strength. +# Default: 22.0 +mouse_panning_decay_strength = + +# Set mouse panning stick minimum decay. +# Default: 5.0 +mouse_panning_minimum_decay = + +# Emulate an analog control stick from keyboard inputs. +# 0 (default): Disabled, 1: Enabled +emulate_analog_keyboard = + +# Enable mouse inputs to the guest +# 0 (default): Disabled, 1: Enabled +mouse_enabled = + +# Enable keyboard inputs to the guest +# 0 (default): Disabled, 1: Enabled +keyboard_enabled = + +)" + R"( +[Core] +# Whether to use multi-core for CPU emulation +# 0: Disabled, 1 (default): Enabled +use_multi_core = + +# Enable unsafe extended guest system memory layout (8GB DRAM) +# 0 (default): Disabled, 1: Enabled +use_unsafe_extended_memory_layout = + +[Cpu] +# Adjusts various optimizations. +# Auto-select mode enables choice unsafe optimizations. +# Accurate enables only safe optimizations. +# Unsafe allows any unsafe optimizations. +# 0 (default): Auto-select, 1: Accurate, 2: Enable unsafe optimizations +cpu_accuracy = + +# Allow disabling safe optimizations. +# 0 (default): Disabled, 1: Enabled +cpu_debug_mode = + +# Enable inline page tables optimization (faster guest memory access) +# 0: Disabled, 1 (default): Enabled +cpuopt_page_tables = + +# Enable block linking CPU optimization (reduce block dispatcher use during predictable jumps) +# 0: Disabled, 1 (default): Enabled +cpuopt_block_linking = + +# Enable return stack buffer CPU optimization (reduce block dispatcher use during predictable returns) +# 0: Disabled, 1 (default): Enabled +cpuopt_return_stack_buffer = + +# Enable fast dispatcher CPU optimization (use a two-tiered dispatcher architecture) +# 0: Disabled, 1 (default): Enabled +cpuopt_fast_dispatcher = + +# Enable context elimination CPU Optimization (reduce host memory use for guest context) +# 0: Disabled, 1 (default): Enabled +cpuopt_context_elimination = + +# Enable constant propagation CPU optimization (basic IR optimization) +# 0: Disabled, 1 (default): Enabled +cpuopt_const_prop = + +# Enable miscellaneous CPU optimizations (basic IR optimization) +# 0: Disabled, 1 (default): Enabled +cpuopt_misc_ir = + +# Enable reduction of memory misalignment checks (reduce memory fallbacks for misaligned access) +# 0: Disabled, 1 (default): Enabled +cpuopt_reduce_misalign_checks = + +# Enable Host MMU Emulation (faster guest memory access) +# 0: Disabled, 1 (default): Enabled +cpuopt_fastmem = + +# Enable Host MMU Emulation for exclusive memory instructions (faster guest memory access) +# 0: Disabled, 1 (default): Enabled +cpuopt_fastmem_exclusives = + +# Enable fallback on failure of fastmem of exclusive memory instructions (faster guest memory access) +# 0: Disabled, 1 (default): Enabled +cpuopt_recompile_exclusives = + +# Enable optimization to ignore invalid memory accesses (faster guest memory access) +# 0: Disabled, 1 (default): Enabled +cpuopt_ignore_memory_aborts = + +# Enable unfuse FMA (improve performance on CPUs without FMA) +# Only enabled if cpu_accuracy is set to Unsafe. Automatically chosen with cpu_accuracy = Auto-select. +# 0: Disabled, 1 (default): Enabled +cpuopt_unsafe_unfuse_fma = + +# Enable faster FRSQRTE and FRECPE +# Only enabled if cpu_accuracy is set to Unsafe. +# 0: Disabled, 1 (default): Enabled +cpuopt_unsafe_reduce_fp_error = + +# Enable faster ASIMD instructions (32 bits only) +# Only enabled if cpu_accuracy is set to Unsafe. Automatically chosen with cpu_accuracy = Auto-select. +# 0: Disabled, 1 (default): Enabled +cpuopt_unsafe_ignore_standard_fpcr = + +# Enable inaccurate NaN handling +# Only enabled if cpu_accuracy is set to Unsafe. Automatically chosen with cpu_accuracy = Auto-select. +# 0: Disabled, 1 (default): Enabled +cpuopt_unsafe_inaccurate_nan = + +# Disable address space checks (64 bits only) +# Only enabled if cpu_accuracy is set to Unsafe. Automatically chosen with cpu_accuracy = Auto-select. +# 0: Disabled, 1 (default): Enabled +cpuopt_unsafe_fastmem_check = + +# Enable faster exclusive instructions +# Only enabled if cpu_accuracy is set to Unsafe. Automatically chosen with cpu_accuracy = Auto-select. +# 0: Disabled, 1 (default): Enabled +cpuopt_unsafe_ignore_global_monitor = + +)" + R"( +[Renderer] +# Which backend API to use. +# 0: OpenGL, 1 (default): Vulkan +backend = + +# Whether to enable asynchronous presentation (Vulkan only) +# 0 (default): Off, 1: On +async_presentation = + +# Enable graphics API debugging mode. +# 0 (default): Disabled, 1: Enabled +debug = + +# Enable shader feedback. +# 0 (default): Disabled, 1: Enabled +renderer_shader_feedback = + +# Enable Nsight Aftermath crash dumps +# 0 (default): Disabled, 1: Enabled +nsight_aftermath = + +# Disable shader loop safety checks, executing the shader without loop logic changes +# 0 (default): Disabled, 1: Enabled +disable_shader_loop_safety_checks = + +# Which Vulkan physical device to use (defaults to 0) +vulkan_device = + +# 0: 0.5x (360p/540p) [EXPERIMENTAL] +# 1: 0.75x (540p/810p) [EXPERIMENTAL] +# 2 (default): 1x (720p/1080p) +# 3: 1.5x (1080p/1620p) [EXPERIMENTAL] +# 4: 2x (1440p/2160p) +# 5: 3x (2160p/3240p) +# 6: 4x (2880p/4320p) +# 7: 5x (3600p/5400p) +# 8: 6x (4320p/6480p) +# 9: 7x (5040p/7560p) +# 10: 8x (5760/8640p) +resolution_setup = + +# Pixel filter to use when up- or down-sampling rendered frames. +# 0: Nearest Neighbor +# 1 (default): Bilinear +# 2: Bicubic +# 3: Gaussian +# 4: ScaleForce +# 5: AMD FidelityFX™️ Super Resolution +scaling_filter = + +# Anti-Aliasing (AA) +# 0 (default): None, 1: FXAA, 2: SMAA +anti_aliasing = + +# Whether to use fullscreen or borderless window mode +# 0 (Windows default): Borderless window, 1 (All other default): Exclusive fullscreen +fullscreen_mode = + +# Aspect ratio +# 0: Default (16:9), 1: Force 4:3, 2: Force 21:9, 3: Force 16:10, 4: Stretch to Window +aspect_ratio = + +# Anisotropic filtering +# 0: Default, 1: 2x, 2: 4x, 3: 8x, 4: 16x +max_anisotropy = + +# Whether to enable VSync or not. +# OpenGL: Values other than 0 enable VSync +# Vulkan: FIFO is selected if the requested mode is not supported by the driver. +# FIFO (VSync) does not drop frames or exhibit tearing but is limited by the screen refresh rate. +# FIFO Relaxed is similar to FIFO but allows tearing as it recovers from a slow down. +# Mailbox can have lower latency than FIFO and does not tear but may drop frames. +# Immediate (no synchronization) just presents whatever is available and can exhibit tearing. +# 0: Immediate (Off), 1: Mailbox, 2 (Default): FIFO (On), 3: FIFO Relaxed +use_vsync = + +# Selects the OpenGL shader backend. NV_gpu_program5 is required for GLASM. If NV_gpu_program5 is +# not available and GLASM is selected, GLSL will be used. +# 0: GLSL, 1 (default): GLASM, 2: SPIR-V +shader_backend = + +# Uses reactive flushing instead of predictive flushing. Allowing a more accurate syncing of memory. +# 0: Off, 1 (default): On +use_reactive_flushing = + +# Whether to allow asynchronous shader building. +# 0 (default): Off, 1: On +use_asynchronous_shaders = + +# NVDEC emulation. +# 0: Disabled, 1: CPU Decoding, 2 (default): GPU Decoding +nvdec_emulation = + +# Accelerate ASTC texture decoding. +# 0: Off, 1 (default): On +accelerate_astc = + +# Decode ASTC textures asynchronously. +# 0 (default): Off, 1: On +async_astc = + +# Recompress ASTC textures to a different format. +# 0 (default): Uncompressed, 1: BC1 (Low quality), 2: BC3: (Medium quality) +async_astc = + +# Turns on the speed limiter, which will limit the emulation speed to the desired speed limit value +# 0: Off, 1: On (default) +use_speed_limit = + +# Limits the speed of the game to run no faster than this value as a percentage of target speed +# 1 - 9999: Speed limit as a percentage of target game speed. 100 (default) +speed_limit = + +# Whether to use disk based shader cache +# 0: Off, 1 (default): On +use_disk_shader_cache = + +# Which gpu accuracy level to use +# 0: Normal, 1 (default): High, 2: Extreme (Very slow) +gpu_accuracy = + +# Whether to use asynchronous GPU emulation +# 0 : Off (slow), 1 (default): On (fast) +use_asynchronous_gpu_emulation = + +# Inform the guest that GPU operations completed more quickly than they did. +# 0: Off, 1 (default): On +use_fast_gpu_time = + +# Whether to use garbage collection or not for GPU caches. +# 0 (default): Off, 1: On +use_caches_gc = + +# The clear color for the renderer. What shows up on the sides of the bottom screen. +# Must be in range of 0-255. Defaults to 0 for all. +bg_red = +bg_blue = +bg_green = + +)" + R"( +[Audio] +# Which audio output engine to use. +# auto (default): Auto-select +# cubeb: Cubeb audio engine (if available) +# sdl2: SDL2 audio engine (if available) +# null: No audio output +output_engine = + +# Which audio device to use. +# auto (default): Auto-select +output_device = + +# Output volume. +# 100 (default): 100%, 0; mute +volume = + +[Data Storage] +# Whether to create a virtual SD card. +# 1 (default): Yes, 0: No +use_virtual_sd = + +# Whether or not to enable gamecard emulation +# 1: Yes, 0 (default): No +gamecard_inserted = + +# Whether or not the gamecard should be emulated as the current game +# If 'gamecard_inserted' is 0 this setting is irrelevant +# 1: Yes, 0 (default): No +gamecard_current_game = + +# Path to an XCI file to use as the gamecard +# If 'gamecard_inserted' is 0 this setting is irrelevant +# If 'gamecard_current_game' is 1 this setting is irrelevant +gamecard_path = + +[System] +# Whether the system is docked +# 1 (default): Yes, 0: No +use_docked_mode = + +# Sets the seed for the RNG generator built into the switch +# rng_seed will be ignored and randomly generated if rng_seed_enabled is false +rng_seed_enabled = +rng_seed = + +# Sets the current time (in seconds since 12:00 AM Jan 1, 1970) that will be used by the time service +# This will auto-increment, with the time set being the time the game is started +# This override will only occur if custom_rtc_enabled is true, otherwise the current time is used +custom_rtc_enabled = +custom_rtc = + +# Sets the systems language index +# 0: Japanese, 1: English (default), 2: French, 3: German, 4: Italian, 5: Spanish, 6: Chinese, +# 7: Korean, 8: Dutch, 9: Portuguese, 10: Russian, 11: Taiwanese, 12: British English, 13: Canadian French, +# 14: Latin American Spanish, 15: Simplified Chinese, 16: Traditional Chinese, 17: Brazilian Portuguese +language_index = + +# The system region that sudachi will use during emulation +# -1: Auto-select (default), 0: Japan, 1: USA, 2: Europe, 3: Australia, 4: China, 5: Korea, 6: Taiwan +region_index = + +# The system time zone that sudachi will use during emulation +# 0: Auto-select (default), 1: Default (system archive value), Others: Index for specified time zone +time_zone_index = + +# Sets the sound output mode. +# 0: Mono, 1 (default): Stereo, 2: Surround +sound_index = + +[Miscellaneous] +# A filter which removes logs below a certain logging level. +# Examples: *:Debug Kernel.SVC:Trace Service.*:Critical +log_filter = *:Trace + +# Use developer keys +# 0 (default): Disabled, 1: Enabled +use_dev_keys = + +[Debugging] +# Record frame time data, can be found in the log directory. Boolean value +record_frame_times = +# Determines whether or not sudachi will dump the ExeFS of all games it attempts to load while loading them +dump_exefs=false +# Determines whether or not sudachi will dump all NSOs it attempts to load while loading them +dump_nso=false +# Determines whether or not sudachi will save the filesystem access log. +enable_fs_access_log=false +# Enables verbose reporting services +reporting_services = +# Determines whether or not sudachi will report to the game that the emulated console is in Kiosk Mode +# false: Retail/Normal Mode (default), true: Kiosk Mode +quest_flag = +# Determines whether debug asserts should be enabled, which will throw an exception on asserts. +# false: Disabled (default), true: Enabled +use_debug_asserts = +# Determines whether unimplemented HLE service calls should be automatically stubbed. +# false: Disabled (default), true: Enabled +use_auto_stub = +# Enables/Disables the macro JIT compiler +disable_macro_jit=false +# Determines whether to enable the GDB stub and wait for the debugger to attach before running. +# false: Disabled (default), true: Enabled +use_gdbstub=false +# The port to use for the GDB server, if it is enabled. +gdbstub_port=6543 + +[WebService] +# Whether or not to enable telemetry +# 0: No, 1 (default): Yes +enable_telemetry = +# URL for Web API +web_api_url = https://api.sudachi-emu.org +# Username and token for sudachi Web Service +# See https://profile.sudachi-emu.org/ for more info +sudachi_username = +sudachi_token = + +[Network] +# Name of the network interface device to use with sudachi LAN play. +# e.g. On *nix: 'enp7s0', 'wlp6s0u1u3u3', 'lo' +# e.g. On Windows: 'Ethernet', 'Wi-Fi' +network_interface = + +[AddOns] +# Used to disable add-ons +# List of title IDs of games that will have add-ons disabled (separated by '|'): +title_ids = +# For each title ID, have a key/value pair called `disabled_` equal to the names of the add-ons to disable (sep. by '|') +# e.x. disabled_0100000000010000 = Update|DLC <- disables Updates and DLC on Super Mario Odyssey +)"; +} // namespace DefaultINI diff --git a/src/sudachi_cmd/emu_window/emu_window_sdl2.cpp b/src/sudachi_cmd/emu_window/emu_window_sdl2.cpp new file mode 100644 index 0000000..0bc387b --- /dev/null +++ b/src/sudachi_cmd/emu_window/emu_window_sdl2.cpp @@ -0,0 +1,254 @@ +// SPDX-FileCopyrightText: 2016 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include + +#include "common/logging/log.h" +#include "common/scm_rev.h" +#include "common/settings.h" +#include "core/core.h" +#include "core/perf_stats.h" +#include "hid_core/hid_core.h" +#include "input_common/drivers/keyboard.h" +#include "input_common/drivers/mouse.h" +#include "input_common/drivers/touch_screen.h" +#include "input_common/main.h" +#include "sudachi_cmd/emu_window/emu_window_sdl2.h" +#include "sudachi_cmd/sudachi_icon.h" + +EmuWindow_SDL2::EmuWindow_SDL2(InputCommon::InputSubsystem* input_subsystem_, Core::System& system_) + : input_subsystem{input_subsystem_}, system{system_} { + input_subsystem->Initialize(); + if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER) < 0) { + LOG_CRITICAL(Frontend, "Failed to initialize SDL2: {}, Exiting...", SDL_GetError()); + exit(1); + } + SDL_SetMainReady(); +} + +EmuWindow_SDL2::~EmuWindow_SDL2() { + system.HIDCore().UnloadInputDevices(); + input_subsystem->Shutdown(); + SDL_Quit(); +} + +InputCommon::MouseButton EmuWindow_SDL2::SDLButtonToMouseButton(u32 button) const { + switch (button) { + case SDL_BUTTON_LEFT: + return InputCommon::MouseButton::Left; + case SDL_BUTTON_RIGHT: + return InputCommon::MouseButton::Right; + case SDL_BUTTON_MIDDLE: + return InputCommon::MouseButton::Wheel; + case SDL_BUTTON_X1: + return InputCommon::MouseButton::Backward; + case SDL_BUTTON_X2: + return InputCommon::MouseButton::Forward; + default: + return InputCommon::MouseButton::Undefined; + } +} + +std::pair EmuWindow_SDL2::MouseToTouchPos(s32 touch_x, s32 touch_y) const { + int w, h; + SDL_GetWindowSize(render_window, &w, &h); + const float fx = static_cast(touch_x) / w; + const float fy = static_cast(touch_y) / h; + + return {std::clamp(fx, 0.0f, 1.0f), std::clamp(fy, 0.0f, 1.0f)}; +} + +void EmuWindow_SDL2::OnMouseButton(u32 button, u8 state, s32 x, s32 y) { + const auto mouse_button = SDLButtonToMouseButton(button); + if (state == SDL_PRESSED) { + const auto [touch_x, touch_y] = MouseToTouchPos(x, y); + input_subsystem->GetMouse()->PressButton(x, y, mouse_button); + input_subsystem->GetMouse()->PressMouseButton(mouse_button); + input_subsystem->GetMouse()->PressTouchButton(touch_x, touch_y, mouse_button); + } else { + input_subsystem->GetMouse()->ReleaseButton(mouse_button); + } +} + +void EmuWindow_SDL2::OnMouseMotion(s32 x, s32 y) { + const auto [touch_x, touch_y] = MouseToTouchPos(x, y); + input_subsystem->GetMouse()->Move(x, y, 0, 0); + input_subsystem->GetMouse()->MouseMove(touch_x, touch_y); + input_subsystem->GetMouse()->TouchMove(touch_x, touch_y); +} + +void EmuWindow_SDL2::OnFingerDown(float x, float y, std::size_t id) { + input_subsystem->GetTouchScreen()->TouchPressed(x, y, id); +} + +void EmuWindow_SDL2::OnFingerMotion(float x, float y, std::size_t id) { + input_subsystem->GetTouchScreen()->TouchMoved(x, y, id); +} + +void EmuWindow_SDL2::OnFingerUp() { + input_subsystem->GetTouchScreen()->ReleaseAllTouch(); +} + +void EmuWindow_SDL2::OnKeyEvent(int key, u8 state) { + if (state == SDL_PRESSED) { + input_subsystem->GetKeyboard()->PressKey(static_cast(key)); + } else if (state == SDL_RELEASED) { + input_subsystem->GetKeyboard()->ReleaseKey(static_cast(key)); + } +} + +bool EmuWindow_SDL2::IsOpen() const { + return is_open; +} + +bool EmuWindow_SDL2::IsShown() const { + return is_shown; +} + +void EmuWindow_SDL2::OnResize() { + int width, height; + SDL_GL_GetDrawableSize(render_window, &width, &height); + UpdateCurrentFramebufferLayout(width, height); +} + +void EmuWindow_SDL2::ShowCursor(bool show_cursor) { + SDL_ShowCursor(show_cursor ? SDL_ENABLE : SDL_DISABLE); +} + +void EmuWindow_SDL2::Fullscreen() { + SDL_DisplayMode display_mode; + switch (Settings::values.fullscreen_mode.GetValue()) { + case Settings::FullscreenMode::Exclusive: + // Set window size to render size before entering fullscreen -- SDL2 does not resize window + // to display dimensions automatically in this mode. + if (SDL_GetDesktopDisplayMode(0, &display_mode) == 0) { + SDL_SetWindowSize(render_window, display_mode.w, display_mode.h); + } else { + LOG_ERROR(Frontend, "SDL_GetDesktopDisplayMode failed: {}", SDL_GetError()); + } + + if (SDL_SetWindowFullscreen(render_window, SDL_WINDOW_FULLSCREEN) == 0) { + return; + } + + LOG_ERROR(Frontend, "Fullscreening failed: {}", SDL_GetError()); + LOG_INFO(Frontend, "Attempting to use borderless fullscreen..."); + [[fallthrough]]; + case Settings::FullscreenMode::Borderless: + if (SDL_SetWindowFullscreen(render_window, SDL_WINDOW_FULLSCREEN_DESKTOP) == 0) { + return; + } + + LOG_ERROR(Frontend, "Borderless fullscreening failed: {}", SDL_GetError()); + [[fallthrough]]; + default: + // Fallback algorithm: Maximise window. + // Works on all systems (unless something is seriously wrong), so no fallback for this one. + LOG_INFO(Frontend, "Falling back on a maximised window..."); + SDL_MaximizeWindow(render_window); + break; + } +} + +void EmuWindow_SDL2::WaitEvent() { + // Called on main thread + SDL_Event event; + + if (!SDL_WaitEvent(&event)) { + const char* error = SDL_GetError(); + if (!error || strcmp(error, "") == 0) { + // https://github.com/libsdl-org/SDL/issues/5780 + // Sometimes SDL will return without actually having hit an error condition; + // just ignore it in this case. + return; + } + + LOG_CRITICAL(Frontend, "SDL_WaitEvent failed: {}", error); + exit(1); + } + + switch (event.type) { + case SDL_WINDOWEVENT: + switch (event.window.event) { + case SDL_WINDOWEVENT_SIZE_CHANGED: + case SDL_WINDOWEVENT_RESIZED: + case SDL_WINDOWEVENT_MAXIMIZED: + case SDL_WINDOWEVENT_RESTORED: + OnResize(); + break; + case SDL_WINDOWEVENT_MINIMIZED: + case SDL_WINDOWEVENT_EXPOSED: + is_shown = event.window.event == SDL_WINDOWEVENT_EXPOSED; + OnResize(); + break; + case SDL_WINDOWEVENT_CLOSE: + is_open = false; + break; + } + break; + case SDL_KEYDOWN: + case SDL_KEYUP: + OnKeyEvent(static_cast(event.key.keysym.scancode), event.key.state); + break; + case SDL_MOUSEMOTION: + // ignore if it came from touch + if (event.button.which != SDL_TOUCH_MOUSEID) + OnMouseMotion(event.motion.x, event.motion.y); + break; + case SDL_MOUSEBUTTONDOWN: + case SDL_MOUSEBUTTONUP: + // ignore if it came from touch + if (event.button.which != SDL_TOUCH_MOUSEID) { + OnMouseButton(event.button.button, event.button.state, event.button.x, event.button.y); + } + break; + case SDL_FINGERDOWN: + OnFingerDown(event.tfinger.x, event.tfinger.y, + static_cast(event.tfinger.touchId)); + break; + case SDL_FINGERMOTION: + OnFingerMotion(event.tfinger.x, event.tfinger.y, + static_cast(event.tfinger.touchId)); + break; + case SDL_FINGERUP: + OnFingerUp(); + break; + case SDL_QUIT: + is_open = false; + break; + default: + break; + } + + const u32 current_time = SDL_GetTicks(); + if (current_time > last_time + 2000) { + const auto results = system.GetAndResetPerfStats(); + const auto title = + fmt::format("sudachi {} | {}-{} | FPS: {:.0f} ({:.0f}%)", Common::g_build_fullname, + Common::g_scm_branch, Common::g_scm_desc, results.average_game_fps, + results.emulation_speed * 100.0); + SDL_SetWindowTitle(render_window, title.c_str()); + last_time = current_time; + } +} + +// Credits to Samantas5855 and others for this function. +void EmuWindow_SDL2::SetWindowIcon() { + SDL_RWops* const sudachi_icon_stream = SDL_RWFromConstMem((void*)sudachi_icon, sudachi_icon_size); + if (sudachi_icon_stream == nullptr) { + LOG_WARNING(Frontend, "Failed to create sudachi icon stream."); + return; + } + SDL_Surface* const window_icon = SDL_LoadBMP_RW(sudachi_icon_stream, 1); + if (window_icon == nullptr) { + LOG_WARNING(Frontend, "Failed to read BMP from stream."); + return; + } + // The icon is attached to the window pointer + SDL_SetWindowIcon(render_window, window_icon); + SDL_FreeSurface(window_icon); +} + +void EmuWindow_SDL2::OnMinimalClientAreaChangeRequest(std::pair minimal_size) { + SDL_SetWindowMinimumSize(render_window, minimal_size.first, minimal_size.second); +} diff --git a/src/sudachi_cmd/emu_window/emu_window_sdl2.h b/src/sudachi_cmd/emu_window/emu_window_sdl2.h new file mode 100644 index 0000000..0c9d057 --- /dev/null +++ b/src/sudachi_cmd/emu_window/emu_window_sdl2.h @@ -0,0 +1,95 @@ +// SPDX-FileCopyrightText: 2016 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include + +#include "core/frontend/emu_window.h" +#include "core/frontend/graphics_context.h" + +struct SDL_Window; + +namespace Core { +class System; +} + +namespace InputCommon { +class InputSubsystem; +enum class MouseButton; +} // namespace InputCommon + +class EmuWindow_SDL2 : public Core::Frontend::EmuWindow { +public: + explicit EmuWindow_SDL2(InputCommon::InputSubsystem* input_subsystem_, Core::System& system_); + ~EmuWindow_SDL2(); + + /// Whether the window is still open, and a close request hasn't yet been sent + bool IsOpen() const; + + /// Returns if window is shown (not minimized) + bool IsShown() const override; + + /// Wait for the next event on the main thread. + void WaitEvent(); + + // Sets the window icon from sudachi.bmp + void SetWindowIcon(); + +protected: + /// Called by WaitEvent when a key is pressed or released. + void OnKeyEvent(int key, u8 state); + + /// Converts a SDL mouse button into MouseInput mouse button + InputCommon::MouseButton SDLButtonToMouseButton(u32 button) const; + + /// Translates pixel position to float position + std::pair MouseToTouchPos(s32 touch_x, s32 touch_y) const; + + /// Called by WaitEvent when a mouse button is pressed or released + void OnMouseButton(u32 button, u8 state, s32 x, s32 y); + + /// Called by WaitEvent when the mouse moves. + void OnMouseMotion(s32 x, s32 y); + + /// Called by WaitEvent when a finger starts touching the touchscreen + void OnFingerDown(float x, float y, std::size_t id); + + /// Called by WaitEvent when a finger moves while touching the touchscreen + void OnFingerMotion(float x, float y, std::size_t id); + + /// Called by WaitEvent when a finger stops touching the touchscreen + void OnFingerUp(); + + /// Called by WaitEvent when any event that may cause the window to be resized occurs + void OnResize(); + + /// Called when users want to hide the mouse cursor + void ShowCursor(bool show_cursor); + + /// Called when user passes the fullscreen parameter flag + void Fullscreen(); + + /// Called when a configuration change affects the minimal size of the window + void OnMinimalClientAreaChangeRequest(std::pair minimal_size) override; + + /// Is the window still open? + bool is_open = true; + + /// Is the window being shown? + bool is_shown = true; + + /// Internal SDL2 render window + SDL_Window* render_window{}; + + /// Keeps track of how often to update the title bar during gameplay + u32 last_time = 0; + + /// Input subsystem to use with this window. + InputCommon::InputSubsystem* input_subsystem; + + /// sudachi core instance + Core::System& system; +}; + +class DummyContext : public Core::Frontend::GraphicsContext {}; diff --git a/src/sudachi_cmd/emu_window/emu_window_sdl2_gl.cpp b/src/sudachi_cmd/emu_window/emu_window_sdl2_gl.cpp new file mode 100644 index 0000000..ce37318 --- /dev/null +++ b/src/sudachi_cmd/emu_window/emu_window_sdl2_gl.cpp @@ -0,0 +1,153 @@ +// SPDX-FileCopyrightText: Copyright 2019 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include +#include + +#define SDL_MAIN_HANDLED +#include + +#include +#include +#include "common/logging/log.h" +#include "common/scm_rev.h" +#include "common/settings.h" +#include "common/string_util.h" +#include "core/core.h" +#include "input_common/main.h" +#include "video_core/renderer_base.h" +#include "sudachi_cmd/emu_window/emu_window_sdl2_gl.h" + +class SDLGLContext : public Core::Frontend::GraphicsContext { +public: + explicit SDLGLContext(SDL_Window* window_) : window{window_} { + context = SDL_GL_CreateContext(window); + } + + ~SDLGLContext() { + DoneCurrent(); + SDL_GL_DeleteContext(context); + } + + void SwapBuffers() override { + SDL_GL_SwapWindow(window); + } + + void MakeCurrent() override { + if (is_current) { + return; + } + is_current = SDL_GL_MakeCurrent(window, context) == 0; + } + + void DoneCurrent() override { + if (!is_current) { + return; + } + SDL_GL_MakeCurrent(window, nullptr); + is_current = false; + } + +private: + SDL_Window* window; + SDL_GLContext context; + bool is_current = false; +}; + +bool EmuWindow_SDL2_GL::SupportsRequiredGLExtensions() { + std::vector unsupported_ext; + + // Extensions required to support some texture formats. + if (!GLAD_GL_EXT_texture_compression_s3tc) { + unsupported_ext.push_back("EXT_texture_compression_s3tc"); + } + if (!GLAD_GL_ARB_texture_compression_rgtc) { + unsupported_ext.push_back("ARB_texture_compression_rgtc"); + } + + for (const auto& extension : unsupported_ext) { + LOG_CRITICAL(Frontend, "Unsupported GL extension: {}", extension); + } + + return unsupported_ext.empty(); +} + +EmuWindow_SDL2_GL::EmuWindow_SDL2_GL(InputCommon::InputSubsystem* input_subsystem_, + Core::System& system_, bool fullscreen) + : EmuWindow_SDL2{input_subsystem_, system_} { + SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 6); + SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY); + SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); + SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8); + SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8); + SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8); + SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 0); + SDL_GL_SetAttribute(SDL_GL_SHARE_WITH_CURRENT_CONTEXT, 1); + if (Settings::values.renderer_debug) { + SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG); + } + SDL_GL_SetSwapInterval(0); + + std::string window_title = fmt::format("sudachi {} | {}-{}", Common::g_build_fullname, + Common::g_scm_branch, Common::g_scm_desc); + render_window = + SDL_CreateWindow(window_title.c_str(), + SDL_WINDOWPOS_UNDEFINED, // x position + SDL_WINDOWPOS_UNDEFINED, // y position + Layout::ScreenUndocked::Width, Layout::ScreenUndocked::Height, + SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI); + + if (render_window == nullptr) { + LOG_CRITICAL(Frontend, "Failed to create SDL2 window! {}", SDL_GetError()); + exit(1); + } + + strict_context_required = strcmp(SDL_GetCurrentVideoDriver(), "wayland") == 0; + + SetWindowIcon(); + + if (fullscreen) { + Fullscreen(); + ShowCursor(false); + } + + window_context = SDL_GL_CreateContext(render_window); + core_context = CreateSharedContext(); + + if (window_context == nullptr) { + LOG_CRITICAL(Frontend, "Failed to create SDL2 GL context: {}", SDL_GetError()); + exit(1); + } + if (core_context == nullptr) { + LOG_CRITICAL(Frontend, "Failed to create shared SDL2 GL context: {}", SDL_GetError()); + exit(1); + } + + if (!gladLoadGLLoader(static_cast(SDL_GL_GetProcAddress))) { + LOG_CRITICAL(Frontend, "Failed to initialize GL functions! {}", SDL_GetError()); + exit(1); + } + + if (!SupportsRequiredGLExtensions()) { + LOG_CRITICAL(Frontend, "GPU does not support all required OpenGL extensions! Exiting..."); + exit(1); + } + + OnResize(); + OnMinimalClientAreaChangeRequest(GetActiveConfig().min_client_area_size); + SDL_PumpEvents(); + LOG_INFO(Frontend, "sudachi Version: {} | {}-{}", Common::g_build_fullname, Common::g_scm_branch, + Common::g_scm_desc); + Settings::LogSettings(); +} + +EmuWindow_SDL2_GL::~EmuWindow_SDL2_GL() { + core_context.reset(); + SDL_GL_DeleteContext(window_context); +} + +std::unique_ptr EmuWindow_SDL2_GL::CreateSharedContext() const { + return std::make_unique(render_window); +} diff --git a/src/sudachi_cmd/emu_window/emu_window_sdl2_gl.h b/src/sudachi_cmd/emu_window/emu_window_sdl2_gl.h new file mode 100644 index 0000000..da5ffc4 --- /dev/null +++ b/src/sudachi_cmd/emu_window/emu_window_sdl2_gl.h @@ -0,0 +1,37 @@ +// SPDX-FileCopyrightText: Copyright 2019 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include "core/frontend/emu_window.h" +#include "sudachi_cmd/emu_window/emu_window_sdl2.h" + +namespace Core { +class System; +} + +namespace InputCommon { +class InputSubsystem; +} + +class EmuWindow_SDL2_GL final : public EmuWindow_SDL2 { +public: + explicit EmuWindow_SDL2_GL(InputCommon::InputSubsystem* input_subsystem_, Core::System& system_, + bool fullscreen); + ~EmuWindow_SDL2_GL(); + + std::unique_ptr CreateSharedContext() const override; + +private: + /// Whether the GPU and driver supports the OpenGL extension required + bool SupportsRequiredGLExtensions(); + + using SDL_GLContext = void*; + + /// The OpenGL context associated with the window + SDL_GLContext window_context; + + /// The OpenGL context associated with the core + std::unique_ptr core_context; +}; diff --git a/src/sudachi_cmd/emu_window/emu_window_sdl2_null.cpp b/src/sudachi_cmd/emu_window/emu_window_sdl2_null.cpp new file mode 100644 index 0000000..596a534 --- /dev/null +++ b/src/sudachi_cmd/emu_window/emu_window_sdl2_null.cpp @@ -0,0 +1,51 @@ +// SPDX-FileCopyrightText: Copyright 2022 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include +#include + +#include + +#include "common/logging/log.h" +#include "common/scm_rev.h" +#include "video_core/renderer_null/renderer_null.h" +#include "sudachi_cmd/emu_window/emu_window_sdl2_null.h" + +#ifdef SUDACHI_USE_EXTERNAL_SDL2 +// Include this before SDL.h to prevent the external from including a dummy +#define USING_GENERATED_CONFIG_H +#include +#endif + +#include + +EmuWindow_SDL2_Null::EmuWindow_SDL2_Null(InputCommon::InputSubsystem* input_subsystem_, + Core::System& system_, bool fullscreen) + : EmuWindow_SDL2{input_subsystem_, system_} { + const std::string window_title = fmt::format("sudachi {} | {}-{} (Vulkan)", Common::g_build_name, + Common::g_scm_branch, Common::g_scm_desc); + render_window = + SDL_CreateWindow(window_title.c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, + Layout::ScreenUndocked::Width, Layout::ScreenUndocked::Height, + SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI); + + SetWindowIcon(); + + if (fullscreen) { + Fullscreen(); + ShowCursor(false); + } + + OnResize(); + OnMinimalClientAreaChangeRequest(GetActiveConfig().min_client_area_size); + SDL_PumpEvents(); + LOG_INFO(Frontend, "sudachi Version: {} | {}-{} (Null)", Common::g_build_name, + Common::g_scm_branch, Common::g_scm_desc); +} + +EmuWindow_SDL2_Null::~EmuWindow_SDL2_Null() = default; + +std::unique_ptr EmuWindow_SDL2_Null::CreateSharedContext() const { + return std::make_unique(); +} diff --git a/src/sudachi_cmd/emu_window/emu_window_sdl2_null.h b/src/sudachi_cmd/emu_window/emu_window_sdl2_null.h new file mode 100644 index 0000000..cc9c709 --- /dev/null +++ b/src/sudachi_cmd/emu_window/emu_window_sdl2_null.h @@ -0,0 +1,26 @@ +// SPDX-FileCopyrightText: Copyright 2022 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include + +#include "core/frontend/emu_window.h" +#include "sudachi_cmd/emu_window/emu_window_sdl2.h" + +namespace Core { +class System; +} + +namespace InputCommon { +class InputSubsystem; +} + +class EmuWindow_SDL2_Null final : public EmuWindow_SDL2 { +public: + explicit EmuWindow_SDL2_Null(InputCommon::InputSubsystem* input_subsystem_, + Core::System& system, bool fullscreen); + ~EmuWindow_SDL2_Null() override; + + std::unique_ptr CreateSharedContext() const override; +}; diff --git a/src/sudachi_cmd/emu_window/emu_window_sdl2_vk.cpp b/src/sudachi_cmd/emu_window/emu_window_sdl2_vk.cpp new file mode 100644 index 0000000..5639c13 --- /dev/null +++ b/src/sudachi_cmd/emu_window/emu_window_sdl2_vk.cpp @@ -0,0 +1,93 @@ +// SPDX-FileCopyrightText: Copyright 2018 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include +#include + +#include + +#include "common/logging/log.h" +#include "common/scm_rev.h" +#include "video_core/renderer_vulkan/renderer_vulkan.h" +#include "sudachi_cmd/emu_window/emu_window_sdl2_vk.h" + +#include +#include + +EmuWindow_SDL2_VK::EmuWindow_SDL2_VK(InputCommon::InputSubsystem* input_subsystem_, + Core::System& system_, bool fullscreen) + : EmuWindow_SDL2{input_subsystem_, system_} { + const std::string window_title = fmt::format("sudachi {} | {}-{} (Vulkan)", Common::g_build_name, + Common::g_scm_branch, Common::g_scm_desc); + render_window = + SDL_CreateWindow(window_title.c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, + Layout::ScreenUndocked::Width, Layout::ScreenUndocked::Height, + SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI); + + SDL_SysWMinfo wm; + SDL_VERSION(&wm.version); + if (SDL_GetWindowWMInfo(render_window, &wm) == SDL_FALSE) { + LOG_CRITICAL(Frontend, "Failed to get information from the window manager: {}", + SDL_GetError()); + std::exit(EXIT_FAILURE); + } + + SetWindowIcon(); + + if (fullscreen) { + Fullscreen(); + ShowCursor(false); + } + + switch (wm.subsystem) { +#ifdef SDL_VIDEO_DRIVER_WINDOWS + case SDL_SYSWM_TYPE::SDL_SYSWM_WINDOWS: + window_info.type = Core::Frontend::WindowSystemType::Windows; + window_info.render_surface = reinterpret_cast(wm.info.win.window); + break; +#endif +#ifdef SDL_VIDEO_DRIVER_X11 + case SDL_SYSWM_TYPE::SDL_SYSWM_X11: + window_info.type = Core::Frontend::WindowSystemType::X11; + window_info.display_connection = wm.info.x11.display; + window_info.render_surface = reinterpret_cast(wm.info.x11.window); + break; +#endif +#ifdef SDL_VIDEO_DRIVER_WAYLAND + case SDL_SYSWM_TYPE::SDL_SYSWM_WAYLAND: + window_info.type = Core::Frontend::WindowSystemType::Wayland; + window_info.display_connection = wm.info.wl.display; + window_info.render_surface = wm.info.wl.surface; + break; +#endif +#ifdef SDL_VIDEO_DRIVER_COCOA + case SDL_SYSWM_TYPE::SDL_SYSWM_COCOA: + window_info.type = Core::Frontend::WindowSystemType::Cocoa; + window_info.render_surface = SDL_Metal_CreateView(render_window); + break; +#endif +#ifdef SDL_VIDEO_DRIVER_ANDROID + case SDL_SYSWM_TYPE::SDL_SYSWM_ANDROID: + window_info.type = Core::Frontend::WindowSystemType::Android; + window_info.render_surface = reinterpret_cast(wm.info.android.window); + break; +#endif + default: + LOG_CRITICAL(Frontend, "Window manager subsystem {} not implemented", wm.subsystem); + std::exit(EXIT_FAILURE); + break; + } + + OnResize(); + OnMinimalClientAreaChangeRequest(GetActiveConfig().min_client_area_size); + SDL_PumpEvents(); + LOG_INFO(Frontend, "sudachi Version: {} | {}-{} (Vulkan)", Common::g_build_name, + Common::g_scm_branch, Common::g_scm_desc); +} + +EmuWindow_SDL2_VK::~EmuWindow_SDL2_VK() = default; + +std::unique_ptr EmuWindow_SDL2_VK::CreateSharedContext() const { + return std::make_unique(); +} diff --git a/src/sudachi_cmd/emu_window/emu_window_sdl2_vk.h b/src/sudachi_cmd/emu_window/emu_window_sdl2_vk.h new file mode 100644 index 0000000..266c38e --- /dev/null +++ b/src/sudachi_cmd/emu_window/emu_window_sdl2_vk.h @@ -0,0 +1,26 @@ +// SPDX-FileCopyrightText: Copyright 2018 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include + +#include "core/frontend/emu_window.h" +#include "sudachi_cmd/emu_window/emu_window_sdl2.h" + +namespace Core { +class System; +} + +namespace InputCommon { +class InputSubsystem; +} + +class EmuWindow_SDL2_VK final : public EmuWindow_SDL2 { +public: + explicit EmuWindow_SDL2_VK(InputCommon::InputSubsystem* input_subsystem_, Core::System& system, + bool fullscreen); + ~EmuWindow_SDL2_VK() override; + + std::unique_ptr CreateSharedContext() const override; +}; diff --git a/src/sudachi_cmd/precompiled_headers.h b/src/sudachi_cmd/precompiled_headers.h new file mode 100644 index 0000000..0303960 --- /dev/null +++ b/src/sudachi_cmd/precompiled_headers.h @@ -0,0 +1,6 @@ +// SPDX-FileCopyrightText: 2022 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include "common/common_precompiled_headers.h" diff --git a/src/sudachi_cmd/sdl_config.cpp b/src/sudachi_cmd/sdl_config.cpp new file mode 100644 index 0000000..9bc25fc --- /dev/null +++ b/src/sudachi_cmd/sdl_config.cpp @@ -0,0 +1,262 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +// SDL will break our main function in sudachi-cmd if we don't define this before adding SDL.h +#define SDL_MAIN_HANDLED +#include + +#include "common/logging/log.h" +#include "input_common/main.h" +#include "sdl_config.h" + +const std::array SdlConfig::default_buttons = { + SDL_SCANCODE_A, SDL_SCANCODE_S, SDL_SCANCODE_Z, SDL_SCANCODE_X, SDL_SCANCODE_T, + SDL_SCANCODE_G, SDL_SCANCODE_F, SDL_SCANCODE_H, SDL_SCANCODE_Q, SDL_SCANCODE_W, + SDL_SCANCODE_M, SDL_SCANCODE_N, SDL_SCANCODE_1, SDL_SCANCODE_2, SDL_SCANCODE_B, +}; + +const std::array SdlConfig::default_motions = { + SDL_SCANCODE_7, + SDL_SCANCODE_8, +}; + +const std::array, Settings::NativeAnalog::NumAnalogs> SdlConfig::default_analogs{ + { + { + SDL_SCANCODE_UP, + SDL_SCANCODE_DOWN, + SDL_SCANCODE_LEFT, + SDL_SCANCODE_RIGHT, + }, + { + SDL_SCANCODE_I, + SDL_SCANCODE_K, + SDL_SCANCODE_J, + SDL_SCANCODE_L, + }, + }}; + +const std::array SdlConfig::default_stick_mod = { + SDL_SCANCODE_D, + 0, +}; + +const std::array SdlConfig::default_ringcon_analogs{{ + 0, + 0, +}}; + +SdlConfig::SdlConfig(const std::optional config_path) { + Initialize(config_path); + ReadSdlValues(); + SaveSdlValues(); +} + +SdlConfig::~SdlConfig() { + if (global) { + SdlConfig::SaveAllValues(); + } +} + +void SdlConfig::ReloadAllValues() { + Reload(); + ReadSdlValues(); + SaveSdlValues(); +} + +void SdlConfig::SaveAllValues() { + SaveValues(); + SaveSdlValues(); +} + +void SdlConfig::ReadSdlValues() { + ReadSdlControlValues(); +} + +void SdlConfig::ReadSdlControlValues() { + BeginGroup(Settings::TranslateCategory(Settings::Category::Controls)); + + Settings::values.players.SetGlobal(!IsCustomConfig()); + for (std::size_t p = 0; p < Settings::values.players.GetValue().size(); ++p) { + ReadSdlPlayerValues(p); + } + if (IsCustomConfig()) { + EndGroup(); + return; + } + ReadDebugControlValues(); + ReadHidbusValues(); + + EndGroup(); +} + +void SdlConfig::ReadSdlPlayerValues(const std::size_t player_index) { + std::string player_prefix; + if (type != ConfigType::InputProfile) { + player_prefix.append("player_").append(ToString(player_index)).append("_"); + } + + auto& player = Settings::values.players.GetValue()[player_index]; + if (IsCustomConfig()) { + const auto profile_name = + ReadStringSetting(std::string(player_prefix).append("profile_name")); + if (profile_name.empty()) { + // Use the global input config + player = Settings::values.players.GetValue(true)[player_index]; + player.profile_name = ""; + return; + } + } + + for (int i = 0; i < Settings::NativeButton::NumButtons; ++i) { + const std::string default_param = InputCommon::GenerateKeyboardParam(default_buttons[i]); + auto& player_buttons = player.buttons[i]; + + player_buttons = ReadStringSetting( + std::string(player_prefix).append(Settings::NativeButton::mapping[i]), default_param); + if (player_buttons.empty()) { + player_buttons = default_param; + } + } + + for (int i = 0; i < Settings::NativeAnalog::NumAnalogs; ++i) { + const std::string default_param = InputCommon::GenerateAnalogParamFromKeys( + default_analogs[i][0], default_analogs[i][1], default_analogs[i][2], + default_analogs[i][3], default_stick_mod[i], 0.5f); + auto& player_analogs = player.analogs[i]; + + player_analogs = ReadStringSetting( + std::string(player_prefix).append(Settings::NativeAnalog::mapping[i]), default_param); + if (player_analogs.empty()) { + player_analogs = default_param; + } + } + + for (int i = 0; i < Settings::NativeMotion::NumMotions; ++i) { + const std::string default_param = InputCommon::GenerateKeyboardParam(default_motions[i]); + auto& player_motions = player.motions[i]; + + player_motions = ReadStringSetting( + std::string(player_prefix).append(Settings::NativeMotion::mapping[i]), default_param); + if (player_motions.empty()) { + player_motions = default_param; + } + } +} + +void SdlConfig::ReadDebugControlValues() { + for (int i = 0; i < Settings::NativeButton::NumButtons; ++i) { + const std::string default_param = InputCommon::GenerateKeyboardParam(default_buttons[i]); + auto& debug_pad_buttons = Settings::values.debug_pad_buttons[i]; + debug_pad_buttons = ReadStringSetting( + std::string("debug_pad_").append(Settings::NativeButton::mapping[i]), default_param); + if (debug_pad_buttons.empty()) { + debug_pad_buttons = default_param; + } + } + for (int i = 0; i < Settings::NativeAnalog::NumAnalogs; ++i) { + const std::string default_param = InputCommon::GenerateAnalogParamFromKeys( + default_analogs[i][0], default_analogs[i][1], default_analogs[i][2], + default_analogs[i][3], default_stick_mod[i], 0.5f); + auto& debug_pad_analogs = Settings::values.debug_pad_analogs[i]; + debug_pad_analogs = ReadStringSetting( + std::string("debug_pad_").append(Settings::NativeAnalog::mapping[i]), default_param); + if (debug_pad_analogs.empty()) { + debug_pad_analogs = default_param; + } + } +} + +void SdlConfig::ReadHidbusValues() { + const std::string default_param = InputCommon::GenerateAnalogParamFromKeys( + 0, 0, default_ringcon_analogs[0], default_ringcon_analogs[1], 0, 0.05f); + auto& ringcon_analogs = Settings::values.ringcon_analogs; + + ringcon_analogs = ReadStringSetting(std::string("ring_controller"), default_param); + if (ringcon_analogs.empty()) { + ringcon_analogs = default_param; + } +} + +void SdlConfig::SaveSdlValues() { + LOG_DEBUG(Config, "Saving SDL configuration values"); + SaveSdlControlValues(); + + WriteToIni(); +} + +void SdlConfig::SaveSdlControlValues() { + BeginGroup(Settings::TranslateCategory(Settings::Category::Controls)); + + Settings::values.players.SetGlobal(!IsCustomConfig()); + for (std::size_t p = 0; p < Settings::values.players.GetValue().size(); ++p) { + SaveSdlPlayerValues(p); + } + if (IsCustomConfig()) { + EndGroup(); + return; + } + SaveDebugControlValues(); + SaveHidbusValues(); + + EndGroup(); +} + +void SdlConfig::SaveSdlPlayerValues(const std::size_t player_index) { + std::string player_prefix; + if (type != ConfigType::InputProfile) { + player_prefix = std::string("player_").append(ToString(player_index)).append("_"); + } + + const auto& player = Settings::values.players.GetValue()[player_index]; + if (IsCustomConfig() && player.profile_name.empty()) { + // No custom profile selected + return; + } + + for (int i = 0; i < Settings::NativeButton::NumButtons; ++i) { + const std::string default_param = InputCommon::GenerateKeyboardParam(default_buttons[i]); + WriteStringSetting(std::string(player_prefix).append(Settings::NativeButton::mapping[i]), + player.buttons[i], std::make_optional(default_param)); + } + for (int i = 0; i < Settings::NativeAnalog::NumAnalogs; ++i) { + const std::string default_param = InputCommon::GenerateAnalogParamFromKeys( + default_analogs[i][0], default_analogs[i][1], default_analogs[i][2], + default_analogs[i][3], default_stick_mod[i], 0.5f); + WriteStringSetting(std::string(player_prefix).append(Settings::NativeAnalog::mapping[i]), + player.analogs[i], std::make_optional(default_param)); + } + for (int i = 0; i < Settings::NativeMotion::NumMotions; ++i) { + const std::string default_param = InputCommon::GenerateKeyboardParam(default_motions[i]); + WriteStringSetting(std::string(player_prefix).append(Settings::NativeMotion::mapping[i]), + player.motions[i], std::make_optional(default_param)); + } +} + +void SdlConfig::SaveDebugControlValues() { + for (int i = 0; i < Settings::NativeButton::NumButtons; ++i) { + const std::string default_param = InputCommon::GenerateKeyboardParam(default_buttons[i]); + WriteStringSetting(std::string("debug_pad_").append(Settings::NativeButton::mapping[i]), + Settings::values.debug_pad_buttons[i], + std::make_optional(default_param)); + } + for (int i = 0; i < Settings::NativeAnalog::NumAnalogs; ++i) { + const std::string default_param = InputCommon::GenerateAnalogParamFromKeys( + default_analogs[i][0], default_analogs[i][1], default_analogs[i][2], + default_analogs[i][3], default_stick_mod[i], 0.5f); + WriteStringSetting(std::string("debug_pad_").append(Settings::NativeAnalog::mapping[i]), + Settings::values.debug_pad_analogs[i], + std::make_optional(default_param)); + } +} + +void SdlConfig::SaveHidbusValues() { + const std::string default_param = InputCommon::GenerateAnalogParamFromKeys( + 0, 0, default_ringcon_analogs[0], default_ringcon_analogs[1], 0, 0.05f); + WriteStringSetting(std::string("ring_controller"), Settings::values.ringcon_analogs, + std::make_optional(default_param)); +} + +std::vector& SdlConfig::FindRelevantList(Settings::Category category) { + return Settings::values.linkage.by_category[category]; +} diff --git a/src/sudachi_cmd/sdl_config.h b/src/sudachi_cmd/sdl_config.h new file mode 100644 index 0000000..8128532 --- /dev/null +++ b/src/sudachi_cmd/sdl_config.h @@ -0,0 +1,49 @@ +// SPDX-FileCopyrightText: 2023 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include "frontend_common/config.h" + +class SdlConfig final : public Config { +public: + explicit SdlConfig(std::optional config_path); + ~SdlConfig() override; + + void ReloadAllValues() override; + void SaveAllValues() override; + +protected: + void ReadSdlValues(); + void ReadSdlPlayerValues(std::size_t player_index); + void ReadSdlControlValues(); + void ReadHidbusValues() override; + void ReadDebugControlValues() override; + void ReadPathValues() override {} + void ReadShortcutValues() override {} + void ReadUIValues() override {} + void ReadUIGamelistValues() override {} + void ReadUILayoutValues() override {} + void ReadMultiplayerValues() override {} + + void SaveSdlValues(); + void SaveSdlPlayerValues(std::size_t player_index); + void SaveSdlControlValues(); + void SaveHidbusValues() override; + void SaveDebugControlValues() override; + void SavePathValues() override {} + void SaveShortcutValues() override {} + void SaveUIValues() override {} + void SaveUIGamelistValues() override {} + void SaveUILayoutValues() override {} + void SaveMultiplayerValues() override {} + + std::vector& FindRelevantList(Settings::Category category) override; + +public: + static const std::array default_buttons; + static const std::array default_motions; + static const std::array, Settings::NativeAnalog::NumAnalogs> default_analogs; + static const std::array default_stick_mod; + static const std::array default_ringcon_analogs; +}; diff --git a/src/sudachi_cmd/sudachi.cpp b/src/sudachi_cmd/sudachi.cpp new file mode 100644 index 0000000..851c8fe --- /dev/null +++ b/src/sudachi_cmd/sudachi.cpp @@ -0,0 +1,459 @@ +// SPDX-FileCopyrightText: 2014 Citra Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include +#include +#include +#include +#include + +#include + +#include "common/detached_tasks.h" +#include "common/logging/backend.h" +#include "common/logging/log.h" +#include "common/microprofile.h" +#include "common/nvidia_flags.h" +#include "common/scm_rev.h" +#include "common/scope_exit.h" +#include "common/settings.h" +#include "common/string_util.h" +#include "common/telemetry.h" +#include "core/core.h" +#include "core/core_timing.h" +#include "core/cpu_manager.h" +#include "core/crypto/key_manager.h" +#include "core/file_sys/registered_cache.h" +#include "core/file_sys/vfs/vfs_real.h" +#include "core/hle/service/am/applet_manager.h" +#include "core/hle/service/filesystem/filesystem.h" +#include "core/loader/loader.h" +#include "core/telemetry_session.h" +#include "frontend_common/config.h" +#include "input_common/main.h" +#include "network/network.h" +#include "sdl_config.h" +#include "video_core/renderer_base.h" +#include "sudachi_cmd/emu_window/emu_window_sdl2.h" +#include "sudachi_cmd/emu_window/emu_window_sdl2_gl.h" +#include "sudachi_cmd/emu_window/emu_window_sdl2_null.h" +#include "sudachi_cmd/emu_window/emu_window_sdl2_vk.h" + +#ifdef _WIN32 +// windows.h needs to be included before shellapi.h +#include + +#include + +#include "common/windows/timer_resolution.h" +#endif + +#undef _UNICODE +#include +#ifndef _MSC_VER +#include +#endif + +#ifdef _WIN32 +extern "C" { +// tells Nvidia and AMD drivers to use the dedicated GPU by default on laptops with switchable +// graphics +__declspec(dllexport) unsigned long NvOptimusEnablement = 0x00000001; +__declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1; +} +#endif + +#ifdef __unix__ +#include "common/linux/gamemode.h" +#endif + +static void PrintHelp(const char* argv0) { + std::cout << "Usage: " << argv0 + << " [options] \n" + "-c, --config Load the specified configuration file\n" + "-f, --fullscreen Start in fullscreen mode\n" + "-g, --game File path of the game to load\n" + "-h, --help Display this help and exit\n" + "-m, --multiplayer=nick:password@address:port" + " Nickname, password, address and port for multiplayer\n" + "-p, --program Pass following string as arguments to executable\n" + "-u, --user Select a specific user profile from 0 to 7\n" + "-v, --version Output version information and exit\n"; +} + +static void PrintVersion() { + std::cout << "sudachi " << Common::g_scm_branch << " " << Common::g_scm_desc << std::endl; +} + +static void OnStateChanged(const Network::RoomMember::State& state) { + switch (state) { + case Network::RoomMember::State::Idle: + LOG_DEBUG(Network, "Network is idle"); + break; + case Network::RoomMember::State::Joining: + LOG_DEBUG(Network, "Connection sequence to room started"); + break; + case Network::RoomMember::State::Joined: + LOG_DEBUG(Network, "Successfully joined to the room"); + break; + case Network::RoomMember::State::Moderator: + LOG_DEBUG(Network, "Successfully joined the room as a moderator"); + break; + default: + break; + } +} + +static void OnNetworkError(const Network::RoomMember::Error& error) { + switch (error) { + case Network::RoomMember::Error::LostConnection: + LOG_DEBUG(Network, "Lost connection to the room"); + break; + case Network::RoomMember::Error::CouldNotConnect: + LOG_ERROR(Network, "Error: Could not connect"); + exit(1); + break; + case Network::RoomMember::Error::NameCollision: + LOG_ERROR( + Network, + "You tried to use the same nickname as another user that is connected to the Room"); + exit(1); + break; + case Network::RoomMember::Error::IpCollision: + LOG_ERROR(Network, "You tried to use the same fake IP-Address as another user that is " + "connected to the Room"); + exit(1); + break; + case Network::RoomMember::Error::WrongPassword: + LOG_ERROR(Network, "Room replied with: Wrong password"); + exit(1); + break; + case Network::RoomMember::Error::WrongVersion: + LOG_ERROR(Network, + "You are using a different version than the room you are trying to connect to"); + exit(1); + break; + case Network::RoomMember::Error::RoomIsFull: + LOG_ERROR(Network, "The room is full"); + exit(1); + break; + case Network::RoomMember::Error::HostKicked: + LOG_ERROR(Network, "You have been kicked by the host"); + break; + case Network::RoomMember::Error::HostBanned: + LOG_ERROR(Network, "You have been banned by the host"); + break; + case Network::RoomMember::Error::UnknownError: + LOG_ERROR(Network, "UnknownError"); + break; + case Network::RoomMember::Error::PermissionDenied: + LOG_ERROR(Network, "PermissionDenied"); + break; + case Network::RoomMember::Error::NoSuchUser: + LOG_ERROR(Network, "NoSuchUser"); + break; + } +} + +static void OnMessageReceived(const Network::ChatEntry& msg) { + std::cout << std::endl << msg.nickname << ": " << msg.message << std::endl << std::endl; +} + +static void OnStatusMessageReceived(const Network::StatusMessageEntry& msg) { + std::string message; + switch (msg.type) { + case Network::IdMemberJoin: + message = fmt::format("{} has joined", msg.nickname); + break; + case Network::IdMemberLeave: + message = fmt::format("{} has left", msg.nickname); + break; + case Network::IdMemberKicked: + message = fmt::format("{} has been kicked", msg.nickname); + break; + case Network::IdMemberBanned: + message = fmt::format("{} has been banned", msg.nickname); + break; + case Network::IdAddressUnbanned: + message = fmt::format("{} has been unbanned", msg.nickname); + break; + } + if (!message.empty()) + std::cout << std::endl << "* " << message << std::endl << std::endl; +} + +/// Application entry point +int main(int argc, char** argv) { +#ifdef _WIN32 + if (AttachConsole(ATTACH_PARENT_PROCESS)) { + freopen("CONOUT$", "wb", stdout); + freopen("CONOUT$", "wb", stderr); + } +#endif + + Common::Log::Initialize(); + Common::Log::SetColorConsoleBackendEnabled(true); + Common::Log::Start(); + Common::DetachedTasks detached_tasks; + + int option_index = 0; +#ifdef _WIN32 + int argc_w; + auto argv_w = CommandLineToArgvW(GetCommandLineW(), &argc_w); + + if (argv_w == nullptr) { + LOG_CRITICAL(Frontend, "Failed to get command line arguments"); + return -1; + } +#endif + std::string filepath; + std::optional config_path; + std::string program_args; + std::optional selected_user; + + bool use_multiplayer = false; + bool fullscreen = false; + std::string nickname{}; + std::string password{}; + std::string address{}; + u16 port = Network::DefaultRoomPort; + + static struct option long_options[] = { + // clang-format off + {"config", required_argument, 0, 'c'}, + {"fullscreen", no_argument, 0, 'f'}, + {"help", no_argument, 0, 'h'}, + {"game", required_argument, 0, 'g'}, + {"multiplayer", required_argument, 0, 'm'}, + {"program", optional_argument, 0, 'p'}, + {"user", required_argument, 0, 'u'}, + {"version", no_argument, 0, 'v'}, + {0, 0, 0, 0}, + // clang-format on + }; + + while (optind < argc) { + int arg = getopt_long(argc, argv, "g:fhvp::c:u:", long_options, &option_index); + if (arg != -1) { + switch (static_cast(arg)) { + case 'c': + config_path = optarg; + break; + case 'f': + fullscreen = true; + LOG_INFO(Frontend, "Starting in fullscreen mode..."); + break; + case 'h': + PrintHelp(argv[0]); + return 0; + case 'g': { + const std::string str_arg(optarg); + filepath = str_arg; + break; + } + case 'm': { + use_multiplayer = true; + const std::string str_arg(optarg); + // regex to check if the format is nickname:password@ip:port + // with optional :password + const std::regex re("^([^:]+)(?::(.+))?@([^:]+)(?::([0-9]+))?$"); + if (!std::regex_match(str_arg, re)) { + std::cout << "Wrong format for option --multiplayer\n"; + PrintHelp(argv[0]); + return 0; + } + + std::smatch match; + std::regex_search(str_arg, match, re); + ASSERT(match.size() == 5); + nickname = match[1]; + password = match[2]; + address = match[3]; + if (!match[4].str().empty()) { + port = static_cast(std::strtoul(match[4].str().c_str(), nullptr, 0)); + } + std::regex nickname_re("^[a-zA-Z0-9._\\- ]+$"); + if (!std::regex_match(nickname, nickname_re)) { + std::cout + << "Nickname is not valid. Must be 4 to 20 alphanumeric characters.\n"; + return 0; + } + if (address.empty()) { + std::cout << "Address to room must not be empty.\n"; + return 0; + } + break; + } + case 'p': + program_args = argv[optind]; + ++optind; + break; + case 'u': + selected_user = atoi(optarg); + break; + case 'v': + PrintVersion(); + return 0; + } + } else { +#ifdef _WIN32 + filepath = Common::UTF16ToUTF8(argv_w[optind]); +#else + filepath = argv[optind]; +#endif + optind++; + } + } + + SdlConfig config{config_path}; + + // apply the log_filter setting + // the logger was initialized before and doesn't pick up the filter on its own + Common::Log::Filter filter; + filter.ParseFilterString(Settings::values.log_filter.GetValue()); + Common::Log::SetGlobalFilter(filter); + + if (!program_args.empty()) { + Settings::values.program_args = program_args; + } + + if (selected_user.has_value()) { + Settings::values.current_user = std::clamp(*selected_user, 0, 7); + } + +#ifdef _WIN32 + LocalFree(argv_w); +#endif + + MicroProfileOnThreadCreate("EmuThread"); + SCOPE_EXIT { + MicroProfileShutdown(); + }; + + Common::ConfigureNvidiaEnvironmentFlags(); + + if (filepath.empty()) { + LOG_CRITICAL(Frontend, "Failed to load ROM: No ROM specified"); + return -1; + } + + Core::System system{}; + system.Initialize(); + + InputCommon::InputSubsystem input_subsystem{}; + + // Apply the command line arguments + system.ApplySettings(); + + std::unique_ptr emu_window; + switch (Settings::values.renderer_backend.GetValue()) { + case Settings::RendererBackend::OpenGL: + emu_window = std::make_unique(&input_subsystem, system, fullscreen); + break; + case Settings::RendererBackend::Vulkan: + emu_window = std::make_unique(&input_subsystem, system, fullscreen); + break; + case Settings::RendererBackend::Null: + emu_window = std::make_unique(&input_subsystem, system, fullscreen); + break; + } + +#ifdef _WIN32 + Common::Windows::SetCurrentTimerResolutionToMaximum(); + system.CoreTiming().SetTimerResolutionNs(Common::Windows::GetCurrentTimerResolution()); +#endif + + system.SetContentProvider(std::make_unique()); + system.SetFilesystem(std::make_shared()); + system.GetFileSystemController().CreateFactories(*system.GetFilesystem()); + system.GetUserChannel().clear(); + + Service::AM::FrontendAppletParameters load_parameters{ + .applet_id = Service::AM::AppletId::Application, + }; + const Core::SystemResultStatus load_result{system.Load(*emu_window, filepath, load_parameters)}; + + switch (load_result) { + case Core::SystemResultStatus::ErrorGetLoader: + LOG_CRITICAL(Frontend, "Failed to obtain loader for {}!", filepath); + return -1; + case Core::SystemResultStatus::ErrorLoader: + LOG_CRITICAL(Frontend, "Failed to load ROM!"); + return -1; + case Core::SystemResultStatus::ErrorNotInitialized: + LOG_CRITICAL(Frontend, "CPUCore not initialized"); + return -1; + case Core::SystemResultStatus::ErrorVideoCore: + LOG_CRITICAL(Frontend, "Failed to initialize VideoCore!"); + return -1; + case Core::SystemResultStatus::Success: + break; // Expected case + default: + if (static_cast(load_result) > + static_cast(Core::SystemResultStatus::ErrorLoader)) { + const u16 loader_id = static_cast(Core::SystemResultStatus::ErrorLoader); + const u16 error_id = static_cast(load_result) - loader_id; + LOG_CRITICAL(Frontend, + "While attempting to load the ROM requested, an error occurred. Please " + "refer to the sudachi wiki for more information or the sudachi discord for " + "additional help.\n\nError Code: {:04X}-{:04X}\nError Description: {}", + loader_id, error_id, static_cast(error_id)); + } + break; + } + + system.TelemetrySession().AddField(Common::Telemetry::FieldType::App, "Frontend", "SDL"); + + if (use_multiplayer) { + if (auto member = system.GetRoomNetwork().GetRoomMember().lock()) { + member->BindOnChatMessageReceived(OnMessageReceived); + member->BindOnStatusMessageReceived(OnStatusMessageReceived); + member->BindOnStateChanged(OnStateChanged); + member->BindOnError(OnNetworkError); + LOG_DEBUG(Network, "Start connection to {}:{} with nickname {}", address, port, + nickname); + member->Join(nickname, address.c_str(), port, 0, Network::NoPreferredIP, password); + } else { + LOG_ERROR(Network, "Could not access RoomMember"); + return 0; + } + } + + // Core is loaded, start the GPU (makes the GPU contexts current to this thread) + system.GPU().Start(); + system.GetCpuManager().OnGpuReady(); + + if (Settings::values.use_disk_shader_cache.GetValue()) { + system.Renderer().ReadRasterizer()->LoadDiskResources( + system.GetApplicationProcessProgramID(), std::stop_token{}, + [](VideoCore::LoadCallbackStage, size_t value, size_t total) {}); + } + + system.RegisterExitCallback([&] { + // Just exit right away. + exit(0); + }); + +#ifdef __unix__ + Common::Linux::StartGamemode(); +#endif + + void(system.Run()); + if (system.DebuggerEnabled()) { + system.InitializeDebugger(); + } + while (emu_window->IsOpen()) { + emu_window->WaitEvent(); + } + system.DetachDebugger(); + void(system.Pause()); + system.ShutdownMainProcess(); + +#ifdef __unix__ + Common::Linux::StopGamemode(); +#endif + + detached_tasks.WaitForAllTasks(); + return 0; +} diff --git a/src/sudachi_cmd/sudachi.rc b/src/sudachi_cmd/sudachi.rc new file mode 100644 index 0000000..294e49c --- /dev/null +++ b/src/sudachi_cmd/sudachi.rc @@ -0,0 +1,20 @@ +// SPDX-FileCopyrightText: 2018 sudachi Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include "winresrc.h" +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +SUDACHI_ICON ICON "../../dist/sudachi.ico" + + +///////////////////////////////////////////////////////////////////////////// +// +// RT_MANIFEST +// + +0 RT_MANIFEST "../../dist/sudachi.manifest"