Exemple #1
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);
        }
Exemple #2
0
        public static Dictionary <string, List <string> > ProcessArguments(string[] args, string optString)
        {
            if (args == null)
            {
                throw new ArgumentNullException("args");
            }
            if (optString.IsNullEmptyOrWhitespace())
            {
                throw new ArgumentNullException("optString");
            }

            _log.Debug("Processing arguments ...");
            var arguments = new Dictionary <string, List <string> >();
            var g         = new Getopt("CliHelper", args, optString);
            int c;

            while ((c = g.getopt()) != -1)
            {
                if (_log.IsDebugEnabled)
                {
                    _log.Debug(string.Format("Found argument {0} with value {1}.", ((char)c), g.Optarg));
                }

                List <string> list;
                var           argumentString = ((char)c).ToString(CultureInfo.InvariantCulture);
                if (!arguments.TryGetValue(argumentString, out list))
                {
                    list = new List <string>();
                    arguments.Add(argumentString, list);
                }
                list.Add(g.Optarg);
            }
            return(arguments);
        }
Exemple #3
0
        static void Main(string[] args)
        {
            var getopt = new Getopt(Assembly.GetExecutingAssembly().GetName().Name, args, "p:e:c:s:f:")
            {
                Opterr = false
            };

            string source      = null;
            string pattern     = null;
            string extension   = null;
            string charset     = null;
            string fromCharset = null;

            int option;

            while (-1 != (option = getopt.getopt()))
            {
                switch (option)
                {
                case 'e': extension = getopt.Optarg; break;

                case 's': source = getopt.Optarg; break;

                case 'c': charset = getopt.Optarg; break;

                case 'p': pattern = getopt.Optarg; break;

                case 'f': fromCharset = getopt.Optarg; break;

                default: PrintUsage(); return;
                }
            }

            if (extension == null || source == null || charset == null)
            {
                PrintUsage();
                return;
            }

            try
            {
                foreach (var file in Directory.GetFiles(source, pattern, SearchOption.AllDirectories))
                {
                    var output = String.Format("{0}.{1}", file, extension);
                    using (var reader = new StreamReader(file, Encoding.GetEncoding(fromCharset)))
                    {
                        using (var writer = new StreamWriter(output, false, Encoding.GetEncoding(charset)))
                        {
                            writer.Write(reader.ReadToEnd());
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine("Failure processing files: {0}", ex.Message);
                return;
            }
        }
Exemple #4
0
        static void Main(string[] args)
        {
            Getopt g           = new Getopt("MSNSend", args, "ap:tn:s:");
            string p           = "";
            bool   addFriend   = false;
            bool   test        = false;
            string testAccount = "";
            int    testNum     = 5;
            int    c;

            while ((c = g.getopt()) != -1)
            {
                switch (c)
                {
                case 'a':
                    addFriend = true;
                    break;

                case 'p':
                    p = g.Optarg;
                    break;

                case 't':
                    test = true;
                    break;

                case 's':
                    testAccount = g.Optarg;
                    break;

                case 'n':
                    testNum = int.Parse(g.Optarg);
                    break;
                }
            }
            if (test)
            {
                MSNTestSend app = new MSNTestSend(p);
                app.TestNum = testNum;
                if (testAccount.Length > 0)
                {
                    app.TestTo = testAccount;
                }
                app.run();
                return;
            }
            else if (addFriend)
            {
                MSNBulkAdd app = new MSNBulkAdd(p);
                app.run();
                return;
            }
            else
            {
                MSNBulk app = new MSNBulk(p);
                app.run();
            }
        }
Exemple #5
0
        public void AddRule4Test()
        {
            int ExecutedCount = 0;
            var Getopt        = new Getopt(new string[] { "-a", "-a" });

            Getopt.AddRule("-a", () => { ExecutedCount++; });
            Getopt.Process();
            Assert.Equal(2, ExecutedCount);
        }
Exemple #6
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.Equal("50,25", Values.ToStringArray());
        }
Exemple #7
0
        private static ProgramContext ParseArgs(string[] args)
        {
            int            c;
            Getopt         g  = new Getopt("ipnetwork", args, "inmcbfltud:Dhs:wWxC:o:S:");
            ProgramContext ac = new ProgramContext();

            while ((c = g.getopt()) != -1)
            {
                string optArg = g.Optarg;
                Program.Args[c].Run(ac, optArg);
            }

            List <string> ipnetworks = new List <string>();

            for (int i = g.Optind; i < args.Length; i++)
            {
                if (!string.IsNullOrEmpty(args[i]))
                {
                    ipnetworks.Add(args[i]);
                }
            }
            ac.NetworksString = ipnetworks.ToArray();
            Program.ParseIPNetworks(ac);

            if (ac.Networks.Length == 0)
            {
                Console.WriteLine("Provide at least one ipnetwork");
                ac.Action = ActionEnum.Usage;
            }

            if (ac.Action == ActionEnum.Supernet &&
                ipnetworks.Count < 2)
            {
                Console.WriteLine("Supernet action required at least two ipnetworks");
                ac.Action = ActionEnum.Usage;
            }

            if (ac.Action == ActionEnum.WideSupernet &&
                ipnetworks.Count < 2)
            {
                Console.WriteLine("WideSupernet action required at least two ipnetworks");
                ac.Action = ActionEnum.Usage;
            }

            if (Program.PrintNoValue(ac))
            {
                Program.PrintAll(ac);
            }

            if (g.Optind == 0)
            {
                Program.PrintAll(ac);
            }

            return(ac);
        }
Exemple #8
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);
        }
Exemple #9
0
        private static async Task <Boolean> DrawCardRankOption(CommandEventArgs e)
        {
            Getopt g = new Getopt("testprog", e.Args, "hs:c:");
            int    c;

            while ((c = g.getopt()) != -1)
            {
                switch (c)
                {
                case 'h':
                    await HelpInformation(e);

                    return(false);

                case 's':
                    if (g.Optarg.ToLower().Equals("top") || g.Optarg.ToLower().Equals("bottom"))
                    {
                        rank_type = g.Optarg;
                    }
                    else
                    {
                        await HelpInformation(e);

                        return(false);
                    }
                    break;

                case 'c':
                    int result;
                    if (int.TryParse(g.Optarg, out result))
                    {
                        DrawCount = result;
                    }
                    else
                    {
                        await HelpInformation(e);

                        return(false);
                    }
                    break;

                default:
                    await HelpInformation(e);

                    return(false);
                }
            }
            return(true);
        }
Exemple #10
0
        //-----------------------------------------------------------------------------------------
        private static void _ParseOptions(ref string[] args)
        {
            int    c;
            Getopt g = new Getopt(System.AppDomain.CurrentDomain.FriendlyName, args, "b:");

            while ((c = g.getopt()) != -1)
            {
                switch (c)
                {
                case 'b':
                    _basePath = g.Optarg;
                    break;

                default:
                    Console.WriteLine("getopt() returned unknown option '" + c + "'");
                    break;
                }
            }
        }
Exemple #11
0
        static void Main(string[] args)
        {
            var getopt = new Getopt(Assembly.GetExecutingAssembly().GetName().Name, args, "f:r:s:tv")
            {
                Opterr = false
            };

            string funcname      = null;
            string resourcesPath = null;
            string filesPath     = null;
            bool   topOnly       = false;
            bool   verbose       = false;

            int option;

            while (-1 != (option = getopt.getopt()))
            {
                switch (option)
                {
                case 'f': funcname = getopt.Optarg; break;

                case 'r': resourcesPath = getopt.Optarg; break;

                case 's': filesPath = getopt.Optarg; break;

                case 't': topOnly = true; break;

                case 'v': verbose = true; break;

                default: PrintUsage(); return;
                }
            }

            if (resourcesPath == null || filesPath == null)
            {
                PrintUsage();
                return;
            }

            var replacer = new Replacer(filesPath, resourcesPath, funcname, topOnly, verbose);

            replacer.Run();
        }
Exemple #12
0
        static void ParseOptions(ref string[] args)
        {
            Getopt g = new Getopt(System.AppDomain.CurrentDomain.FriendlyName, args, "b:");

            int c;

            while ((c = g.getopt()) != -1)
            {
                switch (c)
                {
                case 'b':
                    Program.BasePath = g.Optarg;
                    break;

                default:
                    Console.WriteLine("getopt() returned " + c);
                    break;
                }
            }
        }
Exemple #13
0
        static void Main(string[] args)
        {
            bool   rescan   = false;
            string file     = null;
            string url      = null;
            string progname = Path.GetFileName(Assembly.GetExecutingAssembly().CodeBase);

            Getopt opt = new Getopt(progname, args, "f:u:r");
            int    c;

            while ((c = opt.getopt()) != -1)
            {
                switch (c)
                {
                case 'f':
                    file = opt.Optarg;
                    break;

                case 'u':
                    url = opt.Optarg;
                    break;

                case 'r':
                    rescan = true;
                    break;

                default:
                    return;
                }
            }

            if (file != null)
            {
                FileScan(file, rescan);
            }
            if (url != null)
            {
                UrlScan(url);
            }
        }
Exemple #14
0
        static void processOpts(string[] args)
        {
            var longOpts = new LongOpt[] {
                new LongOpt("quorum", Argument.Required, null, 'k'),
                new LongOpt("count", Argument.Required, null, 'n'),
                new LongOpt("kid", Argument.Required, null, 'i'),
                new LongOpt("size", Argument.Required, null, 's'),
                new LongOpt("output", Argument.Required, null, 'o'),
                new LongOpt("test", Argument.No, null, 't'),
                new LongOpt("tenant", Argument.Required, null, 'e'),
                new LongOpt("appid", Argument.Required, null, 'a'),
                new LongOpt("appsecret", Argument.Required, null, 'z'),
                new LongOpt("redirecturl", Argument.Required, null, 'u'),
                new LongOpt("resource", Argument.Required, null, 'r'),
                new LongOpt("vaulturl", Argument.Required, null, 'v'),
                new LongOpt("skipshareverify", Argument.No, null, 'x'),
                new LongOpt("help", Argument.No, null, 'h'),
                new LongOpt("command", Argument.Required, null, 'c'),
                new LongOpt("backup", Argument.Required, null, 'b')
            };
            var opts = new Getopt("KeyGeneratorCli", args, "k:n:i:s:o:te:a:u:r:v:xz:hc:b:", longOpts);

            var c = 0;

            while ((c = opts.getopt()) != -1)
            {
                switch (c)
                {
                case 'k':
                    quorum = Int32.Parse(opts.Optarg); break;

                case 'n':
                    shareCount = Int32.Parse(opts.Optarg); break;

                case 's':
                    keySize = Int32.Parse(opts.Optarg); break;

                case 'i':
                    kid = opts.Optarg; break;

                case 'o':
                    output = opts.Optarg; break;

                case 't':
                    testModeFlag = true;
                    testMode     = "<<!! TEST MODE !! - no permanent changes will be performed>>";
                    break;

                case 'e':
                    tenant = opts.Optarg; break;

                case 'a':
                    appId = opts.Optarg; break;

                case 'z':
                    appSecret = opts.Optarg; break;

                case 'u':
                    redirectUrl = opts.Optarg; break;

                case 'r':
                    resourceId = opts.Optarg; break;

                case 'v':
                    vaultUrl = opts.Optarg; break;

                case 'x':
                    skipshareverify = true; break;

                case 'c':
                    command = opts.Optarg; break;

                case 'b':
                    backupToRecover = opts.Optarg; break;

                case 'h':
                    displayHelp(); break;

                case '?':
                default:
                    //Console.WriteLine("Unkonwn option")
                    break;
                }
                //Console.WriteLine(String.Format("c: {0}, arg: {1}, ind {2}",(char) c, opts.Optarg, opts.Optind));
            }

            if (Array.Find(COMMANDS, validCommand => validCommand.Equals(command)) == null)
            {
                Console.WriteLine($"Bad command {command}. Allowed commands: [{String.Join(",",COMMANDS)}]");
                Environment.Exit(1);
            }

            if (quorum == -1 || shareCount == -1)
            {
                Console.WriteLine("both -k (--quorum) and -n (--count)  must bespecified");
                Environment.Exit(1);
            }

            if (quorum > shareCount)
            {
                Console.WriteLine("k must be less than or equal to n (k<=n)");
                Environment.Exit(1);
            }

            if (kid == null)
            {
                Console.WriteLine("key identifier must be provided as -i (--kid) option");
                Environment.Exit(1);
            }

            if (output == null)
            {
                output = kid + ".backup";
            }

            if (backupToRecover == null)
            {
                backupToRecover = kid + ".backup";
            }
        }
