public static void LoadCurrentTheme()
        {
            StreamReader TextFile = new StreamReader(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + @"\ThemeConfig.txt");
            string       CurrentLine;
            int          IndexOfColour;

            while ((CurrentLine = TextFile.ReadLine()) != null)
            {
                IndexOfColour = CurrentLine.IndexOf("#");

                if (CurrentLine.Contains("TitleBarColor: "))
                {
                    ThemeMethods.SetTopBarThemeManual(ColorTranslator.FromHtml(CurrentLine.Substring(IndexOfColour)));
                }
                else if (CurrentLine.Contains("SideBarColor: "))
                {
                    ThemeMethods.SetSideBarThemeManual(ColorTranslator.FromHtml(CurrentLine.Substring(IndexOfColour)));
                }
                else if (CurrentLine.Contains("AccentColor: "))
                {
                    ThemeMethods.SetThemeAccentManual(ColorTranslator.FromHtml(CurrentLine.Substring(IndexOfColour)));
                }
            }

            TextFile.Dispose();
        }
Beispiel #2
0
        AsmBlock ParseBlockWithSource()
        {
            int minLine = ParseSourceLineNumber(CurrentLine);

            string lastSourceLine = null;

            while (CurrentLine[0] == ';')
            {
                lastSourceLine = CurrentLine;
                NextLine();
            }

            int maxLine = ParseSourceLineNumber(lastSourceLine);

            AsmBlock block = new AsmBlock {
                Range = new LineRange(minLine, maxLine)
            };

            SkipEmptyLines();

            Debug.Assert(CurrentLine[0] != ';');
            Debug.Assert(!CurrentLine.Contains(FunctionEndID));

            List <AsmInstruction> assembly = new List <AsmInstruction>();

            while (!IsEndOfBlock(CurrentLine))
            {
                assembly.Add(ParseInstruction(CurrentLine));
                NextLine();
            }

            block.Instructions = assembly.ToArray();
            return(block);
        }
Beispiel #3
0
        public void SelectColorAndSave(string ValueToReplace)
        {
            DialogResult result = CD1.ShowDialog();

            // See if user pressed ok.

            if (result != DialogResult.OK)
            {
                return;
            }
            // Set form background to the selected color.
            //this.BackColor = colorDialog1.Color;
            string HexColorCode      = (CD1.Color.ToArgb() & 0x00FFFFFF).ToString("X6");
            int    DecimalColorCode  = Convert.ToInt32(HexColorCode, 16);
            string CurrentCommonFile = "";

            using (StreamReader reader = new StreamReader(new FileStream(CommonFilePath, FileMode.Open)))
            {
                string CurrentLine;
                while ((CurrentLine = reader.ReadLine()) != null)
                {
                    if (CurrentLine.Contains(ValueToReplace))
                    {
                        CurrentCommonFile += ValueToReplace + "\t" + DecimalColorCode + Environment.NewLine;
                    }
                    else
                    {
                        CurrentCommonFile += CurrentLine + Environment.NewLine;
                    }
                }
            }
            File.WriteAllText(CommonFilePath, CurrentCommonFile);
        }
Beispiel #4
0
        public void LoadCurrentTheme()
        {
            StreamReader TextFile = new StreamReader(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + @"\OptionsConfig.txt");
            string       CurrentLine;
            int          IndexOfAnswer;

            while ((CurrentLine = TextFile.ReadLine()) != null)
            {
                IndexOfAnswer  = CurrentLine.LastIndexOf(" ");
                IndexOfAnswer += 1;

                if (CurrentLine.Contains("Opacity: "))
                {
                    string CurrentOpacity = CurrentLine.Substring(IndexOfAnswer);
                    TinyUI_Nud_Opacity.Value = Convert.ToDecimal(CurrentOpacity);
                }

                if (CurrentLine.Contains("AutohookEnabled: "))
                {
                    string Result = CurrentLine.Substring(IndexOfAnswer);
                    if (Result == "Y")
                    {
                        Btn_AutoHook_Click(null, null);
                    }
                }

                if (CurrentLine.Contains("AutohookDelay: "))
                {
                    string Result = CurrentLine.Substring(IndexOfAnswer);
                    TinyUI_Nud_AutoHookInterval.Value = Convert.ToDecimal(Result);
                }
            }

            TextFile.Dispose();
        }
Beispiel #5
0
        private void ReadSegment(string Name, Segment Parent, StreamReader Reader)
        {
            Segment Current = new Segment(Name, Parent);

            if (Parent != null)
            {
                Parent.Children.Add(Current);
            }
            Current.Index = this.Segments.Count;
            this.Segments.Add(Current);
            Reader.ReadLine(); // Opening Bracket
            object[] Tags = new object[2];
            string   CurrentLine;

            while (true)
            {
                CurrentLine = Reader.ReadLine();
                if (CurrentLine.Contains("OFFSET"))
                {
                    string[] Parts  = CleanStringArray(CurrentLine.Split(_WhiteSpaces));
                    Vertex   Offset = new Vertex(Convert.ToSingle(Parts[1]) * 100, Convert.ToSingle(Parts[2]) * 100, Convert.ToSingle(Parts[3]) * 100);
                    if (Parent != null)
                    {
                        Parent.BoneLength = Operations.GetDistance(new Vertex(0, 0, 0), Offset);
                    }
                    Tags[0] = Offset;
                }
                else if (CurrentLine.Contains("CHANNELS"))
                {
                    string[]      Parts    = CleanStringArray(CurrentLine.Split(_WhiteSpaces));
                    List <string> Channels = new List <string>();
                    for (int i = 2; i < Parts.Length; i++)
                    {
                        Channels.Add(Parts[i]);
                    }
                    Tags[1] = Channels;
                }
                else if (CurrentLine.Contains("JOINT"))
                {
                    string[] Parts = CleanStringArray(CurrentLine.Split(_WhiteSpaces));
                    ReadSegment(Parts[1], Current, Reader);
                }
                else if (CurrentLine.Contains("End Site"))
                {
                    Reader.ReadLine();
                    CurrentLine = Reader.ReadLine();
                    string[] Parts  = CleanStringArray(CurrentLine.Split(_WhiteSpaces));
                    Vertex   Offset = new Vertex(Convert.ToSingle(Parts[1]), Convert.ToSingle(Parts[2]), Convert.ToSingle(Parts[3]));
                    Current.BoneLength = Operations.GetDistance(new Vertex(0, 0, 0), Offset);
                    Reader.ReadLine();
                }
                else if (CurrentLine.Contains("}"))
                {
                    break;
                }
            }
            Current.Tag = Tags;
        }
        //--------------------------------------------------------------------------------------------------
        // Procedure ReadFile
        //
        //   Functie     : read a file and store it in the global array 'gProgram'
        //
        //   Input       : Geen
        //
        //   Output      : Geen
        //--------------------------------------------------------------------------------------------------
        public void ReadFile(string sInputFilename)
        {
            try
            {
                StreamReader sr = new StreamReader(sInputFilename);
                ngFileNum = File.ReadAllLines(sInputFilename).Length;
                gProgram  = new string[ngFileNum];
                string allLines   = File.ReadAllText(sInputFilename);
                int    subcounter = 0;

                int    nFirstEnter = 0;
                int    nLine       = 0;
                string sInputLine  = String.Empty;

                gNbProgramLines = 0;
                LinesConverted  = 0;


                //-- Open and read selected file ------------------------------------------------------------------------------------

                for (int i = 0; i < ngFileNum; i++)
                {
                    gProgram[i] = sr.ReadLine();
                }

                //-- Set submain indexes -------------------------------------------------------------------------------------------
                if (!allLines.Contains(';'))
                {
                    submains = CountSubs(allLines);
                    submainI = new Dictionary <int, int>();

                    for (int i = 0; i < submains - 1; i++)
                    {
                        int index = CurrentLineIndex;
                        for (int n = 0; n < ngFileNum; n++)
                        {
                            CurrentLineIndex++;
                            if (CurrentLine.Contains("%") || CurrentLine.Contains("$PROGIN") || CurrentLine.Contains("DFS,P"))
                            {
                                break;
                            }
                        }

                        submainI.Add(index, CurrentLineIndex);
                    }
                }

                gNbProgramLines  = ngFileNum - 1;
                CurrentLineIndex = 0;
                sr.Close();
            }
            catch (System.Exception excep)
            {
                MessageBox.Show(excep.Message);
            }
        }
