ControllerSettingsViewModel.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886
  1. using Avalonia.Collections;
  2. using Avalonia.Controls;
  3. using Avalonia.Controls.ApplicationLifetimes;
  4. using Avalonia.Svg.Skia;
  5. using Avalonia.Threading;
  6. using Avalonia.VisualTree;
  7. using Ryujinx.Ava.Common.Locale;
  8. using Ryujinx.Ava.Input;
  9. using Ryujinx.Ava.Ui.Controls;
  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.Reflection;
  28. using System.Text.Json;
  29. using ConfigGamepadInputId = Ryujinx.Common.Configuration.Hid.Controller.GamepadInputId;
  30. using ConfigStickInputId = Ryujinx.Common.Configuration.Hid.Controller.StickInputId;
  31. using Key = Ryujinx.Common.Configuration.Hid.Key;
  32. namespace Ryujinx.Ava.Ui.ViewModels
  33. {
  34. public class ControllerSettingsViewModel : BaseModel, IDisposable
  35. {
  36. private const string Disabled = "disabled";
  37. private const string ProControllerResource = "Ryujinx.Ui.Common/Resources/Controller_ProCon.svg";
  38. private const string JoyConPairResource = "Ryujinx.Ui.Common/Resources/Controller_JoyConPair.svg";
  39. private const string JoyConLeftResource = "Ryujinx.Ui.Common/Resources/Controller_JoyConLeft.svg";
  40. private const string JoyConRightResource = "Ryujinx.Ui.Common/Resources/Controller_JoyConRight.svg";
  41. private const string KeyboardString = "keyboard";
  42. private const string ControllerString = "controller";
  43. private readonly MainWindow _mainWindow;
  44. private PlayerIndex _playerId;
  45. private int _controller;
  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.AppHost != null)
  207. {
  208. _mainWindow.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["ControllerSettingsPlayer1"]));
  224. PlayerIndexes.Add(new(PlayerIndex.Player2, LocaleManager.Instance["ControllerSettingsPlayer2"]));
  225. PlayerIndexes.Add(new(PlayerIndex.Player3, LocaleManager.Instance["ControllerSettingsPlayer3"]));
  226. PlayerIndexes.Add(new(PlayerIndex.Player4, LocaleManager.Instance["ControllerSettingsPlayer4"]));
  227. PlayerIndexes.Add(new(PlayerIndex.Player5, LocaleManager.Instance["ControllerSettingsPlayer5"]));
  228. PlayerIndexes.Add(new(PlayerIndex.Player6, LocaleManager.Instance["ControllerSettingsPlayer6"]));
  229. PlayerIndexes.Add(new(PlayerIndex.Player7, LocaleManager.Instance["ControllerSettingsPlayer7"]));
  230. PlayerIndexes.Add(new(PlayerIndex.Player8, LocaleManager.Instance["ControllerSettingsPlayer8"]));
  231. PlayerIndexes.Add(new(PlayerIndex.Handheld, LocaleManager.Instance["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["ControllerSettingsControllerTypeHandheld"]));
  343. Controller = 0;
  344. }
  345. else
  346. {
  347. Controllers.Add(new(ControllerType.ProController, LocaleManager.Instance["ControllerSettingsControllerTypeProController"]));
  348. Controllers.Add(new(ControllerType.JoyconPair, LocaleManager.Instance["ControllerSettingsControllerTypeJoyConPair"]));
  349. Controllers.Add(new(ControllerType.JoyconLeft, LocaleManager.Instance["ControllerSettingsControllerTypeJoyConLeft"]));
  350. Controllers.Add(new(ControllerType.JoyconRight, LocaleManager.Instance["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.Substring(0, MaxSize - Ellipsis.Length) + Ellipsis;
  368. }
  369. return str;
  370. }
  371. public void LoadDevices()
  372. {
  373. lock (Devices)
  374. {
  375. Devices.Clear();
  376. DeviceList.Clear();
  377. Devices.Add((DeviceType.None, Disabled, LocaleManager.Instance["ControllerSettingsDeviceDisabled"]));
  378. foreach (string id in _mainWindow.InputManager.KeyboardDriver.GamepadsIds)
  379. {
  380. using IGamepad gamepad = _mainWindow.InputManager.KeyboardDriver.GetGamepad(id);
  381. if (gamepad != null)
  382. {
  383. Devices.Add((DeviceType.Keyboard, id, $"{GetShortGamepadName(gamepad.Name)} ({id})"));
  384. }
  385. }
  386. foreach (string id in _mainWindow.InputManager.GamepadDriver.GamepadsIds)
  387. {
  388. using IGamepad gamepad = _mainWindow.InputManager.GamepadDriver.GetGamepad(id);
  389. if (gamepad != null)
  390. {
  391. Devices.Add((DeviceType.Controller, id, $"{GetShortGamepadName(gamepad.Name)} ({id})"));
  392. }
  393. }
  394. DeviceList.AddRange(Devices.Select(x => x.Name));
  395. Device = Math.Min(Device, DeviceList.Count);
  396. }
  397. }
  398. private string GetProfileBasePath()
  399. {
  400. string path = AppDataManager.ProfilesDirPath;
  401. var type = Devices[Device == -1 ? 0 : Device].Type;
  402. if (type == DeviceType.Keyboard)
  403. {
  404. path = Path.Combine(path, KeyboardString);
  405. }
  406. else if (type == DeviceType.Controller)
  407. {
  408. path = Path.Combine(path, ControllerString);
  409. }
  410. return path;
  411. }
  412. private void LoadProfiles()
  413. {
  414. ProfilesList.Clear();
  415. string basePath = GetProfileBasePath();
  416. if (!Directory.Exists(basePath))
  417. {
  418. Directory.CreateDirectory(basePath);
  419. }
  420. ProfilesList.Add((LocaleManager.Instance["ControllerSettingsProfileDefault"]));
  421. foreach (string profile in Directory.GetFiles(basePath, "*.json", SearchOption.AllDirectories))
  422. {
  423. ProfilesList.Add(Path.GetFileNameWithoutExtension(profile));
  424. }
  425. if (string.IsNullOrWhiteSpace(ProfileName))
  426. {
  427. ProfileName = LocaleManager.Instance["ControllerSettingsProfileDefault"];
  428. }
  429. }
  430. public InputConfig LoadDefaultConfiguration()
  431. {
  432. var activeDevice = Devices.FirstOrDefault();
  433. if (Devices.Count > 0 && Device < Devices.Count && Device >= 0)
  434. {
  435. activeDevice = Devices[Device];
  436. }
  437. InputConfig config;
  438. if (activeDevice.Type == DeviceType.Keyboard)
  439. {
  440. string id = activeDevice.Id;
  441. config = new StandardKeyboardInputConfig
  442. {
  443. Version = Ryujinx.Common.Configuration.Hid.InputConfig.CurrentVersion,
  444. Backend = InputBackendType.WindowKeyboard,
  445. Id = id,
  446. ControllerType = ControllerType.ProController,
  447. LeftJoycon = new LeftJoyconCommonConfig<Key>
  448. {
  449. DpadUp = Key.Up,
  450. DpadDown = Key.Down,
  451. DpadLeft = Key.Left,
  452. DpadRight = Key.Right,
  453. ButtonMinus = Key.Minus,
  454. ButtonL = Key.E,
  455. ButtonZl = Key.Q,
  456. ButtonSl = Key.Unbound,
  457. ButtonSr = Key.Unbound
  458. },
  459. LeftJoyconStick =
  460. new JoyconConfigKeyboardStick<Key>
  461. {
  462. StickUp = Key.W,
  463. StickDown = Key.S,
  464. StickLeft = Key.A,
  465. StickRight = Key.D,
  466. StickButton = Key.F
  467. },
  468. RightJoycon = new RightJoyconCommonConfig<Key>
  469. {
  470. ButtonA = Key.Z,
  471. ButtonB = Key.X,
  472. ButtonX = Key.C,
  473. ButtonY = Key.V,
  474. ButtonPlus = Key.Plus,
  475. ButtonR = Key.U,
  476. ButtonZr = Key.O,
  477. ButtonSl = Key.Unbound,
  478. ButtonSr = Key.Unbound
  479. },
  480. RightJoyconStick = new JoyconConfigKeyboardStick<Key>
  481. {
  482. StickUp = Key.I,
  483. StickDown = Key.K,
  484. StickLeft = Key.J,
  485. StickRight = Key.L,
  486. StickButton = Key.H
  487. }
  488. };
  489. }
  490. else if (activeDevice.Type == DeviceType.Controller)
  491. {
  492. bool isNintendoStyle = Devices.ToList().Find(x => x.Id == activeDevice.Id).Name.Contains("Nintendo");
  493. string id = activeDevice.Id.Split(" ")[0];
  494. config = new StandardControllerInputConfig
  495. {
  496. Version = Ryujinx.Common.Configuration.Hid.InputConfig.CurrentVersion,
  497. Backend = InputBackendType.GamepadSDL2,
  498. Id = id,
  499. ControllerType = ControllerType.ProController,
  500. DeadzoneLeft = 0.1f,
  501. DeadzoneRight = 0.1f,
  502. RangeLeft = 1.0f,
  503. RangeRight = 1.0f,
  504. TriggerThreshold = 0.5f,
  505. LeftJoycon = new LeftJoyconCommonConfig<ConfigGamepadInputId>
  506. {
  507. DpadUp = ConfigGamepadInputId.DpadUp,
  508. DpadDown = ConfigGamepadInputId.DpadDown,
  509. DpadLeft = ConfigGamepadInputId.DpadLeft,
  510. DpadRight = ConfigGamepadInputId.DpadRight,
  511. ButtonMinus = ConfigGamepadInputId.Minus,
  512. ButtonL = ConfigGamepadInputId.LeftShoulder,
  513. ButtonZl = ConfigGamepadInputId.LeftTrigger,
  514. ButtonSl = ConfigGamepadInputId.Unbound,
  515. ButtonSr = ConfigGamepadInputId.Unbound
  516. },
  517. LeftJoyconStick = new JoyconConfigControllerStick<ConfigGamepadInputId, ConfigStickInputId>
  518. {
  519. Joystick = ConfigStickInputId.Left,
  520. StickButton = ConfigGamepadInputId.LeftStick,
  521. InvertStickX = false,
  522. InvertStickY = false
  523. },
  524. RightJoycon = new RightJoyconCommonConfig<ConfigGamepadInputId>
  525. {
  526. ButtonA = isNintendoStyle ? ConfigGamepadInputId.A : ConfigGamepadInputId.B,
  527. ButtonB = isNintendoStyle ? ConfigGamepadInputId.B : ConfigGamepadInputId.A,
  528. ButtonX = isNintendoStyle ? ConfigGamepadInputId.X : ConfigGamepadInputId.Y,
  529. ButtonY = isNintendoStyle ? ConfigGamepadInputId.Y : ConfigGamepadInputId.X,
  530. ButtonPlus = ConfigGamepadInputId.Plus,
  531. ButtonR = ConfigGamepadInputId.RightShoulder,
  532. ButtonZr = ConfigGamepadInputId.RightTrigger,
  533. ButtonSl = ConfigGamepadInputId.Unbound,
  534. ButtonSr = ConfigGamepadInputId.Unbound
  535. },
  536. RightJoyconStick = new JoyconConfigControllerStick<ConfigGamepadInputId, ConfigStickInputId>
  537. {
  538. Joystick = ConfigStickInputId.Right,
  539. StickButton = ConfigGamepadInputId.RightStick,
  540. InvertStickX = false,
  541. InvertStickY = false
  542. },
  543. Motion = new StandardMotionConfigController
  544. {
  545. MotionBackend = MotionInputBackendType.GamepadDriver,
  546. EnableMotion = true,
  547. Sensitivity = 100,
  548. GyroDeadzone = 1
  549. },
  550. Rumble = new RumbleConfigController
  551. {
  552. StrongRumble = 1f,
  553. WeakRumble = 1f,
  554. EnableRumble = false
  555. }
  556. };
  557. }
  558. else
  559. {
  560. config = new InputConfig();
  561. }
  562. config.PlayerIndex = _playerId;
  563. return config;
  564. }
  565. public async void LoadProfile()
  566. {
  567. if (Device == 0)
  568. {
  569. return;
  570. }
  571. InputConfig config = null;
  572. if (string.IsNullOrWhiteSpace(ProfileName))
  573. {
  574. return;
  575. }
  576. if (ProfileName == LocaleManager.Instance["ControllerSettingsProfileDefault"])
  577. {
  578. config = LoadDefaultConfiguration();
  579. }
  580. else
  581. {
  582. string path = Path.Combine(GetProfileBasePath(), ProfileName + ".json");
  583. if (!File.Exists(path))
  584. {
  585. var index = ProfilesList.IndexOf(ProfileName);
  586. if (index != -1)
  587. {
  588. ProfilesList.RemoveAt(index);
  589. }
  590. return;
  591. }
  592. try
  593. {
  594. using (Stream stream = File.OpenRead(path))
  595. {
  596. config = JsonHelper.Deserialize<InputConfig>(stream);
  597. }
  598. }
  599. catch (JsonException) { }
  600. catch (InvalidOperationException)
  601. {
  602. Logger.Error?.Print(LogClass.Configuration, $"Profile {ProfileName} is incompatible with the current input configuration system.");
  603. await ContentDialogHelper.CreateErrorDialog(string.Format(LocaleManager.Instance["DialogProfileInvalidProfileErrorMessage"], ProfileName));
  604. return;
  605. }
  606. }
  607. if (config != null)
  608. {
  609. _isLoaded = false;
  610. LoadConfiguration(config);
  611. LoadDevice();
  612. _isLoaded = true;
  613. NotifyChanges();
  614. }
  615. }
  616. public async void SaveProfile()
  617. {
  618. if (Device == 0)
  619. {
  620. return;
  621. }
  622. if (Configuration == null)
  623. {
  624. return;
  625. }
  626. if (ProfileName == LocaleManager.Instance["ControllerSettingsProfileDefault"])
  627. {
  628. await ContentDialogHelper.CreateErrorDialog(LocaleManager.Instance["DialogProfileDefaultProfileOverwriteErrorMessage"]);
  629. return;
  630. }
  631. else
  632. {
  633. bool validFileName = ProfileName.IndexOfAny(Path.GetInvalidFileNameChars()) == -1;
  634. if (validFileName)
  635. {
  636. string path = Path.Combine(GetProfileBasePath(), ProfileName + ".json");
  637. InputConfig config = null;
  638. if (IsKeyboard)
  639. {
  640. config = (Configuration as InputConfiguration<Key, ConfigStickInputId>).GetConfig();
  641. }
  642. else if (IsController)
  643. {
  644. config = (Configuration as InputConfiguration<GamepadInputId, ConfigStickInputId>).GetConfig();
  645. }
  646. config.ControllerType = Controllers[_controller].Type;
  647. string jsonString = JsonHelper.Serialize(config, true);
  648. await File.WriteAllTextAsync(path, jsonString);
  649. LoadProfiles();
  650. }
  651. else
  652. {
  653. await ContentDialogHelper.CreateErrorDialog(LocaleManager.Instance["DialogProfileInvalidProfileNameErrorMessage"]);
  654. }
  655. }
  656. }
  657. public async void RemoveProfile()
  658. {
  659. if (Device == 0 || ProfileName == LocaleManager.Instance["ControllerSettingsProfileDefault"] || ProfilesList.IndexOf(ProfileName) == -1)
  660. {
  661. return;
  662. }
  663. UserResult result = await ContentDialogHelper.CreateConfirmationDialog(
  664. LocaleManager.Instance["DialogProfileDeleteProfileTitle"],
  665. LocaleManager.Instance["DialogProfileDeleteProfileMessage"],
  666. LocaleManager.Instance["InputDialogYes"],
  667. LocaleManager.Instance["InputDialogNo"],
  668. LocaleManager.Instance["RyujinxConfirm"]);
  669. if (result == UserResult.Yes)
  670. {
  671. string path = Path.Combine(GetProfileBasePath(), ProfileName + ".json");
  672. if (File.Exists(path))
  673. {
  674. File.Delete(path);
  675. }
  676. LoadProfiles();
  677. }
  678. }
  679. public void Save()
  680. {
  681. IsModified = false;
  682. List<InputConfig> newConfig = new();
  683. newConfig.AddRange(ConfigurationState.Instance.Hid.InputConfig.Value);
  684. newConfig.Remove(newConfig.Find(x => x == null));
  685. if (Device == 0)
  686. {
  687. newConfig.Remove(newConfig.Find(x => x.PlayerIndex == this.PlayerId));
  688. }
  689. else
  690. {
  691. var device = Devices[Device];
  692. if (device.Type == DeviceType.Keyboard)
  693. {
  694. var inputConfig = Configuration as InputConfiguration<Key, ConfigStickInputId>;
  695. inputConfig.Id = device.Id;
  696. }
  697. else
  698. {
  699. var inputConfig = Configuration as InputConfiguration<GamepadInputId, ConfigStickInputId>;
  700. inputConfig.Id = device.Id.Split(" ")[0];
  701. }
  702. var config = !IsController
  703. ? (Configuration as InputConfiguration<Key, ConfigStickInputId>).GetConfig()
  704. : (Configuration as InputConfiguration<GamepadInputId, ConfigStickInputId>).GetConfig();
  705. config.ControllerType = Controllers[_controller].Type;
  706. config.PlayerIndex = _playerId;
  707. int i = newConfig.FindIndex(x => x.PlayerIndex == PlayerId);
  708. if (i == -1)
  709. {
  710. newConfig.Add(config);
  711. }
  712. else
  713. {
  714. newConfig[i] = config;
  715. }
  716. }
  717. _mainWindow.AppHost?.NpadManager.ReloadConfiguration(newConfig, ConfigurationState.Instance.Hid.EnableKeyboard, ConfigurationState.Instance.Hid.EnableMouse);
  718. // Atomically replace and signal input change.
  719. // NOTE: Do not modify InputConfig.Value directly as other code depends on the on-change event.
  720. ConfigurationState.Instance.Hid.InputConfig.Value = newConfig;
  721. ConfigurationState.Instance.ToFileFormat().SaveConfig(Program.ConfigurationPath);
  722. }
  723. public void NotifyChange(string property)
  724. {
  725. OnPropertyChanged(property);
  726. }
  727. public void NotifyChanges()
  728. {
  729. OnPropertyChanged(nameof(Configuration));
  730. OnPropertyChanged(nameof(IsController));
  731. OnPropertyChanged(nameof(ShowSettings));
  732. OnPropertyChanged(nameof(IsKeyboard));
  733. OnPropertyChanged(nameof(IsRight));
  734. OnPropertyChanged(nameof(IsLeft));
  735. }
  736. public void Dispose()
  737. {
  738. _mainWindow.InputManager.GamepadDriver.OnGamepadConnected -= HandleOnGamepadConnected;
  739. _mainWindow.InputManager.GamepadDriver.OnGamepadDisconnected -= HandleOnGamepadDisconnected;
  740. _mainWindow.AppHost?.NpadManager.UnblockInputUpdates();
  741. SelectedGamepad?.Dispose();
  742. AvaloniaKeyboardDriver.Dispose();
  743. }
  744. }
  745. }