Exemple #15
0
        static void Main(string[] args)
        {
            LongOpt[] opts = new[] {
                new LongOpt("help", Argument.No, null, 'h'),
                new LongOpt("compress", Argument.Required, null, 'c'),
                new LongOpt("decompress", Argument.Required, null, 'd'),
                new LongOpt("recompress", Argument.Required, null, 'r'),
                new LongOpt("same-filename", Argument.No, null, 's'),
                new LongOpt("little-endian", Argument.No, null, 'l'),
                new LongOpt("no-size", Argument.No, null, 'n')
            };
            Getopt          getopt       = new Getopt("KensSharp", args, Getopt.digest(opts), opts);
            Mode?           mode         = null;
            CompressionType?type         = null;
            Endianness      endian       = Endianness.BigEndian;
            bool            size         = true;
            bool            samefilename = false;
            int             opt          = getopt.getopt();

            while (opt != -1)
            {
                switch (opt)
                {
                case 'h':
                    ShowHelp();
                    return;

                case 'c':
                    mode = Mode.Compress;
                    type = (CompressionType)Enum.Parse(typeof(CompressionType), getopt.Optarg, true);
                    break;

                case 'd':
                    mode = Mode.Decompress;
                    type = (CompressionType)Enum.Parse(typeof(CompressionType), getopt.Optarg, true);
                    break;

                case 'r':
                    mode = Mode.Recompress;
                    type = (CompressionType)Enum.Parse(typeof(CompressionType), getopt.Optarg, true);
                    break;

                case 's':
                    samefilename = true;
                    break;

                case 'l':
                    endian = Endianness.LittleEndian;
                    break;

                case 'n':
                    size = false;
                    break;
                }
                opt = getopt.getopt();
            }
            if (mode == null || type == null || getopt.Optind + (mode == Mode.Recompress | samefilename ? 0 : 1) >= args.Length)
            {
                ShowHelp();
                return;
            }
            string input = args[getopt.Optind];
            string output;

            if (getopt.Optind + 1 == args.Length)
            {
                output = input;
            }
            else
            {
                output = args[getopt.Optind + 1];
            }
            if (samefilename && input != "-")
            {
                switch (mode)
                {
                case Mode.Compress:
                    switch (type)
                    {
                    case CompressionType.Kosinski:
                        output = Path.ChangeExtension(input, "kos");
                        break;

                    case CompressionType.Enigma:
                        output = Path.ChangeExtension(input, "eni");
                        break;

                    case CompressionType.Nemesis:
                        output = Path.ChangeExtension(input, "nem");
                        break;

                    case CompressionType.Saxman:
                        output = Path.ChangeExtension(input, "sax");
                        break;

                    case CompressionType.KosinskiModuled:
                        output = Path.ChangeExtension(input, "kosm");
                        break;
                    }
                    break;

                case Mode.Decompress:
                    output = Path.ChangeExtension(input, "unc");
                    break;
                }
            }
            byte[] indata  = ReadInput(input);
            byte[] outdata = null;
            switch (mode)
            {
            case Mode.Compress:
                switch (type)
                {
                case CompressionType.Kosinski:
                    outdata = Kosinski.Compress(indata);
                    break;

                case CompressionType.Enigma:
                    outdata = Enigma.Compress(indata, endian);
                    break;

                case CompressionType.Nemesis:
                    outdata = Nemesis.Compress(indata);
                    break;

                case CompressionType.Saxman:
                    outdata = Saxman.Compress(indata, size);
                    break;

                case CompressionType.ModuledKosinski:
                    outdata = ModuledKosinski.Compress(indata, endian);
                    break;
                }
                break;

            case Mode.Decompress:
                switch (type)
                {
                case CompressionType.Kosinski:
                    outdata = Kosinski.Decompress(indata);
                    break;

                case CompressionType.Enigma:
                    outdata = Enigma.Decompress(indata, endian);
                    break;

                case CompressionType.Nemesis:
                    outdata = Nemesis.Decompress(indata);
                    break;

                case CompressionType.Saxman:
                    outdata = Saxman.Decompress(indata);
                    break;

                case CompressionType.ModuledKosinski:
                    outdata = ModuledKosinski.Decompress(indata, endian);
                    break;
                }
                break;

            case Mode.Recompress:
                switch (type)
                {
                case CompressionType.Kosinski:
                    outdata = Kosinski.Compress(Kosinski.Decompress(indata));
                    break;

                case CompressionType.Enigma:
                    outdata = Enigma.Compress(Enigma.Decompress(indata, endian), endian);
                    break;

                case CompressionType.Nemesis:
                    outdata = Nemesis.Compress(Nemesis.Decompress(indata));
                    break;

                case CompressionType.Saxman:
                    outdata = Saxman.Compress(Saxman.Decompress(indata), size);
                    break;

                case CompressionType.ModuledKosinski:
                    outdata = ModuledKosinski.Compress(ModuledKosinski.Decompress(indata, endian), endian);
                    break;
                }
                break;
            }
            WriteOutput(output, outdata);
        }
