InputViewModel.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879
  1. using Avalonia.Collections;
  2. using Avalonia.Controls;
  3. using Avalonia.Svg.Skia;
  4. using Avalonia.Threading;
  5. using CommunityToolkit.Mvvm.ComponentModel;
  6. using Ryujinx.Ava.Common.Locale;
  7. using Ryujinx.Ava.Input;
  8. using Ryujinx.Ava.UI.Helpers;
  9. using Ryujinx.Ava.UI.Models;
  10. using Ryujinx.Ava.UI.Models.Input;
  11. using Ryujinx.Ava.UI.Windows;
  12. using Ryujinx.Ava.Utilities.Configuration;
  13. using Ryujinx.Common;
  14. using Ryujinx.Common.Configuration;
  15. using Ryujinx.Common.Configuration.Hid;
  16. using Ryujinx.Common.Configuration.Hid.Controller;
  17. using Ryujinx.Common.Configuration.Hid.Controller.Motion;
  18. using Ryujinx.Common.Configuration.Hid.Keyboard;
  19. using Ryujinx.Common.Logging;
  20. using Ryujinx.Common.Utilities;
  21. using Ryujinx.Input;
  22. using System;
  23. using System.Collections.Generic;
  24. using System.Collections.ObjectModel;
  25. using System.IO;
  26. using System.Linq;
  27. using System.Text.Json;
  28. using ConfigGamepadInputId = Ryujinx.Common.Configuration.Hid.Controller.GamepadInputId;
  29. using ConfigStickInputId = Ryujinx.Common.Configuration.Hid.Controller.StickInputId;
  30. using Key = Ryujinx.Common.Configuration.Hid.Key;
  31. namespace Ryujinx.Ava.UI.ViewModels.Input
  32. {
  33. public partial class InputViewModel : BaseModel, IDisposable
  34. {
  35. private const string Disabled = "disabled";
  36. private const string ProControllerResource = "Ryujinx/Assets/Icons/Controller_ProCon.svg";
  37. private const string JoyConPairResource = "Ryujinx/Assets/Icons/Controller_JoyConPair.svg";
  38. private const string JoyConLeftResource = "Ryujinx/Assets/Icons/Controller_JoyConLeft.svg";
  39. private const string JoyConRightResource = "Ryujinx/Assets/Icons/Controller_JoyConRight.svg";
  40. private const string KeyboardString = "keyboard";
  41. private const string ControllerString = "controller";
  42. private readonly MainWindow _mainWindow;
  43. private PlayerIndex _playerId;
  44. private PlayerIndex _playerIdChoose;
  45. private int _controller;
  46. private string _controllerImage;
  47. private int _device;
  48. [ObservableProperty] private object _configViewModel;
  49. [ObservableProperty] private string _profileName;
  50. private bool _isLoaded;
  51. private static readonly InputConfigJsonSerializerContext _serializerContext = new(JsonHelper.GetDefaultSerializerOptions());
  52. public IGamepadDriver AvaloniaKeyboardDriver { get; }
  53. public IGamepad SelectedGamepad { get; private set; }
  54. public ObservableCollection<PlayerModel> PlayerIndexes { get; set; }
  55. public ObservableCollection<(DeviceType Type, string Id, string Name)> Devices { get; set; }
  56. internal ObservableCollection<ControllerModel> Controllers { get; set; }
  57. public AvaloniaList<string> ProfilesList { get; set; }
  58. public AvaloniaList<string> DeviceList { get; set; }
  59. // XAML Flags
  60. public bool ShowSettings => _device > 0;
  61. public bool IsController => _device > 1;
  62. public bool IsKeyboard => !IsController;
  63. public bool IsRight { get; set; }
  64. public bool IsLeft { get; set; }
  65. public bool IsModified { get; set; }
  66. public event Action NotifyChangesEvent;
  67. public PlayerIndex PlayerIdChoose
  68. {
  69. get => _playerIdChoose;
  70. set { }
  71. }
  72. public PlayerIndex PlayerId
  73. {
  74. get => _playerId;
  75. set
  76. {
  77. if (IsModified)
  78. {
  79. _playerIdChoose = value;
  80. return;
  81. }
  82. IsModified = false;
  83. _playerId = value;
  84. if (!Enum.IsDefined<PlayerIndex>(_playerId))
  85. {
  86. _playerId = PlayerIndex.Player1;
  87. }
  88. _isLoaded = false;
  89. LoadConfiguration();
  90. LoadDevice();
  91. LoadProfiles();
  92. _isLoaded = true;
  93. OnPropertyChanged();
  94. }
  95. }
  96. public int Controller
  97. {
  98. get => _controller;
  99. set
  100. {
  101. _controller = value;
  102. if (_controller == -1)
  103. {
  104. _controller = 0;
  105. }
  106. if (Controllers.Count > 0 && value < Controllers.Count && _controller > -1)
  107. {
  108. ControllerType controller = Controllers[_controller].Type;
  109. IsLeft = true;
  110. IsRight = true;
  111. switch (controller)
  112. {
  113. case ControllerType.Handheld:
  114. ControllerImage = JoyConPairResource;
  115. break;
  116. case ControllerType.ProController:
  117. ControllerImage = ProControllerResource;
  118. break;
  119. case ControllerType.JoyconPair:
  120. ControllerImage = JoyConPairResource;
  121. break;
  122. case ControllerType.JoyconLeft:
  123. ControllerImage = JoyConLeftResource;
  124. IsRight = false;
  125. break;
  126. case ControllerType.JoyconRight:
  127. ControllerImage = JoyConRightResource;
  128. IsLeft = false;
  129. break;
  130. }
  131. LoadInputDriver();
  132. LoadProfiles();
  133. }
  134. OnPropertyChanged();
  135. NotifyChanges();
  136. }
  137. }
  138. public string ControllerImage
  139. {
  140. get => _controllerImage;
  141. set
  142. {
  143. _controllerImage = value;
  144. OnPropertyChanged();
  145. OnPropertyChanged(nameof(Image));
  146. }
  147. }
  148. public SvgImage Image
  149. {
  150. get
  151. {
  152. SvgImage image = new();
  153. if (!string.IsNullOrWhiteSpace(_controllerImage))
  154. {
  155. SvgSource source = SvgSource.LoadFromStream(EmbeddedResources.GetStream(_controllerImage));
  156. image.Source = source;
  157. }
  158. return image;
  159. }
  160. }
  161. public int Device
  162. {
  163. get => _device;
  164. set
  165. {
  166. _device = value < 0 ? 0 : value;
  167. if (_device >= Devices.Count)
  168. {
  169. return;
  170. }
  171. var selected = Devices[_device].Type;
  172. if (selected != DeviceType.None)
  173. {
  174. LoadControllers();
  175. if (_isLoaded)
  176. {
  177. LoadConfiguration(LoadDefaultConfiguration());
  178. }
  179. }
  180. OnPropertyChanged();
  181. NotifyChanges();
  182. }
  183. }
  184. public InputConfig Config { get; set; }
  185. public InputViewModel(UserControl owner) : this()
  186. {
  187. if (Program.PreviewerDetached)
  188. {
  189. _mainWindow = RyujinxApp.MainWindow;
  190. AvaloniaKeyboardDriver = new AvaloniaKeyboardDriver(owner);
  191. _mainWindow.InputManager.GamepadDriver.OnGamepadConnected += HandleOnGamepadConnected;
  192. _mainWindow.InputManager.GamepadDriver.OnGamepadDisconnected += HandleOnGamepadDisconnected;
  193. _mainWindow.ViewModel.AppHost?.NpadManager.BlockInputUpdates();
  194. _isLoaded = false;
  195. LoadDevices();
  196. PlayerId = PlayerIndex.Player1;
  197. }
  198. }
  199. public InputViewModel()
  200. {
  201. PlayerIndexes = new ObservableCollection<PlayerModel>();
  202. Controllers = new ObservableCollection<ControllerModel>();
  203. Devices = new ObservableCollection<(DeviceType Type, string Id, string Name)>();
  204. ProfilesList = new AvaloniaList<string>();
  205. DeviceList = new AvaloniaList<string>();
  206. ControllerImage = ProControllerResource;
  207. PlayerIndexes.Add(new(PlayerIndex.Player1, LocaleManager.Instance[LocaleKeys.ControllerSettingsPlayer1]));
  208. PlayerIndexes.Add(new(PlayerIndex.Player2, LocaleManager.Instance[LocaleKeys.ControllerSettingsPlayer2]));
  209. PlayerIndexes.Add(new(PlayerIndex.Player3, LocaleManager.Instance[LocaleKeys.ControllerSettingsPlayer3]));
  210. PlayerIndexes.Add(new(PlayerIndex.Player4, LocaleManager.Instance[LocaleKeys.ControllerSettingsPlayer4]));
  211. PlayerIndexes.Add(new(PlayerIndex.Player5, LocaleManager.Instance[LocaleKeys.ControllerSettingsPlayer5]));
  212. PlayerIndexes.Add(new(PlayerIndex.Player6, LocaleManager.Instance[LocaleKeys.ControllerSettingsPlayer6]));
  213. PlayerIndexes.Add(new(PlayerIndex.Player7, LocaleManager.Instance[LocaleKeys.ControllerSettingsPlayer7]));
  214. PlayerIndexes.Add(new(PlayerIndex.Player8, LocaleManager.Instance[LocaleKeys.ControllerSettingsPlayer8]));
  215. PlayerIndexes.Add(new(PlayerIndex.Handheld, LocaleManager.Instance[LocaleKeys.ControllerSettingsHandheld]));
  216. }
  217. private void LoadConfiguration(InputConfig inputConfig = null)
  218. {
  219. Config = inputConfig ?? ConfigurationState.Instance.Hid.InputConfig.Value.FirstOrDefault(inputConfig => inputConfig.PlayerIndex == _playerId);
  220. if (Config is StandardKeyboardInputConfig keyboardInputConfig)
  221. {
  222. ConfigViewModel = new KeyboardInputViewModel(this, new KeyboardInputConfig(keyboardInputConfig));
  223. }
  224. if (Config is StandardControllerInputConfig controllerInputConfig)
  225. {
  226. ConfigViewModel = new ControllerInputViewModel(this, new GamepadInputConfig(controllerInputConfig));
  227. }
  228. }
  229. public void LoadDevice()
  230. {
  231. if (Config == null || Config.Backend == InputBackendType.Invalid)
  232. {
  233. Device = 0;
  234. }
  235. else
  236. {
  237. var type = DeviceType.None;
  238. if (Config is StandardKeyboardInputConfig)
  239. {
  240. type = DeviceType.Keyboard;
  241. }
  242. if (Config is StandardControllerInputConfig)
  243. {
  244. type = DeviceType.Controller;
  245. }
  246. var item = Devices.FirstOrDefault(x => x.Type == type && x.Id == Config.Id);
  247. if (item != default)
  248. {
  249. Device = Devices.ToList().FindIndex(x => x.Id == item.Id);
  250. }
  251. else
  252. {
  253. Device = 0;
  254. }
  255. }
  256. }
  257. private void LoadInputDriver()
  258. {
  259. if (_device < 0)
  260. {
  261. return;
  262. }
  263. string id = GetCurrentGamepadId();
  264. var type = Devices[Device].Type;
  265. if (type == DeviceType.None)
  266. {
  267. return;
  268. }
  269. if (type == DeviceType.Keyboard)
  270. {
  271. if (_mainWindow.InputManager.KeyboardDriver is AvaloniaKeyboardDriver)
  272. {
  273. // NOTE: To get input in this window, we need to bind a custom keyboard driver instead of using the InputManager one as the main window isn't focused...
  274. SelectedGamepad = AvaloniaKeyboardDriver.GetGamepad(id);
  275. }
  276. else
  277. {
  278. SelectedGamepad = _mainWindow.InputManager.KeyboardDriver.GetGamepad(id);
  279. }
  280. }
  281. else
  282. {
  283. SelectedGamepad = _mainWindow.InputManager.GamepadDriver.GetGamepad(id);
  284. }
  285. }
  286. private void HandleOnGamepadDisconnected(string id)
  287. {
  288. Dispatcher.UIThread.Post(LoadDevices);
  289. }
  290. private void HandleOnGamepadConnected(string id)
  291. {
  292. Dispatcher.UIThread.Post(LoadDevices);
  293. }
  294. private string GetCurrentGamepadId()
  295. {
  296. if (_device < 0)
  297. {
  298. return string.Empty;
  299. }
  300. var device = Devices[Device];
  301. if (device.Type == DeviceType.None)
  302. {
  303. return null;
  304. }
  305. return device.Id.Split(" ")[0];
  306. }
  307. public void LoadControllers()
  308. {
  309. Controllers.Clear();
  310. if (_playerId == PlayerIndex.Handheld)
  311. {
  312. Controllers.Add(new(ControllerType.Handheld, LocaleManager.Instance[LocaleKeys.ControllerSettingsControllerTypeHandheld]));
  313. Controller = 0;
  314. }
  315. else
  316. {
  317. Controllers.Add(new(ControllerType.ProController, LocaleManager.Instance[LocaleKeys.ControllerSettingsControllerTypeProController]));
  318. Controllers.Add(new(ControllerType.JoyconPair, LocaleManager.Instance[LocaleKeys.ControllerSettingsControllerTypeJoyConPair]));
  319. Controllers.Add(new(ControllerType.JoyconLeft, LocaleManager.Instance[LocaleKeys.ControllerSettingsControllerTypeJoyConLeft]));
  320. Controllers.Add(new(ControllerType.JoyconRight, LocaleManager.Instance[LocaleKeys.ControllerSettingsControllerTypeJoyConRight]));
  321. if (Config != null && Controllers.ToList().FindIndex(x => x.Type == Config.ControllerType) != -1)
  322. {
  323. Controller = Controllers.ToList().FindIndex(x => x.Type == Config.ControllerType);
  324. }
  325. else
  326. {
  327. Controller = 0;
  328. }
  329. }
  330. }
  331. private static string GetShortGamepadName(string str)
  332. {
  333. const string Ellipsis = "...";
  334. const int MaxSize = 50;
  335. if (str.Length > MaxSize)
  336. {
  337. return $"{str.AsSpan(0, MaxSize - Ellipsis.Length)}{Ellipsis}";
  338. }
  339. return str;
  340. }
  341. private static string GetShortGamepadId(string str)
  342. {
  343. const string Hyphen = "-";
  344. const int Offset = 1;
  345. return str[(str.IndexOf(Hyphen) + Offset)..];
  346. }
  347. public void LoadDevices()
  348. {
  349. string GetGamepadName(IGamepad gamepad, int controllerNumber)
  350. {
  351. return $"{GetShortGamepadName(gamepad.Name)} ({controllerNumber})";
  352. }
  353. string GetUniqueGamepadName(IGamepad gamepad, ref int controllerNumber)
  354. {
  355. string name = GetGamepadName(gamepad, controllerNumber);
  356. if (Devices.Any(controller => controller.Name == name))
  357. {
  358. controllerNumber++;
  359. name = GetGamepadName(gamepad, controllerNumber);
  360. }
  361. return name;
  362. }
  363. lock (Devices)
  364. {
  365. Devices.Clear();
  366. DeviceList.Clear();
  367. Devices.Add((DeviceType.None, Disabled, LocaleManager.Instance[LocaleKeys.ControllerSettingsDeviceDisabled]));
  368. int controllerNumber = 0;
  369. foreach (string id in _mainWindow.InputManager.KeyboardDriver.GamepadsIds)
  370. {
  371. using IGamepad gamepad = _mainWindow.InputManager.KeyboardDriver.GetGamepad(id);
  372. if (gamepad != null)
  373. {
  374. Devices.Add((DeviceType.Keyboard, id, $"{GetShortGamepadName(gamepad.Name)}"));
  375. }
  376. }
  377. foreach (string id in _mainWindow.InputManager.GamepadDriver.GamepadsIds)
  378. {
  379. using IGamepad gamepad = _mainWindow.InputManager.GamepadDriver.GetGamepad(id);
  380. if (gamepad != null)
  381. {
  382. string name = GetUniqueGamepadName(gamepad, ref controllerNumber);
  383. Devices.Add((DeviceType.Controller, id, name));
  384. }
  385. }
  386. DeviceList.AddRange(Devices.Select(x => x.Name));
  387. Device = Math.Min(Device, DeviceList.Count);
  388. }
  389. }
  390. private string GetProfileBasePath()
  391. {
  392. string path = AppDataManager.ProfilesDirPath;
  393. var type = Devices[Device == -1 ? 0 : Device].Type;
  394. if (type == DeviceType.Keyboard)
  395. {
  396. path = Path.Combine(path, KeyboardString);
  397. }
  398. else if (type == DeviceType.Controller)
  399. {
  400. path = Path.Combine(path, ControllerString);
  401. }
  402. return path;
  403. }
  404. private void LoadProfiles()
  405. {
  406. ProfilesList.Clear();
  407. string basePath = GetProfileBasePath();
  408. if (!Directory.Exists(basePath))
  409. {
  410. Directory.CreateDirectory(basePath);
  411. }
  412. ProfilesList.Add((LocaleManager.Instance[LocaleKeys.ControllerSettingsProfileDefault]));
  413. foreach (string profile in Directory.GetFiles(basePath, "*.json", SearchOption.AllDirectories))
  414. {
  415. ProfilesList.Add(Path.GetFileNameWithoutExtension(profile));
  416. }
  417. if (string.IsNullOrWhiteSpace(ProfileName))
  418. {
  419. ProfileName = LocaleManager.Instance[LocaleKeys.ControllerSettingsProfileDefault];
  420. }
  421. }
  422. public InputConfig LoadDefaultConfiguration()
  423. {
  424. var activeDevice = Devices.FirstOrDefault();
  425. if (Devices.Count > 0 && Device < Devices.Count && Device >= 0)
  426. {
  427. activeDevice = Devices[Device];
  428. }
  429. InputConfig config;
  430. if (activeDevice.Type == DeviceType.Keyboard)
  431. {
  432. string id = activeDevice.Id;
  433. config = new StandardKeyboardInputConfig
  434. {
  435. Version = InputConfig.CurrentVersion,
  436. Backend = InputBackendType.WindowKeyboard,
  437. Id = id,
  438. ControllerType = ControllerType.ProController,
  439. LeftJoycon = new LeftJoyconCommonConfig<Key>
  440. {
  441. DpadUp = Key.Up,
  442. DpadDown = Key.Down,
  443. DpadLeft = Key.Left,
  444. DpadRight = Key.Right,
  445. ButtonMinus = Key.Minus,
  446. ButtonL = Key.E,
  447. ButtonZl = Key.Q,
  448. ButtonSl = Key.Unbound,
  449. ButtonSr = Key.Unbound,
  450. },
  451. LeftJoyconStick =
  452. new JoyconConfigKeyboardStick<Key>
  453. {
  454. StickUp = Key.W,
  455. StickDown = Key.S,
  456. StickLeft = Key.A,
  457. StickRight = Key.D,
  458. StickButton = Key.F,
  459. },
  460. RightJoycon = new RightJoyconCommonConfig<Key>
  461. {
  462. ButtonA = Key.Z,
  463. ButtonB = Key.X,
  464. ButtonX = Key.C,
  465. ButtonY = Key.V,
  466. ButtonPlus = Key.Plus,
  467. ButtonR = Key.U,
  468. ButtonZr = Key.O,
  469. ButtonSl = Key.Unbound,
  470. ButtonSr = Key.Unbound,
  471. },
  472. RightJoyconStick = new JoyconConfigKeyboardStick<Key>
  473. {
  474. StickUp = Key.I,
  475. StickDown = Key.K,
  476. StickLeft = Key.J,
  477. StickRight = Key.L,
  478. StickButton = Key.H,
  479. },
  480. };
  481. }
  482. else if (activeDevice.Type == DeviceType.Controller)
  483. {
  484. bool isNintendoStyle = Devices.ToList().FirstOrDefault(x => x.Id == activeDevice.Id).Name.Contains("Nintendo");
  485. string id = activeDevice.Id.Split(" ")[0];
  486. config = new StandardControllerInputConfig
  487. {
  488. Version = InputConfig.CurrentVersion,
  489. Backend = InputBackendType.GamepadSDL2,
  490. Id = id,
  491. ControllerType = ControllerType.ProController,
  492. DeadzoneLeft = 0.1f,
  493. DeadzoneRight = 0.1f,
  494. RangeLeft = 1.0f,
  495. RangeRight = 1.0f,
  496. TriggerThreshold = 0.5f,
  497. LeftJoycon = new LeftJoyconCommonConfig<ConfigGamepadInputId>
  498. {
  499. DpadUp = ConfigGamepadInputId.DpadUp,
  500. DpadDown = ConfigGamepadInputId.DpadDown,
  501. DpadLeft = ConfigGamepadInputId.DpadLeft,
  502. DpadRight = ConfigGamepadInputId.DpadRight,
  503. ButtonMinus = ConfigGamepadInputId.Minus,
  504. ButtonL = ConfigGamepadInputId.LeftShoulder,
  505. ButtonZl = ConfigGamepadInputId.LeftTrigger,
  506. ButtonSl = ConfigGamepadInputId.Unbound,
  507. ButtonSr = ConfigGamepadInputId.Unbound,
  508. },
  509. LeftJoyconStick = new JoyconConfigControllerStick<ConfigGamepadInputId, ConfigStickInputId>
  510. {
  511. Joystick = ConfigStickInputId.Left,
  512. StickButton = ConfigGamepadInputId.LeftStick,
  513. InvertStickX = false,
  514. InvertStickY = false,
  515. },
  516. RightJoycon = new RightJoyconCommonConfig<ConfigGamepadInputId>
  517. {
  518. ButtonA = isNintendoStyle ? ConfigGamepadInputId.A : ConfigGamepadInputId.B,
  519. ButtonB = isNintendoStyle ? ConfigGamepadInputId.B : ConfigGamepadInputId.A,
  520. ButtonX = isNintendoStyle ? ConfigGamepadInputId.X : ConfigGamepadInputId.Y,
  521. ButtonY = isNintendoStyle ? ConfigGamepadInputId.Y : ConfigGamepadInputId.X,
  522. ButtonPlus = ConfigGamepadInputId.Plus,
  523. ButtonR = ConfigGamepadInputId.RightShoulder,
  524. ButtonZr = ConfigGamepadInputId.RightTrigger,
  525. ButtonSl = ConfigGamepadInputId.Unbound,
  526. ButtonSr = ConfigGamepadInputId.Unbound,
  527. },
  528. RightJoyconStick = new JoyconConfigControllerStick<ConfigGamepadInputId, ConfigStickInputId>
  529. {
  530. Joystick = ConfigStickInputId.Right,
  531. StickButton = ConfigGamepadInputId.RightStick,
  532. InvertStickX = false,
  533. InvertStickY = false,
  534. },
  535. Motion = new StandardMotionConfigController
  536. {
  537. MotionBackend = MotionInputBackendType.GamepadDriver,
  538. EnableMotion = true,
  539. Sensitivity = 100,
  540. GyroDeadzone = 1,
  541. },
  542. Rumble = new RumbleConfigController
  543. {
  544. StrongRumble = 1f,
  545. WeakRumble = 1f,
  546. EnableRumble = false,
  547. },
  548. };
  549. }
  550. else
  551. {
  552. config = new InputConfig();
  553. }
  554. config.PlayerIndex = _playerId;
  555. return config;
  556. }
  557. public async void LoadProfile()
  558. {
  559. if (Device == 0)
  560. {
  561. return;
  562. }
  563. InputConfig config = null;
  564. if (string.IsNullOrWhiteSpace(ProfileName))
  565. {
  566. return;
  567. }
  568. if (ProfileName == LocaleManager.Instance[LocaleKeys.ControllerSettingsProfileDefault])
  569. {
  570. config = LoadDefaultConfiguration();
  571. }
  572. else
  573. {
  574. string path = Path.Combine(GetProfileBasePath(), ProfileName + ".json");
  575. if (!File.Exists(path))
  576. {
  577. int index = ProfilesList.IndexOf(ProfileName);
  578. if (index != -1)
  579. {
  580. ProfilesList.RemoveAt(index);
  581. }
  582. return;
  583. }
  584. try
  585. {
  586. config = JsonHelper.DeserializeFromFile(path, _serializerContext.InputConfig);
  587. }
  588. catch (JsonException) { }
  589. catch (InvalidOperationException)
  590. {
  591. Logger.Error?.Print(LogClass.Configuration, $"Profile {ProfileName} is incompatible with the current input configuration system.");
  592. await ContentDialogHelper.CreateErrorDialog(LocaleManager.Instance.UpdateAndGetDynamicValue(LocaleKeys.DialogProfileInvalidProfileErrorMessage, ProfileName));
  593. return;
  594. }
  595. }
  596. if (config != null)
  597. {
  598. _isLoaded = false;
  599. LoadConfiguration(config);
  600. LoadDevice();
  601. _isLoaded = true;
  602. NotifyChanges();
  603. }
  604. }
  605. public async void SaveProfile()
  606. {
  607. if (Device == 0)
  608. {
  609. return;
  610. }
  611. if (ConfigViewModel == null)
  612. {
  613. return;
  614. }
  615. if (ProfileName == LocaleManager.Instance[LocaleKeys.ControllerSettingsProfileDefault])
  616. {
  617. await ContentDialogHelper.CreateErrorDialog(LocaleManager.Instance[LocaleKeys.DialogProfileDefaultProfileOverwriteErrorMessage]);
  618. return;
  619. }
  620. else
  621. {
  622. bool validFileName = ProfileName.IndexOfAny(Path.GetInvalidFileNameChars()) == -1;
  623. if (validFileName)
  624. {
  625. string path = Path.Combine(GetProfileBasePath(), ProfileName + ".json");
  626. InputConfig config = null;
  627. if (IsKeyboard)
  628. {
  629. config = (ConfigViewModel as KeyboardInputViewModel).Config.GetConfig();
  630. }
  631. else if (IsController)
  632. {
  633. config = (ConfigViewModel as ControllerInputViewModel).Config.GetConfig();
  634. }
  635. config.ControllerType = Controllers[_controller].Type;
  636. string jsonString = JsonHelper.Serialize(config, _serializerContext.InputConfig);
  637. await File.WriteAllTextAsync(path, jsonString);
  638. LoadProfiles();
  639. }
  640. else
  641. {
  642. await ContentDialogHelper.CreateErrorDialog(LocaleManager.Instance[LocaleKeys.DialogProfileInvalidProfileNameErrorMessage]);
  643. }
  644. }
  645. }
  646. public async void RemoveProfile()
  647. {
  648. if (Device == 0 || ProfileName == LocaleManager.Instance[LocaleKeys.ControllerSettingsProfileDefault] || ProfilesList.IndexOf(ProfileName) == -1)
  649. {
  650. return;
  651. }
  652. UserResult result = await ContentDialogHelper.CreateConfirmationDialog(
  653. LocaleManager.Instance[LocaleKeys.DialogProfileDeleteProfileTitle],
  654. LocaleManager.Instance[LocaleKeys.DialogProfileDeleteProfileMessage],
  655. LocaleManager.Instance[LocaleKeys.InputDialogYes],
  656. LocaleManager.Instance[LocaleKeys.InputDialogNo],
  657. LocaleManager.Instance[LocaleKeys.RyujinxConfirm]);
  658. if (result == UserResult.Yes)
  659. {
  660. string path = Path.Combine(GetProfileBasePath(), ProfileName + ".json");
  661. if (File.Exists(path))
  662. {
  663. File.Delete(path);
  664. }
  665. LoadProfiles();
  666. }
  667. }
  668. public void Save()
  669. {
  670. IsModified = false;
  671. List<InputConfig> newConfig = new();
  672. newConfig.AddRange(ConfigurationState.Instance.Hid.InputConfig.Value);
  673. newConfig.Remove(newConfig.FirstOrDefault(x => x == null));
  674. if (Device == 0)
  675. {
  676. newConfig.Remove(newConfig.FirstOrDefault(x => x.PlayerIndex == this.PlayerId));
  677. }
  678. else
  679. {
  680. var device = Devices[Device];
  681. if (device.Type == DeviceType.Keyboard)
  682. {
  683. var inputConfig = (ConfigViewModel as KeyboardInputViewModel).Config;
  684. inputConfig.Id = device.Id;
  685. }
  686. else
  687. {
  688. var inputConfig = (ConfigViewModel as ControllerInputViewModel).Config;
  689. inputConfig.Id = device.Id.Split(" ")[0];
  690. }
  691. var config = !IsController
  692. ? (ConfigViewModel as KeyboardInputViewModel).Config.GetConfig()
  693. : (ConfigViewModel as ControllerInputViewModel).Config.GetConfig();
  694. config.ControllerType = Controllers[_controller].Type;
  695. config.PlayerIndex = _playerId;
  696. int i = newConfig.FindIndex(x => x.PlayerIndex == PlayerId);
  697. if (i == -1)
  698. {
  699. newConfig.Add(config);
  700. }
  701. else
  702. {
  703. newConfig[i] = config;
  704. }
  705. }
  706. _mainWindow.ViewModel.AppHost?.NpadManager.ReloadConfiguration(newConfig, ConfigurationState.Instance.Hid.EnableKeyboard, ConfigurationState.Instance.Hid.EnableMouse);
  707. // Atomically replace and signal input change.
  708. // NOTE: Do not modify InputConfig.Value directly as other code depends on the on-change event.
  709. ConfigurationState.Instance.Hid.InputConfig.Value = newConfig;
  710. ConfigurationState.Instance.ToFileFormat().SaveConfig(Program.ConfigurationPath);
  711. }
  712. public void NotifyChange(string property)
  713. {
  714. OnPropertyChanged(property);
  715. }
  716. public void NotifyChanges()
  717. {
  718. OnPropertyChanged(nameof(ConfigViewModel));
  719. OnPropertyChanged(nameof(IsController));
  720. OnPropertyChanged(nameof(ShowSettings));
  721. OnPropertyChanged(nameof(IsKeyboard));
  722. OnPropertyChanged(nameof(IsRight));
  723. OnPropertyChanged(nameof(IsLeft));
  724. NotifyChangesEvent?.Invoke();
  725. }
  726. public void Dispose()
  727. {
  728. GC.SuppressFinalize(this);
  729. _mainWindow.InputManager.GamepadDriver.OnGamepadConnected -= HandleOnGamepadConnected;
  730. _mainWindow.InputManager.GamepadDriver.OnGamepadDisconnected -= HandleOnGamepadDisconnected;
  731. _mainWindow.ViewModel.AppHost?.NpadManager.UnblockInputUpdates();
  732. SelectedGamepad?.Dispose();
  733. AvaloniaKeyboardDriver.Dispose();
  734. }
  735. }
  736. }