Beispiel #7
0
        /// <summary>
        /// Process the current line and extract out values
        /// </summary>
        private void ProcessLine()
        {
            // Comment
            if (CurrentLine.StartsWith(";"))
            {
                KeyValuePair = null;
                RowType      = IniRowType.Comment;
            }

            // Section
            else if (CurrentLine.StartsWith("[") && CurrentLine.EndsWith("]"))
            {
                KeyValuePair = null;
                RowType      = IniRowType.SectionHeader;
                Section      = CurrentLine.TrimStart('[').TrimEnd(']');
            }

            // KeyValuePair
            else if (CurrentLine.Contains("="))
            {
                // Split the line by '=' for key-value pairs
                string[] data = CurrentLine.Split('=');

                // If the value field contains an '=', we need to put them back in
                string key   = data[0].Trim();
                string value = string.Join("=", data.Skip(1)).Trim();

                KeyValuePair = new KeyValuePair <string, string>(key, value);
                RowType      = IniRowType.KeyValue;
            }

            // Empty
            else if (string.IsNullOrEmpty(CurrentLine))
            {
                KeyValuePair = null;
                CurrentLine  = string.Empty;
                RowType      = IniRowType.None;
            }

            // Invalid
            else
            {
                KeyValuePair = null;
                RowType      = IniRowType.Invalid;

                if (ValidateRows)
                {
                    throw new InvalidDataException($"Invalid INI row found, cannot continue: {CurrentLine}");
                }
            }
        }
Beispiel #8
0
 public string GetValueFromCommon(string ValueToGet)
 {
     using (StreamReader reader = new StreamReader(new FileStream(CommonFilePath, FileMode.Open)))
     {
         string CurrentLine;
         while ((CurrentLine = reader.ReadLine()) != null)
         {
             if (CurrentLine.Contains(ValueToGet))
             {
                 string[] CurrentLineSplit = CurrentLine.Split('\t');
                 return(CurrentLineSplit[1]);
             }
         }
     }
     return("ERROR");
 }
Beispiel #9
0
        AsmBlock ParseBlockAssembly()
        {
            AsmBlock block = new AsmBlock {
                Range = LineRange.InvalidRange
            };

            List <AsmInstruction> assembly = new List <AsmInstruction>();

            while (!CurrentLine.Contains(FunctionEndID))
            {
                assembly.Add(ParseInstruction(CurrentLine));
                NextLine();
            }

            block.Instructions = assembly.ToArray();
            return(block);
        }
Beispiel #10
0
        /// <summary>
        /// To be used by mod loader mods. Loads the current theme properties for the mod loader configurator.
        /// </summary>
        public static (Color, Color, Color) Load_Theme_Configurator()
        {
            // Colours;
            Color SidebarColor = new Color();
            Color TopBarColor  = new Color();
            Color AccentColor  = new Color();

            try
            {
                // Load Configurator Theme
                string       Save_Seting_Path = File.ReadAllText(Environment.CurrentDirectory + "\\Mod_Loader_Config.txt") + @"\Mod-Loader-Config\\ThemeConfig.txt";
                StreamReader TextFile         = new StreamReader(Save_Seting_Path);

                string CurrentLine;
                int    IndexOfColour;

                while ((CurrentLine = TextFile.ReadLine()) != null)
                {
                    IndexOfColour = CurrentLine.IndexOf("#");

                    if (CurrentLine.Contains("TitleBarColor: "))
                    {
                        SidebarColor = ColorTranslator.FromHtml(CurrentLine.Substring(IndexOfColour));
                    }
                    else if (CurrentLine.Contains("SideBarColor: "))
                    {
                        TopBarColor = ColorTranslator.FromHtml(CurrentLine.Substring(IndexOfColour));
                    }
                    else if (CurrentLine.Contains("AccentColor: "))
                    {
                        AccentColor = ColorTranslator.FromHtml(CurrentLine.Substring(IndexOfColour));
                    }
                }

                TextFile.Dispose();
                return(SidebarColor, TopBarColor, AccentColor);
            }
            catch
            {
                SidebarColor = ColorTranslator.FromHtml("#283540");
                TopBarColor  = ColorTranslator.FromHtml("#22292E");
                AccentColor  = ColorTranslator.FromHtml("#3F51B5");
                return(SidebarColor, TopBarColor, AccentColor);
            }
        }
Beispiel #11
0
        AsmFunction ParseFunction()
        {
            AsmFunction function = ParseFunctionSignature(CurrentLine);

            NextLine();
            List <AsmBlock> blocks = new List <AsmBlock>();

            while (!CurrentLine.Contains(FunctionEndID))
            {
                blocks.Add(ParseBlock());
            }

            function.Blocks = blocks.ToArray();
            Array.Sort(function.Blocks);

            function.Range = new LineRange(function.Blocks[0].Range.Min,
                                           function.Blocks[function.Blocks.Length - 1].Range.Max);
            return(function);
        }
        public void CreateOidListing()
        {
            OidsListing = new ListOidEnt();

            FileStream fs = null;

            try
            {
                fs = new FileStream(MibFile, FileMode.Open, FileAccess.Read);
                StreamReader sr = new StreamReader(fs);

                MovePointerToStart(sr);

                while (sr.Peek() != -1)
                {
                    if (!string.IsNullOrEmpty(CurrentLine) && !CurrentLine.Contains("-- XREF:"))
                    {
                        SetOidType(CurrentLine);
                        BuildOidObject(sr, CurrentLine);
                    }
                    else
                    {
                        CurrentLine = sr.ReadLine().Trim();
                    }
                }
            }
            catch (FileNotFoundException fe) { GetLastError = fe.JoinAllErrorMessages(); }
            catch (DirectoryNotFoundException fe) { GetLastError = fe.JoinAllErrorMessages(); }
            catch (IOException e) { GetLastError = e.JoinAllErrorMessages(); }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                }
            }
        }