Exemple #16
0
        static void Main(string[] args)
        {
            LongOpt[] opts = new[] {
                new LongOpt("help", Argument.No, null, 'h'),
                new LongOpt("padding", Argument.Required, null, 'p'),
                new LongOpt("startpal", Argument.Required, null, 's'),
                new LongOpt("nullfirst", Argument.No, null, 'n'),
                new LongOpt("twoplayer", Argument.No, null, '2'),
                new LongOpt("format", Argument.Required, null, 'f'),
                new LongOpt("game", Argument.Required, null, 'g'),
                new LongOpt("artcmp", Argument.Required, null, 'c'),
                new LongOpt("lowplane", Argument.Required, null, 0),
                new LongOpt("highplane", Argument.Required, null, 0),
                new LongOpt("palette", Argument.Required, null, 0),
                new LongOpt("center", Argument.Required, null, 0),
                new LongOpt("artfile", Argument.Required, null, 0),
                new LongOpt("mapfile", Argument.Required, null, 0),
                new LongOpt("dplcfile", Argument.Required, null, 0),
                new LongOpt("palfile", Argument.Required, null, 0)
            };
            if (args.Length == 0)
            {
                args = new string[] { "-h" }
            }
            ;
            Getopt          getopt        = new Getopt("SpritePlotter.NET", args, Getopt.digest(opts), opts);
            int             padding       = 2;
            byte            startpal      = 0;
            bool            nullfirst     = false;
            bool            twoplayer     = false;
            MappingsFormat  mapfmt        = MappingsFormat.Binary;
            EngineVersion   mapgame       = EngineVersion.Invalid;
            bool            s3kp          = false;
            CompressionType artcmp        = CompressionType.Uncompressed;
            Bitmap          lowplanefile  = null;
            Bitmap          highplanefile = null;

            Color[] palette    = null;
            Bitmap  centerfile = null;
            string  artfile    = null;
            string  mapfile    = null;
            string  dplcfile   = null;
            string  palfile    = null;
            int     opt        = getopt.getopt();

            while (opt != -1)
            {
                switch (opt)
                {
                case 'h':
                    Console.Write(Properties.Resources.HelpText);
                    return;

                case 'p':
                    padding = int.Parse(getopt.Optarg);
                    break;

                case 's':
                    startpal = byte.Parse(getopt.Optarg);
                    break;

                case 'n':
                    nullfirst = true;
                    break;

                case '2':
                    twoplayer = true;
                    break;

                case 'f':
                    mapfmt = (MappingsFormat)Enum.Parse(typeof(MappingsFormat), getopt.Optarg, true);
                    break;

                case 'g':
                    if (getopt.Optarg.Equals("s3kp", StringComparison.OrdinalIgnoreCase))
                    {
                        mapgame = EngineVersion.S3K;
                        s3kp    = true;
                    }
                    else
                    {
                        mapgame = (EngineVersion)Enum.Parse(typeof(EngineVersion), getopt.Optarg, true);
                    }
                    break;

                case 'c':
                    artcmp = (CompressionType)Enum.Parse(typeof(CompressionType), getopt.Optarg, true);
                    break;

                case 0:
                    switch (opts[getopt.Longind].Name)
                    {
                    case "lowplane":
                        lowplanefile = new Bitmap(getopt.Optarg);
                        if (palette == null && (lowplanefile.PixelFormat & PixelFormat.Indexed) == PixelFormat.Indexed)
                        {
                            palette = lowplanefile.Palette.Entries;
                        }
                        break;

                    case "highplane":
                        highplanefile = new Bitmap(getopt.Optarg);
                        if (palette == null && (highplanefile.PixelFormat & PixelFormat.Indexed) == PixelFormat.Indexed)
                        {
                            palette = highplanefile.Palette.Entries;
                        }
                        break;

                    case "palette":
                        switch (System.IO.Path.GetExtension(getopt.Optarg))
                        {
                        case ".bin":
                            palette = SonLVLColor.Load(getopt.Optarg, EngineVersion.S2).Select(a => a.RGBColor).ToArray();
                            break;

                        case ".bmp":
                        case ".png":
                        case ".jpg":
                        case ".gif":
                            using (Bitmap bmp = new Bitmap(getopt.Optarg))
                            {
                                if ((bmp.PixelFormat & PixelFormat.Indexed) == PixelFormat.Indexed)
                                {
                                    palette = bmp.Palette.Entries;
                                }
                                else
                                {
                                    List <Color> pal = new List <Color>();
                                    for (int y = 0; y < bmp.Height; y += 8)
                                    {
                                        for (int x = 0; x < bmp.Width; x += 8)
                                        {
                                            pal.Add(bmp.GetPixel(x, y));
                                        }
                                    }
                                    palette = pal.ToArray();
                                }
                            }
                            break;
                        }
                        break;

                    case "center":
                        centerfile = new Bitmap(getopt.Optarg);
                        break;

                    case "artfile":
                        artfile = getopt.Optarg;
                        break;

                    case "mapfile":
                        mapfile = getopt.Optarg;
                        break;

                    case "dplcfile":
                        dplcfile = getopt.Optarg;
                        break;

                    case "palfile":
                        palfile = getopt.Optarg;
                        break;
                    }
                    break;
                }
                opt = getopt.getopt();
            }
            if (mapgame == EngineVersion.Invalid)
            {
                Console.Error.WriteLine("No game specified.");
                return;
            }
            if (lowplanefile == null && highplanefile == null)
            {
                Console.Error.WriteLine("No image file specified.");
                return;
            }
            if (palette == null)
            {
                Console.Error.WriteLine("No palette specified, and image(s) did not contain palette.");
                return;
            }
            if (artfile == null)
            {
                Console.Error.WriteLine("No output art file specified.");
                return;
            }
            if (mapfile == null)
            {
                Console.Error.WriteLine("No output mappings file specified.");
                return;
            }
            if (palette.Length > 64)
            {
                palette = palette.Take(64).ToArray();                 // lazy
            }
            BitmapBits lowplane = null, highplane = null, combinedplanes = null;

            if (lowplanefile != null)
            {
                if ((lowplanefile.PixelFormat & PixelFormat.Indexed) == PixelFormat.Indexed)
                {
                    lowplane = new BitmapBits(lowplanefile);
                }
                else
                {
                    using (Bitmap bmp = lowplanefile.To32bpp())
                        lowplane = LoadBitmap32BppArgb(bmp, palette);
                }
                lowplanefile.Dispose();
                if (highplanefile == null)
                {
                    combinedplanes = lowplane;
                }
            }
            if (highplanefile != null)
            {
                if ((highplanefile.PixelFormat & PixelFormat.Indexed) == PixelFormat.Indexed)
                {
                    highplane = new BitmapBits(highplanefile);
                }
                else
                {
                    using (Bitmap bmp = highplanefile.To32bpp())
                        highplane = LoadBitmap32BppArgb(bmp, palette);
                }
                highplanefile.Dispose();
                if (lowplanefile == null)
                {
                    combinedplanes = highplane;
                }
            }
            if (combinedplanes == null)
            {
                combinedplanes = new BitmapBits(Math.Max(lowplane.Width, highplane.Width), Math.Max(lowplane.Height, highplane.Height));
                combinedplanes.DrawBitmap(lowplane, 0, 0);
                combinedplanes.DrawBitmapComposited(highplane, 0, 0);
            }
            List <Point> centers = null;

            if (centerfile != null)
            {
                centers = new List <Point>();
                BitmapBits cntr;
                if ((centerfile.PixelFormat & PixelFormat.Indexed) == PixelFormat.Indexed)
                {
                    cntr = new BitmapBits(centerfile);
                }
                else
                {
                    using (Bitmap bmp = centerfile.To32bpp())
                        cntr = LoadBitmap32BppArgb(bmp, Color.Black, Color.White);
                }
                centerfile.Dispose();
                for (int y = 0; y < cntr.Height; y++)
                {
                    for (int x = 0; x < cntr.Width; x++)
                    {
                        if (cntr[x, y] != 0)
                        {
                            centers.Add(new Point(x, y));
                        }
                    }
                }
            }
            List <Rectangle> sprites = new List <Rectangle>();

            for (int y = 0; y < combinedplanes.Height; y++)
            {
                for (int x = 0; x < combinedplanes.Width; x++)
                {
                    if (combinedplanes[x, y] % 16 != 0)
                    {
                        Rectangle newrect = new Rectangle(x - padding, y - padding, (padding * 2) + 1, (padding * 2) + 1);
                        for (int i = 0; i < sprites.Count; i++)
                        {
                            if (newrect.IntersectsWith(sprites[i]))
                            {
                                newrect = Rectangle.Union(newrect, sprites[i]);
                                sprites.RemoveAt(i);
                                i = -1;
                            }
                        }
                        sprites.Add(newrect);
                    }
                }
            }
            List <Rectangle> rows = new List <Rectangle>();

            for (int i = 0; i < sprites.Count; i++)
            {
                Rectangle rect = sprites[i];
                rect.Inflate(-padding, -padding);
                sprites[i] = rect;
                if (rows.Count > 0 && sprites[i].IntersectsWith(rows[rows.Count - 1]))
                {
                    rows[rows.Count - 1] = Rectangle.Union(sprites[i], rows[rows.Count - 1]);
                }
                else
                {
                    rows.Add(new Rectangle(0, sprites[i].Y, combinedplanes.Width, sprites[i].Height));
                }
            }
            List <Rectangle> newsprites = new List <Rectangle>(sprites.Count);

            foreach (Rectangle rect in rows)
            {
                newsprites.AddRange(sprites.Where(a => a.IntersectsWith(rect)).OrderBy(a => a.X));
            }
            sprites = newsprites;
            List <byte[]>             tiles = new List <byte[]>();
            NamedList <MappingsFrame> map   = new NamedList <MappingsFrame>("Map_" + Path.GetFileNameWithoutExtension(mapfile), sprites.Count);
            NamedList <DPLCFrame>     dplc  = null;

            if (dplcfile != null)
            {
                dplc = new NamedList <DPLCFrame>("DPLC_" + Path.GetFileNameWithoutExtension(dplcfile), sprites.Count);
            }
            if (nullfirst)
            {
                map.Add(new MappingsFrame(map.Name + "_Null"));
                if (dplc != null)
                {
                    dplc.Add(new DPLCFrame(dplc.Name + "_Null"));
                }
            }
            for (int i = 0; i < sprites.Count; i++)
            {
                Point center = new Point(sprites[i].Width / 2, sprites[i].Height / 2);
                if (centers != null)
                {
                    foreach (Point item in centers)
                    {
                        if (sprites[i].Contains(item))
                        {
                            center = new Point(item.X - sprites[i].Left, item.Y - sprites[i].Top);
                            break;
                        }
                    }
                }
                MappingsFrame mapframe = new MappingsFrame(map.Name + "_" + i);
                map.Add(mapframe);
                DPLCFrame dplcframe = null;
                if (dplc != null)
                {
                    dplcframe = new DPLCFrame(dplc.Name + "_" + i);
                    dplc.Add(dplcframe);
                }
                if (lowplane != null)
                {
                    SpriteToMap(sprites[i], center, lowplane, tiles, mapframe, dplcframe, startpal, false, twoplayer);
                }
                if (highplane != null)
                {
                    SpriteToMap(sprites[i], center, highplane, tiles, mapframe, dplcframe, startpal, true, twoplayer);
                }
            }
            using (MemoryStream ms = new MemoryStream(tiles.Count * 32))
            {
                using (BinaryWriter bw = new BinaryWriter(ms))
                    foreach (byte[] b in tiles)
                    {
                        bw.Write(b);
                    }
                Compression.Compress(ms.ToArray(), artfile, artcmp);
            }
            if (mapfmt == MappingsFormat.Binary)
            {
                File.WriteAllBytes(mapfile, MappingsFrame.GetBytes(map, mapgame));
                if (dplc != null)
                {
                    File.WriteAllBytes(dplcfile, DPLCFrame.GetBytes(dplc, s3kp ? EngineVersion.S2 : mapgame));
                }
            }
            else
            {
                MappingsFrame.ToASM(mapfile, map, mapgame, mapfmt == MappingsFormat.Macro);
                if (dplc != null)
                {
                    DPLCFrame.ToASM(dplcfile, dplc, mapgame, mapfmt == MappingsFormat.Macro, s3kp);
                }
            }
            if (palfile != null)
            {
                using (FileStream fs = File.Create(palfile))
                    using (BinaryWriter bw = new BinaryWriter(fs))
                        foreach (Color c in palette)
                        {
                            bw.Write(ByteConverter.GetBytes(new SonLVLColor(c).MDColor));
                        }
            }
        }
Exemple #17
0
        static void Main(string[] args)
        {
            // Get infos from assembly
            assembly = Assembly.GetExecutingAssembly();
            prgName  = assembly.GetName().Name;

            // locales management
            string locale = ConfigurationManager.AppSettings["locale"];

            if (string.IsNullOrWhiteSpace(locale))
            {
                catalog = new Catalog(prgName, "./locale");
            }
            else
            {
                catalog = new Catalog(prgName, "./locale", new CultureInfo(locale));
            }

            // status vars
            string outputfile = String.Empty;
            string mode       = "";

            nobanner = false;

            // GNU Getopt options
            LongOpt[] longopts = new LongOpt[6];
            longopts[0] = new LongOpt("help", Argument.No, null, 'h');
            longopts[1] = new LongOpt("nobanner", Argument.No, null, 1000);
            longopts[2] = new LongOpt("output_file", Argument.Required, new StringBuilder(), 'o');
            longopts[3] = new LongOpt("text", Argument.No, null, 1001);
            longopts[4] = new LongOpt("markers", Argument.No, null, 1002);
            longopts[5] = new LongOpt("flyto", Argument.No, null, 1003);

            Getopt options = new Getopt(prgName, args, "ho:", longopts);

            int c;

            while ((c = options.getopt()) != -1)
            {
                switch (c)
                {
                case 'h':
                    PrintHelp();
                    Environment.Exit(0);
                    break;

                case ':':
                    Console.Error.WriteLine(catalog.GetString("Doh! You need an argument for option '{0}'", (char)options.getopt()));
                    Environment.Exit(1);
                    break;

                case '?':
                    Console.Error.WriteLine(catalog.GetString("The option '{0}' is not valid", options.Argv[options.Optind - 1]));
                    Environment.Exit(1);
                    break;

                case 'o':
                    outputfile = options.Optarg;
                    break;

                case 1000:
                    nobanner = true;
                    break;

                case 1001:
                    mode = "";
                    break;

                case 1002:
                    mode = "MKR";
                    break;

                case 1003:
                    mode = "FLYTO";
                    break;
                }
            }

            // checks if inputfile is specified
            if (options.Argv.Length <= options.Optind)
            {
                Console.Error.WriteLine(catalog.GetString("No input file specified."));
                Environment.Exit(2);
            }

            PrintBanner();

            // Converter init
            MSTSConverterFactory factory = new MSTSConverterFactory();
            IConverter           conv    = factory.GetConverter(mode);
            string ret = conv.FileHeader();

            // scan for files
            for (int i = options.Optind; i < options.Argv.Length; i++)
            {
                string inputfile = options.Argv[i];
                if (File.Exists(inputfile))
                {
                    conv.SetKml(inputfile);
                    ret += conv.PlacemarkBody();
                    ret += conv.PathBody();
                    ret += conv.PolyBody();
                }
                else
                {
                    Console.Error.WriteLine(catalog.GetString("File '{0}' not found: ignoring.", inputfile));
                }
            }

            conv.FileOut(ret, outputfile);
        }
