Ejemplo n.º 1
0
        public ErrorListViewModel(LoggerModule module, System.Windows.Media.ImageSource iconSource) : base(module, "ErrorList")
        {
            this.Module     = module;
            this.IconSource = iconSource;

            ClearMessagesCommand = new RelayCommand(ClearMessages);
        }
Ejemplo n.º 2
0
        private void HandleFile(FileInfo f, Uri uri, HttpListenerContext p, StreamWriter sw)
        {
            using (var reader = new System.IO.StreamReader(f.ToString(), true))
            {
                var fs = reader.BaseStream.ToArray();

                p.Response.ContentType = Mime.GetMimeType(f.Extension);

                if (!ContainsLang(f))
                {
                    if (Mime.GetMimeType(f.Extension).StartsWith("image"))
                    {
                        p.Response.OutputStream.Write(fs, 0, fs.Length);
                        p.Response.OutputStream.Flush();
                    }
                    else
                    {
                        sw.WriteLine(reader.CurrentEncoding.GetString(fs));
                        sw.Flush();
                    }
                }
                else
                {
                    var lng = GetLanguageByExtension(f);
                    lng.Load();

                    lng.Execute(reader.CurrentEncoding.GetString(fs), uri, p, _wc, sw);

                    LoggerModule.Log(lng.Name + " Script executed");
                }
            }
        }
Ejemplo n.º 3
0
        static void Main(string[] args)
        {
            var logger = LoggerModule.GetLogger();

            try
            {
                logger.Info("Приложение запущено");

                // Собираем контейнер.
                var builder = new ContainerBuilder();
                builder.RegisterModule <LoggerModule>();
                builder.RegisterModule <ApartmentsMonitorServiceModule>();
                var container = builder.Build();

                // Запускаем.
                container.Resolve <ApartmentsMonitorWorker>().Start();

                // Ожидаем завершения приложения.
                ManualResetEvent resetEvent = new ManualResetEvent(false);
                resetEvent.WaitOne();
                container.Dispose();

                logger.Info("Работа приложения завершена");
            }
            catch (Exception ex)
            {
                logger.Error("Произошла ошибка во время работы приложения", ex);
                throw;
            }
        }
        public void ResolveLoggerDependency()
        {
            var module  = new LoggerModule();
            var kernal  = new StandardKernel(module);
            var service = kernal.Get <TestClass>();

            Assert.That(service, Is.Not.Null);
        }
Ejemplo n.º 5
0
        static void Main(string[] args)
        {
            Console.Title = "Ryujinx Console";

            string systemPath = Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.Machine);

            Environment.SetEnvironmentVariable("Path", $"{Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin")};{systemPath}");

            GLib.ExceptionManager.UnhandledException += Glib_UnhandledException;

            // Initialize the configuration
            ConfigurationState.Initialize();

            // Initialize the logger system
            LoggerModule.Initialize();

            // Initialize Discord integration
            DiscordIntegrationModule.Initialize();

            string configurationPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config.json");

            // Now load the configuration as the other subsystems are now registered
            if (File.Exists(configurationPath))
            {
                ConfigurationFileFormat configurationFileFormat = ConfigurationFileFormat.Load(configurationPath);
                ConfigurationState.Instance.Load(configurationFileFormat);
            }
            else
            {
                // No configuration, we load the default values and save it on disk
                ConfigurationState.Instance.LoadDefault();
                ConfigurationState.Instance.ToFileFormat().SaveConfig(configurationPath);
            }


            Profile.Initialize();

            Application.Init();

            string appDataPath     = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Ryujinx", "system", "prod.keys");
            string userProfilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".switch", "prod.keys");

            if (!File.Exists(appDataPath) && !File.Exists(userProfilePath) && !Migration.IsMigrationNeeded())
            {
                GtkDialog.CreateErrorDialog("Key file was not found. Please refer to `KEYS.md` for more info");
            }

            MainWindow mainWindow = new MainWindow();

            mainWindow.Show();

            if (args.Length == 1)
            {
                mainWindow.LoadApplication(args[0]);
            }

            Application.Run();
        }
Ejemplo n.º 6
0
        public void Render(StreamWriter sw)
        {
            if (!isListing())
            {
                sw.WriteLine(ErrorProvider.GetHtml(403));
                LoggerModule.Log(ErrorProvider.GetHtml(403).StripHtml());

                return;
            }

            LoggerModule.Log("Lisiting Directory");

            string content = Resources.Listing;

            var dict = new Dictionary <string, object>();

            dict.Add("Folder", _p.Request.Url.LocalPath);
            dict.Add("Path", _p.Request.Url.AbsoluteUri);

            content    = Template.Render(content, dict);
            folderItem = Template.Render(folderItem, dict);
            fileItem   = Template.Render(fileItem, dict);

            var sb = new StringBuilder();

            var pdi = new DirectoryInfo(_fi.ToString());

            parentItem = parentItem.Replace("{{ParentFolder}}", "..");

            sb.AppendLine(parentItem);

            foreach (var folder in Directory.GetDirectories(_fi.ToString()))
            {
                var di = new DirectoryInfo(folder);

                if (folder != "Listing")
                {
                    sb.AppendLine(folderItem.Replace("{{folder}}", di.Name).Replace("{{Size}}", "0"));
                }
            }
            foreach (var file in Directory.GetFiles(_fi.ToString()))
            {
                var fi = new FileInfo(file);

                if (isIgnored(fi.Name))
                {
                    continue;
                }

                sb.AppendLine(fileItem.Replace("{{File}}", fi.Name).Replace("{{Size}}", SizeFormatter.Format(fi.Length, 2)));
            }

            content = content.Replace("{{Items}}", sb.ToString());

            sw.WriteLine(content);
        }
Ejemplo n.º 7
0
        public void TestsPublicCommandsReturn()
        {
            LoggerModule    module    = new LoggerModule();
            ModuleResponses responses = utils.moduleReturnsFromAllBaseCalls(module);

            Assert.True(responses.Enabled == true, "Failed to enable.");
            Assert.True(responses.Disabled == true, "Failed to disable.");
            Assert.True(responses.Tracked == true, "Failed to track.");
            Assert.True(responses.Reported == true, "Failed to handle report.");
        }
Ejemplo n.º 8
0
        public void Initialize()
        {
            context = new ExampleContext();
            ContextInfo contextInfo = new ContextInfo(((IObjectContextAdapter)context).ObjectContext);

            contextInfo.UnderlyingType = typeof(ExampleContext);
            loggerModule = new LoggerModule(connectionString, contextInfo, 1);

            // Should inject using Unity instead of set
            context.Logger = loggerModule;
        }