Beispiel #13
0
        //---------------------------------------------------------------------

        protected override IInputParameters Parse()
        {
            ReadLandisDataVar();

            InputParameters parameters = new InputParameters(SpeciesDataset.Count);

            InputVar <int> timestep = new InputVar <int>("Timestep");

            ReadVar(timestep);
            parameters.Timestep = timestep.Value;

            const string  LocalVariables          = "LocalVariables";
            const string  DerivedLocalVariables   = "DerivedLocalVariables";
            const string  NeighborhoodVariables   = "NeighborhoodVariables";
            const string  ClimateVariables        = "ClimateVariables";
            const string  DistanceVariables       = "DistanceVariables";
            const string  SpeciesModels           = "SpeciesModels";
            const string  LocalVarMapFileNames    = "LocalVarMapFileNames";
            const string  NeighborVarMapFileNames = "NeighborVarMapFileNames";
            const string  ClimateVarMapFileNames  = "ClimateVarMapFileNames";
            const string  DistanceVarMapFileNames = "DistanceVarMapFileNames";
            const string  SpeciesMapFileName      = "SpeciesMapFileNames";
            const string  LogFile             = "LogFile";
            const string  SpeciesLogFileNames = "SpeciesLogFileNames";
            List <string> keywordList         = new List <string> {
                LocalVariables, DerivedLocalVariables, NeighborhoodVariables, ClimateVariables, DistanceVariables, SpeciesModels, LocalVarMapFileNames, NeighborVarMapFileNames, ClimateVarMapFileNames, DistanceVarMapFileNames, SpeciesMapFileName, LogFile, SpeciesLogFileNames
            };

            if (ReadOptionalName(LocalVariables))
            {
                InputVar <string> speciesName = new InputVar <string>("Species");

                Dictionary <string, int> lineNumbers = new Dictionary <string, int>();

                InputVar <string> mapName    = new InputVar <string>("Map Name");
                InputVar <string> forestType = new InputVar <string>("Forest Type");
                InputVar <string> ageKeyword = new InputVar <string>("Age Keyword");
                InputVar <int>    minAge     = new InputVar <int>("Min Age");
                InputVar <int>    maxAge     = new InputVar <int>("Max Age");

                lineNumbers.Clear();
                Dictionary <string, int> forestTypeLineNumbers = new Dictionary <string, int>();


                const string nameDelimiter = "->";  // delimiter that separates map name and forest type

                IMapDefinition mapDefn = null;

                while (!AtEndOfInput && !keywordList.Contains(CurrentName))
                {
                    StringReader currentLine = new StringReader(CurrentLine);

                    //  If the current line has the delimiter, then read the map
                    //  name.
                    if (CurrentLine.Contains(nameDelimiter))
                    {
                        ReadValue(mapName, currentLine);
                        CheckForRepeatedName(mapName.Value, "map name", lineNumbers);

                        mapDefn      = new MapDefinition();
                        mapDefn.Name = mapName.Value;
                        parameters.ReclassMaps.Add(mapDefn);

                        TextReader.SkipWhitespace(currentLine);
                        string word = TextReader.ReadWord(currentLine);
                        if (word != nameDelimiter)
                        {
                            throw NewParseException("Expected \"{0}\" after the map name {1}.",
                                                    nameDelimiter, mapName.Value.String);
                        }

                        forestTypeLineNumbers.Clear();
                    }
                    else
                    {
                        //  If there is no name delimiter and we don't have the
                        //  name for the first map yet, then it's an error.
                        if (mapDefn == null)
                        {
                            throw NewParseException("Expected a line with map name followed by \"{0}\"", nameDelimiter);
                        }
                    }

                    ReadValue(forestType, currentLine);
                    CheckForRepeatedName(forestType.Value, "forest type",
                                         forestTypeLineNumbers);

                    IForestType currentForestType = new ForestType(SpeciesDataset.Count);
                    currentForestType.Name = forestType.Value;
                    mapDefn.ForestTypes.Add(currentForestType);

                    // Read the age ranges for the species:
                    ReadValue(ageKeyword, currentLine);
                    if (ageKeyword.Value == "All")
                    {
                        currentForestType.MinAge = 0;
                        int maxAgeAllSpecies = 0;
                        foreach (ISpecies species in PlugIn.ModelCore.Species)
                        {
                            if (species.Longevity > maxAgeAllSpecies)
                            {
                                maxAgeAllSpecies = species.Longevity;
                            }
                        }
                        currentForestType.MaxAge = maxAgeAllSpecies;
                    }
                    else
                    {
                        //ReadValue(minAge, currentLine);
                        currentForestType.MinAge = Convert.ToInt32(ageKeyword.Value);

                        TextReader.SkipWhitespace(currentLine);
                        string currentWord = TextReader.ReadWord(currentLine);
                        if (currentWord != "to")
                        {
                            StringBuilder message = new StringBuilder();
                            message.AppendFormat("Expected \"to\" after the minimum age ({0})",
                                                 minAge.Value.String);
                            if (currentWord.Length > 0)
                            {
                                message.AppendFormat(", but found \"{0}\" instead", currentWord);
                            }
                            throw NewParseException(message.ToString());
                        }

                        ReadValue(maxAge, currentLine);
                        currentForestType.MaxAge = maxAge.Value;
                    }
                    //  Read species for forest types

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

                    TextReader.SkipWhitespace(currentLine);
                    while (currentLine.Peek() != -1)
                    {
                        ReadValue(speciesName, currentLine);
                        string name = speciesName.Value.Actual;
                        bool   negativeMultiplier = name.StartsWith("-");
                        if (negativeMultiplier)
                        {
                            name = name.Substring(1);
                            if (name.Length == 0)
                            {
                                throw new InputValueException(speciesName.Value.String,
                                                              "No species name after \"-\"");
                            }
                        }
                        if (name == "All")
                        {
                            foreach (ISpecies species in PlugIn.ModelCore.Species)
                            {
                                speciesNames.Add(species.Name);
                                currentForestType[species.Index] = 1;
                            }
                        }
                        else if (name == "None")
                        {
                            foreach (ISpecies species in PlugIn.ModelCore.Species)
                            {
                                speciesNames.Add(species.Name);
                                currentForestType[species.Index] = 0;
                            }
                        }
                        else
                        {
                            ISpecies species = GetSpecies(new InputValue <string>(name, speciesName.Value.String));
                            if (speciesNames.Contains(species.Name))
                            {
                                throw NewParseException("The species {0} appears more than once.", species.Name);
                            }
                            speciesNames.Add(species.Name);
                            currentForestType[species.Index] = negativeMultiplier ? -1 : 1;
                        }

                        TextReader.SkipWhitespace(currentLine);
                    }
                    if (speciesNames.Count == 0)
                    {
                        throw NewParseException("At least one species is required.");
                    }

                    GetNextLine();
                }
            }
            if (ReadOptionalName(DerivedLocalVariables))
            {
                Dictionary <string, int> lineNumbers = new Dictionary <string, int>();
                lineNumbers.Clear();
                InputVar <string> derVarName    = new InputVar <string>("Derived Variable Name");
                InputVar <string> derVarFormula = new InputVar <string>("Derived Variable Formula");
                const string      nameDelimiter = "->"; // delimiter that separates map name and forest type
                List <string>     formulaSymbol = new List <string>(new string[] { "+", "-", "*" });

                IVariableDefinition varDefn = null;
                while (!AtEndOfInput && !keywordList.Contains(CurrentName))
                {
                    StringReader currentLine = new StringReader(CurrentLine);

                    ReadValue(derVarName, currentLine);
                    CheckForRepeatedName(derVarName.Value, "var name", lineNumbers);

                    varDefn      = new VariableDefinition();
                    varDefn.Name = derVarName.Value;

                    TextReader.SkipWhitespace(currentLine);
                    string word = TextReader.ReadWord(currentLine);
                    if (word != nameDelimiter)
                    {
                        throw NewParseException("Expected \"{0}\" after the map name {1}.",
                                                nameDelimiter, derVarName.Value.String);
                    }

                    TextReader.SkipWhitespace(currentLine);
                    string variable = TextReader.ReadWord(currentLine);
                    varDefn.Variables.Add(variable);
                    while (currentLine.Peek() != -1)
                    {
                        TextReader.SkipWhitespace(currentLine);
                        string op = TextReader.ReadWord(currentLine);
                        if (op == "")
                        {
                            break;
                        }
                        varDefn.Operators.Add(op);

                        TextReader.SkipWhitespace(currentLine);
                        variable = TextReader.ReadWord(currentLine);
                        varDefn.Variables.Add(variable);
                    }
                    parameters.DerivedVars.Add(varDefn);

                    GetNextLine();
                }
            }
            if (ReadOptionalName(NeighborhoodVariables))
            {
                // Read Neighborhood Variables
                Dictionary <string, int> lineNumbers = new Dictionary <string, int>();
                lineNumbers.Clear();
                InputVar <string> neighborVarName = new InputVar <string>("Neighbor Variable Name");
                InputVar <string> localVarName    = new InputVar <string>("Local Variable Name");
                InputVar <int>    neighborRadius  = new InputVar <int>("Neighbor Radius");
                InputVar <string> transform       = new InputVar <string>("Transform");

                INeighborVariableDefinition neighborVarDefn = null;
                while (!AtEndOfInput && !keywordList.Contains(CurrentName))
                {
                    StringReader currentLine = new StringReader(CurrentLine);

                    ReadValue(neighborVarName, currentLine);
                    CheckForRepeatedName(neighborVarName.Value, "var name", lineNumbers);

                    neighborVarDefn      = new NeighborVariableDefinition();
                    neighborVarDefn.Name = neighborVarName.Value;

                    ReadValue(localVarName, currentLine);
                    neighborVarDefn.LocalVariable = localVarName.Value;

                    ReadValue(neighborRadius, currentLine);
                    neighborVarDefn.NeighborRadius = neighborRadius.Value;

                    ReadValue(transform, currentLine);
                    neighborVarDefn.Transform = transform.Value;

                    parameters.NeighborVars.Add(neighborVarDefn);
                    GetNextLine();
                }
            }
            if (ReadOptionalName(ClimateVariables))
            {
                // Read Climate Variables
                Dictionary <string, int> lineNumbers = new Dictionary <string, int>();
                lineNumbers.Clear();
                InputVar <string> climateVarName        = new InputVar <string>("Climate Variable Name");
                InputVar <string> climateLibraryVarName = new InputVar <string>("Climate Library Variable Name");
                InputVar <string> sourceName            = new InputVar <string>("Source Name");
                InputVar <string> varYear   = new InputVar <string>("Variable Year");
                InputVar <int>    minMonth  = new InputVar <int>("Min Month");
                InputVar <int>    maxMonth  = new InputVar <int>("Max Month");
                InputVar <string> transform = new InputVar <string>("Tranformation");

                IClimateVariableDefinition climateVarDefn = null;
                while (!AtEndOfInput && !keywordList.Contains(CurrentName))
                {
                    StringReader currentLine = new StringReader(CurrentLine);
                    ReadValue(climateVarName, currentLine);
                    CheckForRepeatedName(climateVarName.Value, "var name", lineNumbers);

                    climateVarDefn      = new ClimateVariableDefinition();
                    climateVarDefn.Name = climateVarName.Value;

                    ReadValue(varYear, currentLine);
                    climateVarDefn.Year = varYear.Value;

                    ReadValue(minMonth, currentLine);
                    climateVarDefn.MinMonth = minMonth.Value;

                    TextReader.SkipWhitespace(currentLine);
                    string currentWord = TextReader.ReadWord(currentLine);
                    if (currentWord != "to")
                    {
                        StringBuilder message = new StringBuilder();
                        message.AppendFormat("Expected \"to\" after the minimum month ({0})",
                                             minMonth.Value.String);
                        if (currentWord.Length > 0)
                        {
                            message.AppendFormat(", but found \"{0}\" instead", currentWord);
                        }
                        throw NewParseException(message.ToString());
                    }

                    ReadValue(maxMonth, currentLine);
                    climateVarDefn.MaxMonth = maxMonth.Value;

                    ReadValue(sourceName, currentLine);
                    climateVarDefn.SourceName = sourceName.Value;

                    ReadValue(climateLibraryVarName, currentLine);
                    climateVarDefn.ClimateLibVariable = climateLibraryVarName.Value;

                    ReadValue(transform, currentLine);
                    climateVarDefn.Transform = transform.Value;

                    parameters.ClimateVars.Add(climateVarDefn);
                    GetNextLine();
                }
            }
            if (ReadOptionalName(DistanceVariables))
            {
                // Read Distance Variables
                Dictionary <string, int> lineNumbers = new Dictionary <string, int>();
                lineNumbers.Clear();
                InputVar <string> distanceVarName = new InputVar <string>("Distance Variable Name");
                InputVar <string> localVarName    = new InputVar <string>("Local Variable Name");
                InputVar <string> transform       = new InputVar <string>("Transform");

                IDistanceVariableDefinition distanceVarDefn = null;
                while (!AtEndOfInput && !keywordList.Contains(CurrentName))
                {
                    StringReader currentLine = new StringReader(CurrentLine);

                    ReadValue(distanceVarName, currentLine);
                    CheckForRepeatedName(distanceVarName.Value, "var name", lineNumbers);

                    distanceVarDefn      = new DistanceVariableDefinition();
                    distanceVarDefn.Name = distanceVarName.Value;

                    ReadValue(localVarName, currentLine);
                    distanceVarDefn.LocalVariable = localVarName.Value;

                    ReadValue(transform, currentLine);
                    distanceVarDefn.Transform = transform.Value;

                    parameters.DistanceVars.Add(distanceVarDefn);
                    GetNextLine();
                }
            }
            // Read species models
            ReadName(SpeciesModels);

            InputVar <string> birdName   = new InputVar <string>("Bird Name");
            InputVar <string> parameter  = new InputVar <string>("Parameter");
            InputVar <string> paramType  = new InputVar <string>("Parameter Type");
            InputVar <double> paramValue = new InputVar <double>("Parameter Value");


            Dictionary <string, int> speciesLineNumbers = new Dictionary <string, int>();

            speciesLineNumbers.Clear();

            const string speciesNameDelimiter = "->";  // delimiter that separates map name and forest type

            IModelDefinition modelDefn = null;

            while (!AtEndOfInput && !keywordList.Contains(CurrentName))
            {
                StringReader currentLine = new StringReader(CurrentLine);

                //  If the current line has the delimiter, then read the map
                //  name.
                if (CurrentLine.Contains(speciesNameDelimiter))
                {
                    ReadValue(birdName, currentLine);
                    CheckForRepeatedName(birdName.Value, "bird name", speciesLineNumbers);

                    modelDefn      = new ModelDefinition();
                    modelDefn.Name = birdName.Value;
                    parameters.Models.Add(modelDefn);

                    TextReader.SkipWhitespace(currentLine);
                    string word = TextReader.ReadWord(currentLine);
                    if (word != speciesNameDelimiter)
                    {
                        throw NewParseException("Expected \"{0}\" after the map name {1}.",
                                                speciesNameDelimiter, birdName.Value.String);
                    }

                    speciesLineNumbers.Clear();
                }
                else
                {
                    //  If there is no name delimiter and we don't have the
                    //  name for the first map yet, then it's an error.
                    if (modelDefn == null)
                    {
                        throw NewParseException("Expected a line with map name followed by \"{0}\"", speciesNameDelimiter);
                    }
                }

                // Read the parameter name:
                ReadValue(parameter, currentLine);
                modelDefn.Parameters.Add(parameter.Value);

                // Read the parameter types:
                ReadValue(paramType, currentLine);
                modelDefn.ParamTypes.Add(paramType.Value);

                // Read the parameter value:
                ReadValue(paramValue, currentLine);
                modelDefn.Values.Add(paramValue.Value);

                GetNextLine();
            }

            // Template for filenames of maps
            InputVar <string> localVarMapFileNames = new InputVar <string>(LocalVarMapFileNames);
            bool readLocalMaps = false;

            if (ReadOptionalVar(localVarMapFileNames))
            {
                parameters.LocalVarMapFileNames = localVarMapFileNames.Value;
                readLocalMaps = true;
            }

            InputVar <string> neighborMapFileNames = new InputVar <string>(NeighborVarMapFileNames);
            bool readNeighborMaps = false;

            if (ReadOptionalVar(neighborMapFileNames))
            {
                parameters.NeighborMapFileNames = neighborMapFileNames.Value;
                readNeighborMaps = true;
            }

            InputVar <string> climateMapFileNames = new InputVar <string>(ClimateVarMapFileNames);
            bool readClimateMaps = false;

            if (ReadOptionalVar(climateMapFileNames))
            {
                parameters.ClimateMapFileNames = climateMapFileNames.Value;
                readClimateMaps = true;
            }

            InputVar <string> distanceMapFileNames = new InputVar <string>(DistanceVarMapFileNames);
            bool readDistanceMaps = false;

            if (ReadOptionalVar(distanceMapFileNames))
            {
                parameters.DistanceMapFileNames = distanceMapFileNames.Value;
                readDistanceMaps = true;
            }

            InputVar <string> speciesMapFileNames = new InputVar <string>(SpeciesMapFileName);
            bool readSpeciesMaps = false;

            if (ReadOptionalVar(speciesMapFileNames))
            {
                parameters.SpeciesMapFileNames = speciesMapFileNames.Value;
                readSpeciesMaps = true;
            }
            InputVar <string> speciesLogFileNames = new InputVar <string>(SpeciesLogFileNames);
            bool readSpeciesLogs = false;

            if (ReadOptionalVar(speciesLogFileNames))
            {
                parameters.SpeciesLogFileNames = speciesLogFileNames.Value;
                readSpeciesLogs = true;
            }
            InputVar <string> logFile = new InputVar <string>(LogFile);
            bool readLogFile          = false;

            if (ReadOptionalVar(logFile))
            {
                parameters.LogFileName = logFile.Value;
                readLogFile            = true;
            }

            if (readLogFile)
            {
                CheckNoDataAfter(string.Format("the {0} parameter", LogFile));
            }
            else if (readSpeciesLogs)
            {
                CheckNoDataAfter(string.Format("the {0} parameter", SpeciesLogFileNames));
            }
            else if (readSpeciesMaps)
            {
                CheckNoDataAfter(string.Format("the {0} parameter", SpeciesMapFileName));
            }
            else if (readDistanceMaps)
            {
                CheckNoDataAfter(string.Format("the {0} parameter", DistanceVarMapFileNames));
            }
            else if (readClimateMaps)
            {
                CheckNoDataAfter(string.Format("the {0} parameter", ClimateVarMapFileNames));
            }
            else if (readNeighborMaps)
            {
                CheckNoDataAfter(string.Format("the {0} parameter", NeighborVarMapFileNames));
            }
            else if (readLocalMaps)
            {
                CheckNoDataAfter(string.Format("the {0} parameter", LocalVarMapFileNames));
            }
            else
            {
                CheckNoDataAfter(string.Format("the {0} parameter", SpeciesModels));
            }

            return(parameters); //.GetComplete();
        }
