Example #1
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="SwitchDefaultAttribute"></param>
 /// <param name="Method"></param>
 private void BindDefaultMethod(CommandDefaultAttribute SwitchDefaultAttribute, MethodInfo Method)
 {
     Getopt.AddDefaultRule(() =>
     {
         Method.Invoke(this, new object[] { });
     });
 }
Example #2
0
		public void AddRule3Test()
		{
			var Values = new List<int>();
			var Getopt = new Getopt(new string[] { "-i=50", "-i=25" });
			Getopt.AddRule("-i", (int Value) =>
			{
				Values.Add(Value);
			});
			Getopt.Process();
			Assert.AreEqual("50,25", Values.ToStringArray());
		}
Example #3
0
		public void AddRule4Test()
		{
			int ExecutedCount = 0;
			var Getopt = new Getopt(new string[] { "-a", "-a" });
			Getopt.AddRule("-a", () =>
			{
				ExecutedCount++;
			});
			Getopt.Process();
			Assert.AreEqual(2, ExecutedCount);
		}
Example #4
0
		public void AddRuleTest()
		{
			bool BooleanValue = false;
			int IntegerValue = 0;
			var Getopt = new Getopt(new string[] { "-b", "-i", "50" });
			Getopt.AddRule("-b", ref BooleanValue);
			Getopt.AddRule("-i", ref IntegerValue);
			Getopt.Process();

			Assert.AreEqual(true, BooleanValue);
			Assert.AreEqual(50, IntegerValue);
		}
        /// <summary>
        ///
        /// </summary>
        /// <param name="commandEntry"></param>
        private void BindField(CommandEntry commandEntry)
        {
            var field = commandEntry.FieldInfo;

            Getopt.AddRule(commandEntry.Aliases, () =>
            {
                if (field.FieldType == typeof(bool))
                {
                    field.SetValue(this, true);
                }
                else
                {
                    throw (new NotImplementedException("Not supported field type " + field.FieldType));
                }
            });
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="commandEntry"></param>
        private void BindMethod(CommandEntry commandEntry)
        {
            var method = commandEntry.MethodInfo;

            Getopt.AddRule(commandEntry.Aliases, () =>
            {
                var parameters     = method.GetParameters();
                var parametersData = new List <object>();

                foreach (var parameter in parameters)
                {
                    if (Getopt.HasMore)
                    {
                        var parameterData = Getopt.DequeueNext();
                        if (parameter.ParameterType == typeof(string))
                        {
                            parametersData.Add(parameterData);
                        }
                        else if (parameter.ParameterType == typeof(int))
                        {
                            parametersData.Add(int.Parse(parameterData));
                        }
                        else
                        {
                            throw new NotImplementedException(
                                "Not supported parameter type " + parameter.ParameterType);
                        }
                    }
                    else
                    {
                        parametersData.Add(null);
                    }
                }

                method.Invoke(this, parametersData.ToArray());
            });
        }
Example #7
0
		public void AddRule2Test()
		{
			bool BooleanValue = false;
			int IntegerValue = 0;
			string StringValue = "";
			var Getopt = new Getopt(new string[] { "-b", "-i", "50", "-s", "hello_world" });
			Getopt.AddRule("-b", (bool _Value) =>
			{
				BooleanValue = _Value;
			});
			Getopt.AddRule("-i", (int _Value) =>
			{
				IntegerValue = _Value;
			});
			Getopt.AddRule("-s", (string _Value) =>
			{
				StringValue = _Value;
			});
			Getopt.Process();

			Assert.AreEqual(true, BooleanValue);
			Assert.AreEqual(50, IntegerValue);
			Assert.AreEqual("hello_world", StringValue);
		}
Example #8
0
        static void Main(string[] Arguments)
        {
            // Add the event handler for handling UI thread exceptions to the event.
            Application.ThreadException += new ThreadExceptionEventHandler(Form1_UIThreadException);

            // Set the unhandled exception mode to force all Windows Forms errors to go through
            // our handler.
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

            // Add the event handler for handling non-UI thread exceptions to the event.
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            /*
            IntPtr playback_handle = IntPtr.Zero;
            IntPtr hw_params = IntPtr.Zero;
            Alsa.snd_config_t config;
            int rate = 44100;
            Console.WriteLine(Alsa.snd_pcm_open(&playback_handle, "default", Alsa.snd_pcm_stream_t.SND_PCM_LB_OPEN_PLAYBACK, 0));
            Console.WriteLine(Alsa.snd_pcm_hw_params_malloc(&hw_params));
            Console.WriteLine(Alsa.snd_pcm_hw_params_any(playback_handle, hw_params));

            Console.WriteLine(Alsa.snd_pcm_hw_params_set_access(playback_handle, hw_params, Alsa.snd_pcm_access.SND_PCM_ACCESS_RW_INTERLEAVED));
            Console.WriteLine(Alsa.snd_pcm_hw_params_set_format(playback_handle, hw_params, Alsa.snd_pcm_format.SND_PCM_FORMAT_S16_LE));
            Console.WriteLine(Alsa.snd_pcm_hw_params_set_rate_near(playback_handle, hw_params, &rate, null));
            Console.WriteLine(Alsa.snd_pcm_hw_params_set_channels (playback_handle, hw_params, 2));
            Console.WriteLine(Alsa.snd_pcm_hw_params(playback_handle, hw_params));
            Console.WriteLine(Alsa.snd_pcm_hw_params_free(hw_params));

            var Data = new byte[16 * 1024];
            for (int n = 0; n < Data.Length; n++)
            {
                Data[n] = (byte)n;
            }
            fixed (byte* DataPtr = Data)
            {
                Alsa.snd_pcm_writei(playback_handle, DataPtr, Data.Length / 4);
            }

            Thread.Sleep(128);

            //Console.WriteLine(Alsa.snd_pcm_prepare(playback_handle));
            //Console.WriteLine(Alsa.snd_pcm_open_preferred(out AlsaHandle, null, null, (int)Alsa.OpenMode.SND_PCM_LB_OPEN_PLAYBACK));
            //Console.WriteLine(Alsa.snd_pcm_close(AlsaHandle));
            Environment.Exit(0); return;
            */

            Logger.OnGlobalLog += (LogName, Level, Text, StackFrame) =>
            {
                if (Level >= Logger.Level.Info)
                {
                    var Method = StackFrame.GetMethod();
                    Console.WriteLine("{0} : {1} : {2}.{3} : {4}", LogName, Level, Method.DeclaringType.Name, Method.Name, Text);
                }
            };

            Logger.Info("Running ... plat:{0} ... int*:{1}", Environment.Is64BitProcess ? "x64" : "x86", sizeof(int*));
            #if false
            Console.WriteLine(CSPspEmu.Resources.Translations.GetString("extra", "UnknownGame"));
            Console.ReadKey(); Environment.Exit(0);
            #endif

            #if RUN_TESTS
            TestsAutoProgram.Main(Arguments.Skip(0).ToArray());
            Environment.Exit(0);
            #endif
            //AppDomain.UnHandledException
            /*
            AppDomain.CurrentDomain.UnhandledException += (sender, e) =>
            {
                try
                {
                    Console.Error.WriteLine(e.ExceptionObject);
                }
                catch
                {
                }
                Console.ReadKey();
                Environment.Exit(-1);
            };
            */

            //Application.EnableVisualStyles(); Application.Run(new GameListForm()); Application.Exit();

            string FileToLoad = null;

            var Getopt = new Getopt(Arguments);
            {
                Getopt.AddRule(new[] { "/help", "/?", "-h", "--help", "-?" }, () =>
                {
                    Console.WriteLine("Soywiz's Psp Emulator - {0} - r{1} - {2}", PspGlobalConfiguration.CurrentVersion, PspGlobalConfiguration.CurrentVersionNumeric, PspGlobalConfiguration.GitRevision);
                    Console.WriteLine("");
                    Console.WriteLine(" Switches:");
                    Console.WriteLine("   /version             - Outputs the program version");
                    Console.WriteLine("   /version2            - Outputs the program numeric version");
                    Console.WriteLine("   /decrypt <EBOOT.BIN> - Decrypts an EBOOT.BIN");
                    Console.WriteLine("   /gitrevision         - Outputs the git revision");
                    Console.WriteLine("   /installat3          - Installs the WavDest filter. Requires be launched with administrative rights.");
                    Console.WriteLine("   /associate           - Associates extensions with the program. Requires be launched with administrative rights.");
                    Console.WriteLine("   /tests               - Run integration tests.");
                    Console.WriteLine("");
                    Console.WriteLine(" Examples:");
                    Console.WriteLine("   cspspemu.exe <path_to_psp_executable>");
                    Console.WriteLine("");
                    Environment.Exit(0);
                });
                Getopt.AddRule("/version", () =>
                {
                    Console.Write("{0}", PspGlobalConfiguration.CurrentVersion);
                    Environment.Exit(0);
                });
                Getopt.AddRule("/version2", () =>
                {
                    Console.Write("{0}", PspGlobalConfiguration.CurrentVersionNumeric);
                    Environment.Exit(0);
                });
                Getopt.AddRule("/decrypt", (string EncryptedFile) =>
                {
                    try
                    {
                        using (var EncryptedStream = File.OpenRead(EncryptedFile))
                        {
                            /*
                            var Format = new FormatDetector().DetectSubType(EncryptedStream);

                            switch (Format)
                            {
                                case FormatDetector.SubType.Cso:
                                case FormatDetector.SubType.Dax:
                                case FormatDetector.SubType.Iso:

                                    break;
                            }
                            */

                            var DecryptedFile = String.Format("{0}.decrypted", EncryptedFile);
                            Console.Write("'{0}' -> '{1}'...", EncryptedFile, DecryptedFile);

                            var EncryptedData = EncryptedStream.ReadAll();
                            var DecryptedData = new EncryptedPrx().Decrypt(EncryptedData);
                            File.WriteAllBytes(DecryptedFile, DecryptedData);
                            Console.WriteLine("Ok");
                            Environment.Exit(0);
                        }
                    }
                    catch (Exception Exception)
                    {
                        Console.Error.WriteLine(Exception);
                        Environment.Exit(-1);
                    }
                });
                Getopt.AddRule("/gitrevision", () =>
                {
                    Console.Write("{0}", PspGlobalConfiguration.GitRevision);
                    Environment.Exit(0);
                });
                Getopt.AddRule("/installat3", () =>
                {
                    var OutFile = Environment.SystemDirectory + @"\WavDest.dll";
                    File.WriteAllBytes(OutFile, Assembly.GetEntryAssembly().GetManifestResourceStream("CSPspEmu.WavDest.dll").ReadAll());
                    Process.Start(new ProcessStartInfo("regsvr32", String.Format(@"/s ""{0}"" ", OutFile))).WaitForExit();
                    Environment.Exit(0);
                });
                Getopt.AddRule("/associate", () =>
                {
                    try
                    {
                        Registry.ClassesRoot.CreateSubKey(".elf").SetValue(null, "cspspemu.executable");
                        Registry.ClassesRoot.CreateSubKey(".pbp").SetValue(null, "cspspemu.executable");
                        Registry.ClassesRoot.CreateSubKey(".cso").SetValue(null, "cspspemu.executable");
                        Registry.ClassesRoot.CreateSubKey(".prx").SetValue(null, "cspspemu.executable");
                        Registry.ClassesRoot.CreateSubKey(".dax").SetValue(null, "cspspemu.executable");

                        var Reg = Registry.ClassesRoot.CreateSubKey("cspspemu.executable");
                        Reg.SetValue(null, "PSP executable file (.elf, .pbp, .cso, .prx, .dax)");
                        Reg.SetValue("DefaultIcon", @"""" + ApplicationPaths.ExecutablePath + @""",0");
                        Reg.CreateSubKey("shell").CreateSubKey("open").CreateSubKey("command").SetValue(null, @"""" + ApplicationPaths.ExecutablePath + @""" ""%1""");

                        Environment.Exit(0);
                    }
                    catch (Exception Exception)
                    {
                        Console.Error.WriteLine(Exception);
                        Environment.Exit(-1);
                    }
                });
                Getopt.AddRule("/tests", () =>
                {
                    TestsAutoProgram.Main(Arguments.Skip(1).ToArray());
                    Environment.Exit(0);
                });
                Getopt.AddRule((Name) =>
                {
                    FileToLoad = Name;
                });
            }
            try
            {
                Getopt.Process();
            }
            catch (Exception Exception)
            {
                Console.Error.WriteLine(Exception);
                Environment.Exit(-1);
            }
            //new PspAudioOpenalImpl().__TestAudio();
            //new PspAudioWaveOutImpl().__TestAudio();
            //return;

            /*
            var CsoName = "../../../TestInput/test.cso";
            var Cso = new Cso(File.OpenRead(CsoName));
            var Iso = new IsoFile();
            Console.WriteLine("[1]");
            Iso.SetStream(new CsoProxyStream(Cso), CsoName);
            Console.WriteLine("[2]");
            foreach (var Node in Iso.Root.Descendency())
            {
                Console.WriteLine(Node);
            }
            Console.ReadKey();
            return;
            */

            #if !RELEASE
            try
            {
                Console.OutputEncoding = Encoding.UTF8;
                Console.SetWindowSize(160, 60);
                Console.SetBufferSize(160, 2000);
            }
            catch
            {
            }
            #endif
            var PspEmulator = new PspEmulator();
            //PspEmulator.UseFastMemory = true;
            var CodeBase = Assembly.GetExecutingAssembly().Location;
            var Base = Path.GetDirectoryName(CodeBase) + @"\" + Path.GetFileNameWithoutExtension(CodeBase);
            foreach (var TryExtension in new[] { "iso", "cso", "elf", "pbp" })
            {
                var TryIsoFile = Base + "." + TryExtension;

                //Console.WriteLine(TryIsoFile);
                //Console.ReadKey();

                if (File.Exists(TryIsoFile))
                {
                    Platform.HideConsole();

                    PspEmulator.StartAndLoad(TryIsoFile, TraceSyscalls: false, ShowMenus: false);
                    return;
                }
            }

            if (FileToLoad != null)
            {
                PspEmulator.StartAndLoad(FileToLoad, TraceSyscalls: false);
            }
            else
            {
                //StartWithoutArguments(PspEmulator);
                PspEmulator.Start();
            }
        }
Example #9
0
        static void Main(string[] args)
        {
            try
            {
                string Revision = "<Unknown>";
                string Datetime = "<Unknown>";
                try
                {
                    Datetime = Assembly.GetExecutingAssembly().GetManifestResourceStream("SimpleMassiveRealtimeRankingServer.DATETIME").ReadAllContentsAsString().Trim();
                }
                catch
                {
                }

                try
                {
                    Revision = Assembly.GetExecutingAssembly().GetManifestResourceStream("SimpleMassiveRealtimeRankingServer.ORIG_HEAD").ReadAllContentsAsString().Trim();
                }
                catch
                {
                }

                //FileVersionInfo myFileVersionInfo = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().GetName().ToString());
                //Console.WriteLine(myFileVersionInfo);
                //Console.WriteLine(Datetime);

                //Console.WriteLine(Version.Build);

                string BindIp = "0.0.0.0";
                int BindPort = 9777;
                int NumberOfThreads = Environment.ProcessorCount;

                var Getopt = new Getopt(args);
                Getopt.AddRule("-v", () =>
                {
                    Console.WriteLine(new ServerManager().Version);
                    Environment.Exit(0);
                });
                Getopt.AddRule("-i", (string Value) => { BindIp = Value; });
                Getopt.AddRule("-p", (int Value) => { BindPort = Value; });
                Getopt.AddRule("-t", (int Value) => { NumberOfThreads = Value; });
                Getopt.AddRule(new string[] { "-h", "-?", "--help" }, () =>
                {
                    Console.WriteLine("Simple Massive Realtime Ranking Server - {0} - Carlos Ballesteros Velasco - 2011-2011", new ServerManager().Version);
            #if NET_4_5
                    Console.WriteLine("Compiled with .NET 4.5 Async support.");
            #else
                    Console.WriteLine("Compiled with old .NET 4.0 (no async support).");
            #endif
                    Console.WriteLine("Compiled git Version: {0}", Revision);
                    Console.WriteLine("Build time: {0}", Datetime);
                    Console.WriteLine("Project website: https://github.com/soywiz/smrr-server");
                    Console.WriteLine("");
                    Console.WriteLine("Parameters:");
                    Console.WriteLine("    -i    Sets the binding ip. Example: -i=192.168.1.1");
                    Console.WriteLine("    -p    Sets the binding port. Example: -p=7777");
                    Console.WriteLine("    -t    Sets the number of partition threads. Example: -t=8");
                    Console.WriteLine("");
                    Console.WriteLine("    -v    Shows the version of the server");
                    Console.WriteLine("    -h    Shows this help");
                    Console.WriteLine("");
                    Console.WriteLine("Examples:");
                    Console.WriteLine("    SimpleMassiveRealtimeRankingServer -i=0.0.0.0 -p=7777");
                    Environment.Exit(-1);
                });
                Getopt.Process();

                var ServerHandler = new ServerHandler(BindIp, BindPort, NumberOfThreads);
            #if NET_4_5
                ServerHandler.AcceptClientLoopAsync().Wait();
            #else
                ServerHandler.AcceptClientLoop();
            #endif
            }
            catch (Exception Exception)
            {
                Console.Error.WriteLine(Exception);
                Environment.Exit(-1);
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="args"></param>
        public void Run(string[] args)
        {
            Getopt = new Getopt(args);

            CommandEntries = new List <CommandEntry>();

            foreach (var member in GetType()
                     .GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
            {
                var descriptionAttribute = member.GetSingleAttribute <DescriptionAttribute>();
                var valuesAttribute      = member.GetSingleAttribute <ValuesAttribute>();

                var commandDefaultAttribute = member.GetSingleAttribute <CommandDefaultAttribute>();
                if (commandDefaultAttribute != null)
                {
                    if (member is MethodInfo)
                    {
                        BindDefaultMethod(commandDefaultAttribute, member as MethodInfo);
                    }
                }

                var commandAttribute = member.GetSingleAttribute <CommandAttribute>();
                if (commandAttribute == null)
                {
                    continue;
                }

                var commandEntry = new CommandEntry()
                {
                    Aliases     = commandAttribute.Aliases,
                    MemberInfo  = member,
                    Examples    = member.GetAttribute <ExampleAttribute>().Select(item => item.Example).ToArray(),
                    Description = (descriptionAttribute != null) ? descriptionAttribute.Description : "",
                    Values      = (valuesAttribute != null) ? valuesAttribute.Values : new object[0],
                };

                CommandEntries.Add(commandEntry);

                if (member is MethodInfo)
                {
                    BindMethod(commandEntry);
                }
                else if (member is FieldInfo)
                {
                    BindField(commandEntry);
                }
                else
                {
                    throw(new NotImplementedException("Don't know how to handle type " + member.GetType()));
                }
            }

            try
            {
                Getopt.Process();
            }
            catch (TargetInvocationException targetInvocationException)
            {
                Console.Error.WriteLine(targetInvocationException.InnerException);
                Environment.Exit(-1);
            }
            catch (Exception exception)
            {
                //Console.Error.WriteLine(Exception.Message);
                Console.Error.WriteLine(exception);
                Environment.Exit(-2);
            }

            if (Debugger.IsAttached)
            {
                Console.ReadKey();
            }
        }
Example #11
0
        static unsafe void Main(string[] Arguments)
        {
            //Console.WriteLine(GL.GetConstantString(GL.GL_TEXTURE_2D));
            //_MainData();
            //_MainData2();

            if (!IsNet45OrNewer())
            {
                MessageBox.Show(".NET 4.5 required", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                return;
            }

            // Add the event handler for handling UI thread exceptions to the event.
            Application.ThreadException += new ThreadExceptionEventHandler(Form1_UIThreadException);

            // Set the unhandled exception mode to force all Windows Forms errors to go through
            // our handler.
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

            // Add the event handler for handling non-UI thread exceptions to the event.
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            Logger.OnGlobalLog += (LogName, Level, Text, StackFrame) =>
            {
                if (Level >= Logger.Level.Info)
                {
                    var Method = StackFrame.GetMethod();
                    Console.WriteLine("{0} : {1} : {2}.{3} : {4}", LogName, Level, (Method.DeclaringType != null) ? Method.DeclaringType.Name : null, Method.Name, Text);
                }
            };

            #if false
            Console.WriteLine(CSPspEmu.Resources.Translations.GetString("extra", "UnknownGame"));
            Console.ReadKey(); Environment.Exit(0);
            #endif

            #if RUN_TESTS
            RunTests(Arguments);
            #endif

            string FileToLoad = null;
            bool RunTestsViewOut = false;
            int RunTestsTimeout = 60;

            var Getopt = new Getopt(Arguments);
            {
                Getopt.AddRule(new[] { "/help", "/?", "-h", "--help", "-?" }, () =>
                {
                    Console.WriteLine("Soywiz's Psp Emulator - {0} - r{1} - {2}", PspGlobalConfiguration.CurrentVersion, PspGlobalConfiguration.CurrentVersionNumeric, PspGlobalConfiguration.GitRevision);
                    Console.WriteLine("");
                    Console.WriteLine(" Switches:");
                    Console.WriteLine("   /version                         - Outputs the program version");
                    Console.WriteLine("   /version2                        - Outputs the program numeric version");
                    Console.WriteLine("   /decrypt <EBOOT.BIN>             - Decrypts an EBOOT.BIN");
                    Console.WriteLine("   /gitrevision                     - Outputs the git revision");
                    Console.WriteLine("   /associate                       - Associates extensions with the program. Requires be launched with administrative rights.");
                    Console.WriteLine("   /viewout /timeout X /tests       - Run integration tests.");
                    Console.WriteLine("   ");
                    Console.WriteLine("   /isolist <pathto.iso|cso|dax>    - Lists the content of an iso.");
                    Console.WriteLine("   /isoextract <in.iso> <outfolder> - Extracts the content of an iso.");
                    Console.WriteLine("   /isoconvert <in.xxx> <out.yyy>   - Converts a iso/cso/dax file into other format.");
                    Console.WriteLine("");
                    Console.WriteLine(" Examples:");
                    Console.WriteLine("   cspspemu.exe <path_to_psp_executable>");
                    Console.WriteLine("");
                    Environment.Exit(0);
                });
                Getopt.AddRule("/version", () =>
                {
                    Console.Write("{0}", PspGlobalConfiguration.CurrentVersion);
                    Environment.Exit(0);
                });
                Getopt.AddRule("/version2", () =>
                {
                    Console.Write("{0}", PspGlobalConfiguration.CurrentVersionNumeric);
                    Environment.Exit(0);
                });
                Getopt.AddRule("/isoconvert", () =>
                {
                    var IsoInPath = Getopt.DequeueNext();
                    var IsoOutPath = Getopt.DequeueNext();

                    if (Path.GetExtension(IsoOutPath) != ".iso")
                    {
                        Console.WriteLine("Just support outputing .iso files");
                        Environment.Exit(-1);
                    }

                    var IsoInFile = IsoLoader.GetIso(IsoInPath);
                    var Stopwatch = new Stopwatch();
                    Stopwatch.Start();
                    Console.Write("{0} -> {1}...", IsoInPath, IsoOutPath);
                    IsoInFile.Stream.Slice().CopyToFile(IsoOutPath);
                    Console.WriteLine("Ok ({0})", Stopwatch.Elapsed);
                    Environment.Exit(0);
                });
                Getopt.AddRule("/isolist", () =>
                {
                    var IsoPath = Getopt.DequeueNext();
                    var IsoFile = IsoLoader.GetIso(IsoPath);
                    var IsoFileSystem = new HleIoDriverIso(IsoFile);
                    foreach (var FileName in IsoFileSystem.ListDirRecursive("/"))
                    {
                        var Stat = IsoFileSystem.GetStat(FileName);
                        Console.WriteLine("{0} : {1}", FileName, Stat.Size);
                    }
                    //Console.Write("{0}", PspGlobalConfiguration.CurrentVersionNumeric);
                    Environment.Exit(0);
                });
                Getopt.AddRule("/isoextract", () =>
                {
                    var IsoPath = Getopt.DequeueNext();
                    var OutputPath = Getopt.DequeueNext();
                    var IsoFile = IsoLoader.GetIso(IsoPath);
                    var IsoFileSystem = new HleIoDriverIso(IsoFile);
                    foreach (var FileName in IsoFileSystem.ListDirRecursive("/"))
                    {
                        var Stat = IsoFileSystem.GetStat(FileName);
                        var OutputFileName = OutputPath + "/" + FileName;
                        Console.Write("{0} : {1}...", FileName, Stat.Size);

                        if (!Stat.Attributes.HasFlag(Hle.Vfs.IOFileModes.Directory))
                        {
                            var ParentDirectory = Directory.GetParent(OutputFileName).FullName;
                            //Console.WriteLine(ParentDirectory);
                            try { Directory.CreateDirectory(ParentDirectory); }
                            catch
                            {
                            }
                            using (var InputStream = IsoFileSystem.OpenRead(FileName))
                            {
                                InputStream.CopyToFile(OutputFileName);
                            }
                        }
                        Console.WriteLine("Ok");
                    }
                    //Console.Write("{0}", PspGlobalConfiguration.CurrentVersionNumeric);
                    Environment.Exit(0);
                });
                Getopt.AddRule("/decrypt", (string EncryptedFile) =>
                {
                    try
                    {
                        using (var EncryptedStream = File.OpenRead(EncryptedFile))
                        {
                            var DecryptedFile = String.Format("{0}.decrypted", EncryptedFile);
                            Console.Write("'{0}' -> '{1}'...", EncryptedFile, DecryptedFile);

                            var EncryptedData = EncryptedStream.ReadAll();
                            var DecryptedData = new EncryptedPrx().Decrypt(EncryptedData);
                            File.WriteAllBytes(DecryptedFile, DecryptedData);
                            Console.WriteLine("Ok");
                            Environment.Exit(0);
                        }
                    }
                    catch (Exception Exception)
                    {
                        Console.Error.WriteLine(Exception);
                        Environment.Exit(-1);
                    }
                });
                Getopt.AddRule("/gitrevision", () =>
                {
                    Console.Write("{0}", PspGlobalConfiguration.GitRevision);
                    Environment.Exit(0);
                });
                Getopt.AddRule("/associate", () =>
                {
                    try
                    {
                        Registry.ClassesRoot.CreateSubKey(".pbp").SetValue(null, "cspspemu.executable");
                        Registry.ClassesRoot.CreateSubKey(".elf").SetValue(null, "cspspemu.executable");
                        Registry.ClassesRoot.CreateSubKey(".prx").SetValue(null, "cspspemu.executable");
                        Registry.ClassesRoot.CreateSubKey(".cso").SetValue(null, "cspspemu.executable");
                        Registry.ClassesRoot.CreateSubKey(".dax").SetValue(null, "cspspemu.executable");

                        var Reg = Registry.ClassesRoot.CreateSubKey("cspspemu.executable");
                        Reg.SetValue(null, "PSP executable file (.elf, .pbp, .cso, .prx, .dax)");
                        Reg.SetValue("DefaultIcon", @"""" + ApplicationPaths.ExecutablePath + @""",0");
                        Reg.CreateSubKey("shell").CreateSubKey("open").CreateSubKey("command").SetValue(null, @"""" + ApplicationPaths.ExecutablePath + @""" ""%1""");

                        Environment.Exit(0);
                    }
                    catch (Exception Exception)
                    {
                        Console.Error.WriteLine(Exception);
                        Environment.Exit(-1);
                    }
                });
                Getopt.AddRule("/viewout", () =>
                {
                    RunTestsViewOut = true;
                });
                Getopt.AddRule("/timeout", (int seconds) =>
                {
                    RunTestsTimeout = seconds;
                });
                Getopt.AddRule("/tests", () =>
                {
                    RunTests(RunTestsViewOut, Getopt.DequeueAllNext(), RunTestsTimeout);
                });
                Getopt.AddRule((Name) =>
                {
                    FileToLoad = Name;
                });
            }
            try
            {
                Getopt.Process();
            }
            catch (Exception Exception)
            {
                Console.Error.WriteLine(Exception);
                Environment.Exit(-1);
            }

            Logger.Info("Running ... plat:{0} ... int*:{1}", Environment.Is64BitProcess ? "64bit" : "32bit", sizeof(int*));
            {
                var MonoRuntimeType = Type.GetType("Mono.Runtime");
                if (MonoRuntimeType != null)
                {
                    var GetDisplayNameMethod = MonoRuntimeType.GetMethod("GetDisplayName", BindingFlags.NonPublic | BindingFlags.Static);
                    if (GetDisplayNameMethod != null) Console.WriteLine("Mono: {0}", GetDisplayNameMethod.Invoke(null, null));
                }
            }
            Console.WriteLine("ImageRuntimeVersion: {0}", Assembly.GetExecutingAssembly().ImageRuntimeVersion);

            #if !RELEASE
            try
            {
                Console.OutputEncoding = Encoding.UTF8;
                Console.SetWindowSize(160, 60);
                Console.SetBufferSize(160, 2000);
            }
            catch
            {
            }
            #endif

            /*
            foreach (var NI in NetworkInterface.GetAllNetworkInterfaces())
            {
                if (NI.SupportsMulticast && NI.OperationalStatus == OperationalStatus.Up)
                {
                    var IPProperties = NI.GetIPProperties();
                    Console.WriteLine("[A]:{0}", NI.ToStringDefault());
                    foreach (var Item in IPProperties.DhcpServerAddresses)
                    {
                        Console.WriteLine("[B]:{0},{1}", Item.ToString(), Item.IsIPv6Multicast);
                    }
                    foreach (var Item in IPProperties.AnycastAddresses)
                    {
                        Console.WriteLine("[D]:{0}", Item.Address.ToString());
                    }
                    foreach (var Item in IPProperties.MulticastAddresses)
                    {
                        Console.WriteLine("[E]:{0}", Item.Address.ToString());
                    }
                    foreach (var Item in IPProperties.UnicastAddresses)
                    {
                        Console.WriteLine("[F]:{0}", Item.Address.ToString());
                    }
                    Console.WriteLine("[G]:{0}", NI.GetPhysicalAddress());
                }
                else
                {
                    Console.WriteLine("-");
                }
            }
            */

            using (var PspEmulator = new PspEmulator())
            {
                //PspEmulator.UseFastMemory = true;
                var CodeBase = Assembly.GetExecutingAssembly().Location;
                var Base = Path.GetDirectoryName(CodeBase) + @"\" + Path.GetFileNameWithoutExtension(CodeBase);
                foreach (var TryExtension in new[] { "iso", "cso", "elf", "pbp" })
                {
                    var TryIsoFile = Base + "." + TryExtension;

                    //Console.WriteLine(TryIsoFile);
                    //Console.ReadKey();

                    if (File.Exists(TryIsoFile))
                    {
                        Platform.HideConsole();

                        PspEmulator.StartAndLoad(TryIsoFile, TraceSyscalls: false, ShowMenus: false);
                        return;
                    }
                }

                if (FileToLoad != null)
                {
                    PspEmulator.StartAndLoad(FileToLoad, TraceSyscalls: false);
                }
                else
                {
                    //StartWithoutArguments(PspEmulator);
                    PspEmulator.Start();
                }
            }
        }
Example #12
0
        public void ProcessArgs(string[] args)
        {
            CaptureExceptions(() =>
            {
            #if false
                args = new[] { "-t=yaml" };
            #endif

                var FileNames = new List<string>();
                var CCompiler = new CCompiler();

                CCompiler.SetTarget("cil");

                if (args.Length == 0)
                {
                    ShowHelp();
                }

                var Getopt = new Getopt(args);
                {
                    Getopt.AddRule(new[] { "--help", "-h", "-?" }, () =>
                    {
                        ShowHelp();
                    });

                    Getopt.AddRule(new[] { "--target", "-t" }, (string Target) =>
                    {
                        CCompiler.SetTarget(Target);
                    });

                    Getopt.AddRule(new[] { "--version", "-v" }, () =>
                    {
                        ShowVersion();
                    });

                    Getopt.AddRule(new[] { "-c" }, () =>
                    {
                        CCompiler.CompileOnly = true;
                    });

                    Getopt.AddRule(new[] { "--preprocess", "-E" }, () =>
                    {
                        CCompiler.JustPreprocess = true;
                    });

                    Getopt.AddRule(new[] { "--include_path", "-I" }, (string Path) =>
                    {
                        CCompiler.AddIncludePath(Path);
                    });

                    Getopt.AddRule(new[] { "--show_macros" }, () =>
                    {
                        CCompiler.JustShowMacros = true;
                    });

                    Getopt.AddRule(new[] { "-run" }, (string[] Left) =>
                    {
                        CCompiler.ShouldRun = true;
                        CCompiler.RunParameters = Left;
                    });

                    Getopt.AddRule(new[] { "--show_targets" }, () =>
                    {
                        ShowTargets();
                    });

                    Getopt.AddRule("", (string Name) =>
                    {
                        FileNames.Add(Name);
                    });
                }
                Getopt.Process();

                if (FileNames.Count == 0)
                {
                    ShowHelp();
                }

                CCompiler.CompileFiles(FileNames.ToArray());
            });
        }
		/// <summary>
		/// 
		/// </summary>
		/// <param name="args"></param>
		public void Run(string[] args)
		{
			Getopt = new Getopt(args);

			CommandEntries = new List<CommandEntry>();

			foreach (var Member in this.GetType().GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
			{
				var DescriptionAttribute = Member.GetSingleAttribute<DescriptionAttribute>();
				var ValuesAttribute = Member.GetSingleAttribute<ValuesAttribute>();

				var CommandDefaultAttribute = Member.GetSingleAttribute<CommandDefaultAttribute>();
				if (CommandDefaultAttribute != null)
				{
					if (Member is MethodInfo)
					{
						BindDefaultMethod(CommandDefaultAttribute, Member as MethodInfo);
					}
				}

				var CommandAttribute = Member.GetSingleAttribute<CommandAttribute>();
				if (CommandAttribute != null)
				{
					var CommandEntry = new CommandEntry()
					{
						Aliases = CommandAttribute.Aliases,
						MemberInfo = Member,
						Examples = Member.GetAttribute<ExampleAttribute>().Select(Item => Item.Example).ToArray(),
						Description = (DescriptionAttribute != null) ? DescriptionAttribute.Description : "",
						Values = (ValuesAttribute != null) ? ValuesAttribute.Values : new object[0],
					};

					CommandEntries.Add(CommandEntry);

					if (Member is MethodInfo)
					{
						BindMethod(CommandEntry);
					}
					else if (Member is FieldInfo)
					{
						BindField(CommandEntry);
					}
					else
					{
						throw(new NotImplementedException("Don't know how to handle type " + Member.GetType()));
					}
				}
			}

			try
			{
				Getopt.Process();
			}
			catch (TargetInvocationException TargetInvocationException)
			{
				Console.Error.WriteLine(TargetInvocationException.InnerException);
				Environment.Exit(-1);
			}
			catch (Exception Exception)
			{
				//Console.Error.WriteLine(Exception.Message);
				Console.Error.WriteLine(Exception);
				Environment.Exit(-2);
			}

			if (Debugger.IsAttached)
			{
				Console.ReadKey();
			}
		}