MainWindow.cs 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520
  1. using ARMeilleure.Translation;
  2. using ARMeilleure.Translation.PTC;
  3. using Gtk;
  4. using LibHac.Common;
  5. using LibHac.FsSystem;
  6. using LibHac.FsSystem.NcaUtils;
  7. using LibHac.Ns;
  8. using Ryujinx.Audio.Backends.Dummy;
  9. using Ryujinx.Audio.Backends.OpenAL;
  10. using Ryujinx.Audio.Backends.SDL2;
  11. using Ryujinx.Audio.Backends.SoundIo;
  12. using Ryujinx.Audio.Integration;
  13. using Ryujinx.Common;
  14. using Ryujinx.Common.Configuration;
  15. using Ryujinx.Common.Logging;
  16. using Ryujinx.Common.System;
  17. using Ryujinx.Configuration;
  18. using Ryujinx.Graphics.GAL;
  19. using Ryujinx.Graphics.OpenGL;
  20. using Ryujinx.HLE.FileSystem;
  21. using Ryujinx.HLE.FileSystem.Content;
  22. using Ryujinx.HLE.HOS;
  23. using Ryujinx.HLE.HOS.Services.Account.Acc;
  24. using Ryujinx.HLE.HOS.SystemState;
  25. using Ryujinx.Input.GTK3;
  26. using Ryujinx.Input.HLE;
  27. using Ryujinx.Input.SDL2;
  28. using Ryujinx.Modules;
  29. using Ryujinx.Ui.App;
  30. using Ryujinx.Ui.Applet;
  31. using Ryujinx.Ui.Helper;
  32. using Ryujinx.Ui.Widgets;
  33. using Ryujinx.Ui.Windows;
  34. using System;
  35. using System.Diagnostics;
  36. using System.IO;
  37. using System.Reflection;
  38. using System.Runtime.InteropServices;
  39. using System.Threading;
  40. using System.Threading.Tasks;
  41. using GUI = Gtk.Builder.ObjectAttribute;
  42. using PtcLoadingState = ARMeilleure.Translation.PTC.PtcLoadingState;
  43. using ShaderCacheLoadingState = Ryujinx.Graphics.Gpu.Shader.ShaderCacheState;
  44. namespace Ryujinx.Ui
  45. {
  46. public class MainWindow : Window
  47. {
  48. private readonly VirtualFileSystem _virtualFileSystem;
  49. private readonly ContentManager _contentManager;
  50. private readonly AccountManager _accountManager;
  51. private UserChannelPersistence _userChannelPersistence;
  52. private HLE.Switch _emulationContext;
  53. private WindowsMultimediaTimerResolution _windowsMultimediaTimerResolution;
  54. private readonly ApplicationLibrary _applicationLibrary;
  55. private readonly GtkHostUiHandler _uiHandler;
  56. private readonly AutoResetEvent _deviceExitStatus;
  57. private readonly ListStore _tableStore;
  58. private bool _updatingGameTable;
  59. private bool _gameLoaded;
  60. private bool _ending;
  61. private string _currentEmulatedGamePath = null;
  62. private string _lastScannedAmiiboId = "";
  63. private bool _lastScannedAmiiboShowAll = false;
  64. public RendererWidgetBase RendererWidget;
  65. public InputManager InputManager;
  66. public bool IsFocused;
  67. private static bool UseVulkan = false;
  68. #pragma warning disable CS0169, CS0649, IDE0044
  69. [GUI] public MenuItem ExitMenuItem;
  70. [GUI] public MenuItem UpdateMenuItem;
  71. [GUI] MenuBar _menuBar;
  72. [GUI] Box _footerBox;
  73. [GUI] Box _statusBar;
  74. [GUI] MenuItem _optionMenu;
  75. [GUI] MenuItem _manageUserProfiles;
  76. [GUI] MenuItem _fileMenu;
  77. [GUI] MenuItem _loadApplicationFile;
  78. [GUI] MenuItem _loadApplicationFolder;
  79. [GUI] MenuItem _appletMenu;
  80. [GUI] MenuItem _actionMenu;
  81. [GUI] MenuItem _stopEmulation;
  82. [GUI] MenuItem _simulateWakeUpMessage;
  83. [GUI] MenuItem _scanAmiibo;
  84. [GUI] MenuItem _fullScreen;
  85. [GUI] CheckMenuItem _startFullScreen;
  86. [GUI] CheckMenuItem _favToggle;
  87. [GUI] MenuItem _firmwareInstallDirectory;
  88. [GUI] MenuItem _firmwareInstallFile;
  89. [GUI] Label _fifoStatus;
  90. [GUI] CheckMenuItem _iconToggle;
  91. [GUI] CheckMenuItem _developerToggle;
  92. [GUI] CheckMenuItem _appToggle;
  93. [GUI] CheckMenuItem _timePlayedToggle;
  94. [GUI] CheckMenuItem _versionToggle;
  95. [GUI] CheckMenuItem _lastPlayedToggle;
  96. [GUI] CheckMenuItem _fileExtToggle;
  97. [GUI] CheckMenuItem _pathToggle;
  98. [GUI] CheckMenuItem _fileSizeToggle;
  99. [GUI] Label _dockedMode;
  100. [GUI] Label _aspectRatio;
  101. [GUI] Label _gameStatus;
  102. [GUI] TreeView _gameTable;
  103. [GUI] TreeSelection _gameTableSelection;
  104. [GUI] ScrolledWindow _gameTableWindow;
  105. [GUI] Label _gpuName;
  106. [GUI] Label _progressLabel;
  107. [GUI] Label _firmwareVersionLabel;
  108. [GUI] ProgressBar _progressBar;
  109. [GUI] Box _viewBox;
  110. [GUI] Label _vSyncStatus;
  111. [GUI] Box _listStatusBox;
  112. [GUI] Label _loadingStatusLabel;
  113. [GUI] ProgressBar _loadingStatusBar;
  114. #pragma warning restore CS0649, IDE0044, CS0169
  115. public MainWindow() : this(new Builder("Ryujinx.Ui.MainWindow.glade")) { }
  116. private MainWindow(Builder builder) : base(builder.GetObject("_mainWin").Handle)
  117. {
  118. builder.Autoconnect(this);
  119. // Apply custom theme if needed.
  120. ThemeHelper.ApplyTheme();
  121. // Sets overridden fields.
  122. int monitorWidth = Display.PrimaryMonitor.Geometry.Width * Display.PrimaryMonitor.ScaleFactor;
  123. int monitorHeight = Display.PrimaryMonitor.Geometry.Height * Display.PrimaryMonitor.ScaleFactor;
  124. DefaultWidth = monitorWidth < 1280 ? monitorWidth : 1280;
  125. DefaultHeight = monitorHeight < 760 ? monitorHeight : 760;
  126. Icon = new Gdk.Pixbuf(Assembly.GetExecutingAssembly(), "Ryujinx.Ui.Resources.Logo_Ryujinx.png");
  127. Title = $"Ryujinx {Program.Version}";
  128. // Hide emulation context status bar.
  129. _statusBar.Hide();
  130. // Instanciate HLE objects.
  131. _virtualFileSystem = VirtualFileSystem.CreateInstance();
  132. _contentManager = new ContentManager(_virtualFileSystem);
  133. _accountManager = new AccountManager(_virtualFileSystem);
  134. _userChannelPersistence = new UserChannelPersistence();
  135. // Instanciate GUI objects.
  136. _applicationLibrary = new ApplicationLibrary(_virtualFileSystem);
  137. _uiHandler = new GtkHostUiHandler(this);
  138. _deviceExitStatus = new AutoResetEvent(false);
  139. WindowStateEvent += WindowStateEvent_Changed;
  140. DeleteEvent += Window_Close;
  141. FocusInEvent += MainWindow_FocusInEvent;
  142. FocusOutEvent += MainWindow_FocusOutEvent;
  143. _applicationLibrary.ApplicationAdded += Application_Added;
  144. _applicationLibrary.ApplicationCountUpdated += ApplicationCount_Updated;
  145. _fileMenu.StateChanged += FileMenu_StateChanged;
  146. _actionMenu.StateChanged += ActionMenu_StateChanged;
  147. _optionMenu.StateChanged += OptionMenu_StateChanged;
  148. _gameTable.ButtonReleaseEvent += Row_Clicked;
  149. _fullScreen.Activated += FullScreen_Toggled;
  150. RendererWidgetBase.StatusUpdatedEvent += Update_StatusBar;
  151. ConfigurationState.Instance.System.IgnoreMissingServices.Event += UpdateIgnoreMissingServicesState;
  152. ConfigurationState.Instance.Graphics.AspectRatio.Event += UpdateAspectRatioState;
  153. ConfigurationState.Instance.System.EnableDockedMode.Event += UpdateDockedModeState;
  154. if (ConfigurationState.Instance.Ui.StartFullscreen)
  155. {
  156. _startFullScreen.Active = true;
  157. }
  158. _actionMenu.Sensitive = false;
  159. if (ConfigurationState.Instance.Ui.GuiColumns.FavColumn) _favToggle.Active = true;
  160. if (ConfigurationState.Instance.Ui.GuiColumns.IconColumn) _iconToggle.Active = true;
  161. if (ConfigurationState.Instance.Ui.GuiColumns.AppColumn) _appToggle.Active = true;
  162. if (ConfigurationState.Instance.Ui.GuiColumns.DevColumn) _developerToggle.Active = true;
  163. if (ConfigurationState.Instance.Ui.GuiColumns.VersionColumn) _versionToggle.Active = true;
  164. if (ConfigurationState.Instance.Ui.GuiColumns.TimePlayedColumn) _timePlayedToggle.Active = true;
  165. if (ConfigurationState.Instance.Ui.GuiColumns.LastPlayedColumn) _lastPlayedToggle.Active = true;
  166. if (ConfigurationState.Instance.Ui.GuiColumns.FileExtColumn) _fileExtToggle.Active = true;
  167. if (ConfigurationState.Instance.Ui.GuiColumns.FileSizeColumn) _fileSizeToggle.Active = true;
  168. if (ConfigurationState.Instance.Ui.GuiColumns.PathColumn) _pathToggle.Active = true;
  169. _favToggle.Toggled += Fav_Toggled;
  170. _iconToggle.Toggled += Icon_Toggled;
  171. _appToggle.Toggled += App_Toggled;
  172. _developerToggle.Toggled += Developer_Toggled;
  173. _versionToggle.Toggled += Version_Toggled;
  174. _timePlayedToggle.Toggled += TimePlayed_Toggled;
  175. _lastPlayedToggle.Toggled += LastPlayed_Toggled;
  176. _fileExtToggle.Toggled += FileExt_Toggled;
  177. _fileSizeToggle.Toggled += FileSize_Toggled;
  178. _pathToggle.Toggled += Path_Toggled;
  179. _gameTable.Model = _tableStore = new ListStore(
  180. typeof(bool),
  181. typeof(Gdk.Pixbuf),
  182. typeof(string),
  183. typeof(string),
  184. typeof(string),
  185. typeof(string),
  186. typeof(string),
  187. typeof(string),
  188. typeof(string),
  189. typeof(string),
  190. typeof(BlitStruct<ApplicationControlProperty>));
  191. _tableStore.SetSortFunc(5, SortHelper.TimePlayedSort);
  192. _tableStore.SetSortFunc(6, SortHelper.LastPlayedSort);
  193. _tableStore.SetSortFunc(8, SortHelper.FileSizeSort);
  194. int columnId = ConfigurationState.Instance.Ui.ColumnSort.SortColumnId;
  195. bool ascending = ConfigurationState.Instance.Ui.ColumnSort.SortAscending;
  196. _tableStore.SetSortColumnId(columnId, ascending ? SortType.Ascending : SortType.Descending);
  197. _gameTable.EnableSearch = true;
  198. _gameTable.SearchColumn = 2;
  199. _gameTable.SearchEqualFunc = (model, col, key, iter) => !((string)model.GetValue(iter, col)).Contains(key, StringComparison.InvariantCultureIgnoreCase);
  200. UpdateColumns();
  201. UpdateGameTable();
  202. ConfigurationState.Instance.Ui.GameDirs.Event += (sender, args) =>
  203. {
  204. if (args.OldValue != args.NewValue)
  205. {
  206. UpdateGameTable();
  207. }
  208. };
  209. Task.Run(RefreshFirmwareLabel);
  210. InputManager = new InputManager(new GTK3KeyboardDriver(this), new SDL2GamepadDriver());
  211. }
  212. private void UpdateIgnoreMissingServicesState(object sender, ReactiveEventArgs<bool> args)
  213. {
  214. if (_emulationContext != null)
  215. {
  216. _emulationContext.Configuration.IgnoreMissingServices = args.NewValue;
  217. }
  218. }
  219. private void UpdateAspectRatioState(object sender, ReactiveEventArgs<AspectRatio> args)
  220. {
  221. if (_emulationContext != null)
  222. {
  223. _emulationContext.Configuration.AspectRatio = args.NewValue;
  224. }
  225. }
  226. private void UpdateDockedModeState(object sender, ReactiveEventArgs<bool> e)
  227. {
  228. if (_emulationContext != null)
  229. {
  230. _emulationContext.System.ChangeDockedModeState(e.NewValue);
  231. }
  232. }
  233. private void WindowStateEvent_Changed(object o, WindowStateEventArgs args)
  234. {
  235. _fullScreen.Label = args.Event.NewWindowState.HasFlag(Gdk.WindowState.Fullscreen) ? "Exit Fullscreen" : "Enter Fullscreen";
  236. }
  237. private void MainWindow_FocusOutEvent(object o, FocusOutEventArgs args)
  238. {
  239. IsFocused = false;
  240. }
  241. private void MainWindow_FocusInEvent(object o, FocusInEventArgs args)
  242. {
  243. IsFocused = true;
  244. }
  245. private void UpdateColumns()
  246. {
  247. foreach (TreeViewColumn column in _gameTable.Columns)
  248. {
  249. _gameTable.RemoveColumn(column);
  250. }
  251. CellRendererToggle favToggle = new CellRendererToggle();
  252. favToggle.Toggled += FavToggle_Toggled;
  253. if (ConfigurationState.Instance.Ui.GuiColumns.FavColumn) _gameTable.AppendColumn("Fav", favToggle, "active", 0);
  254. if (ConfigurationState.Instance.Ui.GuiColumns.IconColumn) _gameTable.AppendColumn("Icon", new CellRendererPixbuf(), "pixbuf", 1);
  255. if (ConfigurationState.Instance.Ui.GuiColumns.AppColumn) _gameTable.AppendColumn("Application", new CellRendererText(), "text", 2);
  256. if (ConfigurationState.Instance.Ui.GuiColumns.DevColumn) _gameTable.AppendColumn("Developer", new CellRendererText(), "text", 3);
  257. if (ConfigurationState.Instance.Ui.GuiColumns.VersionColumn) _gameTable.AppendColumn("Version", new CellRendererText(), "text", 4);
  258. if (ConfigurationState.Instance.Ui.GuiColumns.TimePlayedColumn) _gameTable.AppendColumn("Time Played", new CellRendererText(), "text", 5);
  259. if (ConfigurationState.Instance.Ui.GuiColumns.LastPlayedColumn) _gameTable.AppendColumn("Last Played", new CellRendererText(), "text", 6);
  260. if (ConfigurationState.Instance.Ui.GuiColumns.FileExtColumn) _gameTable.AppendColumn("File Ext", new CellRendererText(), "text", 7);
  261. if (ConfigurationState.Instance.Ui.GuiColumns.FileSizeColumn) _gameTable.AppendColumn("File Size", new CellRendererText(), "text", 8);
  262. if (ConfigurationState.Instance.Ui.GuiColumns.PathColumn) _gameTable.AppendColumn("Path", new CellRendererText(), "text", 9);
  263. foreach (TreeViewColumn column in _gameTable.Columns)
  264. {
  265. switch (column.Title)
  266. {
  267. case "Fav":
  268. column.SortColumnId = 0;
  269. column.Clicked += Column_Clicked;
  270. break;
  271. case "Application":
  272. column.SortColumnId = 2;
  273. column.Clicked += Column_Clicked;
  274. break;
  275. case "Developer":
  276. column.SortColumnId = 3;
  277. column.Clicked += Column_Clicked;
  278. break;
  279. case "Version":
  280. column.SortColumnId = 4;
  281. column.Clicked += Column_Clicked;
  282. break;
  283. case "Time Played":
  284. column.SortColumnId = 5;
  285. column.Clicked += Column_Clicked;
  286. break;
  287. case "Last Played":
  288. column.SortColumnId = 6;
  289. column.Clicked += Column_Clicked;
  290. break;
  291. case "File Ext":
  292. column.SortColumnId = 7;
  293. column.Clicked += Column_Clicked;
  294. break;
  295. case "File Size":
  296. column.SortColumnId = 8;
  297. column.Clicked += Column_Clicked;
  298. break;
  299. case "Path":
  300. column.SortColumnId = 9;
  301. column.Clicked += Column_Clicked;
  302. break;
  303. }
  304. }
  305. }
  306. protected override void OnDestroyed()
  307. {
  308. InputManager.Dispose();
  309. }
  310. private void InitializeSwitchInstance()
  311. {
  312. _virtualFileSystem.Reload();
  313. IRenderer renderer;
  314. if (UseVulkan)
  315. {
  316. throw new NotImplementedException();
  317. }
  318. else
  319. {
  320. renderer = new Renderer();
  321. }
  322. IHardwareDeviceDriver deviceDriver = new DummyHardwareDeviceDriver();
  323. if (ConfigurationState.Instance.System.AudioBackend.Value == AudioBackend.SDL2)
  324. {
  325. if (SDL2HardwareDeviceDriver.IsSupported)
  326. {
  327. deviceDriver = new SDL2HardwareDeviceDriver();
  328. }
  329. else
  330. {
  331. Logger.Warning?.Print(LogClass.Audio, "SDL2 audio is not supported, falling back to dummy audio out.");
  332. }
  333. }
  334. else if (ConfigurationState.Instance.System.AudioBackend.Value == AudioBackend.SoundIo)
  335. {
  336. if (SoundIoHardwareDeviceDriver.IsSupported)
  337. {
  338. deviceDriver = new SoundIoHardwareDeviceDriver();
  339. }
  340. else
  341. {
  342. Logger.Warning?.Print(LogClass.Audio, "SoundIO is not supported, falling back to dummy audio out.");
  343. }
  344. }
  345. else if (ConfigurationState.Instance.System.AudioBackend.Value == AudioBackend.OpenAl)
  346. {
  347. if (OpenALHardwareDeviceDriver.IsSupported)
  348. {
  349. deviceDriver = new OpenALHardwareDeviceDriver();
  350. }
  351. else
  352. {
  353. Logger.Warning?.Print(LogClass.Audio, "OpenAL is not supported, trying to fall back to SoundIO.");
  354. if (SoundIoHardwareDeviceDriver.IsSupported)
  355. {
  356. Logger.Warning?.Print(LogClass.Audio, "Found SoundIO, changing configuration.");
  357. ConfigurationState.Instance.System.AudioBackend.Value = AudioBackend.SoundIo;
  358. SaveConfig();
  359. deviceDriver = new SoundIoHardwareDeviceDriver();
  360. }
  361. else
  362. {
  363. Logger.Warning?.Print(LogClass.Audio, "SoundIO is not supported, falling back to dummy audio out.");
  364. }
  365. }
  366. }
  367. var memoryConfiguration = ConfigurationState.Instance.System.ExpandRam.Value
  368. ? HLE.MemoryConfiguration.MemoryConfiguration6GB
  369. : HLE.MemoryConfiguration.MemoryConfiguration4GB;
  370. IntegrityCheckLevel fsIntegrityCheckLevel = ConfigurationState.Instance.System.EnableFsIntegrityChecks ? IntegrityCheckLevel.ErrorOnInvalid : IntegrityCheckLevel.None;
  371. HLE.HLEConfiguration configuration = new HLE.HLEConfiguration(_virtualFileSystem,
  372. _contentManager,
  373. _accountManager,
  374. _userChannelPersistence,
  375. renderer,
  376. deviceDriver,
  377. memoryConfiguration,
  378. _uiHandler,
  379. (SystemLanguage)ConfigurationState.Instance.System.Language.Value,
  380. (RegionCode)ConfigurationState.Instance.System.Region.Value,
  381. ConfigurationState.Instance.Graphics.EnableVsync,
  382. ConfigurationState.Instance.System.EnableDockedMode,
  383. ConfigurationState.Instance.System.EnablePtc,
  384. fsIntegrityCheckLevel,
  385. ConfigurationState.Instance.System.FsGlobalAccessLogMode,
  386. ConfigurationState.Instance.System.SystemTimeOffset,
  387. ConfigurationState.Instance.System.TimeZone,
  388. ConfigurationState.Instance.System.MemoryManagerMode,
  389. ConfigurationState.Instance.System.IgnoreMissingServices,
  390. ConfigurationState.Instance.Graphics.AspectRatio);
  391. _emulationContext = new HLE.Switch(configuration);
  392. }
  393. private void SetupProgressUiHandlers()
  394. {
  395. Ptc.PtcStateChanged -= ProgressHandler;
  396. Ptc.PtcStateChanged += ProgressHandler;
  397. _emulationContext.Gpu.ShaderCacheStateChanged -= ProgressHandler;
  398. _emulationContext.Gpu.ShaderCacheStateChanged += ProgressHandler;
  399. }
  400. private void ProgressHandler<T>(T state, int current, int total) where T : Enum
  401. {
  402. bool visible;
  403. string label;
  404. switch (state)
  405. {
  406. case PtcLoadingState ptcState:
  407. visible = ptcState != PtcLoadingState.Loaded;
  408. label = $"PTC : {current}/{total}";
  409. break;
  410. case ShaderCacheLoadingState shaderCacheState:
  411. visible = shaderCacheState != ShaderCacheLoadingState.Loaded;
  412. label = $"Shaders : {current}/{total}";
  413. break;
  414. default:
  415. throw new ArgumentException($"Unknown Progress Handler type {typeof(T)}");
  416. }
  417. Application.Invoke(delegate
  418. {
  419. _loadingStatusLabel.Text = label;
  420. _loadingStatusBar.Fraction = total > 0 ? (double)current / total : 0;
  421. _loadingStatusBar.Visible = visible;
  422. _loadingStatusLabel.Visible = visible;
  423. });
  424. }
  425. public void UpdateGameTable()
  426. {
  427. if (_updatingGameTable || _gameLoaded)
  428. {
  429. return;
  430. }
  431. _updatingGameTable = true;
  432. _tableStore.Clear();
  433. Thread applicationLibraryThread = new Thread(() =>
  434. {
  435. _applicationLibrary.LoadApplications(ConfigurationState.Instance.Ui.GameDirs, ConfigurationState.Instance.System.Language);
  436. _updatingGameTable = false;
  437. });
  438. applicationLibraryThread.Name = "GUI.ApplicationLibraryThread";
  439. applicationLibraryThread.IsBackground = true;
  440. applicationLibraryThread.Start();
  441. }
  442. [Conditional("RELEASE")]
  443. public void PerformanceCheck()
  444. {
  445. if (ConfigurationState.Instance.Logger.EnableDebug.Value)
  446. {
  447. MessageDialog debugWarningDialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Warning, ButtonsType.YesNo, null)
  448. {
  449. Title = "Ryujinx - Warning",
  450. Text = "You have debug logging enabled, which is designed to be used by developers only.",
  451. SecondaryText = "For optimal performance, it's recommended to disable debug logging. Would you like to disable debug logging now?"
  452. };
  453. if (debugWarningDialog.Run() == (int)ResponseType.Yes)
  454. {
  455. ConfigurationState.Instance.Logger.EnableDebug.Value = false;
  456. SaveConfig();
  457. }
  458. debugWarningDialog.Dispose();
  459. }
  460. if (!string.IsNullOrWhiteSpace(ConfigurationState.Instance.Graphics.ShadersDumpPath.Value))
  461. {
  462. MessageDialog shadersDumpWarningDialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Warning, ButtonsType.YesNo, null)
  463. {
  464. Title = "Ryujinx - Warning",
  465. Text = "You have shader dumping enabled, which is designed to be used by developers only.",
  466. SecondaryText = "For optimal performance, it's recommended to disable shader dumping. Would you like to disable shader dumping now?"
  467. };
  468. if (shadersDumpWarningDialog.Run() == (int)ResponseType.Yes)
  469. {
  470. ConfigurationState.Instance.Graphics.ShadersDumpPath.Value = "";
  471. SaveConfig();
  472. }
  473. shadersDumpWarningDialog.Dispose();
  474. }
  475. }
  476. public void LoadApplication(string path)
  477. {
  478. if (_gameLoaded)
  479. {
  480. GtkDialog.CreateInfoDialog("A game has already been loaded", "Please stop emulation or close the emulator before launching another game.");
  481. }
  482. else
  483. {
  484. PerformanceCheck();
  485. Logger.RestartTime();
  486. RendererWidget = CreateRendererWidget();
  487. SwitchToRenderWidget();
  488. InitializeSwitchInstance();
  489. UpdateGraphicsConfig();
  490. SetupProgressUiHandlers();
  491. SystemVersion firmwareVersion = _contentManager.GetCurrentFirmwareVersion();
  492. bool isDirectory = Directory.Exists(path);
  493. bool isFirmwareTitle = false;
  494. if (path.StartsWith("@SystemContent"))
  495. {
  496. path = _virtualFileSystem.SwitchPathToSystemPath(path);
  497. isFirmwareTitle = true;
  498. }
  499. if (!SetupValidator.CanStartApplication(_contentManager, path, out UserError userError))
  500. {
  501. if (SetupValidator.CanFixStartApplication(_contentManager, path, userError, out firmwareVersion))
  502. {
  503. if (userError == UserError.NoFirmware)
  504. {
  505. string message = $"Would you like to install the firmware embedded in this game? (Firmware {firmwareVersion.VersionString})";
  506. ResponseType responseDialog = (ResponseType)GtkDialog.CreateConfirmationDialog("No Firmware Installed", message).Run();
  507. if (responseDialog != ResponseType.Yes)
  508. {
  509. UserErrorDialog.CreateUserErrorDialog(userError);
  510. _emulationContext.Dispose();
  511. SwitchToGameTable();
  512. RendererWidget.Dispose();
  513. return;
  514. }
  515. }
  516. if (!SetupValidator.TryFixStartApplication(_contentManager, path, userError, out _))
  517. {
  518. UserErrorDialog.CreateUserErrorDialog(userError);
  519. _emulationContext.Dispose();
  520. SwitchToGameTable();
  521. RendererWidget.Dispose();
  522. return;
  523. }
  524. // Tell the user that we installed a firmware for them.
  525. if (userError == UserError.NoFirmware)
  526. {
  527. firmwareVersion = _contentManager.GetCurrentFirmwareVersion();
  528. RefreshFirmwareLabel();
  529. string message = $"No installed firmware was found but Ryujinx was able to install firmware {firmwareVersion.VersionString} from the provided game.\nThe emulator will now start.";
  530. GtkDialog.CreateInfoDialog($"Firmware {firmwareVersion.VersionString} was installed", message);
  531. }
  532. }
  533. else
  534. {
  535. UserErrorDialog.CreateUserErrorDialog(userError);
  536. _emulationContext.Dispose();
  537. SwitchToGameTable();
  538. RendererWidget.Dispose();
  539. return;
  540. }
  541. }
  542. Logger.Notice.Print(LogClass.Application, $"Using Firmware Version: {firmwareVersion?.VersionString}");
  543. if (isFirmwareTitle)
  544. {
  545. Logger.Info?.Print(LogClass.Application, "Loading as Firmware Title (NCA).");
  546. _emulationContext.LoadNca(path);
  547. }
  548. else if (Directory.Exists(path))
  549. {
  550. string[] romFsFiles = Directory.GetFiles(path, "*.istorage");
  551. if (romFsFiles.Length == 0)
  552. {
  553. romFsFiles = Directory.GetFiles(path, "*.romfs");
  554. }
  555. if (romFsFiles.Length > 0)
  556. {
  557. Logger.Info?.Print(LogClass.Application, "Loading as cart with RomFS.");
  558. _emulationContext.LoadCart(path, romFsFiles[0]);
  559. }
  560. else
  561. {
  562. Logger.Info?.Print(LogClass.Application, "Loading as cart WITHOUT RomFS.");
  563. _emulationContext.LoadCart(path);
  564. }
  565. }
  566. else if (File.Exists(path))
  567. {
  568. switch (System.IO.Path.GetExtension(path).ToLowerInvariant())
  569. {
  570. case ".xci":
  571. Logger.Info?.Print(LogClass.Application, "Loading as XCI.");
  572. _emulationContext.LoadXci(path);
  573. break;
  574. case ".nca":
  575. Logger.Info?.Print(LogClass.Application, "Loading as NCA.");
  576. _emulationContext.LoadNca(path);
  577. break;
  578. case ".nsp":
  579. case ".pfs0":
  580. Logger.Info?.Print(LogClass.Application, "Loading as NSP.");
  581. _emulationContext.LoadNsp(path);
  582. break;
  583. default:
  584. Logger.Info?.Print(LogClass.Application, "Loading as Homebrew.");
  585. try
  586. {
  587. _emulationContext.LoadProgram(path);
  588. }
  589. catch (ArgumentOutOfRangeException)
  590. {
  591. Logger.Error?.Print(LogClass.Application, "The specified file is not supported by Ryujinx.");
  592. }
  593. break;
  594. }
  595. }
  596. else
  597. {
  598. Logger.Warning?.Print(LogClass.Application, "Please specify a valid XCI/NCA/NSP/PFS0/NRO file.");
  599. _emulationContext.Dispose();
  600. RendererWidget.Dispose();
  601. return;
  602. }
  603. _currentEmulatedGamePath = path;
  604. _deviceExitStatus.Reset();
  605. Translator.IsReadyForTranslation.Reset();
  606. #if MACOS_BUILD
  607. CreateGameWindow();
  608. #else
  609. Thread windowThread = new Thread(() =>
  610. {
  611. CreateGameWindow();
  612. })
  613. {
  614. Name = "GUI.WindowThread"
  615. };
  616. windowThread.Start();
  617. #endif
  618. _gameLoaded = true;
  619. _actionMenu.Sensitive = true;
  620. _lastScannedAmiiboId = "";
  621. _firmwareInstallFile.Sensitive = false;
  622. _firmwareInstallDirectory.Sensitive = false;
  623. DiscordIntegrationModule.SwitchToPlayingState(_emulationContext.Application.TitleIdText, _emulationContext.Application.TitleName);
  624. _applicationLibrary.LoadAndSaveMetaData(_emulationContext.Application.TitleIdText, appMetadata =>
  625. {
  626. appMetadata.LastPlayed = DateTime.UtcNow.ToString();
  627. });
  628. }
  629. }
  630. private RendererWidgetBase CreateRendererWidget()
  631. {
  632. if (UseVulkan)
  633. {
  634. return new VKRenderer(InputManager, ConfigurationState.Instance.Logger.GraphicsDebugLevel);
  635. }
  636. else
  637. {
  638. return new GlRenderer(InputManager, ConfigurationState.Instance.Logger.GraphicsDebugLevel);
  639. }
  640. }
  641. private void SwitchToRenderWidget()
  642. {
  643. _viewBox.Remove(_gameTableWindow);
  644. RendererWidget.Expand = true;
  645. _viewBox.Child = RendererWidget;
  646. RendererWidget.ShowAll();
  647. EditFooterForGameRenderer();
  648. if (Window.State.HasFlag(Gdk.WindowState.Fullscreen))
  649. {
  650. ToggleExtraWidgets(false);
  651. }
  652. else if (ConfigurationState.Instance.Ui.StartFullscreen.Value)
  653. {
  654. FullScreen_Toggled(null, null);
  655. }
  656. }
  657. private void SwitchToGameTable()
  658. {
  659. if (Window.State.HasFlag(Gdk.WindowState.Fullscreen))
  660. {
  661. ToggleExtraWidgets(true);
  662. }
  663. RendererWidget.Exit();
  664. if (RendererWidget.Window != Window && RendererWidget.Window != null)
  665. {
  666. RendererWidget.Window.Dispose();
  667. }
  668. RendererWidget.Dispose();
  669. _windowsMultimediaTimerResolution?.Dispose();
  670. _windowsMultimediaTimerResolution = null;
  671. DisplaySleep.Restore();
  672. _viewBox.Remove(RendererWidget);
  673. _viewBox.Add(_gameTableWindow);
  674. _gameTableWindow.Expand = true;
  675. Window.Title = $"Ryujinx {Program.Version}";
  676. _emulationContext = null;
  677. _gameLoaded = false;
  678. RendererWidget = null;
  679. DiscordIntegrationModule.SwitchToMainMenu();
  680. RecreateFooterForMenu();
  681. UpdateColumns();
  682. UpdateGameTable();
  683. Task.Run(RefreshFirmwareLabel);
  684. Task.Run(HandleRelaunch);
  685. _actionMenu.Sensitive = false;
  686. _firmwareInstallFile.Sensitive = true;
  687. _firmwareInstallDirectory.Sensitive = true;
  688. }
  689. private void CreateGameWindow()
  690. {
  691. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  692. {
  693. _windowsMultimediaTimerResolution = new WindowsMultimediaTimerResolution(1);
  694. }
  695. DisplaySleep.Prevent();
  696. RendererWidget.Initialize(_emulationContext);
  697. RendererWidget.WaitEvent.WaitOne();
  698. RendererWidget.Start();
  699. Ptc.Close();
  700. PtcProfiler.Stop();
  701. _emulationContext.Dispose();
  702. _deviceExitStatus.Set();
  703. // NOTE: Everything that is here will not be executed when you close the UI.
  704. Application.Invoke(delegate
  705. {
  706. SwitchToGameTable();
  707. });
  708. }
  709. private void RecreateFooterForMenu()
  710. {
  711. _listStatusBox.Show();
  712. _statusBar.Hide();
  713. }
  714. private void EditFooterForGameRenderer()
  715. {
  716. _listStatusBox.Hide();
  717. _statusBar.Show();
  718. }
  719. public void ToggleExtraWidgets(bool show)
  720. {
  721. if (RendererWidget != null)
  722. {
  723. if (show)
  724. {
  725. _menuBar.ShowAll();
  726. _footerBox.Show();
  727. _statusBar.Show();
  728. }
  729. else
  730. {
  731. _menuBar.Hide();
  732. _footerBox.Hide();
  733. }
  734. }
  735. }
  736. private void UpdateGameMetadata(string titleId)
  737. {
  738. if (_gameLoaded)
  739. {
  740. _applicationLibrary.LoadAndSaveMetaData(titleId, appMetadata =>
  741. {
  742. DateTime lastPlayedDateTime = DateTime.Parse(appMetadata.LastPlayed);
  743. double sessionTimePlayed = DateTime.UtcNow.Subtract(lastPlayedDateTime).TotalSeconds;
  744. appMetadata.TimePlayed += Math.Round(sessionTimePlayed, MidpointRounding.AwayFromZero);
  745. });
  746. }
  747. }
  748. public void UpdateGraphicsConfig()
  749. {
  750. int resScale = ConfigurationState.Instance.Graphics.ResScale;
  751. float resScaleCustom = ConfigurationState.Instance.Graphics.ResScaleCustom;
  752. Graphics.Gpu.GraphicsConfig.ResScale = (resScale == -1) ? resScaleCustom : resScale;
  753. Graphics.Gpu.GraphicsConfig.MaxAnisotropy = ConfigurationState.Instance.Graphics.MaxAnisotropy;
  754. Graphics.Gpu.GraphicsConfig.ShadersDumpPath = ConfigurationState.Instance.Graphics.ShadersDumpPath;
  755. Graphics.Gpu.GraphicsConfig.EnableShaderCache = ConfigurationState.Instance.Graphics.EnableShaderCache;
  756. }
  757. public void SaveConfig()
  758. {
  759. ConfigurationState.Instance.ToFileFormat().SaveConfig(Program.ConfigurationPath);
  760. }
  761. private void End()
  762. {
  763. if (_ending)
  764. {
  765. return;
  766. }
  767. _ending = true;
  768. if (_emulationContext != null)
  769. {
  770. UpdateGameMetadata(_emulationContext.Application.TitleIdText);
  771. if (RendererWidget != null)
  772. {
  773. // We tell the widget that we are exiting.
  774. RendererWidget.Exit();
  775. // Wait for the other thread to dispose the HLE context before exiting.
  776. _deviceExitStatus.WaitOne();
  777. RendererWidget.Dispose();
  778. }
  779. }
  780. Dispose();
  781. Program.Exit();
  782. Application.Quit();
  783. }
  784. //
  785. // Events
  786. //
  787. private void Application_Added(object sender, ApplicationAddedEventArgs args)
  788. {
  789. Application.Invoke(delegate
  790. {
  791. _tableStore.AppendValues(
  792. args.AppData.Favorite,
  793. new Gdk.Pixbuf(args.AppData.Icon, 75, 75),
  794. $"{args.AppData.TitleName}\n{args.AppData.TitleId.ToUpper()}",
  795. args.AppData.Developer,
  796. args.AppData.Version,
  797. args.AppData.TimePlayed,
  798. args.AppData.LastPlayed,
  799. args.AppData.FileExtension,
  800. args.AppData.FileSize,
  801. args.AppData.Path,
  802. args.AppData.ControlHolder);
  803. });
  804. }
  805. private void ApplicationCount_Updated(object sender, ApplicationCountUpdatedEventArgs args)
  806. {
  807. Application.Invoke(delegate
  808. {
  809. _progressLabel.Text = $"{args.NumAppsLoaded}/{args.NumAppsFound} Games Loaded";
  810. float barValue = 0;
  811. if (args.NumAppsFound != 0)
  812. {
  813. barValue = (float)args.NumAppsLoaded / args.NumAppsFound;
  814. }
  815. _progressBar.Fraction = barValue;
  816. // Reset the vertical scrollbar to the top when titles finish loading
  817. if (args.NumAppsLoaded == args.NumAppsFound)
  818. {
  819. _gameTableWindow.Vadjustment.Value = 0;
  820. }
  821. });
  822. }
  823. private void Update_StatusBar(object sender, StatusUpdatedEventArgs args)
  824. {
  825. Application.Invoke(delegate
  826. {
  827. _gameStatus.Text = args.GameStatus;
  828. _fifoStatus.Text = args.FifoStatus;
  829. _gpuName.Text = args.GpuName;
  830. _dockedMode.Text = args.DockedMode;
  831. _aspectRatio.Text = args.AspectRatio;
  832. if (args.VSyncEnabled)
  833. {
  834. _vSyncStatus.Attributes = new Pango.AttrList();
  835. _vSyncStatus.Attributes.Insert(new Pango.AttrForeground(11822, 60138, 51657));
  836. }
  837. else
  838. {
  839. _vSyncStatus.Attributes = new Pango.AttrList();
  840. _vSyncStatus.Attributes.Insert(new Pango.AttrForeground(ushort.MaxValue, 17733, 21588));
  841. }
  842. });
  843. }
  844. private void FavToggle_Toggled(object sender, ToggledArgs args)
  845. {
  846. _tableStore.GetIter(out TreeIter treeIter, new TreePath(args.Path));
  847. string titleId = _tableStore.GetValue(treeIter, 2).ToString().Split("\n")[1].ToLower();
  848. bool newToggleValue = !(bool)_tableStore.GetValue(treeIter, 0);
  849. _tableStore.SetValue(treeIter, 0, newToggleValue);
  850. _applicationLibrary.LoadAndSaveMetaData(titleId, appMetadata =>
  851. {
  852. appMetadata.Favorite = newToggleValue;
  853. });
  854. }
  855. private void Column_Clicked(object sender, EventArgs args)
  856. {
  857. TreeViewColumn column = (TreeViewColumn)sender;
  858. ConfigurationState.Instance.Ui.ColumnSort.SortColumnId.Value = column.SortColumnId;
  859. ConfigurationState.Instance.Ui.ColumnSort.SortAscending.Value = column.SortOrder == SortType.Ascending;
  860. SaveConfig();
  861. }
  862. private void Row_Activated(object sender, RowActivatedArgs args)
  863. {
  864. _gameTableSelection.GetSelected(out TreeIter treeIter);
  865. string path = (string)_tableStore.GetValue(treeIter, 9);
  866. LoadApplication(path);
  867. }
  868. private void VSyncStatus_Clicked(object sender, ButtonReleaseEventArgs args)
  869. {
  870. _emulationContext.EnableDeviceVsync = !_emulationContext.EnableDeviceVsync;
  871. Logger.Info?.Print(LogClass.Application, $"VSync toggled to: {_emulationContext.EnableDeviceVsync}");
  872. }
  873. private void DockedMode_Clicked(object sender, ButtonReleaseEventArgs args)
  874. {
  875. ConfigurationState.Instance.System.EnableDockedMode.Value = !ConfigurationState.Instance.System.EnableDockedMode.Value;
  876. }
  877. private void AspectRatio_Clicked(object sender, ButtonReleaseEventArgs args)
  878. {
  879. AspectRatio aspectRatio = ConfigurationState.Instance.Graphics.AspectRatio.Value;
  880. ConfigurationState.Instance.Graphics.AspectRatio.Value = ((int)aspectRatio + 1) > Enum.GetNames(typeof(AspectRatio)).Length - 1 ? AspectRatio.Fixed4x3 : aspectRatio + 1;
  881. }
  882. private void Row_Clicked(object sender, ButtonReleaseEventArgs args)
  883. {
  884. if (args.Event.Button != 3 /* Right Click */)
  885. {
  886. return;
  887. }
  888. _gameTableSelection.GetSelected(out TreeIter treeIter);
  889. if (treeIter.UserData == IntPtr.Zero)
  890. {
  891. return;
  892. }
  893. string titleFilePath = _tableStore.GetValue(treeIter, 9).ToString();
  894. string titleName = _tableStore.GetValue(treeIter, 2).ToString().Split("\n")[0];
  895. string titleId = _tableStore.GetValue(treeIter, 2).ToString().Split("\n")[1].ToLower();
  896. BlitStruct<ApplicationControlProperty> controlData = (BlitStruct<ApplicationControlProperty>)_tableStore.GetValue(treeIter, 10);
  897. _ = new GameTableContextMenu(this, _virtualFileSystem, _accountManager, titleFilePath, titleName, titleId, controlData);
  898. }
  899. private void Load_Application_File(object sender, EventArgs args)
  900. {
  901. using (FileChooserDialog fileChooser = new FileChooserDialog("Choose the file to open", this, FileChooserAction.Open, "Cancel", ResponseType.Cancel, "Open", ResponseType.Accept))
  902. {
  903. fileChooser.Filter = new FileFilter();
  904. fileChooser.Filter.AddPattern("*.nsp");
  905. fileChooser.Filter.AddPattern("*.pfs0");
  906. fileChooser.Filter.AddPattern("*.xci");
  907. fileChooser.Filter.AddPattern("*.nca");
  908. fileChooser.Filter.AddPattern("*.nro");
  909. fileChooser.Filter.AddPattern("*.nso");
  910. if (fileChooser.Run() == (int)ResponseType.Accept)
  911. {
  912. LoadApplication(fileChooser.Filename);
  913. }
  914. }
  915. }
  916. private void Load_Application_Folder(object sender, EventArgs args)
  917. {
  918. using (FileChooserDialog fileChooser = new FileChooserDialog("Choose the folder to open", this, FileChooserAction.SelectFolder, "Cancel", ResponseType.Cancel, "Open", ResponseType.Accept))
  919. {
  920. if (fileChooser.Run() == (int)ResponseType.Accept)
  921. {
  922. LoadApplication(fileChooser.Filename);
  923. }
  924. }
  925. }
  926. private void FileMenu_StateChanged(object o, StateChangedArgs args)
  927. {
  928. _appletMenu.Sensitive = _emulationContext == null && _contentManager.GetCurrentFirmwareVersion() != null && _contentManager.GetCurrentFirmwareVersion().Major > 3;
  929. _loadApplicationFile.Sensitive = _emulationContext == null;
  930. _loadApplicationFolder.Sensitive = _emulationContext == null;
  931. }
  932. private void Load_Mii_Edit_Applet(object sender, EventArgs args)
  933. {
  934. string contentPath = _contentManager.GetInstalledContentPath(0x0100000000001009, StorageId.NandSystem, NcaContentType.Program);
  935. LoadApplication(contentPath);
  936. }
  937. private void Open_Ryu_Folder(object sender, EventArgs args)
  938. {
  939. OpenHelper.OpenFolder(AppDataManager.BaseDirPath);
  940. }
  941. private void OpenLogsFolder_Pressed(object sender, EventArgs args)
  942. {
  943. string logPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Logs");
  944. new DirectoryInfo(logPath).Create();
  945. OpenHelper.OpenFolder(logPath);
  946. }
  947. private void Exit_Pressed(object sender, EventArgs args)
  948. {
  949. if (!_gameLoaded || !ConfigurationState.Instance.ShowConfirmExit || GtkDialog.CreateExitDialog())
  950. {
  951. End();
  952. }
  953. }
  954. private void Window_Close(object sender, DeleteEventArgs args)
  955. {
  956. if (!_gameLoaded || !ConfigurationState.Instance.ShowConfirmExit || GtkDialog.CreateExitDialog())
  957. {
  958. End();
  959. }
  960. else
  961. {
  962. args.RetVal = true;
  963. }
  964. }
  965. private void StopEmulation_Pressed(object sender, EventArgs args)
  966. {
  967. RendererWidget?.Exit();
  968. }
  969. private void Installer_File_Pressed(object o, EventArgs args)
  970. {
  971. FileChooserDialog fileChooser = new FileChooserDialog("Choose the firmware file to open", this, FileChooserAction.Open, "Cancel", ResponseType.Cancel, "Open", ResponseType.Accept);
  972. fileChooser.Filter = new FileFilter();
  973. fileChooser.Filter.AddPattern("*.zip");
  974. fileChooser.Filter.AddPattern("*.xci");
  975. HandleInstallerDialog(fileChooser);
  976. }
  977. private void Installer_Directory_Pressed(object o, EventArgs args)
  978. {
  979. FileChooserDialog directoryChooser = new FileChooserDialog("Choose the firmware directory to open", this, FileChooserAction.SelectFolder, "Cancel", ResponseType.Cancel, "Open", ResponseType.Accept);
  980. HandleInstallerDialog(directoryChooser);
  981. }
  982. private void HandleInstallerDialog(FileChooserDialog fileChooser)
  983. {
  984. if (fileChooser.Run() == (int)ResponseType.Accept)
  985. {
  986. try
  987. {
  988. string filename = fileChooser.Filename;
  989. fileChooser.Dispose();
  990. SystemVersion firmwareVersion = _contentManager.VerifyFirmwarePackage(filename);
  991. string dialogTitle = $"Install Firmware {firmwareVersion.VersionString}";
  992. if (firmwareVersion == null)
  993. {
  994. GtkDialog.CreateErrorDialog($"A valid system firmware was not found in {filename}.");
  995. return;
  996. }
  997. SystemVersion currentVersion = _contentManager.GetCurrentFirmwareVersion();
  998. string dialogMessage = $"System version {firmwareVersion.VersionString} will be installed.";
  999. if (currentVersion != null)
  1000. {
  1001. dialogMessage += $"\n\nThis will replace the current system version {currentVersion.VersionString}. ";
  1002. }
  1003. dialogMessage += "\n\nDo you want to continue?";
  1004. ResponseType responseInstallDialog = (ResponseType)GtkDialog.CreateConfirmationDialog(dialogTitle, dialogMessage).Run();
  1005. MessageDialog waitingDialog = GtkDialog.CreateWaitingDialog(dialogTitle, "Installing firmware...");
  1006. if (responseInstallDialog == ResponseType.Yes)
  1007. {
  1008. Logger.Info?.Print(LogClass.Application, $"Installing firmware {firmwareVersion.VersionString}");
  1009. Thread thread = new Thread(() =>
  1010. {
  1011. Application.Invoke(delegate
  1012. {
  1013. waitingDialog.Run();
  1014. });
  1015. try
  1016. {
  1017. _contentManager.InstallFirmware(filename);
  1018. Application.Invoke(delegate
  1019. {
  1020. waitingDialog.Dispose();
  1021. string message = $"System version {firmwareVersion.VersionString} successfully installed.";
  1022. GtkDialog.CreateInfoDialog(dialogTitle, message);
  1023. Logger.Info?.Print(LogClass.Application, message);
  1024. // Purge Applet Cache.
  1025. DirectoryInfo miiEditorCacheFolder = new DirectoryInfo(System.IO.Path.Combine(AppDataManager.GamesDirPath, "0100000000001009", "cache"));
  1026. if (miiEditorCacheFolder.Exists)
  1027. {
  1028. miiEditorCacheFolder.Delete(true);
  1029. }
  1030. });
  1031. }
  1032. catch (Exception ex)
  1033. {
  1034. Application.Invoke(delegate
  1035. {
  1036. waitingDialog.Dispose();
  1037. GtkDialog.CreateErrorDialog(ex.Message);
  1038. });
  1039. }
  1040. finally
  1041. {
  1042. RefreshFirmwareLabel();
  1043. }
  1044. });
  1045. thread.Name = "GUI.FirmwareInstallerThread";
  1046. thread.Start();
  1047. }
  1048. }
  1049. catch (LibHac.MissingKeyException ex)
  1050. {
  1051. Logger.Error?.Print(LogClass.Application, ex.ToString());
  1052. UserErrorDialog.CreateUserErrorDialog(UserError.NoKeys);
  1053. }
  1054. catch (Exception ex)
  1055. {
  1056. GtkDialog.CreateErrorDialog(ex.Message);
  1057. }
  1058. }
  1059. else
  1060. {
  1061. fileChooser.Dispose();
  1062. }
  1063. }
  1064. private void RefreshFirmwareLabel()
  1065. {
  1066. SystemVersion currentFirmware = _contentManager.GetCurrentFirmwareVersion();
  1067. Application.Invoke(delegate
  1068. {
  1069. _firmwareVersionLabel.Text = currentFirmware != null ? currentFirmware.VersionString : "0.0.0";
  1070. });
  1071. }
  1072. private void HandleRelaunch()
  1073. {
  1074. if (_userChannelPersistence.PreviousIndex != -1 && _userChannelPersistence.ShouldRestart)
  1075. {
  1076. _userChannelPersistence.ShouldRestart = false;
  1077. LoadApplication(_currentEmulatedGamePath);
  1078. }
  1079. else
  1080. {
  1081. // otherwise, clear state.
  1082. _userChannelPersistence = new UserChannelPersistence();
  1083. _currentEmulatedGamePath = null;
  1084. }
  1085. }
  1086. private void FullScreen_Toggled(object sender, EventArgs args)
  1087. {
  1088. if (!Window.State.HasFlag(Gdk.WindowState.Fullscreen))
  1089. {
  1090. Fullscreen();
  1091. ToggleExtraWidgets(false);
  1092. }
  1093. else
  1094. {
  1095. Unfullscreen();
  1096. ToggleExtraWidgets(true);
  1097. }
  1098. }
  1099. private void StartFullScreen_Toggled(object sender, EventArgs args)
  1100. {
  1101. ConfigurationState.Instance.Ui.StartFullscreen.Value = _startFullScreen.Active;
  1102. SaveConfig();
  1103. }
  1104. private void OptionMenu_StateChanged(object o, StateChangedArgs args)
  1105. {
  1106. _manageUserProfiles.Sensitive = _emulationContext == null;
  1107. }
  1108. private void Settings_Pressed(object sender, EventArgs args)
  1109. {
  1110. SettingsWindow settingsWindow = new SettingsWindow(this, _virtualFileSystem, _contentManager);
  1111. settingsWindow.SetSizeRequest((int)(settingsWindow.DefaultWidth * Program.WindowScaleFactor), (int)(settingsWindow.DefaultHeight * Program.WindowScaleFactor));
  1112. settingsWindow.Show();
  1113. }
  1114. private void ManageUserProfiles_Pressed(object sender, EventArgs args)
  1115. {
  1116. UserProfilesManagerWindow userProfilesManagerWindow = new UserProfilesManagerWindow(_accountManager, _contentManager, _virtualFileSystem);
  1117. userProfilesManagerWindow.SetSizeRequest((int)(userProfilesManagerWindow.DefaultWidth * Program.WindowScaleFactor), (int)(userProfilesManagerWindow.DefaultHeight * Program.WindowScaleFactor));
  1118. userProfilesManagerWindow.Show();
  1119. }
  1120. private void Simulate_WakeUp_Message_Pressed(object sender, EventArgs args)
  1121. {
  1122. if (_emulationContext != null)
  1123. {
  1124. _emulationContext.System.SimulateWakeUpMessage();
  1125. }
  1126. }
  1127. private void ActionMenu_StateChanged(object o, StateChangedArgs args)
  1128. {
  1129. _scanAmiibo.Sensitive = _emulationContext != null && _emulationContext.System.SearchingForAmiibo(out int _);
  1130. }
  1131. private void Scan_Amiibo(object sender, EventArgs args)
  1132. {
  1133. if (_emulationContext.System.SearchingForAmiibo(out int deviceId))
  1134. {
  1135. AmiiboWindow amiiboWindow = new AmiiboWindow
  1136. {
  1137. LastScannedAmiiboShowAll = _lastScannedAmiiboShowAll,
  1138. LastScannedAmiiboId = _lastScannedAmiiboId,
  1139. DeviceId = deviceId,
  1140. TitleId = _emulationContext.Application.TitleIdText.ToUpper()
  1141. };
  1142. amiiboWindow.DeleteEvent += AmiiboWindow_DeleteEvent;
  1143. amiiboWindow.Show();
  1144. }
  1145. else
  1146. {
  1147. GtkDialog.CreateInfoDialog($"Amiibo", "The game is currently not ready to receive Amiibo scan data. Ensure that you have an Amiibo-compatible game open and ready to receive Amiibo scan data.");
  1148. }
  1149. }
  1150. private void AmiiboWindow_DeleteEvent(object sender, DeleteEventArgs args)
  1151. {
  1152. if (((AmiiboWindow)sender).AmiiboId != "" && ((AmiiboWindow)sender).Response == ResponseType.Ok)
  1153. {
  1154. _lastScannedAmiiboId = ((AmiiboWindow)sender).AmiiboId;
  1155. _lastScannedAmiiboShowAll = ((AmiiboWindow)sender).LastScannedAmiiboShowAll;
  1156. _emulationContext.System.ScanAmiibo(((AmiiboWindow)sender).DeviceId, ((AmiiboWindow)sender).AmiiboId, ((AmiiboWindow)sender).UseRandomUuid);
  1157. }
  1158. }
  1159. private void Update_Pressed(object sender, EventArgs args)
  1160. {
  1161. if (Updater.CanUpdate(true))
  1162. {
  1163. Updater.BeginParse(this, true).ContinueWith(task =>
  1164. {
  1165. Logger.Error?.Print(LogClass.Application, $"Updater error: {task.Exception}");
  1166. }, TaskContinuationOptions.OnlyOnFaulted);
  1167. }
  1168. }
  1169. private void About_Pressed(object sender, EventArgs args)
  1170. {
  1171. AboutWindow aboutWindow = new AboutWindow();
  1172. aboutWindow.SetSizeRequest((int)(aboutWindow.DefaultWidth * Program.WindowScaleFactor), (int)(aboutWindow.DefaultHeight * Program.WindowScaleFactor));
  1173. aboutWindow.Show();
  1174. }
  1175. private void Fav_Toggled(object sender, EventArgs args)
  1176. {
  1177. ConfigurationState.Instance.Ui.GuiColumns.FavColumn.Value = _favToggle.Active;
  1178. SaveConfig();
  1179. UpdateColumns();
  1180. }
  1181. private void Icon_Toggled(object sender, EventArgs args)
  1182. {
  1183. ConfigurationState.Instance.Ui.GuiColumns.IconColumn.Value = _iconToggle.Active;
  1184. SaveConfig();
  1185. UpdateColumns();
  1186. }
  1187. private void App_Toggled(object sender, EventArgs args)
  1188. {
  1189. ConfigurationState.Instance.Ui.GuiColumns.AppColumn.Value = _appToggle.Active;
  1190. SaveConfig();
  1191. UpdateColumns();
  1192. }
  1193. private void Developer_Toggled(object sender, EventArgs args)
  1194. {
  1195. ConfigurationState.Instance.Ui.GuiColumns.DevColumn.Value = _developerToggle.Active;
  1196. SaveConfig();
  1197. UpdateColumns();
  1198. }
  1199. private void Version_Toggled(object sender, EventArgs args)
  1200. {
  1201. ConfigurationState.Instance.Ui.GuiColumns.VersionColumn.Value = _versionToggle.Active;
  1202. SaveConfig();
  1203. UpdateColumns();
  1204. }
  1205. private void TimePlayed_Toggled(object sender, EventArgs args)
  1206. {
  1207. ConfigurationState.Instance.Ui.GuiColumns.TimePlayedColumn.Value = _timePlayedToggle.Active;
  1208. SaveConfig();
  1209. UpdateColumns();
  1210. }
  1211. private void LastPlayed_Toggled(object sender, EventArgs args)
  1212. {
  1213. ConfigurationState.Instance.Ui.GuiColumns.LastPlayedColumn.Value = _lastPlayedToggle.Active;
  1214. SaveConfig();
  1215. UpdateColumns();
  1216. }
  1217. private void FileExt_Toggled(object sender, EventArgs args)
  1218. {
  1219. ConfigurationState.Instance.Ui.GuiColumns.FileExtColumn.Value = _fileExtToggle.Active;
  1220. SaveConfig();
  1221. UpdateColumns();
  1222. }
  1223. private void FileSize_Toggled(object sender, EventArgs args)
  1224. {
  1225. ConfigurationState.Instance.Ui.GuiColumns.FileSizeColumn.Value = _fileSizeToggle.Active;
  1226. SaveConfig();
  1227. UpdateColumns();
  1228. }
  1229. private void Path_Toggled(object sender, EventArgs args)
  1230. {
  1231. ConfigurationState.Instance.Ui.GuiColumns.PathColumn.Value = _pathToggle.Active;
  1232. SaveConfig();
  1233. UpdateColumns();
  1234. }
  1235. private void RefreshList_Pressed(object sender, ButtonReleaseEventArgs args)
  1236. {
  1237. UpdateGameTable();
  1238. }
  1239. }
  1240. }