Beispiel #14
0
        //---------------------------------------------------------------------

        protected override IParameters Parse()
        {
            ReadLandisDataVar();

            EditableParameters parameters = new EditableParameters(SpeciesDataset.Count);

            InputVar <int> timestep = new InputVar <int>("Timestep");

            ReadVar(timestep);
            parameters.Timestep = timestep.Value;

            // Table of reclass coefficients

            InputVar <string> speciesName  = new InputVar <string>("Species");
            InputVar <double> reclassCoeff = new InputVar <double>("Reclass Coefficient");

            Dictionary <string, int> lineNumbers = new Dictionary <string, int>();

            const string ReclassMaps = "ReclassMaps";

            while (!AtEndOfInput && CurrentName != ReclassMaps)
            {
                StringReader currentLine = new StringReader(CurrentLine);

                ReadValue(speciesName, currentLine);
                ISpecies species = GetSpecies(speciesName.Value);
                CheckForRepeatedName(speciesName.Value, "species", lineNumbers);

                ReadValue(reclassCoeff, currentLine);
                parameters.ReclassCoefficients[species.Index] = reclassCoeff.Value;

                CheckNoDataAfter(string.Format("the {0} column", reclassCoeff.Name),
                                 currentLine);
                GetNextLine();
            }

            //  Read definitions of reclass maps

            ReadName(ReclassMaps);

            InputVar <string> mapName    = new InputVar <string>("Map Name");
            InputVar <string> forestType = new InputVar <string>("Forest Type");

            lineNumbers.Clear();
            Dictionary <string, int> forestTypeLineNumbers = new Dictionary <string, int>();

            const string MapFileNames  = "MapFileNames";
            const string nameDelimiter = "->";              // delimiter that separates map name and forest type

            IEditableMapDefinition mapDefn = null;

            while (!AtEndOfInput && CurrentName != MapFileNames)
            {
                StringReader currentLine = new StringReader(CurrentLine);

                //	If the current line has the delimiter, then read the map
                //	name.
                if (CurrentLine.Contains(nameDelimiter))
                {
                    ReadValue(mapName, currentLine);
                    CheckForRepeatedName(mapName.Value, "map name", lineNumbers);

                    mapDefn      = new EditableMapDefinition();
                    mapDefn.Name = mapName.Value;
                    parameters.ReclassMaps.Add(mapDefn);

                    TextReader.SkipWhitespace(currentLine);
                    string word = TextReader.ReadWord(currentLine);
                    if (word != nameDelimiter)
                    {
                        throw NewParseException("Expected \"{0}\" after the map name {1}.",
                                                nameDelimiter, mapName.Value.String);
                    }

                    forestTypeLineNumbers.Clear();
                }
                else
                {
                    //	If there is no name delimiter and we don't have the
                    //	name for the first map yet, then it's an error.
                    if (mapDefn == null)
                    {
                        throw NewParseException("Expected a line with map name followed by \"{0}\"", nameDelimiter);
                    }
                }

                ReadValue(forestType, currentLine);
                CheckForRepeatedName(forestType.Value, "forest type",
                                     forestTypeLineNumbers);

                IEditableForestType currentForestType = new EditableForestType(SpeciesDataset.Count);
                currentForestType.Name = forestType.Value;
                mapDefn.ForestTypes.Add(currentForestType);

                //	Read species for forest types

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

                TextReader.SkipWhitespace(currentLine);
                while (currentLine.Peek() != -1)
                {
                    ReadValue(speciesName, currentLine);
                    string name = speciesName.Value.Actual;
                    bool   negativeMultiplier = name.StartsWith("-");
                    if (negativeMultiplier)
                    {
                        name = name.Substring(1);
                        if (name.Length == 0)
                        {
                            throw new InputValueException(speciesName.Value.String,
                                                          "No species name after \"-\"");
                        }
                    }
                    ISpecies species = GetSpecies(new InputValue <string>(name, speciesName.Value.String));
                    if (speciesNames.Contains(species.Name))
                    {
                        throw NewParseException("The species {0} appears more than once.", species.Name);
                    }
                    speciesNames.Add(species.Name);

                    currentForestType[species.Index] = negativeMultiplier ? -1 : 1;

                    TextReader.SkipWhitespace(currentLine);
                }
                if (speciesNames.Count == 0)
                {
                    throw NewParseException("At least one species is required.");
                }

                GetNextLine();
            }

            // Template for filenames of reclass maps

            InputVar <string> mapFileNames = new InputVar <string>(MapFileNames);

            ReadVar(mapFileNames);
            parameters.MapFileNames = mapFileNames.Value;

            CheckNoDataAfter(string.Format("the {0} parameter", MapFileNames));

            return(parameters.GetComplete());
        }
