ControllerSettingsViewModel.cs 31 KB

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