Ejemplo n.º 9
0
        public WebServer(WebConfig wc)
        {
            ws  = new HttpListener();
            ac  = new Access("");
            _wc = wc;

            ws.Prefixes.Add("http://" + wc.IPAddress + ":" + wc.Port + "/");
            ws.Prefixes.Add("http://localhost:" + wc.Port + "/");

            LoggerModule.Init();
            ErrorProvider.Init(ac, _wc);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Use to time the time it takes to execute function <c>f</c>.
        /// Logging is a Gauge in the unit seconds
        /// </summary>
        public static T Time <T>(this Logger logger, Func <T> f)
        {
            if (logger == null)
            {
                throw new ArgumentNullException("logger");
            }
            if (f == null)
            {
                throw new ArgumentNullException("f");
            }

            return(LoggerModule.Time(logger, null, CSharpFacade.ToFSharpFunc(f)));
        }
Ejemplo n.º 11
0
 /// <summary>
 /// 初始化日志模块
 /// </summary>
 /// <returns>是否成功</returns>
 private static Boolean InitializeLoggerModule()
 {
     if (!Directory.Exists(AppEnvironment.LogsDirectory))
     {
         try {
             _ = Directory.CreateDirectory(AppEnvironment.LogsDirectory);
         } catch (Exception exception) {
             Helpers.LoggerModuleHelper.TryLog(
                 "Program.InitializeLoggerModule[Error]", $"创建日志目录异常,{exception.Message}\n异常堆栈: {exception.StackTrace}");
             return(false);
         }
     }
     return(LoggerModule.Setup(AppEnvironment.LogsDirectory, 1000));
 }
Ejemplo n.º 12
0
 /// <summary>
 /// Use to time the time it takes to execute function <c>f</c>. The subPath can be your function name, for
 /// example.
 /// </summary>
 public static T TimePath <T>(this Logger logger, string subPath, Func <T> f, LogLevel level = null)
 {
     if (logger == null)
     {
         throw new ArgumentNullException("logger");
     }
     if (subPath == null)
     {
         throw new ArgumentNullException("subPath");
     }
     if (f == null)
     {
         throw new ArgumentNullException("f");
     }
     return(LoggerModule.Time <T>(logger, subPath, CSharpFacade.ToFSharpFunc(f)));
 }
Ejemplo n.º 13
0
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterInstance(LoggerModule.GetLogger()).As <ILogger>();
            builder.RegisterType <MainWindow>().AsSelf();
            builder.RegisterType <MainWindowViewModel>().AsSelf();
            builder.RegisterType <MapViewModel>().AsSelf();
            builder.RegisterType <RegionsService>().AsSelf();
            builder.RegisterType <ApartmentService>().AsSelf();
            builder.RegisterType <ApplicationContextProvider>().As <IDatabaseContextProvider>();

            var config = RegisterOptions(builder);

            if (config.UseOriginalProvider)
            {
                builder.RegisterType <AvitoApartmentsProvider>().As <IApartmentsProvider>();
            }
            else
            {
                builder.RegisterType <DatabaseApartmentsProvider>().As <IApartmentsProvider>();
            }
        }
Ejemplo n.º 14
0
        public static Assembly Init(CodeDomProvider bcp, string src, StreamWriter sw, IniFile ini)
        {
            var options = new CompilerParameters();

            options.GenerateExecutable = false;
            options.GenerateInMemory   = true;

            options.ReferencedAssemblies.AddRange(new[] { "System.dll", "System.Core.dll", "System.Drawing.dll", typeof(IScriptLanguage).Assembly.Location, typeof(Mono.Net.HttpListener).Assembly.Location });

            var sec = ini.GetSection("References");

            if (sec != null)
            {
                foreach (var refs in sec)
                {
                    options.ReferencedAssemblies.Add(refs.Value);
                }
            }

            var res = bcp.CompileAssemblyFromSource(options, src);

            if (res.Errors.HasErrors)
            {
                if (sw != null)
                {
                    foreach (CompilerError item in res.Errors)
                    {
                        LoggerModule.Log(item.Line + ": " + item.ErrorText);

                        throw new Exception(item.ErrorText);
                    }
                }
            }
            else
            {
                return(res.CompiledAssembly);
            }

            return(null);
        }
Ejemplo n.º 15
0
        public static string GetHtml(int errorcode)
        {
            if (_ac.ErrorDocument.ContainsKey(errorcode.ToString()))
            {
                var tmp = _ac.ErrorDocument[errorcode.ToString()];
                var fi  = new FileInfo(tmp.Replace("{data}", _wc.DataDir) + "\\");

                if (fi.Exists)
                {
                    var er = File.ReadAllText(tmp);

                    LoggerModule.Log(er);

                    return(er);
                }

                return(tmp);
            }
            else
            {
                return("<h1>Error " + errorcode + "</h1>");
            }
        }
Ejemplo n.º 16
0
        static void Main(string[] args)
        {
            _logger = LoggerModule.GetLogger();
            _logger.Info("Приложение запущено!");

            try
            {
                ISettingsService <CashlogSettings> settingsService = new CashlogSettingsService();
                var config = settingsService.ReadSettings();
                if (string.IsNullOrEmpty(config.TelegramBotToken))
                {
                    throw new InvalidOperationException($"Поле `{nameof(config.TelegramBotToken)}` в конфиге пустое");
                }

                WorkOn();

                _logger.Info("Приложение завершило свою работу");
            }
            catch (Exception ex)
            {
                _logger.Error("Во время работы приложения произошла ошибка", ex);
                throw;
            }
        }
Ejemplo n.º 17
0
        public PhantomLogger(LoggerModule module)
        {
            var loggerConfig = new LoggingConfiguration();

            var consoleTarget = new ColoredConsoleTarget("PhantomConsoleTarget");

            // Console log layout
            consoleTarget.Layout = @"${date:format=yyyy-MM-dd HH\:mm\:ss} | ${logger} ${level} - ${message}  ${exception}";

            // Replaces the Info log color to Green
            var infoGreenRule = new ConsoleRowHighlightingRule();

            infoGreenRule.Condition       = ConditionParser.ParseExpression("level == LogLevel.Info");
            infoGreenRule.ForegroundColor = ConsoleOutputColor.Green;

            consoleTarget.RowHighlightingRules.Add(infoGreenRule);

            // Add targets and rules
            loggerConfig.AddTarget(consoleTarget);
            loggerConfig.AddRuleForAllLevels(consoleTarget);

            LogManager.Configuration = loggerConfig;
            logger = LogManager.GetLogger(module.ToString());
        }
Ejemplo n.º 18
0
 /// <summary>
 /// 应用程序退出之前
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private static void CurrentDomainProcessExit(object sender, EventArgs e)
 {
     //释放远程管理模块
     RemoteControlModule.Dispose();
     //释放单元管理模块,应确保已无单元正在运行
     UnitManageModule.Dispose();
     //释放单元日志模块
     UnitLoggerModule.Dispose();
     //释放单元性能监控模块
     UnitPerformanceCounterModule.Dispose();
     //是否单元网络监控模块
     UnitNetworkCounterModule.Dispose();
     //停止服务
     if (DaemonServiceController != null)
     {
         DaemonServiceController.Stop();
     }
     //释放自身进程引用
     AppMutex.Dispose();
     AppProcess.Dispose();
     //释放日志模块
     Helpers.LoggerModuleHelper.TryLog("Program.CurrentDomainProcessExit[Warning]", "服务主机进程退出");
     LoggerModule.Dispose();
 }
Ejemplo n.º 19
0
 public OutputViewModel(LoggerModule module, System.Windows.Media.ImageSource iconSource) : base(module, "Output")
 {
     this.Module     = module;
     this.IconSource = iconSource;
 }