Beispiel #15
0
        //.*?\(.*?\).*?\[.*?\]

        /// <summary>
        /// Parse a raw callstack into a pattern
        /// </summary>
        /// <param name="CurrentCrash">The crash with a raw callstack to parse.</param>
        private void ParseCallStack(Crash CurrentCrash)
        {
            // Everything is disabled by default
            bDisplayUnformattedCallStack = false;
            bDisplayModuleNames          = false;
            bDisplayFunctionNames        = false;
            bDisplayFileNames            = false;
            bDisplayFilePathNames        = false;

            bool   bSkipping      = false;
            string LineToSkipUpto = "";

            switch (CurrentCrash.CrashType)
            {
            case 2:
                bSkipping      = true;
                LineToSkipUpto = "FDebug::AssertFailed";
                break;

            case 3:
                bSkipping      = true;
                LineToSkipUpto = "FDebug::";
                break;
            }

            if (string.IsNullOrEmpty(CurrentCrash.RawCallStack))
            {
                return;
            }

            CallStackEntries.Clear();

            // Store off a pre split array of call stack lines
            string[] RawCallStackLines = CurrentCrash.RawCallStack.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);

            int Middle = RawCallStackLines.Length / 2;

            // Support older callstacks uploaded before UE4 upgrade
            if (!NewCallstackFormat.Match(RawCallStackLines[Middle]).Success)
            {
                foreach (string CurrentLine in RawCallStackLines)
                {
                    // Exit if we've hit the max number of lines we want
                    if (CallStackEntries.Count >= MaxLinesToParse)
                    {
                        break;
                    }

                    ParseUE3FormatCallstackLine(CurrentLine);
                }
                return;
            }

            foreach (string CurrentLine in RawCallStackLines)
            {
                // Exit if we've hit the max number of lines we want
                if (CallStackEntries.Count >= MaxLinesToParse)
                {
                    break;
                }

                if (bSkipping)
                {
                    if (CurrentLine.Contains(LineToSkipUpto))
                    {
                        bSkipping = false;
                    }
                }

                if (bSkipping)
                {
                    continue;
                }

                string ModuleName = "<Unknown>";
                string FuncName   = "<Unknown>";
                string FilePath   = "";
                int    LineNumber = 0;

                //
                // Generic sample line "UE4_Engine!UEngine::Exec() {+ 21105 bytes} [d:\depot\ue4\engine\source\runtime\engine\private\unrealengine.cpp:2777]"
                //
                // Mac
                // thread_start()  Address = 0x7fff87ae141d (filename not found) [in libsystem_pthread.dylib]
                //
                // Linux
                // Unknown!AFortPlayerController::execServerSaveLoadoutData(FFrame&, void*) + some bytes

                int ModuleSeparator    = CurrentLine.IndexOf('!');
                int PlusOffset         = CurrentLine.IndexOf(" + ");
                int OpenFuncSymbol     = CurrentLine.IndexOf('(');
                int CloseFuncSymbol    = CurrentLine.IndexOf(')');
                int OpenBracketOffset  = CurrentLine.IndexOf('[');
                int CloseBracketOffset = CurrentLine.LastIndexOf(']');

                int MacModuleStart = CurrentLine.IndexOf("[in ");
                int MacModuleEnd   = MacModuleStart > 0 ? CurrentLine.IndexOf("]", MacModuleStart) : 0;

                bool bLinux   = CurrentCrash.PlatformName.Contains("Linux");
                bool bMac     = CurrentCrash.PlatformName.Contains("Mac");
                bool bWindows = CurrentCrash.PlatformName.Contains("Windows");


                // Parse out the juicy info from the line of the callstack
                if (ModuleSeparator > 0)
                {
                    ModuleName = CurrentLine.Substring(0, ModuleSeparator).Trim();
                    if (OpenFuncSymbol > ModuleSeparator && CloseFuncSymbol > OpenFuncSymbol)
                    {
                        // Grab the function name if it exists
                        FuncName  = CurrentLine.Substring(ModuleSeparator + 1, OpenFuncSymbol - ModuleSeparator - 1).Trim();
                        FuncName += "()";

                        // Grab the source file
                        if (OpenBracketOffset > CloseFuncSymbol && CloseBracketOffset > OpenBracketOffset && (bWindows || bLinux))
                        {
                            string FileLinePath = CurrentLine.Substring(OpenBracketOffset + 1, CloseBracketOffset - OpenBracketOffset - 1).Trim();

                            FilePath = FileLinePath.TrimEnd("0123456789:".ToCharArray());

                            if (FileLinePath.Length > FilePath.Length + 1)
                            {
                                int SourceLine = 0;
                                if (int.TryParse(FileLinePath.Substring(FilePath.Length + 1), out SourceLine))
                                {
                                    LineNumber = SourceLine;
                                }
                            }
                        }
                    }
                }
                else if (bWindows)
                {
                    // Grab the module name if there is no function name
                    int WhiteSpacePos = CurrentLine.IndexOf(' ');
                    ModuleName = WhiteSpacePos > 0 ? CurrentLine.Substring(0, WhiteSpacePos) : CurrentLine;
                }

                if (bMac && MacModuleStart > 0 && MacModuleEnd > 0)
                {
                    int AddressOffset     = CurrentLine.IndexOf("Address =");
                    int OpenFuncSymbolMac = AddressOffset > 0 ? CurrentLine.Substring(0, AddressOffset).LastIndexOf('(') : 0;
                    if (OpenFuncSymbolMac > 0)
                    {
                        FuncName  = CurrentLine.Substring(0, OpenFuncSymbolMac).Trim();
                        FuncName += "()";
                    }

                    ModuleName = CurrentLine.Substring(MacModuleStart + 3, MacModuleEnd - MacModuleStart - 3).Trim();
                }

                // Remove callstack entries that match any of these functions.
                var FuncsToRemove = new HashSet <string>(new string[]
                {
                    "RaiseException",
                    "FDebug::",
                    "Error::Serialize",
                    "FOutputDevice::Logf",
                    "FMsg::Logf",
                    "ReportCrash",
                    "NewReportEnsure",
                    "EngineCrashHandler",
                    "FLinuxPlatformStackWalk::CaptureStackBackTrac",
                    "FGenericPlatformStackWalk::StackWalkAndDump",
                    "FLinuxCrashContext::CaptureStackTrace",
                    "CommonLinuxCrashHandler",
                    // Generic crash handler for all platforms
                });

                bool Contains = FuncsToRemove.Contains(FuncName, new CustomFuncComparer());
                if (!Contains)
                {
                    CallStackEntries.Add(new CallStackEntry(CurrentLine, ModuleName, FilePath, FuncName, LineNumber));
                }
            }
        }