Exemple #18
0
        static void Main(string[] args)
        {
            _applicationName = Path.GetFileNameWithoutExtension(Process.GetCurrentProcess().MainModule.FileName);

            // Load configuration file settings
            ApplicationSettings appSettings = null;

            try
            {
                appSettings = new ApplicationSettings(_configFileName);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"ERROR: Failed while loading configuration file.\nExtended Error Information:\n{ex.Message ?? "<none>"}");
                Environment.Exit(1);
            }


            // Setup and read application arguments
            LongOpt[] longOpts = new LongOpt[]
            {
                new LongOpt("file", Argument.Required, null, 'f'),      // Calibration file
                new LongOpt("allow-oversize", Argument.No, null, 'o'),  // Allow over-sized calibration files
                new LongOpt("read", Argument.Required, null, 'r'),      // Read calibration data from instrument at given address
                new LongOpt("write", Argument.Required, null, 'w'),     // Write calibration data to instrument at given address
                new LongOpt("help", Argument.No, null, 'h')             // Display help
            };

            Getopt g = new Getopt(_applicationName, args, "f:or:w:h", longOpts)
            {
                Opterr = false  // Do our own error handling
            };

            string optionFile          = null;
            bool   optionAllowOverSize = false;
            bool   optionRead          = false;
            bool   optionWrite         = false;
            int    gpibAddress         = 0;

            int c;

            while ((c = g.getopt()) != -1)
            {
                switch (c)
                {
                case 'f':
                    optionFile = g.Optarg;
                    break;

                case 'o':
                    optionAllowOverSize = true;
                    break;

                case 'r':
                    optionRead = true;
                    int.TryParse(g.Optarg, out gpibAddress);
                    break;

                case 'w':
                    optionWrite = true;
                    int.TryParse(g.Optarg, out gpibAddress);
                    break;

                case 'h':
                    ShowUsage();
                    Environment.Exit(0);
                    break;

                case '?':
                default:
                    ShowUsage();
                    Environment.Exit(1);
                    break;
                }
            }

            // Show usage help and exit if:
            //   - Extra parameters are provided.
            //   - No calibration file is specified.
            //   - Both read and write options are set.
            if (g.Optind < args.Length || optionFile == null || (optionRead && optionWrite))
            {
                ShowUsage();
                Environment.Exit(1);
            }

            //Console.WriteLine($"File='{optionFile}'\nOversize={optionAllowOverSize}");
            //Console.WriteLine($"Read={optionRead}\nWrite={optionWrite}\nAddr={gpibAddress}");


            // Validate the calibration file when a write to an instrument will be performed
            // or when only reading a file without connecting to an instrument.
            byte[] fileData = null;
            if (optionWrite || (!optionRead && !optionWrite))
            {
                try
                {
                    FileInfo fi = new FileInfo(optionFile);

                    // Ensure file size is at least 256 bytes
                    if (fi.Length < 256)
                    {
                        throw new ApplicationException("File size is less then 256 bytes.");
                    }

                    // Ensure file size is exactly 256 bytes if 'allow over-size' option is not specified.
                    if (!optionAllowOverSize && fi.Length != 256)
                    {
                        throw new ApplicationException("File size is not 256 bytes.");
                    }

                    // Read data from calibration file
                    fileData = ReadFile(optionFile);

                    // Note: The calibration file contains the raw 256 nibbles from the
                    //       instrument's SRAM. When SRAM is read from the meter, 0x40
                    //       is added to the nibble providing an ASCII byte. The file
                    //       contains these bytes.
                    //
                    // SRAM/File Format:
                    //   - The first byte contains the CPU's calibration switch enable check
                    //     value which alternates between 0x40 and 0x4f when the switch is
                    //     enabled. This first byte does not contain calibration data.
                    //
                    //   - The following bytes contain 19 calibration entries each containing
                    //     13 bytes for a total of 247 bytes of calibration data.
                    //
                    //   - The remaining bytes are unused.

                    // Copy raw file data to 2D array for use in calibration library
                    byte[,] calibrationData = new byte[19, 13];
                    Buffer.BlockCopy(fileData, 1, calibrationData, 0, 247);

                    // Validate checksums in calibration file
                    if (!HP3478ACalibration.ValidateData(calibrationData, false))
                    {
                        throw new ApplicationException("File contains invalid calibration data.");
                    }

                    HP3478ACalibration.PrintData(calibrationData);
                    Console.WriteLine();
                    Console.WriteLine("Calibration file data is valid.");
                    Console.WriteLine();
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"ERROR: Failed to validate calibration file.\n\nExtended Error Information:\n{ex.Message ?? "<none>"}");
                    Environment.Exit(1);
                }
            }


            if (optionRead)  // Read from instrument
            {
                try
                {
                    // Ensure destination file does not already exist
                    if (File.Exists(optionFile))
                    {
                        throw new ApplicationException("Destination file already exists.");
                    }

                    Console.WriteLine("Reading calibration data from instrument...");
                    byte[] sramBytes = ReadCalibration(appSettings, gpibAddress);

                    // Copy raw SRAM data to 2D array for use in calibration library
                    byte[,] calibrationData = new byte[19, 13];
                    Buffer.BlockCopy(sramBytes, 1, calibrationData, 0, 247);

                    // Validate checksums in SRAM
                    if (HP3478ACalibration.ValidateData(calibrationData, false))
                    {
                        Console.WriteLine("Instrument contains valid calibration data.");
                    }
                    else
                    {
                        Console.WriteLine("Warning: Instrument contains invalid calibration data.");
                    }

                    Console.WriteLine("Writing calibration data to file...");
                    WriteFile(optionFile, sramBytes);
                    Console.WriteLine("Operation complete.");

                    Console.WriteLine();
                    HP3478ACalibration.PrintData(calibrationData);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"ERROR: Failed while reading calibration data from instrument.\n\nExtended Error Information:\n{ex.Message ?? "<none>"}");
                    Environment.Exit(1);
                }
            }
            else if (optionWrite)  // Write to instrument
            {
                // Prompt user before writing to instrument
                Console.WriteLine("Warning: This will overwrite all calibration data in the instrument!");

                ConsoleKey keyResponse;
                do
                {
                    Console.Write("Do you want to continue? [y/n] ");
                    keyResponse = Console.ReadKey().Key;
                    Console.WriteLine();
                } while (keyResponse != ConsoleKey.Y && keyResponse != ConsoleKey.N);

                try
                {
                    if (keyResponse == ConsoleKey.Y)
                    {
                        Console.WriteLine("Writing calibration data to instrument...");
                        WriteCalibration(appSettings, gpibAddress, fileData);
                        Console.WriteLine("Operation completed successfully.");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"ERROR: Failed while writing calibration data to instrument.\n\nExtended Error Information:\n{ex.Message ?? "<none>"}");
                    Environment.Exit(1);
                }
            }
        }