Ejemplo n.º 20
0
        public void HandleRequest(HttpListenerContext p)
        {
            var uri = p.Request.Url;

            LoggerModule.Log("request " + uri.AbsolutePath);

            var sw = new StreamWriter(p.Response.OutputStream);

            var f = new FileInfo(_wc.DataDir + uri.AbsolutePath);

            if (Access.HasAccess(f.DirectoryName))
            {
                var htaccess = new Furesoft.Web.Internal.HtAccess.Parser();

                htaccess.AddContstant("HTTP_HOST", uri.Host);
                htaccess.AddContstant("HTTP_URI", uri.ToString());
                htaccess.AddContstant("HTTP_PATH", uri.LocalPath);

                if (f.Exists)
                {
                    htaccess.Parse(File.ReadAllText(f.DirectoryName + @"\.htaccess"));
                }
                else
                {
                    htaccess.Parse(File.ReadAllText(_wc.DataDir + @"\.htaccess"));
                }

                ac = new Access(f.DirectoryName);

                //htaccess.PopulateCondition("*" + Path.GetExtension(f.Name), ac);
                htaccess.Populate(ac);

                AccessModule.Init(ac);

                if (ac.Redirect.Count > 0)
                {
                    foreach (var r in ac.Redirect)
                    {
                        if (uri.AbsolutePath == "/" + r.Key)
                        {
                            uri = new Uri(_wc.DataDir + r.Key);

                            string uris = HttpUtility.UrlDecode(uri.ToString()).Replace("file:///", "");
                            uri = new Uri(uris);

                            if (uris.Contains("?"))
                            {
                                uris = uris.Substring(0, uris.IndexOf("?"));
                            }

                            f = new FileInfo(uris);

                            p.Response.Redirect(r.Value);
                            return;
                        }
                    }
                }

                if (ac.RewriteEngine)
                {
                    var ff = "";
                    RewriteRule.Match(uri, ac, out ff);

                    if (ff != "")
                    {
                        uri = new Uri(_wc.DataDir + ff);
                        string uris = HttpUtility.UrlDecode(uri.ToString()).Replace("file:///", "");
                        uri = new Uri(uris);

                        if (uris.Contains("?"))
                        {
                            uris = uris.Substring(0, uris.IndexOf("?"));
                        }

                        f = new FileInfo(uris);
                    }
                }

                foreach (var er in ac.ErrorDocument)
                {
                    if (!_wc.ErrorPages.ContainsKey(er.Key))
                    {
                        _wc.ErrorPages.Add(er.Key, er.Value);
                    }
                }

                if (htaccess.GetCommand <Directive>("AuthUserFile") != null)
                {
                    ac.ReadUserFile();
                }
            }

            if (AccessModule.IsBlocked(p.Request.LocalEndPoint.Address.ToString()))
            {
                sw.WriteLine(ErrorProvider.GetHtml(403));
                LoggerModule.Log(ErrorProvider.GetHtml(403));

                return;
            }

            if (ac.AuthType == "Basic")
            {
                if (!authed)
                {
                    // ws.AuthenticationSchemes = AuthenticationSchemes.Basic;
                    ws.AuthenticationSchemeSelectorDelegate = (s) =>
                    {
                        try
                        {
                            if (p.User.Identity.IsAuthenticated)
                            {
                                LoggerModule.Log("Authentication requested");

                                foreach (var u in ac.Users)
                                {
                                    var identity = (HttpListenerBasicIdentity)p.User.Identity;

                                    if (identity.Name == u.Username && identity.Password == u.Password)
                                    {
                                        //    authed = true;
                                        return(AuthenticationSchemes.None);
                                    }
                                    else
                                    {
                                        p.Response.StatusCode = 403;
                                        p.Response.OutputStream.Seek(10, SeekOrigin.Current);

                                        sw.WriteLine("<p>Access Denied</p>");

                                        LoggerModule.Log(ErrorProvider.GetHtml(403));
                                    }
                                }
                            }
                        }
                        catch
                        {
                        }
                        if (ac.AuthType == "Basic")
                        {
                            return(AuthenticationSchemes.Basic);
                        }
                        else
                        {
                            return(AuthenticationSchemes.None);
                        }
                    };
                }

                if (File.Exists(f.ToString()))
                {
                    HandleFile(f, uri, p, sw);
                }
                else if (!uri.IsFile && Directory.Exists(f.ToString()))
                {
                    var index = "index.html";

                    if (ac != null)
                    {
                        if (ac.DirectoryIndex != null)
                        {
                            index = ac.DirectoryIndex;
                        }
                    }

                    if (!File.Exists(f.ToString() + index))
                    {
                        new DirectoryListing(ac, p, f).Render(sw);
                    }
                    else
                    {
                        HandleFile(new FileInfo(f.ToString() + index), uri, p, sw);
                    }
                }
                else
                {
                    sw.WriteLine(ErrorProvider.GetHtml(404));
                    LoggerModule.Log(ErrorProvider.GetHtml(404));
                }

                p.Response.OutputStream.Flush();
                sw.Flush();
                p.Response.Close();
                sw.Close();
            }

            /*
             * public byte[] SendResponse(HttpListenerRequest request, HttpListenerResponse response)
             * {
             * var f = new FileInfo(_wc.DataDir + request.Url.AbsolutePath);
             * if (request.HttpMethod == "GET")
             * {
             * if(Access.HasAccess(f.DirectoryName))
             * {
             * var htaccess = new Furesoft.Web.Internal.HtAccess.Parser();
             * htaccess.Parse(File.ReadAllText(f.DirectoryName + @"\.htaccess"));
             * var ac = new Access(f.DirectoryName);
             * htaccess.PopulateCondition("*" + Path.GetExtension(f.Name), ac);
             * htaccess.Populate(ac);
             * if (htaccess.GetCommand<Directive>("AuthUserFile") != null)
             * {
             * ac.AuthUserFile = (string)htaccess.GetCommand<Directive>("AuthUserFile").Values[0];
             * ac.ReadUserFile();
             * }
             * if (htaccess.GetCommand<Directive>("AuthName") != null)
             * {
             * ac.AuthName = (string)htaccess.GetCommand<Directive>("AuthName").Values[0];
             * }
             * if (htaccess.GetCommand<Directive>("AuthType") != null)
             * {
             * ac.AuthType = (string)htaccess.GetCommand<Directive>("AuthType").Values[0];
             * ws._listener.AuthenticationSchemes = (AuthenticationSchemes)Enum.Parse(typeof(AuthenticationSchemes), ac.AuthType);
             * HttpListenerContext context = ws._listener.GetContext();
             * HttpListenerBasicIdentity identity = (HttpListenerBasicIdentity)context.User.Identity;
             * if (identity != null)
             * {
             * foreach (var user in ac.Users)
             * {
             * if (user.Username == identity.Name)
             * {
             * if ((user.Password) == identity.Password)
             * {
             * if (File.Exists(f.ToString()))
             * {
             * // GetScriptByExtension(f.ToString());
             * return File.ReadAllBytes(f.ToString());
             * }
             * else if (!request.Url.IsFile)
             * {
             * return File.ReadAllBytes(_wc.DataDir + "index.html");
             * }
             * else
             * {
             * return Encoding.ASCII.GetBytes(_wc.ErrorPages["403"]);
             * }
             * }
             * else
             * {
             * return Encoding.ASCII.GetBytes(_wc.ErrorPages["403"]);
             * }
             * }
             * }
             * }
             * else
             * {
             * return Encoding.ASCII.GetBytes(_wc.ErrorPages["404"]);
             * }
             * }
             * }
             * }
             * else
             * {
             * if (request.Headers.AllKeys.ToList().Contains("service"))
             * {
             * if (request.IsSecureConnection)
             * {
             * }
             * }
             * }
             * return null;
             * }
             */
        }