Beispiel #16
0
        /// <summary>
        /// Parse a raw callstack into a pattern
        /// </summary>
        /// <param name="CurrentCrash">The crash with a raw callstack to parse.</param>
        private void ParseCallStack(Crash CurrentCrash)
        {
            // Everything is disabled by default
            bDisplayUnformattedCallStack = false;
            bDisplayModuleNames          = false;
            bDisplayFunctionNames        = false;
            bDisplayFileNames            = false;
            bDisplayFilePathNames        = false;

            bool   bSkipping      = false;
            string LineToSkipUpto = "";

            switch (CurrentCrash.CrashType)
            {
            case 2:
                bSkipping      = true;
                LineToSkipUpto = "FDebug::AssertFailed()";
                break;

            case 3:
                bSkipping      = true;
                LineToSkipUpto = "FDebug::EnsureFailed()";
                break;
            }

            if (string.IsNullOrEmpty(CurrentCrash.RawCallStack))
            {
                return;
            }

            CallStackEntries.Clear();

            // Store off a pre split array of call stack lines
            string[] RawCallStackLines = CurrentCrash.RawCallStack.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);

            // Support older callstacks uploaded before UE4 upgrade
            if (!NewCallstackFormat.Match(RawCallStackLines[0]).Success)
            {
                foreach (string CurrentLine in RawCallStackLines)
                {
                    // Exit if we've hit the max number of lines we want
                    if (CallStackEntries.Count >= MaxLinesToParse)
                    {
                        break;
                    }

                    ParseUE3FormatCallstackLine(CurrentLine);
                }
                return;
            }

            foreach (string CurrentLine in RawCallStackLines)
            {
                // Exit if we've hit the max number of lines we want
                if (CallStackEntries.Count >= MaxLinesToParse)
                {
                    break;
                }

                if (bSkipping)
                {
                    if (CurrentLine.Contains(LineToSkipUpto))
                    {
                        bSkipping = false;
                    }
                }

                if (bSkipping)
                {
                    continue;
                }

                string ModuleName = "<Unknown>";
                string FuncName   = "<Unknown>";
                string FilePath   = "";
                int    LineNumber = 0;

                // Sample line "UE4_Engine!UEngine::Exec() + 21105 bytes [d:\depot\ue4\engine\source\runtime\engine\private\unrealengine.cpp:2777]"

                int PlingOffset        = CurrentLine.IndexOf('!');
                int PlusOffset         = CurrentLine.IndexOf(" + ");
                int BytesOffset        = CurrentLine.IndexOf(" bytes");
                int OpenBracketOffset  = CurrentLine.IndexOf('[');
                int CloseBracketOffset = CurrentLine.LastIndexOf(']');

                // Parse out the juicy info from the line of the callstack
                if (PlingOffset > 0)
                {
                    ModuleName = CurrentLine.Substring(0, PlingOffset).Trim();
                    if (BytesOffset > PlingOffset)
                    {
                        // Grab the function name if it exists
                        FuncName = CurrentLine.Substring(PlingOffset + 1, BytesOffset - PlingOffset + " bytes".Length - 1).Trim();

                        // Grab the source file
                        if (OpenBracketOffset > BytesOffset && CloseBracketOffset > BytesOffset && CloseBracketOffset > OpenBracketOffset)
                        {
                            string FileLinePath = CurrentLine.Substring(OpenBracketOffset + 1, CloseBracketOffset - OpenBracketOffset - 1).Trim();

                            FilePath = FileLinePath.TrimEnd("0123456789:".ToCharArray());
                            int SourceLine = 0;
                            Debug.Assert(FilePath.Length < FileLinePath.Length, "WRONG SIZE");
                            if (int.TryParse(FileLinePath.Substring(FilePath.Length + 1), out SourceLine))
                            {
                                LineNumber = SourceLine;
                            }
                        }
                    }
                }
                else if (BytesOffset > 0)
                {
                    // Grab the module name if there is no function name
                    ModuleName = CurrentLine.Substring(0, PlusOffset).Trim();
                }

                CallStackEntries.Add(new CallStackEntry(CurrentLine, ModuleName, FilePath, FuncName, LineNumber));
            }
        }