Exemple #19
0
        static void Main(string[] args)
        {
            byte[]               art;
            ColorPalette         palette;
            List <MappingsFrame> map;
            List <DPLCFrame>     dplc;
            SpriteInfo           spriteInfo;

            LevelData.littleendian = false;
            LongOpt[] opts = new[] {
                new LongOpt("help", Argument.No, null, 'h'),
                new LongOpt("padding", Argument.Required, null, 'p'),
                new LongOpt("columns", Argument.Required, null, 'c'),
                new LongOpt("width", Argument.Required, null, 'w'),
                new LongOpt("background", Argument.Required, null, 'b'),
                new LongOpt("grid", Argument.No, null, 'g')
            };
            Getopt getopt     = new Getopt("SpriteSheetGen", args, Getopt.digest(opts), opts);
            int    padding    = 2;
            int    columns    = 8;
            int    width      = 0;
            bool   fixedwidth = false;
            int    gridsize   = -1;
            Color  background = Color.Transparent;
            int    opt        = getopt.getopt();

            while (opt != -1)
            {
                switch (opt)
                {
                case 'h':
                    Console.Write(Properties.Resources.HelpText);
                    return;

                case 'p':
                    padding = int.Parse(getopt.Optarg);
                    break;

                case 'c':
                    columns = int.Parse(getopt.Optarg);
                    break;

                case 'w':
                    width      = int.Parse(getopt.Optarg);
                    columns    = -1;
                    fixedwidth = true;
                    break;

                case 'g':
                    gridsize = 0;
                    break;

                case 'b':
                    if (getopt.Optarg.StartsWith("#"))
                    {
                        background = Color.FromArgb((int)(0xFF000000 | uint.Parse(getopt.Optarg.Substring(1), System.Globalization.NumberStyles.HexNumber)));
                    }
                    else
                    {
                        background = Color.FromName(getopt.Optarg.Replace(" ", ""));
                    }
                    break;
                }
                opt = getopt.getopt();
            }
            string filename;

            Console.Write("File: ");
            if (getopt.Optind == args.Length)
            {
                filename = Console.ReadLine();
            }
            else
            {
                filename = args[getopt.Optind];
                Console.WriteLine(filename);
            }
            filename = Path.GetFullPath(filename);
            Environment.CurrentDirectory = Path.GetDirectoryName(filename);
            spriteInfo = IniSerializer.Deserialize <SpriteInfo>(filename);
            if (spriteInfo.MappingsGame == EngineVersion.Invalid)
            {
                spriteInfo.MappingsGame = spriteInfo.Game;
            }
            if (spriteInfo.DPLCGame == EngineVersion.Invalid)
            {
                spriteInfo.DPLCGame = spriteInfo.Game;
            }
            MultiFileIndexer <byte> tiles = new MultiFileIndexer <byte>();

            foreach (SonicRetro.SonLVL.API.FileInfo file in spriteInfo.Art)
            {
                tiles.AddFile(new List <byte>(Compression.Decompress(file.Filename, spriteInfo.ArtCompression)), file.Offset);
            }
            art = tiles.ToArray();
            tiles.Clear();
            byte[] tmp = null;
            using (Bitmap palbmp = new Bitmap(1, 1, PixelFormat.Format8bppIndexed))
                palette = palbmp.Palette;
            for (int i = 0; i < 256; i++)
            {
                palette.Entries[i] = Color.Black;
            }
            foreach (PaletteInfo palent in spriteInfo.Palette)
            {
                tmp = File.ReadAllBytes(palent.Filename);
                SonLVLColor[] palfile;
                palfile = new SonLVLColor[tmp.Length / 2];
                for (int pi = 0; pi < tmp.Length; pi += 2)
                {
                    palfile[pi / 2] = new SonLVLColor(SonicRetro.SonLVL.API.ByteConverter.ToUInt16(tmp, pi));
                }
                for (int pa = 0; pa < palent.Length; pa++)
                {
                    palette.Entries[pa + palent.Destination] = palfile[pa + palent.Source].RGBColor;
                }
            }
            palette.Entries[0] = background;
            Dictionary <string, int> labels = new Dictionary <string, int>();

            tmp = null;
            switch (spriteInfo.MappingsFormat)
            {
            case MappingsFormat.Binary:
                tmp = File.ReadAllBytes(spriteInfo.MappingsFile);
                break;

            case MappingsFormat.ASM:
            case MappingsFormat.Macro:
                tmp = LevelData.ASMToBin(spriteInfo.MappingsFile, spriteInfo.MappingsGame, out labels);
                break;
            }
            map = MappingsFrame.Load(tmp, spriteInfo.MappingsGame, labels);
            if (!string.IsNullOrEmpty(spriteInfo.DPLCFile))
            {
                labels = new Dictionary <string, int>();
                tmp    = null;
                switch (spriteInfo.DPLCFormat)
                {
                case MappingsFormat.Binary:
                    tmp = File.ReadAllBytes(spriteInfo.DPLCFile);
                    break;

                case MappingsFormat.ASM:
                case MappingsFormat.Macro:
                    tmp = LevelData.ASMToBin(spriteInfo.DPLCFile, spriteInfo.DPLCGame, out labels);
                    break;
                }
                dplc = DPLCFrame.Load(tmp, spriteInfo.DPLCGame, labels);
            }
            else
            {
                dplc = null;
            }
            List <BitmapBits> spritesLow    = new List <BitmapBits>(map.Count);
            List <BitmapBits> spritesHigh   = new List <BitmapBits>(map.Count);
            List <BitmapBits> spritesMerged = new List <BitmapBits>(map.Count);
            List <Point>      offsets       = new List <Point>(map.Count);
            List <Point>      centers       = new List <Point>(map.Count);

            for (int i = 0; i < map.Count; i++)
            {
                if (map[i].TileCount == 0)
                {
                    //File.AppendAllText("log.txt", "Frame " + i + " empty.\r\n");
                    continue;
                }
                Sprite spr;
                if (dplc != null)
                {
                    spr = LevelData.MapFrameToBmp(art, map[i], dplc[i], spriteInfo.StartPalette);
                }
                else
                {
                    spr = LevelData.MapFrameToBmp(art, map[i], spriteInfo.StartPalette);
                }
                BitmapBits sprLow    = spr.GetBitmapLow();
                BitmapBits sprHigh   = spr.GetBitmapHigh();
                BitmapBits sprMerged = spr.GetBitmap();
                int        cx        = -spr.X;
                int        cy        = -spr.Y;
                for (int _x = 0; _x < sprMerged.Width; _x++)
                {
                    for (int _y = 0; _y < sprMerged.Height; _y++)
                    {
                        if (sprMerged[_x, _y] != 0)
                        {
                            sprMerged = sprMerged.GetSection(_x, 0, sprMerged.Width - _x, sprMerged.Height);
                            sprLow    = sprLow.GetSection(_x, 0, sprLow.Width - _x, sprLow.Height);
                            sprHigh   = sprHigh.GetSection(_x, 0, sprHigh.Width - _x, sprHigh.Height);
                            cx       -= _x;
                            goto checkright;
                        }
                    }
                }
checkright:
                for (int _x = sprMerged.Width - 1; _x >= 0; _x--)
                {
                    for (int _y = 0; _y < sprMerged.Height; _y++)
                    {
                        if (sprMerged[_x, _y] != 0)
                        {
                            sprMerged = sprMerged.GetSection(0, 0, _x + 1, sprMerged.Height);
                            sprLow    = sprLow.GetSection(0, 0, _x + 1, sprLow.Height);
                            sprHigh   = sprHigh.GetSection(0, 0, _x + 1, sprHigh.Height);
                            goto checktop;
                        }
                    }
                }
checktop:
                for (int _y = 0; _y < sprMerged.Height; _y++)
                {
                    for (int _x = 0; _x < sprMerged.Width; _x++)
                    {
                        if (sprMerged[_x, _y] != 0)
                        {
                            sprMerged = sprMerged.GetSection(0, _y, sprMerged.Width, sprMerged.Height - _y);
                            sprLow    = sprLow.GetSection(0, _y, sprLow.Width, sprLow.Height - _y);
                            sprHigh   = sprHigh.GetSection(0, _y, sprHigh.Width, sprHigh.Height - _y);
                            cy       -= _y;
                            goto checkbottom;
                        }
                    }
                }
checkbottom:
                for (int _y = sprMerged.Height - 1; _y >= 0; _y--)
                {
                    for (int _x = 0; _x < sprMerged.Width; _x++)
                    {
                        if (sprMerged[_x, _y] != 0)
                        {
                            sprMerged = sprMerged.GetSection(0, 0, sprMerged.Width, _y + 1);
                            sprLow    = sprLow.GetSection(0, 0, sprLow.Width, _y + 1);
                            sprHigh   = sprHigh.GetSection(0, 0, sprHigh.Width, _y + 1);
                            goto checkdone;
                        }
                    }
                }
checkdone:
                spritesMerged.Add(sprMerged);
                spritesLow.Add(sprLow);
                spritesHigh.Add(sprHigh);
                centers.Add(new Point(cx, cy));
            }
            if (gridsize == 0)
            {
                for (int i = 0; i < spritesMerged.Count; i++)
                {
                    gridsize = Math.Max(gridsize, Math.Max(spritesMerged[i].Width, spritesMerged[i].Height));
                }
                if (!fixedwidth)
                {
                    width = (padding * 2 + gridsize) * columns;
                }
            }
            int x         = padding;
            int y         = padding;
            int height    = 0;
            int rowcnt    = 0;
            int rowheight = 0;

            for (int i = 0; i < spritesMerged.Count; i++)
            {
                BitmapBits spr = spritesMerged[i];
                Point      off;
                if (gridsize == -1)
                {
                    if (fixedwidth && x + spr.Width + padding > width)
                    {
                        x         = padding;
                        y        += rowheight;
                        rowheight = 0;
                    }
                    off        = new System.Drawing.Point(x, y);
                    centers[i] = new Point(centers[i].X + off.X, centers[i].Y + off.Y);
                    if (!fixedwidth)
                    {
                        width = Math.Max(width, x + spr.Width + padding);
                    }
                    height = Math.Max(height, y + spr.Height + padding);
                    if (spr.Height + 2 * padding > rowheight)
                    {
                        rowheight = spr.Height + 2 * padding;
                    }
                    if (!fixedwidth && ++rowcnt == columns)
                    {
                        x         = padding;
                        y        += rowheight;
                        rowcnt    = 0;
                        rowheight = 0;
                    }
                    else
                    {
                        x += spr.Width + 2 * padding;
                    }
                }
                else
                {
                    if (fixedwidth && x + gridsize + padding > width)
                    {
                        x  = padding;
                        y += gridsize + 2 * padding;
                    }
                    off        = new Point(x + (gridsize - spr.Width) / 2, y + (gridsize - spr.Height) / 2);
                    centers[i] = new Point(centers[i].X + off.X, centers[i].Y + off.Y);
                    height     = Math.Max(height, y + gridsize + padding);
                    if (!fixedwidth && ++rowcnt == columns)
                    {
                        x      = padding;
                        y     += gridsize + 2 * padding;
                        rowcnt = 0;
                    }
                    else
                    {
                        x += gridsize + 2 * padding;
                    }
                }
                offsets.Add(off);
            }
            BitmapBits bmpMerged = new BitmapBits(width, height);

            for (int i = 0; i < spritesMerged.Count; i++)
            {
                bmpMerged.DrawBitmap(spritesMerged[i], offsets[i]);
            }
            BitmapBits bmpLow = new BitmapBits(width, height);

            for (int i = 0; i < spritesLow.Count; i++)
            {
                bmpLow.DrawBitmap(spritesLow[i], offsets[i]);
            }
            BitmapBits bmpHigh = new BitmapBits(width, height);

            for (int i = 0; i < spritesHigh.Count; i++)
            {
                bmpHigh.DrawBitmap(spritesHigh[i], offsets[i]);
            }
            BitmapBits bmpCenter = new BitmapBits(width, height);

            for (int i = 0; i < centers.Count; i++)
            {
                bmpCenter[centers[i].X, centers[i].Y] = 1;
            }
            Console.Write("Save as: ");
            if (getopt.Optind + 1 >= args.Length)
            {
                filename = Console.ReadLine();
            }
            else
            {
                filename = args[getopt.Optind + 1];
                Console.WriteLine(filename);
            }
            filename = Path.GetFullPath(filename);
            bmpMerged.ToBitmap(palette).Save(filename);
            if (!bmpLow.Bits.FastArrayEqual(0) && !bmpHigh.Bits.FastArrayEqual(0))
            {
                bmpLow.ToBitmap(palette).Save(Path.Combine(Path.GetDirectoryName(filename), Path.GetFileNameWithoutExtension(filename) + "_low" + Path.GetExtension(filename)));
                bmpHigh.ToBitmap(palette).Save(Path.Combine(Path.GetDirectoryName(filename), Path.GetFileNameWithoutExtension(filename) + "_high" + Path.GetExtension(filename)));
            }
            bmpCenter.ToBitmap1bpp(Color.Black, Color.White).Save(Path.Combine(Path.GetDirectoryName(filename), Path.GetFileNameWithoutExtension(filename) + "_center" + Path.GetExtension(filename)));
        }