Ejemplo n.º 21
0
        static void Main(string[] args)
        {
            Toolkit.Init(new ToolkitOptions
            {
                Backend = PlatformBackend.PreferNative,
                EnableHighResolution = true
            });

            Version = Assembly.GetEntryAssembly().GetCustomAttribute <AssemblyInformationalVersionAttribute>().InformationalVersion;

            Console.Title = $"Ryujinx Console {Version}";

            string systemPath = Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.Machine);

            Environment.SetEnvironmentVariable("Path", $"{Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin")};{systemPath}");

            GLib.ExceptionManager.UnhandledException += Glib_UnhandledException;

            // Initialize the configuration
            ConfigurationState.Initialize();

            // Initialize the logger system
            LoggerModule.Initialize();

            // Initialize Discord integration
            DiscordIntegrationModule.Initialize();

            string localConfigurationPath  = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config.json");
            string globalBasePath          = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Ryujinx");
            string globalConfigurationPath = Path.Combine(globalBasePath, "Config.json");

            // Now load the configuration as the other subsystems are now registered
            if (File.Exists(localConfigurationPath))
            {
                ConfigurationPath = localConfigurationPath;

                ConfigurationFileFormat configurationFileFormat = ConfigurationFileFormat.Load(localConfigurationPath);

                ConfigurationState.Instance.Load(configurationFileFormat, ConfigurationPath);
            }
            else if (File.Exists(globalConfigurationPath))
            {
                ConfigurationPath = globalConfigurationPath;

                ConfigurationFileFormat configurationFileFormat = ConfigurationFileFormat.Load(globalConfigurationPath);

                ConfigurationState.Instance.Load(configurationFileFormat, ConfigurationPath);
            }
            else
            {
                // No configuration, we load the default values and save it on disk
                ConfigurationPath = globalConfigurationPath;

                // Make sure to create the Ryujinx directory if needed.
                Directory.CreateDirectory(globalBasePath);

                ConfigurationState.Instance.LoadDefault();
                ConfigurationState.Instance.ToFileFormat().SaveConfig(globalConfigurationPath);
            }

            Logger.PrintInfo(LogClass.Application, $"Ryujinx Version: {Version}");

            Logger.PrintInfo(LogClass.Application, $"Operating System: {SystemInfo.Instance.OsDescription}");
            Logger.PrintInfo(LogClass.Application, $"CPU: {SystemInfo.Instance.CpuName}");
            Logger.PrintInfo(LogClass.Application, $"Total RAM: {SystemInfo.Instance.RamSizeInMB}");

            Profile.Initialize();

            Application.Init();

            string globalProdKeysPath = Path.Combine(globalBasePath, "system", "prod.keys");
            string userProfilePath    = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".switch", "prod.keys");

            if (!File.Exists(globalProdKeysPath) && !File.Exists(userProfilePath) && !Migration.IsMigrationNeeded())
            {
                GtkDialog.CreateWarningDialog("Key file was not found", "Please refer to `KEYS.md` for more info");
            }

            MainWindow mainWindow = new MainWindow();

            mainWindow.Show();

            if (args.Length == 1)
            {
                mainWindow.LoadApplication(args[0]);
            }

            Application.Run();
        }
Ejemplo n.º 22
0
        static void Main(string[] args)
        {
            Version = ReleaseInformations.GetVersion();

            if (OperatingSystem.IsWindows() && !OperatingSystem.IsWindowsVersionAtLeast(10, 0, 17134))
            {
                MessageBoxA(IntPtr.Zero, "You are running an outdated version of Windows.\n\nStarting on June 1st 2022, Ryujinx will only support Windows 10 1803 and newer.\n", $"Ryujinx {Version}", MB_ICONWARNING);
            }

            // Parse Arguments.
            string launchPathArg      = null;
            string baseDirPathArg     = null;
            bool   startFullscreenArg = false;

            for (int i = 0; i < args.Length; ++i)
            {
                string arg = args[i];

                if (arg == "-r" || arg == "--root-data-dir")
                {
                    if (i + 1 >= args.Length)
                    {
                        Logger.Error?.Print(LogClass.Application, $"Invalid option '{arg}'");

                        continue;
                    }

                    baseDirPathArg = args[++i];
                }
                else if (arg == "-p" || arg == "--profile")
                {
                    if (i + 1 >= args.Length)
                    {
                        Logger.Error?.Print(LogClass.Application, $"Invalid option '{arg}'");

                        continue;
                    }

                    CommandLineProfile = args[++i];
                }
                else if (arg == "-f" || arg == "--fullscreen")
                {
                    startFullscreenArg = true;
                }
                else if (launchPathArg == null)
                {
                    launchPathArg = arg;
                }
            }

            // Make process DPI aware for proper window sizing on high-res screens.
            ForceDpiAware.Windows();
            WindowScaleFactor = ForceDpiAware.GetWindowScaleFactor();

            // Delete backup files after updating.
            Task.Run(Updater.CleanupUpdate);

            Console.Title = $"Ryujinx Console {Version}";

            // NOTE: GTK3 doesn't init X11 in a multi threaded way.
            // This ends up causing race condition and abort of XCB when a context is created by SPB (even if SPB do call XInitThreads).
            if (OperatingSystem.IsLinux())
            {
                XInitThreads();
            }

            string systemPath = Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.Machine);

            Environment.SetEnvironmentVariable("Path", $"{Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin")};{systemPath}");

            // Hook unhandled exception and process exit events.
            GLib.ExceptionManager.UnhandledException   += (GLib.UnhandledExceptionArgs e) => ProcessUnhandledException(e.ExceptionObject as Exception, e.IsTerminating);
            AppDomain.CurrentDomain.UnhandledException += (object sender, UnhandledExceptionEventArgs e) => ProcessUnhandledException(e.ExceptionObject as Exception, e.IsTerminating);
            AppDomain.CurrentDomain.ProcessExit        += (object sender, EventArgs e) => Exit();

            // Setup base data directory.
            AppDataManager.Initialize(baseDirPathArg);

            // Initialize the configuration.
            ConfigurationState.Initialize();

            // Initialize the logger system.
            LoggerModule.Initialize();

            // Initialize Discord integration.
            DiscordIntegrationModule.Initialize();

            // Sets ImageSharp Jpeg Encoder Quality.
            SixLabors.ImageSharp.Configuration.Default.ImageFormatsManager.SetEncoder(JpegFormat.Instance, new JpegEncoder()
            {
                Quality = 100
            });

            string localConfigurationPath   = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config.json");
            string appDataConfigurationPath = Path.Combine(AppDataManager.BaseDirPath, "Config.json");

            // Now load the configuration as the other subsystems are now registered
            ConfigurationPath = File.Exists(localConfigurationPath)
                ? localConfigurationPath
                : File.Exists(appDataConfigurationPath)
                    ? appDataConfigurationPath
                    : null;

            bool showVulkanPrompt = false;

            if (ConfigurationPath == null)
            {
                // No configuration, we load the default values and save it to disk
                ConfigurationPath = appDataConfigurationPath;

                ConfigurationState.Instance.LoadDefault();
                ConfigurationState.Instance.ToFileFormat().SaveConfig(ConfigurationPath);

                showVulkanPrompt = true;
            }
            else
            {
                if (ConfigurationFileFormat.TryLoad(ConfigurationPath, out ConfigurationFileFormat configurationFileFormat))
                {
                    ConfigurationLoadResult result = ConfigurationState.Instance.Load(configurationFileFormat, ConfigurationPath);

                    if ((result & ConfigurationLoadResult.MigratedFromPreVulkan) != 0)
                    {
                        showVulkanPrompt = true;
                    }
                }
                else
                {
                    ConfigurationState.Instance.LoadDefault();

                    showVulkanPrompt = true;

                    Logger.Warning?.PrintMsg(LogClass.Application, $"Failed to load config! Loading the default config instead.\nFailed config location {ConfigurationPath}");
                }
            }

            // Logging system information.
            PrintSystemInfo();

            // Enable OGL multithreading on the driver, when available.
            BackendThreading threadingMode = ConfigurationState.Instance.Graphics.BackendThreading;

            DriverUtilities.ToggleOGLThreading(threadingMode == BackendThreading.Off);

            // Initialize Gtk.
            Application.Init();

            // Check if keys exists.
            bool hasSystemProdKeys = File.Exists(Path.Combine(AppDataManager.KeysDirPath, "prod.keys"));
            bool hasCommonProdKeys = AppDataManager.Mode == AppDataManager.LaunchMode.UserProfile && File.Exists(Path.Combine(AppDataManager.KeysDirPathUser, "prod.keys"));

            if (!hasSystemProdKeys && !hasCommonProdKeys)
            {
                UserErrorDialog.CreateUserErrorDialog(UserError.NoKeys);
            }

            // Show the main window UI.
            MainWindow mainWindow = new MainWindow();

            mainWindow.Show();

            if (launchPathArg != null)
            {
                mainWindow.LoadApplication(launchPathArg, startFullscreenArg);
            }

            if (ConfigurationState.Instance.CheckUpdatesOnStart.Value && Updater.CanUpdate(false))
            {
                Updater.BeginParse(mainWindow, false).ContinueWith(task =>
                {
                    Logger.Error?.Print(LogClass.Application, $"Updater Error: {task.Exception}");
                }, TaskContinuationOptions.OnlyOnFaulted);
            }

            if (showVulkanPrompt)
            {
                var buttonTexts = new Dictionary <int, string>()
                {
                    { 0, "Yes (Vulkan)" },
                    { 1, "No (OpenGL)" }
                };

                ResponseType response = GtkDialog.CreateCustomDialog(
                    "Ryujinx - Default graphics backend",
                    "Use Vulkan as default graphics backend?",
                    "Ryujinx now supports the Vulkan API. " +
                    "Vulkan greatly improves shader compilation performance, " +
                    "and fixes some graphical glitches; however, since it is a new feature, " +
                    "you may experience some issues that did not occur with OpenGL.\n\n" +
                    "Note that you will also lose any existing shader cache the first time you start a game " +
                    "on version 1.1.200 onwards, because Vulkan required changes to the shader cache that makes it incompatible with previous versions.\n\n" +
                    "Would you like to set Vulkan as the default graphics backend? " +
                    "You can change this at any time on the settings window.",
                    buttonTexts,
                    MessageType.Question);

                ConfigurationState.Instance.Graphics.GraphicsBackend.Value = response == 0
                    ? GraphicsBackend.Vulkan
                    : GraphicsBackend.OpenGl;

                ConfigurationState.Instance.ToFileFormat().SaveConfig(Program.ConfigurationPath);
            }

            Application.Run();
        }