Beispiel #17
0
        /// <summary>
        /// Runs a desktop file.
        /// </summary>
        /// <param name="path">Path to the desktop file.</param>
        /// <param name="verbose"></param>
        /// <returns></returns>
        public static ErrorCode Run(string path, bool verbose = false)
        {
            if (string.IsNullOrEmpty(path))
            {
                if (verbose)
                {
                    WriteLine($"Path is {(path == null ? "null" : "empty")}.");
                }

                return(path == null ?
                       ErrorCode.NullPath : ErrorCode.EmptyPath);
            }

            FileInfo file = new FileInfo(path);

            if (!file.Exists)
            {
                if (verbose)
                {
                    WriteLine($"Error: \"{path}\" does not exist.");
                }

                return(ErrorCode.FileNotFound);
            }
            else if (verbose)
            {
                WriteLine("File found.");
            }

            // Defaults
            DesktopFileType type = default(DesktopFileType);
            string          CurrentLine;
            ushort          CurrentLineIndex = 0;

            string[] LineValues;
            // User set
            string value    = string.Empty;
            bool   terminal = false;

            char[] SPLITTER = new char[] { DELIMITER };

            if (verbose)
            {
                WriteLine($"Reading {file.Name}...");
            }

            using (StreamReader sr = file.OpenText())
            {
                if (sr.ReadLine() != "[Desktop Entry]")
                {
                    return(ErrorCode.FileNoSignature);
                }

                while (!sr.EndOfStream)
                {
                    CurrentLine = sr.ReadLine();

                    // line[0] == '[' // Group header (Soon?)
                    if (CurrentLine[0] != '#') // Avoid comments.
                    {
                        if (!CurrentLine.Contains("="))
                        {
                            if (verbose)
                            {
                                WriteLine($"Error: Line {CurrentLineIndex + 1} missing the '=' delimiter.");
                            }

                            return(ErrorCode.FileMissingDelimiter);
                        }

                        LineValues = CurrentLine.Split(SPLITTER,
                                                       StringSplitOptions.RemoveEmptyEntries);

                        switch (LineValues[0])
                        {
                        case "Type":
                            switch (LineValues[1])
                            {
                            case "Application":
                                type = DesktopFileType.Application;
                                break;

                            case "Link":
                                type = DesktopFileType.Link;
                                break;

                            case "Directory":
                                type = DesktopFileType.Directory;
                                break;

                            default:
                                return(ErrorCode.FileMissingType);
                            }

                            if (verbose)
                            {
                                WriteLine($"TYPE SET AS {type}");
                            }
                            break;

                        case "Exec":
                        case "TryExec":
                            value = LineValues[1];

                            if (verbose)
                            {
                                WriteLine($"EXEC SET {value}");
                            }
                            break;

                        case "Url":
                        case "URL":
                            value = LineValues[1];

                            if (verbose)
                            {
                                WriteLine($"URL SET {value}");
                            }
                            break;

                        case "Path":
                            value = LineValues[1];

                            if (verbose)
                            {
                                WriteLine($"PATH SET {value}");
                            }
                            break;

                        case "Terminal":
                            terminal = LineValues[1].ToUpper() == "TRUE";

                            if (terminal && verbose)
                            {
                                WriteLine("TERMINAL SET TRUE");
                            }
                            break;
                        }
                    }

                    ++CurrentLineIndex;
                } // End while
            }     // End using

            if (verbose)
            {
                WriteLine($"Starting...");
            }

            if (string.IsNullOrWhiteSpace(value))
            {
                switch (type)
                {
                case DesktopFileType.Application: return(ErrorCode.FileMissingExecValue);

                case DesktopFileType.Link: return(ErrorCode.FileMissingUrlValue);

                case DesktopFileType.Directory: return(ErrorCode.FileMissingPathValue);
                }
            }

            if (value.Contains("%") || value.Contains("$"))
            {
                ReplaceVars(ref value, verbose);
            }

            if (value.Contains("~"))
            {
                ReplaceHome(ref value, verbose);
            }

            switch (type)
            {
                #region Application
            // Launch an application.
            case DesktopFileType.Application:
                try
                {
                    if (terminal)
                    {
                        Process.Start("cmd", $"/c {value}");
                    }
                    else
                    {
                        Process.Start(value);
                    }
                }
                catch (InvalidOperationException)
                {
                    return(ErrorCode.ExecInvalidOperation);
                }
                catch (System.ComponentModel.Win32Exception ex)
                {
                    if (verbose)
                    {
                        WriteLine($"Exception: {Ex(ex.InnerException ?? ex)}");
                    }

                    return(ErrorCode.ExecWin32Error);
                }
                catch (Exception ex)
                {
                    if (verbose)
                    {
                        WriteLine($"Exception: {Ex(ex)}");
                    }

                    return(ErrorCode.ExecError);
                }
                break;
                #endregion App

                #region Link
            // Launch the user's default application that handles URLs.
            case DesktopFileType.Link:
                try
                {
                    Process.Start(value);
                }
                catch (Exception ex)
                {
                    if (verbose)
                    {
                        WriteLine($"Exception: {Ex(ex)}");
                    }

                    return(ErrorCode.LinkError);
                }
                break;
                #endregion Link

                #region Directory
            // Open File Explorer with a specific path/directory with File Explorer.
            case DesktopFileType.Directory:
                if (Directory.Exists(value))
                {
                    try
                    {
                        Process.Start(
                            $"{GetFolderPath(SpecialFolder.Windows)}\\explorer",
                            value);     // .Replace("/", @"\")
                    }
                    catch (Exception ex)
                    {
                        if (verbose)
                        {
                            WriteLine($"{Ex(ex)}");
                        }

                        return(ErrorCode.DirectoryError);
                    }
                }
                else
                {
                    if (verbose)
                    {
                        WriteLine($"Error: Directory \"{value}\" could not be found.");
                    }

                    return(ErrorCode.DirectoryNotFound);
                }
                break;
                #endregion Directory
            } // End switch

            if (verbose)
            {
                WriteLine("Started successfully.");
            }

            return(0); // 0 is ErrorCode.Success
        }