Exemple #20
0
        static void Main(string[] args)
        {
            var getopt = new Getopt(Assembly.GetExecutingAssembly().GetName().Name, args, "i:o:")
            {
                Opterr = false
            };

            string input  = null;
            string output = null;

            int option;

            while (-1 != (option = getopt.getopt()))
            {
                switch (option)
                {
                case 'i': input = getopt.Optarg; break;

                case 'o': output = getopt.Optarg; break;

                default: PrintUsage(); return;
                }
            }

            if (input == null || output == null)
            {
                PrintUsage();
                return;
            }

            try
            {
                if (!File.Exists(input))
                {
                    Console.WriteLine("File {0} not found", input);
                    return;
                }

                Dictionary <string, string> entries;
                var parser = new PoParser();
                using (var reader = new StreamReader(input))
                {
                    entries = parser.ParseIntoDictionary(reader);
                }

                using (var writer = new ResourceWriter(output))
                {
                    foreach (var kv in entries)
                    {
                        try { writer.AddResource(kv.Key, kv.Value); }
                        catch (Exception e) { Console.WriteLine("Error adding item {0}: {1}", kv.Key, e.Message); }
                    }
                    writer.Generate();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error during execution: {0}", ex.Message);
                return;
            }
        }
Exemple #21
0
        static void DoMain(string[] arguments)
        {
            //Console.WriteLine(GL.GetConstantString(GL.GL_TEXTURE_2D));
            //_MainData();
            //_MainData2();

            if (!IsNet45OrNewer())
            {
                //ThreadManForUser.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);

            //System.AppDomain.CurrentDomain.UnhandledException +=

            // 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 (Exception e)
                            {
                                Console.WriteLine(e);
                            }

                            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 = $"{encryptedFile}.decrypted";
                            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
                //    {
                //        var classesRoot = Registry.ClassesRoot;
//
                //        classesRoot.CreateSubKey(".pbp")?.SetValue(null, "cspspemu.executable");
                //        classesRoot.CreateSubKey(".elf")?.SetValue(null, "cspspemu.executable");
                //        classesRoot.CreateSubKey(".prx")?.SetValue(null, "cspspemu.executable");
                //        classesRoot.CreateSubKey(".cso")?.SetValue(null, "cspspemu.executable");
                //        classesRoot.CreateSubKey(".dax")?.SetValue(null, "cspspemu.executable");
//
                //        var reg = 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 e)
                //    {
                //        Console.Error.WriteLine(e);
                //        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 e)
            {
                Console.Error.WriteLine(e);
                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 (Exception e)
//            {
//                Console.WriteLine(e);
//            }
//#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();
                }
            }
        }
Exemple #22
0
        bool ParseArgs(string[] args)
        {
            int c;

            List <LongOpt> options = new List <LongOpt>();

            options.Add(new LongOpt("message", Argument.Required, null, 'M'));
            options.Add(new LongOpt("message-hex", Argument.Required, null, 'H'));
            options.Add(new LongOpt("private-key", Argument.Required, null, 'K'));
            options.Add(new LongOpt("merchant-name", Argument.Required, null, 'N'));
            options.Add(new LongOpt("merchant-id", Argument.Required, null, 'I'));
            options.Add(new LongOpt("text", Argument.No, null, 't'));
            options.Add(new LongOpt("raw", Argument.No, null, 'r'));
            options.Add(new LongOpt("base64", Argument.No, null, 'b'));
            options.Add(new LongOpt("json", Argument.No, null, 'j'));
            options.Add(new LongOpt("quiet", Argument.No, null, 'q'));
            options.Add(new LongOpt("verbose", Argument.Optional, null, 'v'));
            options.Add(new LongOpt("help", Argument.No, null, 'h'));

            Getopt g = new Getopt(ProgName, args, "N:I:M:H:K:trbjqv::h", options.ToArray());

            g.Opterr = true;

            while ((c = g.getopt()) != -1)
            {
                string arg = g.Optarg;

                switch (c)
                {
                case 'M':
                    if (!StrUtils.Base64UrlTryDecode(arg, out InputMessage))
                    {
                        Console.WriteLine("The MESSAGE parameter must be a base64 string");
                        return(false);
                    }
                    break;

                case 'H':
                    if (!BinConvert.TryHexToBytes(arg, out InputMessage))
                    {
                        Console.WriteLine("The MESSAGE parameter must be an hex string");
                        return(false);
                    }
                    break;

                case 'K':
                    if (!StrUtils.Base64UrlTryDecode(arg, out PrivateKey))
                    {
                        Console.WriteLine("The PRIVATE KEY parameter must be a base64 string");
                        return(false);
                    }
                    break;

                case 'N':
                    MerchantName = arg;
                    break;

                case 'I':
                    if (!StrUtils.Base64UrlTryDecode(arg, out MerchantID))
                    {
                        Console.WriteLine("The MERCHANT ID parameter must be a base64 string");
                        return(false);
                    }
                    if (MerchantID.Length != 32)
                    {
                        Console.WriteLine("The MERCHANT ID parameter must be a 32-byte value");
                        return(false);
                    }
                    break;

                case 't':
                    OutputText = 1;
                    break;

                case 'r':
                    OutputHex = 1;
                    break;

                case 'b':
                    OutputBase64 = 1;
                    break;

                case 'j':
                    Json = true;
                    break;

                case 'q':
                    Quiet = true;
                    break;

                case 'v':
                    Logger.ConsoleLevel = Logger.Level.Trace;
                    if (arg != null)
                    {
                        int level;
                        if (int.TryParse(arg, out level))
                        {
                            Logger.ConsoleLevel = Logger.IntToLevel(level);
                        }
                    }
                    break;

                case 'h':
                    Usage();
                    return(false);

                default:
                    Console.WriteLine("Invalid argument on command line");
                    Console.WriteLine("Try " + ProgName + " --help");
                    return(false);
                }
            }

            if (InputMessage == null)
            {
                Console.WriteLine("You must specify the input message");
                Console.WriteLine("Try " + ProgName + " --help");
                return(false);
            }

            if ((MerchantID != null) && (MerchantName != null))
            {
                Console.WriteLine("You can't both specify a merchant name and a merchant ID");
                Console.WriteLine("Try " + ProgName + " --help");
                return(false);
            }

            if ((MerchantID == null) && (MerchantName == null))
            {
                MerchantName = DefaultMerchantName;
                Console.WriteLine("Using default merchant name: {0}", MerchantName);
            }

            if (PrivateKey == null)
            {
                Console.WriteLine("Using default private key");
                PrivateKey = StrUtils.Base64UrlDecode(DefaultPrivateKey);
            }

            switch (OutputText + OutputHex + OutputBase64)
            {
            case 0:
                /* Default */
                OutputText = 1;
                break;

            case 1:
                /* One value selected */
                break;

            default:
                Console.WriteLine("You must specify one output format (and only one)");
                return(false);
            }

            return(true);
        }
Exemple #23
0
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            // Get infos from assembly
            Assembly assembly = Assembly.GetExecutingAssembly();
            string   prgName  = assembly.GetName().Name;

            #region locales management
            string      localeName = ConfigurationManager.AppSettings["locale"];
            CultureInfo locale;

            if (string.IsNullOrWhiteSpace(localeName))
            {
                locale = CultureInfo.CurrentCulture;
            }
            else
            {
                locale = new CultureInfo(localeName);
            }

            ICatalog T = new Catalog(prgName, "./locale", locale);
            #endregion

            GeneratorForm generator    = new GeneratorForm(T);
            string        saveFileName = string.Empty;

            #region Options from app.config
            string forecolor = ConfigurationManager.AppSettings["forecolor"];
            if (!string.IsNullOrWhiteSpace(forecolor))
            {
                generator.QRForeColor = ColorTranslator.FromHtml(forecolor);
            }
            else
            {
                generator.QRForeColor = Color.FromKnownColor(KnownColor.Black);
            }

            string backcolor = ConfigurationManager.AppSettings["backcolor"];
            if (!string.IsNullOrWhiteSpace(backcolor))
            {
                generator.QRBackColor = ColorTranslator.FromHtml(backcolor);
            }
            else
            {
                generator.QRBackColor = Color.FromKnownColor(KnownColor.White);
            }

            string ecclevel = ConfigurationManager.AppSettings["ecclevel"];
            if (!string.IsNullOrWhiteSpace(ecclevel))
            {
                generator.ErrorCorrectionLevel = ecclevel[0];
            }
            else
            {
                generator.ErrorCorrectionLevel = 'Q';
            }

            string size = ConfigurationManager.AppSettings["size"];
            if (!string.IsNullOrWhiteSpace(size))
            {
                generator.ElementSize = Convert.ToInt16(size);
            }
            else
            {
                generator.ElementSize = 20;
            }
            #endregion

            #region GNU Getopt options
            LongOpt[] longopts = new LongOpt[5];
            longopts[0] = new LongOpt("forecolor", Argument.Required, null, 'f');
            longopts[1] = new LongOpt("backcolor", Argument.Required, null, 'b');
            longopts[2] = new LongOpt("ecclevel", Argument.Required, null, 'e');
            longopts[3] = new LongOpt("size", Argument.Required, null, 's');
            longopts[4] = new LongOpt("output", Argument.Required, null, 'o');

            Getopt options = new Getopt(prgName, args, "f:b:e:s:o:", longopts);

            int c;
            while ((c = options.getopt()) != -1)
            {
                switch (c)
                {
                case ':':
                    throw new ArgumentException(T.GetString("Doh! You need an argument for option '{0}'", (char)options.getopt()));

                case '?':
                    throw new ArgumentException(T.GetString("The option '{0}' is not valid", options.Argv[options.Optind - 1]));

                case 's':
                    generator.ElementSize = Convert.ToInt16(options.Optarg);
                    break;

                case 'e':
                    generator.ErrorCorrectionLevel = options.Optarg[0];
                    break;

                case 'f':
                    generator.QRForeColor = System.Drawing.ColorTranslator.FromHtml(options.Optarg);
                    break;

                case 'b':
                    generator.QRBackColor = System.Drawing.ColorTranslator.FromHtml(options.Optarg);
                    break;

                case 'o':
                    saveFileName = options.Optarg;
                    break;
                }
            }

            // checks if payload is specified
            if (options.Argv.Length > options.Optind)
            {
                generator.Payload = options.Argv[options.Optind];
            }
            #endregion

            generator.refreshData();

            if (string.IsNullOrWhiteSpace(saveFileName))
            {
                Application.Run(generator);
            }
            else
            {
                generator.Save(saveFileName);
            }
        }
Exemple #24
0
        static int Main(string[] args)
        {
            string diffPath = "", xmlFilePath1 = "", xmlFilePath2 = "", rptFile1 = "", rptFile2 = "", rptFolder = "";
            int    ModelNumber = 1; // vychozi je ReportClientDocument

            Getopt opt = new Getopt("", args, "mp:f:s:d:");
            int    c;

            while ((c = opt.getopt()) != (-1))
            {
                switch ((char)c)
                {
                case 'p':
                    if (!File.Exists(opt.Optarg))
                    {
                        Console.Error.WriteLine("Error: Unknown diff application - Bad DiffUtilPath");
                        WriteUsage();
                        return((int)ExitCode.WrongDiffApp);
                    }
                    else
                    {
                        diffPath = opt.Optarg;
                    }
                    break;

                case 'f':
                    if (!File.Exists(opt.Optarg))
                    {
                        Console.Error.WriteLine("Error: Can't find RPT file - Bad RPTPath1");
                        WriteUsage();
                        return((int)ExitCode.WrongRptFile);
                    }
                    else
                    {
                        rptFile1 = opt.Optarg;
                    }
                    break;

                case 's':
                    if (!File.Exists(opt.Optarg))
                    {
                        Console.Error.WriteLine("Error: Can't find RPT file - Bad RPTPath2");
                        WriteUsage();
                        return((int)ExitCode.WrongRptFile);
                    }
                    else
                    {
                        rptFile2 = opt.Optarg;
                    }
                    break;

                case 'm':
                    // pokud je zadan prepinac m tak pouzijem model ReportDocument
                    ModelNumber = 0;
                    break;

                case 'd':
                    if (!Directory.Exists(opt.Optarg))
                    {
                        Console.Error.WriteLine("Error: Can't find RPT directory - Bad RPTDirectory");
                        WriteUsage();
                        return((int)ExitCode.WrongRptFile);
                    }
                    else
                    {
                        rptFolder = opt.Optarg;
                    }
                    break;

                default:
                    WriteUsage();
                    return((int)ExitCode.WrongArgs);
                }
            }

            try
            {
                if (File.Exists(rptFile1))
                {
                    Console.WriteLine("Using object model: \"" + ((ModelNumber == 0) ? "ReportDocument" : "ReportClientDocument") + "\"");
                    Console.WriteLine("Converting file: \"" + rptFile1 + "\"");
                    xmlFilePath1 = RptToXml.ConvertRptToXml(rptFile1, ModelNumber);
                    Console.WriteLine("File \"" + rptFile1 + "\" converted to \"" + xmlFilePath1 + "\"");
                }
                if (File.Exists(rptFile2))
                {
                    Console.WriteLine("Using object model: \"" + ((ModelNumber == 0) ? "ReportDocument" : "ReportClientDocument") + "\"");
                    Console.WriteLine("Converting file: \"" + rptFile2 + "\"");
                    xmlFilePath2 = RptToXml.ConvertRptToXml(rptFile2, ModelNumber);
                    Console.WriteLine("File \"" + rptFile2 + "\" converted to \"" + xmlFilePath2 + "\"");
                }
                if (Directory.Exists(rptFolder))
                {
                    string[] files = Directory.GetFiles(rptFolder, "*.rpt", SearchOption.AllDirectories);
                    string   xmlFilePath;
                    foreach (string file in files)
                    {
                        Console.WriteLine("Using object model: \"" + ((ModelNumber == 0) ? "ReportDocument" : "ReportClientDocument") + "\"");
                        Console.WriteLine("Converting file: \"" + file + "\"");
                        xmlFilePath = RptToXml.ConvertRptToXml(file, ModelNumber);
                        Console.WriteLine("File \"" + file + "\" converted to \"" + xmlFilePath + "\"");
                    }
                }
            }
            catch (Exception e)
            {
                Console.Error.WriteLine("Error: Convert to XML error");
                Console.Error.WriteLine(e);
                return((int)ExitCode.ConvertError);
            }
            if (File.Exists(diffPath) && (File.Exists(xmlFilePath1) || File.Exists(xmlFilePath2)))
            {
                Console.WriteLine("Starting diff application: \"" + diffPath + "\"");
                Process diffProc = Process.Start(diffPath, String.Format("\"{0}\" \"{1}\"", xmlFilePath1, xmlFilePath2));
                diffProc.WaitForExit();
                Console.WriteLine("Diff application exited");
                // delete xml files after closing diff application
                if (File.Exists(xmlFilePath1))
                {
                    Console.WriteLine("Deleting file: \"" + xmlFilePath1 + "\"");
                    File.Delete(xmlFilePath1);
                }
                if (File.Exists(xmlFilePath2))
                {
                    Console.WriteLine("Deleting file: \"" + xmlFilePath2 + "\"");
                    File.Delete(xmlFilePath2);
                }
            }

            return((int)ExitCode.Success);
        }