Ejemplo n.º 23
0
        static void Main(string[] args)
        {
            Version = ReleaseInformations.GetVersion();

            if (OperatingSystem.IsWindows() && !OperatingSystem.IsWindowsVersionAtLeast(10, 0, 17134))
            {
                MessageBoxA(IntPtr.Zero, "You are running an outdated version of Windows.\n\nStarting on June 1st 2022, Ryujinx will only support Windows 10 1803 and newer.\n", $"Ryujinx {Version}", MB_ICONWARNING);
            }

            // Parse Arguments.
            string launchPathArg      = null;
            string baseDirPathArg     = null;
            bool   startFullscreenArg = false;

            for (int i = 0; i < args.Length; ++i)
            {
                string arg = args[i];

                if (arg == "-r" || arg == "--root-data-dir")
                {
                    if (i + 1 >= args.Length)
                    {
                        Logger.Error?.Print(LogClass.Application, $"Invalid option '{arg}'");

                        continue;
                    }

                    baseDirPathArg = args[++i];
                }
                else if (arg == "-p" || arg == "--profile")
                {
                    if (i + 1 >= args.Length)
                    {
                        Logger.Error?.Print(LogClass.Application, $"Invalid option '{arg}'");

                        continue;
                    }

                    CommandLineProfile = args[++i];
                }
                else if (arg == "-f" || arg == "--fullscreen")
                {
                    startFullscreenArg = true;
                }
                else if (launchPathArg == null)
                {
                    launchPathArg = arg;
                }
            }

            // Make process DPI aware for proper window sizing on high-res screens.
            ForceDpiAware.Windows();
            WindowScaleFactor = ForceDpiAware.GetWindowScaleFactor();

            // Delete backup files after updating.
            Task.Run(Updater.CleanupUpdate);

            Console.Title = $"Ryujinx Console {Version}";

            // NOTE: GTK3 doesn't init X11 in a multi threaded way.
            // This ends up causing race condition and abort of XCB when a context is created by SPB (even if SPB do call XInitThreads).
            if (OperatingSystem.IsLinux())
            {
                XInitThreads();
            }

            string systemPath = Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.Machine);

            Environment.SetEnvironmentVariable("Path", $"{Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin")};{systemPath}");

            // Hook unhandled exception and process exit events.
            GLib.ExceptionManager.UnhandledException   += (GLib.UnhandledExceptionArgs e) => ProcessUnhandledException(e.ExceptionObject as Exception, e.IsTerminating);
            AppDomain.CurrentDomain.UnhandledException += (object sender, UnhandledExceptionEventArgs e) => ProcessUnhandledException(e.ExceptionObject as Exception, e.IsTerminating);
            AppDomain.CurrentDomain.ProcessExit        += (object sender, EventArgs e) => Exit();

            // Setup base data directory.
            AppDataManager.Initialize(baseDirPathArg);

            // Initialize the configuration.
            ConfigurationState.Initialize();

            // Initialize the logger system.
            LoggerModule.Initialize();

            // Initialize Discord integration.
            DiscordIntegrationModule.Initialize();

            // Sets ImageSharp Jpeg Encoder Quality.
            SixLabors.ImageSharp.Configuration.Default.ImageFormatsManager.SetEncoder(JpegFormat.Instance, new JpegEncoder()
            {
                Quality = 100
            });

            string localConfigurationPath   = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config.json");
            string appDataConfigurationPath = Path.Combine(AppDataManager.BaseDirPath, "Config.json");

            // Now load the configuration as the other subsystems are now registered
            ConfigurationPath = File.Exists(localConfigurationPath)
                ? localConfigurationPath
                : File.Exists(appDataConfigurationPath)
                    ? appDataConfigurationPath
                    : null;

            if (ConfigurationPath == null)
            {
                // No configuration, we load the default values and save it to disk
                ConfigurationPath = appDataConfigurationPath;

                ConfigurationState.Instance.LoadDefault();
                ConfigurationState.Instance.ToFileFormat().SaveConfig(ConfigurationPath);
            }
            else
            {
                if (ConfigurationFileFormat.TryLoad(ConfigurationPath, out ConfigurationFileFormat configurationFileFormat))
                {
                    ConfigurationState.Instance.Load(configurationFileFormat, ConfigurationPath);
                }
                else
                {
                    ConfigurationState.Instance.LoadDefault();
                    Logger.Warning?.PrintMsg(LogClass.Application, $"Failed to load config! Loading the default config instead.\nFailed config location {ConfigurationPath}");
                }
            }

            // Logging system information.
            PrintSystemInfo();

            // Enable OGL multithreading on the driver, when available.
            BackendThreading threadingMode = ConfigurationState.Instance.Graphics.BackendThreading;

            DriverUtilities.ToggleOGLThreading(threadingMode == BackendThreading.Off);

            // Initialize Gtk.
            Application.Init();

            // Check if keys exists.
            bool hasSystemProdKeys = File.Exists(Path.Combine(AppDataManager.KeysDirPath, "prod.keys"));
            bool hasCommonProdKeys = AppDataManager.Mode == AppDataManager.LaunchMode.UserProfile && File.Exists(Path.Combine(AppDataManager.KeysDirPathUser, "prod.keys"));

            if (!hasSystemProdKeys && !hasCommonProdKeys)
            {
                UserErrorDialog.CreateUserErrorDialog(UserError.NoKeys);
            }

            // Show the main window UI.
            MainWindow mainWindow = new MainWindow();

            mainWindow.Show();

            if (launchPathArg != null)
            {
                mainWindow.LoadApplication(launchPathArg, startFullscreenArg);
            }

            if (ConfigurationState.Instance.CheckUpdatesOnStart.Value && Updater.CanUpdate(false))
            {
                Updater.BeginParse(mainWindow, false).ContinueWith(task =>
                {
                    Logger.Error?.Print(LogClass.Application, $"Updater Error: {task.Exception}");
                }, TaskContinuationOptions.OnlyOnFaulted);
            }

            Application.Run();
        }
Ejemplo n.º 24
0
        /// <summary>
        /// 初始化
        /// </summary>
        /// <returns></returns>
        private static Boolean Initialize()
        {
            //互斥
            AppMutex = new Mutex(true, "WindCommandLineController", out Boolean mutex);
            if (!mutex)
            {
                LoggerModuleHelper.TryLog("Program.Initialize[Error]", "已存在实例");
                return(false);
            }
            //读取配置
            if (!Directory.Exists(AppEnvironment.BaseDirectory))
            {
                return(false);
            }
            String appSettingsFilePath = String.Concat(AppEnvironment.DataDirectory, Path.DirectorySeparatorChar, "AppSettings.json");

            if (!File.Exists(appSettingsFilePath))
            {
                return(false);
            }
            Entities.Common.AppSettings appSettings;
            FileStream fs = null;

            try {
                fs = File.Open(appSettingsFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                if (fs.Length < 1 || fs.Length > 4096)
                {
                    return(false);
                }
                Span <Byte> bufferSpan = new Span <Byte>(new Byte[fs.Length]);
                fs.Read(bufferSpan);
                fs.Dispose();
                appSettings = JsonSerializer.Deserialize <Entities.Common.AppSettings>(bufferSpan);
            }catch (Exception exception) {
                LoggerModuleHelper.TryLog("Program.Initialize[Error]", $"读取应用程序配置文件异常,{exception.Message}\n异常堆栈: {exception.StackTrace}");
                return(false);
            }finally{
                fs?.Dispose();
            }
            if (appSettings == null || String.IsNullOrWhiteSpace(appSettings.RemoteControlAddress) || String.IsNullOrWhiteSpace(appSettings.RemoteControlKey) || appSettings.RemoteControlPort < 1024 || appSettings.RemoteControlPort > Int16.MaxValue)
            {
                return(false);
            }
            Regex regex = new Regex(@"^[0-9\.]{7,15}$", RegexOptions.Compiled);

            if (appSettings.RemoteControlAddress != "localhost" && !regex.IsMatch(appSettings.RemoteControlAddress))
            {
                return(false);
            }
            Regex regex2 = new Regex(@"^\S{32,4096}$", RegexOptions.Compiled);

            if (!regex2.IsMatch(appSettings.RemoteControlKey))
            {
                return(false);
            }
            AppSettings.RemoteControlAddress = appSettings.RemoteControlAddress;
            AppSettings.RemoteControlPort    = appSettings.RemoteControlPort;
            AppSettings.RemoteControlKey     = appSettings.RemoteControlKey;
            //初始化日志模块
            if (!LoggerModule.Setup(AppEnvironment.LogsDirectory, 1000))
            {
                LoggerModuleHelper.TryLog("Program.Initialize[Error]", "初始化日志模块失败");
                return(false);
            }
            //初始化控制模块
            if (!RemoteControlModule.Setup(AppSettings.RemoteControlAddress, AppSettings.RemoteControlPort, AppSettings.RemoteControlKey))
            {
                LoggerModuleHelper.TryLog("Program.Initialize[Error]", "初始化远程控制模块失败");
                return(false);
            }
            //
            Console.CancelKeyPress += ConsoleCancelKeyPress;
            return(true);
        }
Ejemplo n.º 25
0
 /// <summary>
 /// 构造
 /// </summary>
 /// <param name="loggerModule">日志模块依赖</param>
 public ErrorHandlingMiddleware(LoggerModule loggerModule) => this.LoggerModule = loggerModule;
Ejemplo n.º 26
0
        static void Main(string[] args)
        {
            // Parse Arguments
            string launchPath  = null;
            string baseDirPath = null;

            for (int i = 0; i < args.Length; ++i)
            {
                string arg = args[i];

                if (arg == "-r" || arg == "--root-data-dir")
                {
                    if (i + 1 >= args.Length)
                    {
                        Logger.Error?.Print(LogClass.Application, $"Invalid option '{arg}'");
                        continue;
                    }

                    baseDirPath = args[++i];
                }
                else if (launchPath == null)
                {
                    launchPath = arg;
                }
            }

            Toolkit.Init(new ToolkitOptions
            {
                Backend = PlatformBackend.PreferNative,
                EnableHighResolution = true
            });

            Version = Assembly.GetEntryAssembly().GetCustomAttribute <AssemblyInformationalVersionAttribute>().InformationalVersion;

            Console.Title = $"Ryujinx Console {Version}";

            string systemPath = Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.Machine);

            Environment.SetEnvironmentVariable("Path", $"{Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin")};{systemPath}");

            // Hook unhandled exception and process exit events
            GLib.ExceptionManager.UnhandledException   += (GLib.UnhandledExceptionArgs e) => ProcessUnhandledException(e.ExceptionObject as Exception, e.IsTerminating);
            AppDomain.CurrentDomain.UnhandledException += (object sender, UnhandledExceptionEventArgs e) => ProcessUnhandledException(e.ExceptionObject as Exception, e.IsTerminating);
            AppDomain.CurrentDomain.ProcessExit        += (object sender, EventArgs e) => ProgramExit();

            // Setup base data directory
            AppDataManager.Initialize(baseDirPath);

            // Initialize the configuration
            ConfigurationState.Initialize();

            // Initialize the logger system
            LoggerModule.Initialize();

            // Initialize Discord integration
            DiscordIntegrationModule.Initialize();

            string localConfigurationPath   = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config.json");
            string appDataConfigurationPath = Path.Combine(AppDataManager.BaseDirPath, "Config.json");

            // Now load the configuration as the other subsystems are now registered
            if (File.Exists(localConfigurationPath))
            {
                ConfigurationPath = localConfigurationPath;

                ConfigurationFileFormat configurationFileFormat = ConfigurationFileFormat.Load(localConfigurationPath);

                ConfigurationState.Instance.Load(configurationFileFormat, ConfigurationPath);
            }
            else if (File.Exists(appDataConfigurationPath))
            {
                ConfigurationPath = appDataConfigurationPath;

                ConfigurationFileFormat configurationFileFormat = ConfigurationFileFormat.Load(appDataConfigurationPath);

                ConfigurationState.Instance.Load(configurationFileFormat, ConfigurationPath);
            }
            else
            {
                // No configuration, we load the default values and save it on disk
                ConfigurationPath = appDataConfigurationPath;

                ConfigurationState.Instance.LoadDefault();
                ConfigurationState.Instance.ToFileFormat().SaveConfig(appDataConfigurationPath);
            }

            PrintSystemInfo();

            Application.Init();

            bool hasGlobalProdKeys = File.Exists(Path.Combine(AppDataManager.KeysDirPath, "prod.keys"));
            bool hasAltProdKeys    = !AppDataManager.IsCustomBasePath && File.Exists(Path.Combine(AppDataManager.KeysDirPathAlt, "prod.keys"));

            if (!hasGlobalProdKeys && !hasAltProdKeys && !Migration.IsMigrationNeeded())
            {
                UserErrorDialog.CreateUserErrorDialog(UserError.NoKeys);
            }

            MainWindow mainWindow = new MainWindow();

            mainWindow.Show();

            if (launchPath != null)
            {
                mainWindow.LoadApplication(launchPath);
            }

            Application.Run();
        }