Exemple #25
0
        static void Main(string[] args)
        {
            string payloadFile = "";
            string ImageFile   = "";
            string outputFile  = "";
            string passphrase  = "";

            Banner();
            Getopt g = new Getopt("STX", args, "e:d:i:o:p:");
            int    c;

            while ((c = g.getopt()) != -1)
            {
                switch (c)
                {
                case 'e':
                    payloadFile = g.Optarg;
                    break;

                case 'd':
                    ImageFile = g.Optarg;
                    break;

                case 'i':
                    ImageFile = g.Optarg;
                    break;

                case 'o':
                    outputFile = g.Optarg;
                    break;

                case 'p':
                    passphrase = g.Optarg;
                    break;

                default:
                    Usage();
                    return;
                }
            }

            if (ImageFile == "")
            {
                Console.WriteLine("No image has been provided");
                Usage();
                return;
            }

            if (!File.Exists(ImageFile))
            {
                Console.WriteLine("{0} does not exists", ImageFile);
                return;
            }

            if (payloadFile == "")
            {
                string originalFileName = "";
                try
                {
                    byte[] hash = new byte[32];

                    byte[] data = StegaXKernel.Decode(ImageFile, ref originalFileName, passphrase, ref hash);

                    Console.WriteLine("Found {0}\tLength: {1} bytes\n", originalFileName, data.Length);

                    if (File.Exists(originalFileName))
                    {
                        Console.Write("{0} already exists!\nOverwrite (Y/N)?", originalFileName);
                        string answer = Console.ReadLine();
                        if (answer.ToUpper() != "Y")
                        {
                            Console.Write("Alternative Filename? ");
                            answer           = Console.ReadLine();
                            originalFileName = answer;
                        }
                    }
                    File.WriteAllBytes(originalFileName, data);
                    Console.WriteLine("{0} bytes written to disk", data.Length);
                    if (BitConverter.ToString(hash) == BitConverter.ToString(Crypto.ComputeHash(data)))
                    {
                        Console.WriteLine("Integrity Verification OK");
#if DEBUG
                        Console.WriteLine("Read CRC: {0}", BitConverter.ToString(hash).Replace("-", ""));
                        Console.WriteLine("Data CRC: {0}", BitConverter.ToString(Crypto.ComputeHash(data)).Replace("-", ""));
#endif
                    }
                    else
                    {
                        Console.WriteLine("Integrity Verification FAIL");
                        Console.WriteLine("Read CRC: {0}", BitConverter.ToString(hash).Replace("-", ""));
                        Console.WriteLine("Data CRC: {0}", BitConverter.ToString(Crypto.ComputeHash(data)).Replace("-", ""));
                    }
                }
                catch (System.Security.Cryptography.CryptographicException ex)
                {
                    Console.WriteLine("Cryptographic Exception: " + ex.Message);
                    Console.WriteLine("Incorrect Password?");
                    //throw;
                }
            }
            else
            {
                if (ImageFile != "" & outputFile != "")
                {
                    if (!File.Exists(payloadFile))
                    {
                        Console.WriteLine("{0} does not exists", payloadFile);
                        return;
                    }
                    try
                    {
                        Console.WriteLine("Encoding {0} into {1}", payloadFile, ImageFile);
                        Console.WriteLine("Output File: {0}", outputFile);
                        StegaXKernel.Encode(ImageFile, payloadFile, outputFile, passphrase);
                        Console.WriteLine("Done!");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }
                else
                {
                    Usage();
                    return;
                }
            }
        }
Exemple #26
0
        static void Main(string[] args)
        {
            var getopt = new Getopt(Assembly.GetExecutingAssembly().GetName().Name, args, "s:i:c:nadp")
            {
                Opterr = false
            };

            string input   = null;
            string culture = null;

            bool dontDeleteSet  = false;
            bool insertAll      = false;
            bool skipValidation = false;
            bool onlyPrepare    = false;

            string connString   = ConfigurationManager.ConnectionStrings["Gettext"].ConnectionString;
            string insertSP     = ConfigurationManager.AppSettings["SP.Insert"];
            string deleteSP     = ConfigurationManager.AppSettings["SP.Delete"];
            string getSP        = ConfigurationManager.AppSettings["SP.Get"];
            string tableName    = ConfigurationManager.AppSettings["Table.Name"];
            string tableCulture = ConfigurationManager.AppSettings["Table.Fields.Culture"];
            string tableKey     = ConfigurationManager.AppSettings["Table.Fields.Key"];
            string tableValue   = ConfigurationManager.AppSettings["Table.Fields.Value"];

            int option;

            while (-1 != (option = getopt.getopt()))
            {
                switch (option)
                {
                case 'i': input = getopt.Optarg; break;

                case 'c': culture = getopt.Optarg; break;

                case 'n': dontDeleteSet = true; break;

                case 's': connString = getopt.Optarg; break;

                case 'a': insertAll = true; break;

                case 'd': skipValidation = true; break;

                case 'p': onlyPrepare = true; break;

                default: PrintUsage(); return;
                }
            }

            if (input == null && !onlyPrepare)
            {
                PrintUsage();
                return;
            }

            if (connString == null || getSP == null || insertSP == null || deleteSP == null || tableName == null || tableKey == null || tableCulture == null || tableValue == null)
            {
                Console.Out.WriteLine("Ensure that connection string, table name, table fields, insert and delete stored procedures are set in app config.");
                Console.Out.WriteLine();
                Console.Out.WriteLine("Expected connection strings are:");
                Console.Out.WriteLine(" Gettext");
                Console.Out.WriteLine();
                Console.Out.WriteLine("Expected app settings are:");
                Console.Out.WriteLine(" SP.Get");
                Console.Out.WriteLine(" SP.Insert");
                Console.Out.WriteLine(" SP.Delete");
                Console.Out.WriteLine(" Table.Name");
                Console.Out.WriteLine(" Table.Fields.Key");
                Console.Out.WriteLine(" Table.Fields.Value");
                Console.Out.WriteLine(" Table.Fields.Culture");
                return;
            }

            try
            {
                using (var db = new DatabaseInterface(connString)
                {
                    GetSP = getSP,
                    DeleteSP = deleteSP,
                    InsertSP = insertSP,
                    CultureField = tableCulture,
                    KeyField = tableKey,
                    ValueField = tableValue,
                    TableName = tableName
                })
                {
                    db.Init();

                    // Check if table and sps exist
                    if (!skipValidation || onlyPrepare)
                    {
                        db.Prepare();
                    }

                    // If only prepare is set, do not use po file, just make sure everything is ready to use it later
                    if (onlyPrepare)
                    {
                        Console.Out.WriteLine("Table and stored procedures ready.");
                        db.Commit();
                        return;
                    }

                    // Delete previous resource set for the specified culture
                    if (!dontDeleteSet)
                    {
                        db.DeleteResourceSet(culture);
                    }

                    // Dump the file into the database
                    var requestor = new DatabaseParserRequestor(culture, db, insertAll);
                    new PoParser().Parse(new StreamReader(input), requestor);

                    db.Commit();
                }
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine("Exception in program: {0}\n{1}", ex.Message, ex.StackTrace);
            }
        }
Exemple #27
0
        static void Main(string[] args)
        {
            /* flags */
            bool foundOpt   = false;
            bool has_R_flag = false; /* restore flag */
            bool has_B_flag = false; /* backup flag */
            bool has_S_flag = false; /* source flag */
            bool has_D_flag = false; /* destination flag */
            bool has_Q_flag = false; /* quit flag */
            bool has_I_flag = false; /* inetpub flag */
            bool has_P_flag = false; /* inetpub flag */

            /* variables to hold options */
            string sqlServerName = null;
            string destDir       = null;
            string sourceDir     = null;
            string selectedOpt   = null;
            string inetpubDir    = null;
            string rhevpath      = null;

            /* others */
            int c;

            main m = new main();

            if (args.Length < 9)
            {
                m.usage();
                Environment.Exit(-1);
            }

            Getopt g = new Getopt("rhevUP", args, "d:i:rbs:u:n:p:h:q");

            while ((c = g.getopt()) != -1)
            {
                switch (c)
                {
                case 'd':
                    /* destination flag*/
                    foundOpt   = true;
                    has_D_flag = true;

                    /* setting value */
                    destDir = g.Optarg;
                    break;

                case 'r':
                    /* recover flag */
                    foundOpt   = true;
                    has_R_flag = true;

                    /* setting value */
                    selectedOpt = "restore";
                    break;

                case 'b':
                    /* backup flag */
                    foundOpt   = true;
                    has_B_flag = true;

                    /* setting value */
                    selectedOpt = "backup";
                    break;

                case 's':
                    /* source */
                    foundOpt   = true;
                    has_S_flag = true;

                    /* setting value */
                    sourceDir = g.Optarg;
                    break;

                case 'n':
                    /* SQL Server Name */
                    foundOpt = true;

                    /* setting */
                    sqlServerName = g.Optarg;
                    break;

                case 'q':
                    has_Q_flag = true;
                    foundOpt   = true;
                    break;

                case 'h':
                    m.usage();
                    break;

                case 'i':
                    has_I_flag = true;
                    inetpubDir = g.Optarg;
                    foundOpt   = true;
                    break;

                case 'p':
                    has_P_flag = true;
                    rhevpath   = g.Optarg;
                    foundOpt   = true;
                    break;

                default:
                    Console.WriteLine("getopt() returned " + c);
                    m.usage();
                    break;
                }
            }

            /* In case customer doesn't provide '-' argument, print usage */
            if (foundOpt != true)
            {
                m.usage();
            }

            if (has_P_flag == false)
            {
                Console.WriteLine("Cannot proceed, you must specify -p (path RHEVM files) option, aborting..");
                Console.WriteLine("Ex.: -p c:\\Program Files\\RedHat\\RHEVManager");
                Environment.Exit(-1);
            }

            if (has_I_flag == false)
            {
                Console.WriteLine("Cannot proceed, you must specify -i (wwwroot) option, aborting..");
                Console.WriteLine("Ex.: -i c:\\inetpub\\wwwroot");
                Environment.Exit(-1);
            }

            /* quit and restore flags are not compatible */
            if ((has_R_flag == true) && (has_Q_flag == true))
            {
                Console.WriteLine("Cannot use flags -r and -q together, aborting..");
                Environment.Exit(-1);
            }

            /* backup and restore are not compatible flags */
            if ((has_B_flag == true) && (has_R_flag == true))
            {
                Console.WriteLine("Cannot use flags -b and -r together, aborting..");
                Environment.Exit(-1);
            }

            /* destionation and source are not compatible flags */
            if ((has_D_flag == true) && (has_S_flag == true))
            {
                Console.WriteLine("Cannot use flags -d and -s together, aborting..");
                Environment.Exit(-1);
            }

            Run r = new Run();

            if (selectedOpt == "backup")
            {
                if (destDir == null)
                {
                    Console.WriteLine("using backup mode, -d must be specified");
                    Console.WriteLine("aborting...");
                    Environment.Exit(-1);
                }
                r.backupRHEV(sqlServerName, destDir, has_Q_flag, inetpubDir, rhevpath);
            }
            else if (selectedOpt == "restore")
            {
                if (sourceDir == null)
                {
                    Console.WriteLine("using restore mode, -s must be specified");
                    Console.WriteLine("aborting...");
                    Environment.Exit(-1);
                }

                r.restoreRHEV(sqlServerName, sourceDir, inetpubDir, rhevpath);
            }
            else
            {
                Console.WriteLine("You must select restore or backup option");
                Environment.Exit(0);
            }
        }
        public static void Main(string[] args)
        {
            int       c;
            MainClass main = new MainClass();

            LongOpt[] longopts = new LongOpt[] {
                new LongOpt("help", Argument.No, null, 'h'),
                new LongOpt("verbose", Argument.No, null, 'v'),
                new LongOpt("conf", Argument.Required, null, 'c'),
                new LongOpt("tag", Argument.No, null, 2),
                new LongOpt("parse", Argument.No, null, 3),
                new LongOpt("knows", Argument.No, null, 4),
                new LongOpt("spell", Argument.No, null, 'z')
            };
            Getopt g = new Getopt("DataTemple", args, "hvszc:I:P:O:T:i:p:t:", longopts);

            bool acted = false;
            List <PatternTemplateSource> dicta = new List <PatternTemplateSource>();

            string input    = null;
            string output   = null;
            string template = null;

            while ((c = g.getopt()) != -1)
            {
                switch (c)
                {
                case 1: {
                    Console.WriteLine("I see you have return in order set and that " +
                                      "a non-option argv element was just found " +
                                      "with the value '" + g.Optarg + "'");
                    break;
                }

                case 2: {
                    acted = true;
                    if (main.tagger == null)
                    {
                        Console.WriteLine("Use the -c option before --tag or --parse");
                        continue;
                    }
                    List <KeyValuePair <string, string> > tokens = main.tagger.TagString(input);
                    foreach (KeyValuePair <string, string> token in tokens)
                    {
                        Console.Write(token.Key + "/" + token.Value + " ");
                    }
                    Console.WriteLine("");
                    break;
                }

                case 3: {
                    acted = true;
                    if (main.parser == null)
                    {
                        Console.WriteLine("Use the -c option before --tag or --parse");
                        continue;
                    }
                    Console.WriteLine(main.parser.Parse(input));
                    break;
                }

                case 4: {
                    DictumMaker maker = new DictumMaker(main.basectx, "testing");
                    dicta.Add(maker.MakeDictum("%sentence %noun %is %adj", "@know %noun @HasProperty %adj @SubjectTense %is"));
                    dicta.Add(maker.MakeDictum("%sentence %event %attime", "@know %event @AtTime %attime"));
                    dicta.Add(maker.MakeDictum("%sentence %event %inall", "@know %event @InLocation %inall"));
                    dicta.Add(maker.MakeDictum("%sentence %noun %inall", "@know %noun @InLocation %inall"));
                    dicta.Add(maker.MakeDictum("%sentence %noun %is a %noun", "@know %noun1 @IsA %noun2 @SubjectTense %is"));
                    dicta.Add(maker.MakeDictum("%sentence %noun %will %verb1 * to %verb2 *", "@know %verbx1 @Subject %noun @SubjectTense %will %verb1 @ActiveObjects *1 @know %verbx2 @Subject %noun @SubjectTense %verb2 @ActiveObjects *2 @know %verbx2 @Condition %verbx1"));
                    break;
                }

                case 'v': {
                    main.verbose++;
                    break;
                }

                case 'h': {
                    Console.WriteLine("The documentation is currently at \n" + DOCS_URL);
                    break;
                }

                case 's': {
                    main.serialmode = true;
                    break;
                }

                case 'z': {
                    if (!main.initialized)
                    {
                        Console.WriteLine("Use the -c option before -z");
                        continue;
                    }

                    SpellingBeeWordComparer wordComparer = new SpellingBeeWordComparer(main.plugenv.GetConfigDirectory("datadirectory"));
                    main.basectx.Map["$Compare"] = wordComparer;
                    main.tryToRescueMatch        = new CorrectSpellingsRescueMatch(main.tryToRescueMatch, wordComparer, main.parser, 100);
                    break;
                }

                case 'c': {
                    main.Initialize(g.Optarg);
                    break;
                }

                case 'I': {
                    input = g.Optarg;
                    break;
                }

                case 'i': {
                    StreamReader file = new StreamReader(g.Optarg);
                    input = file.ReadToEnd();
                    break;
                }

                case 'P': {
                    if (!main.initialized)
                    {
                        Console.WriteLine("Use the -c option before -P");
                        continue;
                    }
                    Context       context = Interpreter.ParseCommands(main.basectx, g.Optarg);
                    IContinuation cont    = new Evaluator(100.0, ArgumentMode.ManyArguments, main, new NopCallable(), true);
                    cont.Continue(context, new NopCallable());

                    main.RunToEnd();
                    break;
                }

                case 'p': {
                    if (!main.initialized)
                    {
                        Console.WriteLine("Use the -c option before -p");
                        continue;
                    }
                    foreach (string line in File.ReadAllLines(g.Optarg))
                    {
                        if (line.Trim().Length == 0 || line.Trim().StartsWith("#"))
                        {
                            continue;
                        }
                        Context       context = Interpreter.ParseCommands(main.basectx, line);
                        IContinuation cont    = new Evaluator(100.0, ArgumentMode.ManyArguments, main, new NopCallable(), true);
                        cont.Continue(context, new NopCallable());

                        main.RunToEnd();
                    }
                    break;
                }

                case 'T': {
                    if (!main.initialized)
                    {
                        Console.WriteLine("Use the -c option before -T");
                        continue;
                    }
                    template = g.Optarg;
                    if (template != null && output != null)
                    {
                        DictumMaker maker = new DictumMaker(main.basectx, "testing");
                        dicta.Add(maker.MakeDictum(template, output));

                        template = output = null;
                    }
                    break;
                }

                case 'O': {
                    if (!main.initialized)
                    {
                        Console.WriteLine("Use the -c option before -O");
                        continue;
                    }

                    output = g.Optarg;
                    if (template != null && output != null)
                    {
                        DictumMaker maker = new DictumMaker(main.basectx, "testing");
                        dicta.Add(maker.MakeDictum(template, output));

                        template = output = null;
                    }
                    break;
                }

                case 't': {
                    if (!main.initialized)
                    {
                        Console.WriteLine("Use the -c option before -t");
                        continue;
                    }

                    bool nextTemplate = true;
                    foreach (string line in File.ReadAllLines(g.Optarg))
                    {
                        string trimline = line.Trim();
                        if (trimline.Length == 0 || trimline.StartsWith("#"))
                        {
                            continue;
                        }

                        if (nextTemplate)
                        {
                            template     = trimline;
                            nextTemplate = false;
                        }
                        else
                        {
                            output = trimline;
                            DictumMaker maker = new DictumMaker(main.basectx, "testing");
                            dicta.Add(maker.MakeDictum(template, output));
                            nextTemplate = true;
                        }
                    }

                    template = output = null;
                    break;
                }
                }
            }

            if (dicta.Count != 0)
            {
                main.DoMatching(dicta, input);
            }
            else if (!acted)
            {
                Console.WriteLine("Nothing to do.  Add -tag, -parse, or -t or -T and -O");
            }
        }
Exemple #29
0
        private static bool ParseOptions([NotNull] string[] args, [NotNull] out Options options, [NotNull] out StringBuilder message)
        {
            options = new Options();
            message = new StringBuilder();

            try
            {
                var getopt = new Getopt(Assembly.GetExecutingAssembly().GetName().Name, args, SOpts, LOpts)
                {
                    Opterr = false
                };
                int option;
                while ((option = getopt.getopt()) != -1)
                {
                    switch (option)
                    {
                    case 1:
                        options.InputFiles.Add(getopt.Optarg);
                        break;

                    case 'D':
                        options.InputDirs.Add(getopt.Optarg);
                        break;

                    case 'r':
                        options.Recursive = true;
                        break;

                    case 'x':
                        options.Excludes.Add(getopt.Optarg);
                        break;

                    case 'd':
                        options.OutputFile = $"{getopt.Optarg}.pot";
                        break;

                    case 'b':
                        options.Backup = true;
                        break;

                    case 'o':
                        options.OutputFile = getopt.Optarg;
                        break;

                    case 'm':
                        options.Overwrite = false;
                        break;

                    case 'C':
                        options.PreserveComments = true;
                        break;

                    case 'v':
                        options.Verbose = true;
                        break;

                    case 'h':
                        options.ShowUsage = true;
                        return(true);

                    case ':':
                        message.AppendLine(string.Format(Tr._("Option '{0}' requires an argument"), getopt.OptoptStr));
                        return(false);

                    case '?':
                        message.AppendLine(string.Format(Tr._("Invalid option '{0}'"), getopt.OptoptStr));
                        return(false);

                    default:
                        ShowUsage();
                        return(false);
                    }
                }

                if (getopt.Opterr)
                {
                    message.AppendLine();
                    message.Append(Tr._("Error in the command line options. Use -h to display the options usage."));
                    return(false);
                }
            }
            catch (Exception e)
            {
                message.Append(e.Message);
                return(false);
            }

            return(true);
        }
Exemple #30
0
        static void Main(string[] args)
        {
#if true        // Getopt sample
            Getopt g = new Getopt("testprog", args, "ab:c::d");

            int    c;
            string arg;
            while ((c = g.getopt()) != -1)
            {
                switch (c)
                {
                case 'a':
                case 'd':
                    Console.WriteLine("You picked " + (char)c);
                    break;

                case 'b':
                case 'c':
                    arg = g.Optarg;
                    Console.WriteLine("You picked " + (char)c +
                                      " with an argument of " +
                                      ((arg != null) ? arg : "null"));
                    break;

                case '?':
                    break;                             // getopt() already printed an error

                default:
                    Console.WriteLine("getopt() returned " + c);
                    break;
                }
            }

            Console.WriteLine("ÒѾ­Íê³É²âÊÔ");
#else           // Getopt/LongOpt docu sample
            int       c;
            String    arg;
            LongOpt[] longopts = new LongOpt[3];

            StringBuilder sb = new StringBuilder();
            longopts[0] = new LongOpt("help", Argument.No, null, 'h');
            longopts[1] = new LongOpt("outputdir", Argument.Required, sb, 'o');
            longopts[2] = new LongOpt("maximum", Argument.Optional, null, 2);

            Getopt g = new Getopt("testprog", args, "-:bc::d:hW;", longopts);
            g.Opterr = false;             // We'll do our own error handling

            while ((c = g.getopt()) != -1)
            {
                switch (c)
                {
                case 0:
                    arg = g.Optarg;
                    Console.WriteLine("Got long option with value '" +
                                      (char)int.Parse(sb.ToString())
                                      + "' with argument " +
                                      ((arg != null) ? arg : "null"));
                    break;

                case 1:
                    Console.WriteLine("I see you have return in order set and that " +
                                      "a non-option argv element was just found " +
                                      "with the value '" + g.Optarg + "'");
                    break;

                case 2:
                    arg = g.Optarg;
                    Console.WriteLine("I know this, but pretend I didn't");
                    Console.WriteLine("We picked option " +
                                      longopts[g.Longind].Name +
                                      " with value " +
                                      ((arg != null) ? arg : "null"));
                    break;

                case 'b':
                    Console.WriteLine("You picked plain old option " + (char)c);
                    break;

                case 'c':
                case 'd':
                    arg = g.Optarg;
                    Console.WriteLine("You picked option '" + (char)c +
                                      "' with argument " +
                                      ((arg != null) ? arg : "null"));
                    break;

                case 'h':
                    Console.WriteLine("I see you asked for help");
                    break;

                case 'W':
                    Console.WriteLine("Hmmm. You tried a -W with an incorrect long " +
                                      "option name");
                    break;

                case ':':
                    Console.WriteLine("Doh! You need an argument for option " +
                                      (char)g.Optopt);
                    break;

                case '?':
                    Console.WriteLine("The option '" + (char)g.Optopt +
                                      "' is not valid");
                    break;

                default:
                    Console.WriteLine("getopt() returned " + c);
                    break;
                }
            }

            for (int i = g.Optind; i < args.Length; i++)
            {
                Console.WriteLine("Non option argv element: " + args[i] + "\n");
            }
#endif
        }