Ejemplo n.º 27
0
        static void Main(string[] args)
        {
            // Parse Arguments.
            string launchPathArg      = null;
            string baseDirPathArg     = null;
            bool   startFullscreenArg = false;

            for (int i = 0; i < args.Length; ++i)
            {
                string arg = args[i];

                if (arg == "-r" || arg == "--root-data-dir")
                {
                    if (i + 1 >= args.Length)
                    {
                        Logger.Error?.Print(LogClass.Application, $"Invalid option '{arg}'");

                        continue;
                    }

                    baseDirPathArg = args[++i];
                }
                else if (arg == "-f" || arg == "--fullscreen")
                {
                    startFullscreenArg = true;
                }
                else if (launchPathArg == null)
                {
                    launchPathArg = arg;
                }
            }

            // Make process DPI aware for proper window sizing on high-res screens.
            ForceDpiAware.Windows();
            WindowScaleFactor = ForceDpiAware.GetWindowScaleFactor();

            // Delete backup files after updating.
            Task.Run(Updater.CleanupUpdate);

            Toolkit.Init(new ToolkitOptions
            {
                Backend = PlatformBackend.PreferNative
            });

            Version = Assembly.GetEntryAssembly().GetCustomAttribute <AssemblyInformationalVersionAttribute>().InformationalVersion;

            Console.Title = $"Ryujinx Console {Version}";

            string systemPath = Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.Machine);

            Environment.SetEnvironmentVariable("Path", $"{Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin")};{systemPath}");

            // Hook unhandled exception and process exit events.
            GLib.ExceptionManager.UnhandledException   += (GLib.UnhandledExceptionArgs e) => ProcessUnhandledException(e.ExceptionObject as Exception, e.IsTerminating);
            AppDomain.CurrentDomain.UnhandledException += (object sender, UnhandledExceptionEventArgs e) => ProcessUnhandledException(e.ExceptionObject as Exception, e.IsTerminating);
            AppDomain.CurrentDomain.ProcessExit        += (object sender, EventArgs e) => Exit();

            // Setup base data directory.
            AppDataManager.Initialize(baseDirPathArg);

            // Initialize the configuration.
            ConfigurationState.Initialize();

            // Initialize the logger system.
            LoggerModule.Initialize();

            // Initialize Discord integration.
            DiscordIntegrationModule.Initialize();

            string localConfigurationPath   = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config.json");
            string appDataConfigurationPath = Path.Combine(AppDataManager.BaseDirPath, "Config.json");

            // Now load the configuration as the other subsystems are now registered
            ConfigurationPath = File.Exists(localConfigurationPath)
                ? localConfigurationPath
                : File.Exists(appDataConfigurationPath)
                    ? appDataConfigurationPath
                    : null;

            if (ConfigurationPath == null)
            {
                // No configuration, we load the default values and save it to disk
                ConfigurationPath = appDataConfigurationPath;

                ConfigurationState.Instance.LoadDefault();
                ConfigurationState.Instance.ToFileFormat().SaveConfig(ConfigurationPath);
            }
            else
            {
                if (ConfigurationFileFormat.TryLoad(ConfigurationPath, out ConfigurationFileFormat configurationFileFormat))
                {
                    ConfigurationState.Instance.Load(configurationFileFormat, ConfigurationPath);
                }
                else
                {
                    ConfigurationState.Instance.LoadDefault();
                    Logger.Warning?.PrintMsg(LogClass.Application, $"Failed to load config! Loading the default config instead.\nFailed config location {ConfigurationPath}");
                }
            }

            if (startFullscreenArg)
            {
                ConfigurationState.Instance.Ui.StartFullscreen.Value = true;
            }

            // Logging system information.
            PrintSystemInfo();

            // Force dedicated GPU if we can.
            ForceDedicatedGpu.Nvidia();

            // Enable OGL multithreading on the driver, when available.
            DriverUtilities.ToggleOGLThreading(true);

            // Initialize Gtk.
            Application.Init();

            // Check if keys exists.
            bool hasSystemProdKeys = File.Exists(Path.Combine(AppDataManager.KeysDirPath, "prod.keys"));
            bool hasCommonProdKeys = AppDataManager.Mode == AppDataManager.LaunchMode.UserProfile && File.Exists(Path.Combine(AppDataManager.KeysDirPathUser, "prod.keys"));

            if (!hasSystemProdKeys && !hasCommonProdKeys)
            {
                UserErrorDialog.CreateUserErrorDialog(UserError.NoKeys);
            }

            // Show the main window UI.
            MainWindow mainWindow = new MainWindow();

            mainWindow.Show();

            if (launchPathArg != null)
            {
                mainWindow.LoadApplication(launchPathArg);
            }

            if (ConfigurationState.Instance.CheckUpdatesOnStart.Value && Updater.CanUpdate(false))
            {
                Updater.BeginParse(mainWindow, false).ContinueWith(task =>
                {
                    Logger.Error?.Print(LogClass.Application, $"Updater Error: {task.Exception}");
                }, TaskContinuationOptions.OnlyOnFaulted);
            }

            Application.Run();
        }
Ejemplo n.º 28
0
        private static void Initialize(string[] args)
        {
            // Parse Arguments.
            string launchPathArg      = null;
            string baseDirPathArg     = null;
            bool   startFullscreenArg = false;

            for (int i = 0; i < args.Length; ++i)
            {
                string arg = args[i];

                if (arg == "-r" || arg == "--root-data-dir")
                {
                    if (i + 1 >= args.Length)
                    {
                        Logger.Error?.Print(LogClass.Application, $"Invalid option '{arg}'");

                        continue;
                    }

                    baseDirPathArg = args[++i];
                }
                else if (arg == "-p" || arg == "--profile")
                {
                    if (i + 1 >= args.Length)
                    {
                        Logger.Error?.Print(LogClass.Application, $"Invalid option '{arg}'");

                        continue;
                    }

                    CommandLineProfile = args[++i];
                }
                else if (arg == "-f" || arg == "--fullscreen")
                {
                    startFullscreenArg = true;
                }
                else
                {
                    launchPathArg = arg;
                }
            }

            // Delete backup files after updating.
            Task.Run(Updater.CleanupUpdate);

            Console.Title = $"Ryujinx Console {Version}";

            // Hook unhandled exception and process exit events.
            AppDomain.CurrentDomain.UnhandledException += (object sender, UnhandledExceptionEventArgs e) => ProcessUnhandledException(e.ExceptionObject as Exception, e.IsTerminating);
            AppDomain.CurrentDomain.ProcessExit        += (object sender, EventArgs e) => Exit();

            // Setup base data directory.
            AppDataManager.Initialize(baseDirPathArg);

            // Initialize the configuration.
            ConfigurationState.Initialize();

            // Initialize the logger system.
            LoggerModule.Initialize();

            // Initialize Discord integration.
            DiscordIntegrationModule.Initialize();

            ReloadConfig();

            UseVulkan = PreviewerDetached ? ConfigurationState.Instance.Graphics.GraphicsBackend.Value == GraphicsBackend.Vulkan : false;

            if (UseVulkan)
            {
                if (VulkanRenderer.GetPhysicalDevices().Length == 0)
                {
                    UseVulkan = false;

                    ConfigurationState.Instance.Graphics.GraphicsBackend.Value = GraphicsBackend.OpenGl;

                    Logger.Warning?.PrintMsg(LogClass.Application, "A suitable Vulkan physical device is not available. Falling back to OpenGL");
                }
            }

            if (UseVulkan)
            {
                // With a custom gpu backend, avalonia doesn't enable dpi awareness, so the backend must handle it. This isn't so for the opengl backed,
                // as that uses avalonia's gpu backend and it's enabled there.
                ForceDpiAware.Windows();
            }

            WindowScaleFactor = ForceDpiAware.GetWindowScaleFactor();
            ActualScaleFactor = ForceDpiAware.GetActualScaleFactor() / BaseDpi;

            // Logging system information.
            PrintSystemInfo();

            // Enable OGL multithreading on the driver, when available.
            BackendThreading threadingMode = ConfigurationState.Instance.Graphics.BackendThreading;

            DriverUtilities.ToggleOGLThreading(threadingMode == BackendThreading.Off);

            // Check if keys exists.
            bool hasSystemProdKeys = File.Exists(Path.Combine(AppDataManager.KeysDirPath, "prod.keys"));

            if (!hasSystemProdKeys)
            {
                if (!(AppDataManager.Mode == AppDataManager.LaunchMode.UserProfile && File.Exists(Path.Combine(AppDataManager.KeysDirPathUser, "prod.keys"))))
                {
                    MainWindow.ShowKeyErrorOnLoad = true;
                }
            }

            if (launchPathArg != null)
            {
                MainWindow.DeferLoadApplication(launchPathArg, startFullscreenArg);
            }
        }
Ejemplo n.º 29
0
        static void Main(string[] args)
        {
            // Parse Arguments.
            string launchPathArg      = null;
            string baseDirPathArg     = null;
            bool   startFullscreenArg = false;

            for (int i = 0; i < args.Length; ++i)
            {
                string arg = args[i];

                if (arg == "-r" || arg == "--root-data-dir")
                {
                    if (i + 1 >= args.Length)
                    {
                        Logger.Error?.Print(LogClass.Application, $"Invalid option '{arg}'");

                        continue;
                    }

                    baseDirPathArg = args[++i];
                }
                else if (arg == "-f" || arg == "--fullscreen")
                {
                    startFullscreenArg = true;
                }
                else if (launchPathArg == null)
                {
                    launchPathArg = arg;
                }
            }

            // Delete backup files after updating.
            Task.Run(Updater.CleanupUpdate);

            Toolkit.Init(new ToolkitOptions
            {
                Backend = PlatformBackend.PreferNative
            });

            Version = Assembly.GetEntryAssembly().GetCustomAttribute <AssemblyInformationalVersionAttribute>().InformationalVersion;

            Console.Title = $"Ryujinx Console {Version}";

            string systemPath = Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.Machine);

            Environment.SetEnvironmentVariable("Path", $"{Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin")};{systemPath}");

            // Hook unhandled exception and process exit events.
            GLib.ExceptionManager.UnhandledException   += (GLib.UnhandledExceptionArgs e) => ProcessUnhandledException(e.ExceptionObject as Exception, e.IsTerminating);
            AppDomain.CurrentDomain.UnhandledException += (object sender, UnhandledExceptionEventArgs e) => ProcessUnhandledException(e.ExceptionObject as Exception, e.IsTerminating);
            AppDomain.CurrentDomain.ProcessExit        += (object sender, EventArgs e) => Exit();

            // Setup base data directory.
            AppDataManager.Initialize(baseDirPathArg);

            // Initialize the configuration.
            ConfigurationState.Initialize();

            // Initialize the logger system.
            LoggerModule.Initialize();

            // Initialize Discord integration.
            DiscordIntegrationModule.Initialize();

            string localConfigurationPath   = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config.json");
            string appDataConfigurationPath = Path.Combine(AppDataManager.BaseDirPath, "Config.json");

            // Now load the configuration as the other subsystems are now registered.
            if (File.Exists(localConfigurationPath))
            {
                ConfigurationPath = localConfigurationPath;

                ConfigurationFileFormat configurationFileFormat = ConfigurationFileFormat.Load(localConfigurationPath);

                ConfigurationState.Instance.Load(configurationFileFormat, ConfigurationPath);
            }
            else if (File.Exists(appDataConfigurationPath))
            {
                ConfigurationPath = appDataConfigurationPath;

                ConfigurationFileFormat configurationFileFormat = ConfigurationFileFormat.Load(appDataConfigurationPath);

                ConfigurationState.Instance.Load(configurationFileFormat, ConfigurationPath);
            }
            else
            {
                // No configuration, we load the default values and save it on disk.
                ConfigurationPath = appDataConfigurationPath;

                ConfigurationState.Instance.LoadDefault();
                ConfigurationState.Instance.ToFileFormat().SaveConfig(appDataConfigurationPath);
            }

            if (startFullscreenArg)
            {
                ConfigurationState.Instance.Ui.StartFullscreen.Value = true;
            }

            // Logging system informations.
            PrintSystemInfo();

            // Initialize Gtk.
            Application.Init();

            // Check if keys exists.
            bool hasGlobalProdKeys = File.Exists(Path.Combine(AppDataManager.KeysDirPath, "prod.keys"));
            bool hasAltProdKeys    = !AppDataManager.IsCustomBasePath && File.Exists(Path.Combine(AppDataManager.KeysDirPathAlt, "prod.keys"));

            if (!hasGlobalProdKeys && !hasAltProdKeys)
            {
                UserErrorDialog.CreateUserErrorDialog(UserError.NoKeys);
            }

            // Force dedicated GPU if we can.
            ForceDedicatedGpu.Nvidia();

            // Show the main window UI.
            MainWindow mainWindow = new MainWindow();

            mainWindow.Show();

            if (launchPathArg != null)
            {
                mainWindow.LoadApplication(launchPathArg);
            }

            if (ConfigurationState.Instance.CheckUpdatesOnStart.Value && Updater.CanUpdate(false))
            {
                _ = Updater.BeginParse(mainWindow, false);
            }

            Application.Run();
        }
Ejemplo n.º 30
0
        private static void Initialize(string[] args)
        {
            // Parse Arguments.
            string launchPathArg      = null;
            string baseDirPathArg     = null;
            bool   startFullscreenArg = false;

            for (int i = 0; i < args.Length; ++i)
            {
                string arg = args[i];

                if (arg == "-r" || arg == "--root-data-dir")
                {
                    if (i + 1 >= args.Length)
                    {
                        Logger.Error?.Print(LogClass.Application, $"Invalid option '{arg}'");

                        continue;
                    }

                    baseDirPathArg = args[++i];
                }
                else if (arg == "-p" || arg == "--profile")
                {
                    if (i + 1 >= args.Length)
                    {
                        Logger.Error?.Print(LogClass.Application, $"Invalid option '{arg}'");

                        continue;
                    }

                    CommandLineProfile = args[++i];
                }
                else if (arg == "-f" || arg == "--fullscreen")
                {
                    startFullscreenArg = true;
                }
                else
                {
                    launchPathArg = arg;
                }
            }

            // Make process DPI aware for proper window sizing on high-res screens.
            WindowScaleFactor = ForceDpiAware.GetWindowScaleFactor();

            // Delete backup files after updating.
            Task.Run(Updater.CleanupUpdate);

            Console.Title = $"Ryujinx Console {Version}";

            // Hook unhandled exception and process exit events.
            AppDomain.CurrentDomain.UnhandledException += (object sender, UnhandledExceptionEventArgs e) => ProcessUnhandledException(e.ExceptionObject as Exception, e.IsTerminating);
            AppDomain.CurrentDomain.ProcessExit        += (object sender, EventArgs e) => Exit();

            // Setup base data directory.
            AppDataManager.Initialize(baseDirPathArg);

            // Initialize the configuration.
            ConfigurationState.Initialize();

            // Initialize the logger system.
            LoggerModule.Initialize();

            // Initialize Discord integration.
            DiscordIntegrationModule.Initialize();

            ReloadConfig();

            // Logging system information.
            PrintSystemInfo();

            // Enable OGL multithreading on the driver, when available.
            BackendThreading threadingMode = ConfigurationState.Instance.Graphics.BackendThreading;

            DriverUtilities.ToggleOGLThreading(threadingMode == BackendThreading.Off);

            // Check if keys exists.
            bool hasSystemProdKeys = File.Exists(Path.Combine(AppDataManager.KeysDirPath, "prod.keys"));

            if (!hasSystemProdKeys)
            {
                if (!(AppDataManager.Mode == AppDataManager.LaunchMode.UserProfile && File.Exists(Path.Combine(AppDataManager.KeysDirPathUser, "prod.keys"))))
                {
                    MainWindow.ShowKeyErrorOnLoad = true;
                }
            }

            if (launchPathArg != null)
            {
                MainWindow.DeferLoadApplication(launchPathArg, startFullscreenArg);
            }
        }